diff --git a/.gitattributes b/.gitattributes deleted file mode 100644 index 51c63e295e0232f7095a8ee8e03713837e37f419..0000000000000000000000000000000000000000 --- a/.gitattributes +++ /dev/null @@ -1,15 +0,0 @@ -*.tgz filter=lfs diff=lfs merge=lfs -text -*.trp filter=lfs diff=lfs merge=lfs -text -*.apk filter=lfs diff=lfs merge=lfs -text -*.jar filter=lfs diff=lfs merge=lfs -text -*.mp4 filter=lfs diff=lfs merge=lfs -text -*.zip filter=lfs diff=lfs merge=lfs -text -*.asm filter=lfs diff=lfs merge=lfs -text -*.8svn filter=lfs diff=lfs merge=lfs -text -*.9svn filter=lfs diff=lfs merge=lfs -text -*.dylib filter=lfs diff=lfs merge=lfs -text -*.exe filter=lfs diff=lfs merge=lfs -text -*.a filter=lfs diff=lfs merge=lfs -text -*.so filter=lfs diff=lfs merge=lfs -text -*.bin filter=lfs diff=lfs merge=lfs -text -*.dll filter=lfs diff=lfs merge=lfs -text diff --git a/OAT.xml b/OAT.xml old mode 100755 new mode 100644 index 5da7ae2e39e288c75e4e1b2843dfb973ffaf3fae..7c2e5c790169629da9d0750a2fc58d312b9daf28 --- a/OAT.xml +++ b/OAT.xml @@ -1,50 +1,52 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/README.md b/README.md old mode 100755 new mode 100644 index 80a0b795d9613f01c09bd7e96332ca2697d62d15..effaf10bfd154ec1d1f3ec1fe77346c919850561 --- a/README.md +++ b/README.md @@ -32,19 +32,23 @@ The WLAN module provides basic WLAN functions, peer-to-peer \(P2P\) connection, │   └── kits # WLAN APIs ├── services # Services │   └── wifi_standard # Service implementation -└── tests # Test code - └── wifi_standard # Test code for the service implementation module +├── tests # Test code +│   └── wifi_standard # Test code for the service implementation module +└── utils # Utility functions + ├── inc # Header directory for utility functions + └── src # Implementation directory for utility functions ``` ## Usage ### Available APIs -The following table describes JavaScript APIs in **@ohos.wifi\_native\_js** available for basic WLAN functions. +The following table describes JavaScript APIs in **@ohos.wifi** available for basic WLAN functions. **Table 1** Major JavaScript APIs available for basic WLAN functions +

API

Description

@@ -132,35 +136,40 @@ The following table describes JavaScript APIs in **@ohos.wifi\_native\_js** av Before invoking WLAN JavaScript APIs, you need to import the **@ohos.wifi\_native\_js** class. -``` -import wifi_native_js from '@ohos.wifi_native_js'; // Import the @ohos.wifi_native_js class. +```js +import wf from '@ohos.wifi'; // Import the @ohos.wifi class. ``` - Obtaining the WLAN state -1. Call the **isWifiActive​\(\)** method to check whether WLAN is enabled. +1. Call the **isWifiActive​\(\)** method to check whether the WLAN is active. - ``` - var isWifiActive = wifi_native_js.isWifiActive(); // Value true indicates that WLAN is enabled, and false indicates the opposite. + ```js + var isWifiActive = wf.isWifiActive(); // Value true indicates that WLAN is enabled, and false indicates the opposite. ``` -- Starting a scan and obtaining the scan result +- Starting a scan and obtaining the scan results. 1. Call the **scan​\(\)** method to start a scan. -2. Call the **getScanInfoList​\(\)** method to obtain the scan result. +2. Call the **getScanInfoList​\(\)** method to obtain the scan results. - ``` + ```js // Start a scan. - var isScanSuccess = wifi_native_js.scan(); // true - + var isScanSuccess = wf.scan(); // true + // Wait for some time. - - // Obtain the scan result. - wifi_native_js.getScanInfos(result => { - var num = Object.keys(result).length; - console.info("wifi scan result mum: " + num); - for (var i = 0; i < num; ++i) { + + // Obtain the scan results. + wf.getScanInfos((err, result) => { + if (err) { + console.error("get scan info error"); + return; + } + + var len = Object.keys(result).length; + console.log("get scan info number: " + len); + for (var i = 0; i < len; ++i) { console.info("ssid: " + result[i].ssid); console.info("bssid: " + result[i].bssid); console.info("securityType: " + result[i].securityType); @@ -169,15 +178,15 @@ import wifi_native_js from '@ohos.wifi_native_js'; // Import the @ohos.wifi_nati console.info("frequency: " + result[i].frequency); console.info("timestamp: " + result[i].timestamp); } - }) + }); ``` Set up a WLAN connection. -1. Call **addDeviceConfig** to add a hotspot configuration, and set up a WLAN based on the hotspot configuration ID or by calling **connectToDevice** with the hotspot configuration passed. +1. To set up a WLAN, you can call **addDeviceConfig** to add a hotspot configuration first, and then use the returned hotspot configuration ID to coonect to a WLAN. Or you can set up a WLAN by calling **connectToDevice** through the hotspot configuration directly. - ``` + ```js // Configure WLAN information. var config = { "ssid":"test_wifi", @@ -186,20 +195,28 @@ Set up a WLAN connection. "isHiddenSsid":false, "securityType":3, } + Method 1: // Add a hotspot configuration. - wifi_native_js.addDeviceConfig(config, (result) => { + wf.addDeviceConfig(config, (err, result) => { + if (err) { + console.error("add device config error"); + return; + } console.info("config id: " + result); - // Set up a WLAN based on the hotspot configuration ID. - wifi_native_js.connectToNetwork(result); + // Set up a WLAN based on the returned hotspot configuration ID. + wf.connectToNetwork(result); }); + Method 2: - // Set up a WLAN by calling connectToDevice with the hotspot configuration passed. - wifi_native_js.connectToDevice(config); + // Set up a WLAN by calling connectToDevice with the hotspot configuration directly. + wf.connectToDevice(config); ``` ## Repositories Involved -communication\_wifi +[DSoftBus](https://gitee.com/openharmony/docs/blob/master/en/readme/dsoftbus.md) + +**communication\_wifi** diff --git a/README_zh.md b/README_zh.md old mode 100755 new mode 100644 index 4fb93993d593d50bea4df0b0a216024f8c4e9a6b..bf2c8e53d0ed14f371390e0b4b85f4e1ab91e019 --- a/README_zh.md +++ b/README_zh.md @@ -32,19 +32,23 @@ WLAN组件子系统为用户提供WLAN基础功能、P2P(peer-to-peer)功能 │   └── kits # WLAN组件接口的适配代码存放目录 ├── services # service适配目录 │   └── wifi_standard # service实现目录 -└── tests # 测试代码目录 - └── wifi_standard # service实现模块测试代码 +├── tests # 测试代码目录 +│   └── wifi_standard # service实现模块测试代码 +└── utils # 实用函数目录 + ├── inc # 实用函数头文件目录 + └── src # 实用函数实现目录 ``` ## 说明 ### 接口说明 -WLAN基础功能由@ohos.wifi\_native\_js类提供,其接口\(JS接口\)说明如下。 +WLAN基础功能由@ohos.wifi类提供,其接口\(JS接口\)说明如下。 **表 1** WLAN基础功能的主要接口\(JS接口\) + - @@ -130,18 +134,18 @@ WLAN基础功能由@ohos.wifi\_native\_js类提供,其接口\(JS接口\)说明 ### 使用说明 -在调用WLAN JS接口前需要导入接口类。 +在使用WLAN JS接口前需导入接口类@ohos.wifi。 -``` -import wifi_native_js from '@ohos.wifi_native_js'; // 导入js接口类 +```js +import wf from '@ohos.wifi'; // 导入js接口类 ``` (一)获取WLAN状态 1. 调用isWifiActive​\(\)接口查询WLAN是否打开。 - ``` - var isWifiActive = wifi_native_js.isWifiActive(); // 若WLAN打开,则返回true,否则返回false + ```js + var isWifiActive = wf.isWifiActive(); // 若WLAN打开,返回true,否则false ``` @@ -150,17 +154,21 @@ import wifi_native_js from '@ohos.wifi_native_js'; // 导入js接口类 1. 调用scan​\(\)接口发起扫描。 2. 调用getScanInfoList​\(\)接口获取扫描结果。 - ``` + ```js // 调用WLAN扫描接口 - var isScanSuccess = wifi_native_js.scan(); // true - - // 延迟一定时间 - + var isScanSuccess = wf.scan(); // true + // 延迟一段时间 // 获取扫描结果 - wifi_native_js.getScanInfos(result => { - var num = Object.keys(result).length; - console.info("wifi scan result mum: " + num); - for (var i = 0; i < num; ++i) { + + wf.getScanInfos((err, result) => { + if (err) { + console.error("get scan info error"); + return; + } + + var len = Object.keys(result).length; + console.log("get scan info number: " + len); + for (var i = 0; i < len; ++i) { console.info("ssid: " + result[i].ssid); console.info("bssid: " + result[i].bssid); console.info("securityType: " + result[i].securityType); @@ -169,7 +177,7 @@ import wifi_native_js from '@ohos.wifi_native_js'; // 导入js接口类 console.info("frequency: " + result[i].frequency); console.info("timestamp: " + result[i].timestamp); } - }) + }); ``` @@ -177,7 +185,7 @@ import wifi_native_js from '@ohos.wifi_native_js'; // 导入js接口类 1. 调用addDeviceConfig添加配置,然后通过返回的配置id连接WLAN或调用connectToDevice通过配置直接连接WLAN。 - ``` + ```js // WLAN配置信息 var config = { "ssid":"test_wifi", @@ -186,22 +194,26 @@ import wifi_native_js from '@ohos.wifi_native_js'; // 导入js接口类 "isHiddenSsid":false, "securityType":3, } - 方式一: + 方式一: // 添加配置 - wifi_native_js.addDeviceConfig(config, (result) => { + wf.addDeviceConfig(config, (err, result) => { + if (err) { + console.error("add device config error"); + return; + } console.info("config id: " + result); // 通过配置id连接WLAN - wifi_native_js.connectToNetwork(result); + wf.connectToNetwork(result); }); - 方式二: + 方式二: // 通过配置信息直接连接WLAN - wifi_native_js.connectToDevice(config); + wf.connectToDevice(config); ``` ## 相关仓 -分布式软总线子系统 +[分布式软总线子系统](https://gitee.com/openharmony/docs/blob/master/zh-cn/readme/%E5%88%86%E5%B8%83%E5%BC%8F%E8%BD%AF%E6%80%BB%E7%BA%BF%E5%AD%90%E7%B3%BB%E7%BB%9F.md) -communication\_wifi +**communication\_wifi** diff --git a/dhcp/BUILD.gn b/dhcp/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..127487d6eb042aea54dbc0eb985c54a294150fb9 --- /dev/null +++ b/dhcp/BUILD.gn @@ -0,0 +1,27 @@ +# Copyright (C) 2022 Huawei Device Co., Ltd. +# 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. + +if (defined(ohos_lite)) { + import("//build/lite/config/component/lite_component.gni") + import("//foundation/communication/wifi/dhcp/dhcp_lite.gni") + + lite_component("dhcp") { + deps = [ + "$DHCP_ROOT_DIR/services/dhcp_client:dhcp_client_service", + "$DHCP_ROOT_DIR/services/dhcp_server:dhcp_server", + "$DHCP_ROOT_DIR/services/mgr_service:dhcp_manager_service", + ] + + features = [] + } +} diff --git a/dhcp/bundle.json b/dhcp/bundle.json new file mode 100644 index 0000000000000000000000000000000000000000..308b063eb5ee0fe678ade2b4f1aedf3540edf263 --- /dev/null +++ b/dhcp/bundle.json @@ -0,0 +1,85 @@ +{ + "name": "@ohos/communication_wifi", + "version": "3.1.0", + "description": "The DHCP module provides DHCP client and DHCP service, used to obtain, assign and manage IP address.", + "homePage": "https://gitee.com/openharmony", + "license": "Apache License 2.0", + "repository": "https://gitee.com/openharmony/communication_wifi", + "domain": "os", + "language": "", + "publishAs": "code-segment", + "private": false, + "scripts": {}, + "tags": [ + "foundation" + ], + "keywords": [ + "communication", + "dhcp" + ], + "envs": [], + "dirs": [], + "author": { + "name": "", + "email": "", + "url": "" + }, + "contributors": [ + { + "name": "", + "email": "", + "url": "" + } + ], + "segment": { + "destPath": "foundation/communication/wifi/dhcp" + }, + "component": { + "name": "dhcp", + "subsystem": "communication", + "syscap": [ + ], + "features": [ + ], + "adapted_system_type": [ + "standard" + ], + "rom": "", + "ram": "", + "deps": { + "components": [ + "ipc", + "ces_standard", + "hiviewdfx_hilog_native", + "hisysevent_native" + ], + "third_party": [ + "wpa_supplicant", + "node", + "bounds_checking_function", + "googletest", + "openssl" + ] + }, + "build": { + "group_type": { + "base_group": [ + "//foundation/communication/wifi/dhcp/services/mgr_service:dhcp_manager_service", + "//foundation/communication/wifi/dhcp/services/dhcp_client:dhcp_client_service", + "//foundation/communication/wifi/dhcp/services/dhcp_server:dhcp_server" + ], + "fwk_group": [], + "service_group": [] + }, + "inner_kits": [ + ], + "test": [ + "//foundation/communication/wifi/dhcp/test/services/mgr_service:unittest", + "//foundation/communication/wifi/dhcp/test/services/dhcp_client:unittest", + "//foundation/communication/wifi/dhcp/test/services/dhcp_server/unittest:unittest" + ] + }, + "hisysevent_config": [ + ] + } +} diff --git a/services/wifi_standard/wifi_hal/etc/init/wifi_hal_service.rc b/dhcp/dhcp.gni similarity index 71% rename from services/wifi_standard/wifi_hal/etc/init/wifi_hal_service.rc rename to dhcp/dhcp.gni index 6727a09c0dd497263ba6c0eeb7bdbc0964733d40..49b97c33d4f48fd862b79539f1313bdb045eda86 100644 --- a/services/wifi_standard/wifi_hal/etc/init/wifi_hal_service.rc +++ b/dhcp/dhcp.gni @@ -1,4 +1,4 @@ -# Copyright (C) 2021 Huawei Device Co., Ltd. +# Copyright (c) 2022 Huawei Device Co., Ltd. # 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 @@ -11,10 +11,9 @@ # See the License for the specific language governing permissions and # limitations under the License. -on post-fs-data - start wifi_hal_service +SUBSYSTEM_DIR = "//foundation/communication" +WIFI_ROOT_DIR = "$SUBSYSTEM_DIR/wifi/wifi" +DHCP_ROOT_DIR = "$SUBSYSTEM_DIR/wifi/dhcp" -service wifi_hal_service /system/bin/wifi_hal_service - user root - group root shell - seclabel u:r:wifi_hal_service:s0 \ No newline at end of file +declare_args() { +} diff --git a/services/wifi_standard/etc/init/wifi_standard.rc b/dhcp/dhcp_lite.gni similarity index 64% rename from services/wifi_standard/etc/init/wifi_standard.rc rename to dhcp/dhcp_lite.gni index d03d2dbbd268c4a32e8b9d9b076af147ea410b23..49b97c33d4f48fd862b79539f1313bdb045eda86 100644 --- a/services/wifi_standard/etc/init/wifi_standard.rc +++ b/dhcp/dhcp_lite.gni @@ -1,4 +1,4 @@ -# Copyright (C) 2021 Huawei Device Co., Ltd. +# Copyright (c) 2022 Huawei Device Co., Ltd. # 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 @@ -11,12 +11,9 @@ # See the License for the specific language governing permissions and # limitations under the License. -on post-fs-data - mkdir /data/dhcp - start wifi_manager_service +SUBSYSTEM_DIR = "//foundation/communication" +WIFI_ROOT_DIR = "$SUBSYSTEM_DIR/wifi/wifi" +DHCP_ROOT_DIR = "$SUBSYSTEM_DIR/wifi/dhcp" -service wifi_manager_service /system/bin/sa_main /system/profile/wifi_manager_service.xml - class z_core - user root - group root shell - seclabel u:r:wifi_manager_service:s0 \ No newline at end of file +declare_args() { +} diff --git a/services/wifi_standard/wifi_framework/dhcp_manage/mgr_service/include/dhcp_define.h b/dhcp/interfaces/inner_api/include/dhcp_define.h similarity index 91% rename from services/wifi_standard/wifi_framework/dhcp_manage/mgr_service/include/dhcp_define.h rename to dhcp/interfaces/inner_api/include/dhcp_define.h index 44b8a0b65e23f0c26c9be6ceae94c7cd0bfe9fbc..a666a2b78bda89ff3c2d60588676fb8ec3af4b03 100644 --- a/services/wifi_standard/wifi_framework/dhcp_manage/mgr_service/include/dhcp_define.h +++ b/dhcp/interfaces/inner_api/include/dhcp_define.h @@ -1,5 +1,5 @@ /* - * Copyright (C) 2021 Huawei Device Co., Ltd. + * Copyright (C) 2021-2022 Huawei Device Co., Ltd. * 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 @@ -21,7 +21,6 @@ #include #include - namespace OHOS { namespace Wifi { const int ETH_MAC_ADDR_INDEX_0 = 0; @@ -65,17 +64,24 @@ const std::string INVALID_STRING("*"); const std::string EVENT_DATA_DELIMITER(","); const std::string EVENT_DATA_IPV4("ipv4"); const std::string EVENT_DATA_IPV6("ipv6"); -const std::string DHCP_WORK_DIR("/data/dhcp/"); +const std::string DHCP_WORK_DIR("/data/service/el1/public/dhcp/"); const std::string DHCP_CLIENT_PID_FILETYPE(".pid"); const std::string DHCP_RESULT_FILETYPE(".result"); +#ifdef OHOS_ARCH_LITE +const std::string DHCP_CLIENT_FILE("/bin/dhcp_client_service"); +const std::string DHCP_SERVER_FILE("/bin/dhcp_server"); +#else const std::string DHCP_CLIENT_FILE("/system/bin/dhcp_client_service"); const std::string DHCP_SERVER_FILE("/system/bin/dhcp_server"); -const std::string DHCP_SERVER_CONFIG_FILE("/data/dhcp/etc/dhcpd.conf"); -const std::string DHCP_SERVER_CONFIG_DIR("/data/dhcp/etc/"); -const std::string DHCP_SERVER_LEASES_FILE("/data/dhcp/dhcpd_lease.lease"); +#endif +const std::string DHCP_SERVER_CONFIG_FILE(DHCP_WORK_DIR + "etc/dhcpd.conf"); +const std::string DHCP_SERVER_CONFIG_DIR(DHCP_WORK_DIR + "etc/"); +const std::string DHCP_SERVER_LEASES_FILE(DHCP_WORK_DIR + "dhcpd_lease.lease"); const std::string DHCP_SERVER_CFG_IPV4("#ipv4"); const std::string DHCP_SERVER_CFG_IPV6("#ipv6"); const std::string COMMON_EVENT_DHCP_GET_IPV4 = "usual.event.wifi.dhcp.GET_IPV4"; +const std::string IP_V4_MASK("255.255.255.0"); +const std::string IP_V4_DEFAULT("192.168.1.2"); typedef enum EnumErrCode { /* success */ @@ -102,7 +108,7 @@ typedef enum EnumServiceStatus { SERVICE_STATUS_INVALID = 0, SERVICE_STATUS_START = 1, SERVICE_STATUS_STOP = 2 -} DhcpmServiceStatus; +} DhcpServiceStatus; struct DhcpResult { int iptype; /* 0-ipv4,1-ipv6 */ diff --git a/interfaces/innerkits/native_cpp/napi/wifi_napi_hotspot.h b/dhcp/interfaces/inner_api/include/dhcp_service_api.h old mode 100755 new mode 100644 similarity index 73% rename from interfaces/innerkits/native_cpp/napi/wifi_napi_hotspot.h rename to dhcp/interfaces/inner_api/include/dhcp_service_api.h index 74c47d78a17265fc56bc80912c9817375c2fcbbf..ddeeb207afd3f3e5f0952c25c15c1a142bcbfebb --- a/interfaces/innerkits/native_cpp/napi/wifi_napi_hotspot.h +++ b/dhcp/interfaces/inner_api/include/dhcp_service_api.h @@ -1,27 +1,29 @@ -/* - * Copyright (C) 2021 Huawei Device Co., Ltd. - * 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 WIFI_NAPI_HOTSPOT_H_ -#define WIFI_NAPI_HOTSPOT_H_ - -#include "wifi_napi_utils.h" - -namespace OHOS { -namespace Wifi { - -} // namespace Wifi -} // namespace OHOS - -#endif +/* + * Copyright (C) 2022 Huawei Device Co., Ltd. + * 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 OHOS_DHCP_SERVICE_API_H +#define OHOS_DHCP_SERVICE_API_H + +#include "i_dhcp_service.h" + +namespace OHOS { +namespace Wifi { +class DhcpServiceApi { +public: + static std::unique_ptr GetInstance(); +}; +} // namespace Wifi +} // namespace OHOS +#endif diff --git a/services/wifi_standard/wifi_framework/dhcp_manage/mgr_service/interfaces/i_dhcp_client_service.h b/dhcp/interfaces/inner_api/interfaces/i_dhcp_client_service.h similarity index 98% rename from services/wifi_standard/wifi_framework/dhcp_manage/mgr_service/interfaces/i_dhcp_client_service.h rename to dhcp/interfaces/inner_api/interfaces/i_dhcp_client_service.h index 10d17cf55e9669ef88176720405a8dd1eb3a8e73..4f471d916261f1f42f724c7e054aa42c2a074f5e 100644 --- a/services/wifi_standard/wifi_framework/dhcp_manage/mgr_service/interfaces/i_dhcp_client_service.h +++ b/dhcp/interfaces/inner_api/interfaces/i_dhcp_client_service.h @@ -69,7 +69,7 @@ public: * @Description : Obtain the dhcp result of specified interface asynchronously. * * @param ifname - interface name, eg:wlan0 [in] - * @param dhcp - dhcp result notify [in] + * @param pResultNotify - dhcp result notify [in] * @param timeouts - timeout interval [in] * @Return : success - DHCP_OPT_SUCCESS, failed - others. */ diff --git a/services/wifi_standard/wifi_framework/dhcp_manage/mgr_service/interfaces/i_dhcp_result_notify.h b/dhcp/interfaces/inner_api/interfaces/i_dhcp_result_notify.h similarity index 93% rename from services/wifi_standard/wifi_framework/dhcp_manage/mgr_service/interfaces/i_dhcp_result_notify.h rename to dhcp/interfaces/inner_api/interfaces/i_dhcp_result_notify.h index 2cc03bab5ae80fc5c15e81dddd120b28e4b284f4..c1cb933f256ab7af081042feda82d860450fc647 100644 --- a/services/wifi_standard/wifi_framework/dhcp_manage/mgr_service/interfaces/i_dhcp_result_notify.h +++ b/dhcp/interfaces/inner_api/interfaces/i_dhcp_result_notify.h @@ -30,7 +30,7 @@ public: virtual ~IDhcpResultNotify() {} /** - * @Description : Get success the dhcp result of specified interface. + * @Description : Get the success dhcp result of specified interface. * * @param status - success : DHCP_OPT_SUCCESS, failed : DHCP_OPT_FAILED, timeout : DHCP_OPT_TIMEOUT [in] * @param ifname - interface name, eg:wlan0 [in] @@ -39,7 +39,7 @@ public: virtual void OnSuccess(int status, const std::string& ifname, DhcpResult& result) = 0; /** - * @Description : Get failed the dhcp result of specified interface. + * @Description : Get the failed dhcp result of specified interface. * * @param status - success : DHCP_OPT_SUCCESS, failed : DHCP_OPT_FAILED, timeout : DHCP_OPT_TIMEOUT [in] * @param ifname - interface name, eg:wlan0 [in] diff --git a/services/wifi_standard/wifi_framework/dhcp_manage/mgr_service/interfaces/i_dhcp_server_service.h b/dhcp/interfaces/inner_api/interfaces/i_dhcp_server_service.h similarity index 98% rename from services/wifi_standard/wifi_framework/dhcp_manage/mgr_service/interfaces/i_dhcp_server_service.h rename to dhcp/interfaces/inner_api/interfaces/i_dhcp_server_service.h index d402bfe6f55f1dfb586d034ee679d7a1c202f7d2..d7ffde026fa908703e8cb7f4c21e0d58fd905a9d 100644 --- a/services/wifi_standard/wifi_framework/dhcp_manage/mgr_service/interfaces/i_dhcp_server_service.h +++ b/dhcp/interfaces/inner_api/interfaces/i_dhcp_server_service.h @@ -90,7 +90,7 @@ public: virtual int RemoveAllDhcpRange(const std::string& tagName) = 0; /** - * @Description : Set dhcp ip address pool of specified interface. + * @Description : Set dhcp ip address range of specified interface. * * @param ifname - interface name, eg:wlan0 [in] * @param range - ip address range [in] diff --git a/services/wifi_standard/wifi_framework/dhcp_manage/mgr_service/interfaces/i_dhcp_service.h b/dhcp/interfaces/inner_api/interfaces/i_dhcp_service.h similarity index 99% rename from services/wifi_standard/wifi_framework/dhcp_manage/mgr_service/interfaces/i_dhcp_service.h rename to dhcp/interfaces/inner_api/interfaces/i_dhcp_service.h index 036bcc8b18356006b6777b4ffbf4e78821000399..d3181bd1538b69b442f85143009122d4ad29fa18 100644 --- a/services/wifi_standard/wifi_framework/dhcp_manage/mgr_service/interfaces/i_dhcp_service.h +++ b/dhcp/interfaces/inner_api/interfaces/i_dhcp_service.h @@ -62,7 +62,7 @@ public: * @Description : Obtain the dhcp result of specified interface asynchronously. * * @param ifname - interface name, eg:wlan0 [in] - * @param dhcp - dhcp result notify [in] + * @param pResultNotify - dhcp result notify [in] * @param timeouts - timeout interval [in] * @Return : success - DHCP_OPT_SUCCESS, failed - others. */ diff --git a/dhcp/services/dhcp_client/BUILD.gn b/dhcp/services/dhcp_client/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..78d9711309b1be614f687b46d30acfafc2882bc3 --- /dev/null +++ b/dhcp/services/dhcp_client/BUILD.gn @@ -0,0 +1,87 @@ +# Copyright (C) 2021-2022 Huawei Device Co., Ltd. +# 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. + +if (defined(ohos_lite)) { + import("//build/lite/config/component/lite_component.gni") + import("//foundation/communication/wifi/dhcp/dhcp_lite.gni") +} else { + import("//build/ohos.gni") + import("//foundation/communication/wifi/dhcp/dhcp.gni") +} + +################################################################################ + +local_base_sources = [ + "$DHCP_ROOT_DIR/services/dhcp_client/src/dhcp_api.cpp", + "$DHCP_ROOT_DIR/services/dhcp_client/src/dhcp_client.c", + "$DHCP_ROOT_DIR/services/dhcp_client/src/dhcp_function.c", + "$DHCP_ROOT_DIR/services/dhcp_client/src/dhcp_ipv4.c", + "$DHCP_ROOT_DIR/services/dhcp_client/src/dhcp_main.c", + "$DHCP_ROOT_DIR/services/dhcp_client/src/dhcp_options.c", + "$DHCP_ROOT_DIR/services/dhcp_client/src/dhcp_socket.c", +] + +local_base_include_dirs = [ + "$DHCP_ROOT_DIR/services/dhcp_client/include", + "$WIFI_ROOT_DIR/services/wifi_standard/wifi_framework/wifi_toolkit/log", +] + +if (defined(ohos_lite)) { + executable("dhcp_client_service") { + sources = local_base_sources + + include_dirs = local_base_include_dirs + include_dirs += [ + "//base/hiviewdfx/hilog_lite/interfaces/native/innerkits", + "//third_party/bounds_checking_function/include", + ] + + deps = [ + "//base/hiviewdfx/hilog_lite/frameworks/featured:hilog_shared", + "//third_party/bounds_checking_function:libsec_shared", + ] + defines = [ + "_GNU_SOURCE", + "OHOS_ARCH_LITE", + ] + } +} else { + ohos_executable("dhcp_client_service") { + install_enable = true + sources = local_base_sources + + include_dirs = local_base_include_dirs + include_dirs += [ + "//commonlibrary/c_utils/base/include", + "//foundation/communication/ipc/interfaces/innerkits/ipc_core/include", + "//third_party/openssl/include", + ] + + deps = [ "//third_party/openssl:libcrypto_static" ] + + cflags_cc = [ "-fno-rtti" ] + + external_deps = [ + "ability_base:want", + "bundle_framework:appexecfwk_base", + "c_utils:utils", + "common_event_service:cesfwk_innerkits", + "eventhandler:libeventhandler", + "hiviewdfx_hilog_native:libhilog", + ] + defines = [] + + part_name = "dhcp" + subsystem_name = "communication" + } +} diff --git a/services/wifi_standard/wifi_framework/dhcp_manage/dhcp_client/include/dhcp_api.h b/dhcp/services/dhcp_client/include/dhcp_api.h similarity index 100% rename from services/wifi_standard/wifi_framework/dhcp_manage/dhcp_client/include/dhcp_api.h rename to dhcp/services/dhcp_client/include/dhcp_api.h diff --git a/services/wifi_standard/wifi_framework/dhcp_manage/dhcp_client/include/dhcp_client.h b/dhcp/services/dhcp_client/include/dhcp_client.h similarity index 97% rename from services/wifi_standard/wifi_framework/dhcp_manage/dhcp_client/include/dhcp_client.h rename to dhcp/services/dhcp_client/include/dhcp_client.h index 2679ba40000f4fb0cc3332b18903ea2c8dd38b07..9d704821194852fae86ea7ba1390f1be80853ea0 100644 --- a/services/wifi_standard/wifi_framework/dhcp_manage/dhcp_client/include/dhcp_client.h +++ b/dhcp/services/dhcp_client/include/dhcp_client.h @@ -23,7 +23,7 @@ extern "C" { #endif -#define WORKDIR "/data/dhcp/" +#define WORKDIR "/data/service/el1/public/dhcp/" #define DHCPC_NAME "dhcp_client_service" #define DHCPC_CONF "dhcp_client_service.conf" #define DHCPC_PID "dhcp_client_service.pid" diff --git a/services/wifi_standard/wifi_framework/dhcp_manage/dhcp_client/include/dhcp_define.h b/dhcp/services/dhcp_client/include/dhcp_define.h similarity index 99% rename from services/wifi_standard/wifi_framework/dhcp_manage/dhcp_client/include/dhcp_define.h rename to dhcp/services/dhcp_client/include/dhcp_define.h index 2aa154b3830d8068c221fae67a9e4c6d51193815..6c8c5c0d1895c6c150468885c52a61e7f5e81612 100644 --- a/services/wifi_standard/wifi_framework/dhcp_manage/dhcp_client/include/dhcp_define.h +++ b/dhcp/services/dhcp_client/include/dhcp_define.h @@ -1,5 +1,5 @@ /* - * Copyright (C) 2021 Huawei Device Co., Ltd. + * Copyright (C) 2021-2022 Huawei Device Co., Ltd. * 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 @@ -15,7 +15,7 @@ #ifndef OHOS_DHCP_DEFINE_H #define OHOS_DHCP_DEFINE_H - +#include #include #include #include diff --git a/services/wifi_standard/wifi_framework/dhcp_manage/dhcp_client/include/dhcp_function.h b/dhcp/services/dhcp_client/include/dhcp_function.h similarity index 94% rename from services/wifi_standard/wifi_framework/dhcp_manage/dhcp_client/include/dhcp_function.h rename to dhcp/services/dhcp_client/include/dhcp_function.h index 76bc90f61bd6187814ed79db70335118af862e88..cc3da5a6d7dfc402fbc077268e489e585214a59c 100644 --- a/services/wifi_standard/wifi_framework/dhcp_manage/dhcp_client/include/dhcp_function.h +++ b/dhcp/services/dhcp_client/include/dhcp_function.h @@ -30,7 +30,7 @@ bool Ip6StrConToChar(const char *strIp, uint8_t chIp[], size_t chlen); const char *MacChConToMacStr(const unsigned char *pChMac, size_t chLen, char *pStrMac, size_t strLen); int GetLocalInterface(const char *ifname, int *ifindex, unsigned char *hwaddr, uint32_t *ifaddr4); int GetLocalIp(const char *ifname, uint32_t *ifaddr4); -int SetLocalInterface(const char *ifname, uint32_t ifaddr4); +int SetLocalInterface(const char *ifname, uint32_t ipAddr, uint32_t netMask); int InitPidfile(const char *pidDir, const char *pidFile, pid_t pid); pid_t GetPID(const char *pidFile); int CreateDirs(const char *dirs, int mode); diff --git a/services/wifi_standard/wifi_framework/dhcp_manage/dhcp_client/include/dhcp_ipv4.h b/dhcp/services/dhcp_client/include/dhcp_ipv4.h similarity index 100% rename from services/wifi_standard/wifi_framework/dhcp_manage/dhcp_client/include/dhcp_ipv4.h rename to dhcp/services/dhcp_client/include/dhcp_ipv4.h diff --git a/services/wifi_standard/wifi_framework/dhcp_manage/dhcp_client/include/dhcp_options.h b/dhcp/services/dhcp_client/include/dhcp_options.h similarity index 100% rename from services/wifi_standard/wifi_framework/dhcp_manage/dhcp_client/include/dhcp_options.h rename to dhcp/services/dhcp_client/include/dhcp_options.h diff --git a/services/wifi_standard/wifi_framework/dhcp_manage/dhcp_client/include/dhcp_socket.h b/dhcp/services/dhcp_client/include/dhcp_socket.h similarity index 100% rename from services/wifi_standard/wifi_framework/dhcp_manage/dhcp_client/include/dhcp_socket.h rename to dhcp/services/dhcp_client/include/dhcp_socket.h diff --git a/services/wifi_standard/wifi_framework/dhcp_manage/dhcp_client/src/dhcp_api.cpp b/dhcp/services/dhcp_client/src/dhcp_api.cpp similarity index 87% rename from services/wifi_standard/wifi_framework/dhcp_manage/dhcp_client/src/dhcp_api.cpp rename to dhcp/services/dhcp_client/src/dhcp_api.cpp index 76e3a978a3aad9e9104a931a98e34fb8e79b2a2b..5fd307380d11aa0ddef4e4dd7ffb7a0add5b29a9 100644 --- a/services/wifi_standard/wifi_framework/dhcp_manage/dhcp_client/src/dhcp_api.cpp +++ b/dhcp/services/dhcp_client/src/dhcp_api.cpp @@ -1,5 +1,5 @@ /* - * Copyright (C) 2021 Huawei Device Co., Ltd. + * Copyright (C) 2021-2022 Huawei Device Co., Ltd. * 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 @@ -14,6 +14,17 @@ */ #include "dhcp_api.h" +#ifdef OHOS_ARCH_LITE +static bool PublishDhcpEvent(const char *action, const int code, const char *data) +{ + return true; +} + +bool PublishDhcpIpv4ResultEvent(const int code, const char *data, const char *ifname) +{ + return true; +} +#else #include "securec.h" #include "common_event.h" #include "common_event_data.h" @@ -58,3 +69,4 @@ bool PublishDhcpIpv4ResultEvent(const int code, const char *data, const char *if } return PublishDhcpEvent(strAction, code, data); } +#endif diff --git a/services/wifi_standard/wifi_framework/dhcp_manage/dhcp_client/src/dhcp_client.c b/dhcp/services/dhcp_client/src/dhcp_client.c similarity index 98% rename from services/wifi_standard/wifi_framework/dhcp_manage/dhcp_client/src/dhcp_client.c rename to dhcp/services/dhcp_client/src/dhcp_client.c index 6b511b22d0f199d34dae0fcc4259e8cebe2b3d4f..df6843bb69a0394f2bc7353925be1aa655c311dd 100644 --- a/services/wifi_standard/wifi_framework/dhcp_manage/dhcp_client/src/dhcp_client.c +++ b/dhcp/services/dhcp_client/src/dhcp_client.c @@ -61,7 +61,7 @@ int StopProcess(const char *pidFile) } LOGI("StopProcess() sending signal SIGTERM to process:%{public}d.", pid); - if (-1 == kill(pid, SIGTERM)) { + if (kill(pid, SIGTERM) == -1) { if (ESRCH == errno) { LOGW("StopProcess() pidFile:%{public}s,pid:%{public}d is not exist.", pidFile, pid); unlink(pidFile); diff --git a/services/wifi_standard/wifi_framework/dhcp_manage/dhcp_client/src/dhcp_function.c b/dhcp/services/dhcp_client/src/dhcp_function.c similarity index 91% rename from services/wifi_standard/wifi_framework/dhcp_manage/dhcp_client/src/dhcp_function.c rename to dhcp/services/dhcp_client/src/dhcp_function.c index 9ac499dacc00f9174594ebe1387c41bac304c71c..bc370843e30581e284ba3590958ebdbad0bdba70 100644 --- a/services/wifi_standard/wifi_framework/dhcp_manage/dhcp_client/src/dhcp_function.c +++ b/dhcp/services/dhcp_client/src/dhcp_function.c @@ -37,7 +37,6 @@ #undef LOG_TAG #define LOG_TAG "WifiDhcpFunction" - bool Ip4StrConToInt(const char *strIp, uint32_t *uIp, bool bHost) { if ((strIp == NULL) || (strlen(strIp) == 0)) { @@ -89,6 +88,7 @@ char *Ip4IntConToStr(uint32_t uIp, bool bHost) if (strncpy_s(strIp, INET_ADDRSTRLEN, bufIp4, strlen(bufIp4)) != EOK) { LOGE("Ip4IntConToStr uIp:%{private}u failed, strIp strncpy_s failed!", uIp); free(strIp); + strIp = NULL; return NULL; } @@ -155,8 +155,8 @@ const char *MacChConToMacStr(const unsigned char *pChMac, size_t chLen, char *pS int GetLocalInterface(const char *ifname, int *ifindex, unsigned char *hwaddr, uint32_t *ifaddr4) { - if ((ifname == NULL) || (strlen(ifname) == 0)) { - LOGE("GetLocalInterface() failed, ifname == NULL or \"\"!"); + if ((ifname == NULL) || (strlen(ifname) == 0) || hwaddr == NULL) { + LOGE("GetLocalInterface() failed, ifname == NULL or hwaddr is NULL"); return DHCP_OPT_FAILED; } @@ -272,57 +272,61 @@ int GetLocalIp(const char *ifname, uint32_t *ifaddr4) return DHCP_OPT_SUCCESS; } -int SetLocalInterface(const char *ifname, uint32_t ifaddr4) +int SetIpOrMask(const char *ifname, int fd, uint32_t netAddr, unsigned long cmd) { - if ((ifname == NULL) || (strlen(ifname) == 0)) { - LOGE("SetLocalInterface() failed, ifname == NULL or \"\"!"); + struct ifreq ifr; + struct sockaddr_in sin; + if (memset_s(&ifr, sizeof(struct ifreq), 0, sizeof(struct ifreq)) != EOK) { + LOGE("SetIpOrMask() failed, memset_s ifr error!"); return DHCP_OPT_FAILED; } - char *cIp = Ip4IntConToStr(ifaddr4, true); - if (cIp == NULL) { - LOGE("SetLocalInterface() %{public}s failed, Ip4IntConToStr addr4:%{private}u failed!", ifname, ifaddr4); + if (strncpy_s(ifr.ifr_name, sizeof(ifr.ifr_name), ifname, strlen(ifname)) != EOK) { + LOGE("SetIpOrMask() %{public}s failed, , strncpy_s ifr.ifr_name error!", ifname); return DHCP_OPT_FAILED; } - LOGI("SetLocalInterface() %{public}s, ifaddr4:%{private}u -> %{private}s.", ifname, ifaddr4, cIp); - free(cIp); - - int fd; - struct ifreq ifr; - struct sockaddr_in sin; - if ((fd = socket(AF_INET, SOCK_DGRAM, 0)) < 0) { - LOGE("SetLocalInterface() ifname:%{public}s failed, socket error:%{public}d!", ifname, errno); + if (memset_s(&sin, sizeof(struct sockaddr_in), 0, sizeof(struct sockaddr_in)) != EOK) { + LOGE("SetIpOrMask() failed, memset_s sin error!"); + return DHCP_OPT_FAILED; + } + sin.sin_family = AF_INET; + sin.sin_addr.s_addr = netAddr; + if (memcpy_s(&ifr.ifr_addr, sizeof(ifr.ifr_addr), &sin, sizeof(struct sockaddr)) != EOK) { + LOGE("SetIpOrMask() failed, memcpy_s ifr.ifr_addr error!"); return DHCP_OPT_FAILED; } - if (memset_s(&ifr, sizeof(ifr), 0, sizeof(ifr)) != EOK) { - close(fd); + if (ioctl(fd, cmd, &ifr) < 0) { + LOGE("SetIpOrMask() %{public}s failed, %{public}ld!", ifname, cmd); return DHCP_OPT_FAILED; } - if (strncpy_s(ifr.ifr_name, sizeof(ifr.ifr_name), ifname, strlen(ifname)) != EOK) { - close(fd); + return DHCP_OPT_SUCCESS; +} + +int SetLocalInterface(const char *ifname, uint32_t ipAddr, uint32_t netMask) +{ + if ((ifname == NULL) || (strlen(ifname) == 0)) { + LOGE("SetLocalInterface() failed, ifname == NULL or \"\"!"); return DHCP_OPT_FAILED; } + LOGI("SetLocalInterface() %{public}s, ipAddr:%{private}u mask %{private}u.", ifname, ipAddr, netMask); - if (memset_s(&sin, sizeof(sin), 0, sizeof(sin)) != EOK) { - close(fd); + int fd = socket(AF_INET, SOCK_DGRAM, 0); + if (fd < 0) { + LOGE("SetLocalInterface() ifname:%{public}s failed, socket error:%{public}d!", ifname, errno); return DHCP_OPT_FAILED; } - sin.sin_family = AF_INET; - sin.sin_addr.s_addr = htonl(ifaddr4); - if (memcpy_s(&ifr.ifr_addr, sizeof(ifr.ifr_addr), &sin, sizeof(struct sockaddr)) != EOK) { + + if (SetIpOrMask(ifname, fd, ipAddr, SIOCSIFADDR) != DHCP_OPT_SUCCESS) { close(fd); return DHCP_OPT_FAILED; } - /* Similar to the system command: ifconfig ifname ifaddr4. */ - if (ioctl(fd, SIOCSIFADDR, &ifr) < 0) { - LOGE("SetLocalInterface() %{public}s failed, SIOCSIFADDR err:%{public}d!", ifname, errno); + if (SetIpOrMask(ifname, fd, netMask, SIOCSIFNETMASK) != DHCP_OPT_SUCCESS) { close(fd); return DHCP_OPT_FAILED; } - close(fd); return DHCP_OPT_SUCCESS; } diff --git a/services/wifi_standard/wifi_framework/dhcp_manage/dhcp_client/src/dhcp_ipv4.c b/dhcp/services/dhcp_client/src/dhcp_ipv4.c similarity index 97% rename from services/wifi_standard/wifi_framework/dhcp_manage/dhcp_client/src/dhcp_ipv4.c rename to dhcp/services/dhcp_client/src/dhcp_ipv4.c index 678cda3c28d5e4c34a783b29cfd301a10e563932..a2168ebefb52b125d02faf428720030e39b766a3 100644 --- a/services/wifi_standard/wifi_framework/dhcp_manage/dhcp_client/src/dhcp_ipv4.c +++ b/dhcp/services/dhcp_client/src/dhcp_ipv4.c @@ -1,5 +1,5 @@ /* - * Copyright (C) 2021 Huawei Device Co., Ltd. + * Copyright (C) 2021-2022 Huawei Device Co., Ltd. * 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 @@ -28,8 +28,8 @@ #include #include #include -#include -#include +#include +#include #include "securec.h" #include "dhcp_client.h" @@ -167,7 +167,7 @@ int ExecDhcpRenew(void) return DHCP_OPT_SUCCESS; } -/* Add dhcp option paramater request list. */ +/* Add dhcp option parameter request list. */ static void AddParamaterRequestList(struct DhcpPacket *packet) { int end = GetEndOptionIndex(packet->options); @@ -302,13 +302,14 @@ static struct DhcpPacket *ReadLease(void) close(fd); if (rBytes <= 0 || (size_t)rBytes < offsetof(struct DhcpPacket, options)) { free(dhcp); + dhcp = NULL; return NULL; } return dhcp; } -static ssize_t WriteLease(struct DhcpPacket *pkt) +static ssize_t WriteLease(const struct DhcpPacket *pkt) { if (pkt == NULL) { return -1; @@ -384,6 +385,7 @@ static int DhcpReboot(uint32_t transid, uint32_t reqip) if (pReqIp != NULL) { LOGI("DhcpReboot() broadcast req packet, reqip: host %{private}u->%{private}s.", ntohl(reqip), pReqIp); free(pReqIp); + pReqIp = NULL; } return SendToDhcpPacket(&packet, INADDR_ANY, INADDR_BROADCAST, g_cltCnf->ifaceIndex, (uint8_t *)MAC_BCAST_ADDR); } @@ -397,11 +399,14 @@ void SendReboot(struct DhcpPacket *p, time_t timestamp) g_requestedIp4 = p->yiaddr; free(p); + p = NULL; g_transID = GetTransId(); g_dhcp4State = DHCP_STATE_INITREBOOT; g_sentPacketNum = 0; - g_timeoutTimestamp = timestamp + g_renewalSec; + + uint32_t uTimeoutSec = TIMEOUT_WAIT_SEC << g_sentPacketNum; + g_timeoutTimestamp = timestamp + uTimeoutSec; DhcpReboot(g_transID, g_requestedIp4); } @@ -425,6 +430,7 @@ static void Reboot(time_t timestamp) if (timestamp == (time_t)-1 || timestamp < st.st_mtime || (time_t)leaseTime < timestamp - st.st_mtime) { LOGI("Reboot read lease file leaseTime expire"); free(pkt); + pkt = NULL; return; } else { interval = timestamp - st.st_mtime; @@ -437,6 +443,7 @@ static void Reboot(time_t timestamp) } else { LOGI("Reboot read lease file leaseTime option not found"); free(pkt); + pkt = NULL; return; } @@ -591,6 +598,7 @@ static void DhcpOfferPacketHandle(uint8_t type, const struct DhcpPacket *packet, ntohl(g_requestedIp4), pReqIp); free(pReqIp); + pReqIp = NULL; } char *pSerIp = Ip4IntConToStr(g_serverIp4, false); if (pSerIp != NULL) { @@ -598,9 +606,11 @@ static void DhcpOfferPacketHandle(uint8_t type, const struct DhcpPacket *packet, ntohl(g_serverIp4), pSerIp); free(pSerIp); + pSerIp = NULL; } /* Receive dhcp offer packet finished, next send dhcp request packet. */ + WriteLease(packet); g_dhcp4State = DHCP_STATE_REQUESTING; g_sentPacketNum = 0; g_timeoutTimestamp = timestamp; @@ -621,6 +631,7 @@ static void ParseOtherNetworkInfo(const struct DhcpPacket *packet, struct DhcpRe LOGI("ParseOtherNetworkInfo() recv DHCP_ACK 6, dns1: %{private}u->%{private}s.", u32Data, pDnsIp); if (strncpy_s(result->strOptDns1, INET_ADDRSTRLEN, pDnsIp, INET_ADDRSTRLEN - 1) != EOK) { free(pDnsIp); + pDnsIp = NULL; return; } free(pDnsIp); @@ -629,12 +640,14 @@ static void ParseOtherNetworkInfo(const struct DhcpPacket *packet, struct DhcpRe if ((u32Data2 > 0) && ((pDnsIp = Ip4IntConToStr(u32Data2, true)) != NULL)) { LOGI("ParseOtherNetworkInfo() recv DHCP_ACK 6, dns2: %{private}u->%{private}s.", u32Data2, pDnsIp); if (strncpy_s(result->strOptDns2, INET_ADDRSTRLEN, pDnsIp, INET_ADDRSTRLEN - 1) != EOK) { - free(pDnsIp); - return; + LOGE("ParseOtherNetworkInfo() strncpy_s Failed."); } free(pDnsIp); + pDnsIp = NULL; + return; } } + return; } static void ParseNetworkInfo(const struct DhcpPacket *packet, struct DhcpResult *result) @@ -648,10 +661,13 @@ static void ParseNetworkInfo(const struct DhcpPacket *packet, struct DhcpResult if (pReqIp != NULL) { LOGI("ParseNetworkInfo() recv DHCP_ACK yiaddr: %{private}u->%{private}s.", ntohl(g_requestedIp4), pReqIp); if (strncpy_s(result->strYiaddr, INET_ADDRSTRLEN, pReqIp, INET_ADDRSTRLEN - 1) != EOK) { + LOGI("ParseNetworkInfo() strncpy_s failed!"); free(pReqIp); + pReqIp = NULL; return; } free(pReqIp); + pReqIp = NULL; } uint32_t u32Data = 0; @@ -661,9 +677,11 @@ static void ParseNetworkInfo(const struct DhcpPacket *packet, struct DhcpResult LOGI("ParseNetworkInfo() recv DHCP_ACK 1, subnetmask: %{private}u->%{private}s.", u32Data, pSubIp); if (strncpy_s(result->strOptSubnet, INET_ADDRSTRLEN, pSubIp, INET_ADDRSTRLEN - 1) != EOK) { free(pSubIp); + pSubIp = NULL; return; } free(pSubIp); + pSubIp = NULL; } } @@ -675,6 +693,7 @@ static void ParseNetworkInfo(const struct DhcpPacket *packet, struct DhcpResult LOGI("ParseNetworkInfo() recv DHCP_ACK 3, router1: %{private}u->%{private}s.", u32Data, pRouterIp); if (strncpy_s(result->strOptRouter1, INET_ADDRSTRLEN, pRouterIp, INET_ADDRSTRLEN - 1) != EOK) { free(pRouterIp); + pRouterIp = NULL; return; } free(pRouterIp); @@ -684,9 +703,11 @@ static void ParseNetworkInfo(const struct DhcpPacket *packet, struct DhcpResult LOGI("ParseNetworkInfo() recv DHCP_ACK 3, router2: %{private}u->%{private}s.", u32Data2, pRouterIp); if (strncpy_s(result->strOptRouter2, INET_ADDRSTRLEN, pRouterIp, INET_ADDRSTRLEN - 1) != EOK) { free(pRouterIp); + pRouterIp = NULL; return; } free(pRouterIp); + pRouterIp = NULL; } } @@ -814,18 +835,21 @@ static int SyncDhcpResult(const struct DhcpPacket *packet, struct DhcpResult *re if (strncpy_s(result->strOptVendor, DHCP_FILE_MAX_BYTES, pVendor, DHCP_FILE_MAX_BYTES - 1) != EOK) { LOGE("SyncDhcpResult() error, strncpy_s pVendor failed!"); free(pVendor); + pVendor = NULL; return DHCP_OPT_FAILED; } free(pVendor); + pVendor = NULL; } /* Set the specified client process interface network info. */ - if (SetLocalInterface(g_cltCnf->ifaceName, ntohl(g_requestedIp4)) != DHCP_OPT_SUCCESS) { + if (SetLocalInterface(g_cltCnf->ifaceName, inet_addr(result->strYiaddr), inet_addr(result->strOptSubnet)) + != DHCP_OPT_SUCCESS) { LOGE("SyncDhcpResult() error, SetLocalInterface yiaddr:%{private}s failed!", result->strYiaddr); return DHCP_OPT_FAILED; } - /* Wirte to the file. */ + /* Write to the file. */ if (WriteDhcpResult(result) != DHCP_OPT_SUCCESS) { LOGE("SyncDhcpResult() error, WriteDhcpResult result failed!"); return DHCP_OPT_FAILED; @@ -877,9 +901,11 @@ static void ParseDhcpAckPacket(const struct DhcpPacket *packet, time_t timestamp LOGI("ParseDhcpAckPacket() recv DHCP_ACK 54, serid: %{private}u->%{private}s.", u32Data, pSerIp); if (strncpy_s(dhcpResult.strOptServerId, INET_ADDRSTRLEN, pSerIp, INET_ADDRSTRLEN - 1) != EOK) { free(pSerIp); + pSerIp = NULL; return; } free(pSerIp); + pSerIp = NULL; } } @@ -1241,11 +1267,13 @@ int DhcpRequest(uint32_t transid, uint32_t reqip, uint32_t servip) if (pReqIp != NULL) { LOGI("DhcpRequest() broadcast req packet, reqip: host %{private}u->%{private}s.", ntohl(reqip), pReqIp); free(pReqIp); + pReqIp = NULL; } char *pSerIp = Ip4IntConToStr(servip, false); if (pSerIp != NULL) { LOGI("DhcpRequest() broadcast req packet, servIp: host %{private}u->%{private}s.", ntohl(servip), pSerIp); free(pSerIp); + pSerIp = NULL; } return SendToDhcpPacket(&packet, INADDR_ANY, INADDR_BROADCAST, g_cltCnf->ifaceIndex, (uint8_t *)MAC_BCAST_ADDR); } @@ -1378,4 +1406,4 @@ int StartIpv4(void) } } return g_cltCnf->timeoutExit ? StopProcess(g_cltCnf->pidFile) : DHCP_OPT_SUCCESS; -} \ No newline at end of file +} diff --git a/services/wifi_standard/wifi_framework/dhcp_manage/dhcp_client/src/dhcp_main.c b/dhcp/services/dhcp_client/src/dhcp_main.c similarity index 98% rename from services/wifi_standard/wifi_framework/dhcp_manage/dhcp_client/src/dhcp_main.c rename to dhcp/services/dhcp_client/src/dhcp_main.c index 0a9d95f3d17b28aa4439369574990893a8bc3653..31a3deaf5a5af8055e34ea3cfaeae49fc39187d2 100644 --- a/services/wifi_standard/wifi_framework/dhcp_manage/dhcp_client/src/dhcp_main.c +++ b/dhcp/services/dhcp_client/src/dhcp_main.c @@ -208,6 +208,10 @@ static int GetClientOption(int argc, char *argv[]) static int InitSpecifiedClientCfg(int argc, char *argv[]) { + if (argc < NUMBER_TWO + 1) { + LOGE("parameter error!"); + return DHCP_OPT_FAILED; + } g_cltCfg = GetDhcpClientCfg(); if ((strncpy_s(g_cltCfg->workDir, sizeof(g_cltCfg->workDir), WORKDIR, DIR_MAX_LEN - 1) != EOK) || (strncpy_s(g_cltCfg->ifaceName, sizeof(g_cltCfg->ifaceName), argv[NUMBER_TWO], INFNAME_SIZE - 1) != EOK)) { @@ -328,6 +332,7 @@ static int GetClientNetworkInfo(void) LOGI("GetClientNetworkInfo() GetLocalIp ifaceName:%{public}s -> ifaceIpv4:%{private}u - %{private}s.", g_cltCfg->ifaceName, g_cltCfg->ifaceIpv4, cIp); free(cIp); + cIp = NULL; /* Generate clientid for the specified client process interface. */ if (g_cltCfg->pOptClientId == NULL) { @@ -366,6 +371,10 @@ int main(int argc, char *argv[]) } /* Exec the specified client process ACTION. */ + if (argc < NUMBER_ONE + 1) { + LOGE("parameter number is error!"); + return EXIT_FAILURE; + } const char *cmdParam = argv[NUMBER_ONE]; int nExec = ExecClientProAction(cmdParam); if (nExec != 0) { diff --git a/services/wifi_standard/wifi_framework/dhcp_manage/dhcp_client/src/dhcp_options.c b/dhcp/services/dhcp_client/src/dhcp_options.c similarity index 99% rename from services/wifi_standard/wifi_framework/dhcp_manage/dhcp_client/src/dhcp_options.c rename to dhcp/services/dhcp_client/src/dhcp_options.c index c1a49e7b14aa06197d0ccf567028591eaefc3a38..676a87e90ca8cc0d73fcf1fe8156c45f48bf1d6c 100644 --- a/services/wifi_standard/wifi_framework/dhcp_manage/dhcp_client/src/dhcp_options.c +++ b/dhcp/services/dhcp_client/src/dhcp_options.c @@ -299,6 +299,7 @@ char *GetDhcpOptionString(const struct DhcpPacket *packet, int code) if (s) { if (memcpy_s(s, len + 1, p, len) != EOK) { free(s); + s = NULL; return NULL; } s[len] = '\0'; @@ -368,7 +369,7 @@ int AddOptValueToOpts(uint8_t *pOpts, uint8_t code, uint32_t value) *pUint32 = value; break; default: - LOGE("AddOptValueToOpts() uLen:%{public}u error, break!", uLen); + LOGE("AddOptValueToOpts() uLen:%{public}d error, break!", uLen); break; } diff --git a/services/wifi_standard/wifi_framework/dhcp_manage/dhcp_client/src/dhcp_socket.c b/dhcp/services/dhcp_client/src/dhcp_socket.c similarity index 98% rename from services/wifi_standard/wifi_framework/dhcp_manage/dhcp_client/src/dhcp_socket.c rename to dhcp/services/dhcp_client/src/dhcp_socket.c index 6c165cc142e54bb5676a9ad53bf6ad9061d6f816..bfb128c7cc0cbb9c6168dd4dd730a5fd21a2cc2c 100644 --- a/services/wifi_standard/wifi_framework/dhcp_manage/dhcp_client/src/dhcp_socket.c +++ b/dhcp/services/dhcp_client/src/dhcp_socket.c @@ -70,6 +70,10 @@ int CreateRawSocket(int *rawFd) /* Kernel socket can receive data frames or data packets from the local network interface, ip and port. */ int CreateKernelSocket(int *sockFd) { + if (sockFd == NULL) { + LOGE("CreateKernelSocket() failed, sockFd is NULL!"); + return SOCKET_OPT_FAILED; + } int nFd = socket(PF_INET, SOCK_DGRAM, IPPROTO_UDP); if (nFd == -1) { LOGE("CreateKernelSocket() failed, socket error:%{public}d.", errno); @@ -136,7 +140,8 @@ int BindKernelSocket(const int sockFd, const char *ifaceName, const uint32_t soc /* Set the broadcast feature of the data sent by the socket. */ if (bCast) { - if (setsockopt(sockFd, SOL_SOCKET, SO_BROADCAST, (const char *)&bCast, sizeof(bool)) == -1) { + int broadcast = 1; + if (setsockopt(sockFd, SOL_SOCKET, SO_BROADCAST, (const char *)&broadcast, sizeof(int)) == -1) { LOGE("BindKernelSocket() sockFd:%{public}d SO_BROADCAST error:%{public}d.", sockFd, errno); close(sockFd); return SOCKET_OPT_FAILED; diff --git a/dhcp/services/dhcp_server/BUILD.gn b/dhcp/services/dhcp_server/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..85ecd3ba120bddadbad790834ba25c64022a9ac6 --- /dev/null +++ b/dhcp/services/dhcp_server/BUILD.gn @@ -0,0 +1,87 @@ +# Copyright (C) 2021-2022 Huawei Device Co., Ltd. +# 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. + +if (defined(ohos_lite)) { + import("//build/lite/config/component/lite_component.gni") + import("//foundation/communication/wifi/dhcp/dhcp_lite.gni") +} else { + import("//build/ohos.gni") + import("//foundation/communication/wifi/dhcp/dhcp.gni") +} + +local_base_sources = [ + "src/address_utils.c", + "src/common_util.c", + "src/dhcp_address_pool.c", + "src/dhcp_argument.c", + "src/dhcp_binding.c", + "src/dhcp_config.c", + "src/dhcp_dhcpd.c", + "src/dhcp_option.c", + "src/dhcp_server.c", + "src/hash_table.c", +] + +local_base_include_dirs = [ + "include", + "include/common", + "$DHCP_ROOT_DIR/services/dhcp_client/include", +] + +dhcp_hilog_enable = true + +if (defined(ohos_lite)) { + executable("dhcp_server") { + sources = local_base_sources + + include_dirs = local_base_include_dirs + include_dirs += [ + "//base/hiviewdfx/hilog_lite/interfaces/native/innerkits", + "//third_party/bounds_checking_function/include", + ] + + deps = [ "//third_party/bounds_checking_function:libsec_shared" ] + + cflags_cc = [ "-fno-rtti" ] + + defines = [ + "_GNU_SOURCE", + "OHOS_ARCH_LITE", + ] + if (dhcp_hilog_enable) { + deps += [ "//base/hiviewdfx/hilog_lite/frameworks/featured:hilog_shared" ] + defines += [ "DHCP_HILOG_ENABLE" ] + } + } +} else { + ohos_executable("dhcp_server") { + install_enable = true + sources = local_base_sources + + include_dirs = local_base_include_dirs + include_dirs += [ "//commonlibrary/c_utils/base/include" ] + + external_deps = [ "c_utils:utils" ] + + cflags_cc = [ "-fno-rtti" ] + + defines = [] + if (dhcp_hilog_enable) { + external_deps += [ "hiviewdfx_hilog_native:libhilog" ] + defines += [ "DHCP_HILOG_ENABLE" ] + } + + part_name = "dhcp" + subsystem_name = "communication" + } +} diff --git a/services/wifi_standard/wifi_framework/dhcp_manage/dhcp_server/etc/dhcpd.conf.sample b/dhcp/services/dhcp_server/etc/dhcpd.conf.sample similarity index 100% rename from services/wifi_standard/wifi_framework/dhcp_manage/dhcp_server/etc/dhcpd.conf.sample rename to dhcp/services/dhcp_server/etc/dhcpd.conf.sample diff --git a/services/wifi_standard/wifi_framework/dhcp_manage/dhcp_server/etc/dhcpd_mini.conf b/dhcp/services/dhcp_server/etc/dhcpd_mini.conf similarity index 100% rename from services/wifi_standard/wifi_framework/dhcp_manage/dhcp_server/etc/dhcpd_mini.conf rename to dhcp/services/dhcp_server/etc/dhcpd_mini.conf diff --git a/services/wifi_standard/wifi_framework/dhcp_manage/dhcp_server/include/address_utils.h b/dhcp/services/dhcp_server/include/address_utils.h similarity index 96% rename from services/wifi_standard/wifi_framework/dhcp_manage/dhcp_server/include/address_utils.h rename to dhcp/services/dhcp_server/include/address_utils.h index e7a603785a3f3eb42e356cdda69925801f505701..a61fd5c5312d1daa91c938980ef4d442048d5ea5 100644 --- a/services/wifi_standard/wifi_framework/dhcp_manage/dhcp_server/include/address_utils.h +++ b/dhcp/services/dhcp_server/include/address_utils.h @@ -37,8 +37,8 @@ uint32_t BroadCastAddress(uint32_t ip, uint32_t netmask); uint32_t ParseIpAddr(const char *strIp); uint32_t ParseIpHtonl(const char *strIp); int NetworkBits(uint32_t netmask); -int HostBits(uint32_t netmask); -int HostTotal(uint32_t netmask); +uint32_t HostBits(uint32_t netmask); +uint32_t HostTotal(uint32_t netmask); uint32_t ParseIp(const uint8_t *ipAddr); const char *ParseStrIp(uint32_t ipAddr); int IsEmptyHWAddr(uint8_t macAddr[DHCP_HWADDR_LENGTH]); @@ -53,4 +53,4 @@ int AddrEquels(uint8_t firstAddr[DHCP_HWADDR_LENGTH], uint8_t secondAddr[DHCP_HW #ifdef __cplusplus } #endif -#endif \ No newline at end of file +#endif diff --git a/services/wifi_standard/wifi_framework/dhcp_manage/dhcp_server/include/common_util.h b/dhcp/services/dhcp_server/include/common_util.h similarity index 100% rename from services/wifi_standard/wifi_framework/dhcp_manage/dhcp_server/include/common_util.h rename to dhcp/services/dhcp_server/include/common_util.h diff --git a/services/wifi_standard/wifi_framework/dhcp_manage/dhcp_server/include/dhcp_address_pool.h b/dhcp/services/dhcp_server/include/dhcp_address_pool.h similarity index 97% rename from services/wifi_standard/wifi_framework/dhcp_manage/dhcp_server/include/dhcp_address_pool.h rename to dhcp/services/dhcp_server/include/dhcp_address_pool.h index 4ec6d6e88b7333d6860c7686ec688287b5cc6fd4..f13514e8831486f598fa38c5f968734784d490cd 100644 --- a/services/wifi_standard/wifi_framework/dhcp_manage/dhcp_server/include/dhcp_address_pool.h +++ b/dhcp/services/dhcp_server/include/dhcp_address_pool.h @@ -1,5 +1,5 @@ /* - * Copyright (C) 2021 Huawei Device Co., Ltd. + * Copyright (C) 2021-2022 Huawei Device Co., Ltd. * 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 @@ -17,14 +17,15 @@ #define OHOS_DHCP_ADDRESS_POOL_H #include +#include "dhcp_binding.h" #include "dhcp_define.h" #include "dhcp_option.h" #include "hash_table.h" -#include "dhcp_binding.h" #ifdef __cplusplus extern "C" { #endif + typedef struct DhcpAddressPool DhcpAddressPool; typedef AddressBinding *(*QueryBind)(uint8_t macAddr[DHCP_HWADDR_LENGTH], PDhcpOptionList cliOptins); typedef AddressBinding *(*AddBind)(uint8_t macAddr[DHCP_HWADDR_LENGTH], PDhcpOptionList cliOptins); @@ -77,4 +78,4 @@ int GetDistributeMode(void); #ifdef __cplusplus } #endif -#endif \ No newline at end of file +#endif diff --git a/services/wifi_standard/wifi_framework/dhcp_manage/dhcp_server/include/dhcp_argument.h b/dhcp/services/dhcp_server/include/dhcp_argument.h similarity index 92% rename from services/wifi_standard/wifi_framework/dhcp_manage/dhcp_server/include/dhcp_argument.h rename to dhcp/services/dhcp_server/include/dhcp_argument.h index 5741ea5afccc83de777db76099b41d0e76e286a5..20c215d9dee2dba7dd883eda1e851c63ac977faa 100644 --- a/services/wifi_standard/wifi_framework/dhcp_manage/dhcp_server/include/dhcp_argument.h +++ b/dhcp/services/dhcp_server/include/dhcp_argument.h @@ -1,5 +1,5 @@ /* - * Copyright (C) 2021 Huawei Device Co., Ltd. + * Copyright (C) 2021-2022 Huawei Device Co., Ltd. * 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 @@ -13,15 +13,10 @@ * limitations under the License. */ + #ifndef OHOS_DHCP_ARGUMENT_H #define OHOS_DHCP_ARGUMENT_H -#include "hash_table.h" -#include "dhcp_define.h" -#ifdef __cplusplus -extern "C" { -#endif - #define ARGUMENT_NAME_SIZE 32 #define ARGUMENT_VALUE_SIZE 256 #define INIT_ARGS_SIZE 4 @@ -32,6 +27,11 @@ extern "C" { #define USAGE_DESC_MAX_LENGTH 32 + +#ifdef __cplusplus +extern "C" { +#endif + typedef struct DhcpUsage DhcpUsage; struct DhcpUsage { struct option *opt; @@ -66,4 +66,4 @@ void PrintRequiredArguments(void); } #endif -#endif // OHOS_DHCP_ARGUMENT_H \ No newline at end of file +#endif // OHOS_DHCP_ARGUMENT_H diff --git a/services/wifi_standard/wifi_framework/dhcp_manage/dhcp_server/include/dhcp_binding.h b/dhcp/services/dhcp_server/include/dhcp_binding.h similarity index 94% rename from services/wifi_standard/wifi_framework/dhcp_manage/dhcp_server/include/dhcp_binding.h rename to dhcp/services/dhcp_server/include/dhcp_binding.h index 5ef3bcba2023e178e628e8a54086a93e0a57a100..ad3b82b9aeb65027d5e1238334e076d5f4c76ff2 100644 --- a/services/wifi_standard/wifi_framework/dhcp_manage/dhcp_server/include/dhcp_binding.h +++ b/dhcp/services/dhcp_server/include/dhcp_binding.h @@ -1,5 +1,5 @@ /* - * Copyright (C) 2021 Huawei Device Co., Ltd. + * Copyright (C) 2021-2022 Huawei Device Co., Ltd. * 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 @@ -16,14 +16,12 @@ #ifndef OHOS_DHCP_BINDING_H #define OHOS_DHCP_BINDING_H -#include "dhcp_define.h" -#include -#include #include #ifdef __cplusplus extern "C" { #endif + enum BindingMode { BIND_MODE_STATIC = 0, BIND_MODE_DYNAMIC, BIND_MODE_RESERVED }; enum BindingState { BIND_NONE = 0, BIND_PENDING, BIND_ASSOCIATED, BIND_EXPIRED, BIND_RELEASED }; diff --git a/services/wifi_standard/wifi_framework/dhcp_manage/dhcp_server/include/dhcp_config.h b/dhcp/services/dhcp_server/include/dhcp_config.h similarity index 94% rename from services/wifi_standard/wifi_framework/dhcp_manage/dhcp_server/include/dhcp_config.h rename to dhcp/services/dhcp_server/include/dhcp_config.h index c3544fb9b6236bdf1e0f281ddb83da312ad861d0..fe3dfd0df95d39eab887ec698dd97fe5659590aa 100644 --- a/services/wifi_standard/wifi_framework/dhcp_manage/dhcp_server/include/dhcp_config.h +++ b/dhcp/services/dhcp_server/include/dhcp_config.h @@ -1,5 +1,5 @@ /* - * Copyright (C) 2021 Huawei Device Co., Ltd. + * Copyright (C) 2021-2022 Huawei Device Co., Ltd. * 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 @@ -16,18 +16,15 @@ #ifndef OHOS_DHCP_CONFIG_H #define OHOS_DHCP_CONFIG_H - -#include #include -#include +#include "dhcp_address_pool.h" #include "dhcp_define.h" #include "dhcp_option.h" -#include "dhcp_address_pool.h" -#include "dhcp_binding.h" #ifdef __cplusplus extern "C" { #endif + typedef struct DhcpConfig DhcpConfig; struct DhcpConfig { char ifname[IFACE_NAME_SIZE]; /* Network interface name. */ @@ -63,4 +60,4 @@ int LoadConfig(const char *configFile, const char *ifname, DhcpConfig *config); #ifdef __cplusplus } #endif -#endif \ No newline at end of file +#endif diff --git a/services/wifi_standard/wifi_framework/dhcp_manage/dhcp_server/include/dhcp_define.h b/dhcp/services/dhcp_server/include/dhcp_define.h similarity index 75% rename from services/wifi_standard/wifi_framework/dhcp_manage/dhcp_server/include/dhcp_define.h rename to dhcp/services/dhcp_server/include/dhcp_define.h index 6759187f39c3a40f091a16aa8644f2330b397b72..e1e40f9897d1984311c38f1b7f77c8d9dc4b34f7 100644 --- a/services/wifi_standard/wifi_framework/dhcp_manage/dhcp_server/include/dhcp_define.h +++ b/dhcp/services/dhcp_server/include/dhcp_define.h @@ -26,24 +26,18 @@ #define DHCP_BOOT_FILE_LENGTH 128 #define DHCP_LEASE_FILE_LENGTH 256 #define DHCP_FILE_LINE_LENGTH 1024 -#define DHCP_REFRESH_LEASE_FILE_INTERVAL 5 +#define DHCP_REFRESH_LEASE_FILE_INTERVAL 120 #define DHCP_MESSAGE_FLAG_LENGTH 16 #define DHCP_MAX_PATH_LENGTH 256 #define DHCP_ONE_BYTE_BITS 8 -#ifdef __OHOS__ -#define DHCPD_CONFIG_FILE "/data/dhcp/etc/dhcpd.conf" -#define DHCPD_EXT_CONFIG_PATH "/data/dhcp/etc/dhcpd.d" -#define DHCPD_LOG_PATH "/data/log/dhcpd" -#define DHCPD_LEASE_FILE "/data/dhcp/dhcpd_lease.lease" -#define DHCPD_PID_FILE "/data/dhcp/dhcpd.pid" -#else -#define DHCPD_CONFIG_FILE "/etc/dhcp/dhcpd.conf" -#define DHCPD_EXT_CONFIG_PATH "/etc/dhcp/dhcpd.d" -#define DHCPD_LEASE_FILE "/etc/dhcp/dhcpd_lease.lease" -#define DHCPD_LOG_PATH "/var/log/dhcpd" -#define DHCPD_PID_FILE "/etc/dhcp/dhcpd.pid" -#endif // __OHOS__ +#define DHCP_ROOT "/data/service/el1/public/dhcp/" + +#define DHCPD_CONFIG_FILE DHCP_ROOT"etc/dhcpd.conf" +#define DHCPD_EXT_CONFIG_PATH DHCP_ROOT"etc/dhcpd.d" +#define DHCPD_LEASE_FILE DHCP_ROOT"dhcpd_lease.lease" +#define DHCPD_PID_FILE DHCP_ROOT"dhcpd.pid" + #define DHCPD_VERSION "0.0.1" #define DHCP_SERVER_PORT 67 diff --git a/services/wifi_standard/wifi_framework/dhcp_manage/dhcp_server/include/dhcp_ipv4.h b/dhcp/services/dhcp_server/include/dhcp_ipv4.h similarity index 100% rename from services/wifi_standard/wifi_framework/dhcp_manage/dhcp_server/include/dhcp_ipv4.h rename to dhcp/services/dhcp_server/include/dhcp_ipv4.h diff --git a/services/wifi_standard/wifi_framework/dhcp_manage/dhcp_server/include/dhcp_logger.h b/dhcp/services/dhcp_server/include/dhcp_logger.h similarity index 93% rename from services/wifi_standard/wifi_framework/dhcp_manage/dhcp_server/include/dhcp_logger.h rename to dhcp/services/dhcp_server/include/dhcp_logger.h index f519b8dea1f30df0f317ec1950af675d7731fed4..16ee74761ae79379724d9a3102c747951b03590f 100644 --- a/services/wifi_standard/wifi_framework/dhcp_manage/dhcp_server/include/dhcp_logger.h +++ b/dhcp/services/dhcp_server/include/dhcp_logger.h @@ -1,5 +1,5 @@ /* - * Copyright (C) 2021 Huawei Device Co., Ltd. + * Copyright (C) 2021-2022 Huawei Device Co., Ltd. * 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 @@ -17,13 +17,17 @@ #define OHOS_DHCP_LOGGER_H #ifdef DHCP_HILOG_ENABLE +#ifdef OHOS_ARCH_LITE +#include "hilog/log.h" +#else #include "hilog/log_c.h" +#endif #undef LOG_TAG #define LOG_TAG "DhcpServer" #undef LOG_DOMAIN -#define LOG_DOMAIN 0x0000000 +#define LOG_DOMAIN 0xD001560 #define LOGD(...) ((void)HiLogPrint(LOG_CORE, LOG_DEBUG, LOG_DOMAIN, LOG_TAG, __VA_ARGS__)) @@ -41,9 +45,9 @@ #define LOG_DEBUG "Debug" #define LOG_TRACE "Trace" -#define LOG_WARN " Warn" +#define LOG_WARN "Warn" #define LOG_ERROR "Error" -#define LOG_INFO " Info" +#define LOG_INFO "Info" #define DEBUG_MODE 1 diff --git a/services/wifi_standard/wifi_framework/dhcp_manage/dhcp_server/include/dhcp_message.h b/dhcp/services/dhcp_server/include/dhcp_message.h similarity index 100% rename from services/wifi_standard/wifi_framework/dhcp_manage/dhcp_server/include/dhcp_message.h rename to dhcp/services/dhcp_server/include/dhcp_message.h diff --git a/services/wifi_standard/wifi_framework/dhcp_manage/dhcp_server/include/dhcp_option.h b/dhcp/services/dhcp_server/include/dhcp_option.h similarity index 96% rename from services/wifi_standard/wifi_framework/dhcp_manage/dhcp_server/include/dhcp_option.h rename to dhcp/services/dhcp_server/include/dhcp_option.h index cf0af1a5d955090010004417eb1dbc8e78fea632..ec05d6e6ebcfd48ab89e234e08ca151b5f3bb26a 100644 --- a/services/wifi_standard/wifi_framework/dhcp_manage/dhcp_server/include/dhcp_option.h +++ b/dhcp/services/dhcp_server/include/dhcp_option.h @@ -1,5 +1,5 @@ /* - * Copyright (C) 2021 Huawei Device Co., Ltd. + * Copyright (C) 2021-2022 Huawei Device Co., Ltd. * 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 @@ -16,9 +16,8 @@ #ifndef OHOS_DHCP_OPTION_H #define OHOS_DHCP_OPTION_H -#include -#include #include +#include #define DHCP_OPTION_SIZE 256 #define DHCP_END_OPTION_CODE 255 @@ -68,4 +67,4 @@ int AppendAddressOption(PDhcpOption pOption, uint32_t address); #ifdef __cplusplus } #endif -#endif \ No newline at end of file +#endif diff --git a/services/wifi_standard/wifi_framework/dhcp_manage/dhcp_server/include/dhcp_server.h b/dhcp/services/dhcp_server/include/dhcp_server.h similarity index 83% rename from services/wifi_standard/wifi_framework/dhcp_manage/dhcp_server/include/dhcp_server.h rename to dhcp/services/dhcp_server/include/dhcp_server.h index df8182192f4ceec32f2af949e0193c4c1872697b..d6a66fecbcf50d1fc6d7e6599ae23a23a31f4e56 100644 --- a/services/wifi_standard/wifi_framework/dhcp_manage/dhcp_server/include/dhcp_server.h +++ b/dhcp/services/dhcp_server/include/dhcp_server.h @@ -1,5 +1,5 @@ /* - * Copyright (C) 2021 Huawei Device Co., Ltd. + * Copyright (C) 2021-2022 Huawei Device Co., Ltd. * 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 @@ -15,8 +15,10 @@ #ifndef OHOS_DHCP_SERVER_H #define OHOS_DHCP_SERVER_H + #include "dhcp_config.h" -#include "dhcp_address_pool.h" +#include "dhcp_define.h" +#include "dhcp_message.h" enum DhcpServerState { ST_IDEL = 0, ST_STARTING, ST_RUNNING, ST_RELOADNG, ST_STOPING, ST_STOPED }; typedef int (*DhcpServerCallback)(int, int, const char *ifname); @@ -36,9 +38,11 @@ int StartDhcpServer(PDhcpServerContext ctx); int StopDhcpServer(PDhcpServerContext ctx); int GetServerStatus(PDhcpServerContext ctx); void RegisterDhcpCallback(PDhcpServerContext ctx, DhcpServerCallback callback); -int FreeServerContex(PDhcpServerContext ctx); +int FreeServerContext(PDhcpServerContext *ctx); +int SaveLease(PDhcpServerContext ctx); +int ReceiveDhcpMessage(int sock, PDhcpMsgInfo msgInfo); #ifdef __cplusplus } #endif -#endif \ No newline at end of file +#endif diff --git a/services/wifi_standard/wifi_framework/dhcp_manage/dhcp_server/include/hash_table.h b/dhcp/services/dhcp_server/include/hash_table.h similarity index 100% rename from services/wifi_standard/wifi_framework/dhcp_manage/dhcp_server/include/hash_table.h rename to dhcp/services/dhcp_server/include/hash_table.h diff --git a/services/wifi_standard/wifi_framework/dhcp_manage/dhcp_server/src/address_utils.c b/dhcp/services/dhcp_server/src/address_utils.c similarity index 94% rename from services/wifi_standard/wifi_framework/dhcp_manage/dhcp_server/src/address_utils.c rename to dhcp/services/dhcp_server/src/address_utils.c index 6862b77fb9a476c70b41976df62532df203dfdaa..e0e0a2142e93fb8c319d3f626de5659a10756940 100644 --- a/services/wifi_standard/wifi_framework/dhcp_manage/dhcp_server/src/address_utils.c +++ b/dhcp/services/dhcp_server/src/address_utils.c @@ -1,5 +1,5 @@ /* - * Copyright (C) 2021 Huawei Device Co., Ltd. + * Copyright (C) 2021-2022 Huawei Device Co., Ltd. * 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 @@ -14,10 +14,12 @@ */ #include "address_utils.h" -#include -#include #include +#include #include +#include +#include +#include "dhcp_define.h" #include "dhcp_logger.h" #undef LOG_TAG @@ -61,7 +63,7 @@ uint32_t NextIpAddress(uint32_t currIp, uint32_t netmask, uint32_t offset) if (currIp == lastIp || currIp == broadcast) { return FirstIpAddress(currIp, netmask); } - if (next > hostTotal) { + if (next > hostTotal && hostTotal > 0) { next = next % hostTotal; } uint32_t nextIp = htonl(currIp) + next + 1; @@ -138,9 +140,9 @@ int NetworkBits(uint32_t netmask) return bits; } -int HostBits(uint32_t netmask) +uint32_t HostBits(uint32_t netmask) { - int bits = 0; + uint32_t bits = 0; uint32_t net = htonl(netmask); for (int i = IPV4_ADDRESS_BITS; i > 0; --i) { bits++; @@ -152,25 +154,26 @@ int HostBits(uint32_t netmask) return bits; } -int HostTotal(uint32_t netmask) +uint32_t HostTotal(uint32_t netmask) { - int hostBits = HostBits(netmask); - int total = 1; + uint32_t hostBits = HostBits(netmask); + uint32_t total = 1; for (size_t i = 0; i < (size_t)hostBits; i++) { total *= BIT_MAX_VALUE; } total--; return total; } + uint32_t ParseIpAddr(const char *strIp) { struct in_addr inAddr; uint32_t ip = 0; int ret = inet_aton(strIp, &inAddr); if (ret != 0) { - if (memcpy_s(&ip, sizeof(struct in_addr), &inAddr, sizeof(uint32_t)) != EOK) { + if (memcpy_s(&ip, sizeof(uint32_t), &inAddr, sizeof(struct in_addr)) != EOK) { return 0; - }; + } return ip; } return 0; @@ -310,4 +313,4 @@ int AddrEquels(uint8_t firstAddr[DHCP_HWADDR_LENGTH], uint8_t secondAddr[DHCP_HW } } return DHCP_TRUE; -} \ No newline at end of file +} diff --git a/services/wifi_standard/wifi_framework/dhcp_manage/dhcp_server/src/common_util.c b/dhcp/services/dhcp_server/src/common_util.c similarity index 95% rename from services/wifi_standard/wifi_framework/dhcp_manage/dhcp_server/src/common_util.c rename to dhcp/services/dhcp_server/src/common_util.c index 2d6f25f6afc50f68d25832d114e8b9b5a5cd46b6..c2a3221f8bfcfe3d27f26498e8feaefc37b93f8c 100644 --- a/services/wifi_standard/wifi_framework/dhcp_manage/dhcp_server/src/common_util.c +++ b/dhcp/services/dhcp_server/src/common_util.c @@ -1,5 +1,5 @@ /* - * Copyright (C) 2021 Huawei Device Co., Ltd. + * Copyright (C) 2021-2022 Huawei Device Co., Ltd. * 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 @@ -12,23 +12,19 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + #include "common_util.h" -#include -#include #include -#include #include -#include -#include -#include -#include -#include -#include +#include +#include +#include #include -#include -#include -#include "dhcp_logger.h" +#include +#include +#include #include "dhcp_define.h" +#include "dhcp_logger.h" #define NEW_FILEPATH_MODE 0755 #define TIME_BASE_YEAR 1900 @@ -112,7 +108,7 @@ const char *GetFilePath(const char *fileName) return 0; } int flen = strlen(fileName); - if (!flen) { + if (flen == 0) { return 0; } char currName[DHCP_MAX_PATH_LENGTH] = {'\0'}; @@ -135,7 +131,10 @@ const char *GetFilePath(const char *fileName) const char *GetLeaseFile(const char *fileName, const char *ifname) { static char leaseFileName[DHCP_MAX_PATH_LENGTH]; - if (!fileName || ifname) { + if (!fileName || !ifname) { + return 0; + } + if (strlen(fileName) == 0 || strlen(ifname) == 0) { return 0; } if (snprintf_s(leaseFileName, sizeof(leaseFileName), sizeof(leaseFileName) - 1, "%s.%s", fileName, ifname) < 0) { @@ -199,4 +198,4 @@ int RemoveSpaceCharacters(char *buf, size_t bufSize) buf[j] = '\0'; return DHCP_TRUE; -} \ No newline at end of file +} diff --git a/services/wifi_standard/wifi_framework/dhcp_manage/dhcp_server/src/dhcp_address_pool.c b/dhcp/services/dhcp_server/src/dhcp_address_pool.c similarity index 96% rename from services/wifi_standard/wifi_framework/dhcp_manage/dhcp_server/src/dhcp_address_pool.c rename to dhcp/services/dhcp_server/src/dhcp_address_pool.c index f175b62ec5a460af2283513209393e887a31c563..474d17e517a1a2489a25ccc2e8b9b50aa72729b4 100644 --- a/services/wifi_standard/wifi_framework/dhcp_manage/dhcp_server/src/dhcp_address_pool.c +++ b/dhcp/services/dhcp_server/src/dhcp_address_pool.c @@ -1,5 +1,5 @@ /* - * Copyright (C) 2021 Huawei Device Co., Ltd. + * Copyright (C) 2021-2022 Huawei Device Co., Ltd. * 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 @@ -14,12 +14,10 @@ */ #include "dhcp_address_pool.h" +#include #include +#include #include -#include -#include -#include -#include "securec.h" #include "address_utils.h" #include "common_util.h" #include "dhcp_logger.h" @@ -41,7 +39,7 @@ AddressBinding *GetBindingByMac(HashTable *bindTable, uint8_t macAddr[DHCP_HWADD return NULL; } if (!Initialized(bindTable)) { - LOGE("binding recoders table dosn't initialized"); + LOGE("binding recoders table doesn't initialized"); return NULL; } if (ContainsKey(&g_bindingRecoders, (uintptr_t)macAddr)) { @@ -62,7 +60,7 @@ AddressBinding *GetBindingByIp(HashTable *bindTable, uint32_t ipAddress) return NULL; } if (!Initialized(bindTable)) { - LOGE("binding recoders table dosn't initialized"); + LOGE("binding recoders table doesn't initialized"); return NULL; } if (ContainsKey(bindTable, (uintptr_t)&ipAddress)) { @@ -163,7 +161,6 @@ int CheckRangeAvailability( LOGD("address is out of range"); return RET_FAILED; } else { - distIp = beginIp; *outOfRange = 1; } return RET_FAILED; @@ -193,14 +190,14 @@ uint32_t AddressDistribute(DhcpAddressPool *pool, uint8_t macAddr[DHCP_HWADDR_LE if (pool->distribution == 0) { pool->distribution = pool->addressRange.beginAddress; } - int total = HostTotal(pool->netmask); + uint32_t total = HostTotal(pool->netmask); uint32_t distIp = pool->distribution; if (!distIp || distIp < pool->addressRange.beginAddress) { distIp = pool->addressRange.beginAddress; } int distSucess = 0; int outOfRange = 0; - for (int i = 0; i < total; i++) { + for (uint32_t i = 0; i < total; i++) { int offset = 0; if (i == 0) { offset = NextIpOffset(pool->netmask); @@ -275,15 +272,15 @@ void FreeAddressPool(DhcpAddressPool *pool) } if (pool->fixedOptions.size > 0) { - FreeOptionList(&pool->fixedOptions); + ClearOptions(&pool->fixedOptions); } if (pool && Initialized(&pool->leaseTable)) { DestroyHashTable(&pool->leaseTable); } - if (Initialized(&g_bindingRecoders)) { - ClearAll(&g_bindingRecoders); + if (pool && HasInitialized(&pool->fixedOptions)) { + FreeOptionList(&pool->fixedOptions); } } @@ -316,7 +313,7 @@ AddressBinding *FindBindingByIp(uint32_t ipAddress) int IsReserved(uint8_t macAddr[DHCP_HWADDR_LENGTH]) { if (!Initialized(&g_bindingRecoders)) { - LOGD("binding recoders table dosn't initialized"); + LOGD("binding recoders table doesn't initialized"); return DHCP_FALSE; } if (ContainsKey(&g_bindingRecoders, (uintptr_t)macAddr)) { @@ -562,11 +559,13 @@ int LoadBindingRecoders(DhcpAddressPool *pool) int SaveBindingRecoders(const DhcpAddressPool *pool, int force) { if (pool == NULL) { + LOGE("Save binding record, pool is null"); return RET_FAILED; } static uint64_t lastTime = 0; uint64_t currTime = Tmspsec(); if (force == 0 && currTime < lastTime + DHCP_REFRESH_LEASE_FILE_INTERVAL) { + LOGE("Save binding record, time interval is not satisfied."); return RET_WAIT_SAVE; } char filePath[DHCP_LEASE_FILE_LENGTH] = {0}; @@ -577,6 +576,7 @@ int SaveBindingRecoders(const DhcpAddressPool *pool, int force) char line[DHCP_FILE_LINE_LENGTH] = {0}; FILE *fp = fopen(filePath, "w"); if (fp == NULL) { + LOGE("Save binding records %{private}s failed: %{public}d", filePath, errno); return RET_FAILED; } for (size_t index = 0; index < pool->leaseTable.capacity; ++index) { @@ -584,7 +584,7 @@ int SaveBindingRecoders(const DhcpAddressPool *pool, int force) while (node != NULL) { AddressBinding *binding = (AddressBinding *)node->value; if (WriteAddressBinding(binding, line, sizeof(line)) != RET_SUCCESS) { - LOGW("Failed to convert binding info to string"); + LOGE("Failed to convert binding info to string"); } else { fprintf(fp, "%s\n", line); } @@ -603,4 +603,4 @@ void SetDistributeMode(int mode) int GetDistributeMode(void) { return g_distributeMode; -} \ No newline at end of file +} diff --git a/services/wifi_standard/wifi_framework/dhcp_manage/dhcp_server/src/dhcp_argument.c b/dhcp/services/dhcp_server/src/dhcp_argument.c similarity index 77% rename from services/wifi_standard/wifi_framework/dhcp_manage/dhcp_server/src/dhcp_argument.c rename to dhcp/services/dhcp_server/src/dhcp_argument.c index a692d6fd8dea9f521b0b70b0be1fe1f89fd6e76d..f69baf31430784abb0e34c30c12c7f49855577c4 100644 --- a/services/wifi_standard/wifi_framework/dhcp_manage/dhcp_server/src/dhcp_argument.c +++ b/dhcp/services/dhcp_server/src/dhcp_argument.c @@ -1,5 +1,5 @@ /* - * Copyright (C) 2021 Huawei Device Co., Ltd. + * Copyright (C) 2021-2022 Huawei Device Co., Ltd. * 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 @@ -14,12 +14,17 @@ */ #include "dhcp_argument.h" -#include "dhcp_option.h" -#include "dhcp_config.h" +#include +#include +#include +#include +#include +#include #include "address_utils.h" -#include "securec.h" +#include "dhcp_define.h" #include "dhcp_logger.h" -#include +#include "hash_table.h" + #undef LOG_TAG #define LOG_TAG "DhcpArgument" @@ -48,11 +53,8 @@ static int PutPoolArgument(const char *argument, const char *val) static int ShowVersion(const char *argument, const char *val) { - if (argument && PutArgument(argument, val) != RET_SUCCESS) { - LOGD("failed to put argument 'version'."); - } printf("version:%s\n", DHCPD_VERSION); - return RET_BREAK; + return RET_SUCCESS; } static int DefaultArgument(const char *argument, const char *val) @@ -62,9 +64,9 @@ static int DefaultArgument(const char *argument, const char *val) return RET_SUCCESS; } -const char *optionString = "i:c:d:g:s:n:P:S:Bp:o:lb:rvhD"; +const char *g_optionString = "i:c:d:g:s:n:P:S:Bp:o:lb:rvhD"; -static struct option longOptions[] = { +static struct option g_longOptions[] = { {"ifname", REQUIRED_ARG, 0, 'i'}, {"conf", REQUIRED_ARG, 0, 'c'}, {"dns", REQUIRED_ARG, 0, 'd'}, @@ -81,22 +83,22 @@ static struct option longOptions[] = { }; static DhcpUsage usages[] = { - {&longOptions[NUM_ZERO], "", "network interface name.", "--ifname eth0", 1, PutArgument}, - {&longOptions[NUM_ONE], "", "configure file name.", "--conf /etc/conf/dhcp_server.conf", 0, PutArgument}, - {&longOptions[NUM_TWO], "[,dns2][,dns3][...]", "domain name server IP address list.", "", 0, PutArgument}, - {&longOptions[NUM_THREE], "", "gateway option.", "", 0, PutIpArgument}, - {&longOptions[NUM_FOUR], "", "server identifier.", "", 1, PutIpArgument}, - {&longOptions[NUM_FIVE], "", "default subnet mask.", "", 1, PutIpArgument}, - {&longOptions[NUM_SIX], ",", "pool address range.", "", 0, + {&g_longOptions[NUM_ZERO], "", "network interface name.", "--ifname eth0", 1, PutArgument}, + {&g_longOptions[NUM_ONE], "", "configure file name.", "--conf /etc/conf/dhcp_server.conf", 0, PutArgument}, + {&g_longOptions[NUM_TWO], "[,dns2][,dns3][...]", "domain name server IP address list.", "", 0, PutArgument}, + {&g_longOptions[NUM_THREE], "", "gateway option.", "", 0, PutIpArgument}, + {&g_longOptions[NUM_FOUR], "", "server identifier.", "", 1, PutIpArgument}, + {&g_longOptions[NUM_FIVE], "", "default subnet mask.", "", 1, PutIpArgument}, + {&g_longOptions[NUM_SIX], ",", "pool address range.", "", 0, PutPoolArgument}, - {&longOptions[NUM_SEVEN], "", "set lease time value, the value is in units of seconds.", "", 0, + {&g_longOptions[NUM_SEVEN], "", "set lease time value, the value is in units of seconds.", "", 0, PutArgument}, - {&longOptions[NUM_EIGHT], "", "set renewal time value, the value is in units of seconds.", "", 0, + {&g_longOptions[NUM_EIGHT], "", "set renewal time value, the value is in units of seconds.", "", 0, PutArgument}, - {&longOptions[NUM_NINE], "", "set rebinding time value, the value is in units of seconds.", "", 0, + {&g_longOptions[NUM_NINE], "", "set rebinding time value, the value is in units of seconds.", "", 0, PutArgument}, - {&longOptions[NUM_TEN], "", "show version information.", "", 0, ShowVersion}, - {&longOptions[NUM_ELEVEN], "", "show help information.", "", 0, DefaultArgument}, + {&g_longOptions[NUM_TEN], "", "show version information.", "", 0, ShowVersion}, + {&g_longOptions[NUM_ELEVEN], "", "show help information.", "", 0, DefaultArgument}, {0, "", "", ""}, }; @@ -122,16 +124,16 @@ int HasArgument(const char *argument) static void ShowUsage(const DhcpUsage *usage) { - if (!usage) { + if (!usage || !usage->opt) { return; } if (usage->opt->val) { - printf("-%c,--%s ", usage->opt->val, usage->opt->name); + printf("-%d,--%s ", usage->opt->val, usage->opt->name); } else { printf(" --%s ", usage->opt->name); } if (usage->params[0] == '\0') { - printf("\t%s\n", usage->desc); + printf("\t\t%s\n", usage->desc); } else { int plen = strlen(usage->params) + strlen(usage->params); if (plen < USAGE_DESC_MAX_LENGTH) { @@ -164,7 +166,7 @@ void PrintRequiredArguments(void) } printf(".\n\n"); printf("Usage: dhcp_server [options] \n"); - printf("e.g: dhcp_server -i eth0 -c /data/dhcp/dhcp_server.conf \n"); + printf("e.g: dhcp_server -i eth0 -c /data/service/el1/public/dhcp/dhcp_server.conf \n"); printf(" dhcp_server --help \n\n"); } @@ -244,9 +246,6 @@ int PutArgument(const char *argument, const char *val) LOGE("failed to set argument name."); return RET_ERROR; } - if (vlen < 0) { - return RET_ERROR; - } if (vlen >= ARGUMENT_VALUE_SIZE) { LOGE("value string too long."); return RET_ERROR; @@ -266,11 +265,11 @@ int PutArgument(const char *argument, const char *val) return RET_FAILED; } -static int findIndex(int c) +int FindIndex(int c) { - int size = sizeof(longOptions) / sizeof(longOptions[0]); + int size = sizeof(g_longOptions) / sizeof(g_longOptions[0]); for (int i = 0; i < size; ++i) { - if (longOptions[i].val == c) { + if (g_longOptions[i].val == c) { return i; } } @@ -284,14 +283,14 @@ int ParseArguments(int argc, char *argv[]) size_t optsc = sizeof(usages) / sizeof(DhcpUsage); int index = -1; int rst = RET_SUCCESS; - while ((ret = getopt_long(argc, argv, optionString, longOptions, &index)) != -1) { + while ((ret = getopt_long(argc, argv, g_optionString, g_longOptions, &index)) != -1) { if (ret == '?') { LOGW("unknown input arguments! ret = ?"); index = -1; continue; } if (index < 0) { - index = findIndex(ret); + index = FindIndex(ret); } if (index < 0 || index >= (int)optsc) { LOGD("unknown input arguments! ret = %c, index = %d", ret, index); diff --git a/services/wifi_standard/wifi_framework/dhcp_manage/dhcp_server/src/dhcp_binding.c b/dhcp/services/dhcp_server/src/dhcp_binding.c similarity index 97% rename from services/wifi_standard/wifi_framework/dhcp_manage/dhcp_server/src/dhcp_binding.c rename to dhcp/services/dhcp_server/src/dhcp_binding.c index d8c9bc6e73dcc35ea55d03ea7a0535fdc40c3313..e09e3452f990cb29abeea98d63b412bc1e0a98cd 100644 --- a/services/wifi_standard/wifi_framework/dhcp_manage/dhcp_server/src/dhcp_binding.c +++ b/dhcp/services/dhcp_server/src/dhcp_binding.c @@ -1,5 +1,5 @@ /* - * Copyright (C) 2021 Huawei Device Co., Ltd. + * Copyright (C) 2021-2022 Huawei Device Co., Ltd. * 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 @@ -14,12 +14,15 @@ */ #include "dhcp_binding.h" +#include #include #include -#include "dhcp_logger.h" +#include +#include #include "address_utils.h" #include "common_util.h" -#include "securec.h" +#include "dhcp_define.h" +#include "dhcp_logger.h" #undef LOG_TAG #define LOG_TAG "DhcpServerBinding" @@ -31,7 +34,6 @@ #define PENDING_INTERVAL_LEVEL1_TIMES 2 #define PENDING_INTERVAL_LEVEL2_TIMES 5 - uint64_t NextPendingInterval(uint64_t pendingInterval) { uint64_t next = pendingInterval; @@ -107,9 +109,11 @@ static void ReleaseStrings(char **strs) int i = 0; while (strs[i] != NULL) { free(strs[i]); + strs[i] = NULL; ++i; } free(strs); + strs = NULL; return; } diff --git a/services/wifi_standard/wifi_framework/dhcp_manage/dhcp_server/src/dhcp_config.c b/dhcp/services/dhcp_server/src/dhcp_config.c similarity index 98% rename from services/wifi_standard/wifi_framework/dhcp_manage/dhcp_server/src/dhcp_config.c rename to dhcp/services/dhcp_server/src/dhcp_config.c index 460f21c56c4e7211fc18a7fb1583a63049e5d889..bd429726eabf690423fd3386a8d8a31c25d215b8 100644 --- a/services/wifi_standard/wifi_framework/dhcp_manage/dhcp_server/src/dhcp_config.c +++ b/dhcp/services/dhcp_server/src/dhcp_config.c @@ -1,5 +1,5 @@ /* - * Copyright (C) 2021 Huawei Device Co., Ltd. + * Copyright (C) 2021-2022 Huawei Device Co., Ltd. * 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 @@ -12,22 +12,22 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + #include "dhcp_config.h" -#include +#include +#include #include -#include -#include -#include -#include "dhcp_logger.h" -#include "common_util.h" +#include +#include +#include #include "address_utils.h" +#include "common_util.h" #include "dhcp_ipv4.h" -#include "securec.h" +#include "dhcp_logger.h" #undef LOG_TAG #define LOG_TAG "DhcpServerConfig" - #define FILE_LINE_LEN_MAX 1024 #define FILE_LINE_DELIMITER "=" diff --git a/services/wifi_standard/wifi_framework/dhcp_manage/dhcp_server/src/dhcp_dhcpd.c b/dhcp/services/dhcp_server/src/dhcp_dhcpd.c similarity index 88% rename from services/wifi_standard/wifi_framework/dhcp_manage/dhcp_server/src/dhcp_dhcpd.c rename to dhcp/services/dhcp_server/src/dhcp_dhcpd.c index 12fb966de12aa21d0fde6e154f5ad35bd89e5f31..98bbcf5afbe2a1f6e631a8bcc17d250ad37cafaa 100644 --- a/services/wifi_standard/wifi_framework/dhcp_manage/dhcp_server/src/dhcp_dhcpd.c +++ b/dhcp/services/dhcp_server/src/dhcp_dhcpd.c @@ -1,5 +1,5 @@ /* - * Copyright (C) 2021 Huawei Device Co., Ltd. + * Copyright (C) 2021-2022 Huawei Device Co., Ltd. * 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 @@ -13,28 +13,21 @@ * limitations under the License. */ +#include +#include #include -#include -#include #include -#include -#include -#include -#include -#include +#include #include -#include -#include -#include -#include "dhcp_server.h" -#include "dhcp_define.h" -#include "dhcp_logger.h" -#include "dhcp_ipv4.h" -#include "hash_table.h" #include "address_utils.h" -#include "securec.h" -#include "dhcp_config.h" +#include "dhcp_address_pool.h" #include "dhcp_argument.h" +#include "dhcp_config.h" +#include "dhcp_define.h" +#include "dhcp_ipv4.h" +#include "dhcp_logger.h" +#include "dhcp_option.h" +#include "dhcp_server.h" #undef LOG_TAG #define LOG_TAG "DhcpServerMain" @@ -45,7 +38,6 @@ static DhcpConfig g_dhcpConfig; static PDhcpServerContext g_dhcpServer = 0; - enum SignalEvent { EXIT = 0, RELOAD, @@ -99,6 +91,9 @@ static int InitNetworkAbout(DhcpConfig *config) LOGE("error gateway argument."); return RET_FAILED; } + } else { + config->gateway = config->serverId; + LOGW("InitNetworkAbout, set gateway to serverId as default."); } return RET_SUCCESS; } @@ -153,10 +148,9 @@ static int InitAddressRange(DhcpConfig *config) static int InitDomainNameServer(DhcpConfig *config) { + DhcpOption argOpt = {DOMAIN_NAME_SERVER_OPTION, 0, {0}}; ArgumentInfo *arg = GetArgument("dns"); if (arg) { - DhcpOption argOpt = {DOMAIN_NAME_SERVER_OPTION, 0, {0}}; - char *pSave = NULL; char *pTok = strtok_r(arg->value, ",", &pSave); if ((pTok == NULL) || (strlen(pTok) == 0)) { @@ -171,15 +165,21 @@ static int InitDomainNameServer(DhcpConfig *config) } if (AppendAddressOption(&argOpt, dnsAddress) != RET_SUCCESS) { LOGW("failed to append dns option."); - }; + } pTok = strtok_r(NULL, ",", &pSave); } - - if (GetOption(&config->options, argOpt.code) != NULL) { - RemoveOption(&config->options, DOMAIN_NAME_SERVER_OPTION); + } else { + LOGW("%{public}s, set dns to serverId as default.", __func__); + uint32_t dnsAddress = config->serverId; + if (AppendAddressOption(&argOpt, dnsAddress) != RET_SUCCESS) { + LOGW("failed to append dns option."); } - PushBackOption(&config->options, &argOpt); } + + if (GetOption(&config->options, argOpt.code) != NULL) { + RemoveOption(&config->options, DOMAIN_NAME_SERVER_OPTION); + } + PushBackOption(&config->options, &argOpt); return RET_SUCCESS; } @@ -292,8 +292,7 @@ int ServerActionCallback(int state, int code, const char *ifname) break; } case ST_STOPED: { - LOGD(" callback[%s] ==> server stoped.", ifname); - exit(0); + LOGD(" callback[%s] ==> server stopped.", ifname); break; } default: @@ -306,7 +305,7 @@ static void SignalHandler(int signal) { switch (signal) { case SIGTERM: { - StopDhcpServer(g_dhcpServer); + exit(0); break; } case SIGUSR1: @@ -351,13 +350,13 @@ static int InitializeDhcpConfig(const char *ifname, DhcpConfig *config) return RET_FAILED; } } - LOGD("load local config file:%s", configFile); + LOGD("load local dhcp config file:%s", configFile); if (LoadConfig(configFile, ifname, config) != RET_SUCCESS) { - LOGE("faile to load configure file."); + LOGE("failed to load configure file."); return RET_FAILED; } if (InitConfigByArguments(config) != RET_SUCCESS) { - LOGE("faile to parse arguments."); + LOGE("failed to parse arguments."); return RET_FAILED; } @@ -373,7 +372,21 @@ void FreeSeverResources(void) { FreeArguments(); FreeLocalConfig(); - FreeServerContex(g_dhcpServer); + if (FreeServerContext(&g_dhcpServer) != RET_SUCCESS) { + LOGE("Free server context failed!"); + return; + } +} + +static void BeforeExit(void) +{ + if (g_dhcpServer) { + LOGD("saving lease recoder..."); + if (SaveLease(g_dhcpServer) != RET_SUCCESS) { + LOGD("failed to save lease recoder."); + } + } + FreeSeverResources(); } int main(int argc, char *argv[]) @@ -414,11 +427,13 @@ int main(int argc, char *argv[]) FreeSeverResources(); return 1; } + if (atexit(BeforeExit) != 0) { + LOGW("failed to register exit process function."); + } RegisterDhcpCallback(g_dhcpServer, ServerActionCallback); - if (StartDhcpServer(g_dhcpServer)) { + if (StartDhcpServer(g_dhcpServer) != RET_SUCCESS) { FreeSeverResources(); return 1; } - FreeSeverResources(); return 0; -} \ No newline at end of file +} diff --git a/services/wifi_standard/wifi_framework/dhcp_manage/dhcp_server/src/dhcp_option.c b/dhcp/services/dhcp_server/src/dhcp_option.c similarity index 95% rename from services/wifi_standard/wifi_framework/dhcp_manage/dhcp_server/src/dhcp_option.c rename to dhcp/services/dhcp_server/src/dhcp_option.c index dbd3364805f36b1c46c6cfc8af6f3e5fdce4c8f0..1c43d58fad66023e5b1098f6b278fc3db1abb9d0 100644 --- a/services/wifi_standard/wifi_framework/dhcp_manage/dhcp_server/src/dhcp_option.c +++ b/dhcp/services/dhcp_server/src/dhcp_option.c @@ -1,5 +1,5 @@ /* - * Copyright (C) 2021 Huawei Device Co., Ltd. + * Copyright (C) 2021-2022 Huawei Device Co., Ltd. * 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 @@ -16,7 +16,6 @@ #include "dhcp_option.h" #include #include -#include #include "dhcp_define.h" #include "dhcp_logger.h" #include "securec.h" @@ -40,6 +39,7 @@ PDhcpOptionNode CreateOptionNode(PDhcpOption opt) if (memcpy_s(pNode->option.data, sizeof(pNode->option.data), opt->data, opt->length) != EOK) { LOGE("create option node failed when memcpy opt data!"); free(pNode); + pNode = NULL; return NULL; } pNode->previous = pNode->next = 0; @@ -96,7 +96,7 @@ int PushBackOption(PDhcpOptionList pOptions, PDhcpOption pOption) } DhcpOptionNode *pNode = CreateOptionNode(pOption); if (!pNode) { - LOGE("failed to crate option node."); + LOGE("failed to create option node."); return 1; } pNode->previous = pOptions->last; @@ -139,9 +139,12 @@ int PushFrontOption(PDhcpOptionList pOptions, PDhcpOption pOption) int RemoveOption(PDhcpOptionList pOptions, uint8_t code) { - if (pOptions->size == 0) { + if (pOptions == NULL) { return RET_ERROR; } + if (pOptions->size == 0) { + return RET_FAILED; + } DhcpOptionNode *pNode = GetOptionNode(pOptions, code); if (pNode == NULL) { return RET_FAILED; @@ -155,6 +158,7 @@ int RemoveOption(PDhcpOptionList pOptions, uint8_t code) } pOptions->size--; free(pNode); + pNode = NULL; return RET_SUCCESS; } @@ -181,7 +185,7 @@ PDhcpOption GetOption(PDhcpOptionList pOptions, uint8_t code) void ClearOptions(PDhcpOptionList pOptions) { - if (pOptions->size == 0) { + if (pOptions == NULL || pOptions->size == 0) { return; } DhcpOptionNode *pNode = pOptions->first->next; @@ -205,7 +209,10 @@ void ClearOptions(PDhcpOptionList pOptions) void FreeOptionList(PDhcpOptionList pOptions) { - if (pOptions->size == 0) { + if (pOptions == NULL) { + return; + } + if (pOptions->first == NULL) { return; } DhcpOptionNode *pNode = pOptions->first->next; diff --git a/services/wifi_standard/wifi_framework/dhcp_manage/dhcp_server/src/dhcp_server.c b/dhcp/services/dhcp_server/src/dhcp_server.c similarity index 92% rename from services/wifi_standard/wifi_framework/dhcp_manage/dhcp_server/src/dhcp_server.c rename to dhcp/services/dhcp_server/src/dhcp_server.c index 7274acd0f3dd7d94fd55c0a785f4f1ba71a18aff..90af88de9f05395b952cd660da29e0a454e02038 100644 --- a/services/wifi_standard/wifi_framework/dhcp_manage/dhcp_server/src/dhcp_server.c +++ b/dhcp/services/dhcp_server/src/dhcp_server.c @@ -1,5 +1,5 @@ /* - * Copyright (C) 2021 Huawei Device Co., Ltd. + * Copyright (C) 2021-2022 Huawei Device Co., Ltd. * 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 @@ -14,32 +14,37 @@ */ #include "dhcp_server.h" -#include -#include -#include -#include #include -#include -#include +#include #include -#include +#include +#include +#include +#include +#include +#include +#include +#include #include -#include -#include "dhcp_ipv4.h" -#include "dhcp_message.h" -#include "dhcp_option.h" -#include "dhcp_ipv4.h" -#include "securec.h" -#include "dhcp_logger.h" +#include +#include +#include #include "address_utils.h" +#include "common_util.h" #include "dhcp_address_pool.h" +#include "dhcp_binding.h" #include "dhcp_config.h" -#include "common_util.h" +#include "dhcp_ipv4.h" +#include "dhcp_logger.h" +#include "dhcp_option.h" +#include "hash_table.h" #undef LOG_TAG #define LOG_TAG "DhcpServer" -#define DHCP_SEL_WAIT_TIMEOUTS 1500 +#ifndef DHCP_SEL_WAIT_TIMEOUTS +#define DHCP_SEL_WAIT_TIMEOUTS 1000 +#endif #define OPT_MESSAGE_TYPE_LEGTH 1 #define OPT_HEADER_LENGTH 2 #define OPT_TIME_LENGTH 4 @@ -92,7 +97,7 @@ enum LooperState { LS_STOPED }; typedef struct sockaddr_in sockaddr_in; -static int FillReply(PDhcpServerContext ctx, PDhcpMsgInfo received, PDhcpMsgInfo reply); +int FillReply(PDhcpServerContext ctx, PDhcpMsgInfo received, PDhcpMsgInfo reply); static int OnReceivedDiscover(PDhcpServerContext ctx, PDhcpMsgInfo received, PDhcpMsgInfo reply); static int OnReceivedRequest(PDhcpServerContext ctx, PDhcpMsgInfo received, PDhcpMsgInfo reply); static int OnReceivedDecline(PDhcpServerContext ctx, PDhcpMsgInfo received, PDhcpMsgInfo reply); @@ -250,8 +255,8 @@ int ReceiveDhcpMessage(int sock, PDhcpMsgInfo msgInfo) fd_set recvFd; FD_ZERO(&recvFd); FD_SET(sock, &recvFd); - time_t tms = DHCP_SEL_WAIT_TIMEOUTS; - tmt.tv_sec = tms; + time_t seconds = DHCP_SEL_WAIT_TIMEOUTS; + tmt.tv_sec = seconds; tmt.tv_usec = 0; if (select(sock + 1, &recvFd, NULL, NULL, &tmt) < 0) { LOGE("select error, %d", errno); @@ -266,17 +271,17 @@ int ReceiveDhcpMessage(int sock, PDhcpMsgInfo msgInfo) srcAddrIn->sin_addr.s_addr = INADDR_ANY; int rsize = recvfrom(sock, recvBuffer, RECV_BUFFER_SIZE, 0, (struct sockaddr *)srcAddrIn, (socklen_t *)&ssize); if (!rsize) { - LOGE("receive error, %d", errno); + LOGE("receive error, %d", errno); return RET_FAILED; } - if (rsize > (int)sizeof(DhcpMsgInfo) || rsize < DHCP_MSG_HEADER_SIZE) { + if (rsize > (int)sizeof(DhcpMessage) || rsize < DHCP_MSG_HEADER_SIZE) { LOGW("message length error, received %d bytes.", rsize); return RET_FAILED; } msgInfo->length = rsize; if (memcpy_s(&msgInfo->packet, sizeof(DhcpMessage), recvBuffer, rsize) != EOK) { return RET_FAILED; - }; + } if (msgInfo->packet.op != BOOTREQUEST) { LOGW("dhcp message type error!"); return RET_FAILED; @@ -299,7 +304,7 @@ int ReceiveDhcpMessage(int sock, PDhcpMsgInfo msgInfo) void InitReply(PDhcpServerContext ctx, PDhcpMsgInfo received, PDhcpMsgInfo reply) { if (!reply) { - LOGE("reply messsage pointer is null!"); + LOGE("reply message pointer is null!"); return; } reply->packet.op = BOOTREPLY; @@ -336,7 +341,7 @@ void OnUpdateServerConfig(PDhcpServerContext ctx) static void OnServerStoping(PDhcpServerContext ctx) { - LOGD("server stoping ..."); + LOGD("server stopping ..."); ServerContext *srvIns = GetServerInstance(ctx); if (!srvIns) { LOGE("dhcp server context pointer is null."); @@ -355,12 +360,6 @@ void OnServerStoped(PDhcpServerContext ctx, int code) LOGE("dhcp server context pointer is null."); return; } - LOGD("saving lease recoders ...."); - if (SaveBindingRecoders(&srvIns->addressPool, 1) == RET_SUCCESS) { - LOGI("lease seaved. total: %zu", srvIns->addressPool.leaseTable.size); - } else { - LOGW("failed to save lease."); - } if (srvIns->callback) { srvIns->callback(ST_STOPED, code, ctx->ifname); } @@ -444,7 +443,6 @@ static int MessageProcess(PDhcpServerContext ctx, PDhcpMsgInfo received, PDhcpMs return replyType; } - int SaveLease(PDhcpServerContext ctx) { ServerContext *srvIns = GetServerInstance(ctx); @@ -452,7 +450,7 @@ int SaveLease(PDhcpServerContext ctx) LOGE("dhcp server context pointer is null."); return RET_FAILED; } - int saveRet = SaveBindingRecoders(&srvIns->addressPool, 0); + int saveRet = SaveBindingRecoders(&srvIns->addressPool, 1); if (saveRet == RET_FAILED) { LOGD("failed to save lease recoders. total: %zu", srvIns->addressPool.leaseTable.size); } else if (saveRet == RET_SUCCESS) { @@ -502,16 +500,15 @@ static int ContinueReceive(PDhcpMsgInfo from, int recvRet) static int BeginLooper(PDhcpServerContext ctx) { - DhcpMsgInfo from; - DhcpMsgInfo reply; - int saveLease = 0; + DhcpMsgInfo from = { 0 }; + DhcpMsgInfo reply = { 0 }; ServerContext *srvIns = GetServerInstance(ctx); if (!srvIns) { LOGE("dhcp server context pointer is null."); return RET_FAILED; } ctx->instance->serverFd = InitServer(ctx->ifname); - if (!ctx->instance->serverFd) { + if (ctx->instance->serverFd < 0) { LOGE("failed to initialize server socket."); return RET_FAILED; } @@ -524,30 +521,30 @@ static int BeginLooper(PDhcpServerContext ctx) } ClearOptions(&from.options); ClearOptions(&reply.options); - if (saveLease && SaveLease(ctx) == RET_SUCCESS) { - saveLease = 0; - } int recvRet = ReceiveDhcpMessage(ctx->instance->serverFd, &from); + if (recvRet == RET_ERROR || recvRet == ERR_SELECT) { + break; + } if (ContinueReceive(&from, recvRet)) { - if (recvRet == RET_ERROR || recvRet == ERR_SELECT) { - break; - } continue; } InitReply(ctx, &from, &reply); int replyType = MessageProcess(ctx, &from, &reply); - int snedRet = -1; - if (replyType && (snedRet = SendDhcpReply(ctx, replyType, &reply)) != RET_SUCCESS) { + if (replyType && SendDhcpReply(ctx, replyType, &reply) != RET_SUCCESS) { LOGE("failed to send reply message."); } - if (replyType == REPLY_ACK && snedRet) { - saveLease = 1; + if (replyType == REPLY_ACK || replyType == REPLY_OFFER) { + int saveRet = SaveBindingRecoders(&srvIns->addressPool, 0); + if (saveRet != RET_SUCCESS && saveRet != RET_WAIT_SAVE) { + LOGW("failed to save lease recoders."); + } } - } // while (srvIns->looperState) + } FreeOptionList(&from.options); FreeOptionList(&reply.options); - LOGD("dhcp server message looper stoped."); + LOGD("dhcp server message looper stopped."); close(ctx->instance->serverFd); + ctx->instance->serverFd = -1; srvIns->looperState = LS_STOPED; return 0; } @@ -556,12 +553,12 @@ static int CheckAddressRange(DhcpAddressPool *pool) { uint32_t serverNetwork = NetworkAddress(pool->serverId, pool->netmask); uint32_t firstNetwork = NetworkAddress(pool->addressRange.beginAddress, pool->netmask); - uint32_t sencodNetwork = NetworkAddress(pool->addressRange.endAddress, pool->netmask); - if (!serverNetwork || !firstNetwork || !sencodNetwork) { + uint32_t secondNetwork = NetworkAddress(pool->addressRange.endAddress, pool->netmask); + if (!serverNetwork || !firstNetwork || !secondNetwork) { LOGE("network config error."); return DHCP_FALSE; } - if (serverNetwork != firstNetwork || firstNetwork != serverNetwork) { + if (serverNetwork != firstNetwork || serverNetwork != secondNetwork) { LOGE("server network and address pool network belong to different networks."); return DHCP_FALSE; } @@ -594,7 +591,7 @@ void InitBindingRecoders(DhcpAddressPool *pool) LOGE("bad binding recoder."); invalidBindig = 1; } - if (!invalidBindig && pool->distribution < binding->ipAddress) { + if (!invalidBindig && binding && pool->distribution < binding->ipAddress) { pool->distribution = binding->ipAddress; } node = next; @@ -625,6 +622,12 @@ void InitLeaseFile(DhcpAddressPool *pool) InitBindingRecoders(pool); } +static void ExitProcess(void) +{ + LOGD("dhcp server stopped."); + sleep(1); +} + int StartDhcpServer(PDhcpServerContext ctx) { LOGD("dhcp server starting ..."); @@ -641,6 +644,9 @@ int StartDhcpServer(PDhcpServerContext ctx) LOGE("dhcp server context instance pointer is null."); return RET_FAILED; } + if (atexit(ExitProcess) != 0) { + LOGW("failed to regiester exit process function."); + } if (!srvIns->initialized) { LOGE("dhcp server no initialized."); return RET_FAILED; @@ -652,12 +658,10 @@ int StartDhcpServer(PDhcpServerContext ctx) } int ret = BeginLooper(ctx); if (ret != RET_SUCCESS) { - LOGD("faild to start dhcp server."); - FreeAddressPool(&srvIns->addressPool); + LOGD("failed to start dhcp server."); OnServerStoped(ctx, ret); return RET_FAILED; } - FreeAddressPool(&srvIns->addressPool); OnServerStoped(ctx, ret); return RET_SUCCESS; } @@ -682,7 +686,7 @@ int GetServerStatus(PDhcpServerContext ctx) return srvIns->looperState; } -static int FillReply(PDhcpServerContext ctx, PDhcpMsgInfo received, PDhcpMsgInfo reply) +int FillReply(PDhcpServerContext ctx, PDhcpMsgInfo received, PDhcpMsgInfo reply) { if (!received || !reply) { return RET_ERROR; @@ -735,7 +739,7 @@ static int FillReply(PDhcpServerContext ctx, PDhcpMsgInfo received, PDhcpMsgInfo int AppendReplyTimeOptions(PDhcpServerContext ctx, PDhcpOptionList options) { if (!ctx || !options) { - LOGE("server context or options poninter is null."); + LOGE("server context or options pointer is null."); return RET_FAILED; } ServerContext *srvIns = GetServerInstance(ctx); @@ -773,7 +777,6 @@ int AppendReplyTimeOptions(PDhcpServerContext ctx, PDhcpOptionList options) static int Repending(DhcpAddressPool *pool, AddressBinding *binding) { if (!pool) { - LOGE("address pool pointer is null."); return REPLY_NONE; } uint32_t bindingIp = binding->ipAddress; @@ -828,7 +831,6 @@ static int Rebinding(DhcpAddressPool *pool, AddressBinding *binding) static void AddAddressOption(PDhcpMsgInfo reply, uint8_t code, int32_t address) { if (!reply) { - LOGE("reply message pointer is null."); return; } DhcpOption optAddress = {0, 0, {0}}; @@ -840,13 +842,13 @@ static void AddAddressOption(PDhcpMsgInfo reply, uint8_t code, int32_t address) PushBackOption(&reply->options, &optAddress); } -static int AddReplyServerIdOption(PDhcpOptionList options, uint32_t serverId) +int AddReplyServerIdOption(PDhcpOptionList options, uint32_t serverId) { if (!options) { LOGE("option list pointer is null."); return RET_FAILED; } - if (!serverId || serverId==INADDR_BROADCAST) { + if (!serverId || serverId == INADDR_BROADCAST) { LOGE("servier id error."); return RET_FAILED; } @@ -866,7 +868,6 @@ static int AddReplyServerIdOption(PDhcpOptionList options, uint32_t serverId) static void AddReplyMessageTypeOption(PDhcpMsgInfo reply, uint8_t replyMessageType) { if (!reply) { - LOGE("reply message pointer is null."); return; } DhcpOption optMsgType = {DHCP_MESSAGE_TYPE_OPTION, OPT_MESSAGE_TYPE_LEGTH, {replyMessageType, 0}}; @@ -874,19 +875,21 @@ static void AddReplyMessageTypeOption(PDhcpMsgInfo reply, uint8_t replyMessageTy } -static AddressBinding *GetBinding(DhcpAddressPool *pool, PDhcpMsgInfo received) +AddressBinding *GetBinding(DhcpAddressPool *pool, PDhcpMsgInfo received) { if (!pool) { - LOGE("address pool pointer is null."); return NULL; } if (!received) { - LOGE("received message pointer is null."); return NULL; } AddressBinding *binding = pool->binding(received->packet.chaddr, &received->options); if (!binding) { binding = pool->newBinding(received->packet.chaddr, &received->options); + if (binding == NULL) { + LOGE("new binding is null"); + return NULL; + } if (pool->leaseTime) { binding->leaseTime = pool->leaseTime; } @@ -901,25 +904,26 @@ static AddressBinding *GetBinding(DhcpAddressPool *pool, PDhcpMsgInfo received) static int OnReceivedDiscover(PDhcpServerContext ctx, PDhcpMsgInfo received, PDhcpMsgInfo reply) { if (!received || !reply) { - LOGE("receive or reply message pointer is null."); return REPLY_NONE; } LOGI("received 'Discover' message from: %s", ParseLogMac(received->packet.chaddr)); ServerContext *srvIns = GetServerInstance(ctx); if (!srvIns) { - LOGE("dhcp server context pointer is null."); return REPLY_NONE; } + uint32_t reqIp = 0; PDhcpOption optReqIp = GetOption(&received->options, REQUESTED_IP_ADDRESS_OPTION); if (optReqIp) { - uint32_t reqIp = ParseIp(optReqIp->data); + reqIp = ParseIp(optReqIp->data); if (reqIp) { LOGD(" request ip: %s", ParseStrIp(reqIp)); } } uint32_t srcIp = SourceIpAddress(); if (!srvIns->broadCastFlagEnable) { - if (!srcIp) { + if (srcIp) { + LOGD(" client repending:%s", ParseStrIp(srcIp)); + } else { srcIp = INADDR_BROADCAST; } DestinationAddr(srcIp); @@ -932,6 +936,10 @@ static int OnReceivedDiscover(PDhcpServerContext ctx, PDhcpMsgInfo received, PDh LOGE("no ip address available."); return REPLY_NONE; } + if (reqIp != 0 && reqIp != binding->ipAddress) { + LOGE("error request message."); + return REPLY_NONE; + } AddressBinding *lease = GetLease(&srvIns->addressPool, binding->ipAddress); if (!lease) { LOGD("add lease recoder."); @@ -1003,7 +1011,7 @@ static int NotBindingRequest(DhcpAddressPool *pool, PDhcpMsgInfo received, PDhcp AddressBinding *lease = GetLease(pool, yourIpAddr); if (!lease) { if (SourceIpAddress()) { - return REPLY_NAK; + return REPLY_ACK; } return REPLY_NONE; } @@ -1015,14 +1023,19 @@ static int NotBindingRequest(DhcpAddressPool *pool, PDhcpMsgInfo received, PDhcp RemoveLease(pool, lease); } AddressBinding *binding = pool->newBinding(received->packet.chaddr, &received->options); + if (binding == NULL) { + LOGE("Not binding request binding is null."); + return REPLY_NONE; + } binding->ipAddress = yourIpAddr; if (pool->leaseTime) { binding->leaseTime = pool->leaseTime; } int replyType = Repending(pool, binding); - if (replyType != REPLY_ACK) { - return replyType; + if (replyType != REPLY_OFFER) { + return replyType; } + lease = GetLease(pool, yourIpAddr); if (!lease) { LOGD("add new lease recoder."); AddLease(pool, binding); @@ -1043,14 +1056,12 @@ static int ValidateRequestMessage(const PDhcpServerContext ctx, const PDhcpMsgIn PDhcpMsgInfo reply, uint32_t *yourIp) { if (!received || !reply) { - LOGE("receive or reply message pointer is null."); return REPLY_NONE; } LOGI("received 'Request' message from: %s.", ParseLogMac(received->packet.chaddr)); uint32_t yourIpAddr = INADDR_BROADCAST; ServerContext *srvIns = GetServerInstance(ctx); if (!srvIns) { - LOGE("dhcp server context pointer is null."); return RET_FAILED; } if (GetYourIpAddress(received, &yourIpAddr) != RET_SUCCESS) { @@ -1091,7 +1102,7 @@ static int HasNobindgRequest(PDhcpServerContext ctx, PDhcpMsgInfo received, PDhc uint32_t srcIp = SourceIpAddress(); uint32_t reqIp = GetRequestIpAddress(received); LOGD("allow no binding request mode."); - if (!reqIp && !srcIp) { + if (reqIp == 0 && srcIp == 0) { LOGE("error dhcp message."); return REPLY_NONE; } @@ -1101,7 +1112,7 @@ static int HasNobindgRequest(PDhcpServerContext ctx, PDhcpMsgInfo received, PDhc } return NotBindingRequest(&srvIns->addressPool, received, reply); } - return REPLY_ACK; + return REPLY_NONE; } static int OnReceivedRequest(PDhcpServerContext ctx, PDhcpMsgInfo received, PDhcpMsgInfo reply) @@ -1113,8 +1124,9 @@ static int OnReceivedRequest(PDhcpServerContext ctx, PDhcpMsgInfo received, PDhc } ServerContext *srvIns = GetServerInstance(ctx); AddressBinding *binding = srvIns->addressPool.binding(received->packet.chaddr, &received->options); - if ((ret = HasNobindgRequest(ctx, received, reply)) != REPLY_ACK) { - return ret; + if (binding == NULL) { + LOGE("OnReceivedRequest, binding is null"); + return HasNobindgRequest(ctx, received, reply); } Rebinding(&srvIns->addressPool, binding); AddressBinding *lease = GetLease(&srvIns->addressPool, yourIpAddr); @@ -1151,12 +1163,10 @@ static int OnReceivedRequest(PDhcpServerContext ctx, PDhcpMsgInfo received, PDhc static int OnReceivedDecline(PDhcpServerContext ctx, PDhcpMsgInfo received, PDhcpMsgInfo reply) { if (!received || !reply) { - LOGE("receive or reply message pointer is null."); return REPLY_NONE; } ServerContext *srvIns = GetServerInstance(ctx); if (!srvIns) { - LOGE("dhcp server context pointer is null."); return REPLY_NONE; } LOGI("received 'Decline' message from: %s.", ParseLogMac(received->packet.chaddr)); @@ -1194,12 +1204,10 @@ static int OnReceivedDecline(PDhcpServerContext ctx, PDhcpMsgInfo received, PDhc static int OnReceivedRelease(PDhcpServerContext ctx, PDhcpMsgInfo received, PDhcpMsgInfo reply) { if (!received || !reply) { - LOGE("receive or reply message pointer is null."); return REPLY_NONE; } LOGI("received 'Release' message from: %s", ParseLogMac(received->packet.chaddr)); if (!ctx || !ctx->instance) { - LOGE("dhcp server context pointer is null."); return RET_FAILED; } PDhcpOption optReqIp = GetOption(&received->options, REQUESTED_IP_ADDRESS_OPTION); @@ -1222,11 +1230,11 @@ static int OnReceivedRelease(PDhcpServerContext ctx, PDhcpMsgInfo received, PDhc reqIp = ParseIp(optReqIp->data); } uint32_t srcIp = SourceIpAddress(); - if (reqIp && reqIp != srcIp) { + if (srcIp != 0 && reqIp != 0 && reqIp != srcIp) { LOGE("error release message, invalid request ip address."); return REPLY_NONE; } - if (reqIp && reqIp != bindIp) { + if (bindIp != 0 && reqIp != 0 && reqIp != bindIp) { LOGE("error release message, invalid request ip address."); return REPLY_NONE; } @@ -1248,7 +1256,6 @@ static int OnReceivedRelease(PDhcpServerContext ctx, PDhcpMsgInfo received, PDhc static int OnReceivedInform(PDhcpServerContext ctx, PDhcpMsgInfo received, PDhcpMsgInfo reply) { if (!received || !reply) { - LOGE("receive or reply message pointer is null."); return REPLY_NONE; } ServerContext *srvIns = GetServerInstance(ctx); @@ -1267,7 +1274,6 @@ static int AppendFixedOptions(PDhcpServerContext ctx, PDhcpMsgInfo reply) { ServerContext *srvIns = GetServerInstance(ctx); if (!srvIns) { - LOGE("dhcp server context pointer is null."); return RET_FAILED; } if (!reply) { @@ -1328,7 +1334,6 @@ static int SendDhcpOffer(PDhcpServerContext ctx, PDhcpMsgInfo reply) { ServerContext *srvIns = GetServerInstance(ctx); if (!srvIns) { - LOGE("dhcp server context pointer is null."); return RET_FAILED; } if (AppendReplyTypeOption(reply, REPLY_OFFER) != RET_SUCCESS) { @@ -1433,13 +1438,6 @@ static int SendDhcpNak(PDhcpServerContext ctx, PDhcpMsgInfo reply) static int ParseMessageOptions(PDhcpMsgInfo msg) { - if (msg->packet.hlen < 0) { - return RET_FAILED; - } - if (msg->packet.hlen > DHCP_MESSAGE_FLAG_LENGTH) { - return RET_FAILED; - } - if (msg->length < (DHCP_MSG_HEADER_SIZE + MAGIC_COOKIE_LENGTH)) { return RET_FAILED; } @@ -1462,7 +1460,7 @@ static int ParseMessageOptions(PDhcpMsgInfo msg) return RET_FAILED; } if (PushBackOption(&msg->options, current) != RET_SUCCESS) { - LOGD("faild to PushOption."); + LOGD("failed to PushOption."); } current = (DhcpOption *)(((uint8_t *)current) + OPT_HEADER_LENGTH + current->length); optTotal++; @@ -1504,10 +1502,9 @@ static int ValidateReplyOptions(PDhcpMsgInfo reply) if (!pNode) { return RET_ERROR; } - pNode = pNode->next; PDhcpOption pOptMsgType = GetOption(&reply->options, DHCP_MESSAGE_TYPE_OPTION); if (!pOptMsgType) { - LOGE("unkown reply message type."); + LOGE("unknown reply message type."); return ret; } return RET_SUCCESS; @@ -1612,14 +1609,14 @@ static int InitServerContext(DhcpConfig *config, DhcpServerContext *ctx) return RET_FAILED; } if (!CheckAddressRange(&srvIns->addressPool)) { + LOGE("failed to validate address range."); return RET_FAILED; } - InitLeaseFile(&srvIns->addressPool); return RET_SUCCESS; } -static int InitServerFixedOptions(DhcpConfig *config, DhcpServerContext *ctx) +int InitServerFixedOptions(DhcpConfig *config, DhcpServerContext *ctx) { if (!config) { LOGE("server configure pointer is null."); @@ -1635,7 +1632,9 @@ static int InitServerFixedOptions(DhcpConfig *config, DhcpServerContext *ctx) LOGE("dhcp configure has not been initialized."); return RET_FAILED; } - + if (InitOptionList(&srvIns->addressPool.fixedOptions) != RET_SUCCESS) { + return RET_FAILED; + } if (config->options.first != NULL && config->options.size > 0) { DhcpOptionNode *pNode = config->options.first->next; for (size_t i = 0; pNode != NULL && i < config->options.size; i++) { @@ -1669,17 +1668,17 @@ PDhcpServerContext InitializeServer(DhcpConfig *config) } if ((context->instance = calloc(1, sizeof(ServerContext))) == NULL) { LOGE("failed to calloc server instance."); - FreeServerContex(context); + FreeServerContext(&context); return NULL; } if (InitServerContext(config, context) != RET_SUCCESS) { LOGE("failed initialize dhcp server context."); - FreeServerContex(context); + FreeServerContext(&context); return NULL; } if (InitServerFixedOptions(config, context) != RET_SUCCESS) { LOGE("failed initialize dhcp server fixed options."); - FreeServerContex(context); + FreeServerContext(&context); return NULL; } LOGD("server id: %s", ParseStrIp(config->serverId)); @@ -1693,18 +1692,23 @@ PDhcpServerContext InitializeServer(DhcpConfig *config) return context; } -int FreeServerContex(PDhcpServerContext ctx) +int FreeServerContext(PDhcpServerContext *ctx) { - if (!ctx) { + if (ctx == NULL || *ctx == NULL) { LOGE("dhcp server context pointer is null."); return RET_FAILED; } - if (ctx->instance) { - ServerContext *srvIns = GetServerInstance(ctx); - FreeAddressPool(&srvIns->addressPool); - free(ctx->instance); - ctx->instance = NULL; + ServerContext *srvIns = GetServerInstance(*ctx); + if (!srvIns) { + LOGE("dhcp server instance pointer is null."); + return RET_FAILED; + } + FreeAddressPool(&srvIns->addressPool); + if ((*ctx)->instance != NULL) { + free((*ctx)->instance); + (*ctx)->instance = NULL; + free(*ctx); + *ctx = NULL; } - free(ctx); return RET_SUCCESS; -} \ No newline at end of file +} diff --git a/services/wifi_standard/wifi_framework/dhcp_manage/dhcp_server/src/hash_table.c b/dhcp/services/dhcp_server/src/hash_table.c similarity index 98% rename from services/wifi_standard/wifi_framework/dhcp_manage/dhcp_server/src/hash_table.c rename to dhcp/services/dhcp_server/src/hash_table.c index eda7d34e48e3280ed49236c799cb088346328bc6..daa88f6b30aa208913f0462b247a0c0823bcddf4 100644 --- a/services/wifi_standard/wifi_framework/dhcp_manage/dhcp_server/src/hash_table.c +++ b/dhcp/services/dhcp_server/src/hash_table.c @@ -1,5 +1,5 @@ /* - * Copyright (C) 2021 Huawei Device Co., Ltd. + * Copyright (C) 2021-2022 Huawei Device Co., Ltd. * 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 @@ -14,10 +14,9 @@ */ #include "hash_table.h" -#include +#include #include #include -#include "securec.h" #define HASH_TRUE 1 #define HASH_FALSE 0 @@ -307,6 +306,7 @@ HashNode *HashCreateNode(HashTable *table, uintptr_t key, uintptr_t value, HashN free((void *)node->key); free((void *)node->value); free(node); + node = NULL; return 0; } node->next = next; @@ -327,6 +327,7 @@ void DestroyHashNode(HashNode *node) free((void *)node->key); free((void *)node->value); free(node); + node = NULL; } int HashAdjustCapacity(HashTable *table) @@ -367,6 +368,7 @@ int Resize(HashTable *table, size_t newSize) } HashRehash(table, old, oldSize); free(old); + old = NULL; return HASH_SUCCESS; } @@ -382,4 +384,4 @@ void HashRehash(HashTable *table, HashNode **old, size_t oldCapacity) node = next; } } -} \ No newline at end of file +} diff --git a/dhcp/services/mgr_service/BUILD.gn b/dhcp/services/mgr_service/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..b98239508595de9c3bd85be9e97e73c234dbdffe --- /dev/null +++ b/dhcp/services/mgr_service/BUILD.gn @@ -0,0 +1,102 @@ +# Copyright (C) 2021-2022 Huawei Device Co., Ltd. +# 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. + +if (defined(ohos_lite)) { + import("//build/lite/config/component/lite_component.gni") + import("//foundation/communication/wifi/dhcp/dhcp_lite.gni") +} else { + import("//build/ohos.gni") + import("//foundation/communication/wifi/dhcp/dhcp.gni") +} + +################################################################################ + +local_base_sources = [ + "$DHCP_ROOT_DIR/services/mgr_service/src/dhcp_client_service_impl.cpp", + "$DHCP_ROOT_DIR/services/mgr_service/src/dhcp_event_subscriber.cpp", + "$DHCP_ROOT_DIR/services/mgr_service/src/dhcp_func.cpp", + "$DHCP_ROOT_DIR/services/mgr_service/src/dhcp_server_service.cpp", + "$DHCP_ROOT_DIR/services/mgr_service/src/dhcp_service.cpp", + "$DHCP_ROOT_DIR/services/mgr_service/src/dhcp_service_api.cpp", +] + +local_base_include_dirs = [ + "$WIFI_ROOT_DIR/services/wifi_standard/wifi_framework/wifi_toolkit/log", + "$DHCP_ROOT_DIR/services/mgr_service/include", + "$DHCP_ROOT_DIR/interfaces/inner_api/interfaces", + "$DHCP_ROOT_DIR/interfaces/inner_api/include", +] + +if (defined(ohos_lite)) { + shared_library("dhcp_manager_service") { + sources = local_base_sources + + include_dirs = local_base_include_dirs + include_dirs += [ + "//base/hiviewdfx/hilog_lite/interfaces/native/innerkits", + "//third_party/bounds_checking_function/include", + ] + + deps = [ + "//base/hiviewdfx/hilog_lite/frameworks/featured:hilog_shared", + "//third_party/bounds_checking_function:libsec_shared", + ] + + defines = [ + "_GNU_SOURCE", + "OHOS_ARCH_LITE", + ] + configs -= [ "//build/lite/config:language_cpp" ] + cflags_cc = [ + "-fPIC", + "-std=c++17", + "-Wall", + ] + ldflags = [ + "-fPIC", + "-Wl,-E", + ] + } +} else { + ohos_shared_library("dhcp_manager_service") { + install_enable = true + sources = local_base_sources + + include_dirs = local_base_include_dirs + include_dirs += [ + "//commonlibrary/c_utils/base/include", + "//foundation/communication/ipc/interfaces/innerkits/ipc_core/include", + ] + + cflags_cc = [ + "-std=c++17", + "-Wall", + ] + + external_deps = [ + "ability_base:want", + "bundle_framework:appexecfwk_base", + "c_utils:utils", + "common_event_service:cesfwk_innerkits", + "eventhandler:libeventhandler", + "hiviewdfx_hilog_native:libhilog", + ] + ldflags = [ + "-fPIC", + "-Wl,-E", + ] + + part_name = "dhcp" + subsystem_name = "communication" + } +} diff --git a/services/wifi_standard/wifi_framework/dhcp_manage/mgr_service/include/dhcp_client_service_impl.h b/dhcp/services/mgr_service/include/dhcp_client_service_impl.h similarity index 86% rename from services/wifi_standard/wifi_framework/dhcp_manage/mgr_service/include/dhcp_client_service_impl.h rename to dhcp/services/mgr_service/include/dhcp_client_service_impl.h index 045e269362fa33b177ef253df8bc6377c8840f8c..a7eee8c5ad7c2f8f311d6f720d70291ca81e210f 100644 --- a/services/wifi_standard/wifi_framework/dhcp_manage/mgr_service/include/dhcp_client_service_impl.h +++ b/dhcp/services/mgr_service/include/dhcp_client_service_impl.h @@ -1,5 +1,5 @@ /* - * Copyright (C) 2021 Huawei Device Co., Ltd. + * Copyright (C) 2021-2022 Huawei Device Co., Ltd. * 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 @@ -84,7 +84,7 @@ public: * @Description : Obtain the dhcp result of specified interface asynchronously. * * @param ifname - interface name, eg:wlan0 [in] - * @param dhcp - dhcp result notify [in] + * @param pResultNotify - dhcp result notify [in] * @param timeouts - timeout interval [in] * @Return : success - DHCP_OPT_SUCCESS, failed - others. */ @@ -190,6 +190,23 @@ private: * */ void RunDhcpResultHandleThreadFunc(); +#ifdef OHOS_ARCH_LITE + /** + * @Description : Dhcp recv msg threads execution function. + * + * @param ifname - interface name, eg:wlan0 [in] + */ + void RunDhcpRecvMsgThreadFunc(const std::string& ifname); + + /** + * @Description : Handle dhcp packet info. + * + * @param ifname - interface name, eg:wlan0 [in] + * @param packetResult - dhcp packet result [in] + * @param success - get success is true, get failed is false [in] + */ + void DhcpPacketInfoHandle(const std::string& ifname, struct DhcpPacketResult &packetResult, bool success = true); +#endif /** * @Description : Fork child process function for start or stop dhcp process. * @@ -222,11 +239,27 @@ private: */ int UnsubscribeDhcpEvent(const std::string &strAction); + /** + * @Description : release result notify memory. + * + */ + void ReleaseResultNotifyMemory(); + + /** + * @Description : Unsubscribe all dhcp event. + * + * @Return : success - DHCP_OPT_SUCCESS, failed - others. + */ + int UnsubscribeAllDhcpEvent(); + private: std::mutex mResultNotifyMutex; bool isExitDhcpResultHandleThread; std::thread *pDhcpResultHandleThread; - +#ifdef OHOS_ARCH_LITE + std::mutex mRecvMsgThreadMutex; + std::map m_mapDhcpRecvMsgThread; +#endif std::map> m_mapDhcpResultNotify; std::map> m_mapEventSubscriber; }; diff --git a/services/wifi_standard/wifi_framework/dhcp_manage/mgr_service/include/dhcp_event_subscriber.h b/dhcp/services/mgr_service/include/dhcp_event_subscriber.h similarity index 83% rename from services/wifi_standard/wifi_framework/dhcp_manage/mgr_service/include/dhcp_event_subscriber.h rename to dhcp/services/mgr_service/include/dhcp_event_subscriber.h index 56f614513a25dd9ce60b79886a5b7f946b637d0a..9ddd5a5779a1ebc34cf64e742a1436f3b99624d1 100644 --- a/services/wifi_standard/wifi_framework/dhcp_manage/mgr_service/include/dhcp_event_subscriber.h +++ b/dhcp/services/mgr_service/include/dhcp_event_subscriber.h @@ -1,5 +1,5 @@ /* - * Copyright (C) 2021 Huawei Device Co., Ltd. + * Copyright (C) 2021-2022 Huawei Device Co., Ltd. * 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 @@ -17,6 +17,18 @@ #define OHOS_DHCP_EVENT_SUBSCRIBER_H #include +#ifdef OHOS_ARCH_LITE +namespace OHOS { +namespace Wifi { +class DhcpEventSubscriber { +public: + explicit DhcpEventSubscriber() + {} + + ~DhcpEventSubscriber() + {} +}; +#else #include "common_event_subscriber.h" #include "common_event_data.h" @@ -35,6 +47,7 @@ public: private: std::mutex onReceivedLock_; }; +#endif } // namespace Wifi } // namespace OHOS #endif \ No newline at end of file diff --git a/services/wifi_standard/wifi_framework/dhcp_manage/mgr_service/include/dhcp_func.h b/dhcp/services/mgr_service/include/dhcp_func.h similarity index 93% rename from services/wifi_standard/wifi_framework/dhcp_manage/mgr_service/include/dhcp_func.h rename to dhcp/services/mgr_service/include/dhcp_func.h index ceead5d5644a048bf4cf6e00a1f08c222145f665..1302844cf4c11e9c1e427d76835d032b9d775623 100644 --- a/services/wifi_standard/wifi_framework/dhcp_manage/mgr_service/include/dhcp_func.h +++ b/dhcp/services/mgr_service/include/dhcp_func.h @@ -1,5 +1,5 @@ /* - * Copyright (C) 2021 Huawei Device Co., Ltd. + * Copyright (C) 2021-2022 Huawei Device Co., Ltd. * 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 @@ -26,11 +26,12 @@ #include "dhcp_define.h" +#ifndef OHOS_ARCH_LITE #include "common_event_subscriber.h" #include "common_event.h" #include "common_event_data.h" #include "common_event_manager.h" - +#endif namespace OHOS { namespace Wifi { @@ -62,13 +63,16 @@ public: static int CreateDirs(const std::string dirs, int mode = DIR_DEFAULT_MODE); static bool SplitString( const std::string src, const std::string delim, const int count, std::vector &splits); - +#ifdef OHOS_ARCH_LITE + static int GetDhcpPacketResult(const std::string& filename, struct DhcpPacketResult &result); +#else static bool SubscribeDhcpCommonEvent( const std::shared_ptr &subscriber); static bool UnsubscribeDhcpCommonEvent( const std::shared_ptr &subscriber); static bool PublishDhcpEvent(const std::string action, const int code, const std::string data); +#endif }; } // namespace Wifi } // namespace OHOS diff --git a/services/wifi_standard/wifi_framework/dhcp_manage/mgr_service/include/dhcp_server_service.h b/dhcp/services/mgr_service/include/dhcp_server_service.h similarity index 97% rename from services/wifi_standard/wifi_framework/dhcp_manage/mgr_service/include/dhcp_server_service.h rename to dhcp/services/mgr_service/include/dhcp_server_service.h index b0a53fdf5c603e3d2fdd0f6ee16727143e70c019..48ac2b2b13f9902260853fea589f6b05e63f5f59 100644 --- a/services/wifi_standard/wifi_framework/dhcp_manage/mgr_service/include/dhcp_server_service.h +++ b/dhcp/services/mgr_service/include/dhcp_server_service.h @@ -1,5 +1,5 @@ /* - * Copyright (C) 2021 Huawei Device Co., Ltd. + * Copyright (C) 2021-2022 Huawei Device Co., Ltd. * 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 @@ -186,6 +186,13 @@ public: */ int CreateDefaultConfigFile(const std::string strFile); + /** + * @Description : Stop dhcp server on exit + * + * @Return : success - DHCP_OPT_SUCCESS, failed - others. + */ + int StopDhcpServerOnExit(); + private: /** * @Description : Fork parent process function. diff --git a/services/wifi_standard/wifi_framework/dhcp_manage/mgr_service/include/dhcp_service.h b/dhcp/services/mgr_service/include/dhcp_service.h similarity index 95% rename from services/wifi_standard/wifi_framework/dhcp_manage/mgr_service/include/dhcp_service.h rename to dhcp/services/mgr_service/include/dhcp_service.h index d7d0b04ca41ecc7bcb958b8abcdf318c10166ab9..bd7421294fc827c3548aded26c8f8d7a0b0f7717 100644 --- a/services/wifi_standard/wifi_framework/dhcp_manage/mgr_service/include/dhcp_service.h +++ b/dhcp/services/mgr_service/include/dhcp_service.h @@ -1,5 +1,5 @@ /* - * Copyright (C) 2021 Huawei Device Co., Ltd. + * Copyright (C) 2021-2022 Huawei Device Co., Ltd. * 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 @@ -16,11 +16,14 @@ #ifndef OHOS_DHCP_SERVICE_H #define OHOS_DHCP_SERVICE_H -#include "i_dhcp_service.h" +#include +#include +#include #include "dhcp_define.h" -#include "dhcp_client_service_impl.h" -#include "dhcp_server_service.h" - +#include "i_dhcp_client_service.h" +#include "i_dhcp_result_notify.h" +#include "i_dhcp_server_service.h" +#include "i_dhcp_service.h" namespace OHOS { namespace Wifi { @@ -178,6 +181,7 @@ public: private: int InitServerService(void); + bool CheckIfaceValid(const std::string& ifname); private: std::unique_ptr m_pClientService; @@ -185,4 +189,4 @@ private: }; } // namespace Wifi } // namespace OHOS -#endif \ No newline at end of file +#endif diff --git a/services/wifi_standard/wifi_framework/dhcp_manage/mgr_service/src/dhcp_client_service_impl.cpp b/dhcp/services/mgr_service/src/dhcp_client_service_impl.cpp similarity index 77% rename from services/wifi_standard/wifi_framework/dhcp_manage/mgr_service/src/dhcp_client_service_impl.cpp rename to dhcp/services/mgr_service/src/dhcp_client_service_impl.cpp index 8a89ed5f64aaa74ca73b4be82889b744260d87dc..7877e08adb37f716c8e0c9faa3c841efd8ea8dbc 100644 --- a/services/wifi_standard/wifi_framework/dhcp_manage/mgr_service/src/dhcp_client_service_impl.cpp +++ b/dhcp/services/mgr_service/src/dhcp_client_service_impl.cpp @@ -1,5 +1,5 @@ /* - * Copyright (C) 2021 Huawei Device Co., Ltd. + * Copyright (C) 2021-2022 Huawei Device Co., Ltd. * 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 @@ -18,6 +18,7 @@ #include #include #include +#include #include "dhcp_func.h" #include "securec.h" @@ -34,10 +35,14 @@ DhcpClientServiceImpl::DhcpClientServiceImpl() { isExitDhcpResultHandleThread = false; pDhcpResultHandleThread = nullptr; - - m_mapDhcpResultNotify.clear(); +#ifdef OHOS_ARCH_LITE + m_mapDhcpRecvMsgThread.clear(); +#endif + if (!m_mapDhcpResultNotify.empty()) { + ReleaseResultNotifyMemory(); + m_mapDhcpResultNotify.clear(); + } m_mapEventSubscriber.clear(); - InitDhcpMgrThread(); DhcpFunc::CreateDirs(DHCP_WORK_DIR); } @@ -46,20 +51,27 @@ DhcpClientServiceImpl::~DhcpClientServiceImpl() { if (!m_mapEventSubscriber.empty()) { WIFI_LOGE("DhcpClientServiceImpl destructor mapEventSubscriber is not empty!"); - auto iterSubscriber = m_mapEventSubscriber.begin(); - while (iterSubscriber != m_mapEventSubscriber.end()) { - if (UnsubscribeDhcpEvent(iterSubscriber->first) != DHCP_OPT_SUCCESS) { - WIFI_LOGE("DhcpClientServiceImpl destructor %{public}s failed!", (iterSubscriber->first).c_str()); - } else { - WIFI_LOGW("DhcpClientServiceImpl destructor %{public}s success", (iterSubscriber->first).c_str()); - } + if (UnsubscribeAllDhcpEvent() != DHCP_OPT_SUCCESS) { + WIFI_LOGE("DhcpClientServiceImpl unregister all dhcp event failed!"); } - m_mapEventSubscriber.clear(); } ExitDhcpMgrThread(); } +void DhcpClientServiceImpl::ReleaseResultNotifyMemory() +{ + for (auto& item : m_mapDhcpResultNotify) { + auto& secondItem = item.second; + for (auto& each : secondItem) { + if (each != nullptr) { + delete each; + each = nullptr; + } + } + } +} + int DhcpClientServiceImpl::InitDhcpMgrThread() { pDhcpResultHandleThread = new std::thread(&DhcpClientServiceImpl::RunDhcpResultHandleThreadFunc, this); @@ -83,8 +95,19 @@ void DhcpClientServiceImpl::ExitDhcpMgrThread() if (!m_mapDhcpResultNotify.empty()) { WIFI_LOGE("ExitDhcpMgrThread() error, m_mapDhcpResultNotify is not empty!"); + ReleaseResultNotifyMemory(); m_mapDhcpResultNotify.clear(); } +#ifdef OHOS_ARCH_LITE + if (!m_mapDhcpRecvMsgThread.empty()) { + WIFI_LOGE("ExitDhcpMgrThread() error, m_mapDhcpRecvMsgThread is not empty!"); + for (auto &mapThread : m_mapDhcpRecvMsgThread) { + int nStatus = GetDhcpStatus(mapThread.first); + WIFI_LOGE("ExitDhcpMgrThread() ifname:%{public}s, status:%{public}d!", + (mapThread.first).c_str(), nStatus); + } + } +#endif } void DhcpClientServiceImpl::CheckTimeout() @@ -113,6 +136,7 @@ void DhcpClientServiceImpl::CheckTimeout() curTime); (*iterReq)->pResultNotify->OnFailed(DHCP_OPT_TIMEOUT, ifname, "get dhcp result timeout!"); delete *iterReq; + *iterReq = nullptr; iterReq = itemNotify.second.erase(iterReq); } else { ++iterReq; @@ -170,6 +194,7 @@ void DhcpClientServiceImpl::DhcpResultHandle(uint32_t &second) (*iterReq)->pResultNotify->OnFailed(DHCP_OPT_FAILED, ifname, "get dhcp result failed!"); } delete *iterReq; + *iterReq = nullptr; iterReq = iterNotify->second.erase(iterReq); } @@ -186,12 +211,17 @@ int DhcpClientServiceImpl::SubscribeDhcpEvent(const std::string &strAction) WIFI_LOGE("SubscribeDhcpEvent error, strAction is empty!"); return DHCP_OPT_ERROR; } +#ifndef OHOS_ARCH_LITE auto iterSubscriber = m_mapEventSubscriber.find(strAction); if (iterSubscriber == m_mapEventSubscriber.end()) { EventFwk::MatchingSkills matchingSkills; matchingSkills.AddEvent(strAction); EventFwk::CommonEventSubscribeInfo subInfo(matchingSkills); auto dhcpSubscriber = std::make_shared(subInfo); + if (dhcpSubscriber == nullptr) { + WIFI_LOGE("SubscribeDhcpEvent error, dhcpSubscriber is nullptr!"); + return DHCP_OPT_FAILED; + } m_mapEventSubscriber.emplace(std::make_pair(strAction, dhcpSubscriber)); } if (m_mapEventSubscriber[strAction] == nullptr) { @@ -203,6 +233,7 @@ int DhcpClientServiceImpl::SubscribeDhcpEvent(const std::string &strAction) return DHCP_OPT_FAILED; } WIFI_LOGI("SubscribeDhcpEvent %{public}s success", strAction.c_str()); +#endif return DHCP_OPT_SUCCESS; } @@ -222,15 +253,34 @@ int DhcpClientServiceImpl::UnsubscribeDhcpEvent(const std::string &strAction) WIFI_LOGE("UnsubscribeDhcpEvent mapEventSubscriber %{public}s nullptr!", strAction.c_str()); return DHCP_OPT_FAILED; } +#ifndef OHOS_ARCH_LITE if (!DhcpFunc::UnsubscribeDhcpCommonEvent(m_mapEventSubscriber[strAction])) { WIFI_LOGE("UnsubscribeDhcpEvent UnsubscribeDhcpCommonEvent %{public}s failed!", strAction.c_str()); return DHCP_OPT_FAILED; } +#endif m_mapEventSubscriber.erase(iterSubscriber); WIFI_LOGI("UnsubscribeDhcpEvent %{public}s success", strAction.c_str()); return DHCP_OPT_SUCCESS; } +int DhcpClientServiceImpl::UnsubscribeAllDhcpEvent() +{ +#ifndef OHOS_ARCH_LITE + for (auto& e : m_mapEventSubscriber) { + if (e.second != nullptr) { + if (!DhcpFunc::UnsubscribeDhcpCommonEvent(e.second)) { + WIFI_LOGE("UnsubscribeDhcpEvent UnsubscribeDhcpCommonEvent %{public}s failed!", e.first.c_str()); + return DHCP_OPT_FAILED; + } + } + } +#endif + m_mapEventSubscriber.clear(); + WIFI_LOGI("UnsubscribeDhcpEvent all dhcp event success!"); + return DHCP_OPT_SUCCESS; +} + void DhcpClientServiceImpl::RunDhcpResultHandleThreadFunc() { for (; ;) { @@ -247,6 +297,114 @@ void DhcpClientServiceImpl::RunDhcpResultHandleThreadFunc() WIFI_LOGI("DhcpClientServiceImpl::RunDhcpResultHandleThreadFunc() end!"); } +#ifdef OHOS_ARCH_LITE +void DhcpClientServiceImpl::RunDhcpRecvMsgThreadFunc(const std::string &ifname) +{ + if (ifname.empty()) { + WIFI_LOGE("DhcpClientServiceImpl::RunDhcpRecvMsgThreadFunc() error, ifname is empty!"); + return; + } + + struct DhcpPacketResult result; + std::string strResultFile = DHCP_WORK_DIR + ifname + DHCP_RESULT_FILETYPE; + for (; ;) { + /* Check break condition. */ + auto iter = this->m_mapDhcpInfo.find(ifname); + if ((iter != this->m_mapDhcpInfo.end()) && ((iter->second).clientRunStatus) != 1) { + WIFI_LOGI("RunDhcpRecvMsgThreadFunc() Status != 1, need break, ifname:%{public}s.", ifname.c_str()); + break; + } + + /* Check dhcp result file is or not exist. */ + if (!DhcpFunc::IsExistFile(strResultFile)) { + usleep(SLEEP_TIME_200_MS); + continue; + } + + if (memset_s(&result, sizeof(result), 0, sizeof(result)) != EOK) { + return; + } + int nGetRet = DhcpFunc::GetDhcpPacketResult(strResultFile, result); + if (nGetRet == DHCP_OPT_SUCCESS) { + /* Get success, add or reload dhcp packet info. */ + this->DhcpPacketInfoHandle(ifname, result); + usleep(SLEEP_TIME_500_MS); + } else if (nGetRet == DHCP_OPT_FAILED) { + /* Get failed, print dhcp packet info. */ + this->DhcpPacketInfoHandle(ifname, result, false); + usleep(SLEEP_TIME_500_MS); + } else { + /* Get null, continue get dhcp packet info. */ + WIFI_LOGI("RunDhcpRecvMsgThreadFunc() GetDhcpPacketResult NULL, ifname:%{public}s.", ifname.c_str()); + usleep(SLEEP_TIME_200_MS); + } + + continue; + } +} + +void DhcpClientServiceImpl::DhcpPacketInfoHandle( + const std::string &ifname, struct DhcpPacketResult &packetResult, bool success) +{ + if (ifname.empty()) { + WIFI_LOGE("DhcpClientServiceImpl::DhcpPacketInfoHandle() error, ifname is empty!"); + return; + } + + DhcpResult result; + auto iterResult = m_mapDhcpResult.find(ifname); + if (!success) { + /* get failed */ + if (iterResult != m_mapDhcpResult.end()) { + iterResult->second = result; + } else { + m_mapDhcpResult.emplace(std::make_pair(ifname, result)); + } + return; + } + + /* Check dhcp result add time */ + if ((iterResult != m_mapDhcpResult.end()) && ((iterResult->second).uAddTime == packetResult.uAddTime)) { + return; + } + WIFI_LOGI("DhcpPacketInfoHandle() DhcpResult %{public}s old %{public}u no equal new %{public}u, need update...", + ifname.c_str(), (iterResult->second).uAddTime, packetResult.uAddTime); + + /* get success, add or reload dhcp packet info */ + auto iterInfo = m_mapDhcpInfo.find(ifname); + if (iterInfo != m_mapDhcpInfo.end()) { + m_mapDhcpInfo[ifname].serverIp = packetResult.strOptServerId; + WIFI_LOGI("DhcpPacketInfoHandle() m_mapDhcpInfo find ifname:%{public}s.", ifname.c_str()); + } + + result.iptype = 0; + result.isOptSuc = true; + result.strYourCli = packetResult.strYiaddr; + result.strServer = packetResult.strOptServerId; + result.strSubnet = packetResult.strOptSubnet; + result.strDns1 = packetResult.strOptDns1; + result.strDns2 = packetResult.strOptDns2; + result.strRouter1 = packetResult.strOptRouter1; + result.strRouter2 = packetResult.strOptRouter2; + result.strVendor = packetResult.strOptVendor; + result.uLeaseTime = packetResult.uOptLeasetime; + result.uAddTime = packetResult.uAddTime; + result.uGetTime = (uint32_t)time(NULL); + + if (iterResult != m_mapDhcpResult.end()) { + iterResult->second = result; + } else { + m_mapDhcpResult.emplace(std::make_pair(ifname, result)); + } + WIFI_LOGI("DhcpPacketInfoHandle %{public}s, type:%{public}d, opt:%{public}d, cli:%{private}s, server:%{private}s, " + "strSubnet:%{private}s, Dns1:%{private}s, Dns2:%{private}s, strRouter1:%{private}s, strRouter2:%{private}s, " + "strVendor:%{public}s, uLeaseTime:%{public}u, uAddTime:%{public}u, uGetTime:%{public}u.", + ifname.c_str(), result.iptype, result.isOptSuc, result.strYourCli.c_str(), result.strServer.c_str(), + result.strSubnet.c_str(), result.strDns1.c_str(), result.strDns2.c_str(), result.strRouter1.c_str(), + result.strRouter2.c_str(), result.strVendor.c_str(), result.uLeaseTime, result.uAddTime, result.uGetTime); +} +#endif + int DhcpClientServiceImpl::ForkExecChildProcess(const std::string &ifname, bool bIpv6, bool bStart) { if (bIpv6) { @@ -283,6 +441,21 @@ int DhcpClientServiceImpl::ForkExecParentProcess(const std::string &ifname, bool { std::string strAction = OHOS::Wifi::COMMON_EVENT_DHCP_GET_IPV4 + "." + ifname; if (bStart) { +#ifdef OHOS_ARCH_LITE + /* check and new receive dhcp packet msg thread */ + std::unique_lock lock(mRecvMsgThreadMutex); + auto iterRecvMsgThread = m_mapDhcpRecvMsgThread.find(ifname); + if (iterRecvMsgThread != m_mapDhcpRecvMsgThread.end()) { + WIFI_LOGE("ForkExecParentProcess() RecvMsgThread exist ifname:%{public}s, need erase!", ifname.c_str()); + return DHCP_OPT_FAILED; + } + std::thread *pThread = new std::thread(&DhcpClientServiceImpl::RunDhcpRecvMsgThreadFunc, this, ifname); + if (pThread == nullptr) { + WIFI_LOGE("ForkExecParentProcess() init pThread failed, ifname:%{public}s.", ifname.c_str()); + return DHCP_OPT_FAILED; + } + m_mapDhcpRecvMsgThread.emplace(std::make_pair(ifname, pThread)); +#endif /* normal started, update dhcp client service running status */ auto iter = DhcpClientServiceImpl::m_mapDhcpInfo.find(ifname); if (iter != DhcpClientServiceImpl::m_mapDhcpInfo.end()) { @@ -301,6 +474,10 @@ int DhcpClientServiceImpl::ForkExecParentProcess(const std::string &ifname, bool return DHCP_OPT_FAILED; } } else { + /* Unsubscribe dhcp event. */ + if (UnsubscribeDhcpEvent(strAction) != DHCP_OPT_SUCCESS) { + WIFI_LOGI("ForkExecParentProcess() UnsubscribeDhcpEvent ifname:%{public}s failed.", ifname.c_str()); + } auto iter = DhcpClientServiceImpl::m_mapDhcpInfo.find(ifname); if (iter != DhcpClientServiceImpl::m_mapDhcpInfo.end()) { /* not start */ @@ -312,10 +489,22 @@ int DhcpClientServiceImpl::ForkExecParentProcess(const std::string &ifname, bool DhcpClientServiceImpl::m_mapDhcpResult.erase(iterResult); WIFI_LOGI("ForkExecParentProcess() m_mapDhcpResult erase ifname:%{public}s success.", ifname.c_str()); } - } - /* Unsubscribe dhcp event. */ - if (UnsubscribeDhcpEvent(strAction) != DHCP_OPT_SUCCESS) { - return DHCP_OPT_FAILED; +#ifdef OHOS_ARCH_LITE + std::unique_lock lock(mRecvMsgThreadMutex); + auto iterRecvMsgThreadMap = m_mapDhcpRecvMsgThread.find(ifname); + if (iterRecvMsgThreadMap == m_mapDhcpRecvMsgThread.end()) { + WIFI_LOGI("ForkExecParentProcess() RecvMsgThread already del ifname:%{public}s.", ifname.c_str()); + return DHCP_OPT_SUCCESS; + } + if (iterRecvMsgThreadMap->second != nullptr) { + iterRecvMsgThreadMap->second->join(); + delete iterRecvMsgThreadMap->second; + iterRecvMsgThreadMap->second = nullptr; + WIFI_LOGI("ForkExecParentProcess() destroy RecvThread success, ifname:%{public}s.", ifname.c_str()); + } + WIFI_LOGI("ForkExecParentProcess() m_mapDhcpRecvMsgThread erase ifname:%{public}s.", ifname.c_str()); + m_mapDhcpRecvMsgThread.erase(iterRecvMsgThreadMap); +#endif } } return DHCP_OPT_SUCCESS; @@ -398,8 +587,11 @@ int DhcpClientServiceImpl::GetSuccessIpv4Result(const std::vector & ifname.c_str(), (iter->second).uAddTime, result.uAddTime); return DHCP_OPT_SUCCESS; } - WIFI_LOGI("GetSuccessIpv4Result() DhcpResult %{public}s old %{public}u no equal new %{public}u, need update...", - ifname.c_str(), (iter->second).uAddTime, result.uAddTime); + + if (iter != DhcpClientServiceImpl::m_mapDhcpResult.end()) { + WIFI_LOGI("GetSuccessIpv4Result() DhcpResult %{public}s old %{public}u no equal new %{public}u, need update...", + ifname.c_str(), (iter->second).uAddTime, result.uAddTime); + } /* Reload dhcp packet info. */ auto iterInfo = DhcpClientServiceImpl::m_mapDhcpInfo.find(ifname); @@ -656,6 +848,10 @@ int DhcpClientServiceImpl::GetDhcpResult(const std::string &ifname, IDhcpResultN } DhcpResultReq *pResultReq = new DhcpResultReq; + if (pResultReq == nullptr) { + WIFI_LOGE("GetDhcpResult() new failed! ifname:%{public}s.", ifname.c_str()); + return DHCP_OPT_FAILED; + } pResultReq->timeouts = timeouts; pResultReq->getTimestamp = (uint32_t)time(NULL); pResultReq->pResultNotify = pResultNotify; diff --git a/services/wifi_standard/wifi_framework/dhcp_manage/mgr_service/src/dhcp_event_subscriber.cpp b/dhcp/services/mgr_service/src/dhcp_event_subscriber.cpp similarity index 91% rename from services/wifi_standard/wifi_framework/dhcp_manage/mgr_service/src/dhcp_event_subscriber.cpp rename to dhcp/services/mgr_service/src/dhcp_event_subscriber.cpp index ac1d5859e4e1372439fc0bf8e3f143ef9800d7a1..c191546a24157c908e9b5b8b761435d6a2289555 100644 --- a/services/wifi_standard/wifi_framework/dhcp_manage/mgr_service/src/dhcp_event_subscriber.cpp +++ b/dhcp/services/mgr_service/src/dhcp_event_subscriber.cpp @@ -1,5 +1,5 @@ /* - * Copyright (C) 2021 Huawei Device Co., Ltd. + * Copyright (C) 2021-2022 Huawei Device Co., Ltd. * 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 @@ -15,6 +15,10 @@ #include "dhcp_event_subscriber.h" +#ifdef OHOS_ARCH_LITE +namespace OHOS { +namespace Wifi { +#else #include "wifi_logger.h" #include "dhcp_client_service_impl.h" @@ -35,5 +39,6 @@ void DhcpEventSubscriber::OnReceiveEvent(const OHOS::EventFwk::CommonEventData & return; } } +#endif } // namespace Wifi } // namespace OHOS \ No newline at end of file diff --git a/services/wifi_standard/wifi_framework/dhcp_manage/mgr_service/src/dhcp_func.cpp b/dhcp/services/mgr_service/src/dhcp_func.cpp similarity index 91% rename from services/wifi_standard/wifi_framework/dhcp_manage/mgr_service/src/dhcp_func.cpp rename to dhcp/services/mgr_service/src/dhcp_func.cpp index d57c48e19a67194e7bfbef55f2dd0bdded2f73db..93a35e0d92b5f207f13ca3b9f8a4a37c2f02539c 100644 --- a/services/wifi_standard/wifi_framework/dhcp_manage/mgr_service/src/dhcp_func.cpp +++ b/dhcp/services/mgr_service/src/dhcp_func.cpp @@ -1,5 +1,5 @@ /* - * Copyright (C) 2021 Huawei Device Co., Ltd. + * Copyright (C) 2021-2022 Huawei Device Co., Ltd. * 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 @@ -20,6 +20,7 @@ #include #include #include +#include #include "securec.h" #include "wifi_logger.h" @@ -475,6 +476,54 @@ int DhcpFunc::FormatString(struct DhcpPacketResult &result) return 0; } +#ifdef OHOS_ARCH_LITE +int DhcpFunc::GetDhcpPacketResult(const std::string& filename, struct DhcpPacketResult &result) +{ + FILE *pFile = fopen(filename.c_str(), "r"); + if (pFile == nullptr) { + WIFI_LOGE("GetDhcpPacketResult() fopen %{public}s fail, err:%{public}s!", filename.c_str(), strerror(errno)); + return DHCP_OPT_FAILED; + } + + char strIpFlag[DHCP_NUM_EIGHT]; + if (memset_s(strIpFlag, sizeof(strIpFlag), 0, sizeof(strIpFlag)) != EOK) { + fclose(pFile); + return DHCP_OPT_FAILED; + } + /* Format: IpFlag AddTime cliIp servIp subnet dns1 dns2 router1 router2 vendor lease */ + int nRes = fscanf_s(pFile, "%s %u %s %s %s %s %s %s %s %s %u\n", strIpFlag, DHCP_NUM_EIGHT, &result.uAddTime, + result.strYiaddr, INET_ADDRSTRLEN, result.strOptServerId, INET_ADDRSTRLEN, result.strOptSubnet, INET_ADDRSTRLEN, + result.strOptDns1, INET_ADDRSTRLEN, result.strOptDns2, INET_ADDRSTRLEN, result.strOptRouter1, INET_ADDRSTRLEN, + result.strOptRouter2, INET_ADDRSTRLEN, result.strOptVendor, DHCP_FILE_MAX_BYTES, &result.uOptLeasetime); + if (nRes == EOF) { + WIFI_LOGE("GetDhcpPacketResult() fscanf %{public}s err:%{public}s!", filename.c_str(), strerror(errno)); + fclose(pFile); + return DHCP_OPT_FAILED; + } else if (nRes == 0) { + WIFI_LOGW("GetDhcpPacketResult() fscanf file:%{public}s nRes:0 NULL!", filename.c_str()); + fclose(pFile); + return DHCP_OPT_NULL; + } else if (nRes != EVENT_DATA_NUM) { + WIFI_LOGE("GetDhcpPacketResult() fscanf file:%{public}s nRes:%{public}d ERROR!", filename.c_str(), nRes); + fclose(pFile); + return DHCP_OPT_FAILED; + } + + if (fclose(pFile) != 0) { + WIFI_LOGE("GetDhcpPacketResult() fclose file:%{public}s failed!", filename.c_str()); + return DHCP_OPT_FAILED; + } + + /* Format dhcp packet result */ + if (FormatString(result) != 0) { + WIFI_LOGE("GetDhcpPacketResult() file:%{public}s failed, FormatString result error!", filename.c_str()); + return DHCP_OPT_FAILED; + } + + return DHCP_OPT_SUCCESS; +} +#endif + int DhcpFunc::InitPidfile(const std::string& piddir, const std::string& pidfile) { if (piddir.empty() || pidfile.empty()) { @@ -651,6 +700,7 @@ bool DhcpFunc::SplitString( return true; } +#ifndef OHOS_ARCH_LITE bool DhcpFunc::SubscribeDhcpCommonEvent( const std::shared_ptr &subscriber) { @@ -680,5 +730,6 @@ bool DhcpFunc::PublishDhcpEvent(const std::string action, const int code, const action.c_str(), code, data.c_str()); return DHCP_OPT_SUCCESS; } +#endif } // namespace Wifi } // namespace OHOS \ No newline at end of file diff --git a/services/wifi_standard/wifi_framework/dhcp_manage/mgr_service/src/dhcp_server_service.cpp b/dhcp/services/mgr_service/src/dhcp_server_service.cpp similarity index 96% rename from services/wifi_standard/wifi_framework/dhcp_manage/mgr_service/src/dhcp_server_service.cpp rename to dhcp/services/mgr_service/src/dhcp_server_service.cpp index a825fcd60581c8acedbf7f22a204e9f36b43f60b..4d85f421582adabaf2775124b1e96d6bd7b0fb1a 100644 --- a/services/wifi_standard/wifi_framework/dhcp_manage/mgr_service/src/dhcp_server_service.cpp +++ b/dhcp/services/mgr_service/src/dhcp_server_service.cpp @@ -1,5 +1,5 @@ /* - * Copyright (C) 2021 Huawei Device Co., Ltd. + * Copyright (C) 2021-2022 Huawei Device Co., Ltd. * 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 @@ -40,19 +40,8 @@ DhcpServerService::DhcpServerService() DhcpServerService::~DhcpServerService() { - auto iterInterfaces = m_setInterfaces.begin(); - while (iterInterfaces != m_setInterfaces.end()) { - if (GetDhcpServerPid(*iterInterfaces) == 0) { - continue; - } - if (StopDhcpServer(*iterInterfaces) != DHCP_OPT_SUCCESS) { - WIFI_LOGE("Destructor stop dhcp server service failed, ifname:%{public}s", (*iterInterfaces).c_str()); - } else { - WIFI_LOGW("Destructor stop dhcp server service success, ifname:%{public}s", (*iterInterfaces).c_str()); - } - } - m_setInterfaces.clear(); - + WIFI_LOGI("StartDhcpServer: ~DhcpServerService"); + StopDhcpServerOnExit(); ExitDhcpMgrThreadFunc(); } @@ -136,6 +125,35 @@ int DhcpServerService::StopDhcpServer(const std::string &ifname) return DHCP_OPT_SUCCESS; } +int DhcpServerService::StopDhcpServerOnExit() +{ + for (auto& each: m_setInterfaces) { + if (each.empty()) { + WIFI_LOGE("StopDhcpServer() on exit error, ifname is empty!"); + continue; + } + + pid_t pidServer = GetDhcpServerPid(each); + if (pidServer == 0) { + WIFI_LOGI("StopDhcpServer() on exit %{public}s already stop.", each.c_str()); + continue; + } + auto iterRangeMap = m_mapInfDhcpRange.find(each); + if (iterRangeMap != m_mapInfDhcpRange.end()) { + m_mapInfDhcpRange.erase(iterRangeMap); + } + if (RemoveAllDhcpRange(each) != DHCP_OPT_SUCCESS) { + WIFI_LOGE("StopDhcpServer() on exit, RemoveAllDhcpRange %{public}s error.", each.c_str()); + } + if (StopServer(pidServer) != DHCP_OPT_SUCCESS) { + WIFI_LOGE("StopDhcpServer() on exit error, StopServer %{public}s already stop.", each.c_str()); + } + SetDhcpServerInfo(each, SERVICE_STATUS_STOP, 0); + } + m_setInterfaces.clear(); + return DHCP_OPT_SUCCESS; +} + int DhcpServerService::GetServerStatus() { return 0; @@ -296,6 +314,7 @@ int DhcpServerService::SetDhcpRange(const std::string &ifname, const std::string WIFI_LOGE("SetDhcpRange tag m_mapTagDhcpRange no find tagName:%{public}s.", tagName.c_str()); return DHCP_OPT_FAILED; } + int nSize = (int)iterTag->second.size(); if (nSize != 1) { WIFI_LOGE("SetDhcpRange tag %{public}s range size:%{public}d error.", tagName.c_str(), nSize); diff --git a/services/wifi_standard/wifi_framework/dhcp_manage/mgr_service/src/dhcp_service.cpp b/dhcp/services/mgr_service/src/dhcp_service.cpp similarity index 86% rename from services/wifi_standard/wifi_framework/dhcp_manage/mgr_service/src/dhcp_service.cpp rename to dhcp/services/mgr_service/src/dhcp_service.cpp index e93f707b4c61007605efa45ee943e0ac345e4e5c..61727fc2ba46df3db0c438c635a5a1135b635478 100644 --- a/services/wifi_standard/wifi_framework/dhcp_manage/mgr_service/src/dhcp_service.cpp +++ b/dhcp/services/mgr_service/src/dhcp_service.cpp @@ -1,5 +1,5 @@ /* - * Copyright (C) 2021 Huawei Device Co., Ltd. + * Copyright (C) 2021-2022 Huawei Device Co., Ltd. * 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 @@ -14,6 +14,11 @@ */ #include "dhcp_service.h" +#include +#include +#include +#include "dhcp_client_service_impl.h" +#include "dhcp_server_service.h" #include "wifi_logger.h" DEFINE_WIFILOG_DHCP_LABEL("DhcpService"); @@ -36,6 +41,9 @@ DhcpService::~DhcpService() int DhcpService::StartDhcpClient(const std::string& ifname, bool bIpv6) { + if (!CheckIfaceValid(ifname)) { + return DHCP_OPT_FAILED; + } if (m_pClientService == nullptr) { m_pClientService = std::make_unique(); if (m_pClientService == nullptr) { @@ -49,6 +57,9 @@ int DhcpService::StartDhcpClient(const std::string& ifname, bool bIpv6) int DhcpService::StopDhcpClient(const std::string& ifname, bool bIpv6) { + if (!CheckIfaceValid(ifname)) { + return DHCP_OPT_FAILED; + } if (m_pClientService == nullptr) { m_pClientService = std::make_unique(); if (m_pClientService == nullptr) { @@ -102,6 +113,9 @@ int DhcpService::ReleaseDhcpClient(const std::string& ifname) int DhcpService::StartDhcpServer(const std::string& ifname) { + if (!CheckIfaceValid(ifname)) { + return DHCP_OPT_FAILED; + } if (InitServerService() != DHCP_OPT_SUCCESS) { WIFI_LOGE("DhcpService::StartDhcpServer() InitServerService failed!"); return DHCP_OPT_FAILED; @@ -211,5 +225,25 @@ int DhcpService::InitServerService() } return DHCP_OPT_SUCCESS; } + +bool DhcpService::CheckIfaceValid(const std::string& ifname) +{ + struct if_nameindex *ifidxs, *ifni; + + ifidxs = if_nameindex(); + if (ifidxs == nullptr) { + WIFI_LOGE("can not get interfaces"); + return false; + } + for (ifni = ifidxs; !(ifni->if_index == 0 && ifni->if_name == nullptr); ifni++) { + if (strncmp(ifni->if_name, ifname.c_str(), strlen(ifni->if_name)) == 0) { + if_freenameindex(ifidxs); + return true; + } + } + if_freenameindex(ifidxs); + WIFI_LOGE("invalid interface: %{public}s", ifname.c_str()); + return false; +} } // namespace Wifi -} // namespace OHOS \ No newline at end of file +} // namespace OHOS diff --git a/dhcp/services/mgr_service/src/dhcp_service_api.cpp b/dhcp/services/mgr_service/src/dhcp_service_api.cpp new file mode 100644 index 0000000000000000000000000000000000000000..cb0f1075ccd165e5d3b486c10e802c1dc86cf662 --- /dev/null +++ b/dhcp/services/mgr_service/src/dhcp_service_api.cpp @@ -0,0 +1,36 @@ +/* + * Copyright (C) 2022 Huawei Device Co., Ltd. + * 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 "dhcp_service_api.h" +#include +#include "dhcp_service.h" +#include "i_dhcp_service.h" +#include "wifi_logger.h" + +DEFINE_WIFILOG_DHCP_LABEL("DhcpServiceApi"); + +namespace OHOS { +namespace Wifi { +std::unique_ptr DhcpServiceApi::GetInstance() +{ + std::unique_ptr service = std::make_unique(); + if (service == nullptr) { + WIFI_LOGI("DhcpApi GetInstance is null"); + } + return service; +} + +} // namespace Wifi +} // namespace OHOS diff --git a/tests/wifi_standard/wifi_framework/dhcp_manage/dhcp_client/BUILD.gn b/dhcp/test/services/dhcp_client/BUILD.gn similarity index 55% rename from tests/wifi_standard/wifi_framework/dhcp_manage/dhcp_client/BUILD.gn rename to dhcp/test/services/dhcp_client/BUILD.gn index ee7b983a95ee82f190bd11a57718eecdf7a0b77e..659f38a038e307cbb47011dbbf3660a26151aa47 100644 --- a/tests/wifi_standard/wifi_framework/dhcp_manage/dhcp_client/BUILD.gn +++ b/dhcp/test/services/dhcp_client/BUILD.gn @@ -1,4 +1,4 @@ -# Copyright (C) 2021 Huawei Device Co., Ltd. +# Copyright (C) 2021-2022 Huawei Device Co., Ltd. # 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 @@ -12,34 +12,32 @@ # limitations under the License. import("//build/test.gni") -import("//foundation/appexecfwk/standard/appexecfwk.gni") +import("//foundation/communication/wifi/dhcp/dhcp.gni") ################################################################################ -SUBSYSTEM_DIR = "//foundation/communication" -module_output_path = "wifi_standard/dhcp_client_test" +module_output_path = "dhcp/dhcp_client_test" config("module_private_config") { visibility = [ ":*" ] include_dirs = [ - "//utils/native/base/include", - "$SUBSYSTEM_DIR/wifi/services/wifi_standard/wifi_framework/dhcp_manage/dhcp_client/test", + "//commonlibrary/c_utils/base/include", + "$DHCP_ROOT_DIR/services/dhcp_client/include", ] } ohos_unittest("dhcp_client_unittest") { module_out_path = module_output_path sources = [ - "//foundation/communication/wifi/services/wifi_standard/wifi_framework/dhcp_manage/dhcp_client/src/dhcp_api.cpp", - "//foundation/communication/wifi/services/wifi_standard/wifi_framework/dhcp_manage/dhcp_client/src/dhcp_client.c", - "//foundation/communication/wifi/services/wifi_standard/wifi_framework/dhcp_manage/dhcp_client/src/dhcp_function.c", - "//foundation/communication/wifi/services/wifi_standard/wifi_framework/dhcp_manage/dhcp_client/src/dhcp_ipv4.c", - "//foundation/communication/wifi/services/wifi_standard/wifi_framework/dhcp_manage/dhcp_client/src/dhcp_options.c", - "//foundation/communication/wifi/services/wifi_standard/wifi_framework/dhcp_manage/dhcp_client/src/dhcp_socket.c", + "$DHCP_ROOT_DIR/services/dhcp_client/src/dhcp_api.cpp", + "$DHCP_ROOT_DIR/services/dhcp_client/src/dhcp_client.c", + "$DHCP_ROOT_DIR/services/dhcp_client/src/dhcp_function.c", + "$DHCP_ROOT_DIR/services/dhcp_client/src/dhcp_ipv4.c", + "$DHCP_ROOT_DIR/services/dhcp_client/src/dhcp_options.c", + "$DHCP_ROOT_DIR/services/dhcp_client/src/dhcp_socket.c", "dhcp_client_test.cpp", "dhcp_function_test.cpp", "dhcp_ipv4_test.cpp", - "dhcp_main_test.cpp", "dhcp_options_test.cpp", "dhcp_socket_test.cpp", "global_test.cpp", @@ -49,21 +47,18 @@ ohos_unittest("dhcp_client_unittest") { include_dirs = [ "//third_party/googletest/googlemock/include", - "//foundation/communication/wifi/services/wifi_standard/wifi_framework/dhcp_manage/dhcp_client/test", - "//foundation/communication/wifi/services/wifi_standard/wifi_framework/dhcp_manage/dhcp_client/include", - "//foundation/communication/wifi/services/wifi_standard/wifi_framework/common/log", - "//utils/native/base/include", - "//foundation/appexecfwk/standard/interfaces/innerkits/libeventhandler/include", + "$DHCP_ROOT_DIR/services/dhcp_client/test", + "$DHCP_ROOT_DIR/services/dhcp_client/include", + "$WIFI_ROOT_DIR/services/wifi_standard/wifi_framework/wifi_toolkit/log", + "//commonlibrary/c_utils/base/include", "//foundation/communication/ipc/interfaces/innerkits/ipc_core/include", "//third_party/openssl/include", ] deps = [ - "${aafwk_path}/interfaces/innerkits/base:base", - "${aafwk_path}/interfaces/innerkits/want:want", "//third_party/googletest:gmock_main", + "//third_party/googletest:gtest_main", "//third_party/openssl:libcrypto_static", - "//utils/native/base:utils", ] ldflags = [ @@ -89,12 +84,16 @@ ohos_unittest("dhcp_client_unittest") { ] external_deps = [ - "ces_standard:cesfwk_innerkits", + "ability_base:want", + "bundle_framework:appexecfwk_base", + "c_utils:utils", + "common_event_service:cesfwk_innerkits", + "eventhandler:libeventhandler", "hiviewdfx_hilog_native:libhilog", ] configs = [ ":module_private_config" ] - part_name = "wifi_standard" + part_name = "dhcp" subsystem_name = "communication" testonly = true } diff --git a/tests/wifi_standard/wifi_framework/dhcp_manage/dhcp_client/dhcp_client_test.cpp b/dhcp/test/services/dhcp_client/dhcp_client_test.cpp similarity index 100% rename from tests/wifi_standard/wifi_framework/dhcp_manage/dhcp_client/dhcp_client_test.cpp rename to dhcp/test/services/dhcp_client/dhcp_client_test.cpp diff --git a/tests/wifi_standard/wifi_framework/dhcp_manage/dhcp_client/dhcp_function_test.cpp b/dhcp/test/services/dhcp_client/dhcp_function_test.cpp similarity index 90% rename from tests/wifi_standard/wifi_framework/dhcp_manage/dhcp_client/dhcp_function_test.cpp rename to dhcp/test/services/dhcp_client/dhcp_function_test.cpp index 3925c1150e2a218febc7366db33722dd2feab5b2..4865e917818fe92a3adaf34c6e846ba21dbb0e7f 100644 --- a/tests/wifi_standard/wifi_framework/dhcp_manage/dhcp_client/dhcp_function_test.cpp +++ b/dhcp/test/services/dhcp_client/dhcp_function_test.cpp @@ -20,6 +20,7 @@ #include "mock_system_func.h" using namespace testing::ext; +using namespace OHOS::Wifi; namespace OHOS { class DhcpFunctionTest : public testing::Test { @@ -100,9 +101,6 @@ HWTEST_F(DhcpFunctionTest, GetLocalInterface_SUCCESS, TestSize.Level1) EXPECT_CALL(MockSystemFunc::GetInstance(), socket(_, _, _)).WillOnce(Return(-1)).WillRepeatedly(Return(1)); EXPECT_CALL(MockSystemFunc::GetInstance(), ioctl(_, _, _)) - .WillOnce(Return(-1)) - .WillOnce(Return(0)).WillOnce(Return(-1)) - .WillOnce(Return(0)).WillOnce(Return(0)).WillOnce(Return(-1)) .WillRepeatedly(Return(0)); EXPECT_CALL(MockSystemFunc::GetInstance(), close(_)).WillRepeatedly(Return(0)); @@ -113,7 +111,7 @@ HWTEST_F(DhcpFunctionTest, GetLocalInterface_SUCCESS, TestSize.Level1) unsigned char hwaddr[MAC_ADDR_LEN]; EXPECT_EQ(GetLocalInterface(interface, &ifindex, hwaddr, NULL), DHCP_OPT_FAILED); uint32_t ifaddr4; - EXPECT_EQ(GetLocalInterface(interface, &ifindex, hwaddr, &ifaddr4), DHCP_OPT_FAILED); + EXPECT_EQ(GetLocalInterface(interface, &ifindex, hwaddr, &ifaddr4), DHCP_OPT_SUCCESS); EXPECT_EQ(GetLocalInterface(interface, &ifindex, hwaddr, &ifaddr4), DHCP_OPT_SUCCESS); MockSystemFunc::SetMockFlag(false); @@ -136,17 +134,18 @@ HWTEST_F(DhcpFunctionTest, GetLocalIp_FAILED, TestSize.Level1) HWTEST_F(DhcpFunctionTest, SetLocalInterface_SUCCESS, TestSize.Level1) { char interface[INFNAME_SIZE] = "wlan0"; - uint32_t ipaddr4 = 3226272231; - EXPECT_EQ(DHCP_OPT_SUCCESS, SetLocalInterface(interface, ipaddr4)); + uint32_t ipaddr4 = 2981805322; + uint32_t netMask = 16318463; + EXPECT_EQ(DHCP_OPT_SUCCESS, SetLocalInterface(interface, ipaddr4, netMask)); } HWTEST_F(DhcpFunctionTest, SetLocalInterface_FAILED, TestSize.Level1) { char interface[INFNAME_SIZE] = {0}; uint32_t ipaddr4 = 0; - EXPECT_EQ(DHCP_OPT_FAILED, SetLocalInterface(interface, ipaddr4)); - - EXPECT_EQ(DHCP_OPT_FAILED, SetLocalInterface("wlan", ipaddr4)); + uint32_t netMask = 0; + EXPECT_EQ(DHCP_OPT_FAILED, SetLocalInterface(interface, ipaddr4, netMask)); + EXPECT_EQ(DHCP_OPT_FAILED, SetLocalInterface("wlan", ipaddr4, netMask)); } HWTEST_F(DhcpFunctionTest, InitPidfile_SUCCESS, TestSize.Level1) @@ -159,17 +158,6 @@ HWTEST_F(DhcpFunctionTest, InitPidfile_SUCCESS, TestSize.Level1) usleep(SLEEP_TIME_200_MS); } -HWTEST_F(DhcpFunctionTest, InitPidfile_FAILED, TestSize.Level1) -{ - char workDir[DIR_MAX_LEN] = {0}; - char pidFile[DIR_MAX_LEN] = {0}; - EXPECT_EQ(DHCP_OPT_FAILED, InitPidfile(workDir, pidFile, getpid())); - - EXPECT_EQ(DHCP_OPT_FAILED, InitPidfile("./", "./test/wlan0.pid", getpid())); - - EXPECT_EQ(DHCP_OPT_FAILED, InitPidfile("./test/", "./wlan0.pid", getpid())); -} - HWTEST_F(DhcpFunctionTest, GetPID_SUCCESS, TestSize.Level1) { char workDir[DIR_MAX_LEN] = "./"; diff --git a/tests/wifi_standard/wifi_framework/dhcp_manage/dhcp_client/dhcp_ipv4_test.cpp b/dhcp/test/services/dhcp_client/dhcp_ipv4_test.cpp similarity index 36% rename from tests/wifi_standard/wifi_framework/dhcp_manage/dhcp_client/dhcp_ipv4_test.cpp rename to dhcp/test/services/dhcp_client/dhcp_ipv4_test.cpp index 95797fc9ab63552181304c0495defe525d08f63d..49ddb0665e023678291213a0f76111135a2957c7 100644 --- a/tests/wifi_standard/wifi_framework/dhcp_manage/dhcp_client/dhcp_ipv4_test.cpp +++ b/dhcp/test/services/dhcp_client/dhcp_ipv4_test.cpp @@ -1,5 +1,5 @@ /* - * Copyright (C) 2021 Huawei Device Co., Ltd. + * Copyright (C) 2021-2022 Huawei Device Co., Ltd. * 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 @@ -12,6 +12,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + #include #include #include @@ -24,8 +25,8 @@ #include "dhcp_function.h" using namespace testing::ext; +using namespace OHOS::Wifi; -namespace OHOS { class DhcpIpv4Test : public testing::Test { public: static void SetUpTestCase() @@ -37,88 +38,7 @@ public: virtual void TearDown() {} }; -#if 0 -HWTEST_F(DhcpIpv4Test, StartIpv4_Mock1, TestSize.Level1) -{ - MockSystemFunc::SetMockFlag(true); - MockCustomFunc::SetMockFlag(true); - - EXPECT_CALL(MockSystemFunc::GetInstance(), socket(_, _, _)).WillRepeatedly(Return(1)); - EXPECT_CALL(MockSystemFunc::GetInstance(), setsockopt(_, _, _, _, _)).WillRepeatedly(Return(0)); - EXPECT_CALL(MockSystemFunc::GetInstance(), bind(_, _, _)).WillRepeatedly(Return(0)); - EXPECT_CALL(MockSystemFunc::GetInstance(), select(_, _, _, _, _)) - .WillOnce(Return(-1)).WillOnce(Return(1)) - .WillOnce(Return(0)).WillOnce(Return(1)).WillOnce(Return(1)) - .WillOnce(Return(0)).WillOnce(Return(1)) - .WillOnce(Return(0)).WillOnce(Return(1)) - .WillOnce(Return(3)).WillOnce(Return(1)).WillOnce(Return(2)) - .WillRepeatedly(Return(0)); - EXPECT_CALL(MockSystemFunc::GetInstance(), sendto(_, _, _, _, _, _)).WillRepeatedly(Return(1)); - EXPECT_CALL(MockSystemFunc::GetInstance(), read(_, _, _)).WillRepeatedly(Return(500)); - EXPECT_CALL(MockSystemFunc::GetInstance(), close(_)).WillRepeatedly(Return(0)); - EXPECT_CALL(MockSystemFunc::GetInstance(), open(_, _)).WillRepeatedly(Return(1)); - EXPECT_CALL(MockSystemFunc::GetInstance(), ioctl(_, _, _)).WillRepeatedly(Return(0)); - EXPECT_CALL(MockSystemFunc::GetInstance(), connect(_, _, _)).WillRepeatedly(Return(0)); - EXPECT_CALL(MockSystemFunc::GetInstance(), write(_, _, _)).WillRepeatedly(Return(1)); - - EXPECT_CALL(MockCustomFunc::GetInstance(), GetDhcpRawPacket(_, _)) - .WillOnce(Return(SOCKET_OPT_ERROR)) - .WillOnce(Return(1)) - .WillOnce(Return(2)) - .WillRepeatedly(Return(SOCKET_OPT_SUCCESS)); - EXPECT_CALL(MockCustomFunc::GetInstance(), GetDhcpKernelPacket(_, _)) - .WillOnce(Return(2)) - .WillOnce(Return(3)) - .WillRepeatedly(Return(SOCKET_OPT_SUCCESS)); - - struct DhcpClientCfg *pCfg = GetDhcpClientCfg(); - pCfg->timeoutExit = false; - EXPECT_EQ(DHCP_OPT_SUCCESS, StartIpv4()); - - MockSystemFunc::SetMockFlag(false); - MockCustomFunc::SetMockFlag(false); -} - -HWTEST_F(DhcpIpv4Test, StartIpv4_Mock2, TestSize.Level1) -{ - MockSystemFunc::SetMockFlag(true); - MockCustomFunc::SetMockFlag(true); - - EXPECT_CALL(MockSystemFunc::GetInstance(), socket(_, _, _)).WillRepeatedly(Return(1)); - EXPECT_CALL(MockSystemFunc::GetInstance(), setsockopt(_, _, _, _, _)).WillRepeatedly(Return(0)); - EXPECT_CALL(MockSystemFunc::GetInstance(), bind(_, _, _)).WillRepeatedly(Return(0)); - EXPECT_CALL(MockSystemFunc::GetInstance(), select(_, _, _, _, _)) - .WillOnce(Return(0)).WillOnce(Return(1)) - .WillOnce(Return(0)).WillOnce(Return(1)).WillOnce(Return(1)) - .WillOnce(Return(0)).WillOnce(Return(1)) - .WillOnce(Return(0)).WillOnce(Return(1)).WillOnce(Return(0)).WillOnce(Return(0)) - .WillOnce(Return(2)) - .WillRepeatedly(Return(0)); - EXPECT_CALL(MockSystemFunc::GetInstance(), sendto(_, _, _, _, _, _)).WillRepeatedly(Return(1)); - EXPECT_CALL(MockSystemFunc::GetInstance(), read(_, _, _)).WillRepeatedly(Return(500)); - EXPECT_CALL(MockSystemFunc::GetInstance(), close(_)).WillRepeatedly(Return(0)); - EXPECT_CALL(MockSystemFunc::GetInstance(), open(_, _)).WillRepeatedly(Return(1)); - EXPECT_CALL(MockSystemFunc::GetInstance(), ioctl(_, _, _)).WillRepeatedly(Return(0)); - EXPECT_CALL(MockSystemFunc::GetInstance(), connect(_, _, _)).WillRepeatedly(Return(0)); - EXPECT_CALL(MockSystemFunc::GetInstance(), write(_, _, _)).WillRepeatedly(Return(1)); - - EXPECT_CALL(MockCustomFunc::GetInstance(), GetDhcpRawPacket(_, _)) - .WillOnce(Return(3)) - .WillOnce(Return(1)).WillOnce(Return(4)) - .WillRepeatedly(Return(SOCKET_OPT_SUCCESS)); - EXPECT_CALL(MockCustomFunc::GetInstance(), GetDhcpKernelPacket(_, _)) - .WillOnce(Return(1)) - .WillOnce(Return(2)) - .WillRepeatedly(Return(SOCKET_OPT_SUCCESS)); - - struct DhcpClientCfg *pCfg = GetDhcpClientCfg(); - pCfg->timeoutExit = false; - EXPECT_EQ(DHCP_OPT_SUCCESS, StartIpv4()); - MockSystemFunc::SetMockFlag(false); - MockCustomFunc::SetMockFlag(false); -} -#endif HWTEST_F(DhcpIpv4Test, ExecDhcpRenew_SUCCESS, TestSize.Level1) { MockSystemFunc::SetMockFlag(true); @@ -162,19 +82,3 @@ HWTEST_F(DhcpIpv4Test, TEST_FAILED, TestSize.Level1) EXPECT_EQ(DHCP_OPT_FAILED, GetPacketHeaderInfo(NULL, 0)); EXPECT_EQ(DHCP_OPT_FAILED, GetPacketCommonInfo(NULL)); } - -HWTEST_F(DhcpIpv4Test, TEST_SUCCESS, TestSize.Level1) -{ - MockSystemFunc::SetMockFlag(true); - - EXPECT_CALL(MockSystemFunc::GetInstance(), socket(_, _, _)).WillRepeatedly(Return(1)); - EXPECT_CALL(MockSystemFunc::GetInstance(), bind(_, _, _)).WillRepeatedly(Return(0)); - EXPECT_CALL(MockSystemFunc::GetInstance(), sendto(_, _, _, _, _, _)).WillRepeatedly(Return(1)); - EXPECT_CALL(MockSystemFunc::GetInstance(), close(_)).WillRepeatedly(Return(0)); - - EXPECT_EQ(DHCP_OPT_SUCCESS, DhcpDiscover(0, 1)); - EXPECT_EQ(DHCP_OPT_SUCCESS, DhcpRenew(0, 0, 0)); - - MockSystemFunc::SetMockFlag(false); -} -} // namespace OHOS \ No newline at end of file diff --git a/tests/wifi_standard/wifi_framework/dhcp_manage/dhcp_client/dhcp_options_test.cpp b/dhcp/test/services/dhcp_client/dhcp_options_test.cpp similarity index 100% rename from tests/wifi_standard/wifi_framework/dhcp_manage/dhcp_client/dhcp_options_test.cpp rename to dhcp/test/services/dhcp_client/dhcp_options_test.cpp diff --git a/tests/wifi_standard/wifi_framework/dhcp_manage/dhcp_client/dhcp_socket_test.cpp b/dhcp/test/services/dhcp_client/dhcp_socket_test.cpp similarity index 88% rename from tests/wifi_standard/wifi_framework/dhcp_manage/dhcp_client/dhcp_socket_test.cpp rename to dhcp/test/services/dhcp_client/dhcp_socket_test.cpp index f128096447c333776c697777caeb1a75b649922b..3d1181a624c1a004548a4c69e2808e18b2077abb 100644 --- a/tests/wifi_standard/wifi_framework/dhcp_manage/dhcp_client/dhcp_socket_test.cpp +++ b/dhcp/test/services/dhcp_client/dhcp_socket_test.cpp @@ -1,5 +1,5 @@ /* - * Copyright (C) 2021 Huawei Device Co., Ltd. + * Copyright (C) 2021-2022 Huawei Device Co., Ltd. * 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 @@ -12,6 +12,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + #include #include "wifi_log.h" @@ -21,6 +22,7 @@ #include "mock_system_func.h" using namespace testing::ext; +using namespace OHOS::Wifi; namespace OHOS { class DhcpSocketTest : public testing::Test { @@ -107,20 +109,12 @@ HWTEST_F(DhcpSocketTest, SendToDhcpPacket_SUCCESS, TestSize.Level1) EXPECT_CALL(MockSystemFunc::GetInstance(), socket(_, _, _)).WillOnce(Return(-1)).WillRepeatedly(Return(1)); EXPECT_CALL(MockSystemFunc::GetInstance(), bind(_, _, _)).WillOnce(Return(-1)).WillRepeatedly(Return(0)); - EXPECT_CALL(MockSystemFunc::GetInstance(), sendto(_, _, _, _, _, _)) - .WillOnce(Return(-1)) - .WillRepeatedly(Return(1)); + EXPECT_CALL(MockSystemFunc::GetInstance(), sendto(_, _, _, _, _, _)).WillRepeatedly(Return(1)); EXPECT_CALL(MockSystemFunc::GetInstance(), close(_)).WillRepeatedly(Return(0)); EXPECT_EQ(SendToDhcpPacket(NULL, 0, 0, 0, NULL), SOCKET_OPT_FAILED); int ifindex = 1; EXPECT_EQ(SendToDhcpPacket(NULL, 0, 0, ifindex, (uint8_t *)MAC_BCAST_ADDR), SOCKET_OPT_FAILED); - struct DhcpPacket packet; - packet.xid = 123456; - EXPECT_EQ(SendToDhcpPacket(&packet, 0, 0, ifindex, (uint8_t *)MAC_BCAST_ADDR), SOCKET_OPT_FAILED); - EXPECT_EQ(SendToDhcpPacket(&packet, INADDR_ANY, INADDR_BROADCAST, ifindex, (uint8_t *)MAC_BCAST_ADDR), - SOCKET_OPT_SUCCESS); - MockSystemFunc::SetMockFlag(false); } @@ -141,7 +135,6 @@ HWTEST_F(DhcpSocketTest, SendDhcpPacket_SUCCESS, TestSize.Level1) packet.xid = 123456; EXPECT_EQ(SendDhcpPacket(&packet, INADDR_ANY, INADDR_BROADCAST), SOCKET_OPT_FAILED); EXPECT_EQ(SendDhcpPacket(&packet, INADDR_ANY, INADDR_BROADCAST), SOCKET_OPT_SUCCESS); - MockSystemFunc::SetMockFlag(false); } @@ -223,24 +216,6 @@ HWTEST_F(DhcpSocketTest, CheckPacketUdpSum_SUCCESS, TestSize.Level1) EXPECT_EQ(CheckPacketUdpSum(&packet, 1), SOCKET_OPT_SUCCESS); } -HWTEST_F(DhcpSocketTest, GetDhcpRawPacket_FAILED, TestSize.Level1) -{ - EXPECT_EQ(GetDhcpRawPacket(NULL, 0), SOCKET_OPT_FAILED); - - MockSystemFunc::SetMockFlag(true); - - struct UdpDhcpPacket udpPackets; - ASSERT_TRUE(memset_s(&udpPackets, sizeof(struct UdpDhcpPacket), 0, sizeof(struct UdpDhcpPacket)) == EOK); - int total = sizeof(struct iphdr) + sizeof(struct udphdr); - EXPECT_CALL(MockSystemFunc::GetInstance(), read(_, _, _)).WillOnce(Return(-1)).WillRepeatedly(Return(total)); - - struct DhcpPacket packet; - EXPECT_EQ(GetDhcpRawPacket(&packet, 1), SOCKET_OPT_ERROR); - EXPECT_EQ(GetDhcpRawPacket(&packet, 1), SOCKET_OPT_FAILED); - - MockSystemFunc::SetMockFlag(false); -} - HWTEST_F(DhcpSocketTest, GetDhcpKernelPacket_SUCCESS, TestSize.Level1) { EXPECT_EQ(GetDhcpKernelPacket(NULL, 0), SOCKET_OPT_FAILED); diff --git a/tests/wifi_standard/wifi_framework/dhcp_manage/dhcp_client/global_test.cpp b/dhcp/test/services/dhcp_client/global_test.cpp similarity index 100% rename from tests/wifi_standard/wifi_framework/dhcp_manage/dhcp_client/global_test.cpp rename to dhcp/test/services/dhcp_client/global_test.cpp diff --git a/tests/wifi_standard/wifi_framework/dhcp_manage/dhcp_client/global_test.h b/dhcp/test/services/dhcp_client/global_test.h similarity index 100% rename from tests/wifi_standard/wifi_framework/dhcp_manage/dhcp_client/global_test.h rename to dhcp/test/services/dhcp_client/global_test.h diff --git a/tests/wifi_standard/wifi_framework/dhcp_manage/dhcp_client/mock_custom_func.cpp b/dhcp/test/services/dhcp_client/mock_custom_func.cpp similarity index 100% rename from tests/wifi_standard/wifi_framework/dhcp_manage/dhcp_client/mock_custom_func.cpp rename to dhcp/test/services/dhcp_client/mock_custom_func.cpp diff --git a/tests/wifi_standard/wifi_framework/dhcp_manage/dhcp_client/mock_custom_func.h b/dhcp/test/services/dhcp_client/mock_custom_func.h similarity index 81% rename from tests/wifi_standard/wifi_framework/dhcp_manage/dhcp_client/mock_custom_func.h rename to dhcp/test/services/dhcp_client/mock_custom_func.h index f50e7892a304571943d6dd1fa2538842d4d1e23d..325ad1c31068b6d846d60a4943c986cb2f93f7e7 100644 --- a/tests/wifi_standard/wifi_framework/dhcp_manage/dhcp_client/mock_custom_func.h +++ b/dhcp/test/services/dhcp_client/mock_custom_func.h @@ -26,7 +26,6 @@ class MockCustomFunc { public: MOCK_METHOD2(GetDhcpRawPacket, int(struct DhcpPacket *getPacket, int rawFd)); MOCK_METHOD2(GetDhcpKernelPacket, int(struct DhcpPacket *getPacket, int sockFd)); - // MOCK_METHOD0(GetSelectRet, int(void)); static MockCustomFunc &GetInstance(void); static void SetMockFlag(bool flag); @@ -38,15 +37,4 @@ private: }; } // namespace OHOS -// #ifdef __cplusplus -// extern "C" { -// #endif - -// int GetSelectRet(void); -// int MySelect(int nfds, fd_set *readfds, fd_set *writefds, fd_set *exceptfds, struct timeval *timeout); - -// #ifdef __cplusplus -// } -// #endif - #endif \ No newline at end of file diff --git a/tests/wifi_standard/wifi_framework/dhcp_manage/dhcp_client/mock_system_func.cpp b/dhcp/test/services/dhcp_client/mock_system_func.cpp similarity index 97% rename from tests/wifi_standard/wifi_framework/dhcp_manage/dhcp_client/mock_system_func.cpp rename to dhcp/test/services/dhcp_client/mock_system_func.cpp index 092c0bc00660ef040fa1d43492ca94cf62a9ee1b..6e8739cd7a148b53dc4df11f0e76c10a0fe7df17 100644 --- a/tests/wifi_standard/wifi_framework/dhcp_manage/dhcp_client/mock_system_func.cpp +++ b/dhcp/test/services/dhcp_client/mock_system_func.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021 Huawei Device Co., Ltd. + * Copyright (c) 2021-2022 Huawei Device Co., Ltd. * 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 @@ -16,7 +16,8 @@ #include "mock_system_func.h" #include "dhcp_ipv4.h" #include "dhcp_client.h" -using namespace OHOS; + +using namespace OHOS::Wifi; static bool g_mockTag = false; @@ -39,9 +40,7 @@ bool MockSystemFunc::GetMockFlag(void) return g_mockTag; } -#ifdef __cplusplus extern "C" { -#endif int __real_open(const char *__file, int __oflag); int __wrap_open(const char *__file, int __oflag) { @@ -177,6 +176,4 @@ ssize_t __wrap_sendto(int fd, const void *buf, size_t count, int flags, const st return __real_sendto(fd, buf, count, flags, addr, len); } } -#ifdef __cplusplus } -#endif diff --git a/tests/wifi_standard/wifi_framework/dhcp_manage/dhcp_client/mock_system_func.h b/dhcp/test/services/dhcp_client/mock_system_func.h similarity index 95% rename from tests/wifi_standard/wifi_framework/dhcp_manage/dhcp_client/mock_system_func.h rename to dhcp/test/services/dhcp_client/mock_system_func.h index 92b823959ecda41e53cc60d300a087e1efc3cab8..5b50c4f057944142366d24f0b938dd4a1e52a81f 100644 --- a/tests/wifi_standard/wifi_framework/dhcp_manage/dhcp_client/mock_system_func.h +++ b/dhcp/test/services/dhcp_client/mock_system_func.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021 Huawei Device Co., Ltd. + * Copyright (c) 2021-2022 Huawei Device Co., Ltd. * 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 @@ -27,6 +27,7 @@ using ::testing::_; using ::testing::Return; namespace OHOS { +namespace Wifi { class MockSystemFunc { public: MOCK_METHOD2(open, int(const char *__file, int __oflag)); @@ -51,8 +52,6 @@ private: MockSystemFunc(); ~MockSystemFunc(){} }; +} // namespace Wifi } // namespace OHOS - -extern "C" {} - -#endif \ No newline at end of file +#endif diff --git a/tests/wifi_standard/wifi_framework/dhcp_manage/dhcp_server/unittest/BUILD.gn b/dhcp/test/services/dhcp_server/unittest/BUILD.gn similarity index 51% rename from tests/wifi_standard/wifi_framework/dhcp_manage/dhcp_server/unittest/BUILD.gn rename to dhcp/test/services/dhcp_server/unittest/BUILD.gn index a35397f93a8ceea086d664e4d2ddaba140592f51..bf9eb285b2416d3ff71c43e61ec128fc473f2dba 100644 --- a/tests/wifi_standard/wifi_framework/dhcp_manage/dhcp_server/unittest/BUILD.gn +++ b/dhcp/test/services/dhcp_server/unittest/BUILD.gn @@ -1,4 +1,4 @@ -# Copyright (C) 2021 Huawei Device Co., Ltd. +# Copyright (C) 2021-2022 Huawei Device Co., Ltd. # 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 @@ -12,31 +12,33 @@ # limitations under the License. import("//build/test.gni") +import("//foundation/communication/wifi/dhcp/dhcp.gni") -SUBSYSTEM_DIR = "//foundation/communication/wifi" -module_output_path = "wifi_standard/dhcp_server_test" +module_output_path = "dhcp/dhcp_server_test" config("module_private_config") { visibility = [ ":*" ] include_dirs = [ - "//utils/native/base/include", - "$SUBSYSTEM_DIR/services/wifi_standard/wifi_framework/dhcp_manage/dhcp_server/include", + "//commonlibrary/c_utils/base/include", + "$DHCP_ROOT_DIR/services/dhcp_server/include", ] } ohos_unittest("dhcp_server_unittest") { module_out_path = module_output_path + dhcp_hilog_enable = true sources = [ - "$SUBSYSTEM_DIR/services/wifi_standard/wifi_framework/dhcp_manage/dhcp_server/src/address_utils.c", - "$SUBSYSTEM_DIR/services/wifi_standard/wifi_framework/dhcp_manage/dhcp_server/src/common_util.c", - "$SUBSYSTEM_DIR/services/wifi_standard/wifi_framework/dhcp_manage/dhcp_server/src/dhcp_address_pool.c", - "$SUBSYSTEM_DIR/services/wifi_standard/wifi_framework/dhcp_manage/dhcp_server/src/dhcp_argument.c", - "$SUBSYSTEM_DIR/services/wifi_standard/wifi_framework/dhcp_manage/dhcp_server/src/dhcp_binding.c", - "$SUBSYSTEM_DIR/services/wifi_standard/wifi_framework/dhcp_manage/dhcp_server/src/dhcp_config.c", - "$SUBSYSTEM_DIR/services/wifi_standard/wifi_framework/dhcp_manage/dhcp_server/src/dhcp_option.c", - "$SUBSYSTEM_DIR/services/wifi_standard/wifi_framework/dhcp_manage/dhcp_server/src/dhcp_server.c", - "$SUBSYSTEM_DIR/services/wifi_standard/wifi_framework/dhcp_manage/dhcp_server/src/hash_table.c", + "$DHCP_ROOT_DIR/services/dhcp_server/src/address_utils.c", + "$DHCP_ROOT_DIR/services/dhcp_server/src/common_util.c", + "$DHCP_ROOT_DIR/services/dhcp_server/src/dhcp_address_pool.c", + "$DHCP_ROOT_DIR/services/dhcp_server/src/dhcp_argument.c", + "$DHCP_ROOT_DIR/services/dhcp_server/src/dhcp_binding.c", + "$DHCP_ROOT_DIR/services/dhcp_server/src/dhcp_config.c", + "$DHCP_ROOT_DIR/services/dhcp_server/src/dhcp_option.c", + "$DHCP_ROOT_DIR/services/dhcp_server/src/dhcp_server.c", + "$DHCP_ROOT_DIR/services/dhcp_server/src/hash_table.c", "address_utils_test.cpp", + "common_util_test.cpp", "dhcp_address_pool_test.cpp", "dhcp_argument_test.cpp", "dhcp_binding_test.cpp", @@ -49,38 +51,42 @@ ohos_unittest("dhcp_server_unittest") { ] include_dirs = [ - "//utils/native/base/include", + "//commonlibrary/c_utils/base/include", "//third_party/googletest/googlemock/include", "//base/hiviewdfx/hilog/interfaces/native/innerkits/include", - "$SUBSYSTEM_DIR/services/wifi_standard/wifi_framework/dhcp_manage/dhcp_server/include", + "$DHCP_ROOT_DIR/services/dhcp_server/include", ] - defines = [ "__OHOS__" ] - cflags = [] deps = [ "//third_party/googletest:gmock_main", "//third_party/googletest:gtest_main", - "//utils/native/base:utils", ] + external_deps = [ "c_utils:utils" ] + ldflags = [ "-fPIC", + "-Wl,-E", "-Wl,--wrap=socket", - "-Wl,--wrap=recvfrom", - "-Wl,--wrap=sendto", - "-Wl,--wrap=bind", "-Wl,--wrap=setsockopt", "-Wl,--wrap=select", + "-Wl,--wrap=bind", "-Wl,--wrap=close", "--coverage", ] - external_deps = [ "hiviewdfx_hilog_native:libhilog" ] configs = [ ":module_private_config" ] - part_name = "wifi_standard" + defines = [ "DHCP_SEL_WAIT_TIMEOUTS=1" ] + + if (dhcp_hilog_enable) { + external_deps += [ "hiviewdfx_hilog_native:libhilog" ] + defines += [ "DHCP_HILOG_ENABLE" ] + } + + part_name = "dhcp" subsystem_name = "communication" testonly = true } diff --git a/tests/wifi_standard/wifi_framework/dhcp_manage/dhcp_server/unittest/address_utils_test.cpp b/dhcp/test/services/dhcp_server/unittest/address_utils_test.cpp similarity index 94% rename from tests/wifi_standard/wifi_framework/dhcp_manage/dhcp_server/unittest/address_utils_test.cpp rename to dhcp/test/services/dhcp_server/unittest/address_utils_test.cpp index 1e972b3972b3b1b32e87915619a82a9044251b81..52c59703f44fecdfb9afa4a8665bcc9f5559ea27 100644 --- a/tests/wifi_standard/wifi_framework/dhcp_manage/dhcp_server/unittest/address_utils_test.cpp +++ b/dhcp/test/services/dhcp_server/unittest/address_utils_test.cpp @@ -15,7 +15,6 @@ #include #include -#include "string_ex.h" #include "dhcp_define.h" #include "address_utils.h" @@ -98,6 +97,20 @@ HWTEST(AddressUtilsTest, LastIpAddressTest, TestSize.Level1) EXPECT_EQ(srcAddr, LastIpAddress(testIp, testNetmask)); } +HWTEST(AddressUtilsTest, FirstNetIpAddressTest, TestSize.Level1) +{ + uint8_t srcData[] = {192, 168, 100, 1}; + uint32_t srcAddr = ParseIp(srcData); + ASSERT_TRUE(srcAddr != 0); + uint32_t testIp = ParseIpAddr("192.168.100.100"); + ASSERT_TRUE(testIp != 0); + uint32_t testNetmask = ParseIp(netmask24); + EXPECT_TRUE(testNetmask != 0); + uint32_t network = NetworkAddress(testIp, testNetmask); + ASSERT_TRUE(network != 0); + EXPECT_EQ(srcAddr, FirstNetIpAddress(network)); +} + HWTEST(AddressUtilsTest, NextIpAddressTest, TestSize.Level1) { uint8_t srcData[] = {192, 168, 100, 100}; diff --git a/dhcp/test/services/dhcp_server/unittest/common_util_test.cpp b/dhcp/test/services/dhcp_server/unittest/common_util_test.cpp new file mode 100644 index 0000000000000000000000000000000000000000..c824332fce1a864eba66608a61435eb876b7f534 --- /dev/null +++ b/dhcp/test/services/dhcp_server/unittest/common_util_test.cpp @@ -0,0 +1,87 @@ +/* + * Copyright (C) 2021 Huawei Device Co., Ltd. + * 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 "dhcp_define.h" +#include "common_util.h" + +using namespace testing::ext; +HWTEST(CommonUtilTest, LogTimeTest, TestSize.Level1) +{ + LogTime(); + uint64_t begin = Tmspsec(); + EXPECT_TRUE(begin > 0); + sleep(1); + uint64_t curr = Tmspsec(); + EXPECT_TRUE(curr > begin); + begin = Tmspusec(); + EXPECT_TRUE(begin > 0); + sleep(1); + curr = Tmspusec(); + EXPECT_TRUE(begin > 0); +} + +HWTEST(CommonUtilTest, LeftTirmTest, TestSize.Level1) +{ + char src1[] = " aabbccdd"; + LeftTrim(src1); + EXPECT_STREQ("aabbccdd", src1); +} + +HWTEST(CommonUtilTest, RightTrimTest, TestSize.Level1) +{ + char src1[] = "aabbccdd "; + RightTrim(src1); + EXPECT_STREQ("aabbccdd", src1); +} + +HWTEST(CommonUtilTest, TrimStringTest, TestSize.Level1) +{ + char src1[] = "aabbccdd "; + char src2[] = " aabbccdd"; + char src3[] = " aabbccdd "; + TrimString(src1); + TrimString(src2); + TrimString(src3); + EXPECT_STREQ("aabbccdd", src1); + EXPECT_STREQ("aabbccdd", src2); + EXPECT_STREQ("aabbccdd", src3); +} + +HWTEST(CommonUtilTest, GetFilePathTest, TestSize.Level1) +{ + const char *testPath = "/etc/dhcp/dhcp_server.conf"; + EXPECT_TRUE(GetFilePath(NULL) == NULL); + EXPECT_TRUE(GetFilePath("") == NULL); + EXPECT_STREQ("/etc/dhcp", GetFilePath(testPath)); +} + +HWTEST(CommonUtilTest, GetLeaseFileTest, TestSize.Level1) +{ + const char *leaseFile = "/etc/dhcp/dhcp_server.lease"; + const char *ifname = "test_if0"; + EXPECT_TRUE(GetLeaseFile(leaseFile, NULL) == NULL); + EXPECT_TRUE(GetLeaseFile(NULL, NULL) == NULL); + EXPECT_STREQ("/etc/dhcp/dhcp_server.lease.test_if0", GetLeaseFile(leaseFile, ifname)); +} + +HWTEST(CommonUtilTest, CreatePathTest, TestSize.Level1) +{ + const char *testPath = "./test/data/testpath"; + ASSERT_EQ(RET_FAILED, CreatePath(NULL)); + ASSERT_EQ(RET_FAILED, CreatePath("")); + ASSERT_EQ(RET_SUCCESS, CreatePath(testPath)); + EXPECT_EQ(0, remove(testPath)); +} \ No newline at end of file diff --git a/tests/wifi_standard/wifi_framework/dhcp_manage/dhcp_server/unittest/dhcp_address_pool_test.cpp b/dhcp/test/services/dhcp_server/unittest/dhcp_address_pool_test.cpp similarity index 52% rename from tests/wifi_standard/wifi_framework/dhcp_manage/dhcp_server/unittest/dhcp_address_pool_test.cpp rename to dhcp/test/services/dhcp_server/unittest/dhcp_address_pool_test.cpp index 8100e141c67870e0fc9a4f05eb7ab8ada8d6ae33..c1014d41027d278caf93a9a3fc833a0bc7a70add 100644 --- a/tests/wifi_standard/wifi_framework/dhcp_manage/dhcp_server/unittest/dhcp_address_pool_test.cpp +++ b/dhcp/test/services/dhcp_server/unittest/dhcp_address_pool_test.cpp @@ -16,7 +16,6 @@ #include #include #include -#include "string_ex.h" #include "dhcp_define.h" #include "dhcp_ipv4.h" #include "dhcp_message.h" @@ -24,6 +23,7 @@ #include "dhcp_address_pool.h" #include "address_utils.h" #include "common_util.h" +#include "securec.h" using namespace testing::ext; @@ -41,9 +41,39 @@ public: } virtual void TearDown() { + ResetPollConfig(); FreeAddressPool(&testPool); } + bool SamplePoolConfig() + { + uint32_t beginIp = ParseIpAddr("192.168.100.100"); + uint32_t endIp = ParseIpAddr("192.168.100.150"); + uint32_t netmask = ParseIpAddr("255.255.255.0"); + uint32_t gateway = ParseIpAddr("192.168.100.254"); + uint32_t serverId = ParseIpAddr("192.168.100.1"); + if (beginIp != 0 && endIp != 0 && netmask != 0 && gateway != 0) { + testPool.addressRange.beginAddress = beginIp; + testPool.addressRange.endAddress = endIp; + testPool.netmask = netmask; + testPool.gateway = gateway; + testPool.serverId = serverId; + testPool.leaseTime = DHCP_LEASE_TIME; + return true; + } + return false; + } + + void ResetPollConfig() + { + testPool.addressRange.beginAddress = 0; + testPool.addressRange.endAddress = 0; + testPool.netmask = 0; + testPool.gateway = 0; + testPool.serverId = 0; + testPool.leaseTime = 0; + } + public: DhcpAddressPool testPool; @@ -65,12 +95,72 @@ HWTEST_F(DhcpAddressPoolTest, AddBindingTest, TestSize.Level1) for (int i = 0; i < MAC_ADDR_LENGTH; ++i) { bind.chaddr[i] = testMac2[i]; } + + EXPECT_EQ(RET_ERROR, AddBinding(NULL)); EXPECT_EQ(RET_SUCCESS, AddBinding(&bind)); EXPECT_EQ(RET_FAILED, AddBinding(&bind)); + EXPECT_TRUE(memset_s(bind.chaddr, sizeof(bind.chaddr), 0, sizeof(bind.chaddr)) == EOK); EXPECT_EQ(RET_SUCCESS, RemoveBinding(testMac1)); EXPECT_EQ(RET_SUCCESS, RemoveBinding(testMac2)); } +HWTEST_F(DhcpAddressPoolTest, AddNewBindingTest, TestSize.Level1) +{ + uint8_t testMac1[DHCP_HWADDR_LENGTH] = {0x00, 0x0e, 0x3c, 0x65, 0x3a, 0x09, 0}; + ASSERT_TRUE(testPool.newBinding != NULL); + ASSERT_TRUE(testPool.newBinding(testMac1, NULL) != NULL); + EXPECT_EQ(RET_SUCCESS, RemoveBinding(testMac1)); +} + +HWTEST_F(DhcpAddressPoolTest, FindBindingByIpTest, TestSize.Level1) +{ + AddressBinding bind = {0}; + uint8_t testMac1[DHCP_HWADDR_LENGTH] = {0x00, 0x0e, 0x3c, 0x65, 0x3a, 0x09, 0}; + uint8_t testMac2[DHCP_HWADDR_LENGTH] = {0x00, 0x0e, 0x3c, 0x65, 0x3a, 0x0a, 0}; + uint32_t testIp1 = ParseIpAddr("192.168.100.1"); + uint32_t testIp2 = ParseIpAddr("192.168.100.2"); + bind.ipAddress = testIp1; + for (int i = 0; i < MAC_ADDR_LENGTH; ++i) { + bind.chaddr[i] = testMac1[i]; + } + EXPECT_EQ(RET_SUCCESS, AddBinding(&bind)); + bind.ipAddress = testIp2; + for (int i = 0; i < MAC_ADDR_LENGTH; ++i) { + bind.chaddr[i] = testMac2[i]; + } + EXPECT_EQ(RET_SUCCESS, AddBinding(&bind)); + EXPECT_EQ(RET_FAILED, AddBinding(&bind)); + + AddressBinding *pBind1 = FindBindingByIp(testIp1); + AddressBinding *pBind2 = FindBindingByIp(testIp2); + EXPECT_TRUE(pBind1 != NULL); + EXPECT_TRUE(pBind2 != NULL); + if (pBind1 != NULL) { + EXPECT_EQ(testIp1, pBind1->ipAddress); + } + EXPECT_EQ(RET_SUCCESS, RemoveBinding(testMac1)); + EXPECT_EQ(RET_SUCCESS, RemoveBinding(testMac2)); +} + +HWTEST_F(DhcpAddressPoolTest, AddressDistributeTest, TestSize.Level1) +{ + uint8_t testMac1[DHCP_HWADDR_LENGTH] = {0x01, 0x0e, 0x3c, 0x65, 0x3a, 0x09, 0}; + uint8_t testMac2[DHCP_HWADDR_LENGTH] = {0x01, 0x0e, 0x3c, 0x65, 0x3a, 0x0a, 0}; + uint8_t testMac3[DHCP_HWADDR_LENGTH] = {0x01, 0x0e, 0x3c, 0x65, 0x3a, 0x09, 0}; + + EXPECT_TRUE(testPool.distribue(NULL, testMac1) == 0); + EXPECT_TRUE(testPool.distribue(&testPool, testMac1) == 0); + ASSERT_TRUE(SamplePoolConfig()); + SetDistributeMode(0); + EXPECT_EQ(0, GetDistributeMode()); + uint32_t assertAddr = ParseIpAddr("192.168.100.101"); + EXPECT_EQ(assertAddr, testPool.distribue(&testPool, testMac1)); + assertAddr = ParseIpAddr("192.168.100.102"); + EXPECT_EQ(assertAddr, testPool.distribue(&testPool, testMac2)); + assertAddr = ParseIpAddr("192.168.100.103"); + EXPECT_EQ(assertAddr, testPool.distribue(&testPool, testMac3)); +} + HWTEST_F(DhcpAddressPoolTest, IsReservedTest, TestSize.Level1) { AddressBinding bind = {0}; @@ -91,6 +181,7 @@ HWTEST_F(DhcpAddressPoolTest, IsReservedTest, TestSize.Level1) bind.chaddr[i] = testMac2[i]; } EXPECT_EQ(RET_SUCCESS, AddReservedBinding(testMac2)); + EXPECT_EQ(RET_SUCCESS, AddReservedBinding(testMac2)); EXPECT_EQ(RET_FAILED, AddBinding(&bind)); EXPECT_EQ(0, IsReserved(testMac1)); EXPECT_EQ(1, IsReserved(testMac2)); @@ -126,6 +217,8 @@ HWTEST_F(DhcpAddressPoolTest, IsReservedIpTest, TestSize.Level1) EXPECT_EQ(RET_SUCCESS, AddLease(&testPool, &bind)); EXPECT_EQ(0, IsReservedIp(&testPool, testIp1)); EXPECT_EQ(1, IsReservedIp(&testPool, testIp2)); + EXPECT_EQ(DHCP_FALSE, IsReservedIp(NULL, testIp1)); + EXPECT_EQ(DHCP_FALSE, IsReservedIp(&testPool, 0)); bind.ipAddress = testIp1; EXPECT_EQ(RET_SUCCESS, RemoveLease(&testPool, &bind)); bind.ipAddress = testIp2; @@ -138,6 +231,7 @@ HWTEST_F(DhcpAddressPoolTest, RemoveReservedBindingTest, TestSize.Level1) uint8_t testMac1[DHCP_HWADDR_LENGTH] = {0x00, 0x01, 0x3c, 0x65, 0x3a, 0x09, 0}; uint8_t testMac2[DHCP_HWADDR_LENGTH] = {0x00, 0x02, 0x3c, 0x65, 0x3a, 0x0a, 0}; uint8_t testMac3[DHCP_HWADDR_LENGTH] = {0x00, 0x03, 0x3c, 0x65, 0x3a, 0x0b, 0}; + uint8_t testMac4[DHCP_HWADDR_LENGTH] = {0x00, 0x03, 0x3c, 0x65, 0x3a, 0x0c, 0}; uint32_t testIp1 = ParseIpAddr("192.168.100.1"); EXPECT_TRUE(testIp1 != 0); uint32_t testIp2 = ParseIpAddr("192.168.100.2"); @@ -158,7 +252,9 @@ HWTEST_F(DhcpAddressPoolTest, RemoveReservedBindingTest, TestSize.Level1) AddressBinding *binding = QueryBinding(testMac2, NULL); ASSERT_TRUE(binding != NULL); EXPECT_EQ(RET_SUCCESS, RemoveReservedBinding(testMac2)); + EXPECT_EQ(RET_FAILED, RemoveReservedBinding(testMac2)); EXPECT_EQ(RET_FAILED, RemoveReservedBinding(testMac3)); + EXPECT_EQ(RET_FAILED, RemoveReservedBinding(testMac4)); } HWTEST_F(DhcpAddressPoolTest, ReleaseBindingTest, TestSize.Level1) @@ -193,8 +289,8 @@ HWTEST_F(DhcpAddressPoolTest, AddLeaseTest, TestSize.Level1) AddressBinding lease = {0}; lease.bindingMode = BIND_MODE_DYNAMIC; lease.bindingStatus = BIND_ASSOCIATED; - uint8_t testMac1[DHCP_HWADDR_LENGTH] = {0x00, 0x0e, 0x3c, 0x65, 0x3a, 0x09, 0}; - uint8_t testMac2[DHCP_HWADDR_LENGTH] = {0x00, 0x0e, 0x3d, 0x65, 0x3a, 0x09, 0}; + uint8_t testMac1[DHCP_HWADDR_LENGTH] = {0x01, 0x0e, 0x3c, 0x65, 0x3a, 0x09, 0}; + uint8_t testMac2[DHCP_HWADDR_LENGTH] = {0x01, 0x0e, 0x3d, 0x65, 0x3a, 0x0a, 0}; uint32_t testIp1 = ParseIpAddr("192.168.100.101"); ASSERT_TRUE(testIp1 != 0); lease.ipAddress = testIp1; @@ -208,6 +304,8 @@ HWTEST_F(DhcpAddressPoolTest, AddLeaseTest, TestSize.Level1) for (int i = 0; i < MAC_ADDR_LENGTH; ++i) { lease.chaddr[i] = testMac2[i]; } + EXPECT_EQ(RET_ERROR, AddLease(NULL, &lease)); + EXPECT_EQ(RET_ERROR, AddLease(&testPool, NULL)); EXPECT_EQ(RET_SUCCESS, AddLease(&testPool, &lease)); EXPECT_EQ(RET_SUCCESS, RemoveLease(&testPool, &lease)); } @@ -217,9 +315,11 @@ HWTEST_F(DhcpAddressPoolTest, GetLeaseTest, TestSize.Level1) AddressBinding lease = {0}; lease.bindingMode = BIND_MODE_DYNAMIC; lease.bindingStatus = BIND_ASSOCIATED; - uint8_t testMac1[DHCP_HWADDR_LENGTH] = {0x00, 0x0e, 0x3c, 0x65, 0x3a, 0x09, 0}; + uint8_t testMac1[DHCP_HWADDR_LENGTH] = {0x01, 0x0e, 0x3c, 0x65, 0x3a, 0x09, 0}; uint32_t testIp1 = ParseIpAddr("192.168.100.101"); + uint32_t testIp2 = ParseIpAddr("192.168.100.110"); ASSERT_TRUE(testIp1 != 0); + ASSERT_TRUE(testIp2 != 0); lease.ipAddress = testIp1; lease.leaseTime = DHCP_LEASE_TIME; lease.pendingTime = 1631240659; @@ -229,6 +329,9 @@ HWTEST_F(DhcpAddressPoolTest, GetLeaseTest, TestSize.Level1) } EXPECT_EQ(RET_SUCCESS, AddLease(&testPool, &lease)); EXPECT_EQ(RET_SUCCESS, AddLease(&testPool, &lease)); + EXPECT_EQ(NULL, GetLease(&testPool, 0)); + EXPECT_EQ(NULL, GetLease(NULL, testIp1)); + EXPECT_EQ(NULL, GetLease(&testPool, testIp2)); AddressBinding *leaseRec = GetLease(&testPool, testIp1); ASSERT_TRUE(leaseRec != NULL); EXPECT_EQ(lease.ipAddress, leaseRec->ipAddress); @@ -243,9 +346,11 @@ HWTEST_F(DhcpAddressPoolTest, UpdateLeaseTest, TestSize.Level1) AddressBinding lease = {0}; lease.bindingMode = BIND_MODE_DYNAMIC; lease.bindingStatus = BIND_ASSOCIATED; - uint8_t testMac1[DHCP_HWADDR_LENGTH] = {0x00, 0x0e, 0x3c, 0x65, 0x3a, 0x09, 0}; + uint8_t testMac1[DHCP_HWADDR_LENGTH] = {0x01, 0x0e, 0x3c, 0x65, 0x3a, 0x09, 0}; uint32_t testIp1 = ParseIpAddr("192.168.100.101"); + uint32_t testIp2 = ParseIpAddr("192.168.100.110"); ASSERT_TRUE(testIp1 != 0); + ASSERT_TRUE(testIp2 != 0); lease.ipAddress = testIp1; lease.leaseTime = DHCP_LEASE_TIME; lease.pendingTime = 1631240659; @@ -265,6 +370,11 @@ HWTEST_F(DhcpAddressPoolTest, UpdateLeaseTest, TestSize.Level1) EXPECT_EQ(RET_SUCCESS, UpdateLease(&testPool, &lease)); EXPECT_EQ(lease.leaseTime, leaseRec->leaseTime); EXPECT_EQ(lease.leaseTime, leaseRec->leaseTime); + EXPECT_EQ(RET_ERROR, UpdateLease(NULL, &lease)); + EXPECT_EQ(RET_ERROR, UpdateLease(&testPool, NULL)); + lease.ipAddress = testIp2; + EXPECT_EQ(RET_FAILED, UpdateLease(&testPool, &lease)); + lease.ipAddress = testIp1; EXPECT_EQ(RET_SUCCESS, RemoveLease(&testPool, &lease)); } @@ -284,9 +394,9 @@ HWTEST_F(DhcpAddressPoolTest, LoadBindingRecodersTest, TestSize.Level1) lease.pendingTime = 1631260680; lease.bindingTime = 1631260680; - uint8_t testMac1[DHCP_HWADDR_LENGTH] = {0x00, 0x0e, 0x3c, 0x65, 0x3a, 0x09, 0}; - uint8_t testMac2[DHCP_HWADDR_LENGTH] = {0x00, 0x0e, 0x3c, 0x65, 0x3a, 0x0a, 0}; - uint8_t testMac3[DHCP_HWADDR_LENGTH] = {0x00, 0x0e, 0x3c, 0x65, 0x3a, 0x0b, 0}; + uint8_t testMac1[DHCP_HWADDR_LENGTH] = {0x01, 0x0e, 0x3c, 0x65, 0x3a, 0x09, 0}; + uint8_t testMac2[DHCP_HWADDR_LENGTH] = {0x01, 0x0e, 0x3c, 0x65, 0x3a, 0x0a, 0}; + uint8_t testMac3[DHCP_HWADDR_LENGTH] = {0x01, 0x0e, 0x3c, 0x65, 0x3a, 0x0b, 0}; lease.ipAddress = testIp1; for (int i = 0; i < MAC_ADDR_LENGTH; ++i) { lease.chaddr[i] = testMac1[i]; @@ -306,25 +416,111 @@ HWTEST_F(DhcpAddressPoolTest, LoadBindingRecodersTest, TestSize.Level1) EXPECT_EQ(RET_SUCCESS, SaveBindingRecoders(&testPool, 1)); EXPECT_EQ(HASH_SUCCESS, ClearAll(&testPool.leaseTable)); EXPECT_TRUE(testPool.leaseTable.size == 0); + EXPECT_EQ(RET_FAILED, LoadBindingRecoders(NULL)); EXPECT_EQ(RET_SUCCESS, LoadBindingRecoders(&testPool)); EXPECT_TRUE(testPool.leaseTable.size == 3); EXPECT_TRUE(GetLease(&testPool, testIp1) != NULL); EXPECT_TRUE(GetLease(&testPool, testIp2) != NULL); EXPECT_TRUE(GetLease(&testPool, testIp3) != NULL); + EXPECT_EQ(HASH_SUCCESS, ClearAll(&testPool.leaseTable)); } -HWTEST_F(DhcpAddressPoolTest, GetBindingByMacTest, TestSize.Level1) + +extern "C" int CheckRangeAvailability( + DhcpAddressPool *pool, uint8_t macAddr[DHCP_HWADDR_LENGTH], uint32_t distIp, int *outOfRange); + +HWTEST_F(DhcpAddressPoolTest, CheckRangeAvailabilityTest, TestSize.Level1) +{ + uint8_t testMac1[DHCP_HWADDR_LENGTH] = {0x01, 0x0e, 0x3c, 0x65, 0x3a, 0x09, 0}; + uint8_t testMac2[DHCP_HWADDR_LENGTH] = {0x01, 0x0e, 0x3c, 0x65, 0x3a, 0x0a, 0}; + uint8_t testMac3[DHCP_HWADDR_LENGTH] = {0x01, 0x0e, 0x3c, 0x65, 0x3b, 0x0b, 0}; + uint8_t testMac4[DHCP_HWADDR_LENGTH] = {0}; + + uint32_t testIp1 = ParseIpAddr("192.168.100.101"); + uint32_t testIp2 = ParseIpAddr("192.168.100.102"); + uint32_t testIp3 = ParseIpAddr("192.168.100.3"); + + int outOfRange = 0; + EXPECT_EQ(RET_ERROR, CheckRangeAvailability(NULL, testMac1, testIp1, &outOfRange)); + EXPECT_EQ(RET_ERROR, CheckRangeAvailability(&testPool, testMac1, testIp1, &outOfRange)); + EXPECT_TRUE(SamplePoolConfig()); + EXPECT_EQ(RET_ERROR, CheckRangeAvailability(&testPool, testMac4, testIp1, &outOfRange)); + EXPECT_EQ(0, outOfRange); + EXPECT_EQ(RET_SUCCESS, CheckRangeAvailability(&testPool, testMac1, testIp1, &outOfRange)); + EXPECT_EQ(0, outOfRange); + EXPECT_EQ(RET_SUCCESS, CheckRangeAvailability(&testPool, testMac2, testIp2, &outOfRange)); + EXPECT_EQ(0, outOfRange); + EXPECT_EQ(RET_FAILED, CheckRangeAvailability(&testPool, testMac3, testIp3, &outOfRange)); + EXPECT_EQ(1, outOfRange); + + + +} + +extern "C" int CheckIpAvailability(DhcpAddressPool *pool, uint8_t macAddr[DHCP_HWADDR_LENGTH], uint32_t distIp); +HWTEST_F(DhcpAddressPoolTest, CheckIpAvailabilityTest, TestSize.Level1) { AddressBinding lease = {0}; + lease.bindingMode = BIND_MODE_DYNAMIC; + lease.bindingStatus = BIND_ASSOCIATED; + uint8_t testMac1[DHCP_HWADDR_LENGTH] = {0x0d, 0x0a, 0x3c, 0x65, 0x3a, 0x09, 0}; + uint8_t testMac2[DHCP_HWADDR_LENGTH] = {0x0d, 0x0a, 0x3d, 0x65, 0x3a, 0x0a, 0}; + uint8_t testMac3[DHCP_HWADDR_LENGTH] = {0x0d, 0x0a, 0x3d, 0x65, 0x3a, 0x0b, 0}; uint32_t testIp1 = ParseIpAddr("192.168.100.101"); + uint32_t testIp2 = ParseIpAddr("192.168.100.102"); + uint32_t testIp3 = ParseIpAddr("192.168.150.103"); ASSERT_TRUE(testIp1 != 0); + ASSERT_TRUE(testIp2 != 0); + ASSERT_TRUE(testIp3 != 0); + lease.ipAddress = testIp1; + lease.leaseTime = DHCP_LEASE_TIME; + lease.pendingTime = 1631240659; + lease.bindingTime = 1631240659; + for (int i = 0; i < MAC_ADDR_LENGTH; ++i) { + lease.chaddr[i] = testMac1[i]; + } + lease.bindingMode = BIND_MODE_DYNAMIC; + lease.bindingStatus = BIND_ASSOCIATED; + EXPECT_EQ(RET_SUCCESS, AddBinding(&lease)); + ASSERT_EQ(RET_SUCCESS, AddLease(&testPool, &lease)); + EXPECT_EQ(DHCP_TRUE, CheckIpAvailability(&testPool, testMac1, testIp1)); + AddressBinding *pLease = GetLease(&testPool, testIp1); + ASSERT_TRUE(pLease != NULL); + pLease->bindingMode = BIND_MODE_STATIC; + EXPECT_EQ(DHCP_FALSE, CheckIpAvailability(&testPool, testMac2, testIp1)); + pLease->bindingMode = BIND_MODE_DYNAMIC; + + for (int i = 0; i < MAC_ADDR_LENGTH; ++i) { + lease.chaddr[i] = testMac2[i]; + } + lease.ipAddress = testIp2; + lease.bindingMode = BIND_MODE_RESERVED; + EXPECT_EQ(RET_SUCCESS, AddBinding(&lease)); + EXPECT_EQ(RET_SUCCESS, AddLease(&testPool, &lease)); + EXPECT_EQ(DHCP_FALSE, CheckIpAvailability(&testPool, testMac2, testIp2)); + + EXPECT_TRUE(SamplePoolConfig()); + EXPECT_EQ(DHCP_FALSE, CheckIpAvailability(NULL, testMac1, testIp1)); + EXPECT_EQ(DHCP_FALSE, CheckIpAvailability(&testPool, testMac3, testIp1)); + + pLease->pendingTime = Tmspsec() - DHCP_LEASE_TIME - 2600; + pLease->bindingTime = pLease->pendingTime; + EXPECT_EQ(DHCP_TRUE, CheckIpAvailability(&testPool, testMac3, testIp1)); +} + +extern "C" AddressBinding *GetBindingByMac(HashTable *bindTable, uint8_t macAddr[DHCP_HWADDR_LENGTH]); + +HWTEST_F(DhcpAddressPoolTest, GetBindingByMacTest, TestSize.Level1) +{ + AddressBinding lease = {0}; + uint32_t testIp1 = ParseIpAddr("192.168.100.101"); + ASSERT_TRUE(testIp1 != 0); lease.bindingMode = BIND_MODE_DYNAMIC; lease.bindingStatus = BIND_ASSOCIATED; lease.pendingTime = 1631260680; lease.bindingTime = 1631260680; - uint8_t testMac1[DHCP_HWADDR_LENGTH] = {0x00, 0x0e, 0x3c, 0x65, 0x3a, 0x09, 0}; - + uint8_t testMac1[DHCP_HWADDR_LENGTH] = {0x01, 0x0e, 0x3c, 0x65, 0x3a, 0x09, 0}; lease.ipAddress = testIp1; for (int i = 0; i < MAC_ADDR_LENGTH; ++i) { lease.chaddr[i] = testMac1[i]; @@ -332,9 +528,79 @@ HWTEST_F(DhcpAddressPoolTest, GetBindingByMacTest, TestSize.Level1) ASSERT_EQ(RET_SUCCESS, AddBinding(&lease)); AddressBinding *binding = QueryBinding(testMac1, 0); ASSERT_TRUE(binding != NULL); + HashTable tempTable = {0}; + EXPECT_TRUE(GetBindingByMac(NULL, testMac1) == NULL); + EXPECT_TRUE(GetBindingByMac(&tempTable, testMac1) == NULL); EXPECT_EQ(lease.ipAddress, binding->ipAddress); EXPECT_EQ(lease.leaseTime, binding->leaseTime); EXPECT_EQ(lease.bindingMode, binding->bindingMode); EXPECT_EQ(lease.bindingStatus, binding->bindingStatus); + EXPECT_EQ(RET_SUCCESS, RemoveBinding(testMac1)); } +HWTEST_F(DhcpAddressPoolTest, GetBindingByIpTest, TestSize.Level1) +{ + AddressBinding lease = {0}; + uint32_t testIp1 = ParseIpAddr("192.168.100.101"); + ASSERT_TRUE(testIp1 != 0); + lease.bindingMode = BIND_MODE_DYNAMIC; + lease.bindingStatus = BIND_ASSOCIATED; + lease.pendingTime = 1631260680; + lease.bindingTime = 1631260680; + uint8_t testMac1[DHCP_HWADDR_LENGTH] = {0x01, 0x0e, 0x3c, 0x65, 0x3a, 0x09, 0}; + lease.ipAddress = testIp1; + for (int i = 0; i < MAC_ADDR_LENGTH; ++i) { + lease.chaddr[i] = testMac1[i]; + } + ASSERT_EQ(RET_SUCCESS, AddLease(&testPool, &lease)); + + HashTable tempTable = {0}; + EXPECT_TRUE(GetBindingByIp(NULL, testIp1) == NULL); + EXPECT_TRUE(GetBindingByIp(&tempTable, testIp1) == NULL); + AddressBinding *pLease = GetLease(&testPool, testIp1); + ASSERT_TRUE(pLease != NULL); + EXPECT_EQ(lease.ipAddress, pLease->ipAddress); + EXPECT_EQ(lease.leaseTime, pLease->leaseTime); + EXPECT_EQ(lease.bindingMode, pLease->bindingMode); + EXPECT_EQ(lease.bindingStatus, pLease->bindingStatus); +} + +HWTEST_F(DhcpAddressPoolTest, InitAddressPoolTest, TestSize.Level1) +{ + DhcpAddressPool tempPool; + ASSERT_TRUE(memset_s(&tempPool, sizeof(DhcpAddressPool), 0, sizeof(DhcpAddressPool)) == EOK); + tempPool.fixedOptions.size = 100; + EXPECT_EQ(RET_ERROR, InitAddressPool(NULL, "test_if2", NULL)); + EXPECT_EQ(RET_SUCCESS, InitAddressPool(&tempPool, "test_if2", NULL)); + FreeAddressPool(NULL); + FreeAddressPool(&tempPool); +} + +extern "C" uint32_t NextIpOffset(uint32_t netmask); +HWTEST_F(DhcpAddressPoolTest, NextIpOffsetTest, TestSize.Level1) +{ + uint32_t netmask = ParseIpAddr("255.255.255.0"); + ASSERT_TRUE(netmask != 0); + SetDistributeMode(0); + EXPECT_TRUE(NextIpOffset(netmask) == 0); + SetDistributeMode(1); + usleep(10); + uint32_t nextOffset = NextIpOffset(netmask); + EXPECT_TRUE(nextOffset >= 0); + SetDistributeMode(0); +} + +HWTEST_F(DhcpAddressPoolTest, RemoveLeaseFailedTest, TestSize.Level1) +{ + AddressBinding lease = {0}; + uint32_t testIp1 = ParseIpAddr("192.168.100.110"); + ASSERT_TRUE(testIp1 != 0); + uint8_t testMac1[DHCP_HWADDR_LENGTH] = {0x00, 0x0e, 0x3c, 0x65, 0x3a, 0x09, 0}; + lease.ipAddress = testIp1; + for (int i = 0; i < MAC_ADDR_LENGTH; ++i) { + lease.chaddr[i] = testMac1[i]; + } + EXPECT_EQ(RET_ERROR, RemoveLease(NULL, &lease)); + EXPECT_EQ(RET_ERROR, RemoveLease(&testPool, NULL)); + EXPECT_EQ(RET_FAILED, RemoveLease(&testPool, &lease)); +} \ No newline at end of file diff --git a/tests/wifi_standard/wifi_framework/dhcp_manage/dhcp_server/unittest/dhcp_argument_test.cpp b/dhcp/test/services/dhcp_server/unittest/dhcp_argument_test.cpp similarity index 73% rename from tests/wifi_standard/wifi_framework/dhcp_manage/dhcp_server/unittest/dhcp_argument_test.cpp rename to dhcp/test/services/dhcp_server/unittest/dhcp_argument_test.cpp index 06c1d6be4878abe182e0448ac2eb6d7d354cc3da..9f406c3ad231e528307bc20c87e9dcfded551305 100644 --- a/tests/wifi_standard/wifi_framework/dhcp_manage/dhcp_server/unittest/dhcp_argument_test.cpp +++ b/dhcp/test/services/dhcp_server/unittest/dhcp_argument_test.cpp @@ -1,5 +1,5 @@ /* - * Copyright (C) 2021 Huawei Device Co., Ltd. + * Copyright (C) 2021-2022 Huawei Device Co., Ltd. * 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 @@ -20,9 +20,11 @@ #include #include #include "dhcp_argument.h" +#include "dhcp_define.h" using namespace testing::ext; + HWTEST(DhcpArgumentTest, InitArgumentsTest, TestSize.Level1) { EXPECT_TRUE(InitArguments() == RET_SUCCESS); @@ -30,13 +32,20 @@ HWTEST(DhcpArgumentTest, InitArgumentsTest, TestSize.Level1) HWTEST(DhcpArgumentTest, ParseArgumentsTest, TestSize.Level1) { + PrintRequiredArguments(); + ShowHelp(2); char *argv[ARGUMENT_VALUE_SIZE] = { const_cast(""), const_cast("--dns=192.168.1.1,192.168.1.2"), - const_cast("--ifname=eth0") + const_cast("--ifname=eth0"), + const_cast("--gateway=192.168.1.1"), + const_cast("--pool=192.168.1.100,192.168.1.150"), + const_cast("--version"), + const_cast("--help"), + const_cast("--unknown"), }; - EXPECT_TRUE(ParseArguments(3, argv) == RET_SUCCESS); + EXPECT_TRUE(ParseArguments(8, argv) == RET_SUCCESS); ArgumentInfo *arg = GetArgument("dns"); EXPECT_TRUE(arg); EXPECT_EQ(strncmp(arg->name, "dns", strlen("dns")), 0); @@ -59,6 +68,11 @@ HWTEST(DhcpArgumentTest, PutArgumentTest, TestSize.Level1) val = "nothing"; EXPECT_TRUE(PutArgument(argu, val) == RET_SUCCESS); EXPECT_TRUE(PutArgument(argu, val) == RET_FAILED); + argu = "longlongvalue"; + val = "verylongvalueverylongvalueverylongvalueverylongvalueverylongvalueverylongvalueverylongvalueverylongvaluevery" + "longvalueverylongvalueverylongvalueverylongvalueverylongvalueverylongvalueverylongvalueverylongvalueverylongvaluev" + "erylongvalueverylongvalueverylongvalueverylongvalue"; + EXPECT_TRUE(PutArgument(argu, val) == RET_ERROR); } HWTEST(DhcpArgumentTest, GetArgumentTest, TestSize.Level1) @@ -80,4 +94,5 @@ HWTEST(DhcpArgumentTest, HasArgumentTest, TestSize.Level1) EXPECT_TRUE(HasArgument(name) == 0); name = "lease"; EXPECT_TRUE(HasArgument(name) == 1); + FreeArguments(); } diff --git a/tests/wifi_standard/wifi_framework/dhcp_manage/dhcp_server/unittest/dhcp_binding_test.cpp b/dhcp/test/services/dhcp_server/unittest/dhcp_binding_test.cpp similarity index 98% rename from tests/wifi_standard/wifi_framework/dhcp_manage/dhcp_server/unittest/dhcp_binding_test.cpp rename to dhcp/test/services/dhcp_server/unittest/dhcp_binding_test.cpp index 3a1db4307baa9ff59f4c64ae0dff3f30d008311e..5a1827d7904307ea689fe8ec57fa085abc35587c 100644 --- a/tests/wifi_standard/wifi_framework/dhcp_manage/dhcp_server/unittest/dhcp_binding_test.cpp +++ b/dhcp/test/services/dhcp_server/unittest/dhcp_binding_test.cpp @@ -1,5 +1,5 @@ /* - * Copyright (C) 2021 Huawei Device Co., Ltd. + * Copyright (C) 2021-2022 Huawei Device Co., Ltd. * 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 @@ -17,6 +17,7 @@ #include #include #include "dhcp_binding.h" +#include "dhcp_define.h" #include "common_util.h" using namespace testing::ext; diff --git a/tests/wifi_standard/wifi_framework/dhcp_manage/dhcp_server/unittest/dhcp_config_test.cpp b/dhcp/test/services/dhcp_server/unittest/dhcp_config_test.cpp similarity index 100% rename from tests/wifi_standard/wifi_framework/dhcp_manage/dhcp_server/unittest/dhcp_config_test.cpp rename to dhcp/test/services/dhcp_server/unittest/dhcp_config_test.cpp diff --git a/tests/wifi_standard/wifi_framework/dhcp_manage/dhcp_server/unittest/dhcp_message_sim.cpp b/dhcp/test/services/dhcp_server/unittest/dhcp_message_sim.cpp similarity index 88% rename from tests/wifi_standard/wifi_framework/dhcp_manage/dhcp_server/unittest/dhcp_message_sim.cpp rename to dhcp/test/services/dhcp_server/unittest/dhcp_message_sim.cpp index 9717cfc8c64d216b903d090217c82063d4643af0..fb0549263af48f7f69aa647bdff7f29d407eb5cb 100644 --- a/tests/wifi_standard/wifi_framework/dhcp_manage/dhcp_server/unittest/dhcp_message_sim.cpp +++ b/dhcp/test/services/dhcp_server/unittest/dhcp_message_sim.cpp @@ -26,6 +26,7 @@ #include "dhcp_ipv4.h" #include "address_utils.h" #include "securec.h" +#include "common_util.h" #define OPT_MESSAGE_TYPE_LEGTH 1 #define OPT_HEADER_LENGTH 2 @@ -75,11 +76,27 @@ int DhcpMsgManager::RecvTotal() return total; } +bool DhcpMsgManager::FrontSendMsg(DhcpMessage *msg) +{ + int retval = false; + if (!msg) { + return retval; + } + m_sendQueueLocker.lock(); + if (!m_sendMessages.empty()) { + DhcpMessage fmsg = m_sendMessages.front(); + if (memcpy_s(msg, sizeof(DhcpMessage), &fmsg, sizeof(DhcpMessage)) == EOK) { + retval = true; + } + } + m_sendQueueLocker.unlock(); + return retval; +} void DhcpMsgManager::PopSendMsg() { m_sendQueueLocker.lock(); - if (!m_sendMessages.empty()) { + if (m_sendMessages.size() > 0) { m_sendMessages.pop(); } m_sendQueueLocker.unlock(); @@ -110,6 +127,15 @@ int DhcpMsgManager::PushRecvMsg(const DhcpMessage &msg) return 1; } +void DhcpMsgManager::SetClientIp(uint32_t ipAddr) +{ + m_clientIpAddress = ipAddr; +} +uint32_t DhcpMsgManager::GetClientIp() const +{ + return m_clientIpAddress; +} + struct DhcpClientContext { int clientFd; @@ -158,7 +184,9 @@ int FillHwAddr(uint8_t *dst, size_t dsize, uint8_t *src, size_t ssize) struct sockaddr_in *SetDestinationAddr(uint32_t ipAddress) { struct sockaddr_in *destAddr = DestinationAddr(); - destAddr->sin_addr.s_addr = htons(ipAddress); + if (destAddr != nullptr) { + destAddr->sin_addr.s_addr = htons(ipAddress); + } return destAddr; } @@ -197,11 +225,11 @@ DhcpClientContext *InitialDhcpClient(DhcpClientConfig *config) return context; } -static int ParseDhcpOptions(PDhcpMsgInfo msg) +int ParseDhcpOptions(PDhcpMsgInfo msg) { int ret; PDhcpOptionNode pNode = msg->options.first->next; - DhcpOption endOpt = {END_OPTION, 0}; + DhcpOption endOpt = {END_OPTION, 0, {0}}; PushBackOption(&msg->options, &endOpt); int replyOptsLength = 0; uint8_t *current = msg->packet.options, olen = MAGIC_COOKIE_LENGTH; @@ -240,7 +268,6 @@ static int ParseDhcpOptions(PDhcpMsgInfo msg) return ret; } - int SendDhcpMessage(DhcpClientContext *ctx, PDhcpMsgInfo msg) { if (!ctx || !msg) { @@ -264,7 +291,7 @@ static uint32_t GetXid(int update) return currXid; } -static int InitMessage(DhcpClientContext *ctx, PDhcpMsgInfo msg, uint8_t msgType) +int InitMessage(DhcpClientContext *ctx, PDhcpMsgInfo msg, uint8_t msgType) { LOGD("init dhcp message..."); if (!ctx) { @@ -294,9 +321,21 @@ static int InitMessage(DhcpClientContext *ctx, PDhcpMsgInfo msg, uint8_t msgType } else { msg->packet.xid = GetXid(DHCP_FALSE); } + + if (DhcpMsgManager::GetInstance().GetClientIp() != 0) { + DhcpOption optReqIp = {REQUESTED_IP_ADDRESS_OPTION, 0, {0}}; + AppendAddressOption(&optReqIp, DhcpMsgManager::GetInstance().GetClientIp()); + PushFrontOption(&msg->options, &optReqIp); + } + DhcpOption optMsgType = {DHCP_MESSAGE_TYPE_OPTION, OPT_MESSAGE_TYPE_LEGTH, {msgType, 0}}; PushFrontOption(&msg->options, &optMsgType); + PDhcpOption pEndOpt = GetOption(&msg->options, END_OPTION); + if (pEndOpt == NULL) { + DhcpOption endOpt = {END_OPTION, 0, {0}}; + PushBackOption(&msg->options, &endOpt); + } return DHCP_TRUE; } diff --git a/tests/wifi_standard/wifi_framework/dhcp_manage/dhcp_server/unittest/dhcp_message_sim.h b/dhcp/test/services/dhcp_server/unittest/dhcp_message_sim.h similarity index 84% rename from tests/wifi_standard/wifi_framework/dhcp_manage/dhcp_server/unittest/dhcp_message_sim.h rename to dhcp/test/services/dhcp_server/unittest/dhcp_message_sim.h index 1335bad5e55a24db589a0daad04ddbe5845eaf6a..030b1c5259b7aa21f9780cf6e7058f71669c30d0 100644 --- a/tests/wifi_standard/wifi_framework/dhcp_manage/dhcp_server/unittest/dhcp_message_sim.h +++ b/dhcp/test/services/dhcp_server/unittest/dhcp_message_sim.h @@ -15,6 +15,7 @@ #include #include +#include "dhcp_define.h" #include "dhcp_message.h" #ifndef OHOS_DHCP_MESSAGE_SIM_H @@ -40,7 +41,12 @@ public: int PushRecvMsg(const DhcpMessage &msg); void PopSendMsg(); + + bool FrontSendMsg(DhcpMessage *msg); void PopRecvMsg(); + + void SetClientIp(uint32_t ipAddr); + uint32_t GetClientIp() const; private: DhcpMsgManager(){}; ~DhcpMsgManager(){}; @@ -49,6 +55,7 @@ private: std::queue m_recvMessages; std::mutex m_sendQueueLocker; std::queue m_sendMessages; + uint32_t m_clientIpAddress = 0; }; } // namespace Wifi } // namespace OHOS @@ -69,7 +76,7 @@ DhcpClientContext *InitialDhcpClient(DhcpClientConfig *config); int *StatrDhcpClient(DhcpClientContext *config); -int SendDhcpMessage(DhcpClientContext *ctx, PDhcpMsgInfo *msg); +int SendDhcpMessage(DhcpClientContext *ctx, PDhcpMsgInfo msg); int DhcpDiscover(DhcpClientContext *ctx); @@ -86,6 +93,9 @@ int StopDhcpClient(DhcpClientContext *ctx); int GetDhcpClinetState(DhcpClientContext *ctx); int FreeDhcpClient(DhcpClientContext *ctx); +int InitMessage(DhcpClientContext *ctx, PDhcpMsgInfo msg, uint8_t msgType); int FillHwAddr(uint8_t *dst, size_t dsize, uint8_t *src, size_t ssize); +int ParseDhcpOptions(PDhcpMsgInfo msg); +int ParseReceivedOptions(PDhcpMsgInfo msg); #endif \ No newline at end of file diff --git a/tests/wifi_standard/wifi_framework/dhcp_manage/dhcp_server/unittest/dhcp_option_test.cpp b/dhcp/test/services/dhcp_server/unittest/dhcp_option_test.cpp similarity index 76% rename from tests/wifi_standard/wifi_framework/dhcp_manage/dhcp_server/unittest/dhcp_option_test.cpp rename to dhcp/test/services/dhcp_server/unittest/dhcp_option_test.cpp index 28cc6bc930f9557d4a337748a29055147b58d237..43073da0509f7be505a37f14e7667ae438937d4c 100644 --- a/tests/wifi_standard/wifi_framework/dhcp_manage/dhcp_server/unittest/dhcp_option_test.cpp +++ b/dhcp/test/services/dhcp_server/unittest/dhcp_option_test.cpp @@ -16,7 +16,6 @@ #include #include #include -#include "string_ex.h" #include "dhcp_define.h" #include "dhcp_ipv4.h" #include "dhcp_message.h" @@ -42,12 +41,12 @@ public: FreeOptionList(&options); } public: - DhcpOptionList options; + DhcpOptionList options = {0}; }; HWTEST_F(DhcpOptionTest, InitOptionListTest, TestSize.Level1) { - DhcpOptionList testOpts; + DhcpOptionList testOpts = {0}; EXPECT_EQ(RET_SUCCESS, InitOptionList(&testOpts)); FreeOptionList(&testOpts); EXPECT_EQ(RET_SUCCESS, InitOptionList(&options)); @@ -56,8 +55,11 @@ HWTEST_F(DhcpOptionTest, InitOptionListTest, TestSize.Level1) HWTEST_F(DhcpOptionTest, HasInitializedTest, TestSize.Level1) { DhcpOptionList testOpts = {0}; + EXPECT_EQ(0, HasInitialized(NULL)); EXPECT_EQ(0, HasInitialized(&testOpts)); - EXPECT_EQ(1, HasInitialized(&options)); + ASSERT_EQ(RET_SUCCESS, InitOptionList(&testOpts)); + EXPECT_EQ(1, HasInitialized(&testOpts)); + FreeOptionList(&testOpts); } HWTEST_F(DhcpOptionTest, PushBackOptionTest, TestSize.Level1) @@ -66,6 +68,8 @@ HWTEST_F(DhcpOptionTest, PushBackOptionTest, TestSize.Level1) EXPECT_EQ(RET_SUCCESS, PushBackOption(&options, &optRouter)); DhcpOption optMsgType = {DHCP_MESSAGE_TYPE_OPTION, 1, {DHCPOFFER, 0}}; + EXPECT_EQ(RET_ERROR, PushBackOption(NULL, &optMsgType)); + EXPECT_EQ(RET_ERROR, PushBackOption(&options, NULL)); EXPECT_EQ(RET_SUCCESS, PushBackOption(&options, &optMsgType)); EXPECT_TRUE(options.size == 2); ClearOptions(&options); @@ -78,6 +82,8 @@ HWTEST_F(DhcpOptionTest, PushFrontOptionTest, TestSize.Level1) EXPECT_EQ(RET_SUCCESS, PushFrontOption(&options, &optRouter)); DhcpOption optMsgType = {DHCP_MESSAGE_TYPE_OPTION, 1, {DHCPOFFER, 0}}; + EXPECT_EQ(RET_ERROR, PushFrontOption(NULL, &optMsgType)); + EXPECT_EQ(RET_ERROR, PushFrontOption(&options, NULL)); EXPECT_EQ(RET_SUCCESS, PushFrontOption(&options, &optMsgType)); EXPECT_TRUE(options.size == 2); ClearOptions(&options); @@ -112,10 +118,26 @@ HWTEST_F(DhcpOptionTest, GetOptionTest, TestSize.Level1) EXPECT_TRUE(options.size == 0); } + +HWTEST_F(DhcpOptionTest, RemoveOptionTest, TestSize.Level1) +{ + DhcpOption optRouter = {ROUTER_OPTION, 0, {0}}; + EXPECT_EQ(RET_SUCCESS, PushFrontOption(&options, &optRouter)); + EXPECT_TRUE(options.size == 1); + EXPECT_EQ(RET_ERROR, RemoveOption(NULL, DOMAIN_NAME_SERVER_OPTION)); + EXPECT_EQ(RET_FAILED, RemoveOption(&options, DOMAIN_NAME_SERVER_OPTION)); + EXPECT_EQ(RET_SUCCESS, RemoveOption(&options, ROUTER_OPTION)); + EXPECT_EQ(RET_FAILED, RemoveOption(&options, ROUTER_OPTION)); + EXPECT_TRUE(options.size == 0); + ClearOptions(&options); +} + HWTEST_F(DhcpOptionTest, FillOptionTest, TestSize.Level1) { const char *serverInfo = "dhcp server 1.0"; DhcpOption optVendorInfo = {VENDOR_SPECIFIC_INFO_OPTION, 0, {0}}; + EXPECT_EQ(RET_FAILED, FillOption(&optVendorInfo, NULL, 0)); + EXPECT_EQ(RET_ERROR, FillOption(NULL, serverInfo, strlen(serverInfo))); EXPECT_EQ(RET_SUCCESS, FillOption(&optVendorInfo, serverInfo, strlen(serverInfo))); } @@ -123,6 +145,8 @@ HWTEST_F(DhcpOptionTest, FillOptionDataTest, TestSize.Level1) { uint8_t testData[] = {192, 168, 100, 254}; DhcpOption optRouter = {ROUTER_OPTION, 0, {0}}; + EXPECT_EQ(RET_ERROR, FillOptionData(NULL, testData, sizeof(testData))); + EXPECT_EQ(RET_FAILED, FillOptionData(&optRouter, NULL, sizeof(testData))); EXPECT_EQ(RET_SUCCESS, FillOptionData(&optRouter, testData, sizeof(testData))); } @@ -132,6 +156,7 @@ HWTEST_F(DhcpOptionTest, FillU32OptionTest, TestSize.Level1) EXPECT_TRUE(testIp != 0); DhcpOption optRouter = {ROUTER_OPTION, 0, {0}}; EXPECT_EQ(RET_SUCCESS, FillU32Option(&optRouter, testIp)); + EXPECT_EQ(RET_ERROR, FillU32Option(NULL, testIp)); } HWTEST_F(DhcpOptionTest, AppendAddressOptionTest, TestSize.Level1) @@ -144,6 +169,7 @@ HWTEST_F(DhcpOptionTest, AppendAddressOptionTest, TestSize.Level1) EXPECT_TRUE(testDns3 != 0); DhcpOption optDns = {DOMAIN_NAME_SERVER_OPTION, 0, {0}}; + EXPECT_EQ(RET_ERROR, AppendAddressOption(NULL, testDns1)); EXPECT_EQ(RET_SUCCESS, AppendAddressOption(&optDns, testDns1)); EXPECT_EQ(RET_SUCCESS, AppendAddressOption(&optDns, testDns2)); EXPECT_EQ(RET_SUCCESS, AppendAddressOption(&optDns, testDns3)); diff --git a/dhcp/test/services/dhcp_server/unittest/dhcp_server_test.cpp b/dhcp/test/services/dhcp_server/unittest/dhcp_server_test.cpp new file mode 100644 index 0000000000000000000000000000000000000000..d2417bed467fa1158b819c9cab79f3f298145ee0 --- /dev/null +++ b/dhcp/test/services/dhcp_server/unittest/dhcp_server_test.cpp @@ -0,0 +1,794 @@ +/* + * Copyright (C) 2021-2022 Huawei Device Co., Ltd. + * 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 "dhcp_server.h" +#include "address_utils.h" +#include "dhcp_config.h" +#include "dhcp_option.h" +#include "dhcp_logger.h" +#include "system_func_mock.h" +#include "dhcp_message_sim.h" +#include "dhcp_ipv4.h" +#include "common_util.h" +#include "securec.h" + +using namespace testing::ext; +using namespace std; +using namespace OHOS::Wifi; + +#undef LOG_TAG +#define LOG_TAG "DhcpServerTest" + + +static const int SERVER_RUNING_TIME = 10; // the value is in units of seconds. + +struct ServerContext { + int broadCastFlagEnable; + DhcpAddressPool addressPool; + DhcpServerCallback callback; + DhcpConfig config; + int serverFd; + int looperState; + int initialized; +}; + +class DhcpServerTest : public testing::Test { +public: + static void SetUpTestCase() + {} + static void TearDownTestCase() + {} + virtual void SetUp() + {} + virtual void TearDown() + { + SystemFuncMock::GetInstance().SetMockFlag(false); + } + + int InitServerConfig(DhcpConfig *config); + int FreeServerConfig(DhcpConfig *config); + int TestDhcpRequest(uint32_t testIp, uint32_t srvId); + int TestDhcpRequestByMac(uint32_t testIp, uint32_t srvId, uint8_t *macAddr); + int TestDhcpRelease(uint32_t testIp, uint32_t srvId); + int InitDhcpRequests(); + int InitDhcpErrorRequests(); + bool InitBindingRecodersTest(); + bool FixedOptionsTest(); + int InitDhcpClient(); + bool ServerRun(void); + bool StartServerTest(); + void DelayStopServer(); + +private: + DhcpServerContext *m_pServerCtx = nullptr; + DhcpConfig m_serverConfg; + thread delayStopTh; + + DhcpClientContext *m_pMockClient = nullptr; + DhcpClientConfig m_clientConfg; +}; + +int DhcpServerTest::InitServerConfig(DhcpConfig *config) +{ + if (!config) { + return RET_FAILED; + } + const char* testIfaceName = "test_if0"; + uint32_t serverId = ParseIpAddr("192.168.189.254"); + uint32_t netmask = ParseIpAddr("255.255.255.0"); + uint32_t beginIp = ParseIpAddr("192.168.189.100"); + uint32_t endIp = ParseIpAddr("192.168.189.200"); + if (serverId == 0 || netmask == 0 || beginIp == 0 || endIp == 0) { + printf("failed to parse address.\n"); + return RET_FAILED; + } + if (memset_s(config, sizeof(DhcpConfig), 0, sizeof(DhcpConfig)) != EOK) { + return RET_FAILED; + } + if (memset_s(config->ifname, sizeof(config->ifname), '\0', sizeof(config->ifname)) != EOK) { + return RET_FAILED; + } + if (strncpy_s(config->ifname, sizeof(config->ifname), testIfaceName, strlen(testIfaceName)) != EOK) { + return RET_FAILED; + } + config->serverId = serverId; + config->netmask = netmask; + config->pool.beginAddress = beginIp; + config->pool.endAddress = endIp; + config->broadcast = 1; + if (InitOptionList(&config->options) != RET_SUCCESS) { + return RET_FAILED; + } + return RET_SUCCESS; +} + +extern "C" void InitBindingRecoders(DhcpAddressPool *pool); +bool DhcpServerTest::InitBindingRecodersTest() +{ + if (!m_pServerCtx) { + return false; + } + ServerContext *srvIns = (ServerContext *)m_pServerCtx->instance; + + AddressBinding bind = {0}; + bind.bindingMode = BIND_MODE_DYNAMIC; + uint8_t testMac1[DHCP_HWADDR_LENGTH] = {0x00, 0x0e, 0x3c, 0x65, 0x3a, 0x09, 0}; + uint32_t testIp1 = ParseIpAddr("192.168.189.101"); + bind.ipAddress = testIp1; + for (int i = 0; i < MAC_ADDR_LENGTH; ++i) { + bind.chaddr[i] = testMac1[i]; + } + if (AddLease(&srvIns->addressPool, &bind) != RET_SUCCESS) { + LOGE("failed to add lease recoder."); + return false; + } + + uint8_t testMac5[DHCP_HWADDR_LENGTH] = {0x00, 0x0e, 0x3c, 0x65, 0x3a, 0x0e, 0}; + uint32_t testIp5 = ParseIpAddr("192.168.189.130"); + bind.ipAddress = testIp5; + bind.bindingMode = BIND_MODE_DYNAMIC; + for (int i = 0; i < MAC_ADDR_LENGTH; ++i) { + bind.chaddr[i] = testMac5[i]; + } + bind.expireIn = Tmspsec(); + bind.bindingTime = bind.expireIn - DHCP_LEASE_TIME; + if (AddLease(&srvIns->addressPool, &bind) != RET_SUCCESS) { + LOGE("failed to add lease recoder."); + return false; + } + + uint8_t testMac6[DHCP_HWADDR_LENGTH] = {0x00, 0xae, 0x3c, 0x65, 0x3a, 0x0e, 0}; + uint32_t testIp6 = ParseIpAddr("192.168.189.118"); + bind.ipAddress = testIp6; + bind.bindingMode = BIND_MODE_DYNAMIC; + for (int i = 0; i < MAC_ADDR_LENGTH; ++i) { + bind.chaddr[i] = testMac6[i]; + } + bind.expireIn = Tmspsec(); + bind.bindingTime = bind.expireIn - DHCP_LEASE_TIME; + if (AddLease(&srvIns->addressPool, &bind) != RET_SUCCESS) { + LOGE("failed to add lease recoder."); + return false; + } + srvIns->addressPool.leaseTime = DHCP_LEASE_TIME; + srvIns->addressPool.renewalTime = DHCP_RENEWAL_TIME; + InitBindingRecoders(nullptr); + DhcpAddressPool pool; + if (memset_s(&pool, sizeof(DhcpAddressPool), 0, sizeof(DhcpAddressPool)) != EOK) { + return false; + } + InitBindingRecoders(&pool); + InitBindingRecoders(&srvIns->addressPool); + return true; +} + + +bool DhcpServerTest::FixedOptionsTest() +{ + const char *serverVendorId = "ohos-dhcp-server"; + DhcpOption optVendorId = {VENDOR_CLASS_IDENTIFIER_OPTION, 0, {0}}; + if (FillOption(&optVendorId, serverVendorId, strlen(serverVendorId)) != RET_SUCCESS) { + return false; + } + if (PushBackOption(&m_serverConfg.options, &optVendorId) != RET_SUCCESS) { + return false; + } + return true; +} + +static int TestServerCallback(int state, int code, const char *ifname) +{ + int ret = 0; + switch (state) { + case ST_STARTING: { + if (code == 0) { + LOGD(" callback[%s] ==> server starting ...", ifname); + } else if (code == 1) { + LOGD(" callback[%s] ==> server started.", ifname); + } else if (code == NUM_TWO) { + LOGD(" callback[%s] ==> server start failed.", ifname); + } + break; + } + case ST_RELOADNG: { + LOGD(" callback[%s] ==> reloading ...", ifname); + break; + } + case ST_STOPED: { + LOGD(" callback[%s] ==> server stopped.", ifname); + break; + } + default: + break; + } + return ret; +} + +bool DhcpServerTest::ServerRun(void) +{ + LOGD("begin test start dhcp server."); + int retval = true; + EXPECT_CALL(SystemFuncMock::GetInstance(), socket(_, _, _)).WillRepeatedly(Return(1)); + EXPECT_CALL(SystemFuncMock::GetInstance(), setsockopt(_, _, _, _, _)).WillRepeatedly(Return(0)); + EXPECT_CALL(SystemFuncMock::GetInstance(), select(_, _, _, _, _)).WillRepeatedly(Return(0)); + EXPECT_CALL(SystemFuncMock::GetInstance(), bind(_, _, _)).WillRepeatedly(Return(0)); + EXPECT_CALL(SystemFuncMock::GetInstance(), sendto(_, _, _, _, _, _)).WillRepeatedly(Return(sizeof(DhcpMessage))); + EXPECT_CALL(SystemFuncMock::GetInstance(), recvfrom(_, _, _, _, _, _)).WillRepeatedly(Return(0)); + EXPECT_CALL(SystemFuncMock::GetInstance(), close(_)).WillRepeatedly(Return(0)); + + m_pServerCtx = InitializeServer(&m_serverConfg); + if (!m_pServerCtx) { + LOGE("failed to initialized dhcp server context."); + retval = false; + } + if (!InitBindingRecodersTest()) { + LOGE("failed to initialize binding recoders."); + retval = false; + } + RegisterDhcpCallback(m_pServerCtx, TestServerCallback); + if (StartDhcpServer(nullptr) != RET_FAILED) { + LOGE("failed to start dhcp server. \n"); + retval = false; + } + DhcpServerContext tempCtx; + memset_s(&tempCtx, sizeof(DhcpServerContext), 0, sizeof(DhcpServerContext)); + memset_s(tempCtx.ifname, sizeof(tempCtx.ifname), '\0', sizeof(tempCtx.ifname)); + if (StartDhcpServer(&tempCtx) != RET_FAILED) { + LOGE("failed to start dhcp server. \n"); + retval = false; + } + strcpy_s(tempCtx.ifname, sizeof(tempCtx.ifname), "test_if1"); + if (StartDhcpServer(&tempCtx) != RET_FAILED) { + LOGE("failed to start dhcp server. \n"); + retval = false; + } + if (m_pServerCtx && StartDhcpServer(m_pServerCtx) != RET_SUCCESS) { + LOGE("failed to start dhcp server. \n"); + retval = false; + } + if (SaveLease(m_pServerCtx) != RET_SUCCESS) { + retval = false; + } + if (m_pServerCtx) { + FreeServerContext(&m_pServerCtx); + } + return retval; +} + +bool DhcpServerTest::StartServerTest() +{ + bool retval = true; + LOGI("start dhcp server test..."); + if (InitServerConfig(&m_serverConfg) != RET_SUCCESS) { + LOGE("failed to initialized dhcp server config."); + retval = false; + } + if (!FixedOptionsTest()) { + LOGE("failed to initialized fixed options."); + retval = false; + } + delayStopTh = std::thread(std::bind(&DhcpServerTest::DelayStopServer, this)); + delayStopTh.detach(); + if (InitDhcpClient() != RET_SUCCESS) { + retval = false; + } + LOGI("wait for test completed..."); + retval = ServerRun(); + return retval; +} + +void DhcpServerTest::DelayStopServer() +{ + const int SLEEP_TIME = 3; + const int SLEEP_TIME1 = 1; + const int SLEEP_TIME2 = 1; + LOGI("wait for dhcp server stopped..."); + LOGI("wait %d seconds...\n", SERVER_RUNING_TIME); + EXPECT_CALL(SystemFuncMock::GetInstance(), close(_)).WillRepeatedly(Return(0)); + std::this_thread::sleep_for(std::chrono::seconds(SLEEP_TIME)); + if (m_pServerCtx && m_pServerCtx->instance) { + ServerContext *srvIns = (ServerContext *)m_pServerCtx->instance; + srvIns->looperState = SLEEP_TIME; + } + std::this_thread::sleep_for(std::chrono::seconds(SERVER_RUNING_TIME)); + if (StopDhcpServer(m_pServerCtx) != RET_SUCCESS) { + LOGE("failed to stop dhcp server."); + return; + } + int waitSesc = 0; + while (waitSesc < SERVER_RUNING_TIME) { + if (GetServerStatus(m_pServerCtx) == ST_STOPED) { + LOGI("dhcp server stopped."); + break; + } else { + std::this_thread::sleep_for(std::chrono::seconds(SLEEP_TIME1)); + waitSesc++; + } + } + std::this_thread::sleep_for(std::chrono::seconds(SLEEP_TIME2)); +} + +int DhcpServerTest::TestDhcpRequest(uint32_t testIp, uint32_t srvId) +{ + return TestDhcpRequestByMac(testIp, srvId, nullptr); +} + +int DhcpServerTest::TestDhcpRequestByMac(uint32_t testIp, uint32_t srvId, uint8_t *macAddr) +{ + DhcpMsgInfo msgInfo = {{0}, 0, {0}}; + InitOptionList(&msgInfo.options); + if (!InitMessage(m_pMockClient, &msgInfo, DHCPREQUEST)) { + LOGE("failed to init dhcp message."); + FreeOptionList(&msgInfo.options); + return RET_FAILED; + } + RemoveOption(&msgInfo.options, END_OPTION); + if (srvId != 0) { + DhcpOption optSrvId = {SERVER_IDENTIFIER_OPTION, 0, {0}}; + AppendAddressOption(&optSrvId, srvId); + PushFrontOption(&msgInfo.options, &optSrvId); + } + DhcpOption optReqIp = {REQUESTED_IP_ADDRESS_OPTION, 0, {0}}; + AppendAddressOption(&optReqIp, testIp); + PushBackOption(&msgInfo.options, &optReqIp); + DhcpOption endOpt = {END_OPTION, 0, {0}}; + PushBackOption(&msgInfo.options, &endOpt); + msgInfo.packet.ciaddr = testIp; + if (macAddr != nullptr) { + if (!FillHwAddr(msgInfo.packet.chaddr, DHCP_HWADDR_LENGTH, macAddr, MAC_ADDR_LENGTH)) { + return DHCP_FALSE; + } + } + if (SendDhcpMessage(m_pMockClient, &msgInfo) != RET_SUCCESS) { + LOGE("failed to send dhcp message."); + FreeOptionList(&msgInfo.options); + return RET_FAILED; + } + FreeOptionList(&msgInfo.options); + return RET_SUCCESS; +} + +int DhcpServerTest::TestDhcpRelease(uint32_t testIp, uint32_t srvId) +{ + DhcpMsgInfo msgInfo = {{0}, 0, {0}}; + InitOptionList(&msgInfo.options); + if (!InitMessage(m_pMockClient, &msgInfo, DHCPRELEASE)) { + LOGE("failed to init dhcp message."); + FreeOptionList(&msgInfo.options); + return RET_FAILED; + } + RemoveOption(&msgInfo.options, END_OPTION); + if (srvId != 0) { + DhcpOption optSrvId = {SERVER_IDENTIFIER_OPTION, 0, {0}}; + AppendAddressOption(&optSrvId, srvId); + PushBackOption(&msgInfo.options, &optSrvId); + } + DhcpOption optReqIp = {REQUESTED_IP_ADDRESS_OPTION, 0, {0}}; + AppendAddressOption(&optReqIp, testIp); + PushBackOption(&msgInfo.options, &optReqIp); + msgInfo.packet.ciaddr = testIp; + + DhcpOption endOpt = {END_OPTION, 0, {0}}; + PushBackOption(&msgInfo.options, &endOpt); + if (SendDhcpMessage(m_pMockClient, &msgInfo) != RET_SUCCESS) { + LOGE("failed to send dhcp message."); + FreeOptionList(&msgInfo.options); + return RET_FAILED; + } + FreeOptionList(&msgInfo.options); + return RET_SUCCESS; +} + +int DhcpServerTest::InitDhcpRequests() +{ + uint32_t testIp = ParseIpAddr("192.168.189.101"); + uint32_t srvId = ParseIpAddr("192.168.189.254"); + DhcpMsgManager::GetInstance().SetClientIp(testIp); + if (DhcpRequest(m_pMockClient) != RET_SUCCESS) { + LOGE("[InitDhcpRequests] DhcpRequest failed"); + return RET_FAILED; + } + DhcpMsgManager::GetInstance().SetClientIp(0); + if (TestDhcpRequest(testIp, srvId) != RET_SUCCESS) { + LOGE("[InitDhcpRequests] TestDhcpRequest1 failed"); + return RET_FAILED; + } + testIp = ParseIpAddr("192.168.189.102"); + if (TestDhcpRequest(testIp, 0) != RET_SUCCESS) { + LOGE("[InitDhcpRequests] TestDhcpRequest2 failed"); + return RET_FAILED; + } + testIp = ParseIpAddr("192.168.189.120"); + uint8_t testMac1[DHCP_HWADDR_LENGTH] = {0x00, 0x0e, 0x3c, 0x65, 0x3a, 0x0a, 0}; + uint8_t testMac2[DHCP_HWADDR_LENGTH] = {0x00, 0x0e, 0x3c, 0x65, 0x3a, 0x0b, 0}; + uint8_t testMac3[DHCP_HWADDR_LENGTH] = {0x00, 0x0e, 0x3c, 0x65, 0x3a, 0x0c, 0}; + if (TestDhcpRequestByMac(testIp, srvId, testMac1) != RET_SUCCESS) { + LOGE("[InitDhcpRequests] TestDhcpRequestByMac1 failed"); + return RET_FAILED; + } + DhcpMsgManager::GetInstance().SetClientIp(testIp); + if (TestDhcpRequest(testIp, srvId) != RET_SUCCESS) { + LOGE("[InitDhcpRequests] TestDhcpRequest3 failed"); + return RET_FAILED; + } + testIp = ParseIpAddr("192.168.189.101"); + if (TestDhcpRequestByMac(testIp, srvId, testMac2) != RET_SUCCESS) { + LOGE("[InitDhcpRequests] TestDhcpRequestByMac2 failed"); + return RET_FAILED; + } + testIp = ParseIpAddr("192.168.189.120"); + DhcpMsgManager::GetInstance().SetClientIp(testIp); + if (TestDhcpRequestByMac(testIp, srvId, testMac3) != RET_SUCCESS) { + LOGE("[InitDhcpRequests] TestDhcpRequestByMac3 failed"); + return RET_FAILED; + } + DhcpMsgManager::GetInstance().SetClientIp(0); + uint8_t testMac4[DHCP_HWADDR_LENGTH] = {0x00, 0x0e, 0x3c, 0x65, 0x3a, 0x0d, 0}; + testIp = ParseIpAddr("192.168.190.210"); + if (TestDhcpRequestByMac(testIp, srvId, testMac4) != RET_SUCCESS) { + LOGE("[InitDhcpRequests] TestDhcpRequestByMac4 failed"); + return RET_FAILED; + } + uint8_t testMac5[DHCP_HWADDR_LENGTH] = {0x0a, 0x0e, 0x3c, 0x65, 0x3a, 0x0e, 0}; + testIp = ParseIpAddr("192.168.189.130"); + DhcpMsgManager::GetInstance().SetClientIp(testIp); + if (TestDhcpRequestByMac(testIp, srvId, testMac5) != RET_SUCCESS) { + LOGE("[InitDhcpRequests] TestDhcpRequestByMac5 failed"); + return RET_FAILED; + } + DhcpMsgManager::GetInstance().SetClientIp(0); + return RET_SUCCESS; +} + +int DhcpServerTest::InitDhcpErrorRequests() +{ + uint32_t srvId = ParseIpAddr("192.168.100.254"); + uint32_t testIp = ParseIpAddr("192.168.100.101"); + DhcpMsgInfo msgInfo = {{0}, 0, {0}}; + InitOptionList(&msgInfo.options); + if (!InitMessage(m_pMockClient, &msgInfo, DHCPREQUEST)) { + LOGE("failed to init dhcp message."); + FreeOptionList(&msgInfo.options); + return RET_FAILED; + } + + DhcpOption optReqIp = {REQUESTED_IP_ADDRESS_OPTION, 0, {0}}; + AppendAddressOption(&optReqIp, testIp); + PushFrontOption(&msgInfo.options, &optReqIp); + DhcpOption optSrvId = {SERVER_IDENTIFIER_OPTION, 0, {0}}; + AppendAddressOption(&optSrvId, srvId); + PushFrontOption(&msgInfo.options, &optSrvId); + if (SendDhcpMessage(m_pMockClient, &msgInfo) != RET_SUCCESS) { + LOGE("failed to send dhcp message."); + FreeOptionList(&msgInfo.options); + return RET_FAILED; + } + + RemoveOption(&msgInfo.options, DHCP_MESSAGE_TYPE_OPTION); + if (SendDhcpMessage(m_pMockClient, &msgInfo) != RET_SUCCESS) { + LOGE("failed to send dhcp message."); + FreeOptionList(&msgInfo.options); + return RET_FAILED; + } + + RemoveOption(&msgInfo.options, END_OPTION); + RemoveOption(&msgInfo.options, SERVER_IDENTIFIER_OPTION); + if (SendDhcpMessage(m_pMockClient, &msgInfo) != RET_SUCCESS) { + LOGE("failed to send dhcp message."); + FreeOptionList(&msgInfo.options); + return RET_FAILED; + } + return RET_SUCCESS; +} + +int DhcpServerTest::InitDhcpClient() +{ + uint8_t testMacAddr[DHCP_HWADDR_LENGTH] = {0x00, 0x0e, 0x3c, 0x65, 0x3a, 0x09, 0}; + + LOGI("init mock dhcp client."); + const char* testIfname = "test_if0"; + + if (memset_s(&m_clientConfg, sizeof(DhcpClientConfig), 0, sizeof(DhcpClientConfig)) != EOK) { + return RET_FAILED; + } + if (!FillHwAddr(m_clientConfg.chaddr, DHCP_HWADDR_LENGTH, testMacAddr, MAC_ADDR_LENGTH)) { + LOGE("FillHwAddr failed"); + return RET_FAILED; + } + if (memset_s(m_clientConfg.ifname, IFACE_NAME_SIZE, '\0', IFACE_NAME_SIZE) != EOK) { + return RET_FAILED; + } + if (memcpy_s(m_clientConfg.ifname, IFACE_NAME_SIZE, testIfname, strlen(testIfname)) != EOK) { + return RET_FAILED; + } + + m_pMockClient = InitialDhcpClient(&m_clientConfg); + if (!m_pMockClient) { + LOGE("[InitDhcpClient] InitialDhcpClient failed"); + return RET_FAILED; + } + if (DhcpDiscover(m_pMockClient) != RET_SUCCESS) { + LOGE("[InitDhcpClient] DhcpDiscover1 failed"); + return RET_FAILED; + } + uint32_t testIp = ParseIpAddr("192.168.189.102"); + uint32_t srvId = ParseIpAddr("192.168.189.254"); + DhcpMsgManager::GetInstance().SetClientIp(testIp); + if (DhcpDiscover(m_pMockClient) != RET_SUCCESS) { + LOGE("[InitDhcpClient] DhcpDiscover2 failed"); + return RET_FAILED; + } + InitDhcpRequests(); + InitDhcpErrorRequests(); + if (DhcpInform(m_pMockClient) != RET_SUCCESS) { + LOGE("[InitDhcpClient] DhcpInform1 failed"); + return RET_FAILED; + } + DhcpMsgManager::GetInstance().SetClientIp(testIp); + if (DhcpInform(m_pMockClient) != RET_SUCCESS) { + LOGE("[InitDhcpClient] DhcpInform2 failed"); + return RET_FAILED; + } + DhcpMsgManager::GetInstance().SetClientIp(0); + if (DhcpDecline(m_pMockClient) != RET_SUCCESS) { + LOGE("[InitDhcpClient] DhcpDecline1 failed"); + return RET_FAILED; + } + testIp = ParseIpAddr("192.168.189.118"); + DhcpMsgManager::GetInstance().SetClientIp(testIp); + if (DhcpDecline(m_pMockClient) != RET_SUCCESS) { + LOGE("[InitDhcpClient] DhcpDecline2 failed"); + return RET_FAILED; + } + DhcpMsgManager::GetInstance().SetClientIp(0); + if (DhcpRelease(m_pMockClient) != RET_SUCCESS) { + LOGE("[InitDhcpClient] DhcpRelease failed"); + return RET_FAILED; + } + testIp = ParseIpAddr("192.168.189.102"); + if (TestDhcpRelease(testIp, srvId)) { + LOGE("[InitDhcpClient] TestDhcpRelease failed"); + return RET_FAILED; + } + return RET_SUCCESS; +} + +int DhcpServerTest::FreeServerConfig(DhcpConfig *config) +{ + if (!config) { + return RET_FAILED; + } + FreeOptionList(&config->options); + return RET_SUCCESS; +} + +HWTEST_F(DhcpServerTest, InitializeServerTest, TestSize.Level1) +{ + SystemFuncMock::GetInstance().SetMockFlag(true); + EXPECT_CALL(SystemFuncMock::GetInstance(), socket(_, _, _)).WillRepeatedly(Return(1)); + EXPECT_CALL(SystemFuncMock::GetInstance(), setsockopt(_, _, _, _, _)).WillRepeatedly(Return(0)); + EXPECT_CALL(SystemFuncMock::GetInstance(), select(_, _, _, _, _)).WillRepeatedly(Return(0)); + EXPECT_CALL(SystemFuncMock::GetInstance(), recvfrom(_, _, _, _, _, _)).WillRepeatedly(Return(0)); + EXPECT_CALL(SystemFuncMock::GetInstance(), bind(_, _, _)).WillRepeatedly(Return(0)); + EXPECT_CALL(SystemFuncMock::GetInstance(), close(_)).WillRepeatedly(Return(0)); + DhcpConfig config; + PDhcpServerContext ctx = InitializeServer(nullptr); + EXPECT_TRUE(ctx == nullptr); + ASSERT_TRUE(memset_s(&config, sizeof(DhcpConfig), 0, sizeof(DhcpConfig)) == EOK); + ctx = InitializeServer(&config); + EXPECT_TRUE(ctx == nullptr); + EXPECT_TRUE(strcpy_s(config.ifname, sizeof(config.ifname), "test_if0") == EOK); + ctx = InitializeServer(&config); + EXPECT_TRUE(ctx == nullptr); + + EXPECT_EQ(RET_SUCCESS, InitServerConfig(&config)); + ctx = InitializeServer(&config); + ASSERT_TRUE(ctx != nullptr); + + EXPECT_EQ(RET_SUCCESS, FreeServerConfig(&config)); + EXPECT_EQ(RET_SUCCESS, FreeServerContext(&ctx)); +} + +extern "C" int InitServer(const char *ifname); + +HWTEST_F(DhcpServerTest, InitServerByIfaceTest, TestSize.Level1) +{ + const int SO_BROADCAST = 6; + const int SO_REUSEADDR = 2; + SystemFuncMock::GetInstance().SetMockFlag(true); + EXPECT_CALL(SystemFuncMock::GetInstance(), socket(_, _, _)) + .WillOnce(Return(-1)) + .WillRepeatedly(Return(1)); + EXPECT_CALL(SystemFuncMock::GetInstance(), setsockopt(_, _, SO_REUSEADDR, _, _)) + .WillOnce(Return(-1)) + .WillRepeatedly(Return(0)); + EXPECT_CALL(SystemFuncMock::GetInstance(), setsockopt(_, _, SO_BROADCAST, _, _)) + .WillOnce(Return(-1)) + .WillRepeatedly(Return(0)); + EXPECT_CALL(SystemFuncMock::GetInstance(), select(_, _, _, _, _)).WillRepeatedly(Return(0)); + EXPECT_CALL(SystemFuncMock::GetInstance(), recvfrom(_, _, _, _, _, _)).WillRepeatedly(Return(0)); + EXPECT_CALL(SystemFuncMock::GetInstance(), bind(_, _, _)) + .WillOnce(Return(-1)) + .WillRepeatedly(Return(0)); + EXPECT_CALL(SystemFuncMock::GetInstance(), close(_)).WillRepeatedly(Return(0)); + const char* ifaceName = "test_if01"; + EXPECT_EQ(-1, InitServer(ifaceName)); + EXPECT_EQ(-1, InitServer(ifaceName)); + EXPECT_EQ(-1, InitServer(ifaceName)); + EXPECT_EQ(1, InitServer(ifaceName)); +} + +HWTEST_F(DhcpServerTest, StartServerTest, TestSize.Level1) +{ + SystemFuncMock::GetInstance().SetMockFlag(true); + EXPECT_TRUE(StartServerTest()); +} + +HWTEST_F(DhcpServerTest, ReceiveDhcpMessageFailedTest, TestSize.Level1) +{ + SystemFuncMock::GetInstance().SetMockFlag(true); + ON_CALL(SystemFuncMock::GetInstance(), select(_, _, _, _, _)) + .WillByDefault(Return(0)); + ON_CALL(SystemFuncMock::GetInstance(), recvfrom(_, _, _, _, _, _)) + .WillByDefault(Return((int)sizeof(DhcpMsgInfo))); + DhcpMsgInfo msgInfo = {{0}, 0, {0}}; + uint8_t testMac1[DHCP_HWADDR_LENGTH] = {0x00, 0x0e, 0x3c, 0x65, 0x3a, 0x09, 0}; + + int ret = ReceiveDhcpMessage(1, &msgInfo); // failed to select isset. + EXPECT_TRUE(ret == RET_FAILED || ret == RET_ERROR); + ret = ReceiveDhcpMessage(1, &msgInfo); // message length error + EXPECT_TRUE(ret == RET_FAILED || ret == RET_ERROR); + ret = ReceiveDhcpMessage(1, &msgInfo); // dhcp message type error + EXPECT_TRUE(ret == RET_FAILED || ret == RET_ERROR); + msgInfo.packet.hlen = 128; + ret = ReceiveDhcpMessage(1, &msgInfo); // hlen error + EXPECT_TRUE(ret == RET_FAILED || ret == RET_ERROR); + msgInfo.packet.hlen = 16; + msgInfo.packet.op = BOOTREPLY; + ret = ReceiveDhcpMessage(1, &msgInfo); // client op type error + EXPECT_TRUE(ret == RET_FAILED || ret == RET_ERROR); + msgInfo.packet.op = BOOTREQUEST; + ret = ReceiveDhcpMessage(1, &msgInfo); // client hardware address error + EXPECT_TRUE(ret == RET_FAILED || ret == RET_ERROR); + for (int i = 0; i < MAC_ADDR_LENGTH; ++i) { + msgInfo.packet.chaddr[i] = testMac1[i]; + } + ret = ReceiveDhcpMessage(1, &msgInfo); + EXPECT_TRUE(ret == RET_FAILED || ret == RET_ERROR); +} + +extern "C" int FillReply(PDhcpServerContext ctx, PDhcpMsgInfo received, PDhcpMsgInfo reply); +HWTEST_F(DhcpServerTest, FillReplyFailedTest, TestSize.Level1) +{ + DhcpServerContext tempCtx; + ASSERT_TRUE(memset_s(&tempCtx, sizeof(DhcpServerContext), 0, sizeof(DhcpServerContext)) == EOK); + ASSERT_TRUE(memset_s(tempCtx.ifname, sizeof(tempCtx.ifname), '\0', sizeof(tempCtx.ifname)) == EOK); + DhcpMsgInfo recv, repl; + ASSERT_TRUE(memset_s(&recv, sizeof(DhcpMsgInfo), 0, sizeof(DhcpMsgInfo)) == EOK); + ASSERT_TRUE(memset_s(&repl, sizeof(DhcpMsgInfo), 0, sizeof(DhcpMsgInfo)) == EOK); + EXPECT_EQ(RET_ERROR, FillReply(&tempCtx, &recv, nullptr)); + EXPECT_EQ(RET_FAILED, FillReply(&tempCtx, &recv, &repl)); + recv.packet.flags = 1; + ServerContext srvInst; + ASSERT_TRUE(memset_s(&srvInst, sizeof(ServerContext), 0, sizeof(ServerContext)) == EOK); + tempCtx.instance = &srvInst; + recv.packet.siaddr = ParseIpAddr("192.168.189.252"); + srvInst.addressPool.gateway = ParseIpAddr("192.168.189.254"); + recv.packet.giaddr = ParseIpAddr("192.168.189.254"); + EXPECT_EQ(RET_SUCCESS, FillReply(&tempCtx, &recv, &repl)); + recv.packet.giaddr = 0; + EXPECT_EQ(RET_SUCCESS, FillReply(&tempCtx, &recv, &repl)); +} + +extern "C" int BindNetInterface(int fd, const char *ifname); +HWTEST_F(DhcpServerTest, BindNetInterfaceFailedTest, TestSize.Level1) +{ + SystemFuncMock::GetInstance().SetMockFlag(true); + EXPECT_CALL(SystemFuncMock::GetInstance(), setsockopt(_, _, _, _, _)) + .WillOnce(Return(-1)) + .WillOnce(Return(0)); + const char* ifaceName = "test_if01"; + EXPECT_EQ(RET_FAILED, BindNetInterface(1, nullptr)); + EXPECT_EQ(RET_FAILED, BindNetInterface(1, ifaceName)); + EXPECT_EQ(RET_SUCCESS, BindNetInterface(1, ifaceName)); +} + +extern "C" int AddReplyServerIdOption(PDhcpOptionList options, uint32_t serverId); +HWTEST_F(DhcpServerTest, AddReplyServerIdOptionFailedTest, TestSize.Level1) +{ + uint32_t srvId = ParseIpAddr("192.168.189.254"); + ASSERT_TRUE(srvId != 0); + DhcpOptionList opts; + ASSERT_TRUE(memset_s(&opts, sizeof(DhcpOptionList), '\0', sizeof(DhcpOptionList)) == EOK); + EXPECT_EQ(RET_FAILED, AddReplyServerIdOption(nullptr, 0)); + EXPECT_EQ(RET_FAILED, AddReplyServerIdOption(&opts, 0)); + + EXPECT_EQ(RET_SUCCESS, AddReplyServerIdOption(&opts, srvId)); + EXPECT_EQ(RET_SUCCESS, AddReplyServerIdOption(&opts, srvId)); +} + +extern "C" int InitServerFixedOptions(DhcpConfig *config, DhcpServerContext *ctx); +HWTEST_F(DhcpServerTest, InitServerFixedOptionsFailedTest, TestSize.Level1) +{ + DhcpServerContext tempCtx; + tempCtx.instance = nullptr; + ASSERT_TRUE(memset_s(&tempCtx, sizeof(DhcpServerContext), 0, sizeof(DhcpServerContext)) == EOK); + ASSERT_TRUE(memset_s(tempCtx.ifname, sizeof(tempCtx.ifname), '\0', sizeof(tempCtx.ifname)) == EOK); + DhcpConfig tempConfig; + ASSERT_TRUE(memset_s(&tempConfig, sizeof(DhcpConfig), 0, sizeof(DhcpConfig)) == EOK); + EXPECT_EQ(RET_FAILED, InitServerFixedOptions(nullptr, &tempCtx)); + EXPECT_EQ(RET_FAILED, InitServerFixedOptions(&tempConfig, &tempCtx)); + + ServerContext srvInst; + ASSERT_TRUE(memset_s(&srvInst, sizeof(ServerContext), 0, sizeof(ServerContext)) == EOK); + tempCtx.instance = &srvInst; + EXPECT_EQ(RET_FAILED, InitServerFixedOptions(&tempConfig, &tempCtx)); +} + + +extern "C" int AppendReplyTimeOptions(PDhcpServerContext ctx, PDhcpOptionList options); +HWTEST_F(DhcpServerTest, AppendReplyTimeOptionsFailedTest, TestSize.Level1) +{ + DhcpServerContext tempCtx; + tempCtx.instance = nullptr; + ASSERT_TRUE(memset_s(&tempCtx, sizeof(DhcpServerContext), 0, sizeof(DhcpServerContext)) == EOK); + ASSERT_TRUE(memset_s(tempCtx.ifname, sizeof(tempCtx.ifname), '\0', sizeof(tempCtx.ifname)) == EOK); + EXPECT_EQ(RET_FAILED, AppendReplyTimeOptions(nullptr, nullptr)); + EXPECT_EQ(RET_FAILED, AppendReplyTimeOptions(&tempCtx, nullptr)); +} + +HWTEST_F(DhcpServerTest, FreeServerContextFailedTest, TestSize.Level1) +{ + EXPECT_EQ(RET_FAILED, FreeServerContext(nullptr)); +} + +extern "C" AddressBinding *GetBinding(DhcpAddressPool *pool, PDhcpMsgInfo received); +HWTEST_F(DhcpServerTest, GetBindingFailedTest, TestSize.Level1) +{ + DhcpAddressPool tempPool; + DhcpMsgInfo msgInfo; + ASSERT_TRUE(memset_s(&tempPool, sizeof(DhcpAddressPool), 0, sizeof(DhcpAddressPool)) == EOK); + ASSERT_TRUE(memset_s(&msgInfo, sizeof(DhcpMsgInfo), 0, sizeof(DhcpMsgInfo)) == EOK); + EXPECT_TRUE(GetBinding(&tempPool, nullptr) == nullptr); + EXPECT_TRUE(GetBinding(nullptr, &msgInfo) == nullptr); + ASSERT_EQ(RET_SUCCESS, InitAddressPool(&tempPool, "test_if01", nullptr)); + EXPECT_TRUE(GetBinding(&tempPool, &msgInfo) != nullptr); + FreeAddressPool(&tempPool); +} + +extern "C" int SendDhcpReply(PDhcpServerContext ctx, int replyType, PDhcpMsgInfo reply); +HWTEST_F(DhcpServerTest, SendDhcpReplyTest, TestSize.Level1) +{ + DhcpServerContext tempCtx; + tempCtx.instance = nullptr; + ASSERT_TRUE(memset_s(&tempCtx, sizeof(DhcpServerContext), 0, sizeof(DhcpServerContext)) == EOK); + EXPECT_EQ(RET_FAILED, SendDhcpReply(&tempCtx, REPLY_NAK, nullptr)); + EXPECT_EQ(RET_FAILED, SendDhcpReply(nullptr, REPLY_NAK, nullptr)); +} + +HWTEST_F(DhcpServerTest, SaveLeaseFailedTest, TestSize.Level1) +{ + DhcpServerContext tempCtx; + tempCtx.instance = nullptr; + ASSERT_TRUE(memset_s(&tempCtx, sizeof(DhcpServerContext), 0, sizeof(DhcpServerContext)) == EOK); + EXPECT_EQ(RET_FAILED, SaveLease(nullptr)); + EXPECT_EQ(RET_FAILED, SaveLease(&tempCtx)); +} diff --git a/tests/wifi_standard/wifi_framework/dhcp_manage/dhcp_server/unittest/hash_table_test.cpp b/dhcp/test/services/dhcp_server/unittest/hash_table_test.cpp similarity index 91% rename from tests/wifi_standard/wifi_framework/dhcp_manage/dhcp_server/unittest/hash_table_test.cpp rename to dhcp/test/services/dhcp_server/unittest/hash_table_test.cpp index 7500b394ba3f68ba5ecea9196227c7cec8a0744f..5b503dd5a36d7465c7c1edaf5787d7c06cb1fab0 100644 --- a/tests/wifi_standard/wifi_framework/dhcp_manage/dhcp_server/unittest/hash_table_test.cpp +++ b/dhcp/test/services/dhcp_server/unittest/hash_table_test.cpp @@ -16,7 +16,6 @@ #include #include #include -#include "string_ex.h" #include "hash_table.h" using namespace testing::ext; @@ -164,4 +163,16 @@ HWTEST_F(HashTableTest, ResizeTest, TestSize.Level1) EXPECT_EQ(HASH_SUCCESS, Resize(&testTable, HASH_MINI_CAPACITY * 2)); EXPECT_TRUE(testTable.capacity == HASH_MINI_CAPACITY * 2); EXPECT_EQ(HASH_SUCCESS, DestroyHashTable(&testTable)); -} \ No newline at end of file +} + +extern "C" int CapExtend(HashTable *table, size_t miniCapacity); +HWTEST_F(HashTableTest, CapExtendTest, TestSize.Level1) +{ + HashTable testTable; + EXPECT_EQ(HASH_SUCCESS, CreateHashTable(&testTable, sizeof(uint32_t), + sizeof(uint32_t), HASH_MINI_CAPACITY)); + EXPECT_TRUE(testTable.capacity == HASH_MINI_CAPACITY); + EXPECT_EQ(HASH_SUCCESS, CapExtend(&testTable, HASH_MINI_CAPACITY * 5)); + EXPECT_TRUE(testTable.capacity == HASH_MINI_CAPACITY); + EXPECT_EQ(HASH_SUCCESS, DestroyHashTable(&testTable)); +} diff --git a/tests/wifi_standard/wifi_framework/dhcp_manage/dhcp_server/unittest/system_func_mock.cpp b/dhcp/test/services/dhcp_server/unittest/system_func_mock.cpp similarity index 52% rename from tests/wifi_standard/wifi_framework/dhcp_manage/dhcp_server/unittest/system_func_mock.cpp rename to dhcp/test/services/dhcp_server/unittest/system_func_mock.cpp index 6d5b8965935c7a9e57786835a88ffb1d8a8bf31e..ef0340dd3a4d9a256a710f88655da11be2960236 100644 --- a/tests/wifi_standard/wifi_framework/dhcp_manage/dhcp_server/unittest/system_func_mock.cpp +++ b/dhcp/test/services/dhcp_server/unittest/system_func_mock.cpp @@ -1,5 +1,5 @@ /* - * Copyright (C) 2021 Huawei Device Co., Ltd. + * Copyright (C) 2021-2022 Huawei Device Co., Ltd. * 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 @@ -14,22 +14,27 @@ */ #include "system_func_mock.h" +#include "address_utils.h" +#include "dhcp_define.h" +#include "dhcp_ipv4.h" +#include "dhcp_logger.h" +#include "dhcp_message.h" +#include "dhcp_message_sim.h" +#include "dhcp_option.h" +#include "securec.h" #include -#include #include #include -#include -#include "dhcp_logger.h" -#include "dhcp_message_sim.h" using namespace OHOS::Wifi; +#define MAGIC_COOKIE_LENGTH 4 +#define OPT_HEADER_LENGTH 2 +#define TIME_SEC_TO_USEC (1000 * 1000) + #undef LOG_TAG #define LOG_TAG "DhcpServerSystemFuncMock" -#define TIME_SEC_TO_USEC (1000 * 1000) -#define DHCP_SEL_WAIT_TIMEOUTS 1500 - static bool g_mockTag = false; SystemFuncMock &SystemFuncMock::GetInstance() @@ -38,11 +43,9 @@ SystemFuncMock &SystemFuncMock::GetInstance() return gSystemFuncMock; }; -SystemFuncMock::SystemFuncMock() -{} +SystemFuncMock::SystemFuncMock() {} -SystemFuncMock::~SystemFuncMock() -{} +SystemFuncMock::~SystemFuncMock() {} void SystemFuncMock::SetMockFlag(bool flag) { @@ -55,6 +58,17 @@ bool SystemFuncMock::GetMockFlag(void) } extern "C" { +struct in_addr { + uint32_t s_addr; +}; + +struct sockaddr_in { + short int sin_family; + unsigned short int sin_port; + struct in_addr sin_addr; + unsigned char sin_zero[8]; +}; + int __real_socket(int __domain, int __type, int __protocol); int __wrap_socket(int __domain, int __type, int __protocol) { @@ -62,6 +76,8 @@ int __wrap_socket(int __domain, int __type, int __protocol) if (g_mockTag) { LOGD(" ==>mock enable."); return SystemFuncMock::GetInstance().socket(__domain, __type, __protocol); + } else { + LOGD(" ==>mock disable."); } return __real_socket(__domain, __type, __protocol); } @@ -73,39 +89,48 @@ int __wrap_setsockopt(int __fd, int __level, int __optname, const void *__optval if (g_mockTag) { LOGD(" ==>mock enable."); return SystemFuncMock::GetInstance().setsockopt(__fd, __level, __optname, __optval, __optlen); + } else { + LOGD(" ==>mock disable."); } return __real_setsockopt(__fd, __level, __optname, __optval, __optlen); } + int __real_select(int __nfds, fd_set *__readfds, fd_set *__writefds, fd_set *__exceptfds, struct timeval *__timeout); int __wrap_select(int __nfds, fd_set *__readfds, fd_set *__writefds, fd_set *__exceptfds, struct timeval *__timeout) { + const unsigned int SLEEP_TIEM = 300000; LOGD("==>select."); if (g_mockTag) { LOGD(" ==>mock enable."); LOGD("message queue total: %d.", DhcpMsgManager::GetInstance().SendTotal()); if (DhcpMsgManager::GetInstance().SendTotal() > 0) { FD_CLR(__nfds, __readfds); + usleep(SLEEP_TIEM); return 1; } int retval = SystemFuncMock::GetInstance().select(__nfds, __readfds, __writefds, __exceptfds, __timeout); if (retval == 0) { - if (__timeout) { + if (__timeout != nullptr) { usleep(DHCP_SEL_WAIT_TIMEOUTS * 1000); LOGD("select time out."); } } return retval; + } else { + LOGD(" ==>mock disable."); } return __real_select(__nfds, __readfds, __writefds, __exceptfds, __timeout); } -int __real_bind(int __fd, struct sockaddr * __addr, socklen_t __len); -int __wrap_bind(int __fd, struct sockaddr * __addr, socklen_t __len) +int __real_bind(int __fd, struct sockaddr *__addr, socklen_t __len); +int __wrap_bind(int __fd, struct sockaddr *__addr, socklen_t __len) { LOGD("==>bind."); if (g_mockTag) { LOGD(" ==>mock enable."); return SystemFuncMock::GetInstance().bind(__fd, __addr, __len); + } else { + LOGD(" ==>mock disable."); } return __real_bind(__fd, __addr, __len); } @@ -117,39 +142,74 @@ int __wrap_close(int _fileno) if (g_mockTag) { LOGD(" ==>mock enable."); return SystemFuncMock::GetInstance().close(_fileno); + } else { + LOGD(" ==>mock disable."); } return __real_close(_fileno); } -ssize_t __real_sendto(int __fd, const void *__buf, size_t __n, int __flags, struct sockaddr *__addr, - socklen_t __addr_len); -ssize_t __wrap_sendto(int __fd, const void *__buf, size_t __n, int __flags, struct sockaddr *__addr, - socklen_t __addr_len) +ssize_t recvfrom(int __fd, void *__buf, size_t __n, int __flags, struct sockaddr *__addr, socklen_t *__addr_len) { - LOGD("==>sendto."); + LOGD("==>recvfrom."); if (g_mockTag) { LOGD(" ==>mock enable."); - return SystemFuncMock::GetInstance().sendto(__fd, __buf, __n, __flags, __addr, __addr_len); + if (DhcpMsgManager::GetInstance().SendTotal() > 0 && __buf) { + LOGD("== new message received."); + DhcpMessage msg = { 0 }; + if (DhcpMsgManager::GetInstance().FrontSendMsg(&msg)) { + (void)memcpy_s(__buf, __n, &msg, sizeof(DhcpMessage)); + DhcpMsgManager::GetInstance().PopSendMsg(); + uint32_t srcIp = DhcpMsgManager::GetInstance().GetClientIp(); + if (__addr != nullptr && srcIp != 0) { + struct sockaddr_in *sAddr = (struct sockaddr_in *)__addr; + sAddr->sin_addr.s_addr = HostToNetwork(srcIp); + DhcpMsgManager::GetInstance().SetClientIp(0); + } + return sizeof(DhcpMessage); + } + } + } else { + LOGD(" ==>mock disable."); } - return __real_sendto(__fd, __buf, __n, __flags, __addr, __addr_len); + return SystemFuncMock::GetInstance().recvfrom(__fd, __buf, __n, __flags, __addr, __addr_len); } -ssize_t __real_recvfrom(int __fd, void *__buf, size_t __n, int __flags, struct sockaddr *__addr, - socklen_t *__addr_len); +int ParseMockOptions(DhcpMessage *packet) +{ + if (packet == nullptr) { + LOGD("dhcp message pointer is null."); + return RET_FAILED; + } + DhcpMsgInfo reply; + if (memset_s(&reply, sizeof(DhcpMsgInfo), 0, sizeof(DhcpMsgInfo)) != EOK) { + LOGD("failed to reset dhcp message info."); + return RET_FAILED; + } + int retval = RET_FAILED; + if (memcpy_s(&reply.packet, sizeof(reply.packet), packet, sizeof(DhcpMessage)) != EOK) { + LOGD("failed to fill dhcp message."); + return RET_FAILED; + } + reply.length = sizeof(DhcpMessage); + if (InitOptionList(&reply.options) != RET_SUCCESS) { + LOGD("failed to init dhcp option list."); + return retval; + } + FreeOptionList(&reply.options); + return retval; +} -ssize_t __wrap_recvfrom(int __fd, void *__buf, size_t __n, int __flags, struct sockaddr *__addr, - socklen_t *__addr_len) +ssize_t sendto(int __fd, const void *__buf, size_t __n, int __flags, struct sockaddr *__addr, socklen_t __addr_len) { - LOGD("==>recvfrom."); + LOGD("==>sendto."); if (g_mockTag) { LOGD(" ==>mock enable."); - if (DhcpMsgManager::GetInstance().SendTotal() > 0) { - LOGD("== new message received."); - usleep(150 * 1000); - DhcpMsgManager::GetInstance().PopSendMsg(); + if (__buf == nullptr) { + return SystemFuncMock::GetInstance().sendto(__fd, __buf, __n, __flags, __addr, __addr_len); } - return SystemFuncMock::GetInstance().recvfrom(__fd, __buf, __n, __flags, __addr, __addr_len); + } else { + LOGD(" ==>mock disable."); } - return __real_recvfrom(__fd, __buf, __n, __flags, __addr, __addr_len); + return SystemFuncMock::GetInstance().sendto(__fd, __buf, __n, __flags, __addr, __addr_len); +} } -} \ No newline at end of file diff --git a/tests/wifi_standard/wifi_framework/dhcp_manage/dhcp_server/unittest/system_func_mock.h b/dhcp/test/services/dhcp_server/unittest/system_func_mock.h similarity index 95% rename from tests/wifi_standard/wifi_framework/dhcp_manage/dhcp_server/unittest/system_func_mock.h rename to dhcp/test/services/dhcp_server/unittest/system_func_mock.h index 65be403a82c72575e4bbd236db679526c7022730..29b044afa5777726688f23c9b6c353c1a54eb331 100644 --- a/tests/wifi_standard/wifi_framework/dhcp_manage/dhcp_server/unittest/system_func_mock.h +++ b/dhcp/test/services/dhcp_server/unittest/system_func_mock.h @@ -1,5 +1,5 @@ /* - * Copyright (C) 2021 Huawei Device Co., Ltd. + * Copyright (C) 2021-2022 Huawei Device Co., Ltd. * 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 @@ -20,9 +20,10 @@ #include #include #include -#include #include +typedef unsigned int socklen_t; + using ::testing::_; using ::testing::Return; @@ -35,6 +36,7 @@ public: MOCK_METHOD5(select, int(int __nfds, fd_set *__readfds, fd_set *__writefds, fd_set *__exceptfds, struct timeval *__timeout)); MOCK_METHOD3(bind, int(int __fd, struct sockaddr *__addr, socklen_t __len)); + MOCK_METHOD6(sendto, ssize_t(int __fd, const void *__buf, size_t __n, int __flags, struct sockaddr *__addr, socklen_t __addr_len)); MOCK_METHOD6(recvfrom, ssize_t(int __fd, void *__buf, size_t __n, int __flags, struct sockaddr *__addr, @@ -49,4 +51,4 @@ private: }; } // namespace Wifi } // namespace OHOS -#endif \ No newline at end of file +#endif diff --git a/tests/wifi_standard/wifi_framework/dhcp_manage/mgr_service/BUILD.gn b/dhcp/test/services/mgr_service/BUILD.gn similarity index 53% rename from tests/wifi_standard/wifi_framework/dhcp_manage/mgr_service/BUILD.gn rename to dhcp/test/services/mgr_service/BUILD.gn index 2e84991c9fc5925370b4e328b1fbb45f2a8f7fd8..f41a65f81b886f8819cb9529ed41d929fc39f07e 100644 --- a/tests/wifi_standard/wifi_framework/dhcp_manage/mgr_service/BUILD.gn +++ b/dhcp/test/services/mgr_service/BUILD.gn @@ -1,4 +1,4 @@ -# Copyright (C) 2021 Huawei Device Co., Ltd. +# Copyright (C) 2021-2022 Huawei Device Co., Ltd. # 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 @@ -12,32 +12,31 @@ # limitations under the License. import("//build/test.gni") -import("//foundation/appexecfwk/standard/appexecfwk.gni") +import("//foundation/communication/wifi/dhcp/dhcp.gni") ################################################################################ -SUBSYSTEM_DIR = "//foundation/communication" -module_output_path = "wifi_standard/dhcp_manage_test" +module_output_path = "dhcp/dhcp_manage_test" +even_path = "//base/notification/common_event_service" config("module_private_config") { visibility = [ ":*" ] include_dirs = [ - "//utils/native/base/include", - "$SUBSYSTEM_DIR/wifi/services/wifi_standard/wifi_framework/dhcp_manage/mgr_service/test", + "//commonlibrary/c_utils/base/include", + "$DHCP_ROOT_DIR/services/mgr_service/include", ] } ohos_unittest("dhcp_manage_unittest") { module_out_path = module_output_path sources = [ - "//foundation/communication/wifi/services/wifi_standard/wifi_framework/dhcp_manage/mgr_service/src/dhcp_client_service_impl.cpp", - "//foundation/communication/wifi/services/wifi_standard/wifi_framework/dhcp_manage/mgr_service/src/dhcp_event_subscriber.cpp", - "//foundation/communication/wifi/services/wifi_standard/wifi_framework/dhcp_manage/mgr_service/src/dhcp_func.cpp", - "//foundation/communication/wifi/services/wifi_standard/wifi_framework/dhcp_manage/mgr_service/src/dhcp_server_service.cpp", - "//foundation/communication/wifi/services/wifi_standard/wifi_framework/dhcp_manage/mgr_service/src/dhcp_service.cpp", + "$DHCP_ROOT_DIR/services/mgr_service/src/dhcp_client_service_impl.cpp", + "$DHCP_ROOT_DIR/services/mgr_service/src/dhcp_event_subscriber.cpp", + "$DHCP_ROOT_DIR/services/mgr_service/src/dhcp_func.cpp", + "$DHCP_ROOT_DIR/services/mgr_service/src/dhcp_server_service.cpp", + "$DHCP_ROOT_DIR/services/mgr_service/src/dhcp_service.cpp", "dhcp_client_service_test.cpp", "dhcp_func_test.cpp", - "dhcp_manage_test.cpp", "dhcp_result_notify.cpp", "dhcp_server_service_test.cpp", "dhcp_service_test.cpp", @@ -47,23 +46,21 @@ ohos_unittest("dhcp_manage_unittest") { include_dirs = [ "//third_party/googletest/googlemock/include", - "//foundation/communication/wifi/services/wifi_standard/wifi_framework/dhcp_manage/mgr_service/test", - "//foundation/communication/wifi/services/wifi_standard/wifi_framework/dhcp_manage/mgr_service/include", - "//foundation/communication/wifi/services/wifi_standard/wifi_framework/dhcp_manage/mgr_service/interfaces", - "//foundation/communication/wifi/services/wifi_standard/wifi_framework/common/log", - "//utils/native/base/include", - "//foundation/appexecfwk/standard/interfaces/innerkits/libeventhandler/include", + "$DHCP_ROOT_DIR/services/mgr_service/test", + "$DHCP_ROOT_DIR/services/mgr_service/include", + "$DHCP_ROOT_DIR/interfaces/inner_api/include", + "$DHCP_ROOT_DIR/interfaces/inner_api/interfaces", + "$WIFI_ROOT_DIR/services/wifi_standard/wifi_framework/wifi_toolkit/log", + "//commonlibrary/c_utils/base/include", "//foundation/communication/ipc/interfaces/innerkits/ipc_core/include", "${even_path}/cesfwk/kits/native/include", "${even_path}/cesfwk/innerkits/include", - "//base/notification/ces_standard/frameworks/core/include", + "//base/notification/common_event_service/frameworks/core/include", ] deps = [ - "${aafwk_path}/interfaces/innerkits/base:base", - "${aafwk_path}/interfaces/innerkits/want:want", "//third_party/googletest:gmock_main", - "//utils/native/base:utils", + "//third_party/googletest:gtest_main", ] ldflags = [ @@ -91,12 +88,16 @@ ohos_unittest("dhcp_manage_unittest") { ] external_deps = [ - "ces_standard:cesfwk_innerkits", + "ability_base:want", + "bundle_framework:appexecfwk_base", + "c_utils:utils", + "common_event_service:cesfwk_innerkits", + "eventhandler:libeventhandler", "hiviewdfx_hilog_native:libhilog", ] configs = [ ":module_private_config" ] - part_name = "wifi_standard" + part_name = "dhcp" subsystem_name = "communication" } diff --git a/tests/wifi_standard/wifi_framework/dhcp_manage/mgr_service/dhcp_client_service_test.cpp b/dhcp/test/services/mgr_service/dhcp_client_service_test.cpp similarity index 100% rename from tests/wifi_standard/wifi_framework/dhcp_manage/mgr_service/dhcp_client_service_test.cpp rename to dhcp/test/services/mgr_service/dhcp_client_service_test.cpp diff --git a/tests/wifi_standard/wifi_framework/dhcp_manage/mgr_service/dhcp_func_test.cpp b/dhcp/test/services/mgr_service/dhcp_func_test.cpp similarity index 96% rename from tests/wifi_standard/wifi_framework/dhcp_manage/mgr_service/dhcp_func_test.cpp rename to dhcp/test/services/mgr_service/dhcp_func_test.cpp index caa2122d8d8949c9afc04fa5aa7da87e36373c0f..ec9e5e039485609307b6ee7ccd3d8f9f769b980a 100644 --- a/tests/wifi_standard/wifi_framework/dhcp_manage/mgr_service/dhcp_func_test.cpp +++ b/dhcp/test/services/mgr_service/dhcp_func_test.cpp @@ -1,5 +1,5 @@ /* - * Copyright (C) 2021 Huawei Device Co., Ltd. + * Copyright (C) 2021-2022 Huawei Device Co., Ltd. * 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 @@ -221,14 +221,11 @@ HWTEST_F(DhcpFuncTest, InitPidfile_TEST, TestSize.Level1) MockSystemFunc::SetMockFlag(true); EXPECT_CALL(MockSystemFunc::GetInstance(), open(_, _)).WillOnce(Return(-1)).WillRepeatedly(Return(1)); - EXPECT_CALL(MockSystemFunc::GetInstance(), write(_, _, _)).WillOnce(Return(-1)).WillRepeatedly(Return(1)); EXPECT_CALL(MockSystemFunc::GetInstance(), close(_)).WillRepeatedly(Return(0)); pidDir = "./"; pidFile = "./wlan.pid"; EXPECT_EQ(DHCP_OPT_FAILED, DhcpFunc::InitPidfile(pidDir, pidFile)); - EXPECT_EQ(DHCP_OPT_FAILED, DhcpFunc::InitPidfile(pidDir, pidFile)); - EXPECT_EQ(DHCP_OPT_SUCCESS, DhcpFunc::InitPidfile(pidDir, pidFile)); MockSystemFunc::SetMockFlag(false); } diff --git a/tests/wifi_standard/wifi_framework/dhcp_manage/mgr_service/dhcp_result_notify.cpp b/dhcp/test/services/mgr_service/dhcp_result_notify.cpp similarity index 100% rename from tests/wifi_standard/wifi_framework/dhcp_manage/mgr_service/dhcp_result_notify.cpp rename to dhcp/test/services/mgr_service/dhcp_result_notify.cpp diff --git a/tests/wifi_standard/wifi_framework/dhcp_manage/mgr_service/dhcp_result_notify.h b/dhcp/test/services/mgr_service/dhcp_result_notify.h similarity index 100% rename from tests/wifi_standard/wifi_framework/dhcp_manage/mgr_service/dhcp_result_notify.h rename to dhcp/test/services/mgr_service/dhcp_result_notify.h diff --git a/tests/wifi_standard/wifi_framework/dhcp_manage/mgr_service/dhcp_server_service_test.cpp b/dhcp/test/services/mgr_service/dhcp_server_service_test.cpp similarity index 100% rename from tests/wifi_standard/wifi_framework/dhcp_manage/mgr_service/dhcp_server_service_test.cpp rename to dhcp/test/services/mgr_service/dhcp_server_service_test.cpp diff --git a/tests/wifi_standard/wifi_framework/dhcp_manage/mgr_service/dhcp_service_test.cpp b/dhcp/test/services/mgr_service/dhcp_service_test.cpp similarity index 100% rename from tests/wifi_standard/wifi_framework/dhcp_manage/mgr_service/dhcp_service_test.cpp rename to dhcp/test/services/mgr_service/dhcp_service_test.cpp diff --git a/tests/wifi_standard/wifi_framework/dhcp_manage/mgr_service/global_test.cpp b/dhcp/test/services/mgr_service/global_test.cpp similarity index 100% rename from tests/wifi_standard/wifi_framework/dhcp_manage/mgr_service/global_test.cpp rename to dhcp/test/services/mgr_service/global_test.cpp diff --git a/tests/wifi_standard/wifi_framework/dhcp_manage/mgr_service/global_test.h b/dhcp/test/services/mgr_service/global_test.h similarity index 100% rename from tests/wifi_standard/wifi_framework/dhcp_manage/mgr_service/global_test.h rename to dhcp/test/services/mgr_service/global_test.h diff --git a/tests/wifi_standard/wifi_framework/dhcp_manage/mgr_service/mock_system_func.cpp b/dhcp/test/services/mgr_service/mock_system_func.cpp similarity index 100% rename from tests/wifi_standard/wifi_framework/dhcp_manage/mgr_service/mock_system_func.cpp rename to dhcp/test/services/mgr_service/mock_system_func.cpp diff --git a/tests/wifi_standard/wifi_framework/dhcp_manage/mgr_service/mock_system_func.h b/dhcp/test/services/mgr_service/mock_system_func.h similarity index 100% rename from tests/wifi_standard/wifi_framework/dhcp_manage/mgr_service/mock_system_func.h rename to dhcp/test/services/mgr_service/mock_system_func.h diff --git a/figures/en-us_image_0000001115710400.png b/figures/en-us_image_0000001115710400.png old mode 100755 new mode 100644 diff --git a/figures/zh-cn_image_0000001115710400.png b/figures/zh-cn_image_0000001115710400.png old mode 100755 new mode 100644 diff --git a/interfaces/innerkits/native_cpp/napi/BUILD.gn b/interfaces/innerkits/native_cpp/napi/BUILD.gn deleted file mode 100755 index ea63e51dd37904a6aba06fd99eb51b5aa6965ddc..0000000000000000000000000000000000000000 --- a/interfaces/innerkits/native_cpp/napi/BUILD.gn +++ /dev/null @@ -1,58 +0,0 @@ -# Copyright (C) 2021 Huawei Device Co., Ltd. -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -import("//build/ohos.gni") - -ohos_shared_library("wifi_native_js") { - install_enable = true - include_dirs = [ - "//third_party/node/src", - "//native_engine", - "//utils/native/base/include", - "//utils/system/safwk/native/include", - "//foundation/communication/wifi/services/wifi_standard/wifi_framework/common/log", - "//foundation/communication/wifi/interfaces/innerkits/native_cpp/wifi_standard/interfaces", - "//base/hiviewdfx/hilog/interfaces/native/innerkits/include", - "//foundation/communication/wifi/interfaces/innerkits/native_cpp/wifi_standard/include", - "//foundation/communication/wifi/services/wifi_standard/wifi_framework/common/net_helper", - "//base/notification/ces_standard/frameworks/core/include", - ] - - sources = [ - "wifi_napi_device.cpp", - "wifi_napi_entry.cpp", - "wifi_napi_event.cpp", - "wifi_napi_hotspot.cpp", - "wifi_napi_p2p.cpp", - "wifi_napi_utils.cpp", - ] - deps = [ - "//base/hiviewdfx/hilog/interfaces/native/innerkits:libhilog", - "//base/notification/ces_standard/frameworks/core:cesfwk_core", - "//base/notification/ces_standard/frameworks/native:cesfwk_innerkits", - "//foundation/aafwk/standard/interfaces/innerkits/want:want", - "//foundation/ace/napi:ace_napi", - "//foundation/communication/wifi/interfaces/innerkits/native_cpp/wifi_standard:wifi_sdk", - "//utils/native/base:utils", - ] - - external_deps = [ "ipc:ipc_core" ] - - relative_install_dir = "module" - part_name = "wifi_native_js" - subsystem_name = "communication" -} - -group("wifi_js") { - deps = [ ":wifi_native_js" ] -} diff --git a/interfaces/innerkits/native_cpp/napi/wifi_napi_device.cpp b/interfaces/innerkits/native_cpp/napi/wifi_napi_device.cpp deleted file mode 100755 index 3afaf93c3bd43f8188cb64c9cc026f688783113a..0000000000000000000000000000000000000000 --- a/interfaces/innerkits/native_cpp/napi/wifi_napi_device.cpp +++ /dev/null @@ -1,518 +0,0 @@ -/* - * Copyright (C) 2021 Huawei Device Co., Ltd. - * 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 "wifi_napi_device.h" -#include "wifi_logger.h" -#include "wifi_device.h" -#include "wifi_scan.h" -#include - -namespace OHOS { -namespace Wifi { -DEFINE_WIFILOG_LABEL("WifiNAPIDevice"); - -std::unique_ptr wifiDevicePtr = WifiDevice::GetInstance(WIFI_DEVICE_ABILITY_ID); -std::unique_ptr wifiScanPtr = WifiScan::GetInstance(WIFI_SCAN_ABILITY_ID); - -napi_value EnableWifi(napi_env env, napi_callback_info info) -{ - size_t argc = 1; - napi_value argv[1]; - napi_value thisVar; - NAPI_CALL(env, napi_get_cb_info(env, info, &argc, argv, &thisVar, NULL)); - - NAPI_ASSERT(env, wifiDevicePtr != nullptr, "[NAPI] Wifi device instance is null."); - ErrCode ret = wifiDevicePtr->EnableWifi(); - napi_value result; - napi_get_boolean(env, ret == WIFI_OPT_SUCCESS, &result); - return result; -} - -napi_value DisableWifi(napi_env env, napi_callback_info info) -{ - size_t argc = 1; - napi_value argv[1]; - napi_value thisVar; - NAPI_CALL(env, napi_get_cb_info(env, info, &argc, argv, &thisVar, NULL)); - - NAPI_ASSERT(env, wifiDevicePtr != nullptr, "[NAPI] Wifi device instance is null."); - ErrCode ret = wifiDevicePtr->DisableWifi(); - napi_value result; - napi_get_boolean(env, ret == WIFI_OPT_SUCCESS, &result); - return result; -} - -napi_value IsWifiActive(napi_env env, napi_callback_info info) -{ - size_t argc = 1; - napi_value argv[1]; - napi_value thisVar; - NAPI_CALL(env, napi_get_cb_info(env, info, &argc, argv, &thisVar, NULL)); - - NAPI_ASSERT(env, wifiDevicePtr != nullptr, "[NAPI] Wifi device instance is null."); - bool activeStatus = true; - ErrCode ret = wifiDevicePtr->IsWifiActive(activeStatus); - if (ret != WIFI_OPT_SUCCESS) { - WIFI_LOGE("[Napi Device] Get wifi active status fail: %{public}d", ret); - } - - napi_value result; - napi_get_boolean(env, activeStatus, &result); - return result; -} - -napi_value Scan(napi_env env, napi_callback_info info) -{ - size_t argc = 1; - napi_value argv[1]; - napi_value thisVar; - NAPI_CALL(env, napi_get_cb_info(env, info, &argc, argv, &thisVar, NULL)); - - NAPI_ASSERT(env, wifiScanPtr != nullptr, "[NAPI] Wifi scan instance is null."); - ErrCode ret = wifiScanPtr->Scan(); - - napi_value result; - napi_get_boolean(env, ret == WIFI_OPT_SUCCESS, &result); - return result; -} - -static SecTypeJs SecurityTypeNativeToJs(const WifiSecurity& cppSecurityType) -{ - SecTypeJs jsSecurityType = SecTypeJs::SEC_TYPE_INVALID; - switch (cppSecurityType) { - case WifiSecurity::OPEN: - jsSecurityType = SecTypeJs::SEC_TYPE_OPEN; - break; - - case WifiSecurity::WEP: - jsSecurityType = SecTypeJs::SEC_TYPE_WEP; - break; - - case WifiSecurity::PSK: - jsSecurityType = SecTypeJs::SEC_TYPE_PSK; - break; - - case WifiSecurity::SAE: - jsSecurityType = SecTypeJs::SEC_TYPE_SAE; - break; - - default: - jsSecurityType = SecTypeJs::SEC_TYPE_INVALID; - break; - } - return jsSecurityType; -} - -static bool NativeScanInfosToJsObj(const napi_env& env, napi_value& arrayResult, - const std::vector& vecScnIanfos) -{ - uint32_t idx = 0; - for (auto& each : vecScnIanfos) { - napi_value eachObj; - napi_create_object(env, &eachObj); - - SetValueUtf8String(env, "ssid", each.ssid.c_str(), eachObj); - SetValueUtf8String(env, "bssid", each.bssid.c_str(), eachObj); - SetValueInt32(env, "securityType", static_cast(SecurityTypeNativeToJs(each.securityType)), eachObj); - SetValueInt32(env, "rssi", each.rssi, eachObj); - SetValueInt32(env, "band", each.band, eachObj); - SetValueInt32(env, "frequency", each.frequency, eachObj); - SetValueInt64(env, "timestamp", each.timestamp, eachObj); - - napi_status status = napi_set_element(env, arrayResult, idx++, eachObj); - if (status != napi_ok) { - WIFI_LOGE("[Napi Device] wifi napi set element error: %{public}d, idx: %{public}d", status, idx - 1); - return false; - } - } - return true; -} - -static bool GetWifiScanInfoList(const napi_env& env, napi_value& arrayResult) -{ - std::vector vecCppScanInfos; - if (wifiScanPtr->GetScanInfoList(vecCppScanInfos) != WIFI_OPT_SUCCESS) { - WIFI_LOGE("[Napi Device] Get Scaninf list error"); - return false; - } - - WIFI_LOGI("[Napi Device] GetScanInfoList, size: %{public}zu", vecCppScanInfos.size()); - napi_create_array_with_length(env, vecCppScanInfos.size(), &arrayResult); - return NativeScanInfosToJsObj(env, arrayResult, vecCppScanInfos); -} - -static napi_value ScanInfoToCallBack(const napi_env& env, AsyncCallbackInfo *asCallbackInfo, - const size_t argc, const napi_value *argv) -{ - napi_value resourceName; - napi_create_string_latin1(env, "getScanInfos", NAPI_AUTO_LENGTH, &resourceName); - - for (size_t i = 0; i != argc; ++i) { - napi_valuetype valuetype; - NAPI_CALL(env, napi_typeof(env, argv[i], &valuetype)); - NAPI_ASSERT(env, valuetype == napi_function, "Wrong argument type. Function expected."); - napi_create_reference(env, argv[i], 1, &asCallbackInfo->callback[i]); - } - - napi_create_async_work( - env, nullptr, resourceName, - [](napi_env env, void* data) { - }, - [](napi_env env, napi_status status, void* data) { - napi_value undefine; - napi_get_undefined(env, &undefine); - napi_value callback; - AsyncCallbackInfo* asCallbackInfo = (AsyncCallbackInfo *)data; - asCallbackInfo->isSuccess = GetWifiScanInfoList(env, asCallbackInfo->result); - if (asCallbackInfo->isSuccess) { - napi_get_reference_value(env, asCallbackInfo->callback[0], &callback); - napi_call_function(env, nullptr, callback, 1, &asCallbackInfo->result, &undefine); - } else { - if (asCallbackInfo->callback[1]) { - napi_get_reference_value(env, asCallbackInfo->callback[1], &callback); - napi_call_function(env, nullptr, callback, 1, &asCallbackInfo->result, &undefine); - } else { - WIFI_LOGE("[Napi Device] get scan info callback func is null"); - napi_throw_error(env, "error", "get scan info callback func is null"); - } - } - if (asCallbackInfo->callback[0] != nullptr) { - napi_delete_reference(env, asCallbackInfo->callback[0]); - } - if (asCallbackInfo->callback[1] != nullptr) { - napi_delete_reference(env, asCallbackInfo->callback[1]); - } - napi_delete_async_work(env, asCallbackInfo->asyncWork); - delete asCallbackInfo; - }, - (void *)asCallbackInfo, - &asCallbackInfo->asyncWork); - NAPI_CALL(env, napi_queue_async_work(env, asCallbackInfo->asyncWork)); - return UndefinedNapiValue(env); -} - -static napi_value ScanInfoToPromise(const napi_env& env, AsyncCallbackInfo *asCallbackInfo, napi_value& promise) -{ - napi_value resourceName; - napi_create_string_latin1(env, "getScanInfos", NAPI_AUTO_LENGTH, &resourceName); - - napi_deferred deferred; - NAPI_CALL(env, napi_create_promise(env, &deferred, &promise)); - asCallbackInfo->deferred = deferred; - - napi_create_async_work( - env, - nullptr, - resourceName, - [](napi_env env, void *data) { - }, - [](napi_env env, napi_status status, void *data) { - AsyncCallbackInfo *asCallbackInfo = (AsyncCallbackInfo *)data; - asCallbackInfo->isSuccess = GetWifiScanInfoList(env, asCallbackInfo->result); - if (asCallbackInfo->isSuccess) { - napi_resolve_deferred(asCallbackInfo->env, asCallbackInfo->deferred, asCallbackInfo->result); - } else { - napi_reject_deferred(asCallbackInfo->env, asCallbackInfo->deferred, asCallbackInfo->result); - } - napi_delete_async_work(env, asCallbackInfo->asyncWork); - delete asCallbackInfo; - }, - (void *)asCallbackInfo, - &asCallbackInfo->asyncWork); - napi_queue_async_work(env, asCallbackInfo->asyncWork); - return UndefinedNapiValue(env); -} - -napi_value GetScanInfos(napi_env env, napi_callback_info info) -{ - size_t argc = 2; - napi_value argv[argc]; - napi_value thisVar = nullptr; - void *data = nullptr; - NAPI_CALL(env, napi_get_cb_info(env, info, &argc, argv, &thisVar, &data)); - - AsyncCallbackInfo *asCallbackInfo = - new AsyncCallbackInfo{.env = env, .asyncWork = nullptr, .deferred = nullptr}; - - if (argc >= 1) { - return ScanInfoToCallBack(env, asCallbackInfo, argc, argv); - } else { - napi_value promise; - ScanInfoToPromise(env, asCallbackInfo, promise); - return promise; - } -} - -static void ConvertEncryptionMode(const SecTypeJs& securityType, std::string& keyMgmt) -{ - switch (securityType) { - case SecTypeJs::SEC_TYPE_OPEN: - keyMgmt = "NONE"; - break; - - case SecTypeJs::SEC_TYPE_WEP: - keyMgmt = "WEP"; - break; - - case SecTypeJs::SEC_TYPE_PSK: - keyMgmt = "WPA-PSK"; - break; - - case SecTypeJs::SEC_TYPE_SAE: - keyMgmt = "SAE"; - break; - - default: - keyMgmt = "WPA-PSK"; - break; - } -} - -static void JsObjToDeviceConfig(const napi_env& env, const napi_value& object, WifiDeviceConfig& cppConfig) -{ - JsObjectToString(env, object, "ssid", 33, cppConfig.ssid); /* 33: ssid max length is 32 + '\0' */ - JsObjectToString(env, object, "bssid", 18, cppConfig.bssid); /* 18: max bssid length for string type */ - JsObjectToString(env, object, "preSharedKey", 256, cppConfig.preSharedKey); /* 256: max length */ - JsObjectToBool(env, object, "isHiddenSsid", cppConfig.hiddenSSID); - int type = static_cast(SecTypeJs::SEC_TYPE_INVALID); - JsObjectToInt(env, object, "securityType", type); - ConvertEncryptionMode(SecTypeJs(type), cppConfig.keyMgmt); -} - -static napi_value AddDeviceConfigImpl(const napi_env& env, AsyncCallbackInfo *asCallbackInfo) -{ - NAPI_ASSERT(env, wifiDevicePtr != nullptr, "[NAPI] Wifi device instance is null."); - int addResult = -1; - int retValue = 0; - ErrCode ret = wifiDevicePtr->AddDeviceConfig(*(WifiDeviceConfig *)asCallbackInfo->obj, addResult); - if (addResult < 0 || ret != WIFI_OPT_SUCCESS) { - retValue = -1; - } else { - retValue = addResult; - } - - napi_value result; - napi_create_int32(env, retValue, &result); - asCallbackInfo->isSuccess = (ret == WIFI_OPT_SUCCESS); - asCallbackInfo->result = result; - return UndefinedNapiValue(env); -} - -static napi_value AddDeviceConfigCallBack(const napi_env& env, AsyncCallbackInfo *asCallbackInfo, - size_t argc, napi_value *argv) -{ - napi_value resourceName; - napi_create_string_latin1(env, "addDeviceConfig", NAPI_AUTO_LENGTH, &resourceName); - - for (size_t i = 1; i != argc; ++i) { - napi_valuetype valuetype; - NAPI_CALL(env, napi_typeof(env, argv[i], &valuetype)); - NAPI_ASSERT(env, valuetype == napi_function, "Wrong argument type. Function expected."); - napi_create_reference(env, argv[i], 1, &asCallbackInfo->callback[i - 1]); - } - - napi_create_async_work( - env, nullptr, resourceName, - [](napi_env env, void* data) { - }, - [](napi_env env, napi_status status, void* data) { - AsyncCallbackInfo* asCallbackInfo = (AsyncCallbackInfo *)data; - AddDeviceConfigImpl(env, asCallbackInfo); - napi_value callback; - napi_value undefine; - napi_get_undefined(env, &undefine); - if (asCallbackInfo->isSuccess) { - napi_get_reference_value(env, asCallbackInfo->callback[0], &callback); - napi_call_function(env, nullptr, callback, 1, &asCallbackInfo->result, &undefine); - } else { - if (asCallbackInfo->callback[1]) { - napi_get_reference_value(env, asCallbackInfo->callback[1], &callback); - napi_call_function(env, nullptr, callback, 1, &asCallbackInfo->result, &undefine); - } else { - WIFI_LOGE("[Napi Device] get scan info callback func is null"); - napi_throw_error(env, "error", "add wifi config callback func is null"); - } - } - if (asCallbackInfo->callback[0] != nullptr) { - napi_delete_reference(env, asCallbackInfo->callback[0]); - } - if (asCallbackInfo->callback[1] != nullptr) { - napi_delete_reference(env, asCallbackInfo->callback[1]); - } - napi_delete_async_work(env, asCallbackInfo->asyncWork); - delete (WifiDeviceConfig *)asCallbackInfo->obj; - delete asCallbackInfo; - }, - (void *)asCallbackInfo, - &asCallbackInfo->asyncWork); - NAPI_CALL(env, napi_queue_async_work(env, asCallbackInfo->asyncWork)); - return UndefinedNapiValue(env); -} - -static napi_value AddDeviceConfigPromise(const napi_env& env, AsyncCallbackInfo *asCallbackInfo, napi_value& promise) -{ - napi_value resourceName; - napi_create_string_latin1(env, "addDeviceConfig", NAPI_AUTO_LENGTH, &resourceName); - - napi_deferred deferred; - NAPI_CALL(env, napi_create_promise(env, &deferred, &promise)); - asCallbackInfo->deferred = deferred; - - napi_create_async_work( - env, - nullptr, - resourceName, - [](napi_env env, void *data) { - }, - [](napi_env env, napi_status status, void *data) { - AsyncCallbackInfo *asCallbackInfo = (AsyncCallbackInfo *)data; - AddDeviceConfigImpl(env, asCallbackInfo); - if (asCallbackInfo->isSuccess) { - napi_resolve_deferred(asCallbackInfo->env, asCallbackInfo->deferred, asCallbackInfo->result); - } else { - napi_reject_deferred(asCallbackInfo->env, asCallbackInfo->deferred, asCallbackInfo->result); - } - napi_delete_async_work(env, asCallbackInfo->asyncWork); - delete (WifiDeviceConfig *)asCallbackInfo->obj; - delete asCallbackInfo; - }, - (void *)asCallbackInfo, - &asCallbackInfo->asyncWork); - napi_queue_async_work(env, asCallbackInfo->asyncWork); - return UndefinedNapiValue(env); -} - -napi_value AddDeviceConfig(napi_env env, napi_callback_info info) -{ - size_t argc = 3; - napi_value argv[argc]; - napi_value thisVar = nullptr; - void *data = nullptr; - NAPI_CALL(env, napi_get_cb_info(env, info, &argc, argv, &thisVar, &data)); - NAPI_ASSERT(env, argc >= 1, "Wrong number of arguments"); - - napi_valuetype valueType; - napi_typeof(env, argv[0], &valueType); - NAPI_ASSERT(env, valueType == napi_object, "Wrong argument type. Object expected for parameter 1."); - - AsyncCallbackInfo *asCallbackInfo = - new AsyncCallbackInfo{.env = env, .asyncWork = nullptr, .deferred = nullptr}; - - WifiDeviceConfig *config = new WifiDeviceConfig(); - if (config == NULL) { - delete asCallbackInfo; - return UndefinedNapiValue(env); - } - JsObjToDeviceConfig(env, argv[0], *config); - asCallbackInfo->obj = config; - if (argc > 1) { - return AddDeviceConfigCallBack(env, asCallbackInfo, argc, argv); - } else { - napi_value promise; - AddDeviceConfigPromise(env, asCallbackInfo, promise); - return promise; - } -} - -napi_value ConnectToNetwork(napi_env env, napi_callback_info info) -{ - size_t argc = 1; - napi_value argv[1]; - napi_value thisVar; - NAPI_CALL(env, napi_get_cb_info(env, info, &argc, argv, &thisVar, NULL)); - NAPI_ASSERT(env, argc == 1, "Wrong number of arguments"); - - napi_valuetype valueType; - napi_typeof(env, argv[0], &valueType); - NAPI_ASSERT(env, valueType == napi_number, "Wrong argument type. napi_number expected."); - - int networkId = -1; - napi_get_value_int32(env, argv[0], &networkId); - - NAPI_ASSERT(env, wifiDevicePtr != nullptr, "[NAPI] Wifi device instance is null."); - ErrCode ret = wifiDevicePtr->ConnectToNetwork(networkId); - napi_value result; - napi_get_boolean(env, ret == WIFI_OPT_SUCCESS, &result); - return result; -} - -napi_value ConnectToDevice(napi_env env, napi_callback_info info) -{ - size_t argc = 1; - napi_value argv[1]; - napi_value thisVar; - NAPI_CALL(env, napi_get_cb_info(env, info, &argc, argv, &thisVar, NULL)); - - napi_valuetype valueType; - napi_typeof(env, argv[0], &valueType); - NAPI_ASSERT(env, valueType == napi_object, "Wrong argument type. Object expected."); - - NAPI_ASSERT(env, wifiDevicePtr != nullptr, "[NAPI] Wifi device instance is null."); - WifiDeviceConfig config; - JsObjToDeviceConfig(env, argv[0], config); - ErrCode ret = wifiDevicePtr->ConnectToDevice(config); - - napi_value result; - napi_get_boolean(env, ret == WIFI_OPT_SUCCESS, &result); - return result; -} - -napi_value Disconnect(napi_env env, napi_callback_info info) -{ - size_t argc = 1; - napi_value argv[1]; - napi_value thisVar; - NAPI_CALL(env, napi_get_cb_info(env, info, &argc, argv, &thisVar, NULL)); - - NAPI_ASSERT(env, wifiDevicePtr != nullptr, "[NAPI] Wifi device instance is null."); - ErrCode ret = wifiDevicePtr->Disconnect(); - napi_value result; - napi_get_boolean(env, ret == WIFI_OPT_SUCCESS, &result); - return result; -} - -napi_value GetSignalLevel(napi_env env, napi_callback_info info) -{ - size_t argc = 2; - napi_value argv[2]; - napi_value thisVar; - NAPI_CALL(env, napi_get_cb_info(env, info, &argc, argv, &thisVar, NULL)); - /* the input have 2 parameters */ - NAPI_ASSERT(env, argc == 2, "Wrong number of arguments"); - - napi_valuetype type1; - napi_valuetype type2; - napi_typeof(env, argv[0], &type1); - napi_typeof(env, argv[1], &type2); - NAPI_ASSERT(env, type1 == napi_number, "Wrong argument type. napi_number expected."); - NAPI_ASSERT(env, type2 == napi_number, "Wrong argument type. napi_number expected."); - - int rssi, band; - napi_get_value_int32(env, argv[0], &rssi); - napi_get_value_int32(env, argv[1], &band); - - NAPI_ASSERT(env, wifiDevicePtr != nullptr, "[NAPI] Wifi device instance is null."); - int level = -1; - ErrCode ret = wifiDevicePtr->GetSignalLevel(rssi, band, level); - if (ret != WIFI_OPT_SUCCESS) { - WIFI_LOGW("[Napi Device] Get wifi signal level fail: %{public}d", ret); - } - - napi_value result; - napi_create_uint32(env, level, &result); - return result; -} -} // namespace Wifi -} // namespace OHOS diff --git a/interfaces/innerkits/native_cpp/napi/wifi_napi_event.cpp b/interfaces/innerkits/native_cpp/napi/wifi_napi_event.cpp deleted file mode 100755 index 8b45dc5504a1a71045d7af1fa8b82b529d6b7f48..0000000000000000000000000000000000000000 --- a/interfaces/innerkits/native_cpp/napi/wifi_napi_event.cpp +++ /dev/null @@ -1,407 +0,0 @@ -/* - * Copyright (C) 2021 Huawei Device Co., Ltd. - * 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 "wifi_napi_event.h" -#include -#include "wifi_napi_utils.h" -#include "wifi_logger.h" - -using namespace OHOS::EventFwk; - -namespace OHOS { -namespace Wifi { -DEFINE_WIFILOG_LABEL("WifiNAPIEvent"); - -const std::string WIFI_EVENT_TYPE_POWER_STATE = "wifiStateChange"; -const std::string WIFI_EVENT_TYPE_CONN_STATE = "wifiConnectionChange"; - -const std::string WIFI_USUAL_EVENT_POWER_STATE = "usual.event.wifi.POWER_STATE"; -const std::string WIFI_USUAL_EVENT_CONN_STATE = "usual.event.wifi.CONN_STATE"; - -std::shared_mutex g_regInfoMutex; -static std::map g_eventRegisterInfo; - -static std::map g_mapEventTypeToUsualEvent = { - { WIFI_EVENT_TYPE_POWER_STATE, WIFI_USUAL_EVENT_POWER_STATE }, - { WIFI_EVENT_TYPE_CONN_STATE, WIFI_USUAL_EVENT_CONN_STATE }, -}; - -static std::map g_mapUserDefinedEventProcessFunc = {}; - -class EventRegisterInfo { -public: - explicit EventRegisterInfo(EventManager* context) : m_context(context) { - } - - EventRegisterInfo() { - } - - virtual ~EventRegisterInfo() { - } - - std::set& GetHandlersCb() { - return m_handlersCb; - } - - void SetSubscriber(std::shared_ptr& subscriber) { - m_subscriber = subscriber; - } - - std::shared_ptr GetSubscriber() { - return m_subscriber; - } - - void SetContext(EventManager* context) { - m_context = context; - } - - EventManager* GetContext() { - return m_context; - } - -private: - std::set m_handlersCb; - std::shared_ptr m_subscriber; - EventManager* m_context; -}; - -void Event::SetName(std::string& name) { - m_name = name; -} - -std::string Event::GetName() { - return m_name; -} - -napi_env Event::GetEnv() { - return m_env; -} - -napi_value WifiCommonEvent::PackResult() { - napi_value result; - napi_create_int32(GetEnv(), m_value, &result); - return result; -} - -static bool GetUsualEventByEventType(const std::string& type, std::string& usual) { - std::map::const_iterator it = g_mapEventTypeToUsualEvent.find(type); - if (it == g_mapEventTypeToUsualEvent.end()) { - return false; - } - usual = it->second; - return true; -} - -static bool GetEventTypeByUsualEvent(const std::string& usual, std::string& type) { - for (auto& each : g_mapEventTypeToUsualEvent) { - if (each.second == usual) { - type = each.first; - return true; - } - } - return false; -} - -static bool IsEventTypeExist(const std::string& type) { - return g_mapEventTypeToUsualEvent.find(type) != g_mapEventTypeToUsualEvent.end(); -} - -void WifiEventSubscriber::OnReceiveEvent(const CommonEventData& data) { - std::string event = data.GetWant().GetAction(); - int code = data.GetCode(); - WIFI_LOGI("[Napi Event] Received event: %{public}s, value: %{public}d", event.c_str(), code); - - std::string type; - if (!GetEventTypeByUsualEvent(event, type)) { - WIFI_LOGI("[Napi Event] Received event: %{public}s is ignored", event.c_str()); - return; - } - - EventManager* manager = nullptr; - { - std::shared_lock guard(g_regInfoMutex); - std::map::iterator it = g_eventRegisterInfo.find(type); - if (it == g_eventRegisterInfo.end()) { - WIFI_LOGE("[Napi Event] no register info for event: %{public}s", type.c_str()); - return; - } - manager = it->second.GetContext(); - if (manager == nullptr) { - WIFI_LOGE("[Napi Event] Context is null"); - return; - } - } - - std::map::iterator iter = g_mapUserDefinedEventProcessFunc.find(type); - if (iter != g_mapUserDefinedEventProcessFunc.end()) { - WIFI_LOGI("[Napi Event] Has user-defined func for event: %{public}s", type.c_str()); - iter->second(manager->GetEnv(), type, data); - } else { - WIFI_LOGI("[Napi Event] Use default policy to process event: %{public}s", type.c_str()); - WifiCommonEvent commonEvent(manager->GetEnv(), type, code); - if (!manager->Send(commonEvent)) { - WIFI_LOGE("[Napi Event] Send event error"); - } - } -} - -EventManager::EventManager(napi_env env, napi_value thisVar) : m_env(env) { - m_thisVarRef = nullptr; - napi_create_reference(env, thisVar, 1, &m_thisVarRef); -} - -EventManager::~EventManager() {} - -bool EventManager::Send(Event& event) { - WIFI_LOGI("[Napi Event] Report event: %{public}s", event.GetName().c_str()); - - napi_handle_scope scope = nullptr; - napi_open_handle_scope(m_env, &scope); - - std::shared_lock guard(g_regInfoMutex); - std::map::iterator it = g_eventRegisterInfo.find(event.GetName()); - if (it == g_eventRegisterInfo.end()) { - WIFI_LOGE("[Napi Event] Event receive owner not exits: %{public}s", event.GetName().c_str()); - return false; - } - - bool result = true; - napi_value thisVar = nullptr; - napi_get_reference_value(m_env, m_thisVarRef, &thisVar); - for (auto& each : it->second.GetHandlersCb()) { - napi_value undefine; - napi_value handler = nullptr; - napi_get_undefined(m_env, &undefine); - napi_get_reference_value(m_env, each, &handler); - napi_value jsEvent = event.PackResult(); - if (napi_call_function(m_env, thisVar, handler, 1, &jsEvent, &undefine) != napi_ok) { - WIFI_LOGE("[Napi Event] Report event failed"); - result = false; - } - } - napi_close_handle_scope(m_env, scope); - return result; -} - -bool EventManager::SubscribeServiceEvent(const std::string& event) { - MatchingSkills matchingSkills; - matchingSkills.AddEvent(event); - CommonEventSubscribeInfo subscriberInfo(matchingSkills); - std::shared_ptr subscriber = std::make_shared(subscriberInfo); - WIFI_LOGI("[Napi Event] Subscribe event -> %{public}s", event.c_str()); - bool subscribeResult = CommonEventManager::SubscribeCommonEvent(subscriber); - if (subscribeResult) { - g_eventRegisterInfo[m_eventType].SetSubscriber(subscriber); - } else { - WIFI_LOGE("[Napi Event] Subscribe service event error: %{public}s", event.c_str()); - } - return subscribeResult; -} - -bool EventManager::UnsubscribeServiceEvent(const std::string& event) { - bool unsubscribeResult = CommonEventManager::SubscribeCommonEvent(g_eventRegisterInfo[m_eventType].GetSubscriber()); - if (!unsubscribeResult) { - WIFI_LOGE("[Napi Event] Unsubscribe service event error: %{public}s", event.c_str()); - } - return unsubscribeResult; -} - -bool EventManager::SubscribeEvent(const std::string& name, napi_value handler) { - WIFI_LOGI("[Napi Event] Subscribe event: %{public}s", name.c_str()); - - if (!IsEventTypeExist(name)) { - WIFI_LOGE("[Napi Event] Subscribe event is not a valid event: %{public}s", name.c_str()); - return false; - } - SetEventType(name); - std::unique_lock guard(g_regInfoMutex); - std::map::iterator it = g_eventRegisterInfo.find(name); - if (it == g_eventRegisterInfo.end()) { - std::string usualEvent; - GetUsualEventByEventType(name, usualEvent); - bool result = SubscribeServiceEvent(usualEvent); - if (!result) { - WIFI_LOGE("[Napi Event] Service register event failed: %{public}s", name.c_str()); - return false; - } - - EventRegisterInfo regInfo(this); - g_eventRegisterInfo[name] = regInfo; - } - - if (g_eventRegisterInfo[name].GetContext() != this) { - WIFI_LOGW("[Napi Event] Subscribe event context changed!"); - g_eventRegisterInfo[name].SetContext(this); - } - - napi_ref handlerRef = nullptr; - napi_create_reference(m_env, handler, 1, &handlerRef); - g_eventRegisterInfo[name].GetHandlersCb().insert(handlerRef); - return true; -} - -void EventManager::DeleteHanderRef(std::set& setRefs, napi_value handler) { - for (auto& each : setRefs) { - napi_value handlerTemp = nullptr; - napi_get_reference_value(m_env, each, &handlerTemp); - bool isEqual = false; - napi_strict_equals(m_env, handlerTemp, handler, &isEqual); - if (isEqual) { - napi_delete_reference(m_env, each); - setRefs.erase(each); - return; - } - } -} - -void EventManager::DeleteAllHanderRef(std::set& setRefs) { - for (auto& each : setRefs) { - napi_delete_reference(m_env, each); - } - setRefs.clear(); -} - -bool EventManager::UnsubscribeEvent(const std::string& name, napi_value handler) { - WIFI_LOGI("[Napi Event] Unsubscribe event: %{public}s", name.c_str()); - - if (!IsEventTypeExist(name)) { - WIFI_LOGE("[Napi Event] Unsubscribe event is not a valid event: %{public}s", name.c_str()); - return false; - } - - bool isNeedUnsubscribe = false; - std::unique_lock guard(g_regInfoMutex); - std::map::iterator it = g_eventRegisterInfo.find(name); - if (it == g_eventRegisterInfo.end()) { - WIFI_LOGE("[Napi Event] Unsubscribe event is not subscribe: %{public}s", name.c_str()); - return false; - } - if (handler != nullptr) { - DeleteHanderRef(it->second.GetHandlersCb(), handler); - } else { - WIFI_LOGW("[Napi Event] All callback is unsubscribe for event: %{public}s", name.c_str()); - DeleteAllHanderRef(it->second.GetHandlersCb()); - } - /* No one subscribes event now */ - if (it->second.GetHandlersCb().empty()) { - isNeedUnsubscribe = true; - } - - SetEventType(name); - if (isNeedUnsubscribe) { - std::string usualEvent; - GetUsualEventByEventType(name, usualEvent); - bool result = UnsubscribeServiceEvent(usualEvent); - g_eventRegisterInfo.erase(name); - if (!result) { - WIFI_LOGE("[Napi Event] Service unregister event failed: %{public}s", name.c_str()); - return false; - } - } - return true; -} - -void EventManager::SetEventType(const std::string& type) { - m_eventType = type; -} - -napi_env EventManager::GetEnv() { - return m_env; -} - -napi_value On(napi_env env, napi_callback_info cbinfo) { - size_t requireArgc = 2; - size_t argc = 2; - napi_value argv[2] = {0}; - napi_value thisVar = 0; - napi_get_cb_info(env, cbinfo, &argc, argv, &thisVar, nullptr); - NAPI_ASSERT(env, argc >= requireArgc, "requires 2 parameter"); - - napi_valuetype eventName = napi_undefined; - napi_typeof(env, argv[0], &eventName); - NAPI_ASSERT(env, eventName == napi_string, "type mismatch for parameter 1"); - - napi_valuetype handler = napi_undefined; - napi_typeof(env, argv[1], &handler); - NAPI_ASSERT(env, handler == napi_function, "type mismatch for parameter 2"); - - EventManager* manager = nullptr; - napi_status status = napi_unwrap(env, thisVar, (void**)&manager); - if (status == napi_ok) { - char type[64] = {0}; - size_t typeLen = 0; - napi_get_value_string_utf8(env, argv[0], type, sizeof(type), &typeLen); - manager->SubscribeEvent(type, argv[1]); - } else { - WIFI_LOGE("[Napi Event] On unwrap class failed"); - } - napi_value result = nullptr; - napi_get_undefined(env, &result); - return result; -} - -napi_value Off(napi_env env, napi_callback_info cbinfo) { - size_t requireArgc = 1; - size_t requireArgcWithCb = 2; - size_t argc = 2; - napi_value argv[2] = {0}; - napi_value thisVar = 0; - napi_get_cb_info(env, cbinfo, &argc, argv, &thisVar, nullptr); - NAPI_ASSERT(env, argc >= requireArgc, "requires at least 1 parameter"); - - napi_valuetype eventName = napi_undefined; - napi_typeof(env, argv[0], &eventName); - NAPI_ASSERT(env, eventName == napi_string, "type mismatch for parameter 1"); - - if (argc >= requireArgcWithCb) { - napi_valuetype handler = napi_undefined; - napi_typeof(env, argv[1], &handler); - NAPI_ASSERT(env, handler == napi_function, "type mismatch for parameter 2"); - } - - EventManager* manager = nullptr; - napi_status status = napi_unwrap(env, thisVar, (void**)&manager); - if (status == napi_ok) { - char type[64] = {0}; - size_t typeLen = 0; - napi_get_value_string_utf8(env, argv[0], type, sizeof(type), &typeLen); - manager->UnsubscribeEvent(type, argc >= requireArgcWithCb ? argv[1] : nullptr); - } else { - WIFI_LOGE("[Napi Event] Off unwrap class failed"); - } - napi_value result = nullptr; - napi_get_undefined(env, &result); - return result; -} - -napi_value EventListenerConstructor(napi_env env, napi_callback_info cbinfo) { - napi_value thisVar = nullptr; - void* data = nullptr; - napi_get_cb_info(env, cbinfo, nullptr, nullptr, &thisVar, &data); - - EventManager* eventManager = new EventManager(env, thisVar); - WIFI_LOGI("[Napi Event] Event listener constructor"); - napi_wrap( - env, thisVar, eventManager, - [](napi_env env, void* data, void* hint) { - WIFI_LOGI("[Napi Event] Event listener destructor"); - EventManager* eventManager = (EventManager *)data; - delete eventManager; - }, - nullptr, nullptr); - return thisVar; -} -} // namespace Wifi -} // namespace OHOS diff --git a/interfaces/innerkits/native_cpp/napi/wifi_napi_event.h b/interfaces/innerkits/native_cpp/napi/wifi_napi_event.h deleted file mode 100755 index e9da73dd56379ea1855c3c15cf2d08cde52276b0..0000000000000000000000000000000000000000 --- a/interfaces/innerkits/native_cpp/napi/wifi_napi_event.h +++ /dev/null @@ -1,106 +0,0 @@ -/* - * Copyright (C) 2021 Huawei Device Co., Ltd. - * 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 WIFI_NAPI_EVENT_H_ -#define WIFI_NAPI_EVENT_H_ - -#include -#include -#include -#include "napi/native_api.h" -#include "common_event_manager.h" -#include "common_event.h" - -namespace OHOS { -namespace Wifi { - -typedef void (*UserDefinedEventProcessFunc)(const napi_env& env, const std::string& type, - const OHOS::EventFwk::CommonEventData& data); - -class Event { -public: - Event(napi_env env, std::string& name) : m_env(env), m_name(name) { - } - - virtual ~Event() { - } - - virtual napi_value PackResult() = 0; - - void SetName(std::string& name); - - std::string GetName(); - - napi_env GetEnv(); - -private: - napi_env m_env; - std::string m_name; -}; - -class WifiCommonEvent: public Event { -public: - WifiCommonEvent(napi_env env, std::string& name, int value) : Event(env, name), m_value(value) { - } - - virtual napi_value PackResult(); - -private: - int m_value; -}; - -class WifiEventSubscriber : public OHOS::EventFwk::CommonEventSubscriber { -public: - explicit WifiEventSubscriber(const OHOS::EventFwk::CommonEventSubscribeInfo &subscribeInfo) : - CommonEventSubscriber(subscribeInfo) { - } - - virtual ~WifiEventSubscriber() { - } - - virtual void OnReceiveEvent(const OHOS::EventFwk::CommonEventData &data) override; -}; - -class EventRegisterInfo; -class EventManager { -public: - EventManager(napi_env env, napi_value thisVar); - virtual ~EventManager(); - - bool Send(Event& event); - bool SubscribeEvent(const std::string& name, napi_value handler); - bool UnsubscribeEvent(const std::string& name, napi_value handler); - napi_env GetEnv(); - -private: - bool SubscribeServiceEvent(const std::string& event); - bool UnsubscribeServiceEvent(const std::string& event); - void DeleteHanderRef(std::set& setRefs, napi_value handler); - void DeleteAllHanderRef(std::set& setRefs); - void SetEventType(const std::string& type); - -private: - napi_env m_env; - napi_ref m_thisVarRef; - std::string m_eventType; -}; - -napi_value On(napi_env env, napi_callback_info cbinfo); -napi_value Off(napi_env env, napi_callback_info cbinfo); -napi_value EventListenerConstructor(napi_env env, napi_callback_info cbinfo); -} // namespace Wifi -} // namespace OHOS - -#endif diff --git a/interfaces/innerkits/native_cpp/napi/wifi_napi_utils.cpp b/interfaces/innerkits/native_cpp/napi/wifi_napi_utils.cpp deleted file mode 100755 index be68a0100eb6320bb3ecc2e1edf891c9cdb5f803..0000000000000000000000000000000000000000 --- a/interfaces/innerkits/native_cpp/napi/wifi_napi_utils.cpp +++ /dev/null @@ -1,123 +0,0 @@ -/* - * Copyright (C) 2021 Huawei Device Co., Ltd. - * 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 "wifi_napi_utils.h" -#include "securec.h" -#include "wifi_logger.h" - -namespace OHOS { -namespace Wifi { -DEFINE_WIFILOG_LABEL("WifiNAPIUtils"); - -napi_value UndefinedNapiValue(const napi_env& env) -{ - napi_value result; - napi_get_undefined(env, &result); - return result; -} - -napi_value JsObjectToString(const napi_env& env, const napi_value& object, - const char* fieldStr, const int bufLen, std::string& fieldRef) -{ - bool hasProperty = false; - NAPI_CALL(env, napi_has_named_property(env, object, fieldStr, &hasProperty)); - if (hasProperty) { - napi_value field; - napi_valuetype valueType; - - napi_get_named_property(env, object, fieldStr, &field); - NAPI_CALL(env, napi_typeof(env, field, &valueType)); - NAPI_ASSERT(env, valueType == napi_string, "Wrong argument type. String expected."); - if (bufLen <= 0) { - goto error; - } - char *buf = (char *)malloc(bufLen); - if (buf == nullptr) { - WIFI_LOGE("[Wifi Js] js object to str malloc failed"); - goto error; - } - (void)memset_s(buf, bufLen, 0, bufLen); - size_t result = 0; - NAPI_CALL(env, napi_get_value_string_utf8(env, field, buf, bufLen, &result)); - fieldRef = buf; - free(buf); - buf = nullptr; - } else { - WIFI_LOGW("[Wifi Js] wifi napi js to str no property: %{public}s", fieldStr); - } - -error: - return UndefinedNapiValue(env); -} - -napi_value JsObjectToInt(const napi_env& env, const napi_value& object, const char* fieldStr, int& fieldRef) -{ - bool hasProperty = false; - NAPI_CALL(env, napi_has_named_property(env, object, fieldStr, &hasProperty)); - if (hasProperty) { - napi_value field; - napi_valuetype valueType; - - napi_get_named_property(env, object, fieldStr, &field); - NAPI_CALL(env, napi_typeof(env, field, &valueType)); - NAPI_ASSERT(env, valueType == napi_number, "Wrong argument type. Number expected."); - napi_get_value_int32(env, field, &fieldRef); - } else { - WIFI_LOGW("[Wifi Js] wifi napi js to int no property: %{public}s", fieldStr); - } - return UndefinedNapiValue(env); -} - -napi_value JsObjectToBool(const napi_env& env, const napi_value& object, const char* fieldStr, bool& fieldRef) -{ - bool hasProperty = false; - NAPI_CALL(env, napi_has_named_property(env, object, fieldStr, &hasProperty)); - if (hasProperty) { - napi_value field; - napi_valuetype valueType; - - napi_get_named_property(env, object, fieldStr, &field); - NAPI_CALL(env, napi_typeof(env, field, &valueType)); - NAPI_ASSERT(env, valueType == napi_boolean, "Wrong argument type. Bool expected."); - napi_get_value_bool(env, field, &fieldRef); - } else { - WIFI_LOGW("[Wifi Js] wifi napi js to bool no property: %{public}s", fieldStr); - } - return UndefinedNapiValue(env); -} - -void SetValueUtf8String(const napi_env& env, const char* fieldStr, const char* str, napi_value& result) -{ - napi_value value; - napi_create_string_utf8(env, str, NAPI_AUTO_LENGTH, &value); - napi_set_named_property(env, result, fieldStr, value); -} - -void SetValueInt32(const napi_env& env, const char* fieldStr, const int intValue, napi_value& result) -{ - napi_value value; - napi_create_int32(env, intValue, &value); - napi_set_named_property(env, result, fieldStr, value); -} - -void SetValueInt64(const napi_env& env, const char* fieldStr, const int64_t intValue, napi_value& result) -{ - napi_value value; - napi_create_int64(env, intValue, &value); - napi_set_named_property(env, result, fieldStr, value); -} - -} // namespace Wifi -} // namespace OHOS diff --git a/interfaces/innerkits/native_cpp/wifi_standard/BUILD.gn b/interfaces/innerkits/native_cpp/wifi_standard/BUILD.gn deleted file mode 100755 index e766deea1f95c342b99fcfc5e0eccf1afa7dc1c6..0000000000000000000000000000000000000000 --- a/interfaces/innerkits/native_cpp/wifi_standard/BUILD.gn +++ /dev/null @@ -1,159 +0,0 @@ -# Copyright (C) 2021 Huawei Device Co., Ltd. -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -import("//build/ohos.gni") - -################################################################################ - -config("wifi_sdk_header") { - include_dirs = [ - "//utils/native/base/include", - "//utils/system/safwk/native/include", - "//base/hiviewdfx/hilog/interfaces/native/innerkits/include", - "//foundation/ace/ace_engine/frameworks/base/utils", - "//foundation/ace/ace_engine/frameworks", - "//foundation/distributedschedule/samgr/interfaces/innerkits/samgr_proxy/include", - "//foundation/communication/wifi/interfaces/innerkits/native_cpp/wifi_standard/include", - "//foundation/communication/wifi/interfaces/innerkits/native_cpp/wifi_standard/interfaces", - "//foundation/communication/wifi/services/wifi_standard/wifi_framework/common/net_helper", - "//foundation/communication/wifi/services/wifi_standard/wifi_framework/common/log/", - "//foundation/distributedschedule/samgr/adapter/interfaces/innerkits/include", - "//foundation/communication/wifi/services/wifi_standard/wifi_framework/common/include", - ] -} - -config("wifi_sdk_config") { - visibility = [ "//:*" ] - include_dirs = [ ":wifi_fw_common_header" ] - - cflags = [ - "-std=c++17", - "-fno-rtti", - ] - - if (target_cpu == "arm") { - cflags += [ "-DBINDER_IPC_32BIT" ] - } -} - -ohos_source_set("wifi_device_proxy_impl") { - sources = [ - "src/wifi_device_impl.cpp", - "src/wifi_device_proxy.cpp", - ] - - configs = [ - ":wifi_sdk_config", - ":wifi_sdk_header", - ] - - external_deps = [ "ipc:ipc_core" ] -} - -ohos_source_set("wifi_hotspot_proxy_impl") { - sources = [ - "src/wifi_hotspot_impl.cpp", - "src/wifi_hotspot_proxy.cpp", - ] - - configs = [ - ":wifi_sdk_config", - ":wifi_sdk_header", - ] - - external_deps = [ "ipc:ipc_core" ] -} - -ohos_source_set("wifi_scan_proxy_impl") { - sources = [ - "src/wifi_scan_impl.cpp", - "src/wifi_scan_proxy.cpp", - ] - - configs = [ - ":wifi_sdk_config", - ":wifi_sdk_header", - ] - - external_deps = [ "ipc:ipc_core" ] -} - -ohos_source_set("wifi_p2p_proxy_impl") { - sources = [ - "src/wifi_p2p_impl.cpp", - "src/wifi_p2p_proxy.cpp", - ] - - configs = [ - ":wifi_sdk_config", - ":wifi_sdk_header", - ] - - external_deps = [ "ipc:ipc_core" ] -} -ohos_shared_library("wifi_sdk") { - install_enable = true - - include_dirs = [ "//foundation/communication/wifi/interfaces/innerkits" ] - - sources = [ - "c_adapter/wifi_c_device.cpp", - "c_adapter/wifi_c_event.cpp", - "c_adapter/wifi_c_hotspot.cpp", - "c_adapter/wifi_c_utils.cpp", - "src/wifi_device.cpp", - "src/wifi_device_callback_stub.cpp", - "src/wifi_hotspot.cpp", - "src/wifi_hotspot_callback_stub.cpp", - "src/wifi_p2p.cpp", - "src/wifi_p2p_callback_stub.cpp", - "src/wifi_p2p_msg.cpp", - "src/wifi_scan.cpp", - "src/wifi_scan_callback_stub.cpp", - ] - - deps = [ - ":wifi_device_proxy_impl", - ":wifi_hotspot_proxy_impl", - ":wifi_p2p_proxy_impl", - ":wifi_scan_proxy_impl", - "//base/hiviewdfx/hilog/interfaces/native/innerkits:libhilog", - "//base/notification/ces_standard/frameworks/core:cesfwk_core", - "//base/notification/ces_standard/frameworks/native:cesfwk_innerkits", - "//foundation/aafwk/standard/interfaces/innerkits/want:want", - "//foundation/communication/wifi/services/wifi_standard/wifi_framework/wifi_manage:wifi_manager_service", - "//foundation/distributedschedule/samgr/interfaces/innerkits/samgr_proxy:samgr_proxy", - "//third_party/bounds_checking_function:libsec_static", - "//utils/native/base:utils", - ] - - external_deps = [ "ipc:ipc_core" ] - - cflags_cc = [ - "-std=c++17", - "-fno-rtti", - ] - - ldflags = [ - "-fPIC", - "-Wl,-E", - ] - - configs = [ - ":wifi_sdk_config", - ":wifi_sdk_header", - ] - - part_name = "wifi_standard" - subsystem_name = "communication" -} diff --git a/interfaces/innerkits/native_cpp/wifi_standard/c_adapter/wifi_c_event.cpp b/interfaces/innerkits/native_cpp/wifi_standard/c_adapter/wifi_c_event.cpp deleted file mode 100755 index 0cbc26c60ab544b36ac50dbdd563646b612c0bc6..0000000000000000000000000000000000000000 --- a/interfaces/innerkits/native_cpp/wifi_standard/c_adapter/wifi_c_event.cpp +++ /dev/null @@ -1,290 +0,0 @@ -/* - * Copyright (C) 2021 Huawei Device Co., Ltd. - * 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 "native_c/wifi_event.h" -#include "native_c/wifi_device.h" -#include "native_c/wifi_scan_info.h" -#include "wifi_logger.h" -#include "common_event_manager.h" -#include "common_event.h" -#include - -DEFINE_WIFILOG_LABEL("WifiCEvent"); - -const std::string WIFI_USUAL_EVENT_CONN_STATE = "usual.event.wifi.CONN_STATE"; -const std::string WIFI_USUAL_EVENT_SCAN_STATE = "usual.event.wifi.SCAN_FINISHED"; -const std::string WIFI_USUAL_EVENT_HOTSPOT_STATE = "usual.event.wifi.HOTSPOT_STATE"; -const std::string WIFI_USUAL_EVENT_STA_JOIN = "usual.event.wifi.WIFI_HS_STA_JOIN"; -const std::string WIFI_USUAL_EVENT_STA_LEAVE = "usual.event.wifi.WIFI_HS_STA_LEAVE"; - -using ConnectionChangeCb = void (*)(int, WifiLinkedInfo*); -using ScanStateChangeCb = void (*)(int, int); -using HotspotStateChangeCb = void (*)(int); -using HotspotJoinCb = void (*)(StationInfo*); -using HotspotLeaveCb = void (*)(StationInfo*); - -using namespace OHOS::EventFwk; -class EventManager { -public: - EventManager() { - } - - virtual ~EventManager() { - } - - bool AddConnectionChangeCb(const ConnectionChangeCb cb) { - if (m_setConnectionChangeCb.empty()) { - if (!SubscribeServiceEvent(WIFI_USUAL_EVENT_CONN_STATE)) { - return false; - } - } - return m_setConnectionChangeCb.insert(cb).second; - } - - void RemoveConnectionChangeCb(const ConnectionChangeCb cb) { - m_setConnectionChangeCb.erase(cb); - if (m_setConnectionChangeCb.empty()) { - UnsubscribeServiceEvent(WIFI_USUAL_EVENT_CONN_STATE); - } - } - - static std::set GetConnectionChangeCb() { - return m_setConnectionChangeCb; - } - - bool AddScanStateChangeCb(const ScanStateChangeCb cb) { - if (m_setScanStateChangeCb.empty()) { - if (!SubscribeServiceEvent(WIFI_USUAL_EVENT_SCAN_STATE)) { - return false; - } - } - return m_setScanStateChangeCb.insert(cb).second; - } - - void RemoveScanStateChangeCb(const ScanStateChangeCb cb) { - m_setScanStateChangeCb.erase(cb); - if (m_setScanStateChangeCb.empty()) { - UnsubscribeServiceEvent(WIFI_USUAL_EVENT_SCAN_STATE); - } - } - - static std::set GetScanStateChangeCb() { - return m_setScanStateChangeCb; - } - - bool AddHotspotChangeCb(const HotspotStateChangeCb cb) { - if (m_setHotspotChangeCb.empty()) { - if (!SubscribeServiceEvent(WIFI_USUAL_EVENT_HOTSPOT_STATE)) { - return false; - } - } - return m_setHotspotChangeCb.insert(cb).second; - } - - void RemoveHotspotChangeCb(const HotspotStateChangeCb cb) { - m_setHotspotChangeCb.erase(cb); - if (m_setHotspotChangeCb.empty()) { - UnsubscribeServiceEvent(WIFI_USUAL_EVENT_HOTSPOT_STATE); - } - } - - static std::set GetHotspotChangeCb() { - return m_setHotspotChangeCb; - } - - bool AddHotspotJoinCb(const HotspotJoinCb cb) { - if (m_setHotspotJoinCb.empty()) { - if (!SubscribeServiceEvent(WIFI_USUAL_EVENT_STA_JOIN)) { - return false; - } - } - return m_setHotspotJoinCb.insert(cb).second; - } - - void RemoveHotspotJoinCb(const HotspotJoinCb cb) { - m_setHotspotJoinCb.erase(cb); - if (m_setHotspotJoinCb.empty()) { - UnsubscribeServiceEvent(WIFI_USUAL_EVENT_STA_JOIN); - } - } - - static std::set GetHotspotJoinCb() { - return m_setHotspotJoinCb; - } - - bool AddHotspotLeaveCb(const HotspotLeaveCb cb) { - if (m_setHotspotLeaveCb.empty()) { - if (!SubscribeServiceEvent(WIFI_USUAL_EVENT_STA_LEAVE)) { - return false; - } - } - return m_setHotspotLeaveCb.insert(cb).second; - } - - void RemoveHotspotLeaveCb(const HotspotLeaveCb cb) { - m_setHotspotLeaveCb.erase(cb); - if (m_setHotspotLeaveCb.empty()) { - UnsubscribeServiceEvent(WIFI_USUAL_EVENT_STA_LEAVE); - } - } - - static std::set GetHotspotLeaveCb() { - return m_setHotspotLeaveCb; - } - - class WifiEventSubscriber : public OHOS::EventFwk::CommonEventSubscriber { - public: - explicit WifiEventSubscriber(const OHOS::EventFwk::CommonEventSubscribeInfo &subscribeInfo) - : CommonEventSubscriber(subscribeInfo) { - } - - virtual ~WifiEventSubscriber() { - } - - virtual void OnReceiveEvent(const OHOS::EventFwk::CommonEventData &data) override { - std::string event = data.GetWant().GetAction(); - int code = data.GetCode(); - WIFI_LOGI("Received event: %{public}s, value: %{public}d", event.c_str(), code); - if (event == WIFI_USUAL_EVENT_CONN_STATE && !GetConnectionChangeCb().empty()) { - WifiLinkedInfo linkInfo; - WifiErrorCode ret = GetLinkedInfo(&linkInfo); - if (ret != WIFI_SUCCESS) { - WIFI_LOGE("Received event get linked info failed"); - return; - } - for (auto& cb : GetConnectionChangeCb()) { - cb(code, &linkInfo); - } - } - - if (event == WIFI_USUAL_EVENT_SCAN_STATE && !EventManager::m_setScanStateChangeCb.empty()) { - for (auto& cb : EventManager::m_setScanStateChangeCb) { - cb(code, WIFI_SCAN_HOTSPOT_LIMIT); - } - } - - if (event == WIFI_USUAL_EVENT_HOTSPOT_STATE && !EventManager::m_setHotspotChangeCb.empty()) { - for (auto& cb : EventManager::m_setHotspotChangeCb) { - cb(code); - } - } - - if (event == WIFI_USUAL_EVENT_STA_JOIN && !EventManager::m_setHotspotJoinCb.empty()) { - } - - if (event == WIFI_USUAL_EVENT_STA_LEAVE && !EventManager::m_setHotspotLeaveCb.empty()) { - } - } - }; - - bool SubscribeServiceEvent(const std::string& event) { - MatchingSkills matchingSkills; - matchingSkills.AddEvent(event); - CommonEventSubscribeInfo subscriberInfo(matchingSkills); - std::shared_ptr subscriber = std::make_shared(subscriberInfo); - WIFI_LOGI("Subscribe event: %{public}s", event.c_str()); - bool subscribeResult = CommonEventManager::SubscribeCommonEvent(subscriber); - if (subscribeResult) { - m_mapEventSubscriber[event] = subscriber; - } else { - WIFI_LOGE("Subscribe service event fail: %{public}s", event.c_str()); - } - return subscribeResult; - } - - bool UnsubscribeServiceEvent(const std::string& event) { - std::map>::iterator iter; - iter = m_mapEventSubscriber.find(event); - if (iter == m_mapEventSubscriber.end()) { - return false; - } - - bool unsubscribeResult = CommonEventManager::SubscribeCommonEvent(iter->second); - if (!unsubscribeResult) { - WIFI_LOGE("Unsubscribe event fail: %{public}s", event.c_str()); - } - return unsubscribeResult; - } - -private: - static std::set m_setConnectionChangeCb; - static std::set m_setScanStateChangeCb; - static std::set m_setHotspotChangeCb; - static std::set m_setHotspotJoinCb; - static std::set m_setHotspotLeaveCb; - std::map > m_mapEventSubscriber; -}; -std::set EventManager::m_setConnectionChangeCb; -std::set EventManager::m_setScanStateChangeCb; -std::set EventManager::m_setHotspotChangeCb; -std::set EventManager::m_setHotspotJoinCb; -std::set EventManager::m_setHotspotLeaveCb; - -static EventManager g_eventManager; - -WifiErrorCode RegisterWifiEvent(WifiEvent *event) -{ - WIFI_LOGI("Register wifi event"); - if (event == nullptr) { - return ERROR_WIFI_INVALID_ARGS; - } - - if (event->OnWifiConnectionChanged != nullptr) { - return g_eventManager.AddConnectionChangeCb(event->OnWifiConnectionChanged) - ? WIFI_SUCCESS : ERROR_WIFI_INVALID_ARGS; - } - if (event->OnWifiScanStateChanged != nullptr) { - return g_eventManager.AddScanStateChangeCb(event->OnWifiScanStateChanged) - ? WIFI_SUCCESS : ERROR_WIFI_INVALID_ARGS; - } - if (event->OnHotspotStateChanged != nullptr) { - return g_eventManager.AddHotspotChangeCb(event->OnHotspotStateChanged) - ? WIFI_SUCCESS : ERROR_WIFI_INVALID_ARGS; - } - if (event->OnHotspotStaJoin != nullptr) { - return g_eventManager.AddHotspotJoinCb(event->OnHotspotStaJoin) - ? WIFI_SUCCESS : ERROR_WIFI_INVALID_ARGS; - } - if (event->OnHotspotStaLeave != nullptr) { - return g_eventManager.AddHotspotLeaveCb(event->OnHotspotStaLeave) - ? WIFI_SUCCESS : ERROR_WIFI_INVALID_ARGS; - } - return ERROR_WIFI_INVALID_ARGS; -} - -WifiErrorCode UnRegisterWifiEvent(const WifiEvent *event) -{ - WIFI_LOGI("Unregister wifi event"); - if (event == nullptr) { - return ERROR_WIFI_INVALID_ARGS; - } - - if (event->OnWifiConnectionChanged != nullptr) { - g_eventManager.RemoveConnectionChangeCb(event->OnWifiConnectionChanged); - } - if (event->OnWifiScanStateChanged != nullptr) { - g_eventManager.RemoveScanStateChangeCb(event->OnWifiScanStateChanged); - } - if (event->OnHotspotStateChanged != nullptr) { - g_eventManager.RemoveHotspotChangeCb(event->OnHotspotStateChanged); - } - if (event->OnHotspotStaJoin != nullptr) { - g_eventManager.RemoveHotspotJoinCb(event->OnHotspotStaJoin); - } - if (event->OnHotspotStaLeave != nullptr) { - g_eventManager.RemoveHotspotLeaveCb(event->OnHotspotStaLeave); - } - return WIFI_SUCCESS; -} diff --git a/interfaces/kits/jskits/@ohos.wifi.d.ts b/interfaces/kits/jskits/@ohos.wifi.d.ts deleted file mode 100755 index 6da7d84a8a0973f72a44d059b58ecf33bfe52bbc..0000000000000000000000000000000000000000 --- a/interfaces/kits/jskits/@ohos.wifi.d.ts +++ /dev/null @@ -1,202 +0,0 @@ -/* - * Copyright (C) 2021 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -import { AsyncCallback } from "./basic"; - -/** - * Provides methods to operate or manage Wi-Fi. - * - * @SysCap SystemCapability.Communication.WifiDevice - * @devices phone, tablet - * @since 6 - */ -declare namespace wifi { - /** - * Enables Wi-Fi. - * - * @return Returns {@code true} if the operation is successful; returns {@code false} otherwise. - * - * @since 6 - * @systemapi Hide this for inner system use. - */ - function enableWifi(): boolean; - - /** - * Disables Wi-Fi. - * - * @return Returns {@code true} if the operation is successful; returns {@code false} otherwise. - * - * @since 6 - * @systemapi Hide this for inner system use. - */ - function disableWifi(): boolean; - - /** - * Queries the Wi-Fi status - * - * @return Returns {@code true} if the Wi-Fi is active; returns {@code false} otherwise. - * - * @since 6 - */ - function isWifiActive(): boolean; - - /** - * Scans Wi-Fi hotspots with parameters. - * - *

This API works in asynchronous mode.

- * - * @return Returns {@code true} if the scanning is successful; returns {@code false} otherwise. - * - * @since 6 - */ - function scan(): boolean; - - /** - * Obtains the hotspot information that scanned. - * - * @return Returns information about scanned Wi-Fi hotspots if any. - * - * @since 6 - */ - function getScanInfos(): Promise>; - function getScanInfos(callback: AsyncCallback>): void; - - /** - * Adds Wi-Fi connection configuration to the device. - * - *

The configuration will be updated when the configuration is added.

- * - * @return Returns {@code networkId} if the configuration is added; returns {@code -1} otherwise. - * - * @devices phone, tablet - * @since 6 - * @systemapi Hide this for inner system use. - */ - function addDeviceConfig(config: WifiDeviceConfig): Promise; - function addDeviceConfig(config: WifiDeviceConfig, callback: AsyncCallback): void; - - /** - * Connects to Wi-Fi network. - * - * @param networkId ID of the connected network. - * @return Returns {@code true} if the network connection is successful; returns {@code false} otherwise. - * - * @since 6 - * @systemapi Hide this for inner system use. - */ - function connectToNetwork(networkId: number): boolean; - - /** - * Connects to Wi-Fi network. - * - * @param config Indicates the device configuration for connection to the Wi-Fi network. - * @return Returns {@code true} if the network connection is successful; returns {@code false} otherwise. - * - * @devices phone, tablet - * @since 6 - * @systemapi Hide this for inner system use. - */ - function connectToDevice(config: WifiDeviceConfig): boolean; - - /** - * Disconnects Wi-Fi network. - * - * @return Returns {@code true} for disconnecting network success, returns {@code false} otherwise. - * - * @since 6 - * @systemapi Hide this for inner system use. - */ - function disconnect(): boolean; - - /** - * Calculates the Wi-Fi signal level based on the Wi-Fi RSSI and frequency band. - * - * @param rssi Indicates the Wi-Fi RSSI. - * @band Indicates the Wi-Fi frequency band. - * @return Returns Wi-Fi signal level ranging from 0 to 4. - * - * @since 6 - */ - function getSignalLevel(rssi: number, band: number): number; - - /** - * Wi-Fi device configuration information. - * - * @devices phone, tablet - * @since 6 - * @systemapi Hide this for inner system use. - */ - interface WifiDeviceConfig { - /** Wi-Fi SSID: the maximum length is 32 */ - ssid: string; - - /** Wi-Fi bssid(MAC): the length is 6 */ - bssid: string; - - /** Wi-Fi key: maximum length is 64 */ - preSharedKey: string; - - /** Hide SSID or not, false(default): not hide */ - isHiddenSsid: boolean; - - /** Security type: reference definition of WifiSecurityType */ - securityType: number; - } - - /** - * Describes the scanned Wi-Fi information. - * - * @devices phone, tablet - * @since 6 - */ - interface WifiScanInfo { - /** Wi-Fi SSID: the maximum length is 32 */ - ssid: string; - - /** Wi-Fi bssid(MAC): the length is 6 */ - bssid: string; - - /** Security type: reference definition of WifiSecurityType */ - securityType: number; - - /** Received signal strength indicator (RSSI) */ - rssi: number; - - /** Frequency band, 1: 2.4G, 2: 5G */ - band: number; - - /** Frequency */ - frequency: number; - - /** Time stamp */ - timestamp: number; - } - - /** - * Describes the wifi security type. - * - * @devices phone, tablet - * @since 6 - */ - enum WifiSecurityType { - WIFI_SEC_TYPE_INVALID = 0, /* Invalid security type */ - WIFI_SEC_TYPE_OPEN = 1, /* Open */ - WIFI_SEC_TYPE_WEP = 2, /* Wired Equivalent Privacy (WEP) */ - WIFI_SEC_TYPE_PSK = 3, /* Pre-shared key (PSK) */ - WIFI_SEC_TYPE_SAE = 4, /* Simultaneous Authentication of Equals (SAE) */ - } -} - -export default wifi; diff --git a/ohos.build b/ohos.build deleted file mode 100755 index 098ff8f66ba86f101e23b7bbf2c4cc4a37344f48..0000000000000000000000000000000000000000 --- a/ohos.build +++ /dev/null @@ -1,90 +0,0 @@ -{ - "subsystem": "communication", - "parts": { - "wifi_standard": { - "module_list": [ - "//foundation/communication/wifi/interfaces/innerkits/native_cpp/wifi_standard:wifi_sdk", - "//foundation/communication/wifi/services/wifi_standard/wifi_framework:wifi_manage", - "//foundation/communication/wifi/services/wifi_standard/wifi_framework:dhcp_manage", - "//foundation/communication/wifi/services/wifi_standard/wifi_hal:wifi_hal_service", - "//foundation/communication/wifi/services/wifi_standard/wifi_framework:wifi_system_ability", - "//foundation/communication/wifi/services/wifi_standard/sa_profile:wifi_standard_sa_profile" - ], - "wifi_system_ability": { - "module_list": [ - "//foundation/communication/wifi/services/wifi_standard/wifi_framework/wifi_manage:wifi_device_ability", - "//foundation/communication/wifi/services/wifi_standard/wifi_framework/wifi_manage:wifi_scan_ability", - "//foundation/communication/wifi/services/wifi_standard/wifi_framework/wifi_manage:wifi_hotspot_ability", - "//foundation/communication/wifi/services/wifi_standard/wifi_framework/wifi_manage:wifi_p2p_ability" - ] - }, - "wifi_manage": { - "module_list": [ - "//foundation/communication/wifi/services/wifi_standard/wifi_framework/wifi_manage:wifi_manager_service", - "//foundation/communication/wifi/services/wifi_standard/wifi_framework/wifi_manage/idl_client:wifi_idl_client", - "//foundation/communication/wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_scan:wifi_scan_service", - "//foundation/communication/wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_sta:wifi_sta_service", - "//foundation/communication/wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_ap:wifi_ap_service", - "//foundation/communication/wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_p2p:wifi_p2p_service" - ], - "wifi_idl_client": [ - { - "type": "so", - "name": "//foundation/communication/wifi/services/wifi_standard/wifi_framework/wifi_manage/idl_client:wifi_idl_client", - "header": { - "header_files": [ - "idl_client.h", - "wifi_idl_define.h" - ], - "header_base": "//foundation/communication/wifi/services/wifi_standard/wifi_framework/wifi_manage/idl_client" - } - } - ] - }, - "dhcp_manage": { - "module_list": [ - "//foundation/communication/wifi/services/wifi_standard/wifi_framework/dhcp_manage/mgr_service:dhcp_manager_service", - "//foundation/communication/wifi/services/wifi_standard/wifi_framework/dhcp_manage/dhcp_client:dhcp_client_service", - "//foundation/communication/wifi/services/wifi_standard/wifi_framework/dhcp_manage/dhcp_server:dhcp_server" - ] - }, - "wifi_hal_service": [ - { - "type": "so", - "name": "//foundation/communication/wifi/services/wifi_standard/wifi_hal:wifi_hal_service", - "header": { - "header_files": [ - "wifi_hal_define.h", - "wifi_hal_sta_interface.h", - "wifi_hal_ap_interface.h", - "wifi_hal_struct.h" - ], - "header_base": "//foundation/communication/wifi/services/wifi_standard/wifi_hal/" - } - } - ], - "test_list": [ - "//foundation/communication/wifi/tests/wifi_standard/wifi_framework/wifi_manage/wifi_scan:unittest", - "//foundation/communication/wifi/tests/wifi_standard/wifi_framework/wifi_manage/wifi_sta:unittest", - "//foundation/communication/wifi/tests/wifi_standard/wifi_framework/wifi_manage/wifi_ap/wifi_hotspot_test:unittest", - "//foundation/communication/wifi/tests/wifi_standard/wifi_framework/wifi_manage/wifi_ap/:unittest", - "//foundation/communication/wifi/tests/wifi_standard/wifi_framework/wifi_manage/wifi_ap/wifi_ap_dhcp_nat:unittest", - "//foundation/communication/wifi/tests/wifi_standard/wifi_framework/dhcp_manage/mgr_service:unittest", - "//foundation/communication/wifi/tests/wifi_standard/wifi_framework/dhcp_manage/dhcp_client:unittest", - "//foundation/communication/wifi/tests/wifi_standard/wifi_framework/dhcp_manage/dhcp_server/unittest:unittest", - "//foundation/communication/wifi/tests/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/test:unittest", - "//foundation/communication/wifi/tests/wifi_standard/ipc_framework/cRPC/unittest:unittest", - "//foundation/communication/wifi/tests/wifi_standard/wifi_framework/common/unittest:unittest", - "//foundation/communication/wifi/tests/wifi_standard/wifi_framework/wifi_manage/unittest:unittest", - "//foundation/communication/wifi/tests/wifi_standard/wifi_framework/wifi_manage/idl_client/unittest:unittest", - "//foundation/communication/wifi/tests/wifi_standard/wifi_hal/unittest:unittest" - ] - }, - - "wifi_native_js": { - "module_list": [ - "//foundation/communication/wifi/interfaces/innerkits/native_cpp/napi:wifi_native_js" - ] - } - } -} diff --git a/services/wifi_standard/wifi_framework/BUILD.gn b/services/wifi_standard/wifi_framework/BUILD.gn deleted file mode 100644 index fe2de5aabb2ff30d3a7469b095b9bb83174024b3..0000000000000000000000000000000000000000 --- a/services/wifi_standard/wifi_framework/BUILD.gn +++ /dev/null @@ -1,43 +0,0 @@ -# Copyright (C) 2021 Huawei Device Co., Ltd. -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -import("//build/ohos.gni") - -group("wifi_system_ability") { - deps = [ - "//foundation/communication/wifi/services/wifi_standard/sa_profile:wifi_standard_sa_profile", - "//foundation/communication/wifi/services/wifi_standard/wifi_framework/wifi_manage:wifi_device_ability", - "//foundation/communication/wifi/services/wifi_standard/wifi_framework/wifi_manage:wifi_hotspot_ability", - "//foundation/communication/wifi/services/wifi_standard/wifi_framework/wifi_manage:wifi_p2p_ability", - "//foundation/communication/wifi/services/wifi_standard/wifi_framework/wifi_manage:wifi_scan_ability", - ] -} - -group("wifi_manage") { - deps = [ - "//foundation/communication/wifi/services/wifi_standard/wifi_framework/wifi_manage:wifi_manager_service", - "//foundation/communication/wifi/services/wifi_standard/wifi_framework/wifi_manage/idl_client:wifi_idl_client", - "//foundation/communication/wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_ap:wifi_ap_service", - "//foundation/communication/wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_p2p:wifi_p2p_service", - "//foundation/communication/wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_scan:wifi_scan_service", - "//foundation/communication/wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_sta:wifi_sta_service", - ] -} - -group("dhcp_manage") { - deps = [ - "//foundation/communication/wifi/services/wifi_standard/wifi_framework/dhcp_manage/dhcp_client:dhcp_client_service", - "//foundation/communication/wifi/services/wifi_standard/wifi_framework/dhcp_manage/dhcp_server:dhcp_server", - "//foundation/communication/wifi/services/wifi_standard/wifi_framework/dhcp_manage/mgr_service:dhcp_manager_service", - ] -} diff --git a/services/wifi_standard/wifi_framework/dhcp_manage/dhcp_client/BUILD.gn b/services/wifi_standard/wifi_framework/dhcp_manage/dhcp_client/BUILD.gn deleted file mode 100644 index ab41006378d5be4a2437a79a8840c86cb6a26939..0000000000000000000000000000000000000000 --- a/services/wifi_standard/wifi_framework/dhcp_manage/dhcp_client/BUILD.gn +++ /dev/null @@ -1,57 +0,0 @@ -# Copyright (C) 2021 Huawei Device Co., Ltd. -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -import("//build/ohos.gni") -import("//foundation/appexecfwk/standard/appexecfwk.gni") - -################################################################################ - -ohos_executable("dhcp_client_service") { - install_enable = true - sources = [ - "//foundation/communication/wifi/services/wifi_standard/wifi_framework/dhcp_manage/dhcp_client/src/dhcp_api.cpp", - "//foundation/communication/wifi/services/wifi_standard/wifi_framework/dhcp_manage/dhcp_client/src/dhcp_client.c", - "//foundation/communication/wifi/services/wifi_standard/wifi_framework/dhcp_manage/dhcp_client/src/dhcp_function.c", - "//foundation/communication/wifi/services/wifi_standard/wifi_framework/dhcp_manage/dhcp_client/src/dhcp_ipv4.c", - "//foundation/communication/wifi/services/wifi_standard/wifi_framework/dhcp_manage/dhcp_client/src/dhcp_main.c", - "//foundation/communication/wifi/services/wifi_standard/wifi_framework/dhcp_manage/dhcp_client/src/dhcp_options.c", - "//foundation/communication/wifi/services/wifi_standard/wifi_framework/dhcp_manage/dhcp_client/src/dhcp_socket.c", - ] - - include_dirs = [ - "//foundation/communication/wifi/services/wifi_standard/wifi_framework/common/log", - "//foundation/communication/wifi/services/wifi_standard/wifi_framework/dhcp_manage/dhcp_client/include", - "//utils/native/base/include", - "//foundation/appexecfwk/standard/interfaces/innerkits/libeventhandler/include", - "//foundation/communication/ipc/interfaces/innerkits/ipc_core/include", - "//third_party/openssl/include", - ] - - deps = [ - "${aafwk_path}/interfaces/innerkits/base:base", - "${aafwk_path}/interfaces/innerkits/want:want", - "//third_party/openssl:libcrypto_static", - "//utils/native/base:utils", - ] - - cflags_cc = [ "-fno-rtti" ] - - external_deps = [ - "ces_standard:cesfwk_innerkits", - "hiviewdfx_hilog_native:libhilog", - ] - defines = [] - - part_name = "wifi_standard" - subsystem_name = "communication" -} diff --git a/services/wifi_standard/wifi_framework/dhcp_manage/mgr_service/BUILD.gn b/services/wifi_standard/wifi_framework/dhcp_manage/mgr_service/BUILD.gn deleted file mode 100644 index b68e530af31939700748747beaa4f1d1026218b7..0000000000000000000000000000000000000000 --- a/services/wifi_standard/wifi_framework/dhcp_manage/mgr_service/BUILD.gn +++ /dev/null @@ -1,60 +0,0 @@ -# Copyright (C) 2021 Huawei Device Co., Ltd. -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -import("//build/ohos.gni") -import("//foundation/appexecfwk/standard/appexecfwk.gni") - -################################################################################ - -ohos_shared_library("dhcp_manager_service") { - install_enable = true - sources = [ - "//foundation/communication/wifi/services/wifi_standard/wifi_framework/dhcp_manage/mgr_service/src/dhcp_client_service_impl.cpp", - "//foundation/communication/wifi/services/wifi_standard/wifi_framework/dhcp_manage/mgr_service/src/dhcp_event_subscriber.cpp", - "//foundation/communication/wifi/services/wifi_standard/wifi_framework/dhcp_manage/mgr_service/src/dhcp_func.cpp", - "//foundation/communication/wifi/services/wifi_standard/wifi_framework/dhcp_manage/mgr_service/src/dhcp_server_service.cpp", - "//foundation/communication/wifi/services/wifi_standard/wifi_framework/dhcp_manage/mgr_service/src/dhcp_service.cpp", - ] - - include_dirs = [ - "//foundation/communication/wifi/services/wifi_standard/wifi_framework/common/log", - "//foundation/communication/wifi/services/wifi_standard/wifi_framework/dhcp_manage/mgr_service/include", - "//foundation/communication/wifi/services/wifi_standard/wifi_framework/dhcp_manage/mgr_service/interfaces", - "//utils/native/base/include", - "//foundation/appexecfwk/standard/interfaces/innerkits/libeventhandler/include", - "//foundation/communication/ipc/interfaces/innerkits/ipc_core/include", - ] - - deps = [ - "${aafwk_path}/interfaces/innerkits/base:base", - "${aafwk_path}/interfaces/innerkits/want:want", - "//utils/native/base:utils", - ] - - cflags_cc = [ - "-std=c++17", - "-Wall", - ] - - external_deps = [ - "ces_standard:cesfwk_innerkits", - "hiviewdfx_hilog_native:libhilog", - ] - ldflags = [ - "-fPIC", - "-Wl,-E", - ] - - part_name = "wifi_standard" - subsystem_name = "communication" -} diff --git a/services/wifi_standard/wifi_framework/wifi_manage/BUILD.gn b/services/wifi_standard/wifi_framework/wifi_manage/BUILD.gn deleted file mode 100755 index bbb4334ccdcb1c168a5a11ffae5baea4bc910d36..0000000000000000000000000000000000000000 --- a/services/wifi_standard/wifi_framework/wifi_manage/BUILD.gn +++ /dev/null @@ -1,226 +0,0 @@ -# Copyright (C) 2021 Huawei Device Co., Ltd. -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -import("//build/ohos.gni") -import("//build/ohos/sa_profile/sa_profile.gni") -import("//build/ohos_var.gni") -import("//foundation/appexecfwk/standard/appexecfwk.gni") - -################################################################################ - -config("wifi_manager_service_header") { - include_dirs = [ - "//utils/native/base/include", - "//base/hiviewdfx/hilog/interfaces/native/innerkits/include", - "//foundation/ace/ace_engine/frameworks/base/utils", - "//foundation/ace/ace_engine/frameworks", - "//foundation/distributedschedule/safwk/interfaces/innerkits/safwk/", - "//foundation/communication/wifi/interfaces/innerkits/native_cpp/wifi_standard/interfaces", - "//foundation/communication/wifi/services/wifi_standard/ipc_framework/cRPC/include", - "//foundation/communication/wifi/services/wifi_standard/wifi_framework/common/include", - "//foundation/communication/wifi/services/wifi_standard/wifi_framework/common/log", - "//foundation/communication/wifi/services/wifi_standard/wifi_framework/common/net_helper", - "//foundation/communication/wifi/services/wifi_standard/wifi_framework/common/utils", - "//foundation/communication/wifi/services/wifi_standard/wifi_framework/common/config", - "//foundation/communication/wifi/services/wifi_standard/wifi_framework/wifi_manage", - "//foundation/communication/wifi/services/wifi_standard/wifi_framework/wifi_manage/common", - "//foundation/communication/wifi/services/wifi_standard/wifi_framework/wifi_manage/idl_client", - "//foundation/communication/wifi/services/wifi_standard/wifi_framework/wifi_manage/idl_client/idl_interface", - "//foundation/communication/wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_sta", - "//foundation/communication/wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_scan", - "//foundation/communication/wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_ap", - "//foundation/communication/wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_p2p", - "//foundation/communication/wifi/services/wifi_standard/wifi_framework/dhcp_manage/mgr_service/include", - "//foundation/communication/wifi/services/wifi_standard/wifi_framework/dhcp_manage/mgr_service/interfaces", - "${aafwk_path}/interfaces/innerkits/want/include", - "${aafwk_path}/interfaces/innerkits/want/include/ohos/aafwk/content", - "//foundation/distributedschedule/dmsfwk/services/dtbschedmgr/include", - "//foundation/aafwk/intent/interfaces/innerkits/base/include", - "//foundation/appexecfwk/adapter/interfaces/innerkits/appexecfwk_base/include", - "//foundation/appexecfwk/standard/interfaces/innerkits/libeventhandler/include", - "//foundation/aafwk/standard/interfaces/innerkits/base/include", - "//foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_base/include", - ] -} - -config("wifi_manager_service_config") { - visibility = [ "//:*" ] - include_dirs = [ ":wifi_fw_common_header" ] - - cflags = [ - "-std=c++17", - "-fno-rtti", - ] - if (target_cpu == "arm") { - cflags += [ "-DBINDER_IPC_32BIT" ] - } -} - -ohos_source_set("wifi_scan_service_impl") { - sources = [ - "wifi_scan_callback_proxy.cpp", - "wifi_scan_death_recipient.cpp", - "wifi_scan_service_impl.cpp", - "wifi_scan_stub.cpp", - ] - configs = [ - ":wifi_manager_service_config", - ":wifi_manager_service_header", - ] - - external_deps = [ "ipc:ipc_core" ] -} -ohos_source_set("wifi_device_service_impl") { - sources = [ - "wifi_device_callback_proxy.cpp", - "wifi_device_death_recipient.cpp", - "wifi_device_service_impl.cpp", - "wifi_device_stub.cpp", - ] - configs = [ - ":wifi_manager_service_config", - ":wifi_manager_service_header", - ] - - external_deps = [ "ipc:ipc_core" ] -} -ohos_source_set("wifi_hotspot_service_impl") { - sources = [ - "wifi_hotspot_callback_proxy.cpp", - "wifi_hotspot_death_recipient.cpp", - "wifi_hotspot_service_impl.cpp", - "wifi_hotspot_stub.cpp", - ] - configs = [ - ":wifi_manager_service_config", - ":wifi_manager_service_header", - ] - - external_deps = [ "ipc:ipc_core" ] -} -ohos_source_set("wifi_p2p_service_impl") { - sources = [ - "//foundation/communication/wifi/interfaces/innerkits/native_cpp/wifi_standard/src/wifi_p2p_msg.cpp", - "wifi_p2p_callback_proxy.cpp", - "wifi_p2p_death_recipient.cpp", - "wifi_p2p_service_impl.cpp", - "wifi_p2p_stub.cpp", - ] - configs = [ - ":wifi_manager_service_config", - ":wifi_manager_service_header", - ] - - external_deps = [ "ipc:ipc_core" ] -} -ohos_shared_library("wifi_manager_service") { - install_enable = true - sources = [ - "//foundation/communication/wifi/services/wifi_standard/wifi_framework/common/config/wifi_config_file_spec.cpp", - "//foundation/communication/wifi/services/wifi_standard/wifi_framework/common/config/wifi_settings.cpp", - "//foundation/communication/wifi/services/wifi_standard/wifi_framework/common/log/log_helper.c", - "//foundation/communication/wifi/services/wifi_standard/wifi_framework/common/net_helper/base_address.cpp", - "//foundation/communication/wifi/services/wifi_standard/wifi_framework/common/net_helper/ip_tools.cpp", - "//foundation/communication/wifi/services/wifi_standard/wifi_framework/common/net_helper/ipv4_address.cpp", - "//foundation/communication/wifi/services/wifi_standard/wifi_framework/common/net_helper/ipv6_address.cpp", - "//foundation/communication/wifi/services/wifi_standard/wifi_framework/common/net_helper/mac_address.cpp", - "//foundation/communication/wifi/services/wifi_standard/wifi_framework/common/net_helper/network_interface.cpp", - "//foundation/communication/wifi/services/wifi_standard/wifi_framework/common/utils/wifi_common_event_helper.cpp", - "//foundation/communication/wifi/services/wifi_standard/wifi_framework/common/utils/wifi_global_func.cpp", - "//foundation/communication/wifi/services/wifi_standard/wifi_framework/wifi_manage/common/wifi_permission_helper.cpp", - "//foundation/communication/wifi/services/wifi_standard/wifi_framework/wifi_manage/common/wifi_permission_utils.cpp", - "wifi_auth_center.cpp", - "wifi_config_center.cpp", - "wifi_internal_event_dispatcher.cpp", - "wifi_manager.cpp", - "wifi_service_manager.cpp", - ] - - deps = [ - "${aafwk_path}/interfaces/innerkits/base:base", - "${aafwk_path}/interfaces/innerkits/want:want", - "//base/hiviewdfx/hilog/interfaces/native/innerkits:libhilog", - "//foundation/communication/wifi/services/wifi_standard/etc/init:etc", - "//foundation/communication/wifi/services/wifi_standard/wifi_framework/wifi_manage/idl_client:wifi_idl_client", - "//foundation/distributedschedule/safwk/interfaces/innerkits/safwk:system_ability_fwk", - "//utils/native/base:utils", - ] - - defines = [ "PERMISSION_ALWAYS_GRANT" ] - - configs = [ ":wifi_manager_service_header" ] - - external_deps = [ - "ces_standard:cesfwk_innerkits", - "ipc:ipc_core", - ] - - part_name = "wifi_standard" - subsystem_name = "communication" -} -ohos_shared_library("wifi_device_ability") { - install_enable = true - deps = [ - ":wifi_device_service_impl", - ":wifi_manager_service", - "//base/hiviewdfx/hilog/interfaces/native/innerkits:libhilog", - "//foundation/distributedschedule/safwk/interfaces/innerkits/safwk:system_ability_fwk", - "//utils/native/base:utils", - ] - - external_deps = [ "ipc:ipc_core" ] - part_name = "wifi_standard" - subsystem_name = "communication" -} -ohos_shared_library("wifi_scan_ability") { - install_enable = true - deps = [ - ":wifi_manager_service", - ":wifi_scan_service_impl", - "//base/hiviewdfx/hilog/interfaces/native/innerkits:libhilog", - "//foundation/distributedschedule/safwk/interfaces/innerkits/safwk:system_ability_fwk", - "//utils/native/base:utils", - ] - - external_deps = [ "ipc:ipc_core" ] - part_name = "wifi_standard" - subsystem_name = "communication" -} -ohos_shared_library("wifi_hotspot_ability") { - install_enable = true - deps = [ - ":wifi_hotspot_service_impl", - ":wifi_manager_service", - "//base/hiviewdfx/hilog/interfaces/native/innerkits:libhilog", - "//foundation/distributedschedule/safwk/interfaces/innerkits/safwk:system_ability_fwk", - "//utils/native/base:utils", - ] - - external_deps = [ "ipc:ipc_core" ] - part_name = "wifi_standard" - subsystem_name = "communication" -} -ohos_shared_library("wifi_p2p_ability") { - install_enable = true - deps = [ - ":wifi_manager_service", - ":wifi_p2p_service_impl", - "//base/hiviewdfx/hilog/interfaces/native/innerkits:libhilog", - "//foundation/distributedschedule/safwk/interfaces/innerkits/safwk:system_ability_fwk", - "//utils/native/base:utils", - ] - - external_deps = [ "ipc:ipc_core" ] - part_name = "wifi_standard" - subsystem_name = "communication" -} diff --git a/services/wifi_standard/wifi_framework/wifi_manage/idl_client/BUILD.gn b/services/wifi_standard/wifi_framework/wifi_manage/idl_client/BUILD.gn deleted file mode 100644 index f3e92463360efbc7acbe57def1ea47b21a3973c8..0000000000000000000000000000000000000000 --- a/services/wifi_standard/wifi_framework/wifi_manage/idl_client/BUILD.gn +++ /dev/null @@ -1,125 +0,0 @@ -# Copyright (C) 2021 Huawei Device Co., Ltd. -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -import("//build/ohos.gni") - -config("wifi_fw_common_header") { - include_dirs = [ - "idl_interface", - "//utils/native/base/include", - "//base/hiviewdfx/hilog/interfaces/native/innerkits/include", - "//foundation/communication/wifi/interfaces/innerkits/native_cpp/wifi_standard/interfaces", - "//foundation/communication/wifi/services/wifi_standard/sdk/include", - "//foundation/communication/wifi/services/wifi_standard/ipc_framework/cRPC/include", - "//foundation/communication/wifi/services/wifi_standard/wifi_framework/common/include", - "//foundation/communication/wifi/services/wifi_standard/wifi_framework/common/net_helper", - "//foundation/communication/wifi/services/wifi_standard/wifi_framework/common/log", - "//foundation/communication/wifi/services/wifi_standard/wifi_framework/common/config", - "//foundation/communication/wifi/services/wifi_standard/wifi_framework/common/utils", - "//foundation/communication/wifi/services/wifi_standard/ipc_framework/interface", - "//foundation/communication/wifi/services/wifi_standard/wifi_framework/wifi_manage/idl_client", - ] -} - -config("wifi_idl_cxx_config") { - visibility = [ "//:*" ] - include_dirs = [ ":wifi_fw_common_header" ] - - cflags = [ - "-std=c++17", - "-fno-rtti", - ] - - if (target_cpu == "arm") { - cflags += [ "-DBINDER_IPC_32BIT" ] - } -} - -ohos_source_set("wifi_utils") { - sources = [ "//foundation/communication/wifi/services/wifi_standard/wifi_framework/common/utils/wifi_global_func.cpp" ] - - configs = [ - ":wifi_idl_cxx_config", - ":wifi_fw_common_header", - ] -} - -ohos_source_set("net_helper") { - sources = [ - "//foundation/communication/wifi/services/wifi_standard/wifi_framework/common/net_helper/base_address.cpp", - "//foundation/communication/wifi/services/wifi_standard/wifi_framework/common/net_helper/http_request.cpp", - "//foundation/communication/wifi/services/wifi_standard/wifi_framework/common/net_helper/ip_tools.cpp", - "//foundation/communication/wifi/services/wifi_standard/wifi_framework/common/net_helper/ipv4_address.cpp", - "//foundation/communication/wifi/services/wifi_standard/wifi_framework/common/net_helper/ipv6_address.cpp", - "//foundation/communication/wifi/services/wifi_standard/wifi_framework/common/net_helper/mac_address.cpp", - "//foundation/communication/wifi/services/wifi_standard/wifi_framework/common/net_helper/network_interface.cpp", - ] - - configs = [ - ":wifi_idl_cxx_config", - ":wifi_fw_common_header", - ] -} - -ohos_source_set("log_helper") { - sources = [ "//foundation/communication/wifi/services/wifi_standard/wifi_framework/common/log/log_helper.c" ] - - configs = [ ":wifi_fw_common_header" ] -} - -ohos_shared_library("wifi_idl_client") { - install_enable = true - sources = [ - "//foundation/communication/wifi/interfaces/innerkits/native_cpp/wifi_standard/src/wifi_p2p_msg.cpp", - "idl_interface/i_wifi.c", - "idl_interface/i_wifi_chip.c", - "idl_interface/i_wifi_hotspot_iface.c", - "idl_interface/i_wifi_iface.c", - "idl_interface/i_wifi_p2p_iface.c", - "idl_interface/i_wifi_public_func.c", - "idl_interface/i_wifi_sta_iface.c", - "idl_interface/i_wifi_supplicant_iface.c", - "wifi_ap_hal_interface.cpp", - "wifi_base_hal_interface.cpp", - "wifi_chip_hal_interface.cpp", - "wifi_idl_client.cpp", - "wifi_idl_inner_interface.cpp", - "wifi_p2p_hal_interface.cpp", - "wifi_sta_hal_interface.cpp", - "wifi_supplicant_hal_interface.cpp", - ] - - configs = [ ":wifi_fw_common_header" ] - - deps = [ - ":log_helper", - ":net_helper", - ":wifi_utils", - "//foundation/communication/wifi/services/wifi_standard/ipc_framework/cRPC:crpc_client", - "//utils/native/base:utils", - ] - - external_deps = [ "hiviewdfx_hilog_native:libhilog" ] - cflags_cc = [ - "-std=c++17", - "-fno-rtti", - ] - - ldflags = [ - "-fPIC", - "-Wl,-E", - ] - - part_name = "wifi_standard" - subsystem_name = "communication" -} diff --git a/services/wifi_standard/wifi_framework/wifi_manage/wifi_scan/BUILD.gn b/services/wifi_standard/wifi_framework/wifi_manage/wifi_scan/BUILD.gn deleted file mode 100644 index caa661a47f91ed318a48878d4998ae8138d31e87..0000000000000000000000000000000000000000 --- a/services/wifi_standard/wifi_framework/wifi_manage/wifi_scan/BUILD.gn +++ /dev/null @@ -1,76 +0,0 @@ -# Copyright (C) 2021 Huawei Device Co., Ltd. -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -import("//build/ohos.gni") - -ohos_shared_library("wifi_scan_service") { - install_enable = true - sources = [ - "../common/handler.cpp", - "../common/internal_message.cpp", - "../common/message_queue.cpp", - "../common/state.cpp", - "../common/state_machine.cpp", - "//foundation/communication/wifi/services/wifi_standard/wifi_framework/common/log/log_helper.c", - "scan_interface.cpp", - "scan_monitor.cpp", - "scan_service.cpp", - "scan_state_machine.cpp", - ] - - include_dirs = [ - "//utils/native/base/include", - "//foundation/communication/wifi/interfaces/innerkits/native_cpp/wifi_standard/interfaces", - "//foundation/communication/wifi/services/wifi_standard/ipc_framework/interface", - "//foundation/communication/wifi/services/wifi_standard/ipc_framework/cRPC/include", - "//foundation/communication/wifi/services/wifi_standard/wifi_framework/common/include", - "//foundation/communication/wifi/services/wifi_standard/wifi_framework/common/config", - "//foundation/communication/wifi/services/wifi_standard/wifi_framework/common/log", - "//foundation/communication/wifi/services/wifi_standard/wifi_framework/common/utils", - "//foundation/communication/wifi/services/wifi_standard/wifi_framework/common/net_helper", - "//foundation/communication/wifi/services/wifi_standard/wifi_framework/wifi_manage/common", - "//foundation/communication/wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_scan", - "//foundation/communication/wifi/services/wifi_standard/wifi_framework/wifi_manage/", - "//foundation/communication/wifi/services/wifi_standard/wifi_framework/wifi_manage/idl_client", - "//foundation/communication/wifi/services/wifi_standard/wifi_framework/wifi_manage/idl_client/idl_interface", - "//foundation/communication/wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_sta/net_conf", - "//foundation/communication/wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_sta", - "//base/hiviewdfx/hilog/interfaces/native/innerkits/include", - "//foundation/communication/wifi/services/wifi_standard/depends/include/hardware/libhardware/include", - "//foundation/communication/wifi/services/wifi_standard/depends/include/system/core/include", - "//foundation/communication/wifi/services/wifi_standard/depends/include/frameworks/native/include", - "//foundation/communication/wifi/services/wifi_standard/depends/include/system/core/libutils/include", - "//foundation/communication/wifi/services/wifi_standard/depends/include/system/core/base/include", - "//foundation/communication/wifi/services/wifi_standard/depends/include/system/libbase/include", - ] - - deps = [ - "//foundation/communication/wifi/services/wifi_standard/wifi_framework/wifi_manage:wifi_manager_service", - "//foundation/communication/wifi/services/wifi_standard/wifi_framework/wifi_manage/idl_client:wifi_idl_client", - "//utils/native/base:utils", - ] - - external_deps = [ "hiviewdfx_hilog_native:libhilog" ] - cflags_cc = [ - "-std=c++17", - "-fno-rtti", - ] - - ldflags = [ - "-fPIC", - "-Wl,-E", - ] - - part_name = "wifi_standard" - subsystem_name = "communication" -} diff --git a/services/wifi_standard/wifi_framework/wifi_manage/wifi_sta/BUILD.gn b/services/wifi_standard/wifi_framework/wifi_manage/wifi_sta/BUILD.gn deleted file mode 100644 index 028d3826fb01b795c9f39fcba4ee22c9ce7f6423..0000000000000000000000000000000000000000 --- a/services/wifi_standard/wifi_framework/wifi_manage/wifi_sta/BUILD.gn +++ /dev/null @@ -1,86 +0,0 @@ -# Copyright (C) 2021 Huawei Device Co., Ltd. -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -import("//build/ohos.gni") - -ohos_shared_library("wifi_sta_service") { - install_enable = true - sources = [ - "../common/handler.cpp", - "../common/internal_message.cpp", - "../common/message_queue.cpp", - "../common/state.cpp", - "../common/state_machine.cpp", - "./net_conf/if_config.cpp", - "//foundation/communication/wifi/services/wifi_standard/wifi_framework/common/log/log_helper.c", - "//foundation/communication/wifi/services/wifi_standard/wifi_framework/common/net_helper/http_request.cpp", - "//foundation/communication/wifi/services/wifi_standard/wifi_framework/common/net_helper/ip_tools.cpp", - "sta_auto_connect_service.cpp", - "sta_interface.cpp", - "sta_monitor.cpp", - "sta_network_check.cpp", - "sta_network_speed.cpp", - "sta_saved_device_appraisal.cpp", - "sta_service.cpp", - "sta_state_machine.cpp", - ] - include_dirs = [ - "//foundation/communication/wifi/services/wifi_standard/sdk/include", - "//utils/native/base/include", - "//foundation/communication/wifi/interfaces/innerkits/native_cpp/wifi_standard/interfaces", - "//foundation/communication/wifi/services/wifi_standard/ipc_framework/interface", - "//foundation/communication/wifi/services/wifi_standard/ipc_framework/cRPC/include", - "//foundation/communication/wifi/services/wifi_standard/wifi_framework/common/include", - "//foundation/communication/wifi/services/wifi_standard/wifi_framework/common/net_helper", - "//foundation/communication/wifi/services/wifi_standard/wifi_framework/common/log", - "//foundation/communication/wifi/services/wifi_standard/wifi_framework/common/utils", - "//foundation/communication/wifi/services/wifi_standard/wifi_framework/common/config", - "//foundation/communication/wifi/services/wifi_standard/wifi_framework/wifi_manage/common", - "//foundation/communication/wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_scan", - "//foundation/communication/wifi/services/wifi_standard/wifi_framework/wifi_manage/idl_client", - "//foundation/communication/wifi/services/wifi_standard/wifi_framework/wifi_manage/idl_client/idl_interface", - "//foundation/communication/wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_sta/net_conf", - "//foundation/communication/wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_sta", - "//base/hiviewdfx/hilog/interfaces/native/innerkits/include", - "//foundation/communication/wifi/services/wifi_standard/depends/include/hardware/libhardware/include", - "//foundation/communication/wifi/services/wifi_standard/depends/include/system/core/include", - "//foundation/communication/wifi/services/wifi_standard/depends/include/frameworks/native/include", - "//foundation/communication/wifi/services/wifi_standard/depends/include/system/core/libutils/include", - "//foundation/communication/wifi/services/wifi_standard/depends/include/system/core/base/include", - "//foundation/communication/wifi/services/wifi_standard/depends/include/system/libbase/include", - "//foundation/communication/wifi/services/wifi_standard/wifi_framework/dhcp_manage/mgr_service/include", - "//foundation/communication/wifi/services/wifi_standard/wifi_framework/dhcp_manage/mgr_service/interfaces", - ] - - cflags_cc = [ - "-std=c++17", - "-fno-rtti", - ] - - ldflags = [ - "-fPIC", - "-Wl,-E", - ] - - deps = [ - "//foundation/communication/wifi/services/wifi_standard/wifi_framework/dhcp_manage/mgr_service:dhcp_manager_service", - "//foundation/communication/wifi/services/wifi_standard/wifi_framework/wifi_manage:wifi_manager_service", - "//foundation/communication/wifi/services/wifi_standard/wifi_framework/wifi_manage/idl_client:wifi_idl_client", - "//utils/native/base:utils", - ] - - external_deps = [ "hiviewdfx_hilog_native:libhilog" ] - - part_name = "wifi_standard" - subsystem_name = "communication" -} diff --git a/services/wifi_standard/wifi_framework/wifi_manage/wifi_sta/sta_network_speed.cpp b/services/wifi_standard/wifi_framework/wifi_manage/wifi_sta/sta_network_speed.cpp deleted file mode 100644 index 6e14659bed67264b18dfee2c29441c28d34c839b..0000000000000000000000000000000000000000 --- a/services/wifi_standard/wifi_framework/wifi_manage/wifi_sta/sta_network_speed.cpp +++ /dev/null @@ -1,120 +0,0 @@ -/* - * Copyright (C) 2021 Huawei Device Co., Ltd. - * 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 "sta_network_speed.h" -#include "wifi_logger.h" - -DEFINE_WIFILOG_LABEL("StaNetWorkSpeed"); - -namespace OHOS { -namespace Wifi { -StaNetWorkSpeed::StaNetWorkSpeed() -{} - -StaNetWorkSpeed::~StaNetWorkSpeed() -{ - WIFI_LOGI("StaNetWorkSpeed::~StaNetWorkSpeed enter"); -} - -void StaNetWorkSpeed::GetNetSpeed(std::string &strRx, std::string &strTx) -{ - WIFI_LOGE("enter GetNetSpeed\n"); - long rxBytesPre = 0; - long txBytesPre = 0; - long rxBytesNext = 0; - long txBytesNext = 0; - GetTxAndRxBytes(rxBytesPre, txBytesPre); - sleep(1); - GetTxAndRxBytes(rxBytesNext, txBytesNext); - - if ((rxBytesNext - rxBytesPre) < MAXIMUM_BYTE) { - strRx = std::to_string(rxBytesNext - rxBytesPre); - strRx += "B/s"; - } else if ((rxBytesNext - rxBytesPre) < MAXIMUM_KILOBYTE) { - strRx = std::to_string((rxBytesNext - rxBytesPre) / MAXIMUM_KILOBYTE); - strRx += "M/s"; - } else { - strRx = std::to_string((rxBytesNext - rxBytesPre) / MAXIMUM_BYTE); - strRx += "KB/s"; - } - - if ((txBytesNext - txBytesPre) < MAXIMUM_BYTE) { - strTx = std::to_string(txBytesNext - txBytesPre); - strTx += "B/s"; - } else if ((txBytesNext - txBytesPre) < MAXIMUM_KILOBYTE) { - strTx = std::to_string((txBytesNext - txBytesPre) / MAXIMUM_KILOBYTE); - strTx += "M/s"; - } else { - strTx = std::to_string((txBytesNext - txBytesPre) / MAXIMUM_BYTE); - strTx += "KB/s"; - } - WIFI_LOGI("GetNetSpeed strRx = %{public}s\n", strRx.c_str()); - WIFI_LOGI("GetNetSpeed strTx = %{public}s\n", strTx.c_str()); -} - -std::vector StaNetWorkSpeed::SplitString(std::string source, const std::string delim) -{ - std::vector res; - if (source.empty()) { - return res; - } - - if (delim.empty()) { - res.push_back(source); - return res; - } - std::string::size_type begPos = 0; - std::string::size_type endPos = 0; - std::string tmpStr; - while ((endPos = source.find(delim, begPos)) != std::string::npos) { - if (endPos > begPos) { - tmpStr = source.substr(begPos, endPos - begPos); - res.push_back(tmpStr); - } - begPos = endPos + delim.size(); - } - tmpStr = source.substr(begPos); - if (!tmpStr.empty()) { - res.push_back(tmpStr); - } - return res; -} - -ErrCode StaNetWorkSpeed::GetTxAndRxBytes(long &rxBytes, long &txBytes) -{ - std::ifstream fs(WLAN0_NETSPEED_FILE.c_str()); - if (!fs.is_open()) { - return ErrCode::WIFI_OPT_FAILED; - } - - std::string line; - while (std::getline(fs, line)) { - if (line.empty()) { - continue; - } - - if (line.find(IF_NAME) == std::string::npos) { - continue; - } - - std::vector splitDataList; - splitDataList = SplitString(line.substr(line.find(":")), " "); - rxBytes = std::atol(splitDataList[UP_TRAFFIC_INDEX].c_str()); - txBytes = std::atol(splitDataList[REV_TRAFFIC_INDEX].c_str()); - } - fs.close(); - return ErrCode::WIFI_OPT_SUCCESS; -} -} // namespace Wifi -} // namespace OHOS \ No newline at end of file diff --git a/services/wifi_standard/wifi_hal/BUILD.gn b/services/wifi_standard/wifi_hal/BUILD.gn deleted file mode 100755 index 9e78ec5e3524488f15d905f9472c6d2e7f7b04e8..0000000000000000000000000000000000000000 --- a/services/wifi_standard/wifi_hal/BUILD.gn +++ /dev/null @@ -1,78 +0,0 @@ -# Copyright (C) 2021 Huawei Device Co., Ltd. -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -import("//build/ohos.gni") - -ohos_executable("wifi_hal_service") { - install_enable = true - sources = [ - "common/wifi_hal_common_func.c", - "main.c", - "wifi_hal_adapter.c", - "wifi_hal_ap_interface.c", - "wifi_hal_base_interface.c", - "wifi_hal_callback.c", - "wifi_hal_chip_interface.c", - "wifi_hal_crpc_ap.c", - "wifi_hal_crpc_base.c", - "wifi_hal_crpc_chip.c", - "wifi_hal_crpc_common.c", - "wifi_hal_crpc_p2p.c", - "wifi_hal_crpc_server.c", - "wifi_hal_crpc_sta.c", - "wifi_hal_crpc_supplicant.c", - "wifi_hal_module/hostapd_hal/wifi_hostapd_hal.c", - "wifi_hal_module/wpa_supplicant_hal/wifi_wpa_common.c", - "wifi_hal_module/wpa_supplicant_hal/wifi_wpa_hal.c", - "wifi_hal_module/wpa_supplicant_hal/wpa_p2p_hal/wifi_p2p_hal.c", - "wifi_hal_module/wpa_supplicant_hal/wpa_sta_hal/wifi_supplicant_hal.c", - "wifi_hal_module_manage.c", - "wifi_hal_p2p_interface.c", - "wifi_hal_sta_interface.c", - "wifi_hal_vendor_interface.c", - ] - - include_dirs = [ - "//utils/native/base/include", - "//foundation/communication/wifi/interfaces/innerkits/native_cpp/wifi_standard/interfaces", - "//foundation/communication/wifi/services/wifi_standard/ipc_framework/cRPC/include", - "//foundation/communication/wifi/services/wifi_standard/wifi_hal", - "//foundation/communication/wifi/services/wifi_standard/wifi_hal/common", - "//foundation/communication/wifi/services/wifi_standard/wifi_hal/wifi_hal_module/hostapd_hal", - "//foundation/communication/wifi/services/wifi_standard/wifi_hal/wifi_hal_module/wpa_supplicant_hal", - "//foundation/communication/wifi/services/wifi_standard/wifi_hal/wifi_hal_module/wpa_supplicant_hal/wpa_sta_hal", - "//foundation/communication/wifi/services/wifi_standard/wifi_hal/wifi_hal_module/wpa_supplicant_hal/wpa_p2p_hal", - "//base/hiviewdfx/hilog/interfaces/native/innerkits/include", - "//third_party/wpa_supplicant/wpa_supplicant-2.9_standard/src/", - "//third_party/bounds_checking_function/include/", - ] - - deps = [ - "//base/hiviewdfx/hilog/interfaces/native/innerkits:libhilog", - "//foundation/communication/wifi/services//wifi_standard/wifi_hal/etc/init:etc", - "//foundation/communication/wifi/services/wifi_standard/ipc_framework/cRPC:crpc_server", - "//third_party/wpa_supplicant/wpa_supplicant-2.9_standard:wpa_client", - "//utils/native/base:utils", - ] - - cflags_cc = [ "-fno-rtti" ] - - defines = [] - - part_name = "wifi_standard" - subsystem_name = "communication" -} - -group("wifi_hal") { - deps = [ ":wifi_hal_service" ] -} diff --git a/tests/wifi_standard/wifi_framework/dhcp_manage/dhcp_server/unittest/dhcp_server_test.cpp b/tests/wifi_standard/wifi_framework/dhcp_manage/dhcp_server/unittest/dhcp_server_test.cpp deleted file mode 100644 index 28558aa9aa42be94501ba7e8a1e5d5d6c8cf56b7..0000000000000000000000000000000000000000 --- a/tests/wifi_standard/wifi_framework/dhcp_manage/dhcp_server/unittest/dhcp_server_test.cpp +++ /dev/null @@ -1,210 +0,0 @@ -/* - * Copyright (C) 2021 Huawei Device Co., Ltd. - * 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 "string_ex.h" -#include "dhcp_server.h" -#include "address_utils.h" -#include "dhcp_config.h" -#include "dhcp_option.h" -#include "dhcp_logger.h" -#include "system_func_mock.h" -#include "dhcp_message_sim.h" -#include "securec.h" - -using namespace testing::ext; -using namespace std; -using namespace OHOS::Wifi; - -#undef LOG_TAG -#define LOG_TAG "DhcpServerTest" - -static const int SERVER_RUNING_TIME = 10; //the value is in units of seconds. -class DhcpServerTest : public testing::Test { -public: - static void SetUpTestCase() - {} - static void TearDownTestCase() - {} - virtual void SetUp() - {} - virtual void TearDown() - {} - - int InitServerConfig(DhcpConfig *config); - int FreeServerConfig(DhcpConfig *config); - - int InitDhcpClient(); - void ServerRun(void); - bool StartServerTest(); - bool StopServerTest(); - -private: - DhcpServerContext *m_pServerCtx = NULL; - DhcpConfig m_serverConfg; - thread testSrvTh; - - DhcpClientContext *m_pMockClient = NULL; - DhcpClientConfig m_clientConfg; -}; - -int DhcpServerTest::InitServerConfig(DhcpConfig *config) -{ - if (!config) { - return RET_FAILED; - } - const char* testIfaceName = "wlan0"; - uint32_t serverId = ParseIpAddr("192.168.188.254"); - uint32_t netmask = ParseIpAddr("255.255.255.0"); - uint32_t beginIp = ParseIpAddr("192.168.188.100"); - uint32_t endIp = ParseIpAddr("192.168.188.150"); - if (serverId == 0 || netmask == 0 || beginIp == 0 || endIp == 0) { - printf("failed to parse address.\n"); - return RET_FAILED; - } - if (memset_s(config, sizeof(DhcpConfig), 0, sizeof(DhcpConfig)) != EOK) { - return RET_FAILED; - } - if (memset_s(config->ifname, sizeof(config->ifname), '\0', sizeof(config->ifname)) != EOK) { - return RET_FAILED; - } - if (strncpy_s(config->ifname, sizeof(config->ifname), testIfaceName, sizeof(config->ifname)) != EOK) { - return RET_FAILED; - } - config->serverId = serverId; - config->netmask = netmask; - config->pool.beginAddress = beginIp; - config->pool.endAddress = endIp; - if (InitOptionList(&config->options) != RET_SUCCESS) { - return RET_FAILED; - } - return RET_SUCCESS; -} - -void DhcpServerTest::ServerRun(void) -{ - LOGD("begin test start dhcp server."); - SystemFuncMock::GetInstance().SetMockFlag(true); - EXPECT_CALL(SystemFuncMock::GetInstance(), socket(_, _, _)).WillRepeatedly(Return(1)); - EXPECT_CALL(SystemFuncMock::GetInstance(), setsockopt(_, _, _, _, _)).WillRepeatedly(Return(0)); - EXPECT_CALL(SystemFuncMock::GetInstance(), select(_, _, _, _, _)).WillRepeatedly(Return(0)); - EXPECT_CALL(SystemFuncMock::GetInstance(), recvfrom(_, _, _, _, _, _)).WillRepeatedly(Return(0)); - EXPECT_CALL(SystemFuncMock::GetInstance(), bind(_, _, _)).WillRepeatedly(Return(0)); - EXPECT_CALL(SystemFuncMock::GetInstance(), close(_)).WillRepeatedly(Return(0)); - m_pServerCtx = InitializeServer(&m_serverConfg); - if (!m_pServerCtx) { - LOGE("failed to initialized dhcp server context."); - } - if (m_pServerCtx && StartDhcpServer(m_pServerCtx) != RET_SUCCESS) { - printf("failed to start dhcp server. \n"); - } - SystemFuncMock::GetInstance().SetMockFlag(false); -} -bool DhcpServerTest::StartServerTest() -{ - SystemFuncMock::GetInstance().SetMockFlag(true); - EXPECT_CALL(SystemFuncMock::GetInstance(), close(_)).WillRepeatedly(Return(0)); - bool retval = true; - if (InitServerConfig(&m_serverConfg) != RET_SUCCESS) { - LOGD("failed to initialized dhcp server config."); - retval = false; - } - testSrvTh = std::thread(std::bind(&DhcpServerTest::ServerRun, this)); - testSrvTh.detach(); - sleep(SERVER_RUNING_TIME); - if (retval && StopServerTest() != RET_SUCCESS) { - retval = false; - } - sleep(6); - if (m_pServerCtx) { - FreeServerContex(m_pServerCtx); - m_pServerCtx = NULL; - } - SystemFuncMock::GetInstance().SetMockFlag(false); - return retval; -} - -bool DhcpServerTest::StopServerTest() -{ - printf("begin stop dhcp server. \n"); - if (!m_pServerCtx) { - return false; - } - if (StopDhcpServer(m_pServerCtx) != RET_SUCCESS) { - return false; - } - return true; -} - -int DhcpServerTest::InitDhcpClient() -{ - LOGD("init mock dhcp client."); - const char* testIfname = "wlan0"; - uint8_t testMac[DHCP_HWADDR_LENGTH] = {0x00, 0x0e, 0x3c, 0x65, 0x3a, 0x09, 0}; - - if (memset_s(&m_clientConfg, sizeof(DhcpClientConfig), 0, sizeof(DhcpClientConfig)) != EOK) { - return RET_FAILED; - } - if (!FillHwAddr(m_clientConfg.chaddr, DHCP_HWADDR_LENGTH, testMac, MAC_ADDR_LENGTH)) { - return RET_FAILED; - } - if (memset_s(m_clientConfg.ifname, IFACE_NAME_SIZE, '\0', IFACE_NAME_SIZE) != EOK) { - return RET_FAILED; - } - if (memcpy_s(m_clientConfg.ifname, IFACE_NAME_SIZE, testIfname, strlen(testIfname)) != EOK) { - return RET_FAILED; - } - m_pMockClient = InitialDhcpClient(&m_clientConfg); - - if (!m_pMockClient) { - return RET_FAILED; - } - return DhcpDiscover(m_pMockClient); -} - -int DhcpServerTest::FreeServerConfig(DhcpConfig *config) -{ - if (!config) { - return RET_FAILED; - } - FreeOptionList(&config->options); - return RET_SUCCESS; -} - -HWTEST_F(DhcpServerTest, InitializeServerTest, TestSize.Level1) -{ - SystemFuncMock::GetInstance().SetMockFlag(true); - EXPECT_CALL(SystemFuncMock::GetInstance(), socket(_, _, _)).WillRepeatedly(Return(1)); - EXPECT_CALL(SystemFuncMock::GetInstance(), setsockopt(_, _, _, _, _)).WillRepeatedly(Return(0)); - EXPECT_CALL(SystemFuncMock::GetInstance(), select(_, _, _, _, _)).WillRepeatedly(Return(0)); - EXPECT_CALL(SystemFuncMock::GetInstance(), recvfrom(_, _, _, _, _, _)).WillRepeatedly(Return(0)); - EXPECT_CALL(SystemFuncMock::GetInstance(), bind(_, _, _)).WillRepeatedly(Return(0)); - EXPECT_CALL(SystemFuncMock::GetInstance(), close(_)).WillRepeatedly(Return(0)); - - DhcpConfig config; - PDhcpServerContext ctx = InitializeServer(&config); - EXPECT_TRUE(ctx == NULL); - EXPECT_EQ(RET_SUCCESS, InitServerConfig(&config)); - ctx = InitializeServer(&config); - ASSERT_TRUE(ctx != NULL); - EXPECT_EQ(RET_SUCCESS, FreeServerConfig(&config)); - EXPECT_EQ(RET_SUCCESS, FreeServerContex(ctx)); - SystemFuncMock::GetInstance().SetMockFlag(false); -} \ No newline at end of file diff --git a/tests/wifi_standard/wifi_framework/wifi_manage/wifi_ap/BUILD.gn b/tests/wifi_standard/wifi_framework/wifi_manage/wifi_ap/BUILD.gn deleted file mode 100644 index 7e99e7aa559bdaa56f070f3575691e9cc5ebe60a..0000000000000000000000000000000000000000 --- a/tests/wifi_standard/wifi_framework/wifi_manage/wifi_ap/BUILD.gn +++ /dev/null @@ -1,68 +0,0 @@ -# Copyright (C) 2021 Huawei Device Co., Ltd. -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -import("//build/test.gni") -SUBSYSTEM_DIR = "//foundation/communication" -module_output_path = "wifi_standard/ap_test" - -config("module_private_config") { - visibility = [ ":*" ] - include_dirs = [ - "//utils/native/base/include", - "$SUBSYSTEM_DIR/wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_ap/test", - ] -} - -ohos_unittest("WifiApServiceTest") { - module_out_path = module_output_path - sources = [ "wifi_ap_service_test.cpp" ] - - include_dirs = [ - "./", - "../..", - "../Mock/", - "//utils/native/base/include", - "//base/hiviewdfx/hilog/interfaces/native/innerkits/include", - "//foundation/communication/wifi/interfaces/innerkits/native_cpp/wifi_standard/interfaces", - "//foundation/communication/wifi/services/wifi_standard/ipc_framework/cRPC/include", - "//foundation/communication/wifi/services/wifi_standard/wifi_framework/common/include", - "//foundation/communication/wifi/services/wifi_standard/wifi_framework/common/net_helper", - "//foundation/communication/wifi/services/wifi_standard/wifi_framework/common/config", - "//foundation/communication/wifi/services/wifi_standard/wifi_framework/common/log", - "//foundation/communication/wifi/services/wifi_standard/wifi_framework/wifi_manage/common/include", - "//foundation/communication/wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_ap", - "//foundation/communication/wifi/services/wifi_standard/wifi_framework/wifi_manage", - "//foundation/communication/wifi/services/wifi_standard/wifi_framework/wifi_manage/common", - "//foundation/communication/wifi/services/wifi_standard/wifi_framework/wifi_manage/idl_client", - "//foundation/communication/wifi/services/wifi_standard/wifi_framework/wifi_manage/idl_client/idl_interface", - "//foundation/communication/wifi/services/wifi_standard/wifi_framework/dhcp_manage/mgr_service/include", - "//foundation/communication/wifi/services/wifi_standard/wifi_framework/dhcp_manage/mgr_service/interfaces", - "//third_party/googletest/googlemock/include", - "//foundation/communication/wifi/services/wifi_standard/wifi_framework/common/utils", - ] - - deps = [ - "//foundation/communication/wifi/tests/wifi_standard/wifi_framework/wifi_manage/wifi_ap/wifi_ap_dhcp_nat:WifiApNatManagerTest", - "//foundation/communication/wifi/tests/wifi_standard/wifi_framework/wifi_manage/wifi_ap/wifi_hotspot_test:WifiHotspotTest", - "//third_party/googletest:gmock_main", - "//utils/native/base:utils", - ] - external_deps = [ "hiviewdfx_hilog_native:libhilog" ] - part_name = "wifi_standard" - subsystem_name = "communication" -} -group("unittest") { - testonly = true - deps = [] - deps += [ ":WifiApServiceTest" ] -} diff --git a/tests/wifi_standard/wifi_framework/wifi_manage/wifi_ap/wifi_ap_dhcp_nat/BUILD.gn b/tests/wifi_standard/wifi_framework/wifi_manage/wifi_ap/wifi_ap_dhcp_nat/BUILD.gn deleted file mode 100644 index cc4a8d0d7dc36dcb56963234b1400f52672a271e..0000000000000000000000000000000000000000 --- a/tests/wifi_standard/wifi_framework/wifi_manage/wifi_ap/wifi_ap_dhcp_nat/BUILD.gn +++ /dev/null @@ -1,82 +0,0 @@ -# Copyright (C) 2021 Huawei Device Co., Ltd. -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -import("//build/test.gni") -SUBSYSTEM_DIR = "//foundation/communication" -config("module_private_config") { - visibility = [ ":*" ] - include_dirs = [ - "//utils/native/base/include", - "$SUBSYSTEM_DIR/wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_ap/test/wifi_ap_dhcp_nat", - ] -} - -ohos_unittest("WifiApNatManagerTest") { - module_out_path = "wifi_standard/ap_test" - sources = [ - "../Mock/mock_network_interface.cpp", - "../Mock/mock_system_interface.cpp", - "../global_test.cpp", - "../wifi_ap_test.cpp", - "//foundation/communication/wifi/services/wifi_standard/wifi_framework/common/log/log_helper.c", - "//foundation/communication/wifi/services/wifi_standard/wifi_framework/common/net_helper/base_address.cpp", - "//foundation/communication/wifi/services/wifi_standard/wifi_framework/common/net_helper/ipv4_address.cpp", - "//foundation/communication/wifi/services/wifi_standard/wifi_framework/common/net_helper/ipv6_address.cpp", - "//foundation/communication/wifi/services/wifi_standard/wifi_framework/common/net_helper/mac_address.cpp", - "//foundation/communication/wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_ap/wifi_ap_nat_manager.cpp", - "wifi_ap_nat_manager_test.cpp", - ] - - include_dirs = [ - "./", - "../../", - "../Mock/", - "//utils/native/base/include", - "//base/hiviewdfx/hilog/interfaces/native/innerkits/include", - "//foundation/communication/wifi/interfaces/innerkits/native_cpp/wifi_standard/interfaces", - "//foundation/communication/wifi/services/wifi_standard/ipc_framework/cRPC/include", - "//foundation/communication/wifi/services/wifi_standard/wifi_framework/common/include", - "//foundation/communication/wifi/services/wifi_standard/wifi_framework/common/net_helper", - "//foundation/communication/wifi/services/wifi_standard/wifi_framework/common/config", - "//foundation/communication/wifi/services/wifi_standard/wifi_framework/common/log", - "//foundation/communication/wifi/services/wifi_standard/wifi_framework/common/utils", - "//foundation/communication/wifi/services/wifi_standard/wifi_framework/wifi_manage/common/include", - "//foundation/communication/wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_ap", - "//foundation/communication/wifi/services/wifi_standard/wifi_framework/wifi_manage", - "//foundation/communication/wifi/services/wifi_standard/wifi_framework/wifi_manage/common", - "//foundation/communication/wifi/services/wifi_standard/wifi_framework/wifi_manage/idl_client", - "//foundation/communication/wifi/services/wifi_standard/wifi_framework/wifi_manage/idl_client/idl_interface", - "//foundation/communication/wifi/services/wifi_standard/wifi_framework/dhcp_manage/mgr_service/include", - "//foundation/communication/wifi/services/wifi_standard/wifi_framework/dhcp_manage/mgr_service/interfaces", - "//third_party/googletest/googlemock/include", - "//third_party/googletest/googletest/include", - ] - ldflags = [ - "-fPIC", - "-Wl,-E", - "-Wl,--wrap=system", - "--coverage", - ] - deps = [ - "//third_party/googletest:gmock_main", - "//utils/native/base:utils", - ] - external_deps = [ "hiviewdfx_hilog_native:libhilog" ] - part_name = "wifi_standard" - subsystem_name = "communication" -} -group("unittest") { - testonly = true - deps = [] - deps += [ ":WifiApNatManagerTest" ] -} diff --git a/tests/wifi_standard/wifi_framework/wifi_manage/wifi_ap/wifi_ap_dhcp_nat/global_test.cpp b/tests/wifi_standard/wifi_framework/wifi_manage/wifi_ap/wifi_ap_dhcp_nat/global_test.cpp deleted file mode 100644 index e3d7891fd48377ed172f8eef420271689a4e8a05..0000000000000000000000000000000000000000 --- a/tests/wifi_standard/wifi_framework/wifi_manage/wifi_ap/wifi_ap_dhcp_nat/global_test.cpp +++ /dev/null @@ -1,23 +0,0 @@ -/* - * Copyright (c) 2021 Huawei Device Co., Ltd. - * 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 "global_test.h" -void GlobalTest::SetUp() -{ - printf("GlobalTest SetUp\n"); -} -void GlobalTest::TearDown() -{ - printf("GlobalTest TearDown\n"); -} \ No newline at end of file diff --git a/tests/wifi_standard/wifi_framework/wifi_manage/wifi_ap/wifi_ap_dhcp_nat/global_test.h b/tests/wifi_standard/wifi_framework/wifi_manage/wifi_ap/wifi_ap_dhcp_nat/global_test.h deleted file mode 100644 index 65afff0de04a7e633830cb39c993b2d9edcb6c42..0000000000000000000000000000000000000000 --- a/tests/wifi_standard/wifi_framework/wifi_manage/wifi_ap/wifi_ap_dhcp_nat/global_test.h +++ /dev/null @@ -1,24 +0,0 @@ -/* - * Copyright (c) 2021 Huawei Device Co., Ltd. - * 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 GLOBAL_TEST_H -#define GLOBAL_TEST_H -#include -class GlobalTest : public testing::Environment { -public: - virtual void SetUp(); - virtual void TearDown(); -}; -#endif \ No newline at end of file diff --git a/tests/wifi_standard/wifi_framework/wifi_manage/wifi_ap/wifi_ap_test.cpp b/tests/wifi_standard/wifi_framework/wifi_manage/wifi_ap/wifi_ap_test.cpp deleted file mode 100644 index e2e4b1c030867587608887b1dca485967e3a02b3..0000000000000000000000000000000000000000 --- a/tests/wifi_standard/wifi_framework/wifi_manage/wifi_ap/wifi_ap_test.cpp +++ /dev/null @@ -1,25 +0,0 @@ -/* - * Copyright (c) 2021 Huawei Device Co., Ltd. - * 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 "global_test.h" -#include - -int main(int argc, char *argv[]) -{ - testing::InitGoogleTest(&argc, argv); - testing::Environment *env = new GlobalTest(); - testing::AddGlobalTestEnvironment(env); - return RUN_ALL_TESTS(); -} \ No newline at end of file diff --git a/tests/wifi_standard/wifi_framework/wifi_manage/wifi_ap/wifi_hotspot_test/BUILD.gn b/tests/wifi_standard/wifi_framework/wifi_manage/wifi_ap/wifi_hotspot_test/BUILD.gn deleted file mode 100644 index 874995c699cd1c61144a6f7ce452db2f931384fd..0000000000000000000000000000000000000000 --- a/tests/wifi_standard/wifi_framework/wifi_manage/wifi_ap/wifi_hotspot_test/BUILD.gn +++ /dev/null @@ -1,108 +0,0 @@ -# Copyright (C) 2021 Huawei Device Co., Ltd. -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -import("//build/test.gni") -SUBSYSTEM_DIR = "//foundation/communication" -config("module_private_config") { - visibility = [ ":*" ] - include_dirs = [ - "//utils/native/base/include", - "$SUBSYSTEM_DIR/wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_ap/test/wifi_hotspot_test", - ] -} -ohos_unittest("WifiHotspotTest") { - module_out_path = "wifi_standard/ap_test" - sources = [ - "../Mock/mock_network_interface.cpp", - "../Mock/mock_system_interface.cpp", - "../Mock/mock_wifi_ap_hal_interface.cpp", - "../Mock/mock_wifi_settings.cpp", - "../Mock/operator_overload.cpp", - "../global_test.cpp", - "../wifi_ap_test.cpp", - "//foundation/communication/wifi/interfaces/innerkits/native_cpp/wifi_standard/src/wifi_p2p_msg.cpp", - "//foundation/communication/wifi/services/wifi_standard/wifi_framework/common/log/log_helper.c", - "//foundation/communication/wifi/services/wifi_standard/wifi_framework/common/net_helper/base_address.cpp", - "//foundation/communication/wifi/services/wifi_standard/wifi_framework/common/net_helper/dhcpd_interface.cpp", - "//foundation/communication/wifi/services/wifi_standard/wifi_framework/common/net_helper/ipv4_address.cpp", - "//foundation/communication/wifi/services/wifi_standard/wifi_framework/common/net_helper/ipv6_address.cpp", - "//foundation/communication/wifi/services/wifi_standard/wifi_framework/common/net_helper/mac_address.cpp", - "//foundation/communication/wifi/services/wifi_standard/wifi_framework/common/utils/wifi_global_func.cpp", - "//foundation/communication/wifi/services/wifi_standard/wifi_framework/wifi_manage/common/handler.cpp", - "//foundation/communication/wifi/services/wifi_standard/wifi_framework/wifi_manage/common/internal_message.cpp", - "//foundation/communication/wifi/services/wifi_standard/wifi_framework/wifi_manage/common/message_queue.cpp", - "//foundation/communication/wifi/services/wifi_standard/wifi_framework/wifi_manage/common/state.cpp", - "//foundation/communication/wifi/services/wifi_standard/wifi_framework/wifi_manage/common/state_machine.cpp", - "//foundation/communication/wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_ap/ap_config_use.cpp", - "//foundation/communication/wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_ap/ap_idle_state.cpp", - "//foundation/communication/wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_ap/ap_monitor.cpp", - "//foundation/communication/wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_ap/ap_root_state.cpp", - "//foundation/communication/wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_ap/ap_service.cpp", - "//foundation/communication/wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_ap/ap_started_state.cpp", - "//foundation/communication/wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_ap/ap_state_machine.cpp", - "//foundation/communication/wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_ap/ap_stations_manager.cpp", - "//foundation/communication/wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_ap/wifi_ap_nat_manager.cpp", - "ap_config_use_test.cpp", - "ap_idle_state_test.cpp", - "ap_monitor_test.cpp", - "ap_root_state_test.cpp", - "ap_service_test.cpp", - "ap_started_state_test.cpp", - "ap_state_machine_test.cpp", - "ap_stations_manager_test.cpp", - ] - ldflags = [ - "-fPIC", - "-Wl,-E", - "-Wl,--wrap=system", - "--coverage", - ] - include_dirs = [ - "./", - "../../", - "../Mock/", - "//utils/native/base/include", - "//base/hiviewdfx/hilog/interfaces/native/innerkits/include", - "//foundation/communication/wifi/interfaces/innerkits/native_cpp/wifi_standard/interfaces", - "//foundation/communication/wifi/services/wifi_standard/ipc_framework/cRPC/include", - "//foundation/communication/wifi/services/wifi_standard/wifi_framework/common/include", - "//foundation/communication/wifi/services/wifi_standard/wifi_framework/common/net_helper", - "//foundation/communication/wifi/services/wifi_standard/wifi_framework/common/config", - "//foundation/communication/wifi/services/wifi_standard/wifi_framework/common/log", - "//foundation/communication/wifi/services/wifi_standard/wifi_framework/common/utils", - "//foundation/communication/wifi/services/wifi_standard/wifi_framework/wifi_manage/common/include", - "//foundation/communication/wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_ap", - "//foundation/communication/wifi/services/wifi_standard/wifi_framework/wifi_manage", - "//foundation/communication/wifi/services/wifi_standard/wifi_framework/wifi_manage/common", - "//foundation/communication/wifi/services/wifi_standard/wifi_framework/wifi_manage/idl_client", - "//foundation/communication/wifi/services/wifi_standard/wifi_framework/wifi_manage/idl_client/idl_interface", - "//foundation/communication/wifi/services/wifi_standard/wifi_framework/dhcp_manage/mgr_service/include", - "//foundation/communication/wifi/services/wifi_standard/wifi_framework/dhcp_manage/mgr_service/interfaces", - "//third_party/googletest/googlemock/include", - "//third_party/googletest/googletest/include", - ] - - deps = [ - "//foundation/communication/wifi/services/wifi_standard/wifi_framework/dhcp_manage/mgr_service:dhcp_manager_service", - "//third_party/googletest:gmock_main", - "//utils/native/base:utils", - ] - external_deps = [ "hiviewdfx_hilog_native:libhilog" ] - part_name = "wifi_standard" - subsystem_name = "communication" -} -group("unittest") { - testonly = true - deps = [] - deps += [ ":WifiHotspotTest" ] -} diff --git a/tests/wifi_standard/wifi_framework/wifi_manage/wifi_ap/wifi_hotspot_test/global_test.cpp b/tests/wifi_standard/wifi_framework/wifi_manage/wifi_ap/wifi_hotspot_test/global_test.cpp deleted file mode 100644 index e3d7891fd48377ed172f8eef420271689a4e8a05..0000000000000000000000000000000000000000 --- a/tests/wifi_standard/wifi_framework/wifi_manage/wifi_ap/wifi_hotspot_test/global_test.cpp +++ /dev/null @@ -1,23 +0,0 @@ -/* - * Copyright (c) 2021 Huawei Device Co., Ltd. - * 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 "global_test.h" -void GlobalTest::SetUp() -{ - printf("GlobalTest SetUp\n"); -} -void GlobalTest::TearDown() -{ - printf("GlobalTest TearDown\n"); -} \ No newline at end of file diff --git a/tests/wifi_standard/wifi_framework/wifi_manage/wifi_ap/wifi_hotspot_test/global_test.h b/tests/wifi_standard/wifi_framework/wifi_manage/wifi_ap/wifi_hotspot_test/global_test.h deleted file mode 100644 index 65afff0de04a7e633830cb39c993b2d9edcb6c42..0000000000000000000000000000000000000000 --- a/tests/wifi_standard/wifi_framework/wifi_manage/wifi_ap/wifi_hotspot_test/global_test.h +++ /dev/null @@ -1,24 +0,0 @@ -/* - * Copyright (c) 2021 Huawei Device Co., Ltd. - * 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 GLOBAL_TEST_H -#define GLOBAL_TEST_H -#include -class GlobalTest : public testing::Environment { -public: - virtual void SetUp(); - virtual void TearDown(); -}; -#endif \ No newline at end of file diff --git a/tests/wifi_standard/wifi_framework/wifi_manage/wifi_ap/wifi_hotspot_test/wifi_ap_test.cpp b/tests/wifi_standard/wifi_framework/wifi_manage/wifi_ap/wifi_hotspot_test/wifi_ap_test.cpp deleted file mode 100644 index e2e4b1c030867587608887b1dca485967e3a02b3..0000000000000000000000000000000000000000 --- a/tests/wifi_standard/wifi_framework/wifi_manage/wifi_ap/wifi_hotspot_test/wifi_ap_test.cpp +++ /dev/null @@ -1,25 +0,0 @@ -/* - * Copyright (c) 2021 Huawei Device Co., Ltd. - * 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 "global_test.h" -#include - -int main(int argc, char *argv[]) -{ - testing::InitGoogleTest(&argc, argv); - testing::Environment *env = new GlobalTest(); - testing::AddGlobalTestEnvironment(env); - return RUN_ALL_TESTS(); -} \ No newline at end of file diff --git a/tests/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/test/BUILD.gn b/tests/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/test/BUILD.gn deleted file mode 100644 index 1dc4744aae34884c358f5ff4015ea02907b96e93..0000000000000000000000000000000000000000 --- a/tests/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/test/BUILD.gn +++ /dev/null @@ -1,169 +0,0 @@ -# Copyright (C) 2021 Huawei Device Co., Ltd. -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -import("//build/test.gni") -SUBSYSTEM_DIR = "//foundation/communication" -config("module_private_config") { - visibility = [ ":*" ] - include_dirs = [ - "//utils/native/base/include", - "$SUBSYSTEM_DIR/wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/test", - ] -} - -ohos_unittest("wifi_p2p_test") { - module_out_path = "wifi_standard/p2p_test" - sources = [ - "./Mock/mock_wifi_p2p_hal_interface.cpp", - "//foundation/communication/wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/authorizing_negotiation_request_state.cpp", - "//foundation/communication/wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/group_formed_state.cpp", - "//foundation/communication/wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/group_negotiation_state.cpp", - "//foundation/communication/wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/invitation_received_state.cpp", - "//foundation/communication/wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/invitation_request_state.cpp", - "//foundation/communication/wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/p2p_default_state.cpp", - "//foundation/communication/wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/p2p_disabled_state.cpp", - "//foundation/communication/wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/p2p_disabling_state.cpp", - "//foundation/communication/wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/p2p_enabled_state.cpp", - "//foundation/communication/wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/p2p_enabling_state.cpp", - "//foundation/communication/wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/p2p_group_formation_state.cpp", - "//foundation/communication/wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/p2p_group_join_state.cpp", - "//foundation/communication/wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/p2p_group_operating_state.cpp", - "//foundation/communication/wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/p2p_idle_state.cpp", - "//foundation/communication/wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/p2p_inviting_state.cpp", - "//foundation/communication/wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/p2p_monitor.cpp", - "//foundation/communication/wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/p2p_state_machine.cpp", - "//foundation/communication/wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/provision_discovery_state.cpp", - "//foundation/communication/wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/wifi_p2p_device_manager.cpp", - "//foundation/communication/wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/wifi_p2p_dns_sd_service_info.cpp", - "//foundation/communication/wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/wifi_p2p_dns_sd_service_request.cpp", - "//foundation/communication/wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/wifi_p2p_dns_sd_service_response.cpp", - "//foundation/communication/wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/wifi_p2p_dns_txt_record.cpp", - "//foundation/communication/wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/wifi_p2p_group_info_proxy.cpp", - "//foundation/communication/wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/wifi_p2p_group_manager.cpp", - "//foundation/communication/wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/wifi_p2p_service.cpp", - "//foundation/communication/wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/wifi_p2p_service_manager.cpp", - "//foundation/communication/wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/wifi_p2p_service_request_list.cpp", - "//foundation/communication/wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/wifi_p2p_service_response_list.cpp", - "//foundation/communication/wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/wifi_p2p_temp_disc_event.cpp", - "//foundation/communication/wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/wifi_p2p_upnp_service_info.cpp", - "//foundation/communication/wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/wifi_p2p_upnp_service_request.cpp", - "//foundation/communication/wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/wifi_p2p_upnp_service_response.cpp", - "authorizing_negotiation_request_state_test.cpp", - "group_formed_state_test.cpp", - "group_negotiation_state_test.cpp", - "invitation_recelved_state_test.cpp", - "invitation_request_state_test.cpp", - "p2p_default_state_test.cpp", - "p2p_disabled_state_test.cpp", - "p2p_disabling_state_test.cpp", - "p2p_enabled_state_test.cpp", - "p2p_enabling_state_test.cpp", - "p2p_group_formation_state_test.cpp", - "p2p_group_join_state_test.cpp", - "p2p_group_operating_state_test.cpp", - "p2p_idle_state_test.cpp", - "p2p_inviting_state_test.cpp", - "p2p_monitor_test.cpp", - "p2p_state_machine_test.cpp", - "provision_discovery_state_test.cpp", - "wifi_p2p_device_manager_test.cpp", - "wifi_p2p_dns_sd_service_info_test.cpp", - "wifi_p2p_dns_sd_service_request_test.cpp", - "wifi_p2p_dns_sd_service_response_test.cpp", - "wifi_p2p_group_info_proxy_test.cpp", - "wifi_p2p_group_manager_test.cpp", - "wifi_p2p_service_manager_test.cpp", - "wifi_p2p_service_request_list_test.cpp", - "wifi_p2p_service_response_list_test.cpp", - "wifi_p2p_service_test.cpp", - "wifi_p2p_upnp_service_info_test.cpp", - "wifi_p2p_upnp_service_request_test.cpp", - "wifi_p2p_upnp_service_response_test.cpp", - - #"./Mock/mock_wifi_settings.cpp", - - "//foundation/communication/wifi/interfaces/innerkits/native_cpp/wifi_standard/src/wifi_p2p_msg.cpp", - "//foundation/communication/wifi/services/wifi_standard/wifi_framework/common/config/wifi_config_file_spec.cpp", - "//foundation/communication/wifi/services/wifi_standard/wifi_framework/common/config/wifi_settings.cpp", - "//foundation/communication/wifi/services/wifi_standard/wifi_framework/common/log/log_helper.c", - "//foundation/communication/wifi/services/wifi_standard/wifi_framework/common/net_helper/base_address.cpp", - "//foundation/communication/wifi/services/wifi_standard/wifi_framework/common/net_helper/dhcpd_interface.cpp", - "//foundation/communication/wifi/services/wifi_standard/wifi_framework/common/net_helper/ip_tools.cpp", - "//foundation/communication/wifi/services/wifi_standard/wifi_framework/common/net_helper/ipv4_address.cpp", - "//foundation/communication/wifi/services/wifi_standard/wifi_framework/common/net_helper/ipv6_address.cpp", - "//foundation/communication/wifi/services/wifi_standard/wifi_framework/common/net_helper/mac_address.cpp", - "//foundation/communication/wifi/services/wifi_standard/wifi_framework/common/net_helper/network_interface.cpp", - "//foundation/communication/wifi/services/wifi_standard/wifi_framework/common/utils/wifi_global_func.cpp", - "//foundation/communication/wifi/services/wifi_standard/wifi_framework/wifi_manage/common/handler.cpp", - "//foundation/communication/wifi/services/wifi_standard/wifi_framework/wifi_manage/common/internal_message.cpp", - "//foundation/communication/wifi/services/wifi_standard/wifi_framework/wifi_manage/common/message_queue.cpp", - "//foundation/communication/wifi/services/wifi_standard/wifi_framework/wifi_manage/common/state.cpp", - "//foundation/communication/wifi/services/wifi_standard/wifi_framework/wifi_manage/common/state_machine.cpp", - "//foundation/communication/wifi/services/wifi_standard/wifi_framework/wifi_manage/common/wifi_broadcast_helper.cpp", - "global_test.cpp", - "wifi_p2p_test_entry.cpp", - - #"//foundation/communication/wifi/interfaces/innerkits/native_cpp/wifi_standard/samples/test_all/mock_ui/system_ui.cpp", - #"//foundation/communication/wifi/interfaces/innerkits/native_cpp/wifi_standard/samples/test_all/libaxprintf/xprint.c", - #"//foundation/communication/wifi/interfaces/innerkits/native_cpp/wifi_standard/samples/test_all/libaxprintf/log.c", - #"//foundation/communication/wifi/interfaces/innerkits/native_cpp/wifi_standard/samples/test_all/mock_ui/alert_dialog.cpp", - #"//foundation/communication/wifi/interfaces/innerkits/native_cpp/wifi_standard/samples/test_all/mock_ui/handle_message.cpp", - #"//foundation/communication/wifi/interfaces/innerkits/native_cpp/wifi_standard/samples/test_all/mock_ui/tcp_client.cpp", - #"//foundation/communication/wifi/interfaces/innerkits/native_cpp/wifi_standard/samples/test_all/mock_ui/tcp_server.cpp", - ] - - include_dirs = [ - "./", - "//foundation/communication/wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_p2p", - "./Mock", - "//utils/native/base/include", - "//base/hiviewdfx/hilog/interfaces/native/innerkits/include", - "//foundation/communication/wifi/interfaces/innerkits/native_cpp/wifi_standard/interfaces", - "//foundation/communication/wifi/services/wifi_standard/ipc_framework/cRPC/include", - "//foundation/communication/wifi/services/wifi_standard/wifi_framework/common/include", - "//foundation/communication/wifi/services/wifi_standard/wifi_framework/common/net_helper", - "//foundation/communication/wifi/services/wifi_standard/wifi_framework/common/config", - "//foundation/communication/wifi/services/wifi_standard/wifi_framework/common/log", - "//foundation/communication/wifi/services/wifi_standard/wifi_framework/common/utils", - "//foundation/communication/wifi/services/wifi_standard/wifi_framework/wifi_manage/common/include", - "//foundation/communication/wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_ap", - "//foundation/communication/wifi/services/wifi_standard/wifi_framework/wifi_manage", - "//foundation/communication/wifi/services/wifi_standard/wifi_framework/wifi_manage/common", - "//foundation/communication/wifi/services/wifi_standard/wifi_framework/wifi_manage/idl_client", - "//foundation/communication/wifi/services/wifi_standard/wifi_framework/wifi_manage/idl_client/idl_interface", - "//foundation/communication/wifi/services/wifi_standard/wifi_framework/dhcp_manage/mgr_service/include", - "//foundation/communication/wifi/services/wifi_standard/wifi_framework/dhcp_manage/mgr_service/interfaces", - - #"//foundation/communication/wifi/interfaces/innerkits/native_cpp/wifi_standard/samples/test_all/libaxprintf", - #"//foundation/communication/wifi/interfaces/innerkits/native_cpp/wifi_standard/samples/test_all/mock_ui", - "//third_party/googletest/googlemock/include", - "//third_party/googletest/googletest/include", - ] - - deps = [ - "//foundation/communication/wifi/services/wifi_standard/wifi_framework/dhcp_manage/mgr_service:dhcp_manager_service", - - #"//foundation/communication/wifi/interfaces/innerkits/native_cpp/wifi_standard/samples/test_all:all_test", - "//third_party/googletest:gmock_main", - "//utils/native/base:utils", - ] - external_deps = [ "hiviewdfx_hilog_native:libhilog" ] - part_name = "wifi_standard" - subsystem_name = "communication" -} - -group("unittest") { - testonly = true - deps = [] - deps += [ ":wifi_p2p_test" ] -} diff --git a/tests/wifi_standard/wifi_framework/wifi_manage/wifi_scan/BUILD.gn b/tests/wifi_standard/wifi_framework/wifi_manage/wifi_scan/BUILD.gn deleted file mode 100644 index ab4f861f16017c7692b64e5a4c24c6a8bda8cb27..0000000000000000000000000000000000000000 --- a/tests/wifi_standard/wifi_framework/wifi_manage/wifi_scan/BUILD.gn +++ /dev/null @@ -1,101 +0,0 @@ -# Copyright (C) 2021 Huawei Device Co., Ltd. -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -import("//build/test.gni") -SUBSYSTEM_DIR = "//foundation/communication" -module_output_path = "wifi_standard/scan_test" - -config("module_private_config") { - visibility = [ ":*" ] - include_dirs = [ - "//utils/native/base/include", - "$SUBSYSTEM_DIR/wifi/tests/wifi_standard/wifi_framework/wifi_manage/wifi_scan", - ] -} - -ohos_unittest("wifi_scan_unittest") { - module_out_path = module_output_path - sources = [ - "//foundation/communication/wifi/services/wifi_standard/wifi_framework/common/log/log_helper.c", - "//foundation/communication/wifi/services/wifi_standard/wifi_framework/common/net_helper/base_address.cpp", - "//foundation/communication/wifi/services/wifi_standard/wifi_framework/common/net_helper/ipv4_address.cpp", - "//foundation/communication/wifi/services/wifi_standard/wifi_framework/common/net_helper/ipv6_address.cpp", - "//foundation/communication/wifi/services/wifi_standard/wifi_framework/common/net_helper/mac_address.cpp", - "//foundation/communication/wifi/services/wifi_standard/wifi_framework/common/net_helper/network_interface.cpp", - "//foundation/communication/wifi/services/wifi_standard/wifi_framework/wifi_manage/common/handler.cpp", - "//foundation/communication/wifi/services/wifi_standard/wifi_framework/wifi_manage/common/internal_message.cpp", - "//foundation/communication/wifi/services/wifi_standard/wifi_framework/wifi_manage/common/message_queue.cpp", - "//foundation/communication/wifi/services/wifi_standard/wifi_framework/wifi_manage/common/state.cpp", - "//foundation/communication/wifi/services/wifi_standard/wifi_framework/wifi_manage/common/state_machine.cpp", - "//foundation/communication/wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_scan/scan_interface.cpp", - "//foundation/communication/wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_scan/scan_monitor.cpp", - "//foundation/communication/wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_scan/scan_service.cpp", - "//foundation/communication/wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_scan/scan_state_machine.cpp", - "Mock/mock_scan_service.cpp", - "Mock/mock_scan_state_machine.cpp", - "Mock/mock_wifi_manager.cpp", - "Mock/mock_wifi_settings.cpp", - "Mock/mock_wifi_sta_hal_interface.cpp", - "Mock/mock_wifi_supplicant_hal_interface.cpp", - "global_test.cpp", - "scan_interface_test.cpp", - "scan_monitor_test.cpp", - "scan_service_test.cpp", - "scan_state_machine_test.cpp", - "wifi_scan_test.cpp", - ] - - include_dirs = [ - "//utils/native/base/include", - "//foundation/communication/wifi/interfaces/innerkits/native_cpp/wifi_standard/interfaces", - "//foundation/communication/wifi/services/wifi_standard/sdk/include", - "//foundation/communication/wifi/services/wifi_standard/ipc_framework/cRPC/include", - "//foundation/communication/wifi/services/wifi_standard/wifi_framework/common/include", - "//foundation/communication/wifi/services/wifi_standard/wifi_framework/common/net_helper", - "//foundation/communication/wifi/services/wifi_standard/wifi_framework/common/log", - "//foundation/communication/wifi/services/wifi_standard/wifi_framework/common/config", - "//foundation/communication/wifi/services/wifi_standard/wifi_framework/common/utils", - "//foundation/communication/wifi/services/wifi_standard/wifi_framework/wifi_manage/common", - "//foundation/communication/wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_scan", - "//foundation/communication/wifi/tests/wifi_standard/wifi_framework/wifi_manage/wifi_scan/Mock", - "//foundation/communication/wifi/services/wifi_standard/wifi_framework/wifi_manage/", - "//foundation/communication/wifi/services/wifi_standard/wifi_framework/wifi_manage/idl_client", - "//foundation/communication/wifi/services/wifi_standard/wifi_framework/wifi_manage/idl_client/idl_interface", - "//foundation/communication/wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_sta/net_conf", - "//foundation/communication/wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_sta", - "//base/hiviewdfx/hilog/interfaces/native/innerkits/include", - "//foundation/communication/wifi/services/wifi_standard/depends/include/hardware/libhardware/include", - "//foundation/communication/wifi/services/wifi_standard/depends/include/system/core/include", - "//foundation/communication/wifi/services/wifi_standard/depends/include/frameworks/native/include", - "//foundation/communication/wifi/services/wifi_standard/depends/include/system/core/libutils/include", - "//foundation/communication/wifi/services/wifi_standard/depends/include/system/core/base/include", - "//foundation/communication/wifi/services/wifi_standard/depends/include/system/libbase/include", - "//foundation/communication/wifi/services/wifi_standard/depends/include/system/core/libnetutils/include/netutils", - "//third_party/googletest/googlemock/include", - "//third_party/googletest/googletest/include", - ] - deps = [ - "//foundation/communication/wifi/services/wifi_standard/wifi_framework/wifi_manage:wifi_manager_service", - "//foundation/communication/wifi/services/wifi_standard/wifi_framework/wifi_manage/idl_client:wifi_idl_client", - "//third_party/googletest:gmock_main", - "//utils/native/base:utils", - ] - external_deps = [ "hiviewdfx_hilog_native:libhilog" ] - part_name = "wifi_standard" - subsystem_name = "communication" -} - -group("unittest") { - testonly = true - deps = [ ":wifi_scan_unittest" ] -} diff --git a/tests/wifi_standard/wifi_framework/wifi_manage/wifi_scan/wifi_scan_test.cpp b/tests/wifi_standard/wifi_framework/wifi_manage/wifi_scan/wifi_scan_test.cpp deleted file mode 100644 index 067af39ab9fea0041b8737fb4ff45edc06d53e48..0000000000000000000000000000000000000000 --- a/tests/wifi_standard/wifi_framework/wifi_manage/wifi_scan/wifi_scan_test.cpp +++ /dev/null @@ -1,24 +0,0 @@ -/* - * Copyright (C) 2021 Huawei Device Co., Ltd. - * 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 "global_test.h" - -int main(int argc, char *argv[]) -{ - testing::InitGoogleTest(&argc, argv); - testing::Environment *env = new GlobalTest(); - testing::AddGlobalTestEnvironment(env); - return RUN_ALL_TESTS(); -} \ No newline at end of file diff --git a/tests/wifi_standard/wifi_framework/wifi_manage/wifi_sta/BUILD.gn b/tests/wifi_standard/wifi_framework/wifi_manage/wifi_sta/BUILD.gn deleted file mode 100644 index ed8238a2c7ba5f85e38452f0ba8689a94949b212..0000000000000000000000000000000000000000 --- a/tests/wifi_standard/wifi_framework/wifi_manage/wifi_sta/BUILD.gn +++ /dev/null @@ -1,129 +0,0 @@ -# Copyright (C) 2021 Huawei Device Co., Ltd. -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -import("//build/test.gni") -SUBSYSTEM_DIR = "//foundation/communication" -module_output_path = "wifi_standard/sta_test" - -defines = [] -defines += [ "OHOS_WIFI_STA_TEST" ] - -config("module_private_config") { - visibility = [ ":*" ] - include_dirs = [ - "//utils/native/base/include", - "$SUBSYSTEM_DIR/wifi/tests/wifi_standard/wifi_framework/wifi_manage/wifi_sta", - ] -} - -ohos_unittest("wifi_sta_unittest") { - module_out_path = module_output_path - sources = [ - "//foundation/communication/wifi/services/wifi_standard/wifi_framework/common/log/log_helper.c", - "//foundation/communication/wifi/services/wifi_standard/wifi_framework/common/net_helper/http_request.cpp", - "//foundation/communication/wifi/services/wifi_standard/wifi_framework/common/net_helper/ip_tools.cpp", - "//foundation/communication/wifi/services/wifi_standard/wifi_framework/wifi_manage/common/handler.cpp", - "//foundation/communication/wifi/services/wifi_standard/wifi_framework/wifi_manage/common/internal_message.cpp", - "//foundation/communication/wifi/services/wifi_standard/wifi_framework/wifi_manage/common/message_queue.cpp", - "//foundation/communication/wifi/services/wifi_standard/wifi_framework/wifi_manage/common/state.cpp", - "//foundation/communication/wifi/services/wifi_standard/wifi_framework/wifi_manage/common/state_machine.cpp", - "//foundation/communication/wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_sta/sta_auto_connect_service.cpp", - - #"//foundation/communication/wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_sta/sta_extern_device_appraisal.cpp", - "//foundation/communication/wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_sta/sta_interface.cpp", - "//foundation/communication/wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_sta/sta_monitor.cpp", - "//foundation/communication/wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_sta/sta_network_check.cpp", - "//foundation/communication/wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_sta/sta_network_speed.cpp", - "//foundation/communication/wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_sta/sta_saved_device_appraisal.cpp", - "//foundation/communication/wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_sta/sta_service.cpp", - "//foundation/communication/wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_sta/sta_state_machine.cpp", - "Mock/mock_dhcp_service.cpp", - "Mock/mock_if_config.cpp", - "Mock/mock_mac_address.cpp", - "Mock/mock_sta_auto_connect_service.cpp", - "Mock/mock_sta_network_check.cpp", - "Mock/mock_sta_state_machine.cpp", - "Mock/mock_wifi_chip_hal_interface.cpp", - "Mock/mock_wifi_manager.cpp", - "Mock/mock_wifi_settings.cpp", - "Mock/mock_wifi_sta_hal_interface.cpp", - "Mock/mock_wifi_supplicant_hal_interface.cpp", - "global_test.cpp", - "sta_auto_connect_service_test.cpp", - "sta_interface_test.cpp", - "sta_monitor_test.cpp", - "sta_network_check_test.cpp", - "sta_saved_device_appraisal_test.cpp", - "sta_service_test.cpp", - "sta_state_machine_test.cpp", - "wifi_sta_test.cpp", - ] - - include_dirs = [ - "./", - "./Mock", - "//foundation/communication/wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_sta/net_conf", - "//foundation/communication/wifi/interfaces/innerkits/native_cpp/wifi_standard/include", - "//foundation/communication/wifi/interfaces/innerkits/native_cpp/wifi_standard/interfaces", - "//foundation/communication/wifi/services/wifi_standard/interface", - "//foundation/communication/wifi/services/wifi_standard/ipc_framework/cRPC/include", - "//foundation/communication/wifi/services/wifi_standard/wifi_framework/common/include", - "//foundation/communication/wifi/services/wifi_standard/wifi_framework/common/net_helper", - "//foundation/communication/wifi/services/wifi_standard/wifi_framework/common/log", - "//foundation/communication/wifi/services/wifi_standard/wifi_framework/common/config", - "//foundation/communication/wifi/services/wifi_standard/wifi_framework/common/utils", - "//foundation/communication/wifi/services/wifi_standard/wifi_framework/wifi_manage/common", - "//foundation/communication/wifi/services/wifi_standard/wifi_framework/wifi_manage", - "//foundation/communication/wifi/services/wifi_standard/wifi_framework/wifi_manage/idl_client", - "//foundation/communication/wifi/services/wifi_standard/wifi_framework/wifi_manage/idl_client/idl_interface", - "//foundation/communication/wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_ap", - "//foundation/communication/wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_aware", - "//foundation/communication/wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_p2p", - "//foundation/communication/wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_scan", - "//foundation/communication/wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_sta", - "//foundation/communication/wifi/services/wifi_standard/ipc_framework/cRPC/include", - "//foundation/communication/wifi/services/wifi_standard/wifi_framework/dhcp_manage/mgr_service/include", - "//foundation/communication/wifi/services/wifi_standard/wifi_framework/dhcp_manage/mgr_service/interfaces", - - "//third_party/googletest/googlemock/include", - "//third_party/googletest/googletest/include", - - "//base/notification/ces_standard/cesfwk/kits/native/include", - "//out/ohos-arm-release/innerkits/ohos-arm/ces_standard/cesfwk_kits/include", - - "//utils/native/base/include", - "//foundation/communication/ipc/interfaces/innerkits/ipc_core/include", - "//base/hiviewdfx/hilog/interfaces/native/innerkits/include", - "//foundation/ace/ace_engine/frameworks/base/utils", - "//foundation/ace/ace_engine/frameworks", - "//foundation/distributedschedule/safwk/interfaces/innerkits/safwk/", - "//foundation/aafwk/standard/interfaces/innerkits/want/include/ohos/aafwk/content/", - "//foundation/aafwk/aafwk_lite/interfaces/kits/want_lite/", - ] - - deps = [ - "//foundation/communication/wifi/services/wifi_standard/wifi_framework/dhcp_manage/mgr_service:dhcp_manager_service", - "//foundation/communication/wifi/services/wifi_standard/wifi_framework/wifi_manage:wifi_manager_service", - "//foundation/communication/wifi/services/wifi_standard/wifi_framework/wifi_manage/idl_client:wifi_idl_client", - "//third_party/googletest:gmock_main", - "//utils/native/base:utils", - ] - external_deps = [ "hiviewdfx_hilog_native:libhilog" ] - part_name = "wifi_standard" - subsystem_name = "communication" -} - -group("unittest") { - testonly = true - deps = [ ":wifi_sta_unittest" ] -} diff --git a/tests/wifi_standard/wifi_framework/wifi_manage/wifi_sta/wifi_sta_test.cpp b/tests/wifi_standard/wifi_framework/wifi_manage/wifi_sta/wifi_sta_test.cpp deleted file mode 100644 index 067af39ab9fea0041b8737fb4ff45edc06d53e48..0000000000000000000000000000000000000000 --- a/tests/wifi_standard/wifi_framework/wifi_manage/wifi_sta/wifi_sta_test.cpp +++ /dev/null @@ -1,24 +0,0 @@ -/* - * Copyright (C) 2021 Huawei Device Co., Ltd. - * 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 "global_test.h" - -int main(int argc, char *argv[]) -{ - testing::InitGoogleTest(&argc, argv); - testing::Environment *env = new GlobalTest(); - testing::AddGlobalTestEnvironment(env); - return RUN_ALL_TESTS(); -} \ No newline at end of file diff --git a/wifi/BUILD.gn b/wifi/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..f99a0a8e0d924308101c92d94adfe627c5c78ac5 --- /dev/null +++ b/wifi/BUILD.gn @@ -0,0 +1,29 @@ +# Copyright (C) 2022 Huawei Device Co., Ltd. +# 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. + +if (defined(ohos_lite)) { + import("//build/lite/config/component/lite_component.gni") + import("//foundation/communication/wifi/wifi/wifi_lite.gni") + + lite_component("wifi") { + deps = [ + "$WIFI_ROOT_DIR/frameworks:wifi_kits", + "$WIFI_ROOT_DIR/services/wifi_standard/wifi_framework:wifi_manage", + "$WIFI_ROOT_DIR/services/wifi_standard/wifi_framework:wifi_system_ability", + "$WIFI_ROOT_DIR/services/wifi_standard/wifi_hal:wifi_hal", + "$WIFI_ROOT_DIR/test/wifi_client:wifi_client", + "$WIFI_ROOT_DIR/utils:wifi_utils", + ] + features = [] + } +} diff --git a/wifi/application/wifi_direct_demo/README.md b/wifi/application/wifi_direct_demo/README.md new file mode 100644 index 0000000000000000000000000000000000000000..e586324184ef28d8fba935a650f07300a3ea6274 --- /dev/null +++ b/wifi/application/wifi_direct_demo/README.md @@ -0,0 +1,25 @@ +# WifiDirectDemo + +## 简介 +WIFI DIRECT接口使用DEMO +### 效果图 +![](figures/img.png) + +## 目录 + +``` +├── entry # 主entry模块目录 +│ └── src +│ ├── main +│ ├── ets # ets模块目录 +│ ├── MainAbility +│ ├── common # 公共工具存放目录 +│ ├── model # 数据管理和决策逻辑存放目录 +│ ├── pages # 组件页面存放目录 +│ ├── res # 部分图片资源 +│ ├── app.ets # 全局ets逻辑和应用生命周期管理文件 +│ ├── resources # 资源配置文件存放目录 +│ ├── base # 默认语言场景,图片资源,字体大小,颜色资源内容存放目录 +│ ├── rawfile # 本地配置文件存放目录 +│ └── config.json # 全局配置文件 +``` diff --git a/wifi/application/wifi_direct_demo/build.gradle b/wifi/application/wifi_direct_demo/build.gradle new file mode 100644 index 0000000000000000000000000000000000000000..c950ef3a6802fde212c4298697b14ec87f0d4ccc --- /dev/null +++ b/wifi/application/wifi_direct_demo/build.gradle @@ -0,0 +1,45 @@ +// Top-level build file where you can add configuration options common to all sub-projects/modules. +apply plugin: 'com.huawei.ohos.app' + +//For instructions on signature configuration, see https://developer.harmonyos.com/cn/docs/documentation/doc-guides/ide_debug_device-0000001053822404#section1112183053510 +ohos { + signingConfigs { + release { + storeFile file('D:\\DEMO\\p2pConn\\key\\p12.p12') + storePassword '000000191B43D06B5E9EDFED66FD3F6E1CAE7F525ADB341F4505171E2C399FFEC71203E24A5E3A22AD' + keyAlias = 'harmony' + keyPassword '00000019787AB39924ADB7C6BDCFF7510EF04C4BC4C09A817D7F38553D5C6AFFF8B3ED0CE84FD1415F' + signAlg = 'SHA256withECDSA' + profile file('D:\\DEMO\\p2pConn\\key\\p7b.p7b') + certpath file('D:\\DEMO\\p2pConn\\key\\cer.cer') + } + } + compileSdkVersion 7 + supportSystem "standard" +} + +buildscript { + repositories { + maven { + url 'https://repo.huaweicloud.com/repository/maven/' + } + maven { + url 'https://developer.huawei.com/repo/' + } + } + dependencies { + classpath 'com.huawei.ohos:hap:3.0.5.2' + classpath 'com.huawei.ohos:decctest:1.2.7.2' + } +} + +allprojects { + repositories { + maven { + url 'https://repo.huaweicloud.com/repository/maven/' + } + maven { + url 'https://developer.huawei.com/repo/' + } + } +} diff --git a/wifi/application/wifi_direct_demo/entry/.gitignore b/wifi/application/wifi_direct_demo/entry/.gitignore new file mode 100644 index 0000000000000000000000000000000000000000..7d5b7a94f4dcf381f03ff21f28f8a2494b58023f --- /dev/null +++ b/wifi/application/wifi_direct_demo/entry/.gitignore @@ -0,0 +1,2 @@ +/build +/node_modules diff --git a/wifi/application/wifi_direct_demo/entry/build.gradle b/wifi/application/wifi_direct_demo/entry/build.gradle new file mode 100644 index 0000000000000000000000000000000000000000..907b2a3044a0cc2bf6b38c232708426fa7e9e417 --- /dev/null +++ b/wifi/application/wifi_direct_demo/entry/build.gradle @@ -0,0 +1,21 @@ +apply plugin: 'com.huawei.ohos.hap' +//For instructions on signature configuration, see https://developer.harmonyos.com/cn/docs/documentation/doc-guides/ide_debug_device-0000001053822404#section1112183053510 +ohos { + compileSdkVersion 7 + defaultConfig { + compatibleSdkVersion 6 + } + buildTypes { + release { + proguardOpt { + proguardEnabled false + rulesFiles 'proguard-rules.pro' + } + } + } +} + +dependencies { + implementation fileTree(dir: 'libs', include: ['*.jar', '*.har']) + testImplementation 'junit:junit:4.13.1' +} diff --git a/wifi/application/wifi_direct_demo/entry/proguard-rules.pro b/wifi/application/wifi_direct_demo/entry/proguard-rules.pro new file mode 100644 index 0000000000000000000000000000000000000000..f7666e47561d514b2a76d5a7dfbb43ede86da92a --- /dev/null +++ b/wifi/application/wifi_direct_demo/entry/proguard-rules.pro @@ -0,0 +1 @@ +# config module specific ProGuard rules here. \ No newline at end of file diff --git a/wifi/application/wifi_direct_demo/entry/src/main/config.json b/wifi/application/wifi_direct_demo/entry/src/main/config.json new file mode 100644 index 0000000000000000000000000000000000000000..7348386e0236b5dc2d0c19635dc2070482fdc954 --- /dev/null +++ b/wifi/application/wifi_direct_demo/entry/src/main/config.json @@ -0,0 +1,69 @@ +{ + "app": { + "bundleName": "com.ohos.wifidirectdemo", + "vendor": "example", + "version": { + "code": 1000000, + "name": "1.0.0" + } + }, + "deviceConfig": {}, + "module": { + "package": "com.ohos.wifidirectdemo", + "name": ".MyApplication", + "mainAbility": ".MainAbility", + "srcPath": "", + "deviceType": [ + "default", + "phone", + "tablet" + ], + "distro": { + "deliveryWithInstall": true, + "moduleName": "entry", + "moduleType": "entry", + "installationFree": false + }, + "abilities": [ + { + "skills": [ + { + "entities": [ + "entity.system.home" + ], + "actions": [ + "action.system.home" + ] + } + ], + "orientation": "unspecified", + "visible": true, + "srcPath": "MainAbility", + "name": ".MainAbility", + "srcLanguage": "ets", + "icon": "$media:icon", + "description": "$string:description_mainability", + "formsEnabled": false, + "label": "$string:app_name", + "type": "page", + "launchType": "standard" + } + ], + "js": [ + { + "mode": { + "syntax": "ets", + "type": "pageAbility" + }, + "pages": [ + "pages/index" + ], + "name": ".MainAbility", + "window": { + "designWidth": 720, + "autoDesignWidth": false + } + } + ] + } +} \ No newline at end of file diff --git a/tests/wifi_standard/wifi_framework/dhcp_manage/mgr_service/dhcp_manage_test.cpp b/wifi/application/wifi_direct_demo/entry/src/main/ets/MainAbility/app.ets similarity index 56% rename from tests/wifi_standard/wifi_framework/dhcp_manage/mgr_service/dhcp_manage_test.cpp rename to wifi/application/wifi_direct_demo/entry/src/main/ets/MainAbility/app.ets index 17d38d8b84b0206319d1b264d40bbd60de704975..68aa8a1d2dc702d26fe1ad2ad77c82684991aa54 100644 --- a/tests/wifi_standard/wifi_framework/dhcp_manage/mgr_service/dhcp_manage_test.cpp +++ b/wifi/application/wifi_direct_demo/entry/src/main/ets/MainAbility/app.ets @@ -1,10 +1,10 @@ -/* - * Copyright (C) 2021 Huawei Device Co., Ltd. +/** + * Copyright (c) 2022 Shenzhen Kaihong Digital Industry Development Co., Ltd. * 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 + * 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, @@ -13,13 +13,14 @@ * limitations under the License. */ -#include -#include "global_test.h" - -int main(int argc, char *argv[]) -{ - testing::InitGoogleTest(&argc, argv); - testing::Environment *env = new GlobalTest(); - testing::AddGlobalTestEnvironment(env); - return RUN_ALL_TESTS(); +import logUtil from './common/LogUtil.ets' +import wifiModel from './model/wifiModeImpl/WifiModel.ets' +export default { + onCreate() { + logUtil.info('Application onCreate') + wifiModel.enableP2p() + }, + onDestroy() { + logUtil.info('Application onDestroy') + }, } \ No newline at end of file diff --git a/wifi/application/wifi_direct_demo/entry/src/main/ets/MainAbility/common/LogUtil.ets b/wifi/application/wifi_direct_demo/entry/src/main/ets/MainAbility/common/LogUtil.ets new file mode 100644 index 0000000000000000000000000000000000000000..498b0ef5574a0bf43db7ed729a9e04db6bec362f --- /dev/null +++ b/wifi/application/wifi_direct_demo/entry/src/main/ets/MainAbility/common/LogUtil.ets @@ -0,0 +1,48 @@ +/** + * Copyright (c) 2022 Shenzhen Kaihong Digital Industry Development Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import BaseModel from '../model/BaseModel.ets'; + +export class LogUtil extends BaseModel { + TAG() { + return '------------ P2P ------------ '; + } + + debug(msg) { + console.info(this.TAG() + msg); + } + + log(msg) { + console.log(this.TAG() + msg); + + } + + info(msg) { + console.info(this.TAG() + msg); + } + + warn(msg) { + console.warn(this.TAG() + msg); + } + + error(msg) { + console.error(this.TAG() + msg); + } +} + +let mLogUtil = new LogUtil(); + +export default mLogUtil as LogUtil; + diff --git a/wifi/application/wifi_direct_demo/entry/src/main/ets/MainAbility/common/StorageUtil.ets b/wifi/application/wifi_direct_demo/entry/src/main/ets/MainAbility/common/StorageUtil.ets new file mode 100644 index 0000000000000000000000000000000000000000..c701859cfbbcbd403ee94dc914254faedaec6cbe --- /dev/null +++ b/wifi/application/wifi_direct_demo/entry/src/main/ets/MainAbility/common/StorageUtil.ets @@ -0,0 +1,67 @@ +/** + * Copyright (c) 2022 Shenzhen Kaihong Digital Industry Development Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import BaseModel from '../model/BaseModel.ets'; +import LogUtil from './LogUtil.ets'; +import Storage from '@ohos.data.storage'; + +const PREFERENCES_PATH = '/data/accounts/account_0/appdata/com.ohos.wifidirectdemo/sharedPreference/WifiDirectPreference'; + +let mPreferences = null; +export class StorageUtil extends BaseModel { + constructor() { + super(); + mPreferences = Storage.getStorageSync(PREFERENCES_PATH); + } + + isPreferencesExist(key) { + if (mPreferences && mPreferences.hasSync(key)) { + return true; + } + return false; + } + /** + * 获取数据并指定默认 + */ + getDataToDef(key, def) { + let data; + if (mPreferences && mPreferences.hasSync(key)) { + data = mPreferences.getSync(key, def); + } else { + data = def; + } + LogUtil.info('getDataToDef key == ' + key + ' data == ' + data); + return data; + } + /** + * 同步保存原始数据 + */ + putObjData(key, value) { + LogUtil.info('putObjData key == ' + key + ' value == ' + value); + mPreferences.putSync(key, value); + mPreferences.flush(); + } + /** + * 删除指定键数据 + */ + delObjData(key) { + LogUtil.info('delObjData key == ' + key); + mPreferences.delete(key); + } +} + +let mStorageUtil = new StorageUtil(); + +export default mStorageUtil as StorageUtil; diff --git a/wifi/application/wifi_direct_demo/entry/src/main/ets/MainAbility/model/BaseModel.ets b/wifi/application/wifi_direct_demo/entry/src/main/ets/MainAbility/model/BaseModel.ets new file mode 100644 index 0000000000000000000000000000000000000000..c23113efc164eadd239fbe1552f79a4aeccc6f59 --- /dev/null +++ b/wifi/application/wifi_direct_demo/entry/src/main/ets/MainAbility/model/BaseModel.ets @@ -0,0 +1,19 @@ +/** + * Copyright (c) 2022 Shenzhen Kaihong Digital Industry Development Co., Ltd. + * 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. + */ + +export default class BaseModel { + constructor() { + } +} \ No newline at end of file diff --git a/tests/wifi_standard/wifi_framework/wifi_manage/wifi_ap/wifi_ap_dhcp_nat/wifi_ap_test.cpp b/wifi/application/wifi_direct_demo/entry/src/main/ets/MainAbility/model/wifiModeImpl/WifiEntity.ets similarity index 54% rename from tests/wifi_standard/wifi_framework/wifi_manage/wifi_ap/wifi_ap_dhcp_nat/wifi_ap_test.cpp rename to wifi/application/wifi_direct_demo/entry/src/main/ets/MainAbility/model/wifiModeImpl/WifiEntity.ets index e2e4b1c030867587608887b1dca485967e3a02b3..831d3bac3b0f30da655294cb87967c03771c259d 100644 --- a/tests/wifi_standard/wifi_framework/wifi_manage/wifi_ap/wifi_ap_dhcp_nat/wifi_ap_test.cpp +++ b/wifi/application/wifi_direct_demo/entry/src/main/ets/MainAbility/model/wifiModeImpl/WifiEntity.ets @@ -1,10 +1,10 @@ -/* - * Copyright (c) 2021 Huawei Device Co., Ltd. +/** + * Copyright (c) 2022 Shenzhen Kaihong Digital Industry Development Co., Ltd. * 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 + * 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, @@ -13,13 +13,16 @@ * limitations under the License. */ -#include "global_test.h" -#include +export class WifiEntity { + index: number + deviceName: string + macAddress: string + status: number -int main(int argc, char *argv[]) -{ - testing::InitGoogleTest(&argc, argv); - testing::Environment *env = new GlobalTest(); - testing::AddGlobalTestEnvironment(env); - return RUN_ALL_TESTS(); + constructor(index: number, deviceName: string, macAddress: string, status: number) { + this.index = index + this.deviceName = deviceName + this.macAddress = macAddress + this.status = status + } } \ No newline at end of file diff --git a/wifi/application/wifi_direct_demo/entry/src/main/ets/MainAbility/model/wifiModeImpl/WifiModel.ets b/wifi/application/wifi_direct_demo/entry/src/main/ets/MainAbility/model/wifiModeImpl/WifiModel.ets new file mode 100644 index 0000000000000000000000000000000000000000..d92c85f3939cc86f535d5174aa664e5033df4fe3 --- /dev/null +++ b/wifi/application/wifi_direct_demo/entry/src/main/ets/MainAbility/model/wifiModeImpl/WifiModel.ets @@ -0,0 +1,162 @@ +/** + * Copyright (c) 2022 Shenzhen Kaihong Digital Industry Development Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import BaseModel from '../BaseModel.ets'; +import mLogUtil from '../../common/LogUtil.ets'; +import WifiNativeJs from '@ohos.wifi'; + +export class WifiModel extends BaseModel { + getListener() { + return new WifiNativeJs.EventListener(); + } + + enableP2p() { + mLogUtil.log("enableP2p"); + return WifiNativeJs.enableP2p(); + } + + disableP2p() { + mLogUtil.log("disableP2p") + return WifiNativeJs.disableP2p(); + } + + on(typeValue, callBack) { + mLogUtil.log("on " + typeValue); + WifiNativeJs.on(typeValue, callBack); + } + + discoverDevices() { + mLogUtil.log("startDiscoverDevices"); + return WifiNativeJs.startDiscoverDevices(); + } + + stopDiscoverDevices() { + mLogUtil.log("stopDiscoverDevices"); + return WifiNativeJs.stopDiscoverDevices(); + } + + discoverServices() { + mLogUtil.log("DiscoverServices"); + return WifiNativeJs.discoverServices(); + } + + setDeviceName(name) { + mLogUtil.log("setDeviceName"); + return WifiNativeJs.setP2pDeviceName(name); + } + + stopDiscoverServices() { + mLogUtil.log("stopDiscoverServices"); + return WifiNativeJs.stopDiscoverServices(); + } + + connectP2pDevices(config) { + mLogUtil.log("connectP2pDevices"); + return WifiNativeJs.p2pConnect(config); + } + + disconnectP2pDevices() { + mLogUtil.log("disconnectP2pDevices"); + return WifiNativeJs.removeGroup(); + } + + cancelConnect() { + mLogUtil.log("wifi direct - p2pCancelConnect()"); + return WifiNativeJs.p2pCancelConnect()(); + } + + getLinkInfo(cb) { + mLogUtil.log("getLinkInfo"); + WifiNativeJs.getP2pLinkedInfo((result) => { + mLogUtil.log("getLinkInfo " + JSON.stringify(result)); + let resultStr = null + if (result != null) { + let info = JSON.parse(JSON.stringify(result)); + resultStr = 'connectState' + (info.connectState == 1 ? 'CONNECTED' : 'DISCONNECTED') + '\nisP2pGroupOwner' + info.isP2pGroupOwner + '\ngroupOwnerAddress' + info.groupOwnerAddress + } + cb(resultStr) + }); + } + + getCurrentGroupInfo(cb) { + mLogUtil.log("getCurrentGroupInfo"); + WifiNativeJs.getCurrentGroup((result) => { + let info = result; + mLogUtil.log("current group result = " + result); + if (result != null) { + mLogUtil.log("current group info = " + JSON.stringify(result)); + info = JSON.parse(JSON.stringify(result)); + } + cb(info); + }); + } + + getP2pDevicesCallBack() { + mLogUtil.log("wifi model getP2pDevicesCallBack"); + let mDeviceList = []; + return new Promise((resolve) => { + WifiNativeJs.getP2pDevices((result) => { + if (result == null) { + mLogUtil.log("WifiNativeJs queryP2pDevices"); + return; + } + let datas = JSON.parse(JSON.stringify(result)); + mLogUtil.log('result === ' + JSON.stringify(result)) + for (let j = 0; j < datas.length; j++) { + mDeviceList.push({ + ssid: datas[j].deviceName, + macAddress: datas[j].macAddress, + status: datas[j].status + }); + } + mLogUtil.log("mWifiList = " + JSON.stringify(mDeviceList)); + resolve(mDeviceList); + }); + }) + } + + createGroup() { + /* + const int TEMPORARY_NET_ID = -1; + const int PERSISTENT_NET_ID = -2; + const int INVALID_NET_ID = -999; + */ + WifiNativeJs.createGroup({ + 'netId': -2 + }); + } + + deletePersistentGroup(id) { + mLogUtil.log("deletePersistentGroup id = " + id) + return WifiNativeJs.deletePersistentGroup(id) + } + + removeGroup() { + WifiNativeJs.removeGroup(); + } + + getMacAddress() { + mLogUtil.log("getMacAddress"); + return WifiNativeJs.getDeviceMacAddress(); + } + + setWfdInfo() { + return WifiNativeJs.setP2pWfdInfo(true); + } +} + +let wifiModel = new WifiModel(); + +export default wifiModel as WifiModel; \ No newline at end of file diff --git a/wifi/application/wifi_direct_demo/entry/src/main/ets/MainAbility/pages/component/dialog/customPromptDialog.ets b/wifi/application/wifi_direct_demo/entry/src/main/ets/MainAbility/pages/component/dialog/customPromptDialog.ets new file mode 100644 index 0000000000000000000000000000000000000000..c5c9be17d4c1ffaa820d91621880a62a58105992 --- /dev/null +++ b/wifi/application/wifi_direct_demo/entry/src/main/ets/MainAbility/pages/component/dialog/customPromptDialog.ets @@ -0,0 +1,97 @@ +/** + * Copyright (c) 2022 Shenzhen Kaihong Digital Industry Development Co., Ltd. + * 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. + */ + +/** + * 自定义提示弹窗 + */ +@CustomDialog +export default struct CustomPromptDialog { + title: string = '提示'; + cancelVal: string= '取消'; + confirmVal: string= '确定'; + @State contentVal: string = ''; + controller: CustomDialogController; + eventAction: () => void; + + build() { + Column() { + Text(this.title) + .width('95%') + .fontSize(20) + .fontColor(Color.Black) + .fontWeight(FontWeight.Bold) + .margin({ + top: 20, + bottom: 15, + left: 20 + }) + Scroll() { + Flex() { + Text(this.contentVal) + .fontSize(18) + .fontColor(Color.Black) + .lineHeight(33) + } + .margin({ + left: 20, + top: 10, + right: 20, + bottom: 10 + }) + } + .width('95%') + .height(120) + .scrollable(ScrollDirection.Vertical) + + Row() { + Button(this.cancelVal, { type: ButtonType.Capsule, stateEffect: true }) + .padding({ + top: 10, + bottom: 10 + }) + .stateEffect(false) + .fontSize(17) + .fontColor(Color.Black) + .backgroundColor(Color.White) + .layoutWeight(1) + .onClick(() => { + this.controller.close(); + }) + Divider() + .width(1) + .height(30) + .color('#bcbcbc') + .vertical(true) + Button(this.confirmVal, { type: ButtonType.Capsule, stateEffect: true }) + .padding({ + top: 10, + bottom: 10 + }) + .stateEffect(false) + .fontSize(17) + .fontColor(Color.Black) + .backgroundColor(Color.White) + .layoutWeight(1) + .onClick(() => { + this.controller.close(); + this.eventAction(); + }) + } + } + .width('100%') + .backgroundColor(Color.White) + .borderRadius(15) + } +} \ No newline at end of file diff --git a/wifi/application/wifi_direct_demo/entry/src/main/ets/MainAbility/pages/component/dialog/inputComponent.ets b/wifi/application/wifi_direct_demo/entry/src/main/ets/MainAbility/pages/component/dialog/inputComponent.ets new file mode 100644 index 0000000000000000000000000000000000000000..6c836ad983058104757ac3fdd328f650e0410dc5 --- /dev/null +++ b/wifi/application/wifi_direct_demo/entry/src/main/ets/MainAbility/pages/component/dialog/inputComponent.ets @@ -0,0 +1,122 @@ +/** + * Copyright (c) 2022 Shenzhen Kaihong Digital Industry Development Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import prompt from '@system.prompt'; +/** + * 自定义输入弹窗 + */ +@CustomDialog +export default struct InputComponent { + title: string = '提示'; + cancelVal: string= '取消'; + confirmVal: string= '确定'; + inputValLength: number = 15; //输入字符长度限制 + @State inputHint: string= ''; + @State inputValue: string = ''; + @State inputType: number = InputType.Password; + controller: CustomDialogController; + eventConnect: (value: string) => void; + +// checkCharacter(str: string): boolean{ +// let pattern = new RegExp("[`+-\\~!@#$^&*()=|{}':;',\\[\\].<>《》/?~!@#¥……&*()——|{}【】‘;:”“'。,、? ]"); +// if (pattern.test(str)) { +// return true; +// } +// return false; +// } + + build() { + Column() { + Text(this.title) + .fontSize(20) + .fontWeight(FontWeight.Bold) + .fontColor(Color.Black) + .margin({ + top: 15, + bottom: 15, + left: 20, + right: 20 + }) + + TextInput({ placeholder: this.inputHint, text: this.inputValue }) + .placeholderColor(Color.Black) + .placeholderFont({ size: 20 }) + .height(50) + .borderRadius(6) + .type(this.inputType) + .margin({ + top: 10, + left: 15, + right: 15, + bottom: 10 + }) + .padding({ left: 10, right: 10 }) + .onChange((value: string) => { + this.inputValue = value; + }) + .height(60) + // Divider() + // .color('#bcbcbc') + // .height(1) + // .margin({ + // left: 15, + // right: 15 + // }) + + Row() { + Button(this.cancelVal, { type: ButtonType.Capsule, stateEffect: true }) + .fontSize(17) + .fontColor(Color.Black) + .backgroundColor(Color.White) + .layoutWeight(1) + .stateEffect(false) + .padding({ + top: 5, + bottom: 5 + }) + .onClick(() => { + this.controller.close(); + }) + Divider() + .width(1) + .height(30) + .vertical(true) + .color('#bcbcbc') + Button(this.confirmVal, { type: ButtonType.Capsule, stateEffect: true }) + .fontSize(17) + .fontColor(Color.Black) + .backgroundColor(Color.White) + .layoutWeight(1) + .stateEffect(false) + .padding({ + top: 5, + bottom: 5 + }) + .onClick(() => { + if (this.inputValue == '') { + prompt.showToast({ message: '请输入' + this.title }) + } else if (this.inputValue.length > this.inputValLength) { + prompt.showToast({ message: '输入内容超出限制' }) + } else { + this.controller.close(); + this.eventConnect(this.inputValue); + } + }) + } + } + .backgroundColor(Color.White) + .borderRadius(10) + } +} \ No newline at end of file diff --git a/wifi/application/wifi_direct_demo/entry/src/main/ets/MainAbility/pages/index.ets b/wifi/application/wifi_direct_demo/entry/src/main/ets/MainAbility/pages/index.ets new file mode 100644 index 0000000000000000000000000000000000000000..8e8a969cd731e5a7bcbbfa093af0fc07fafbd45b --- /dev/null +++ b/wifi/application/wifi_direct_demo/entry/src/main/ets/MainAbility/pages/index.ets @@ -0,0 +1,464 @@ +/** + * Copyright (c) 2022 Shenzhen Kaihong Digital Industry Development Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import InputComponent from './component/dialog/inputComponent.ets' +import CustomPromptDialog from './component/dialog/customPromptDialog.ets' +import wifiModel from '../model/wifiModeImpl/WifiModel.ets' +import logUtil from '../common/LogUtil.ets' +import storageUtil from '../common/StorageUtil.ets' +import {WifiEntity} from '../model/wifiModeImpl/WifiEntity.ets' +import prompt from '@system.prompt'; + +@Entry +@Component +struct Index { + private dialogEvent: (value: string) => void //输入窗确认按钮回调方法 + private promptEvent: () => void //提示窗确认按钮回调方法 + private isFinding: boolean = true //是否正在扫描 + private connDeviceName: string = '' //提示框标题 + private connContent: string= '' //提示框内容 + private currentGroupInfo: any= {} //当前群组信息 + @State p2pDeviceList: any[] = [] //扫描到的P2P信息列表 + @State deviceName: string = 'OHOS' //本设备名称 + @State isDeviceStatus: boolean = true //设备状态 + @State isCreateDelGroup: boolean = false //创建/删除 群组 状态 + @State btnText: string= '停止' // + + private aboutToAppear() { + logUtil.log('start ----------------- aboutToAppear') + wifiModel.setDeviceName('OHOS') //设置设备名称 + storageUtil.putObjData('deviceName', 'OHOS') //缓存设备名称到本地 + wifiModel.getListener().on("p2pDevicesChange", this.onDevicesChange.bind(this)) + wifiModel.getListener().on("p2pStateChange", this.onP2pStateChange.bind(this)) + wifiModel.getListener().on("p2pConnStateChange", this.onP2pConnStateChange.bind(this)) + wifiModel.getListener().on("p2pPeerDiscoveryStateChange", this.onP2pPeerDiscoveryStateChange.bind(this)) + wifiModel.getListener().on("p2pCurrentDeviceChange", this.onP2pCurrentDeviceChange.bind(this)) + wifiModel.getListener().on("p2pGroupStateChange", this.onP2pGroupStateChange.bind(this)) + wifiModel.discoverDevices() + logUtil.log('end ----------------- aboutToAppear') + } + +/*输入弹出窗*/ + inputController: CustomDialogController = new CustomDialogController({ + builder: InputComponent({ + title: '设备名称', + inputHint: '请输入设备名称', + inputValue: this.deviceName, + inputType: InputType.Normal, + eventConnect: (value: string) => { + this.dialogEvent(value); + } + }), + autoCancel: false + }); +//提示弹窗 + promptDialogController: CustomDialogController = new CustomDialogController({ + builder: CustomPromptDialog({ + title: this.connDeviceName, + contentVal: this.connContent, + eventAction: () => { + this.promptEvent() + } + }), + autoCancel: true + }); + + build() { + Column() { + Text('WLAN直连') + .fontSize(24) + .fontWeight(FontWeight.Bold) + .margin({ + top: 15, + left: 20, + bottom: 15 + }) + Row() { + Text('设备状态').fontSize(20) + Text('').layoutWeight(1) + Toggle({ type: ToggleType.Switch, isOn: this.isDeviceStatus }) + .width(40).height(30) + .selectedColor(Color.Blue) + .onChange(() => { + this.isDeviceStatus = !this.isDeviceStatus; + if (this.isDeviceStatus) { + wifiModel.enableP2p() + } else { + wifiModel.disableP2p() + this.p2pDeviceList = []; + } + }); + } + .backgroundColor(Color.White) + .borderRadius(6) + .padding({ + left: 10, + right: 10, + }) + .margin({ + top: 10, + left: 10, + right: 10 + }) + + Row() { + Text('创建/删除 群组').fontSize(20) + Text('').layoutWeight(1) + Toggle({ type: ToggleType.Switch, isOn: this.isCreateDelGroup }) + .width(40).height(30) + .selectedColor(Color.Blue) + .onChange(() => { + this.isCreateDelGroup = !this.isCreateDelGroup; + if (this.isCreateDelGroup) { + wifiModel.createGroup(); + } else { + wifiModel.removeGroup(); + } + }); + } + .backgroundColor(Color.White) + .borderRadius(6) + .padding({ + left: 10, + right: 10, + }) + .margin({ + top: 10, + left: 10, + right: 10 + }) + + Row() { + Text('Current Group Info').fontSize(20) + Text('').layoutWeight(1) + Image('res/image/ic_right.svg').width(28).height(28).objectFit(ImageFit.Contain) + } + .backgroundColor(Color.White) + .borderRadius(6) + .padding({ + left: 10, + right: 10, + top: 10, + bottom: 10 + }) + .margin({ + top: 10, + bottom: 10, + left: 10, + right: 10 + }) + .onClick(() => { + this.getCurrentGroupInfo() + }) + + Row() { + Text('Delete Persist Group').fontSize(20) + Text('').layoutWeight(1) + Image('res/image/ic_right.svg').width(28).height(28).objectFit(ImageFit.Contain) + } + .backgroundColor(Color.White) + .borderRadius(6) + .padding({ + left: 10, + right: 10, + top: 10, + bottom: 10 + }) + .margin({ + left: 10, + right: 10 + }) + .onClick(() => { + this.deletePersistGroup() + }) + + Text('我的设备') + .fontSize(18) + .fontColor(Color.Gray) + .margin({ + left: 20, + top: 10, + bottom: 10 + }) + Row() { + Text('设备名称').fontSize(20) + Text(this.deviceName) + .fontColor('#999') + .fontSize(18) + .layoutWeight(1) + .maxLines(1) + .textAlign(TextAlign.End) + .margin({ + left: 30, + right: 5 + }) + Image('res/image/ic_right.svg').width(28).height(28).objectFit(ImageFit.Contain) + } + .backgroundColor(Color.White) + .borderRadius(6) + .padding({ + left: 10, + right: 10, + top: 10, + bottom: 10 + }) + .margin({ + left: 10, + right: 10 + }) + .onClick(() => { + this.dialogEvent = (value: string) => { + if (wifiModel.setDeviceName(value)) { + this.deviceName = value + storageUtil.putObjData('deviceName', this.deviceName) + } + } + this.inputController.open() + }) + + Row() { + Text('可用设备') + .backgroundColor('#F7FCFF') + .fontSize(18) + .fontColor(Color.Gray) + .padding({ + top: 5, + bottom: 5 + }) + Text('').layoutWeight(1) + Image($r("app.media.ic_loading")) + .width(24) + .height(24) + .objectFit(ImageFit.Contain) + .visibility(this.isFinding ? Visibility.Visible : Visibility.None) + } + .margin({ + top: 10, + right: 20, + left: 20, + bottom: 10 + }) + + List({ space: 15 }) { + ForEach(this.p2pDeviceList, (item) => { + ListItem() { + CustomItem({ + deviceName: item.deviceName, + macAddress: item.macAddress, + status: item.status + }) + }.onClick(() => { + this.connectP2pDevice(item) + }) + }) + }.layoutWeight(1) + + Button(this.btnText) + .fontSize(20) + .width(200) + .alignSelf(ItemAlign.Center) + .margin({ + top: 20, + bottom: 20 + }) + .onClick(() => { + if (this.isFinding) { + this.btnText = '扫描' + this.isFinding = false; + wifiModel.stopDiscoverDevices() + } else { + this.btnText = '停止' + this.isFinding = true; + wifiModel.discoverDevices() + } + }) + } + .backgroundColor('#F7FCFF') + .width('100%') + .height('100%') + .alignItems(HorizontalAlign.Start) + } + + private connectP2pDevice(item) { + logUtil.log("wifi direct: connectP2pDevice " + item.deviceName + " " + item.status); + if (item.status == 0) { + this.connDeviceName = item.deviceName + wifiModel.getLinkInfo((result) => { + this.connContent = result + }) + this.promptEvent = () => { + } + if (this.connContent != null) { + this.promptDialogController.open(); + } + } else if (item.status == 1) { + this.connDeviceName = '提示' + this.connContent = '确定取消当前连接?' + this.promptEvent = () => { + prompt.showToast({ message: wifiModel.cancelConnect() ? '取消成功' : '取消失败' }) + } + this.promptDialogController.open(); + } else if (item.status == 4) { + prompt.showToast({ message: '当前不可用' }) + } else if (item.status == 3) { + let config = { + 'macAddress': item.macAddress, + 'groupOwnerIntent': 7 + }; + wifiModel.connectP2pDevices(config); + } + } +//获取p2p设备列表 + private onDevicesChange() { + logUtil.log("onDevicesChange"); + this.p2pDeviceList = [] + wifiModel.getP2pDevicesCallBack().then((list) => { + logUtil.log('----------------------------- ' + JSON.stringify(list)) + for (let i = 0;i < JSON.parse(JSON.stringify(list)) + .length; i++) { + if (this.checkDouble(list[i].macAddress)) { + continue + } + this.p2pDeviceList.push(new WifiEntity(i, list[i].ssid, list[i].macAddress, list[i].status)) + } + logUtil.log('this.p2pDeviceList ... ' + JSON.stringify(this.p2pDeviceList)) + }); + } + + private checkDouble(macAddress: string): boolean{ + for (var index = 0; index < this.p2pDeviceList.length; index++) { + const element = this.p2pDeviceList[index]; + if (element.macAddress == macAddress) { + return true + } + } + return false + } + + private onP2pStateChange(code) { + logUtil.log("onP2pStateChange " + code); + if (code === 3) { + logUtil.log("code is 3, call discoverDevices"); + this.isDeviceStatus = true + wifiModel.discoverDevices() + } else { + this.isDeviceStatus = false + wifiModel.stopDiscoverDevices(); + } + } + + private onP2pConnStateChange(code) { + logUtil.log("onP2pConnectedStateChange " + code); + } + + private onP2pPeerDiscoveryStateChange(code) { + logUtil.log("onP2pPeerDiscoveryStateChange " + JSON.stringify(code)); + } + + private onP2pCurrentDeviceChange(code) { + logUtil.log("onP2pCurrentDeviceChange " + JSON.stringify(code)); + } + + private onP2pGroupStateChange(code) { + logUtil.log("onP2pGroupStateChange " + JSON.stringify(code)); + } + + private getCurrentGroupInfo() { + wifiModel.getCurrentGroupInfo((info) => { + logUtil.log("current group info" + info); + this.currentGroupInfo = { + "isP2pGroupOwner": info.isP2pGroupOwner, + "passphrase": info.passphrase, + "interface": info.interface, + "groupName": info.groupName, + "networkId": info.networkId, + "frequency": info.frequency, + "isP2pPersistent": info.isP2pPersistent, + "goIpAddress": info.goIpAddress + } + this.connDeviceName = '群组信息' + this.connContent = JSON.stringify(this.currentGroupInfo) + this.promptEvent = () => { + } + this.promptDialogController.open(); + }); + } + + deletePersistGroup() { + this.connDeviceName = '群组信息' + this.connContent = '确定删除群组?' + this.promptEvent = () => { + logUtil.log("deletePersistGroup" + JSON.stringify(this.currentGroupInfo)); + if (this.currentGroupInfo && this.currentGroupInfo.isP2pPersistent) { + logUtil.log("networkid is " + this.currentGroupInfo.networkId); + prompt.showToast({ + message: wifiModel.deletePersistentGroup(this.currentGroupInfo.networkId) ? '成功' : '失败' + }) + } + } + this.promptDialogController.open(); + } + + private aboutToDisappear() { + wifiModel.stopDiscoverDevices() + } +} + +@Component +struct CustomItem { + private statusStr: string[] = ["已连接", "已邀请", "失败", "可用", "不可用"] + @Prop deviceName: string + @Prop macAddress: string + @Prop status: number + + build() { + Column() { + Row() { + Image('res/image/ic_phone.svg') + .width(48).height(48) + .objectFit(ImageFit.Contain) + .margin({ + top: 10, + bottom: 10, + right: 10 + }) + Column() { + Text(this.deviceName).fontSize(20).maxLines(1).fontWeight(FontWeight.Bold) + Text(this.macAddress).fontSize(18).maxLines(1) + Text(this.statusStr[this.status]).fontSize(16) + } + // .borderWidth(1) + // .borderColor(Color.Red) + .alignItems(HorizontalAlign.Start) + .layoutWeight(1) + + Image('res/image/ic_right.svg').width(28).height(28).objectFit(ImageFit.Contain) + } + .width('100%') + .height(100) + .borderRadius(10) + .alignItems(VerticalAlign.Center) + .backgroundColor('#D2E9FF') + .padding({ + left: 10, + right: 10 + }) + } + .margin({ + right: 20, + left: 20, + }) + } +} \ No newline at end of file diff --git a/wifi/application/wifi_direct_demo/entry/src/main/ets/MainAbility/res/image/ic_phone.svg b/wifi/application/wifi_direct_demo/entry/src/main/ets/MainAbility/res/image/ic_phone.svg new file mode 100644 index 0000000000000000000000000000000000000000..f10f0f3522bea8b04004d5d89f552ad2f03cceb5 --- /dev/null +++ b/wifi/application/wifi_direct_demo/entry/src/main/ets/MainAbility/res/image/ic_phone.svg @@ -0,0 +1,33 @@ + + + + + + + + \ No newline at end of file diff --git a/wifi/application/wifi_direct_demo/entry/src/main/ets/MainAbility/res/image/ic_right.svg b/wifi/application/wifi_direct_demo/entry/src/main/ets/MainAbility/res/image/ic_right.svg new file mode 100644 index 0000000000000000000000000000000000000000..48e297e5e8bbd0d1c0f39285e2829cfcf9e2225b --- /dev/null +++ b/wifi/application/wifi_direct_demo/entry/src/main/ets/MainAbility/res/image/ic_right.svg @@ -0,0 +1,18 @@ + + + + + \ No newline at end of file diff --git a/wifi/application/wifi_direct_demo/entry/src/main/resources/base/element/string.json b/wifi/application/wifi_direct_demo/entry/src/main/resources/base/element/string.json new file mode 100644 index 0000000000000000000000000000000000000000..697d96f11b19cd231efd35bc957c7c97bc8de9cf --- /dev/null +++ b/wifi/application/wifi_direct_demo/entry/src/main/resources/base/element/string.json @@ -0,0 +1,12 @@ +{ + "string": [ + { + "name": "app_name", + "value": "WifiDirectDemo" + }, + { + "name": "description_mainability", + "value": "p2p connect demo" + } + ] +} \ No newline at end of file diff --git a/wifi/application/wifi_direct_demo/entry/src/main/resources/base/media/ic_loading.gif b/wifi/application/wifi_direct_demo/entry/src/main/resources/base/media/ic_loading.gif new file mode 100644 index 0000000000000000000000000000000000000000..5bb90fd6a49107a321c35b9cee4a7b810314b51f Binary files /dev/null and b/wifi/application/wifi_direct_demo/entry/src/main/resources/base/media/ic_loading.gif differ diff --git a/wifi/application/wifi_direct_demo/entry/src/main/resources/base/media/icon.png b/wifi/application/wifi_direct_demo/entry/src/main/resources/base/media/icon.png new file mode 100644 index 0000000000000000000000000000000000000000..ce307a8827bd75456441ceb57d530e4c8d45d36c Binary files /dev/null and b/wifi/application/wifi_direct_demo/entry/src/main/resources/base/media/icon.png differ diff --git a/wifi/application/wifi_direct_demo/figures/img.png b/wifi/application/wifi_direct_demo/figures/img.png new file mode 100644 index 0000000000000000000000000000000000000000..d8407be91477ea5074d213d98bb73c8945790007 Binary files /dev/null and b/wifi/application/wifi_direct_demo/figures/img.png differ diff --git a/wifi/application/wifi_direct_demo/gradle.properties b/wifi/application/wifi_direct_demo/gradle.properties new file mode 100644 index 0000000000000000000000000000000000000000..43a589b3dfb0f49de8009a616775d1dd79c7e318 --- /dev/null +++ b/wifi/application/wifi_direct_demo/gradle.properties @@ -0,0 +1,28 @@ +# +# Copyright (c) 2022 Shenzhen Kaihong Digital Industry Development Co., Ltd. +# 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. +# + +# Project-wide Gradle settings. +# IDE (e.g. DevEco Studio) users: +# Gradle settings configured through the IDE *will override* +# any settings specified in this file. +# For more details on how to configure your build environment visit +# http://www.gradle.org/docs/current/userguide/build_environment.html +# Specifies the JVM arguments used for the daemon process. +# The setting is particularly useful for tweaking memory settings. +# If the Chinese output is garbled, please configure the following parameter. +# This function is enabled by default when the DevEco Studio builds the hap/app,if you need disable gradle parallel,you should set org.gradle.parallel false. +# more information see https://docs.gradle.org/current/userguide/performance.html +# org.gradle.parallel=false +# org.gradle.jvmargs=-Dfile.encoding=GBK \ No newline at end of file diff --git a/wifi/application/wifi_direct_demo/gradlew b/wifi/application/wifi_direct_demo/gradlew new file mode 100644 index 0000000000000000000000000000000000000000..b5d4d9f415ed8bebd9d1f4f816b92af0b3191f62 --- /dev/null +++ b/wifi/application/wifi_direct_demo/gradlew @@ -0,0 +1,182 @@ +#!/usr/bin/env sh + +# +# Copyright (c) 2022 Shenzhen Kaihong Digital Industry Development Co., Ltd. +# 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. +# + +############################################################################## +## +## Gradle start up script for UN*X +## +############################################################################## + +# Attempt to set APP_HOME +# Resolve links: $0 may be a link +PRG="$0" +# Need this for relative symlinks. +while [ -h "$PRG" ]; do + ls=$(ls -ld "$PRG") + link=$(expr "$ls" : '.*-> \(.*\)$') + if expr "$link" : '/.*' >/dev/null; then + PRG="$link" + else + PRG=$(dirname "$PRG")"/$link" + fi +done +SAVED="$(pwd)" +cd "$(dirname \"$PRG\")/" >/dev/null +APP_HOME="$(pwd -P)" +cd "$SAVED" >/dev/null + +APP_NAME="Gradle" +APP_BASE_NAME=$(basename "$0") + +# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' + +# Use the maximum available, or set MAX_FD != -1 to use that value. +MAX_FD="maximum" + +warn() { + echo "$*" +} + +die() { + echo + echo "$*" + echo + exit 1 +} + +# OS specific support (must be 'true' or 'false'). +cygwin=false +msys=false +darwin=false +nonstop=false +case "$(uname)" in +CYGWIN*) + cygwin=true + ;; +Darwin*) + darwin=true + ;; +MINGW*) + msys=true + ;; +NONSTOP*) + nonstop=true + ;; +esac + +CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar + +# Determine the Java command to use to start the JVM. +if [ -n "$JAVA_HOME" ]; then + if [ -x "$JAVA_HOME/jre/sh/java" ]; then + # IBM's JDK on AIX uses strange locations for the executables + JAVACMD="$JAVA_HOME/jre/sh/java" + else + JAVACMD="$JAVA_HOME/bin/java" + fi + if [ ! -x "$JAVACMD" ]; then + die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +else + JAVACMD="java" + which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." +fi + +# Increase the maximum file descriptors if we can. +if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ]; then + MAX_FD_LIMIT=$(ulimit -H -n) + if [ $? -eq 0 ]; then + if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ]; then + MAX_FD="$MAX_FD_LIMIT" + fi + ulimit -n $MAX_FD + if [ $? -ne 0 ]; then + warn "Could not set maximum file descriptor limit: $MAX_FD" + fi + else + warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT" + fi +fi + +# For Darwin, add options to specify how the application appears in the dock +if $darwin; then + GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\"" +fi + +# For Cygwin or MSYS, switch paths to Windows format before running java +if [ "$cygwin" = "true" -o "$msys" = "true" ]; then + APP_HOME=$(cygpath --path --mixed "$APP_HOME") + CLASSPATH=$(cygpath --path --mixed "$CLASSPATH") + JAVACMD=$(cygpath --unix "$JAVACMD") + + # We build the pattern for arguments to be converted via cygpath + ROOTDIRSRAW=$(find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null) + SEP="" + for dir in $ROOTDIRSRAW; do + ROOTDIRS="$ROOTDIRS$SEP$dir" + SEP="|" + done + OURCYGPATTERN="(^($ROOTDIRS))" + # Add a user-defined pattern to the cygpath arguments + if [ "$GRADLE_CYGPATTERN" != "" ]; then + OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)" + fi + # Now convert the arguments - kludge to limit ourselves to /bin/sh + i=0 + for arg in "$@"; do + CHECK=$(echo "$arg" | egrep -c "$OURCYGPATTERN" -) + CHECK2=$(echo "$arg" | egrep -c "^-") ### Determine if an option + + if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ]; then ### Added a condition + eval $(echo args$i)=$(cygpath --path --ignore --mixed "$arg") + else + eval $(echo args$i)="\"$arg\"" + fi + i=$(expr $i + 1) + done + case $i in + 0) set -- ;; + 1) set -- "$args0" ;; + 2) set -- "$args0" "$args1" ;; + 3) set -- "$args0" "$args1" "$args2" ;; + 4) set -- "$args0" "$args1" "$args2" "$args3" ;; + 5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;; + 6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;; + 7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;; + 8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;; + 9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;; + esac +fi + +# Escape application args +save() { + for i; do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/"; done + echo " " +} +APP_ARGS=$(save "$@") + +# Collect all arguments for the java command, following the shell quoting and substitution rules +eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS" + +exec "$JAVACMD" "$@" diff --git a/wifi/application/wifi_direct_demo/gradlew.bat b/wifi/application/wifi_direct_demo/gradlew.bat new file mode 100644 index 0000000000000000000000000000000000000000..62d61e0cb9a75f3a8df4e97006af515532858aa8 --- /dev/null +++ b/wifi/application/wifi_direct_demo/gradlew.bat @@ -0,0 +1,102 @@ +@rem +@rem Copyright (c) 2022 Shenzhen Kaihong Digital Industry Development Co., Ltd. +@rem Licensed under the Apache License, Version 2.0 (the "License"); +@rem you may not use this file except in compliance with the License. +@rem You may obtain a copy of the License at +@rem +@rem http://www.apache.org/licenses/LICENSE-2.0 +@rem +@rem Unless required by applicable law or agreed to in writing, software +@rem distributed under the License is distributed on an "AS IS" BASIS, +@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +@rem See the License for the specific language governing permissions and +@rem limitations under the License. +@rem + +@if "%DEBUG%" == "" @echo off +@rem ########################################################################## +@rem +@rem Gradle startup script for Windows +@rem +@rem ########################################################################## + +@rem Set local scope for the variables with windows NT shell +if "%OS%"=="Windows_NT" setlocal + +set DIRNAME=%~dp0 +if "%DIRNAME%" == "" set DIRNAME=. +set APP_BASE_NAME=%~n0 +set APP_HOME=%DIRNAME% + +@rem Resolve any "." and ".." in APP_HOME to make it shorter. +for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi + +@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" + +@rem Find java.exe +if defined JAVA_HOME goto findJavaFromJavaHome + +set JAVA_EXE=java.exe +%JAVA_EXE% -version >NUL 2>&1 +if "%ERRORLEVEL%" == "0" goto init + +echo. +echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +:findJavaFromJavaHome +set JAVA_HOME=%JAVA_HOME:"=% +set JAVA_EXE=%JAVA_HOME%/bin/java.exe + +if exist "%JAVA_EXE%" goto init + +echo. +echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +:init +@rem Get command-line arguments, handling Windows variants + +if not "%OS%" == "Windows_NT" goto win9xME_args + +:win9xME_args +@rem Slurp the command line arguments. +set CMD_LINE_ARGS= +set _SKIP=2 + +:win9xME_args_slurp +if "x%~1" == "x" goto execute + +set CMD_LINE_ARGS=%* + +:execute +@rem Setup the command line + +set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar + +@rem Execute Gradle +"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS% + +:end +@rem End local scope for the variables with windows NT shell +if "%ERRORLEVEL%"=="0" goto mainEnd + +:fail +rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of +rem the _cmd.exe /c_ return code! +if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 +exit /b 1 + +:mainEnd +if "%OS%"=="Windows_NT" endlocal + +:omega diff --git a/wifi/application/wifi_direct_demo/package.json b/wifi/application/wifi_direct_demo/package.json new file mode 100644 index 0000000000000000000000000000000000000000..0967ef424bce6791893e9a57bb952f80fd536e93 --- /dev/null +++ b/wifi/application/wifi_direct_demo/package.json @@ -0,0 +1 @@ +{} diff --git a/wifi/application/wifi_direct_demo/settings.gradle b/wifi/application/wifi_direct_demo/settings.gradle new file mode 100644 index 0000000000000000000000000000000000000000..4773db73233a570c2d0c01a22e75321acfbf7a07 --- /dev/null +++ b/wifi/application/wifi_direct_demo/settings.gradle @@ -0,0 +1 @@ +include ':entry' diff --git a/wifi/bundle.json b/wifi/bundle.json new file mode 100644 index 0000000000000000000000000000000000000000..e8df36716f1ce48c1c6ce7ef32931dcfbe8e9cd9 --- /dev/null +++ b/wifi/bundle.json @@ -0,0 +1,135 @@ +{ + "name": "@ohos/communication_wifi", + "version": "3.1.0", + "description": "The WLAN module provides basic WLAN functions, peer-to-peer (P2P) connection, and WLAN notification, enabling your application to communicate with other devices through a WLAN.", + "homePage": "https://gitee.com/openharmony", + "license": "Apache License 2.0", + "repository": "https://gitee.com/openharmony/communication_wifi", + "domain": "os", + "language": "", + "publishAs": "code-segment", + "private": false, + "scripts": {}, + "tags": [ + "foundation" + ], + "keywords": [ + "communication", + "wifi" + ], + "envs": [], + "dirs": [], + "author": { + "name": "", + "email": "", + "url": "" + }, + "contributors": [ + { + "name": "", + "email": "", + "url": "" + } + ], + "segment": { + "destPath": "foundation/communication/wifi/wifi" + }, + "component": { + "name": "wifi", + "subsystem": "communication", + "syscap": [ + "SystemCapability.Communication.WiFi.STA", + "SystemCapability.Communication.WiFi.AP.Core", + "SystemCapability.Communication.WiFi.P2P", + "SystemCapability.Communication.WiFi.Core", + "SystemCapability.Communication.WiFi.AP.Extension = false" + ], + "features": [ + "wifi_feature_with_p2p", + "wifi_feature_with_ap_intf", + "wifi_feature_with_ap_num", + "wifi_feature_with_auth_disable", + "wifi_feature_with_dhcp_disable", + "wifi_feature_with_encryption", + "wifi_feature_is_hdi_supported" + ], + "adapted_system_type": [ + "standard" + ], + "rom": "", + "ram": "", + "deps": { + "components": [ + "ipc", + "ces_standard", + "hiviewdfx_hilog_native", + "hisysevent_native", + "netmanager_base" + ], + "third_party": [ + "wpa_supplicant", + "node", + "bounds_checking_function", + "googletest", + "openssl" + ] + }, + "build": { + "group_type": { + "base_group": [ + "//foundation/communication/wifi/wifi/utils:wifi_utils" + ], + "fwk_group": [ + "//foundation/communication/wifi/wifi/frameworks:wifi_kits" + ], + "service_group": [ + "//foundation/communication/wifi/wifi/services/wifi_standard/wifi_framework:wifi_manage", + "//foundation/communication/wifi/wifi/services/wifi_standard/wifi_framework:wifi_system_ability", + "//foundation/communication/wifi/wifi/services/wifi_standard/wifi_hal:wifi_hal" + ] + }, + "inner_kits": [ + { + "header" : { + "header_base": "//foundation/communication/wifi/wifi/interfaces/kits/c", + "header_files": [ + "wifi_device.h", + "wifi_hotspot.h", + "wifi_p2p.h", + "wifi_hid2d.h" + ] + }, + "name" : "//foundation/communication/wifi/wifi/frameworks/native:wifi_sdk" + }, + { + "header" : { + "header_base": "//foundation/communication/wifi/wifi/frameworks/native/include", + "header_files": [ + "wifi_device.h", + "wifi_hotspot.h", + "wifi_p2p.h", + "wifi_scan.h", + "wifi_hid2d.h" + ] + }, + "name" : "//foundation/communication/wifi/wifi/frameworks/native:wifi_sdk" + } + ], + "test": [ + "//foundation/communication/wifi/wifi/test/fuzztest/wifi_sta:fuzztest", + "//foundation/communication/wifi/wifi/test/wifi_standard/wifi_framework/wifi_manage/wifi_scan:unittest", + "//foundation/communication/wifi/wifi/test/wifi_standard/wifi_framework/wifi_manage/wifi_sta:unittest", + "//foundation/communication/wifi/wifi/test/wifi_standard/wifi_framework/wifi_manage/wifi_ap:unittest", + "//foundation/communication/wifi/wifi/test/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/test:unittest", + "//foundation/communication/wifi/wifi/test/wifi_standard/ipc_framework/cRPC/unittest:unittest", + "//foundation/communication/wifi/wifi/test/wifi_standard/wifi_framework/wifi_toolkit/unittest:unittest", + "//foundation/communication/wifi/wifi/test/wifi_standard/wifi_framework/wifi_manage/unittest:unittest", + "//foundation/communication/wifi/wifi/test/wifi_standard/wifi_framework/wifi_manage/idl_client/unittest:unittest", + "//foundation/communication/wifi/wifi/test/wifi_standard/wifi_hal/unittest:unittest" + ] + }, + "hisysevent_config": [ + "//foundation/communication/wifi/wifi/hisysevent.yaml" + ] + } +} diff --git a/wifi/frameworks/BUILD.gn b/wifi/frameworks/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..79ec889360cef1c3923ce8e1ed3abc9d31742f44 --- /dev/null +++ b/wifi/frameworks/BUILD.gn @@ -0,0 +1,32 @@ +# Copyright (C) 2022 Huawei Device Co., Ltd. +# 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. + +if (defined(ohos_lite)) { + import("//build/lite/config/component/lite_component.gni") + import("//foundation/communication/wifi/wifi/wifi_lite.gni") +} else { + import("//build/ohos.gni") + import("//foundation/communication/wifi/wifi/wifi.gni") +} + +group("wifi_kits") { + deps = [ "$WIFI_ROOT_DIR/frameworks/native:wifi_sdk" ] + if (!defined(ohos_lite)) { + deps += [ + "$WIFI_ROOT_DIR/frameworks/js/napi:wifi", + "$WIFI_ROOT_DIR/frameworks/js/napi:wifi_manager", + "$WIFI_ROOT_DIR/frameworks/js/napi:wifi_native_js", + "$WIFI_ROOT_DIR/frameworks/js/napi:wifiext", + ] + } +} diff --git a/wifi/frameworks/js/napi/BUILD.gn b/wifi/frameworks/js/napi/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..aee0e73a9a56a7d9af6ec98065b706bd56dea929 --- /dev/null +++ b/wifi/frameworks/js/napi/BUILD.gn @@ -0,0 +1,187 @@ +# Copyright (C) 2021-2022 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import("//build/ohos.gni") +import("//foundation/communication/wifi/wifi/wifi.gni") + +ohos_shared_library("wifi") { + install_enable = true + include_dirs = [ + "//third_party/node/src", + "//native_engine", + "//commonlibrary/c_utils/base/include", + "$WIFI_ROOT_DIR/services/wifi_standard/wifi_framework/wifi_toolkit/log", + "$WIFI_ROOT_DIR/frameworks/native/interfaces", + "//base/hiviewdfx/hilog/interfaces/native/innerkits/include", + "//base/security/access_token/interfaces/innerkits/accesstoken/include", + "$WIFI_ROOT_DIR/frameworks/native/include", + "$WIFI_ROOT_DIR/services/wifi_standard/wifi_framework/wifi_toolkit/net_helper", + "${ability_runtime_path}/interfaces/kits/native/appkit/ability_runtime/context", + "$WIFI_ROOT_DIR/utils/inc", + "$WIFI_ROOT_DIR/frameworks/js/napi/inc", + ] + + sources = [ + "src/wifi_napi_device.cpp", + "src/wifi_napi_entry.cpp", + "src/wifi_napi_errcode.cpp", + "src/wifi_napi_event.cpp", + "src/wifi_napi_hotspot.cpp", + "src/wifi_napi_p2p.cpp", + "src/wifi_napi_utils.cpp", + ] + deps = [ + "$WIFI_ROOT_DIR/frameworks/native:wifi_sdk", + "${ability_runtime_path}/frameworks/native/appkit:app_context", + "//base/hiviewdfx/hilog/interfaces/native/innerkits:libhilog", + "//foundation/arkui/napi:ace_napi", + ] + + external_deps = [ + "access_token:libaccesstoken_sdk", + "bundle_framework:appexecfwk_base", + "c_utils:utils", + "ipc:ipc_core", + ] + + relative_install_dir = "module" + part_name = "wifi" + subsystem_name = "communication" +} + +ohos_shared_library("wifiext") { + install_enable = true + include_dirs = [ + "//third_party/node/src", + "//native_engine", + "//commonlibrary/c_utils/base/include", + "$WIFI_ROOT_DIR/services/wifi_standard/wifi_framework/wifi_toolkit/log", + "//base/hiviewdfx/hilog/interfaces/native/innerkits/include", + "$WIFI_ROOT_DIR/frameworks/native/include", + "$WIFI_ROOT_DIR/frameworks/native/interfaces", + "$WIFI_ROOT_DIR/frameworks/js/napi/inc", + "${ability_runtime_path}/interfaces/kits/native/appkit/ability_runtime/context", + ] + + sources = [ + "src/wifi_ext_napi_entry.cpp", + "src/wifi_ext_napi_hotspot.cpp", + "src/wifi_napi_errcode.cpp", + "src/wifi_napi_utils.cpp", + ] + deps = [ + "$WIFI_ROOT_DIR/frameworks/native:wifi_sdk", + "${ability_runtime_path}/frameworks/native/appkit:app_context", + "//base/hiviewdfx/hilog/interfaces/native/innerkits:libhilog", + "//foundation/arkui/napi:ace_napi", + ] + + external_deps = [ + "bundle_framework:appexecfwk_base", + "c_utils:utils", + ] + + relative_install_dir = "module" + part_name = "wifi" + subsystem_name = "communication" +} + +ohos_shared_library("wifi_native_js") { + install_enable = true + include_dirs = [ + "//third_party/node/src", + "//native_engine", + "//commonlibrary/c_utils/base/include", + "$WIFI_ROOT_DIR/services/wifi_standard/wifi_framework/wifi_toolkit/log", + "$WIFI_ROOT_DIR/frameworks/js/napi/inc", + "$WIFI_ROOT_DIR/frameworks/native/include", + "$WIFI_ROOT_DIR/frameworks/native/interfaces", + "//base/hiviewdfx/hilog/interfaces/native/innerkits/include", + "//base/security/access_token/interfaces/innerkits/accesstoken/include", + "$WIFI_ROOT_DIR/services/wifi_standard/wifi_framework/wifi_toolkit/net_helper", + "${ability_runtime_path}/interfaces/kits/native/appkit/ability_runtime/context", + "$WIFI_ROOT_DIR/utils/inc", + ] + + sources = [ + "src/wifi_napi_device.cpp", + "src/wifi_napi_entry.cpp", + "src/wifi_napi_errcode.cpp", + "src/wifi_napi_event.cpp", + "src/wifi_napi_hotspot.cpp", + "src/wifi_napi_p2p.cpp", + "src/wifi_napi_utils.cpp", + ] + deps = [ + "$WIFI_ROOT_DIR/frameworks/native:wifi_sdk", + "${ability_runtime_path}/frameworks/native/appkit:app_context", + "//base/hiviewdfx/hilog/interfaces/native/innerkits:libhilog", + "//foundation/arkui/napi:ace_napi", + ] + + defines = [ "ENABLE_NAPI_COMPATIBLE" ] + + external_deps = [ + "access_token:libaccesstoken_sdk", + "bundle_framework:appexecfwk_base", + "c_utils:utils", + "ipc:ipc_core", + ] + + relative_install_dir = "module" + part_name = "wifi" + subsystem_name = "communication" +} + +ohos_shared_library("wifi_manager") { + install_enable = true + include_dirs = [ + "//third_party/node/src", + "//native_engine", + "//commonlibrary/c_utils/base/include", + "$WIFI_ROOT_DIR/services/wifi_standard/wifi_framework/wifi_toolkit/log", + "$WIFI_ROOT_DIR/frameworks/native/interfaces", + "//base/hiviewdfx/hilog/interfaces/native/innerkits/include", + "//base/security/access_token/interfaces/innerkits/accesstoken/include", + "$WIFI_ROOT_DIR/frameworks/native/include", + "$WIFI_ROOT_DIR/services/wifi_standard/wifi_framework/wifi_toolkit/net_helper", + "${ability_runtime_path}/interfaces/kits/native/appkit/ability_runtime/context", + "$WIFI_ROOT_DIR/utils/inc", + "$WIFI_ROOT_DIR/frameworks/js/napi/inc", + ] + sources = [ + "src/wifi_napi_device.cpp", + "src/wifi_napi_entry.cpp", + "src/wifi_napi_errcode.cpp", + "src/wifi_napi_event.cpp", + "src/wifi_napi_hotspot.cpp", + "src/wifi_napi_p2p.cpp", + "src/wifi_napi_utils.cpp", + ] + deps = [ + "$WIFI_ROOT_DIR/frameworks/native:wifi_sdk", + "${ability_runtime_path}/frameworks/native/appkit:app_context", + "//base/hiviewdfx/hilog/interfaces/native/innerkits:libhilog", + "//foundation/arkui/napi:ace_napi", + ] + defines = [ "ENABLE_NAPI_WIFI_MANAGER" ] + external_deps = [ + "access_token:libaccesstoken_sdk", + "bundle_framework:appexecfwk_base", + "c_utils:utils", + "ipc:ipc_core", + ] + relative_install_dir = "module" + part_name = "wifi" + subsystem_name = "communication" +} diff --git a/interfaces/innerkits/native_cpp/napi/wifi_napi_device.h b/wifi/frameworks/js/napi/inc/wifi_ext_napi_hotspot.h old mode 100755 new mode 100644 similarity index 36% rename from interfaces/innerkits/native_cpp/napi/wifi_napi_device.h rename to wifi/frameworks/js/napi/inc/wifi_ext_napi_hotspot.h index a562b7bc3ec2b2d09ac3e4f7fa8d351c91bcb570..cf76a2a7e385ce38fd99bfe533320070deb6c6c0 --- a/interfaces/innerkits/native_cpp/napi/wifi_napi_device.h +++ b/wifi/frameworks/js/napi/inc/wifi_ext_napi_hotspot.h @@ -1,44 +1,55 @@ -/* - * Copyright (C) 2021 Huawei Device Co., Ltd. - * 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 WIFI_NAPI_DEVICE_H_ -#define WIFI_NAPI_DEVICE_H_ - -#include "wifi_napi_utils.h" - -namespace OHOS { -namespace Wifi { -napi_value EnableWifi(napi_env env, napi_callback_info info); -napi_value DisableWifi(napi_env env, napi_callback_info info); -napi_value IsWifiActive(napi_env env, napi_callback_info info); -napi_value Scan(napi_env env, napi_callback_info info); -napi_value GetScanInfos(napi_env env, napi_callback_info info); -napi_value AddDeviceConfig(napi_env env, napi_callback_info info); -napi_value ConnectToNetwork(napi_env env, napi_callback_info info); -napi_value ConnectToDevice(napi_env env, napi_callback_info info); -napi_value Disconnect(napi_env env, napi_callback_info info); -napi_value GetSignalLevel(napi_env env, napi_callback_info info); - -enum class SecTypeJs { - SEC_TYPE_INVALID = 0, /* Invalid security type */ - SEC_TYPE_OPEN = 1, /* Open */ - SEC_TYPE_WEP = 2, /* Wired Equivalent Privacy (WEP) */ - SEC_TYPE_PSK = 3, /* Pre-shared key (PSK) */ - SEC_TYPE_SAE = 4, /* Simultaneous Authentication of Equals (SAE) */ -}; -} // namespace Wifi -} // namespace OHOS - -#endif +/* + * Copyright (C) 2022 Huawei Device Co., Ltd. + * 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 WIFI_EXT_NAPI_HOTSPOT_H_ +#define WIFI_EXT_NAPI_HOTSPOT_H_ + +#include +#include "wifi_napi_utils.h" +#include "wifi_hotspot.h" + +namespace OHOS { +namespace Wifi { +napi_value EnableHotspot(napi_env env, napi_callback_info info); +napi_value DisableHotspot(napi_env env, napi_callback_info info); +napi_value GetSupportedPowerModel(napi_env env, napi_callback_info info); +napi_value GetPowerModel(napi_env env, napi_callback_info info); +napi_value SetPowerModel(napi_env env, napi_callback_info info); + +class PowerModelAsyncContext : public AsyncContext { +public: + PowerModel powerModel; + + PowerModelAsyncContext(napi_env env, napi_async_work work = nullptr, napi_deferred deferred = nullptr) + : AsyncContext(env, work, deferred), powerModel(PowerModel::GENERAL) {} + + PowerModelAsyncContext() = delete; + ~PowerModelAsyncContext() override {} +}; + +class PowerModelListAsyncContext : public AsyncContext { +public: + std::set setPowerModelList; + + PowerModelListAsyncContext(napi_env env, napi_async_work work = nullptr, napi_deferred deferred = nullptr) + : AsyncContext(env, work, deferred) {} + + PowerModelListAsyncContext() = delete; + ~PowerModelListAsyncContext() override {} +}; +} // namespace Wifi +} // namespace OHOS + +#endif diff --git a/wifi/frameworks/js/napi/inc/wifi_napi_device.h b/wifi/frameworks/js/napi/inc/wifi_napi_device.h new file mode 100644 index 0000000000000000000000000000000000000000..7fa04fd915408de4988a935bd0d32c88c0fe57c9 --- /dev/null +++ b/wifi/frameworks/js/napi/inc/wifi_napi_device.h @@ -0,0 +1,121 @@ +/* + * Copyright (C) 2021 Huawei Device Co., Ltd. + * 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 WIFI_NAPI_DEVICE_H_ +#define WIFI_NAPI_DEVICE_H_ + +#include "wifi_napi_utils.h" +#include "wifi_device.h" +#include "wifi_scan.h" + +namespace OHOS { +namespace Wifi { +napi_value EnableWifi(napi_env env, napi_callback_info info); +napi_value DisableWifi(napi_env env, napi_callback_info info); +napi_value IsWifiActive(napi_env env, napi_callback_info info); +napi_value Scan(napi_env env, napi_callback_info info); +napi_value GetScanInfos(napi_env env, napi_callback_info info); +napi_value GetScanResults(napi_env env, napi_callback_info info); +napi_value AddDeviceConfig(napi_env env, napi_callback_info info); +napi_value AddUntrustedConfig(napi_env env, napi_callback_info info); +napi_value RemoveUntrustedConfig(napi_env env, napi_callback_info info); +napi_value AddCandidateConfig(napi_env env, napi_callback_info info); +napi_value RemoveCandidateConfig(napi_env env, napi_callback_info info); +napi_value ConnectToCandidateConfig(napi_env env, napi_callback_info info); +napi_value GetCandidateConfigs(napi_env env, napi_callback_info info); +napi_value ConnectToNetwork(napi_env env, napi_callback_info info); +napi_value ConnectToDevice(napi_env env, napi_callback_info info); +napi_value IsConnected(napi_env env, napi_callback_info info); +napi_value Disconnect(napi_env env, napi_callback_info info); +napi_value GetSignalLevel(napi_env env, napi_callback_info info); +napi_value ReConnect(napi_env env, napi_callback_info info); +napi_value ReAssociate(napi_env env, napi_callback_info info); +napi_value GetIpInfo(napi_env env, napi_callback_info info); +napi_value GetLinkedInfo(napi_env env, napi_callback_info info); +napi_value RemoveDevice(napi_env env, napi_callback_info info); +napi_value RemoveAllNetwork(napi_env env, napi_callback_info info); +napi_value DisableNetwork(napi_env env, napi_callback_info info); +napi_value GetCountryCode(napi_env env, napi_callback_info info); +napi_value GetDeviceConfigs(napi_env env, napi_callback_info info); +napi_value UpdateNetwork(napi_env env, napi_callback_info info); +napi_value GetSupportedFeatures(napi_env env, napi_callback_info info); +napi_value IsFeatureSupported(napi_env env, napi_callback_info info); +napi_value GetDeviceMacAddress(napi_env env, napi_callback_info info); + +enum class ConnStateJs { + SCANNING, /* The device is searching for an available AP */ + CONNECTING, /* The Wi-Fi connection is being set up */ + AUTHENTICATING, /* The Wi-Fi connection is being authenticated */ + OBTAINING_IPADDR, /* The IP address of the Wi-Fi connection is being obtained */ + CONNECTED, /* The Wi-Fi connection has been set up */ + DISCONNECTING, /* The Wi-Fi connection is being torn down */ + DISCONNECTED, /* The Wi-Fi connection has been torn down */ + UNKNOWN /* Failed to set up the Wi-Fi connection */ +}; + +enum class IpTypeJs { + /** Use statically configured IP settings */ + IP_TYPE_STATIC, + /** Use dynamically configured IP settings */ + IP_TYPE_DHCP, + /** No IP details are assigned */ + IP_TYPE_UNKNOWN, +}; + +class ScanInfoAsyncContext : public AsyncContext { +public: + std::vector vecScanInfos; + + ScanInfoAsyncContext(napi_env env, napi_async_work work = nullptr, napi_deferred deferred = nullptr) : + AsyncContext(env, work, deferred){} + + ScanInfoAsyncContext() = delete; + + virtual ~ScanInfoAsyncContext(){} +}; + +class DeviceConfigContext : public AsyncContext { +public: + WifiDeviceConfig *config; + int networkId; + bool isCandidate; + + DeviceConfigContext(napi_env env, napi_async_work work = nullptr, napi_deferred deferred = nullptr) : + AsyncContext(env, work, deferred) { + config = nullptr; + networkId = -1; + isCandidate = false; + } + + DeviceConfigContext() = delete; + + virtual ~DeviceConfigContext() {} +}; + +class LinkedInfoAsyncContext : public AsyncContext { +public: + WifiLinkedInfo linkedInfo; + + LinkedInfoAsyncContext(napi_env env, napi_async_work work = nullptr, napi_deferred deferred = nullptr) : + AsyncContext(env, work, deferred){} + + LinkedInfoAsyncContext() = delete; + + virtual ~LinkedInfoAsyncContext(){} +}; +} // namespace Wifi +} // namespace OHOS + +#endif diff --git a/wifi/frameworks/js/napi/inc/wifi_napi_errcode.h b/wifi/frameworks/js/napi/inc/wifi_napi_errcode.h new file mode 100644 index 0000000000000000000000000000000000000000..121e3e6c971ada976369290aea621fdd9e8bdb00 --- /dev/null +++ b/wifi/frameworks/js/napi/inc/wifi_napi_errcode.h @@ -0,0 +1,118 @@ +/* + * Copyright (C) 2022 Huawei Device Co., Ltd. + * 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 WIFI_NAPI_ERRCODE_H_ +#define WIFI_NAPI_ERRCODE_H_ + +#include "wifi_napi_utils.h" +#include +#include "wifi_napi_errcode.h" + +namespace OHOS { +namespace Wifi { +static const std::string BUSINESS_ERROR_PROPERTY_CODE = "code"; +static const std::string BUSINESS_ERROR_PROPERTY_MESSAGE = "message"; +static const std::string BUSINESS_ERROR_PROPERTY_DATA = "data"; + +enum WifiNapiErrCode { + WIFI_ERRCODE_SUCCESS = 0, /* successfully */ + WIFI_ERRCODE_PERMISSION_DENIED = 201, /* permission denied */ + WIFI_ERRCODE_INVALID_PARAM = 401, /* invalid params */ + WIFI_ERRCODE_NOT_SUPPORTED = 801, /* not supported */ + WIFI_ERRCODE_OPERATION_FAILED = 1000, /* failed */ + WIFI_ERRCODE_WIFI_NOT_OPENED = 1001, /* sta service not opened */ + WIFI_ERRCODE_OPEN_FAIL_WHEN_CLOSING = 1003, /* forbid when current airplane opened */ + WIFI_ERRCODE_CLOSE_FAIL_WHEN_OPENING = 1004, /* forbid when current powersaving opened */ +}; + +#ifdef ENABLE_NAPI_WIFI_MANAGER +#ifndef WIFI_NAPI_ASSERT +#define WIFI_NAPI_ASSERT(env, cond, errCode, sysCap) \ +do { \ + if (!(cond)) { \ + napi_value res = nullptr; \ + HandleSyncErrCode(env, errCode, sysCap); \ + napi_get_undefined(env, &res); \ + return res; \ + } \ +} while (0) +#endif + +#ifndef WIFI_NAPI_RETURN +#define WIFI_NAPI_RETURN(env, cond, errCode, sysCap) \ +do { \ + napi_value res = nullptr; \ + if (!(cond)) { \ + HandleSyncErrCode(env, errCode, sysCap); \ + } \ + napi_get_undefined(env, &res); \ + return res; \ +} while (0) +#endif + +#else /* #else ENABLE_NAPI_WIFI_MANAGER */ + +#ifndef WIFI_NAPI_ASSERT +#define WIFI_NAPI_ASSERT(env, cond, errCode, sysCap) \ +do { \ + if (!(cond)) { \ + napi_value res = nullptr; \ + napi_get_boolean(env, cond, &res); \ + return res; \ + } \ +} while (0) +#endif + +#ifndef WIFI_NAPI_RETURN +#define WIFI_NAPI_RETURN(env, cond, errCode, sysCap) \ +do { \ + napi_value res = nullptr; \ + napi_get_boolean(env, cond, &res); \ + return res; \ +} while (0) +#endif +#endif /* #endif ENABLE_NAPI_WIFI_MANAGER */ + +/** + * @brief Thow error code for async-callback function. + * + * @param env The env. + * @param info The input data. + */ +void HandleCallbackErrCode( const napi_env &env, const AsyncContext &info); + +/** + * @brief Thow error code for async-promise function. + * + * @param env The env. + * @param info The input data. + */ +void HandlePromiseErrCode(const napi_env &env, const AsyncContext &info); + + +#ifdef ENABLE_NAPI_WIFI_MANAGER +/** + * @brief Thow error code for async function. + * + * @param env The env. + * @param errCode The error code. + * @param sysCap System capability code. + */ +void HandleSyncErrCode(const napi_env &env, int32_t errCode, int32_t sysCap); +#endif +} // namespace Wifi +} // namespace OHOS +#endif + diff --git a/wifi/frameworks/js/napi/inc/wifi_napi_event.h b/wifi/frameworks/js/napi/inc/wifi_napi_event.h new file mode 100644 index 0000000000000000000000000000000000000000..9597e07ea743910e0ff42a61b0f66523bf33b5f5 --- /dev/null +++ b/wifi/frameworks/js/napi/inc/wifi_napi_event.h @@ -0,0 +1,134 @@ +/* + * Copyright (C) 2021-2022 Huawei Device Co., Ltd. + * 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 WIFI_NAPI_EVENT_H_ +#define WIFI_NAPI_EVENT_H_ + +#include +#include +#include +#include "napi/native_api.h" +#include "wifi_errcode.h" +#include +#include "wifi_p2p.h" +#include "wifi_hotspot.h" + +namespace OHOS { +namespace Wifi { +class RegObj { +public: + RegObj() : m_regEnv(0), m_regHanderRef(nullptr) { + } + explicit RegObj(const napi_env& env, const napi_ref& ref) { + m_regEnv = env; + m_regHanderRef = ref; + } + + ~RegObj() { + } + + bool operator == (const RegObj& other) const { + return m_regEnv == other.m_regEnv && m_regHanderRef == other.m_regHanderRef; + } + + bool operator != (const RegObj& other) const { + return !(*this == other); + } + + bool operator < (const RegObj& other) const { + return m_regEnv < other.m_regEnv || (m_regEnv == other.m_regEnv && m_regHanderRef < other.m_regHanderRef); + } + + napi_env m_regEnv; + napi_ref m_regHanderRef; +}; + +class AsyncEventData { +public: + napi_env env; + napi_ref callbackRef; + std::function packResult; + + explicit AsyncEventData(napi_env e, napi_ref r, std::function p) { + env = e; + callbackRef = r; + packResult = p; + } + + AsyncEventData() = delete; + + virtual ~AsyncEventData() { + } +}; + +static std::shared_mutex g_regInfoMutex; +static std::map> g_eventRegisterInfo; + +class NapiEvent { +public: + napi_value CreateResult(const napi_env& env, int value); + napi_value CreateResult(const napi_env& env, const StationInfo& info); + napi_value CreateResult(const napi_env& env, napi_value placehoders); + napi_value CreateResult(const napi_env& env, const WifiP2pDevice& device); + napi_value CreateResult(const napi_env& env, const std::vector& devices); + napi_value CreateResult(const napi_env& env, const WifiP2pLinkedInfo& info); + void EventNotify(AsyncEventData *asyncEvent); + + template + void CheckAndNotify(const std::string& type, const T& obj) { + std::shared_lock guard(g_regInfoMutex); + auto it = g_eventRegisterInfo.find(type); + if (it == g_eventRegisterInfo.end()) { + return; + } + for (auto& each : it->second) { + auto func = [this, env = each.m_regEnv, obj] () -> napi_value { return CreateResult(env, obj); }; + AsyncEventData *asyncEvent = new (std::nothrow)AsyncEventData(each.m_regEnv, each.m_regHanderRef, func); + if (asyncEvent == nullptr) { + return; + } + EventNotify(asyncEvent); + } + } +}; + +class EventRegister { +public: + EventRegister() { + } + ~EventRegister() { + } + + static EventRegister& GetInstance(); + + void Register(const napi_env& env, const std::string& type, napi_value handler); + void Unregister(const napi_env& env, const std::string& type, napi_value handler); + +private: + ErrCode RegisterWifiEvents(); + bool IsEventSupport(const std::string& type); + int CheckPermission(const std::string& eventType); + void DeleteRegisterObj(const napi_env& env, std::vector& vecRegObjs, napi_value& handler); + void DeleteAllRegisterObj(const napi_env& env, std::vector& vecRegObjs); + + static bool isEventRegistered; +}; + +napi_value On(napi_env env, napi_callback_info cbinfo); +napi_value Off(napi_env env, napi_callback_info cbinfo); +} // namespace Wifi +} // namespace OHOS + +#endif diff --git a/wifi/frameworks/js/napi/inc/wifi_napi_hotspot.h b/wifi/frameworks/js/napi/inc/wifi_napi_hotspot.h new file mode 100644 index 0000000000000000000000000000000000000000..a04ed5cf19a931793f9cf043fd6182dd214bd3d7 --- /dev/null +++ b/wifi/frameworks/js/napi/inc/wifi_napi_hotspot.h @@ -0,0 +1,35 @@ +/* + * Copyright (C) 2021 Huawei Device Co., Ltd. + * 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 WIFI_NAPI_HOTSPOT_H_ +#define WIFI_NAPI_HOTSPOT_H_ + +#include "wifi_napi_utils.h" + +namespace OHOS { +namespace Wifi { +napi_value EnableHotspot(napi_env env, napi_callback_info info); +napi_value DisableHotspot(napi_env env, napi_callback_info info); +napi_value IsHotspotActive(napi_env env, napi_callback_info info); +napi_value IsHotspotDualBandSupported(napi_env env, napi_callback_info info); +napi_value SetHotspotConfig(napi_env env, napi_callback_info info); +napi_value GetHotspotConfig(napi_env env, napi_callback_info info); +napi_value GetStations(napi_env env, napi_callback_info info); +napi_value AddBlockList(napi_env env, napi_callback_info info); +napi_value DelBlockList(napi_env env, napi_callback_info info); +} // namespace Wifi +} // namespace OHOS + +#endif diff --git a/wifi/frameworks/js/napi/inc/wifi_napi_p2p.h b/wifi/frameworks/js/napi/inc/wifi_napi_p2p.h new file mode 100644 index 0000000000000000000000000000000000000000..d6ec710b86dae7fc64e1d78310ee54304848d008 --- /dev/null +++ b/wifi/frameworks/js/napi/inc/wifi_napi_p2p.h @@ -0,0 +1,101 @@ +/* + * Copyright (C) 2021-2022 Huawei Device Co., Ltd. + * 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 WIFI_NAPI_P2P_H_ +#define WIFI_NAPI_P2P_H_ + +#include "wifi_napi_utils.h" +#include "wifi_p2p.h" + +namespace OHOS { +namespace Wifi { +napi_value GetP2pLinkedInfo(napi_env env, napi_callback_info info); +napi_value GetCurrentGroup(napi_env env, napi_callback_info info); +napi_value GetP2pDevices(napi_env env, napi_callback_info info); +napi_value GetP2pLocalDevice(napi_env env, napi_callback_info info); +napi_value GetP2pGroups(napi_env env, napi_callback_info info); +napi_value CreateGroup(napi_env env, napi_callback_info info); +napi_value RemoveGroup(napi_env env, napi_callback_info info); +napi_value P2pConnect(napi_env env, napi_callback_info info); +napi_value P2pCancelConnect(napi_env env, napi_callback_info info); +napi_value StartDiscoverDevices(napi_env env, napi_callback_info info); +napi_value StopDiscoverDevices(napi_env env, napi_callback_info info); +napi_value DeletePersistentGroup(napi_env env, napi_callback_info info); +napi_value SetDeviceName(napi_env env, napi_callback_info info); + +class P2pLocalDeviceAsyncContext : public AsyncContext { +public: + WifiP2pDevice deviceInfo; + + P2pLocalDeviceAsyncContext(napi_env env, napi_async_work work = nullptr, napi_deferred deferred = nullptr) + : AsyncContext(env, work, deferred) {} + + P2pLocalDeviceAsyncContext() = delete; + + ~P2pLocalDeviceAsyncContext() override {} +}; + +class QueryP2pDeviceAsyncContext : public AsyncContext { +public: + std::vector vecP2pDevices; + + QueryP2pDeviceAsyncContext(napi_env env, napi_async_work work = nullptr, napi_deferred deferred = nullptr) + : AsyncContext(env, work, deferred) {} + + QueryP2pDeviceAsyncContext() = delete; + + ~QueryP2pDeviceAsyncContext() override {} +}; + +class P2pLinkedInfoAsyncContext : public AsyncContext { +public: + WifiP2pLinkedInfo linkedInfo; + + P2pLinkedInfoAsyncContext(napi_env env, napi_async_work work = nullptr, napi_deferred deferred = nullptr) + : AsyncContext(env, work, deferred) {} + + P2pLinkedInfoAsyncContext() = delete; + + ~P2pLinkedInfoAsyncContext() override {} +}; + +class P2pGroupInfoAsyncContext : public AsyncContext { +public: + WifiP2pGroupInfo groupInfo; + + P2pGroupInfoAsyncContext(napi_env env, napi_async_work work = nullptr, napi_deferred deferred = nullptr) + : AsyncContext(env, work, deferred) {} + + P2pGroupInfoAsyncContext() = delete; + + ~P2pGroupInfoAsyncContext() override {} +}; + +class P2pGroupInfoListAsyncContext : public AsyncContext { +public: + std::vector vecGroupInfoList; + + P2pGroupInfoListAsyncContext(napi_env env, napi_async_work work = nullptr, + napi_deferred deferred = nullptr) + : AsyncContext(env, work, deferred) {} + + P2pGroupInfoListAsyncContext() = delete; + + ~P2pGroupInfoListAsyncContext() override {} +}; +} // namespace Wifi +} // namespace OHOS + +#endif diff --git a/wifi/frameworks/js/napi/inc/wifi_napi_utils.h b/wifi/frameworks/js/napi/inc/wifi_napi_utils.h new file mode 100644 index 0000000000000000000000000000000000000000..ead7569f2b3c72bf5b005ea57c8c30a98ef03d48 --- /dev/null +++ b/wifi/frameworks/js/napi/inc/wifi_napi_utils.h @@ -0,0 +1,122 @@ +/* + * Copyright (C) 2021-2022 Huawei Device Co., Ltd. + * 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 WIFI_NAPI_UTILS_H_ +#define WIFI_NAPI_UTILS_H_ + +#include +#include +#include "napi/native_api.h" +#include "napi/native_node_api.h" + +namespace OHOS { +namespace Wifi { +static constexpr int NAPI_MAX_STR_LENT = 128; +static const std::int32_t SYSCAP_WIFI_CORE = 2400000; +static const std::int32_t SYSCAP_WIFI_STA = 2500000; +static const std::int32_t SYSCAP_WIFI_AP_CORE = 2600000; +static const std::int32_t SYSCAP_WIFI_AP_EXT = 2700000; +static const std::int32_t SYSCAP_WIFI_P2P = 2800000; + +class TraceFuncCall final { +public: + TraceFuncCall(std::string funcName); + + TraceFuncCall() = delete; + + ~TraceFuncCall(); + +private: + std::string m_funcName; + std::chrono::steady_clock::time_point m_startTime; + bool m_isTrace = true; +}; + +#define TRACE_FUNC_CALL TraceFuncCall func(__func__) +#define TRACE_FUNC_CALL_NAME(name) TraceFuncCall funcName(name) + +constexpr int ERR_CODE_SUCCESS = 0; + +class AsyncContext { +public: + napi_env env; + napi_async_work work; + napi_deferred deferred; + napi_ref callback[2] = { 0 }; + std::function executeFunc; + std::function completeFunc; + napi_value resourceName; + napi_value result; + int32_t sysCap; + int errorCode; + + AsyncContext(napi_env e, napi_async_work w = nullptr, napi_deferred d = nullptr) + { + env = e; + work = w; + deferred = d; + executeFunc = nullptr; + completeFunc = nullptr; + result = nullptr; + sysCap = 0; + errorCode = ERR_CODE_SUCCESS; + } + + AsyncContext() = delete; + + virtual ~AsyncContext() + { + } +}; + +napi_value UndefinedNapiValue(const napi_env& env); +napi_value JsObjectToString(const napi_env& env, const napi_value& object, + const char* fieldStr, const int bufLen, std::string& fieldRef); +napi_value JsObjectToInt(const napi_env& env, const napi_value& object, const char* fieldStr, int& fieldRef); +napi_value JsObjectToUint(const napi_env& env, const napi_value& object, const char* fieldStr, uint32_t& fieldRef); +napi_value JsObjectToBool(const napi_env& env, const napi_value& object, const char* fieldStr, bool& fieldRef); +napi_status SetValueUtf8String(const napi_env& env, const char* fieldStr, const char* str, + napi_value& result, size_t strLen = NAPI_AUTO_LENGTH); +napi_status SetValueInt32(const napi_env& env, const char* fieldStr, const int intValue, napi_value& result); +napi_status SetValueUnsignedInt32(const napi_env& env, const char* fieldStr, const int intValue, napi_value& result); +napi_status SetValueInt64(const napi_env& env, const char* fieldStr, const int64_t intValue, napi_value& result); +napi_status SetValueBool(const napi_env& env, const char* fieldStr, const bool boolValue, napi_value& result); +napi_value DoAsyncWork(const napi_env& env, AsyncContext *asyncContext, + const size_t argc, const napi_value *argv, const size_t nonCallbackArgNum); + +enum class SecTypeJs { + SEC_TYPE_INVALID = 0, /* Invalid security type */ + SEC_TYPE_OPEN = 1, /* Open */ + SEC_TYPE_WEP = 2, /* Wired Equivalent Privacy (WEP) */ + SEC_TYPE_PSK = 3, /* Pre-shared key (PSK) */ + SEC_TYPE_SAE = 4, /* Simultaneous Authentication of Equals (SAE) */ + SEC_TYPE_EAP = 5, /* Extensible Authentication Protocol (EAP) */ +}; + +enum class EapMethodJs { + EAP_NONE = 0, + EAP_PEAP = 1, + EAP_TLS = 2, + EAP_TTLS = 3, + EAP_PWD = 4, + EAP_SIM = 5, + EAP_AKA = 6, + EAP_AKA_PRIME = 7, + EAP_UNAUTH_TLS = 8, +}; +} // namespace Wifi +} // namespace OHOS + +#endif diff --git a/wifi/frameworks/js/napi/src/wifi_ext_napi_entry.cpp b/wifi/frameworks/js/napi/src/wifi_ext_napi_entry.cpp new file mode 100644 index 0000000000000000000000000000000000000000..127b8fcb52212369e7b752b331a4e68bc929a1cf --- /dev/null +++ b/wifi/frameworks/js/napi/src/wifi_ext_napi_entry.cpp @@ -0,0 +1,52 @@ +/* + * Copyright (C) 2022 Huawei Device Co., Ltd. + * 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 "wifi_ext_napi_hotspot.h" + +namespace OHOS { +namespace Wifi { +/* + * Module initialization function + */ +static napi_value Init(napi_env env, napi_value exports) +{ + napi_property_descriptor desc[] = { + DECLARE_NAPI_FUNCTION("enableHotspot", EnableHotspot), + DECLARE_NAPI_FUNCTION("disableHotspot", DisableHotspot), + DECLARE_NAPI_FUNCTION("getSupportedPowerModel", GetSupportedPowerModel), + DECLARE_NAPI_FUNCTION("getPowerModel", GetPowerModel), + DECLARE_NAPI_FUNCTION("setPowerModel", SetPowerModel), + }; + + NAPI_CALL(env, napi_define_properties(env, exports, sizeof(desc) / sizeof(napi_property_descriptor), desc)); + return exports; +} + +static napi_module wifiExtJsModule = { + .nm_version = 1, + .nm_flags = 0, + .nm_filename = NULL, + .nm_register_func = Init, + .nm_modname = "wifiext", + .nm_priv = ((void *)0), + .reserved = { 0 } +}; + +extern "C" __attribute__((constructor)) void RegisterModule(void) +{ + napi_module_register(&wifiExtJsModule); +} +} // namespace Wifi +} // namespace OHOS diff --git a/wifi/frameworks/js/napi/src/wifi_ext_napi_hotspot.cpp b/wifi/frameworks/js/napi/src/wifi_ext_napi_hotspot.cpp new file mode 100644 index 0000000000000000000000000000000000000000..4192799f8892c3090e4967115bb9f8b010c4e7d5 --- /dev/null +++ b/wifi/frameworks/js/napi/src/wifi_ext_napi_hotspot.cpp @@ -0,0 +1,164 @@ +/* + * Copyright (C) 2022 Huawei Device Co., Ltd. + * 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 "wifi_ext_napi_hotspot.h" +#include "wifi_logger.h" +#include "wifi_napi_errcode.h" + +namespace OHOS { +namespace Wifi { +DEFINE_WIFILOG_LABEL("WifiExtNAPIHotspot"); + +std::unique_ptr GetHotspotInstance() +{ + return WifiHotspot::GetInstance(WIFI_HOTSPOT_ABILITY_ID); +} + +napi_value EnableHotspot(napi_env env, napi_callback_info info) +{ + TRACE_FUNC_CALL; + std::unique_ptr hotspot = GetHotspotInstance(); + WIFI_NAPI_ASSERT(env, hotspot != nullptr, WIFI_OPT_FAILED, SYSCAP_WIFI_AP_EXT); + ErrCode ret = hotspot->EnableHotspot(ServiceType::WIFI_EXT); + if (ret != WIFI_OPT_SUCCESS) { + WIFI_LOGE("Enable hotspot error: %{public}d", ret); + } + WIFI_NAPI_RETURN(env, ret == WIFI_OPT_SUCCESS, ret, SYSCAP_WIFI_AP_EXT); +} + +napi_value DisableHotspot(napi_env env, napi_callback_info info) +{ + TRACE_FUNC_CALL; + std::unique_ptr hotspot = GetHotspotInstance(); + WIFI_NAPI_ASSERT(env, hotspot != nullptr, WIFI_OPT_FAILED, SYSCAP_WIFI_AP_EXT); + ErrCode ret = hotspot->DisableHotspot(ServiceType::WIFI_EXT); + if (ret != WIFI_OPT_SUCCESS) { + WIFI_LOGE("Disable hotspot error: %{public}d", ret); + } + WIFI_NAPI_RETURN(env, ret == WIFI_OPT_SUCCESS, ret, SYSCAP_WIFI_AP_EXT); +} + +static ErrCode NativePowerModelListToJsObj(const napi_env& env, + const std::set& setPowerModelList, napi_value& arrayResult) +{ + uint32_t idx = 0; + for (auto& each : setPowerModelList) { + napi_value result; + napi_create_int32(env, static_cast(each), &result); + napi_status status = napi_set_element(env, arrayResult, idx++, result); + if (status != napi_ok) { + WIFI_LOGE("Wifi napi set element error: %{public}d, idx: %{public}d", status, idx - 1); + return WIFI_OPT_FAILED; + } + } + return WIFI_OPT_SUCCESS; +} + +napi_value GetSupportedPowerModel(napi_env env, napi_callback_info info) +{ + TRACE_FUNC_CALL; + size_t argc = 1; + napi_value argv[argc]; + napi_value thisVar = nullptr; + void *data = nullptr; + NAPI_CALL(env, napi_get_cb_info(env, info, &argc, argv, &thisVar, &data)); + + PowerModelListAsyncContext *asyncContext = new (std::nothrow) PowerModelListAsyncContext(env); + WIFI_NAPI_ASSERT(env, asyncContext != nullptr, WIFI_OPT_FAILED, SYSCAP_WIFI_AP_EXT); + napi_create_string_latin1(env, "getSupportedPowerModel", NAPI_AUTO_LENGTH, &asyncContext->resourceName); + + asyncContext->executeFunc = [&](void* data) -> void { + PowerModelListAsyncContext *context = static_cast(data); + std::unique_ptr hotspot = GetHotspotInstance(); + if (hotspot == nullptr) { + WIFI_LOGE("hotspot instance is null."); + return; + } + TRACE_FUNC_CALL_NAME("hotspot->GetSupportedPowerModel"); + context->errorCode = hotspot->GetSupportedPowerModel(context->setPowerModelList); + }; + + asyncContext->completeFunc = [&](void* data) -> void { + PowerModelListAsyncContext *context = static_cast(data); + napi_create_array_with_length(context->env, context->setPowerModelList.size(), &context->result); + NativePowerModelListToJsObj(context->env, context->setPowerModelList, context->result); + WIFI_LOGI("Push power model list to client"); + }; + + size_t nonCallbackArgNum = 0; + asyncContext->sysCap = SYSCAP_WIFI_AP_EXT; + return DoAsyncWork(env, asyncContext, argc, argv, nonCallbackArgNum); +} + +napi_value GetPowerModel(napi_env env, napi_callback_info info) +{ + TRACE_FUNC_CALL; + size_t argc = 1; + napi_value argv[argc]; + napi_value thisVar = nullptr; + void *data = nullptr; + NAPI_CALL(env, napi_get_cb_info(env, info, &argc, argv, &thisVar, &data)); + + PowerModelAsyncContext *asyncContext = new (std::nothrow) PowerModelAsyncContext(env); + WIFI_NAPI_ASSERT(env, asyncContext != nullptr, WIFI_OPT_FAILED, SYSCAP_WIFI_AP_EXT); + napi_create_string_latin1(env, "getPowerModel", NAPI_AUTO_LENGTH, &asyncContext->resourceName); + + asyncContext->executeFunc = [&](void* data) -> void { + PowerModelAsyncContext *context = static_cast(data); + std::unique_ptr hotspot = GetHotspotInstance(); + if (hotspot == nullptr) { + WIFI_LOGE("hotspot instance is null."); + return; + } + TRACE_FUNC_CALL_NAME("hotspot->GetPowerModel"); + context->errorCode = hotspot->GetPowerModel(context->powerModel); + }; + + asyncContext->completeFunc = [&](void* data) -> void { + PowerModelAsyncContext *context = static_cast(data); + napi_create_int32(context->env, static_cast(context->powerModel), &context->result); + WIFI_LOGI("Push power model result to client"); + }; + + size_t nonCallbackArgNum = 0; + asyncContext->sysCap = SYSCAP_WIFI_AP_EXT; + return DoAsyncWork(env, asyncContext, argc, argv, nonCallbackArgNum); +} + +napi_value SetPowerModel(napi_env env, napi_callback_info info) +{ + TRACE_FUNC_CALL; + size_t argc = 1; + napi_value argv[1]; + napi_value thisVar; + NAPI_CALL(env, napi_get_cb_info(env, info, &argc, argv, &thisVar, NULL)); + WIFI_NAPI_ASSERT(env, argc == 1, WIFI_OPT_INVALID_PARAM, SYSCAP_WIFI_AP_EXT); + + napi_valuetype valueType; + napi_typeof(env, argv[0], &valueType); + WIFI_NAPI_ASSERT(env, valueType == napi_number, WIFI_OPT_INVALID_PARAM, SYSCAP_WIFI_AP_EXT); + + int model = -1; + napi_get_value_int32(env, argv[0], &model); + std::unique_ptr hotspot = GetHotspotInstance(); + WIFI_NAPI_ASSERT(env, hotspot != nullptr, WIFI_OPT_FAILED, SYSCAP_WIFI_AP_EXT); + ErrCode ret = hotspot->SetPowerModel(static_cast(model)); + if (ret != WIFI_OPT_SUCCESS) { + WIFI_LOGE("Set power model error: %{public}d", ret); + } + WIFI_NAPI_RETURN(env, ret == WIFI_OPT_SUCCESS, ret, SYSCAP_WIFI_AP_EXT); +} +} // namespace Wifi +} // namespace OHOS diff --git a/wifi/frameworks/js/napi/src/wifi_napi_device.cpp b/wifi/frameworks/js/napi/src/wifi_napi_device.cpp new file mode 100644 index 0000000000000000000000000000000000000000..b1ff923fe6f970530717d9e887e30db200608734 --- /dev/null +++ b/wifi/frameworks/js/napi/src/wifi_napi_device.cpp @@ -0,0 +1,1118 @@ +/* + * Copyright (C) 2021-2022 Huawei Device Co., Ltd. + * 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 "wifi_napi_device.h" +#include +#include +#include "wifi_common_util.h" +#include "wifi_logger.h" +#include "wifi_napi_errcode.h" + +namespace OHOS { +namespace Wifi { +DEFINE_WIFILOG_LABEL("WifiNAPIDevice"); +static constexpr int DEFAULT_INVALID_VALUE = -1; + +std::unique_ptr wifiDevicePtr = WifiDevice::GetInstance(WIFI_DEVICE_ABILITY_ID); +std::unique_ptr wifiScanPtr = WifiScan::GetInstance(WIFI_SCAN_ABILITY_ID); + +napi_value EnableWifi(napi_env env, napi_callback_info info) +{ + TRACE_FUNC_CALL; + WIFI_NAPI_ASSERT(env, wifiDevicePtr != nullptr, WIFI_OPT_FAILED, SYSCAP_WIFI_STA); + ErrCode ret = wifiDevicePtr->EnableWifi(); + WIFI_NAPI_RETURN(env, ret == WIFI_OPT_SUCCESS, ret, SYSCAP_WIFI_STA); +} + +napi_value DisableWifi(napi_env env, napi_callback_info info) +{ + TRACE_FUNC_CALL; + WIFI_NAPI_ASSERT(env, wifiDevicePtr != nullptr, WIFI_OPT_FAILED, SYSCAP_WIFI_STA); + ErrCode ret = wifiDevicePtr->DisableWifi(); + WIFI_NAPI_RETURN(env, ret == WIFI_OPT_SUCCESS, ret, SYSCAP_WIFI_STA); +} + +napi_value IsWifiActive(napi_env env, napi_callback_info info) +{ + WIFI_NAPI_ASSERT(env, wifiDevicePtr != nullptr, WIFI_OPT_FAILED, SYSCAP_WIFI_STA); + bool activeStatus = false; + ErrCode ret = wifiDevicePtr->IsWifiActive(activeStatus); + if (ret != WIFI_OPT_SUCCESS) { + WIFI_LOGE("Get wifi active status fail: %{public}d", ret); + } + WIFI_NAPI_RETURN(env, activeStatus, WIFI_OPT_SUCCESS, SYSCAP_WIFI_STA); +} + +napi_value Scan(napi_env env, napi_callback_info info) +{ + TRACE_FUNC_CALL; + WIFI_NAPI_ASSERT(env, wifiDevicePtr != nullptr, WIFI_OPT_FAILED, SYSCAP_WIFI_STA); + ErrCode ret = wifiScanPtr->Scan(); + WIFI_NAPI_RETURN(env, ret == WIFI_OPT_SUCCESS, ret, SYSCAP_WIFI_STA); +} + +static SecTypeJs SecurityTypeNativeToJs(const WifiSecurity& cppSecurityType) +{ + SecTypeJs jsSecurityType = SecTypeJs::SEC_TYPE_INVALID; + switch (cppSecurityType) { + case WifiSecurity::OPEN: + jsSecurityType = SecTypeJs::SEC_TYPE_OPEN; + break; + case WifiSecurity::WEP: + jsSecurityType = SecTypeJs::SEC_TYPE_WEP; + break; + case WifiSecurity::PSK: + jsSecurityType = SecTypeJs::SEC_TYPE_PSK; + break; + case WifiSecurity::SAE: + jsSecurityType = SecTypeJs::SEC_TYPE_SAE; + break; + case WifiSecurity::EAP: + jsSecurityType = SecTypeJs::SEC_TYPE_EAP; + break; + default: + jsSecurityType = SecTypeJs::SEC_TYPE_INVALID; + break; + } + return jsSecurityType; +} + +static ErrCode NativeInfoElemsToJsObj(const napi_env& env, + const std::vector& infoElems, napi_value& eachObj) +{ + napi_value arr; + napi_create_array(env, &arr); + uint8_t idx_ie = 0; + napi_status status; + int valueStep = 2; + for (size_t i = 0; i < infoElems.size(); i++) { + napi_value ieObj; + napi_create_object(env, &ieObj); + SetValueInt32(env, "eid", infoElems[i].id, ieObj); + const char *uStr = &infoElems[i].content[0]; + size_t len = infoElems[i].content.size(); + size_t inLen = (infoElems[i].content.size()) * valueStep + 1; + char *buf = (char *)calloc(inLen + 1, sizeof(char)); + if (buf == NULL) { + return WIFI_OPT_FAILED; + } + int pos = 0; + for (size_t k = 0; k < len; ++k) { + pos = (k << 1); + if (snprintf_s(buf + pos, inLen - pos, inLen - pos - 1, "%02x", uStr[k]) < 0) { + free(buf); + buf = NULL; + return WIFI_OPT_FAILED; + } + } + SetValueUtf8String(env, "content", (const char *)buf, ieObj, inLen - 1); + status = napi_set_element(env, arr, idx_ie++, ieObj); + if (status != napi_ok) { + WIFI_LOGE("set content error"); + free(buf); + buf = NULL; + return WIFI_OPT_FAILED; + } + free(buf); + buf = NULL; + } + status = napi_set_named_property(env, eachObj, "infoElems", arr); + if (status != napi_ok) { + WIFI_LOGE("set infoElems error"); + return WIFI_OPT_FAILED; + } + return WIFI_OPT_SUCCESS; +} + +static ErrCode NativeScanInfosToJsObj(const napi_env& env, + const std::vector& vecScnIanfos, napi_value& arrayResult) +{ + uint32_t idx = 0; + for (auto& each : vecScnIanfos) { + napi_value eachObj; + napi_create_object(env, &eachObj); + SetValueUtf8String(env, "ssid", each.ssid.c_str(), eachObj); + SetValueUtf8String(env, "bssid", each.bssid.c_str(), eachObj); + SetValueUtf8String(env, "capabilities", each.capabilities.c_str(), eachObj); + SetValueInt32(env, "securityType", static_cast(SecurityTypeNativeToJs(each.securityType)), eachObj); + SetValueInt32(env, "rssi", each.rssi, eachObj); + SetValueInt32(env, "band", each.band, eachObj); + SetValueInt32(env, "frequency", each.frequency, eachObj); + SetValueInt32(env, "channelWidth", static_cast(each.channelWidth), eachObj); + SetValueInt32(env, "centerFrequency0", each.centerFrequency0, eachObj); + SetValueInt32(env, "centerFrequency1", each.centerFrequency1, eachObj); + NativeInfoElemsToJsObj(env, each.infoElems, eachObj); + SetValueInt64(env, "timestamp", each.timestamp, eachObj); + napi_status status = napi_set_element(env, arrayResult, idx++, eachObj); + if (status != napi_ok) { + WIFI_LOGE("Wifi napi set element error: %{public}d, idx: %{public}d", status, idx - 1); + return WIFI_OPT_FAILED; + } + } + return WIFI_OPT_SUCCESS; +} + +napi_value GetScanInfos(napi_env env, napi_callback_info info) +{ + TRACE_FUNC_CALL; + size_t argc = 2; + napi_value argv[argc]; + napi_value thisVar = nullptr; + void *data = nullptr; + NAPI_CALL(env, napi_get_cb_info(env, info, &argc, argv, &thisVar, &data)); + WIFI_NAPI_ASSERT(env, wifiDevicePtr != nullptr, WIFI_OPT_FAILED, SYSCAP_WIFI_STA); + + ScanInfoAsyncContext *asyncContext = new ScanInfoAsyncContext(env); + WIFI_NAPI_ASSERT(env, asyncContext != nullptr, WIFI_OPT_FAILED, SYSCAP_WIFI_STA); + napi_create_string_latin1(env, "getScanInfos", NAPI_AUTO_LENGTH, &asyncContext->resourceName); + + asyncContext->executeFunc = [&](void* data) -> void { + ScanInfoAsyncContext *context = static_cast(data); + TRACE_FUNC_CALL_NAME("wifiScanPtr->GetScanInfoList"); + context->errorCode = wifiScanPtr->GetScanInfoList(context->vecScanInfos); + WIFI_LOGI("GetScanInfoList, size: %{public}zu", context->vecScanInfos.size()); + }; + + asyncContext->completeFunc = [&](void* data) -> void { + ScanInfoAsyncContext *context = static_cast(data); + napi_create_array_with_length(context->env, context->vecScanInfos.size(), &context->result); + context->errorCode = NativeScanInfosToJsObj(context->env, context->vecScanInfos, context->result); + WIFI_LOGI("Push scan info list to client"); + }; + + size_t nonCallbackArgNum = 0; + asyncContext->sysCap = SYSCAP_WIFI_STA; + return DoAsyncWork(env, asyncContext, argc, argv, nonCallbackArgNum); +} + +napi_value GetScanResults(napi_env env, napi_callback_info info) +{ + TRACE_FUNC_CALL; + WIFI_NAPI_ASSERT(env, wifiDevicePtr != nullptr, WIFI_OPT_FAILED, SYSCAP_WIFI_STA); + std::vector scanInfos; + ErrCode ret = wifiScanPtr->GetScanInfoList(scanInfos); + if (ret != WIFI_OPT_SUCCESS) { + WIFI_LOGE("GetScanInfoList return fail: %{public}d", ret); + } + + WIFI_NAPI_ASSERT(env, ret == WIFI_OPT_SUCCESS, ret, SYSCAP_WIFI_STA); + WIFI_LOGI("GetScanInfoList, size: %{public}zu", scanInfos.size()); + napi_value arrayResult; + napi_create_array_with_length(env, scanInfos.size(), &arrayResult); + ret = NativeScanInfosToJsObj(env, scanInfos, arrayResult); + if (ret != WIFI_OPT_SUCCESS) { + WIFI_LOGE("NativeScanInfosToJsObj return fail: %{public}d", ret); + } + return arrayResult; +} + +static void ConvertEncryptionMode(const SecTypeJs& securityType, std::string& keyMgmt) +{ + switch (securityType) { + case SecTypeJs::SEC_TYPE_OPEN: + keyMgmt = KEY_MGMT_NONE; + break; + case SecTypeJs::SEC_TYPE_WEP: + keyMgmt = KEY_MGMT_WEP; + break; + case SecTypeJs::SEC_TYPE_PSK: + keyMgmt = KEY_MGMT_WPA_PSK; + break; + case SecTypeJs::SEC_TYPE_SAE: + keyMgmt = KEY_MGMT_SAE; + break; + case SecTypeJs::SEC_TYPE_EAP: + keyMgmt = KEY_MGMT_EAP; + break; + default: + keyMgmt = KEY_MGMT_NONE; + break; + } +} + +static void ProcessPassphrase(const SecTypeJs& securityType, WifiDeviceConfig& cppConfig) +{ + if (securityType == SecTypeJs::SEC_TYPE_WEP) { + cppConfig.wepKeys[0] = cppConfig.preSharedKey; + cppConfig.wepTxKeyIndex = 0; + cppConfig.preSharedKey = ""; + } +} + +void ProcessEapPeapConfig(const napi_env& env, const napi_value& object, WifiEapConfig& eapConfig) +{ + // identity, password, phase2Method filed is necessary + eapConfig.eap = EAP_METHOD_PEAP; + JsObjectToString(env, object, "identity", NAPI_MAX_STR_LENT, eapConfig.identity); + JsObjectToString(env, object, "password", NAPI_MAX_STR_LENT, eapConfig.password); + + int phase2 = static_cast(Phase2Method::NONE); + JsObjectToInt(env, object, "phase2Method", phase2); + eapConfig.phase2Method = Phase2Method(phase2); +} + +napi_value ProcessEapConfig(const napi_env& env, const napi_value& object, WifiDeviceConfig& devConfig) +{ + bool hasProperty = false; + + NAPI_CALL(env, napi_has_named_property(env, object, "eapConfig", &hasProperty)); + if (!hasProperty) { + WIFI_LOGI("Js has no property: eapConfig."); + return UndefinedNapiValue(env); + } + + napi_value napiEap; + napi_get_named_property(env, object, "eapConfig", &napiEap); + + int eapMethod = static_cast(EapMethodJs::EAP_NONE); + JsObjectToInt(env, napiEap, "eapMethod", eapMethod); + switch (EapMethodJs(eapMethod)) { + case EapMethodJs::EAP_PEAP: + ProcessEapPeapConfig(env, napiEap, devConfig.wifiEapConfig); + break; + default: + WIFI_LOGE("EapMethod: %{public}d unsupported", eapMethod); + break; + } + return UndefinedNapiValue(env); +} + +napi_value ConfigStaticIp(const napi_env& env, const napi_value& object, WifiDeviceConfig& cppConfig) +{ + bool hasProperty = false; + JsObjectToInt(env, object, "prefixLength", cppConfig.wifiIpConfig.staticIpAddress.ipAddress.prefixLength); + NAPI_CALL(env, napi_has_named_property(env, object, "staticIp", &hasProperty)); + if (!hasProperty) { + WIFI_LOGE("Js has no property: staticIp."); + return UndefinedNapiValue(env); + } + napi_value staticIp; + napi_value dnsServers; + napi_value primaryDns; + napi_value secondDns; + napi_get_named_property(env, object, "staticIp", &staticIp); + JsObjectToUint(env, staticIp, "ipAddress", + cppConfig.wifiIpConfig.staticIpAddress.ipAddress.address.addressIpv4); + cppConfig.wifiIpConfig.staticIpAddress.ipAddress.address.family = 0; + JsObjectToUint(env, staticIp, "gateway", cppConfig.wifiIpConfig.staticIpAddress.gateway.addressIpv4); + + NAPI_CALL(env, napi_has_named_property(env, staticIp, "dnsServers", &hasProperty)); + if (!hasProperty) { + WIFI_LOGE("Js has no property: dnsServers."); + return UndefinedNapiValue(env); + } + uint32_t arrayLength = 0; + const int DNS_NUM = 2; + napi_get_named_property(env, staticIp, "dnsServers", &dnsServers); + napi_get_array_length(env, dnsServers, &arrayLength); + if (arrayLength != DNS_NUM) { + WIFI_LOGE("It needs two dns servers."); + return UndefinedNapiValue(env); + } + napi_get_element(env, dnsServers, 0, &primaryDns); + napi_get_element(env, dnsServers, 1, &secondDns); + napi_get_value_uint32(env, primaryDns, &cppConfig.wifiIpConfig.staticIpAddress.dnsServer1.addressIpv4); + napi_get_value_uint32(env, secondDns, &cppConfig.wifiIpConfig.staticIpAddress.dnsServer2.addressIpv4); + + return UndefinedNapiValue(env); +} + +static void JsObjToDeviceConfig(const napi_env& env, const napi_value& object, WifiDeviceConfig& cppConfig) +{ + JsObjectToString(env, object, "ssid", NAPI_MAX_STR_LENT, cppConfig.ssid); /* ssid max length is 32 + '\0' */ + JsObjectToString(env, object, "bssid", NAPI_MAX_STR_LENT, cppConfig.bssid); /* max bssid length: 18 */ + JsObjectToString(env, object, "preSharedKey", NAPI_MAX_STR_LENT, cppConfig.preSharedKey); + JsObjectToBool(env, object, "isHiddenSsid", cppConfig.hiddenSSID); + int type = static_cast(SecTypeJs::SEC_TYPE_INVALID); + JsObjectToInt(env, object, "securityType", type); + ConvertEncryptionMode(SecTypeJs(type), cppConfig.keyMgmt); + ProcessPassphrase(SecTypeJs(type), cppConfig); + /* "creatorUid" is not supported currently */ + /* "disableReason" is not supported currently */ + JsObjectToInt(env, object, "netId", cppConfig.networkId); + /* "randomMacType" is not supported currently */ + /* "randomMacAddr" is not supported currently */ + int ipType = static_cast(AssignIpMethod::UNASSIGNED); + JsObjectToInt(env, object, "ipType", ipType); + WIFI_LOGI("JsObjToDeviceConfig, ipType: %{public}d.", ipType); + if (IpTypeJs(ipType) == IpTypeJs::IP_TYPE_DHCP) { + cppConfig.wifiIpConfig.assignMethod = AssignIpMethod::DHCP; + } else if (IpTypeJs(ipType) == IpTypeJs::IP_TYPE_STATIC) { + cppConfig.wifiIpConfig.assignMethod = AssignIpMethod::STATIC; + ConfigStaticIp(env, object, cppConfig); + } + (void)ProcessEapConfig(env, object, cppConfig); +} + +napi_value AddDeviceConfig(napi_env env, napi_callback_info info) +{ + TRACE_FUNC_CALL; + size_t argc = 3; + napi_value argv[argc]; + napi_value thisVar = nullptr; + void *data = nullptr; + NAPI_CALL(env, napi_get_cb_info(env, info, &argc, argv, &thisVar, &data)); + WIFI_NAPI_ASSERT(env, argc >= 1, WIFI_OPT_INVALID_PARAM, SYSCAP_WIFI_STA); + WIFI_NAPI_ASSERT(env, wifiDevicePtr != nullptr, WIFI_OPT_FAILED, SYSCAP_WIFI_STA); + + napi_valuetype valueType; + napi_typeof(env, argv[0], &valueType); + WIFI_NAPI_ASSERT(env, valueType == napi_object, WIFI_OPT_INVALID_PARAM, SYSCAP_WIFI_STA); + + DeviceConfigContext *asyncContext = new DeviceConfigContext(env); + WIFI_NAPI_ASSERT(env, asyncContext != nullptr, WIFI_OPT_FAILED, SYSCAP_WIFI_STA); + napi_create_string_latin1(env, "addDeviceConfig", NAPI_AUTO_LENGTH, &asyncContext->resourceName); + + WifiDeviceConfig *config = new WifiDeviceConfig(); + if (config == nullptr) { + delete asyncContext; + return UndefinedNapiValue(env); + } + JsObjToDeviceConfig(env, argv[0], *config); + asyncContext->config = config; + asyncContext->isCandidate = false; + + asyncContext->executeFunc = [&](void* data) -> void { + DeviceConfigContext *context = static_cast(data); + TRACE_FUNC_CALL_NAME("wifiDevicePtr->AddDeviceConfig"); + ErrCode ret = wifiDevicePtr->AddDeviceConfig(*context->config, context->networkId, context->isCandidate); + if (context->networkId < 0 || ret != WIFI_OPT_SUCCESS) { + context->networkId = -1; + } + context->errorCode = ret; + }; + + asyncContext->completeFunc = [&](void* data) -> void { + DeviceConfigContext *context = static_cast(data); + napi_create_int32(context->env, context->networkId, &context->result); + if (context->config != nullptr) { + delete context->config; + context->config = nullptr; + } + WIFI_LOGI("Push add device config result to client"); + }; + + size_t nonCallbackArgNum = 1; + asyncContext->sysCap = SYSCAP_WIFI_STA; + return DoAsyncWork(env, asyncContext, argc, argv, nonCallbackArgNum); +} + +napi_value AddUntrustedConfig(napi_env env, napi_callback_info info) +{ + TRACE_FUNC_CALL; + size_t argc = 2; + napi_value argv[argc]; + napi_value thisVar = nullptr; + void *data = nullptr; + NAPI_CALL(env, napi_get_cb_info(env, info, &argc, argv, &thisVar, &data)); + WIFI_NAPI_ASSERT(env, argc >= 1, WIFI_OPT_INVALID_PARAM, SYSCAP_WIFI_STA); + WIFI_NAPI_ASSERT(env, wifiDevicePtr != nullptr, WIFI_OPT_FAILED, SYSCAP_WIFI_STA); + + napi_valuetype valueType; + napi_typeof(env, argv[0], &valueType); + WIFI_NAPI_ASSERT(env, valueType == napi_object, WIFI_OPT_INVALID_PARAM, SYSCAP_WIFI_STA); + + DeviceConfigContext *asyncContext = new DeviceConfigContext(env); + WIFI_NAPI_ASSERT(env, asyncContext != nullptr, WIFI_OPT_FAILED, SYSCAP_WIFI_STA); + napi_create_string_latin1(env, "AddUntrustedConfig", NAPI_AUTO_LENGTH, &asyncContext->resourceName); + + WifiDeviceConfig *config = new WifiDeviceConfig(); + if (config == nullptr) { + delete asyncContext; + return UndefinedNapiValue(env); + } + JsObjToDeviceConfig(env, argv[0], *config); + asyncContext->config = config; + asyncContext->isCandidate = true; + + asyncContext->executeFunc = [&](void* data) -> void { + DeviceConfigContext *context = static_cast(data); + TRACE_FUNC_CALL_NAME("wifiDevicePtr->AddUntrustedConfig"); + ErrCode ret = wifiDevicePtr->AddDeviceConfig(*context->config, context->networkId, context->isCandidate); + if (context->networkId < 0 || ret != WIFI_OPT_SUCCESS) { + context->networkId = -1; + } + context->errorCode = ret; + }; + + asyncContext->completeFunc = [&](void* data) -> void { + DeviceConfigContext *context = static_cast(data); + napi_get_boolean(context->env, (context->networkId >= 0), &context->result); + if (context->config != nullptr) { + delete context->config; + context->config = nullptr; + } + WIFI_LOGI("Push add untrusted device config result to client"); + }; + + size_t nonCallbackArgNum = 1; + asyncContext->sysCap = SYSCAP_WIFI_STA; + return DoAsyncWork(env, asyncContext, argc, argv, nonCallbackArgNum); +} + +napi_value RemoveUntrustedConfig(napi_env env, napi_callback_info info) +{ + TRACE_FUNC_CALL; + size_t argc = 3; + napi_value argv[argc]; + napi_value thisVar = nullptr; + void *data = nullptr; + NAPI_CALL(env, napi_get_cb_info(env, info, &argc, argv, &thisVar, &data)); + WIFI_NAPI_ASSERT(env, argc >= 1, WIFI_OPT_INVALID_PARAM, SYSCAP_WIFI_STA); + WIFI_NAPI_ASSERT(env, wifiDevicePtr != nullptr, WIFI_OPT_FAILED, SYSCAP_WIFI_STA); + + napi_valuetype valueType; + napi_typeof(env, argv[0], &valueType); + WIFI_NAPI_ASSERT(env, valueType == napi_object, WIFI_OPT_INVALID_PARAM, SYSCAP_WIFI_STA); + + DeviceConfigContext *asyncContext = new DeviceConfigContext(env); + WIFI_NAPI_ASSERT(env, asyncContext != nullptr, WIFI_OPT_FAILED, SYSCAP_WIFI_STA); + napi_create_string_latin1(env, "RemoveUntrustedConfig", NAPI_AUTO_LENGTH, &asyncContext->resourceName); + + WifiDeviceConfig *config = new WifiDeviceConfig(); + if (config == nullptr) { + delete asyncContext; + return UndefinedNapiValue(env); + } + JsObjToDeviceConfig(env, argv[0], *config); + asyncContext->config = config; + + asyncContext->executeFunc = [&](void* data) -> void { + DeviceConfigContext *context = static_cast(data); + TRACE_FUNC_CALL_NAME("wifiDevicePtr->RemoveCandidateConfig"); + context->errorCode = wifiDevicePtr->RemoveCandidateConfig(*context->config); + }; + + asyncContext->completeFunc = [&](void* data) -> void { + DeviceConfigContext *context = static_cast(data); + napi_get_boolean(context->env, context->errorCode == WIFI_OPT_SUCCESS, &context->result); + if (context->config != nullptr) { + delete context->config; + context->config = nullptr; + } + WIFI_LOGI("Push remove untrusted device config result to client"); + }; + + size_t nonCallbackArgNum = 1; + asyncContext->sysCap = SYSCAP_WIFI_STA; + return DoAsyncWork(env, asyncContext, argc, argv, nonCallbackArgNum); +} + +napi_value AddCandidateConfig(napi_env env, napi_callback_info info) +{ + TRACE_FUNC_CALL; + size_t argc = 2; + napi_value argv[argc]; + napi_value thisVar = nullptr; + void *data = nullptr; + NAPI_CALL(env, napi_get_cb_info(env, info, &argc, argv, &thisVar, &data)); + WIFI_NAPI_ASSERT(env, argc >= 1, WIFI_OPT_INVALID_PARAM, SYSCAP_WIFI_STA); + WIFI_NAPI_ASSERT(env, wifiDevicePtr != nullptr, WIFI_OPT_FAILED, SYSCAP_WIFI_STA); + + napi_valuetype valueType; + napi_typeof(env, argv[0], &valueType); + WIFI_NAPI_ASSERT(env, valueType == napi_object, WIFI_OPT_INVALID_PARAM, SYSCAP_WIFI_STA); + + DeviceConfigContext *asyncContext = new DeviceConfigContext(env); + WIFI_NAPI_ASSERT(env, asyncContext != nullptr, WIFI_OPT_FAILED, SYSCAP_WIFI_STA); + napi_create_string_latin1(env, "AddCandidateConfig", NAPI_AUTO_LENGTH, &asyncContext->resourceName); + + WifiDeviceConfig *config = new WifiDeviceConfig(); + if (config == nullptr) { + delete asyncContext; + return UndefinedNapiValue(env); + } + JsObjToDeviceConfig(env, argv[0], *config); + asyncContext->config = config; + asyncContext->isCandidate = true; + + asyncContext->executeFunc = [&](void* data) -> void { + DeviceConfigContext *context = static_cast(data); + TRACE_FUNC_CALL_NAME("wifiDevicePtr->AddCandidateConfig"); + ErrCode ret = wifiDevicePtr->AddDeviceConfig(*context->config, context->networkId, context->isCandidate); + if (context->networkId < 0 || ret != WIFI_OPT_SUCCESS) { + WIFI_LOGE("Add candidate device config failed: %{public}d", static_cast(ret)); + context->networkId = -1; + } + context->errorCode = ret; + }; + + asyncContext->completeFunc = [&](void* data) -> void { + DeviceConfigContext *context = static_cast(data); + napi_create_int32(context->env, context->networkId, &context->result); + if (context->config != nullptr) { + delete context->config; + context->config = nullptr; + } + WIFI_LOGI("Push add candidate device config result to client"); + }; + + size_t nonCallbackArgNum = 1; + asyncContext->sysCap = SYSCAP_WIFI_STA; + return DoAsyncWork(env, asyncContext, argc, argv, nonCallbackArgNum); +} + +napi_value RemoveCandidateConfig(napi_env env, napi_callback_info info) +{ + TRACE_FUNC_CALL; + size_t argc = 3; + napi_value argv[argc]; + napi_value thisVar = nullptr; + void *data = nullptr; + NAPI_CALL(env, napi_get_cb_info(env, info, &argc, argv, &thisVar, &data)); + WIFI_NAPI_ASSERT(env, argc >= 1, WIFI_OPT_INVALID_PARAM, SYSCAP_WIFI_STA); + WIFI_NAPI_ASSERT(env, wifiDevicePtr != nullptr, WIFI_OPT_FAILED, SYSCAP_WIFI_STA); + + napi_valuetype valueType; + napi_typeof(env, argv[0], &valueType); + WIFI_NAPI_ASSERT(env, valueType == napi_number, WIFI_OPT_INVALID_PARAM, SYSCAP_WIFI_STA); + + DeviceConfigContext *asyncContext = new DeviceConfigContext(env); + WIFI_NAPI_ASSERT(env, asyncContext != nullptr, WIFI_OPT_FAILED, SYSCAP_WIFI_STA); + napi_create_string_latin1(env, "RemoveCandidateConfig", NAPI_AUTO_LENGTH, &asyncContext->resourceName); + + napi_get_value_int32(env, argv[0], &asyncContext->networkId); + asyncContext->executeFunc = [&](void* data) -> void { + DeviceConfigContext *context = static_cast(data); + context->errorCode = wifiDevicePtr->RemoveCandidateConfig(context->networkId); + }; + + asyncContext->completeFunc = [&](void* data) -> void { + DeviceConfigContext *context = static_cast(data); + napi_get_boolean(context->env, (context->errorCode == WIFI_OPT_SUCCESS), &context->result); + if (context->config != nullptr) { + delete context->config; + context->config = nullptr; + } + WIFI_LOGI("Push remove candidate device config result to client"); + }; + + size_t nonCallbackArgNum = 1; + asyncContext->sysCap = SYSCAP_WIFI_STA; + return DoAsyncWork(env, asyncContext, argc, argv, nonCallbackArgNum); +} + +napi_value ConnectToCandidateConfig(napi_env env, napi_callback_info info) +{ + TRACE_FUNC_CALL; + size_t argc = 1; + napi_value argv[1]; + napi_value thisVar; + NAPI_CALL(env, napi_get_cb_info(env, info, &argc, argv, &thisVar, NULL)); + WIFI_NAPI_ASSERT(env, argc == 1, WIFI_OPT_INVALID_PARAM, SYSCAP_WIFI_STA); + + napi_valuetype valueType; + napi_typeof(env, argv[0], &valueType); + WIFI_NAPI_ASSERT(env, valueType == napi_number, WIFI_OPT_INVALID_PARAM, SYSCAP_WIFI_STA); + + int networkId = -1; + napi_get_value_int32(env, argv[0], &networkId); + bool isCandidate = true; + + WIFI_NAPI_ASSERT(env, wifiDevicePtr != nullptr, WIFI_OPT_FAILED, SYSCAP_WIFI_STA); + ErrCode ret = wifiDevicePtr->ConnectToNetwork(networkId, isCandidate); + WIFI_NAPI_RETURN(env, ret == WIFI_OPT_SUCCESS, ret, SYSCAP_WIFI_STA); +} + +napi_value ConnectToNetwork(napi_env env, napi_callback_info info) +{ + TRACE_FUNC_CALL; + size_t argc = 1; + napi_value argv[1]; + napi_value thisVar; + NAPI_CALL(env, napi_get_cb_info(env, info, &argc, argv, &thisVar, NULL)); + WIFI_NAPI_ASSERT(env, argc == 1, WIFI_OPT_INVALID_PARAM, SYSCAP_WIFI_STA); + + napi_valuetype valueType; + napi_typeof(env, argv[0], &valueType); + WIFI_NAPI_ASSERT(env, valueType == napi_number, WIFI_OPT_INVALID_PARAM, SYSCAP_WIFI_STA); + + int networkId = -1; + napi_get_value_int32(env, argv[0], &networkId); + bool isCandidate = false; + + WIFI_NAPI_ASSERT(env, wifiDevicePtr != nullptr, WIFI_OPT_FAILED, SYSCAP_WIFI_STA); + ErrCode ret = wifiDevicePtr->ConnectToNetwork(networkId, isCandidate); + WIFI_NAPI_RETURN(env, ret == WIFI_OPT_SUCCESS, ret, SYSCAP_WIFI_STA); +} + +napi_value ConnectToDevice(napi_env env, napi_callback_info info) +{ + TRACE_FUNC_CALL; + size_t argc = 1; + napi_value argv[1]; + napi_value thisVar; + NAPI_CALL(env, napi_get_cb_info(env, info, &argc, argv, &thisVar, NULL)); + + napi_valuetype valueType; + napi_typeof(env, argv[0], &valueType); + WIFI_NAPI_ASSERT(env, valueType == napi_object, WIFI_OPT_INVALID_PARAM, SYSCAP_WIFI_STA); + + WIFI_NAPI_ASSERT(env, wifiDevicePtr != nullptr, WIFI_OPT_FAILED, SYSCAP_WIFI_STA); + WifiDeviceConfig config; + JsObjToDeviceConfig(env, argv[0], config); + ErrCode ret = wifiDevicePtr->ConnectToDevice(config); + if (ret != WIFI_OPT_SUCCESS) { + WIFI_LOGE("Connect to device fail: %{public}d", ret); + } + WIFI_NAPI_RETURN(env, ret == WIFI_OPT_SUCCESS, ret, SYSCAP_WIFI_STA); +} + +napi_value IsConnected(napi_env env, napi_callback_info info) +{ + TRACE_FUNC_CALL; + WIFI_NAPI_ASSERT(env, wifiDevicePtr != nullptr, WIFI_OPT_FAILED, SYSCAP_WIFI_STA); + WIFI_NAPI_RETURN(env, wifiDevicePtr->IsConnected(), WIFI_OPT_SUCCESS, SYSCAP_WIFI_STA); +} + +napi_value Disconnect(napi_env env, napi_callback_info info) +{ + TRACE_FUNC_CALL; + WIFI_NAPI_ASSERT(env, wifiDevicePtr != nullptr, WIFI_OPT_FAILED, SYSCAP_WIFI_STA); + ErrCode ret = wifiDevicePtr->Disconnect(); + WIFI_NAPI_RETURN(env, ret == WIFI_OPT_SUCCESS, ret, SYSCAP_WIFI_STA); +} + +napi_value GetSignalLevel(napi_env env, napi_callback_info info) +{ + size_t argc = 2; + const int PARAMS_NUM = 2; + napi_value argv[2]; + napi_value thisVar; + NAPI_CALL(env, napi_get_cb_info(env, info, &argc, argv, &thisVar, NULL)); + /* the input have 2 parameters */ + WIFI_NAPI_ASSERT(env, argc == PARAMS_NUM, WIFI_OPT_INVALID_PARAM, SYSCAP_WIFI_STA); + + napi_valuetype type1; + napi_valuetype type2; + napi_typeof(env, argv[0], &type1); + napi_typeof(env, argv[1], &type2); + WIFI_NAPI_ASSERT(env, type1 == napi_number, WIFI_OPT_INVALID_PARAM, SYSCAP_WIFI_STA); + WIFI_NAPI_ASSERT(env, type2 == napi_number, WIFI_OPT_INVALID_PARAM, SYSCAP_WIFI_STA); + WIFI_NAPI_ASSERT(env, wifiDevicePtr != nullptr, WIFI_OPT_FAILED, SYSCAP_WIFI_STA); + + int level = -1; + int rssi = 0; + int band = 0; + napi_get_value_int32(env, argv[0], &rssi); + napi_get_value_int32(env, argv[1], &band); + ErrCode ret = wifiDevicePtr->GetSignalLevel(rssi, band, level); + if (ret != WIFI_OPT_SUCCESS) { + WIFI_LOGE("Get wifi signal level fail: %{public}d", ret); + WIFI_NAPI_ASSERT(env, ret == WIFI_OPT_SUCCESS, ret, SYSCAP_WIFI_STA); + } + napi_value result; + napi_create_uint32(env, level, &result); + return result; +} + +napi_value ReConnect(napi_env env, napi_callback_info info) +{ + TRACE_FUNC_CALL; + WIFI_NAPI_ASSERT(env, wifiDevicePtr != nullptr, WIFI_OPT_FAILED, SYSCAP_WIFI_STA); + ErrCode ret = wifiDevicePtr->ReConnect(); + WIFI_NAPI_RETURN(env, ret == WIFI_OPT_SUCCESS, ret, SYSCAP_WIFI_STA); +} + +napi_value ReAssociate(napi_env env, napi_callback_info info) +{ + TRACE_FUNC_CALL; + WIFI_NAPI_ASSERT(env, wifiDevicePtr != nullptr, WIFI_OPT_FAILED, SYSCAP_WIFI_STA); + ErrCode ret = wifiDevicePtr->ReAssociate(); + WIFI_NAPI_RETURN(env, ret == WIFI_OPT_SUCCESS, ret, SYSCAP_WIFI_STA); +} + +static void IpInfoToJsObj(const napi_env& env, IpInfo& ipInfo, napi_value& result) +{ + napi_create_object(env, &result); + SetValueUnsignedInt32(env, "ipAddress", ipInfo.ipAddress, result); + SetValueUnsignedInt32(env, "gateway", ipInfo.gateway, result); + SetValueUnsignedInt32(env, "netmask", ipInfo.netmask, result); + SetValueUnsignedInt32(env, "primaryDns", ipInfo.primaryDns, result); + SetValueUnsignedInt32(env, "secondDns", ipInfo.secondDns, result); + SetValueUnsignedInt32(env, "serverIp", ipInfo.serverIp, result); + SetValueUnsignedInt32(env, "leaseDuration", ipInfo.leaseDuration, result); +} + +napi_value GetIpInfo(napi_env env, napi_callback_info info) +{ + TRACE_FUNC_CALL; + WIFI_NAPI_ASSERT(env, wifiDevicePtr != nullptr, WIFI_OPT_FAILED, SYSCAP_WIFI_STA); + + IpInfo ipInfo; + napi_value result; + ErrCode ret = wifiDevicePtr->GetIpInfo(ipInfo); + if (ret != WIFI_OPT_SUCCESS) { + WIFI_LOGE("Get ip info fail: %{public}d", ret); + } + WIFI_NAPI_ASSERT(env, ret == WIFI_OPT_SUCCESS, ret, SYSCAP_WIFI_STA); + IpInfoToJsObj(env, ipInfo, result); + return result; +} + +static void LinkedInfoToJs(const napi_env& env, WifiLinkedInfo& linkedInfo, napi_value& result) +{ + SetValueUtf8String(env, "ssid", linkedInfo.ssid.c_str(), result); + SetValueUtf8String(env, "bssid", linkedInfo.bssid.c_str(), result); + SetValueInt32(env, "networkId", linkedInfo.networkId, result); + SetValueInt32(env, "rssi", linkedInfo.rssi, result); + SetValueInt32(env, "band", linkedInfo.band, result); + SetValueInt32(env, "linkSpeed", linkedInfo.linkSpeed, result); + SetValueInt32(env, "frequency", linkedInfo.frequency, result); + SetValueBool(env, "isHidden", linkedInfo.ifHiddenSSID, result); + /* isRestricted not support now, set as default value */ + SetValueBool(env, "isRestricted", false, result); + SetValueInt32(env, "chload", linkedInfo.chload, result); + SetValueInt32(env, "snr", linkedInfo.snr, result); + SetValueUtf8String(env, "macAddress", linkedInfo.macAddress.c_str(), result); + SetValueInt32(env, "macType", linkedInfo.macType, result); + SetValueUnsignedInt32(env, "ipAddress", linkedInfo.ipAddress, result); + SetValueInt32(env, "suppState", static_cast(linkedInfo.supplicantState), result); + SetValueInt32(env, "connState", static_cast(linkedInfo.connState), result); +} + +/* This interface has not been fully implemented */ +napi_value GetLinkedInfo(napi_env env, napi_callback_info info) +{ + TRACE_FUNC_CALL; + size_t argc = 2; + napi_value argv[argc]; + napi_value thisVar = nullptr; + void *data = nullptr; + NAPI_CALL(env, napi_get_cb_info(env, info, &argc, argv, &thisVar, &data)); + WIFI_NAPI_ASSERT(env, wifiDevicePtr != nullptr, WIFI_OPT_FAILED, SYSCAP_WIFI_STA); + + LinkedInfoAsyncContext *asyncContext = new LinkedInfoAsyncContext(env); + WIFI_NAPI_ASSERT(env, asyncContext != nullptr, WIFI_OPT_FAILED, SYSCAP_WIFI_STA); + napi_create_string_latin1(env, "getLinkedInfo", NAPI_AUTO_LENGTH, &asyncContext->resourceName); + + asyncContext->executeFunc = [&](void* data) -> void { + LinkedInfoAsyncContext *context = static_cast(data); + TRACE_FUNC_CALL_NAME("wifiDevicePtr->GetLinkedInfo"); + context->errorCode = wifiDevicePtr->GetLinkedInfo(context->linkedInfo); + }; + + asyncContext->completeFunc = [&](void* data) -> void { + LinkedInfoAsyncContext *context = static_cast(data); + napi_create_object(context->env, &context->result); + LinkedInfoToJs(context->env, context->linkedInfo, context->result); + WIFI_LOGI("Push get linkedInfo result to client"); + }; + + size_t nonCallbackArgNum = 0; + asyncContext->sysCap = SYSCAP_WIFI_STA; + return DoAsyncWork(env, asyncContext, argc, argv, nonCallbackArgNum); +} + +napi_value RemoveDevice(napi_env env, napi_callback_info info) +{ + TRACE_FUNC_CALL; + size_t argc = 1; + napi_value argv[1]; + napi_value thisVar; + NAPI_CALL(env, napi_get_cb_info(env, info, &argc, argv, &thisVar, NULL)); + WIFI_NAPI_ASSERT(env, argc == 1, WIFI_OPT_INVALID_PARAM, SYSCAP_WIFI_STA); + + napi_valuetype valueType; + napi_typeof(env, argv[0], &valueType); + WIFI_NAPI_ASSERT(env, valueType == napi_number, WIFI_OPT_INVALID_PARAM, SYSCAP_WIFI_STA); + + int networkId = -1; + napi_get_value_int32(env, argv[0], &networkId); + WIFI_NAPI_ASSERT(env, wifiDevicePtr != nullptr, WIFI_OPT_FAILED, SYSCAP_WIFI_STA); + + ErrCode ret = wifiDevicePtr->RemoveDevice(networkId); + WIFI_NAPI_RETURN(env, ret == WIFI_OPT_SUCCESS, ret, SYSCAP_WIFI_STA); +} + +napi_value RemoveAllNetwork(napi_env env, napi_callback_info info) +{ + TRACE_FUNC_CALL; + WIFI_NAPI_ASSERT(env, wifiDevicePtr != nullptr, WIFI_OPT_FAILED, SYSCAP_WIFI_STA); + ErrCode ret = wifiDevicePtr->RemoveAllDevice(); + WIFI_NAPI_RETURN(env, ret == WIFI_OPT_SUCCESS, ret, SYSCAP_WIFI_STA); +} + +napi_value DisableNetwork(napi_env env, napi_callback_info info) +{ + TRACE_FUNC_CALL; + size_t argc = 1; + napi_value argv[1]; + napi_value thisVar; + NAPI_CALL(env, napi_get_cb_info(env, info, &argc, argv, &thisVar, NULL)); + WIFI_NAPI_ASSERT(env, argc == 1, WIFI_OPT_INVALID_PARAM, SYSCAP_WIFI_STA); + + napi_valuetype valueType; + napi_typeof(env, argv[0], &valueType); + WIFI_NAPI_ASSERT(env, valueType == napi_number, WIFI_OPT_INVALID_PARAM, SYSCAP_WIFI_STA); + WIFI_NAPI_ASSERT(env, wifiDevicePtr != nullptr, WIFI_OPT_FAILED, SYSCAP_WIFI_STA); + + int networkId = -1; + napi_get_value_int32(env, argv[0], &networkId); + ErrCode ret = wifiDevicePtr->DisableDeviceConfig(networkId); + WIFI_NAPI_RETURN(env, ret == WIFI_OPT_SUCCESS, ret, SYSCAP_WIFI_STA); +} + +napi_value GetCountryCode(napi_env env, napi_callback_info info) +{ + TRACE_FUNC_CALL; + WIFI_NAPI_ASSERT(env, wifiDevicePtr != nullptr, WIFI_OPT_FAILED, SYSCAP_WIFI_CORE); + std::string countryCode; + ErrCode ret = wifiDevicePtr->GetCountryCode(countryCode); + if (ret != WIFI_OPT_SUCCESS) { + WIFI_LOGE("Get countryCode fail: %{public}d", ret); + } + WIFI_NAPI_ASSERT(env, ret == WIFI_OPT_SUCCESS, ret, SYSCAP_WIFI_CORE); + napi_value cc; + napi_create_string_utf8(env, countryCode.c_str(), NAPI_AUTO_LENGTH, &cc); + return cc; +} + +static SecTypeJs ConvertKeyMgmtToSecType(const std::string& keyMgmt) +{ + std::map mapKeyMgmtToSecType = { + {KEY_MGMT_NONE, SecTypeJs::SEC_TYPE_OPEN}, + {KEY_MGMT_WEP, SecTypeJs::SEC_TYPE_WEP}, + {KEY_MGMT_WPA_PSK, SecTypeJs::SEC_TYPE_PSK}, + {KEY_MGMT_SAE, SecTypeJs::SEC_TYPE_SAE}, + {KEY_MGMT_EAP, SecTypeJs::SEC_TYPE_EAP}, + }; + + std::map::iterator iter = mapKeyMgmtToSecType.find(keyMgmt); + return iter == mapKeyMgmtToSecType.end() ? SecTypeJs::SEC_TYPE_OPEN : iter->second; +} + +static void IpConfigToJs(const napi_env& env, const WifiIpConfig& wifiIpConfig, napi_value& ipCfgObj) +{ + SetValueInt32(env, "ipAddress", wifiIpConfig.staticIpAddress.ipAddress.address.addressIpv4, ipCfgObj); + SetValueInt32(env, "gateway", wifiIpConfig.staticIpAddress.gateway.addressIpv4, ipCfgObj); + + const int DNS_NUM = 2; + napi_value dnsArray; + napi_create_array_with_length(env, DNS_NUM, &dnsArray); + std::vector vecDns = {wifiIpConfig.staticIpAddress.dnsServer1.addressIpv4, + wifiIpConfig.staticIpAddress.dnsServer2.addressIpv4}; + for (int i = 0; i != DNS_NUM; ++i) { + napi_value value; + napi_status status = napi_create_int32(env, vecDns[i], &value); + if (status != napi_ok) { + WIFI_LOGE("Ip config to js create int32 error!"); + return; + } + status = napi_set_element(env, dnsArray, i, value); + if (status != napi_ok) { + WIFI_LOGE("Ip config to js set element error: %{public}d", status); + return; + } + } + if (napi_set_named_property(env, ipCfgObj, "dnsServers", dnsArray) != napi_ok) { + WIFI_LOGE("Set dnsServers named property error!"); + } + + const int DOMAINS_NUM = 1; + napi_value domainsArray; + napi_create_array_with_length(env, DOMAINS_NUM, &domainsArray); + std::vector vecDomains = {wifiIpConfig.staticIpAddress.domains}; + for (int i = 0; i != DOMAINS_NUM; ++i) { + napi_value value; + napi_status status = napi_create_string_utf8(env, vecDomains[i].c_str(), NAPI_AUTO_LENGTH, &value); + if (status != napi_ok) { + WIFI_LOGE("Ip config to js create utf8 string error!"); + return; + } + status = napi_set_element(env, domainsArray, i, value); + if (status != napi_ok) { + WIFI_LOGE("Ip config to js set element error: %{public}d", status); + } + } + if (napi_set_named_property(env, ipCfgObj, "domains", domainsArray) != napi_ok) { + WIFI_LOGE("Set domains named property error!"); + } +} + +static void UpdateSecurityTypeAndPreSharedKey(WifiDeviceConfig& cppConfig) +{ + if (cppConfig.keyMgmt != KEY_MGMT_NONE) { + return; + } + for (int i = 0; i != WEPKEYS_SIZE; ++i) { + if (!cppConfig.wepKeys[i].empty() && cppConfig.wepTxKeyIndex == i) { + cppConfig.keyMgmt = KEY_MGMT_WEP; + cppConfig.preSharedKey = cppConfig.wepKeys[i]; + } + } +} + +static void DeviceConfigToJsArray(const napi_env& env, std::vector& vecDeviceConfigs, + const int idx, napi_value& arrayResult) +{ + UpdateSecurityTypeAndPreSharedKey(vecDeviceConfigs[idx]); + napi_value result; + napi_create_object(env, &result); + SetValueUtf8String(env, "ssid", vecDeviceConfigs[idx].ssid.c_str(), result); + SetValueUtf8String(env, "bssid", vecDeviceConfigs[idx].bssid.c_str(), result); + SetValueUtf8String(env, "preSharedKey", vecDeviceConfigs[idx].preSharedKey.c_str(), result); + SetValueBool(env, "isHiddenSsid", vecDeviceConfigs[idx].hiddenSSID, result); + SetValueInt32(env, "securityType", + static_cast(ConvertKeyMgmtToSecType(vecDeviceConfigs[idx].keyMgmt)), result); + SetValueInt32(env, "creatorUid", vecDeviceConfigs[idx].uid, result); + /* not supported currently */ + SetValueInt32(env, "disableReason", DEFAULT_INVALID_VALUE, result); + SetValueInt32(env, "netId", vecDeviceConfigs[idx].networkId, result); + /* not supported currently */ + SetValueInt32(env, "randomMacType", DEFAULT_INVALID_VALUE, result); + /* not supported currently */ + SetValueUtf8String(env, "randomMacAddr", std::string("").c_str(), result); + if (vecDeviceConfigs[idx].wifiIpConfig.assignMethod == AssignIpMethod::STATIC) { + SetValueInt32(env, "ipType", static_cast(IpTypeJs::IP_TYPE_STATIC), result); + } else { + SetValueInt32(env, "ipType", static_cast(IpTypeJs::IP_TYPE_DHCP), result); + } + napi_value ipCfgObj; + napi_create_object(env, &ipCfgObj); + IpConfigToJs(env, vecDeviceConfigs[idx].wifiIpConfig, ipCfgObj); + napi_status status = napi_set_named_property(env, result, "staticIp", ipCfgObj); + if (status != napi_ok) { + WIFI_LOGE("Set staticIp field!"); + } + status = napi_set_element(env, arrayResult, idx, result); + if (status != napi_ok) { + WIFI_LOGE("Wifi napi set element error: %{public}d", status); + } +} + +napi_value GetDeviceConfigs(napi_env env, napi_callback_info info) +{ + TRACE_FUNC_CALL; + WIFI_NAPI_ASSERT(env, wifiDevicePtr != nullptr, WIFI_OPT_FAILED, SYSCAP_WIFI_STA); + std::vector vecDeviceConfigs; + bool isCandidate = false; + ErrCode ret = wifiDevicePtr->GetDeviceConfigs(vecDeviceConfigs, isCandidate); + if (ret != WIFI_OPT_SUCCESS) { + WIFI_LOGE("Get device configs fail: %{public}d", ret); + } + + WIFI_NAPI_ASSERT(env, ret == WIFI_OPT_SUCCESS, ret, SYSCAP_WIFI_STA); + WIFI_LOGI("Get device configs size: %{public}zu", vecDeviceConfigs.size()); + napi_value arrayResult; + napi_create_array_with_length(env, vecDeviceConfigs.size(), &arrayResult); + for (size_t i = 0; i != vecDeviceConfigs.size(); ++i) { + DeviceConfigToJsArray(env, vecDeviceConfigs, i, arrayResult); + } + return arrayResult; +} + +napi_value GetCandidateConfigs(napi_env env, napi_callback_info info) +{ + TRACE_FUNC_CALL; + WIFI_NAPI_ASSERT(env, wifiDevicePtr != nullptr, WIFI_OPT_FAILED, SYSCAP_WIFI_STA); + std::vector vecDeviceConfigs; + bool isCandidate = true; + ErrCode ret = wifiDevicePtr->GetDeviceConfigs(vecDeviceConfigs, isCandidate); + if (ret != WIFI_OPT_SUCCESS) { + WIFI_LOGE("Get candidate device configs fail: %{public}d", ret); + } + + WIFI_NAPI_ASSERT(env, ret == WIFI_OPT_SUCCESS, ret, SYSCAP_WIFI_STA); + WIFI_LOGI("Get candidate device configs size: %{public}zu", vecDeviceConfigs.size()); + napi_value arrayResult; + napi_create_array_with_length(env, vecDeviceConfigs.size(), &arrayResult); + for (size_t i = 0; i != vecDeviceConfigs.size(); ++i) { + DeviceConfigToJsArray(env, vecDeviceConfigs, i, arrayResult); + } + return arrayResult; +} + +napi_value UpdateNetwork(napi_env env, napi_callback_info info) +{ + TRACE_FUNC_CALL; + size_t argc = 1; + napi_value argv[1]; + napi_value thisVar; + NAPI_CALL(env, napi_get_cb_info(env, info, &argc, argv, &thisVar, NULL)); + + napi_valuetype valueType; + napi_typeof(env, argv[0], &valueType); + WIFI_NAPI_ASSERT(env, valueType == napi_object, WIFI_OPT_INVALID_PARAM, SYSCAP_WIFI_STA); + + WIFI_NAPI_ASSERT(env, wifiDevicePtr != nullptr, WIFI_OPT_FAILED, SYSCAP_WIFI_STA); + int updateResult; + WifiDeviceConfig config; + JsObjToDeviceConfig(env, argv[0], config); + ErrCode ret = wifiDevicePtr->UpdateDeviceConfig(config, updateResult); + if (ret != WIFI_OPT_SUCCESS) { + WIFI_LOGE("Update device config fail: %{public}d", ret); + } + + WIFI_NAPI_ASSERT(env, ret == WIFI_OPT_SUCCESS, ret, SYSCAP_WIFI_STA); + napi_value result; + napi_create_uint32(env, updateResult, &result); + return result; +} + +napi_value GetSupportedFeatures(napi_env env, napi_callback_info info) +{ + TRACE_FUNC_CALL; + WIFI_NAPI_ASSERT(env, wifiDevicePtr != nullptr, WIFI_OPT_FAILED, SYSCAP_WIFI_CORE); + long features = -1; + ErrCode ret = wifiDevicePtr->GetSupportedFeatures(features); + if (ret != WIFI_OPT_SUCCESS) { + WIFI_LOGE("Get supported features fail: %{public}d", ret); + } + + WIFI_NAPI_ASSERT(env, ret == WIFI_OPT_SUCCESS, ret, SYSCAP_WIFI_CORE); + napi_value result; + napi_create_int64(env, features, &result); + return result; +} + +napi_value IsFeatureSupported(napi_env env, napi_callback_info info) +{ + TRACE_FUNC_CALL; + size_t argc = 1; + napi_value argv[1]; + napi_value thisVar; + NAPI_CALL(env, napi_get_cb_info(env, info, &argc, argv, &thisVar, NULL)); + WIFI_NAPI_ASSERT(env, argc == 1, WIFI_OPT_INVALID_PARAM, SYSCAP_WIFI_CORE); + + napi_valuetype valueType; + napi_typeof(env, argv[0], &valueType); + WIFI_NAPI_ASSERT(env, valueType == napi_number, WIFI_OPT_INVALID_PARAM, SYSCAP_WIFI_CORE); + + long feature = -1; + napi_get_value_int64(env, argv[0], (int64_t*)&feature); + WIFI_NAPI_ASSERT(env, wifiDevicePtr != nullptr, WIFI_OPT_FAILED, SYSCAP_WIFI_CORE); + + bool ret = wifiDevicePtr->IsFeatureSupported(feature); + WIFI_NAPI_RETURN(env, ret == WIFI_OPT_SUCCESS, ret, SYSCAP_WIFI_CORE); +} + +napi_value GetDeviceMacAddress(napi_env env, napi_callback_info info) +{ + TRACE_FUNC_CALL; + WIFI_NAPI_ASSERT(env, wifiDevicePtr != nullptr, WIFI_OPT_FAILED, SYSCAP_WIFI_STA); + std::string macAddr; + ErrCode ret = wifiDevicePtr->GetDeviceMacAddress(macAddr); + if (ret != WIFI_OPT_SUCCESS) { + WIFI_LOGE("Get mac address fail: %{public}d", ret); + } + + WIFI_NAPI_ASSERT(env, ret == WIFI_OPT_SUCCESS, ret, SYSCAP_WIFI_STA); + napi_value addr; + napi_create_string_utf8(env, macAddr.c_str(), NAPI_AUTO_LENGTH, &addr); + return addr; +} +} // namespace Wifi +} // namespace OHOS \ No newline at end of file diff --git a/interfaces/innerkits/native_cpp/napi/wifi_napi_entry.cpp b/wifi/frameworks/js/napi/src/wifi_napi_entry.cpp old mode 100755 new mode 100644 similarity index 31% rename from interfaces/innerkits/native_cpp/napi/wifi_napi_entry.cpp rename to wifi/frameworks/js/napi/src/wifi_napi_entry.cpp index b30880e02997707710b22e03b815d2177e89ef48..7db9218a8bc910f5ee79e3e938486f21c9f498d6 --- a/interfaces/innerkits/native_cpp/napi/wifi_napi_entry.cpp +++ b/wifi/frameworks/js/napi/src/wifi_napi_entry.cpp @@ -1,81 +1,151 @@ -/* - * Copyright (C) 2021 Huawei Device Co., Ltd. - * 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 "wifi_napi_device.h" -#include "wifi_napi_hotspot.h" -#include "wifi_napi_p2p.h" -#include "wifi_napi_event.h" -#include "wifi_logger.h" - -namespace OHOS { -namespace Wifi { -DEFINE_WIFILOG_LABEL("WifiNAPIEntry"); - -/* - * Event class initialization function - */ -static void InitEventClass(napi_env& env, napi_value& exports) { - const char className[] = "EventListener"; - napi_property_descriptor properties[] = { - DECLARE_NAPI_FUNCTION("on", On), - DECLARE_NAPI_FUNCTION("off", Off), - }; - - napi_value eventListenerClass = nullptr; - napi_define_class(env, className, sizeof(className), EventListenerConstructor, nullptr, - sizeof(properties) / sizeof(napi_property_descriptor), properties, &eventListenerClass); - napi_status status = napi_set_named_property(env, exports, "EventListener", eventListenerClass); - if (status != napi_ok) { - WIFI_LOGE("[Napi Entry] Init event class set property error."); - } -} - -/* - * Module initialization function - */ -static napi_value Init(napi_env env, napi_value exports) { - napi_property_descriptor desc[] = { - DECLARE_NAPI_FUNCTION("enableWifi", EnableWifi), - DECLARE_NAPI_FUNCTION("disableWifi", DisableWifi), - DECLARE_NAPI_FUNCTION("isWifiActive", IsWifiActive), - DECLARE_NAPI_FUNCTION("scan", Scan), - DECLARE_NAPI_FUNCTION("getScanInfos", GetScanInfos), - DECLARE_NAPI_FUNCTION("addDeviceConfig", AddDeviceConfig), - DECLARE_NAPI_FUNCTION("connectToNetwork", ConnectToNetwork), - DECLARE_NAPI_FUNCTION("connectToDevice", ConnectToDevice), - DECLARE_NAPI_FUNCTION("disconnect", Disconnect), - DECLARE_NAPI_FUNCTION("getSignalLevel", GetSignalLevel), - }; - - NAPI_CALL(env, napi_define_properties(env, exports, sizeof(desc) / sizeof(napi_property_descriptor), desc)); - InitEventClass(env, exports); - return exports; -} - -static napi_module wifiJsModule = { - .nm_version = 1, - .nm_flags = 0, - .nm_filename = NULL, - .nm_register_func = Init, - .nm_modname = "wifi_native_js", - .nm_priv = ((void *)0), - .reserved = { 0 } -}; - -extern "C" __attribute__((constructor)) void RegisterModule(void) { - napi_module_register(&wifiJsModule); -} -} // namespace Wifi -} // namespace OHOS +/* + * Copyright (C) 2021-2022 Huawei Device Co., Ltd. + * 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 "wifi_napi_device.h" +#include "wifi_napi_hotspot.h" +#include "wifi_napi_p2p.h" +#include "wifi_napi_event.h" +#include "wifi_logger.h" + +namespace OHOS { +namespace Wifi { +#ifndef ENABLE_NAPI_COMPATIBLE +/* + * Module initialization function + */ +static napi_value Init(napi_env env, napi_value exports) { + napi_property_descriptor desc[] = { + DECLARE_NAPI_FUNCTION("enableWifi", EnableWifi), + DECLARE_NAPI_FUNCTION("disableWifi", DisableWifi), + DECLARE_NAPI_FUNCTION("isWifiActive", IsWifiActive), + DECLARE_NAPI_FUNCTION("scan", Scan), + DECLARE_NAPI_FUNCTION("getScanInfos", GetScanInfos), + DECLARE_NAPI_FUNCTION("getScanInfosSync", GetScanResults), + DECLARE_NAPI_FUNCTION("addDeviceConfig", AddDeviceConfig), + DECLARE_NAPI_FUNCTION("addUntrustedConfig", AddUntrustedConfig), + DECLARE_NAPI_FUNCTION("removeUntrustedConfig", RemoveUntrustedConfig), + DECLARE_NAPI_FUNCTION("addCandidateConfig", AddCandidateConfig), + DECLARE_NAPI_FUNCTION("removeCandidateConfig", RemoveCandidateConfig), + DECLARE_NAPI_FUNCTION("connectToCandidateConfig", ConnectToCandidateConfig), + DECLARE_NAPI_FUNCTION("getCandidateConfigs", GetCandidateConfigs), + DECLARE_NAPI_FUNCTION("connectToNetwork", ConnectToNetwork), + DECLARE_NAPI_FUNCTION("connectToDevice", ConnectToDevice), + DECLARE_NAPI_FUNCTION("isConnected", IsConnected), + DECLARE_NAPI_FUNCTION("disconnect", Disconnect), + DECLARE_NAPI_FUNCTION("getSignalLevel", GetSignalLevel), + DECLARE_NAPI_FUNCTION("reconnect", ReConnect), + DECLARE_NAPI_FUNCTION("reassociate", ReAssociate), + DECLARE_NAPI_FUNCTION("getIpInfo", GetIpInfo), + DECLARE_NAPI_FUNCTION("getLinkedInfo", GetLinkedInfo), + DECLARE_NAPI_FUNCTION("removeDevice", RemoveDevice), + DECLARE_NAPI_FUNCTION("removeAllNetwork", RemoveAllNetwork), + DECLARE_NAPI_FUNCTION("disableNetwork", DisableNetwork), + DECLARE_NAPI_FUNCTION("getCountryCode", GetCountryCode), + DECLARE_NAPI_FUNCTION("getDeviceConfigs", GetDeviceConfigs), + DECLARE_NAPI_FUNCTION("updateNetwork", UpdateNetwork), + DECLARE_NAPI_FUNCTION("getSupportedFeatures", GetSupportedFeatures), + DECLARE_NAPI_FUNCTION("isFeatureSupported", IsFeatureSupported), + DECLARE_NAPI_FUNCTION("getDeviceMacAddress", GetDeviceMacAddress), + DECLARE_NAPI_FUNCTION("isHotspotActive", IsHotspotActive), + DECLARE_NAPI_FUNCTION("isHotspotDualBandSupported", IsHotspotDualBandSupported), + DECLARE_NAPI_FUNCTION("enableHotspot", EnableHotspot), + DECLARE_NAPI_FUNCTION("disableHotspot", DisableHotspot), + DECLARE_NAPI_FUNCTION("setHotspotConfig", SetHotspotConfig), + DECLARE_NAPI_FUNCTION("getHotspotConfig", GetHotspotConfig), + DECLARE_NAPI_FUNCTION("getStations", GetStations), + DECLARE_NAPI_FUNCTION("addBlockList", AddBlockList), + DECLARE_NAPI_FUNCTION("delBlockList", DelBlockList), + DECLARE_NAPI_FUNCTION("getP2pLinkedInfo", GetP2pLinkedInfo), + DECLARE_NAPI_FUNCTION("getCurrentGroup", GetCurrentGroup), + DECLARE_NAPI_FUNCTION("getP2pPeerDevices", GetP2pDevices), + DECLARE_NAPI_FUNCTION("getP2pLocalDevice", GetP2pLocalDevice), + DECLARE_NAPI_FUNCTION("createGroup", CreateGroup), + DECLARE_NAPI_FUNCTION("removeGroup", RemoveGroup), + DECLARE_NAPI_FUNCTION("p2pConnect", P2pConnect), + DECLARE_NAPI_FUNCTION("p2pCancelConnect", P2pCancelConnect), + DECLARE_NAPI_FUNCTION("p2pDisonnect", P2pCancelConnect), + DECLARE_NAPI_FUNCTION("startDiscoverDevices", StartDiscoverDevices), + DECLARE_NAPI_FUNCTION("stopDiscoverDevices", StopDiscoverDevices), + DECLARE_NAPI_FUNCTION("deletePersistentGroup", DeletePersistentGroup), + DECLARE_NAPI_FUNCTION("getP2pGroups", GetP2pGroups), + DECLARE_NAPI_FUNCTION("setDeviceName", SetDeviceName), + DECLARE_NAPI_FUNCTION("on", On), + DECLARE_NAPI_FUNCTION("off", Off), + }; + + NAPI_CALL(env, napi_define_properties(env, exports, sizeof(desc) / sizeof(napi_property_descriptor), desc)); + return exports; +} + +static napi_module wifiJsModule = { + .nm_version = 1, + .nm_flags = 0, + .nm_filename = NULL, + .nm_register_func = Init, +#ifdef ENABLE_NAPI_WIFI_MANAGER + .nm_modname = "wifiManager", +#else + .nm_modname = "wifi", +#endif + .nm_priv = ((void *)0), + .reserved = { 0 } +}; + +#else + +/* + * Module initialization function + */ +static napi_value InitForCompatible(napi_env env, napi_value exports) { + napi_property_descriptor desc[] = { + DECLARE_NAPI_FUNCTION("enableWifi", EnableWifi), + DECLARE_NAPI_FUNCTION("disableWifi", DisableWifi), + DECLARE_NAPI_FUNCTION("isWifiActive", IsWifiActive), + DECLARE_NAPI_FUNCTION("scan", Scan), + DECLARE_NAPI_FUNCTION("getScanInfos", GetScanInfos), + DECLARE_NAPI_FUNCTION("addDeviceConfig", AddDeviceConfig), + DECLARE_NAPI_FUNCTION("connectToNetwork", ConnectToNetwork), + DECLARE_NAPI_FUNCTION("connectToDevice", ConnectToDevice), + DECLARE_NAPI_FUNCTION("disconnect", Disconnect), + DECLARE_NAPI_FUNCTION("getSignalLevel", GetSignalLevel), + }; + + NAPI_CALL(env, napi_define_properties(env, exports, sizeof(desc) / sizeof(napi_property_descriptor), desc)); + return exports; +} + +/* @Deprecated - Changeme module name from "wifi_native_js" to "wifi", + * "wifi_native_js" will be discarded. Modify @11/2021 + */ +static napi_module wifiJsModuleForCompatible = { + .nm_version = 1, + .nm_flags = 0, + .nm_filename = NULL, + .nm_register_func = InitForCompatible, + .nm_modname = "wifi_native_js", + .nm_priv = ((void *)0), + .reserved = { 0 } +}; +#endif + +extern "C" __attribute__((constructor)) void RegisterModule(void) { +#ifndef ENABLE_NAPI_COMPATIBLE + napi_module_register(&wifiJsModule); +#else + napi_module_register(&wifiJsModuleForCompatible); +#endif +} +} // namespace Wifi +} // namespace OHOS diff --git a/wifi/frameworks/js/napi/src/wifi_napi_errcode.cpp b/wifi/frameworks/js/napi/src/wifi_napi_errcode.cpp new file mode 100644 index 0000000000000000000000000000000000000000..90c85c5c75dacaca62b9f31086166ab62e0d24cf --- /dev/null +++ b/wifi/frameworks/js/napi/src/wifi_napi_errcode.cpp @@ -0,0 +1,186 @@ +/* + * Copyright (C) 2022 Huawei Device Co., Ltd. + * 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 "wifi_napi_errcode.h" +#include +#include "wifi_logger.h" +#include "wifi_errcode.h" + +namespace OHOS { +namespace Wifi { +DEFINE_WIFILOG_LABEL("WifiNAPIErrCode"); +static std::map errCodeMap = { + { ErrCode::WIFI_OPT_SUCCESS, WifiNapiErrCode::WIFI_ERRCODE_SUCCESS }, + { ErrCode::WIFI_OPT_FAILED, WifiNapiErrCode::WIFI_ERRCODE_OPERATION_FAILED }, + { ErrCode::WIFI_OPT_NOT_SUPPORTED, WifiNapiErrCode::WIFI_ERRCODE_NOT_SUPPORTED }, + { ErrCode::WIFI_OPT_INVALID_PARAM, WifiNapiErrCode::WIFI_ERRCODE_INVALID_PARAM }, + { ErrCode::WIFI_OPT_FORBID_AIRPLANE, WifiNapiErrCode::WIFI_ERRCODE_OPERATION_FAILED }, + { ErrCode::WIFI_OPT_FORBID_POWSAVING, WifiNapiErrCode::WIFI_ERRCODE_OPERATION_FAILED}, + { ErrCode::WIFI_OPT_PERMISSION_DENIED, WifiNapiErrCode::WIFI_ERRCODE_PERMISSION_DENIED }, + { ErrCode::WIFI_OPT_OPEN_FAIL_WHEN_CLOSING, WifiNapiErrCode::WIFI_ERRCODE_OPEN_FAIL_WHEN_CLOSING }, + { ErrCode::WIFI_OPT_OPEN_SUCC_WHEN_OPENED, WifiNapiErrCode::WIFI_ERRCODE_CLOSE_FAIL_WHEN_OPENING }, + { ErrCode::WIFI_OPT_CLOSE_FAIL_WHEN_OPENING, WifiNapiErrCode::WIFI_ERRCODE_OPERATION_FAILED }, + { ErrCode::WIFI_OPT_CLOSE_SUCC_WHEN_CLOSED, WifiNapiErrCode::WIFI_ERRCODE_OPERATION_FAILED }, + { ErrCode::WIFI_OPT_STA_NOT_OPENED, WifiNapiErrCode::WIFI_ERRCODE_WIFI_NOT_OPENED }, + { ErrCode::WIFI_OPT_SCAN_NOT_OPENED, WifiNapiErrCode::WIFI_ERRCODE_OPERATION_FAILED }, + { ErrCode::WIFI_OPT_AP_NOT_OPENED, WifiNapiErrCode::WIFI_ERRCODE_OPERATION_FAILED }, + { ErrCode::WIFI_OPT_INVALID_CONFIG, WifiNapiErrCode::WIFI_ERRCODE_OPERATION_FAILED }, + { ErrCode::WIFI_OPT_P2P_NOT_OPENED, WifiNapiErrCode::WIFI_ERRCODE_WIFI_NOT_OPENED }, + { ErrCode::WIFI_OPT_P2P_MAC_NOT_FOUND, WifiNapiErrCode::WIFI_ERRCODE_OPERATION_FAILED }, + { ErrCode::WIFI_OPT_P2P_ERR_MAC_FORMAT, WifiNapiErrCode::WIFI_ERRCODE_OPERATION_FAILED }, + { ErrCode::WIFI_OPT_P2P_ERR_INTENT, WifiNapiErrCode::WIFI_ERRCODE_OPERATION_FAILED }, + { ErrCode::WIFI_OPT_P2P_ERR_SIZE_NW_NAME, WifiNapiErrCode::WIFI_ERRCODE_OPERATION_FAILED }, + { ErrCode::WIFI_OPT_MOVING_FREEZE_CTRL, WifiNapiErrCode::WIFI_ERRCODE_OPERATION_FAILED }, +}; + +static std::map napiErrMsgMap { + { WifiNapiErrCode::WIFI_ERRCODE_OPERATION_FAILED, "System exception." }, + { WifiNapiErrCode::WIFI_ERRCODE_WIFI_NOT_OPENED, "WIFI doesn't open." }, + { WifiNapiErrCode::WIFI_ERRCODE_PERMISSION_DENIED, "Permission denied." }, + { WifiNapiErrCode::WIFI_ERRCODE_INVALID_PARAM, "Parameter error." }, + { WifiNapiErrCode::WIFI_ERRCODE_NOT_SUPPORTED, "Capability not supported." }, + { WifiNapiErrCode::WIFI_ERRCODE_OPEN_FAIL_WHEN_CLOSING, "Failed for wifi is closing." }, + { WifiNapiErrCode::WIFI_ERRCODE_CLOSE_FAIL_WHEN_OPENING, "Failed for wifi is opening." }, +}; + +static napi_value NapiGetUndefined(const napi_env &env) +{ + napi_value undefined = nullptr; + napi_get_undefined(env, &undefined); + return undefined; +} + +static int32_t GetNapiErrCode(const napi_env &env, const int32_t errCodeIn) +{ + auto iter = errCodeMap.find(errCodeIn); + if (iter != errCodeMap.end()) { + return WifiNapiErrCode::WIFI_ERRCODE_OPERATION_FAILED; + } + return iter->second; +} + +static std::string GetNapiErrMsg(const napi_env &env, const int32_t errCode, int sysCap) +{ + if (errCode == ErrCode::WIFI_OPT_SUCCESS) { + return ""; + } + + int32_t napiErrCode = GetNapiErrCode(env, errCode); + auto iter = napiErrMsgMap.find(napiErrCode); + if (iter != napiErrMsgMap.end()) { + std::string errMessage = "BussinessError "; + napiErrCode += sysCap; + errMessage.append(std::to_string(napiErrCode)).append(": ").append(iter->second); + return errMessage; + } + return "Inner error."; +} + +#ifdef ENABLE_NAPI_WIFI_MANAGER +static napi_value NapiGetNull(const napi_env &env) +{ + napi_value res = nullptr; + napi_get_null(env, &res); + return res; +} + +static napi_value GetCallbackErrorValue(napi_env env, const int32_t errCode, const std::string errMsg) +{ + napi_value businessError = nullptr; + napi_value eCode = nullptr; + napi_value eMsg = nullptr; + NAPI_CALL(env, napi_create_int32(env, errCode, &eCode)); + NAPI_CALL(env, napi_create_string_utf8(env, errMsg.c_str(), errMsg.length(), &eMsg)); + NAPI_CALL(env, napi_create_object(env, &businessError)); + NAPI_CALL(env, napi_set_named_property(env, businessError, "code", eCode)); + NAPI_CALL(env, napi_set_named_property(env, businessError, "message", eMsg)); + return businessError; +} +#endif + +void HandleCallbackErrCode( const napi_env &env, const AsyncContext &info) +{ + WIFI_LOGI("HandleCallbackErrCode, errCode = %{public}d", (int)info.errorCode); + constexpr int RESULT_PARAMS_NUM = 2; + napi_value undefine = NapiGetUndefined(env); + napi_value callback = nullptr; + napi_value result[RESULT_PARAMS_NUM] = {nullptr}; + result[1] = info.result; + if (info.errorCode == ErrCode::WIFI_OPT_SUCCESS) { +#ifdef ENABLE_NAPI_WIFI_MANAGER + result[0] = NapiGetUndefined(env); +#else + napi_create_uint32(env, info.errorCode, &result[0]); + napi_get_reference_value(env, info.callback[0], &callback); +#endif + napi_call_function(env, nullptr, callback, RESULT_PARAMS_NUM, result, &undefine); + } else { + napi_ref errCb = info.callback[1]; + if (!errCb) { + WIFI_LOGE("Get callback func[1] is null"); + errCb = info.callback[0]; + } + napi_get_reference_value(env, errCb, &callback); +#ifdef ENABLE_NAPI_WIFI_MANAGER + std::string errMsg = GetNapiErrMsg(env, info.errorCode, info.sysCap); + int32_t errCodeInfo = GetNapiErrCode(env, info.errorCode) + info.sysCap; + result[0] = GetCallbackErrorValue(env, errCodeInfo, errMsg); +#else + napi_create_uint32(env, info.errorCode, &result[0]); +#endif + napi_call_function(env, nullptr, callback, RESULT_PARAMS_NUM, result, &undefine); + } +} + +void HandlePromiseErrCode( const napi_env &env, const AsyncContext &info) +{ + WIFI_LOGI("HandlePromiseErrCode, errCode = %{public}d", (int)info.errorCode); + if (info.errorCode == ErrCode::WIFI_OPT_SUCCESS) { + napi_resolve_deferred(env, info.deferred, info.result); + } else { +#ifdef ENABLE_NAPI_WIFI_MANAGER + int32_t errCodeInfo = info.sysCap + GetNapiErrCode(env, info.errorCode); + std::string errMsg = GetNapiErrMsg(env, info.errorCode, info.sysCap); + napi_value businessError = nullptr; + napi_value eCode = nullptr; + napi_value eMsg = nullptr; + napi_value eData = NapiGetNull(env); + napi_create_int32(env, errCodeInfo, &eCode); + napi_create_string_utf8(env, errMsg.c_str(), errMsg.length(), &eMsg); + napi_create_object(env, &businessError); + napi_set_named_property(env, businessError, "code", eCode); + napi_set_named_property(env, businessError, "message", eMsg); + napi_set_named_property(env, businessError, "data", eData); + napi_reject_deferred(env, info.deferred, businessError); +#else + napi_reject_deferred(info.env, info.deferred, info.result); +#endif + } +} + +void HandleSyncErrCode(const napi_env &env, int32_t errCode, int32_t sysCap) +{ + WIFI_LOGI("HandleSyncErrCode, errCode = %{public}d", (int)errCode); + if (errCode == ErrCode::WIFI_OPT_SUCCESS) { + return; + } + std::string errMsg = GetNapiErrMsg(env, errCode, sysCap); + int32_t errCodeInfo = sysCap + GetNapiErrCode(env, errCode); + if (errMsg != "") { + napi_throw_error(env, std::to_string(errCodeInfo).c_str(), errMsg.c_str()); + } +} +} // namespace Wifi +} // namespace OHOS diff --git a/wifi/frameworks/js/napi/src/wifi_napi_event.cpp b/wifi/frameworks/js/napi/src/wifi_napi_event.cpp new file mode 100644 index 0000000000000000000000000000000000000000..88f365738587281381d7ab071de2ef5d8cb4d93f --- /dev/null +++ b/wifi/frameworks/js/napi/src/wifi_napi_event.cpp @@ -0,0 +1,745 @@ +/* + * Copyright (C) 2021-2022 Huawei Device Co., Ltd. + * 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 "wifi_napi_event.h" +#include +#include "accesstoken_kit.h" +#include "ipc_skeleton.h" +#include "wifi_device.h" +#include "wifi_logger.h" +#include "wifi_napi_utils.h" +#include "wifi_scan.h" +#include "wifi_napi_errcode.h" + +namespace OHOS { +namespace Wifi { +DEFINE_WIFILOG_LABEL("WifiNAPIEvent"); + +/* Events definition */ +const std::string EVENT_STA_POWER_STATE_CHANGE = "wifiStateChange"; +const std::string EVENT_STA_CONN_STATE_CHANGE = "wifiConnectionChange"; +const std::string EVENT_STA_SCAN_STATE_CHANGE = "wifiScanStateChange"; +const std::string EVENT_STA_RSSI_STATE_CHANGE = "wifiRssiChange"; +const std::string EVENT_STA_DEVICE_CONFIG_CHANGE = "deviceConfigChange"; +const std::string EVENT_HOTSPOT_STATE_CHANGE = "hotspotStateChange"; +const std::string EVENT_HOTSPOT_STA_JOIN = "hotspotStaJoin"; +const std::string EVENT_HOTSPOT_STA_LEAVE = "hotspotStaLeave"; +const std::string EVENT_P2P_STATE_CHANGE = "p2pStateChange"; +const std::string EVENT_P2P_CONN_STATE_CHANGE = "p2pConnectionChange"; +const std::string EVENT_P2P_DEVICE_STATE_CHANGE = "p2pDeviceChange"; +const std::string EVENT_P2P_PERSISTENT_GROUP_CHANGE = "p2pPersistentGroupChange"; +const std::string EVENT_P2P_PEER_DEVICE_CHANGE = "p2pPeerDeviceChange"; +const std::string EVENT_P2P_DISCOVERY_CHANGE = "p2pDiscoveryChange"; +const std::string EVENT_STREAM_CHANGE = "streamChange"; + +/* Permissions definition */ +const std::string WIFI_PERMISSION_GET_WIFI_INFO = "ohos.permission.GET_WIFI_INFO"; +const std::string WIFI_PERMISSION_SET_WIFI_INFO = "ohos.permission.SET_WIFI_INFO"; +const std::string WIFI_PERMISSION_GET_WIFI_CONFIG = "ohos.permission.GET_WIFI_CONFIG"; +const std::string WIFI_PERMISSION_MANAGE_WIFI_CONNECTION = "ohos.permission.MANAGE_WIFI_CONNECTION"; +const std::string WIFI_PERMISSION_MANAGE_WIFI_HOTSPOT = "ohos.permission.MANAGE_WIFI_HOTSPOT"; +const std::string WIFI_PERMISSION_GET_WIFI_LOCAL_MAC = "ohos.permission.GET_WIFI_LOCAL_MAC"; +const std::string WIFI_PERMISSION_LOCATION = "ohos.permission.LOCATION"; +const std::string WIFI_PERMISSION_GET_WIFI_INFO_INTERNAL = "ohos.permission.GET_WIFI_INFO_INTERNAL"; +const int WIFI_NAPI_PERMISSION_DENIED = 0; +const int WIFI_NAPI_PERMISSION_GRANTED = 1; + +constexpr uint32_t INVALID_REF_COUNT = 0xff; + +static std::set g_supportEventList = { + EVENT_STA_POWER_STATE_CHANGE, + EVENT_STA_CONN_STATE_CHANGE, + EVENT_STA_SCAN_STATE_CHANGE, + EVENT_STA_RSSI_STATE_CHANGE, + EVENT_STA_DEVICE_CONFIG_CHANGE, + EVENT_HOTSPOT_STATE_CHANGE, + EVENT_HOTSPOT_STA_JOIN, + EVENT_HOTSPOT_STA_LEAVE, + EVENT_P2P_STATE_CHANGE, + EVENT_P2P_CONN_STATE_CHANGE, + EVENT_P2P_DEVICE_STATE_CHANGE, + EVENT_P2P_PERSISTENT_GROUP_CHANGE, + EVENT_P2P_PEER_DEVICE_CHANGE, + EVENT_P2P_DISCOVERY_CHANGE, +}; + +std::multimap g_EventPermissionMap = { + { EVENT_STA_POWER_STATE_CHANGE, WIFI_PERMISSION_GET_WIFI_INFO }, + { EVENT_STA_CONN_STATE_CHANGE, WIFI_PERMISSION_GET_WIFI_INFO }, + { EVENT_STA_SCAN_STATE_CHANGE, WIFI_PERMISSION_GET_WIFI_INFO }, + { EVENT_STA_RSSI_STATE_CHANGE, WIFI_PERMISSION_GET_WIFI_INFO }, + { EVENT_STA_DEVICE_CONFIG_CHANGE, WIFI_PERMISSION_GET_WIFI_INFO }, + { EVENT_HOTSPOT_STATE_CHANGE, WIFI_PERMISSION_GET_WIFI_INFO }, + { EVENT_HOTSPOT_STA_JOIN, WIFI_PERMISSION_MANAGE_WIFI_HOTSPOT }, + { EVENT_HOTSPOT_STA_LEAVE, WIFI_PERMISSION_MANAGE_WIFI_HOTSPOT }, + { EVENT_P2P_STATE_CHANGE, WIFI_PERMISSION_GET_WIFI_INFO }, + { EVENT_P2P_CONN_STATE_CHANGE, WIFI_PERMISSION_GET_WIFI_INFO }, + { EVENT_P2P_DEVICE_STATE_CHANGE, WIFI_PERMISSION_GET_WIFI_INFO }, + { EVENT_P2P_DEVICE_STATE_CHANGE, WIFI_PERMISSION_LOCATION }, + { EVENT_P2P_DEVICE_STATE_CHANGE, WIFI_PERMISSION_GET_WIFI_INFO_INTERNAL }, + { EVENT_P2P_PERSISTENT_GROUP_CHANGE, WIFI_PERMISSION_GET_WIFI_INFO }, + { EVENT_P2P_PEER_DEVICE_CHANGE, WIFI_PERMISSION_GET_WIFI_INFO }, + { EVENT_P2P_PEER_DEVICE_CHANGE, WIFI_PERMISSION_LOCATION }, + { EVENT_P2P_PEER_DEVICE_CHANGE, WIFI_PERMISSION_GET_WIFI_INFO_INTERNAL }, + { EVENT_P2P_DISCOVERY_CHANGE, WIFI_PERMISSION_GET_WIFI_INFO }, + { EVENT_STREAM_CHANGE, WIFI_PERMISSION_MANAGE_WIFI_CONNECTION }, +}; + +std::map g_EventSysCapMap = { + { EVENT_STA_POWER_STATE_CHANGE, SYSCAP_WIFI_STA }, + { EVENT_STA_CONN_STATE_CHANGE, SYSCAP_WIFI_STA }, + { EVENT_STA_SCAN_STATE_CHANGE, SYSCAP_WIFI_STA }, + { EVENT_STA_RSSI_STATE_CHANGE, SYSCAP_WIFI_STA }, + { EVENT_STA_DEVICE_CONFIG_CHANGE, SYSCAP_WIFI_STA }, + { EVENT_HOTSPOT_STATE_CHANGE, SYSCAP_WIFI_AP_CORE }, + { EVENT_HOTSPOT_STA_JOIN, SYSCAP_WIFI_AP_CORE }, + { EVENT_HOTSPOT_STA_LEAVE, SYSCAP_WIFI_AP_CORE }, + { EVENT_P2P_STATE_CHANGE, SYSCAP_WIFI_P2P }, + { EVENT_P2P_CONN_STATE_CHANGE, SYSCAP_WIFI_P2P }, + { EVENT_P2P_DEVICE_STATE_CHANGE, SYSCAP_WIFI_P2P }, + { EVENT_P2P_PERSISTENT_GROUP_CHANGE, SYSCAP_WIFI_P2P }, + { EVENT_P2P_PEER_DEVICE_CHANGE, SYSCAP_WIFI_P2P }, + { EVENT_P2P_DISCOVERY_CHANGE, SYSCAP_WIFI_P2P }, + { EVENT_STREAM_CHANGE, SYSCAP_WIFI_P2P }, +}; + +void NapiEvent::EventNotify(AsyncEventData *asyncEvent) +{ + WIFI_LOGI("Enter wifi event notify"); + uv_loop_s* loop = nullptr; + napi_get_uv_event_loop(asyncEvent->env, &loop); + + uv_work_t* work = new uv_work_t; + if (work == nullptr) { + WIFI_LOGE("uv_work_t work is null."); + delete asyncEvent; + asyncEvent = nullptr; + return; + } + + uint32_t refCount = INVALID_REF_COUNT; + napi_reference_ref(asyncEvent->env, asyncEvent->callbackRef, &refCount); + work->data = asyncEvent; + WIFI_LOGI("event notify, env: %{private}p, callbackRef: %{private}p, refCount: %{public}d", + asyncEvent->env, asyncEvent->callbackRef, refCount); + uv_queue_work( + loop, + work, + [](uv_work_t* work) {}, + [](uv_work_t* work, int status) { + AsyncEventData *asyncData = static_cast(work->data); + WIFI_LOGI("uv_queue_work, env: %{private}p, status: %{public}d", asyncData->env, status); + napi_value handler = nullptr; + napi_handle_scope scope = nullptr; + napi_value jsEvent = nullptr; + uint32_t refCount = INVALID_REF_COUNT; + napi_open_handle_scope(asyncData->env, &scope); + if (scope == nullptr) { + WIFI_LOGE("scope is nullptr"); + goto EXIT; + } + napi_get_reference_value(asyncData->env, asyncData->callbackRef, &handler); + if (handler == nullptr) { + WIFI_LOGE("handler is nullptr"); + goto EXIT; + } + napi_value undefine; + napi_get_undefined(asyncData->env, &undefine); + jsEvent = asyncData->packResult(); + WIFI_LOGI("Push event to js, env: %{private}p, ref : %{private}p", asyncData->env, &asyncData->callbackRef); + if (napi_call_function(asyncData->env, nullptr, handler, 1, &jsEvent, &undefine) != napi_ok) { + WIFI_LOGE("Report event to Js failed"); + } + + EXIT: + napi_close_handle_scope(asyncData->env, scope); + napi_reference_unref(asyncData->env, asyncData->callbackRef, &refCount); + WIFI_LOGI("uv_queue_work unref, env: %{private}p, callbackRef: %{private}p, refCount: %{public}d", + asyncData->env, asyncData->callbackRef, refCount); + if (refCount == 0) { + napi_delete_reference(asyncData->env, asyncData->callbackRef); + } + delete asyncData; + delete work; + asyncData = nullptr; + work = nullptr; + } + ); +} + +napi_value NapiEvent::CreateResult(const napi_env& env, int value) +{ + napi_value result; + napi_create_int32(env, value, &result); + return result; +} + +napi_value NapiEvent::CreateResult(const napi_env& env, const StationInfo& info) +{ + napi_value result; + napi_create_object(env, &result); + SetValueUtf8String(env, "name", info.deviceName.c_str(), result); + SetValueUtf8String(env, "macAddress", info.bssid.c_str(), result); + SetValueUtf8String(env, "ipAddress", info.ipAddr.c_str(), result); + return result; +} + +napi_value NapiEvent::CreateResult(const napi_env& env, const WifiP2pDevice& device) +{ + napi_value result; + napi_create_object(env, &result); + SetValueUtf8String(env, "deviceName", device.GetDeviceName().c_str(), result); + SetValueUtf8String(env, "deviceAddress", device.GetDeviceAddress().c_str(), result); + SetValueUtf8String(env, "primaryDeviceType", device.GetPrimaryDeviceType().c_str(), result); + SetValueInt32(env, "devStatus", static_cast(device.GetP2pDeviceStatus()), result); + SetValueInt32(env, "groupCapability", device.GetGroupCapabilitys(), result); + return result; +} + +napi_value NapiEvent::CreateResult(const napi_env& env, const std::vector& devices) +{ + uint32_t idx = 0; + napi_value arrayResult; + napi_create_array_with_length(env, devices.size(), &arrayResult); + for (auto& each : devices) { + if (napi_set_element(env, arrayResult, idx++, CreateResult(env, each)) != napi_ok) { + WIFI_LOGE("Array result set element error, idx: %{public}u", idx - 1); + } + } + return arrayResult; +} + +napi_value NapiEvent::CreateResult(const napi_env& env, const WifiP2pLinkedInfo& info) +{ + napi_value result; + napi_create_object(env, &result); + SetValueInt32(env, "connectState", static_cast(info.GetConnectState()), result); + SetValueBool(env, "isGroupOwner", info.IsGroupOwner(), result); + SetValueUtf8String(env, "groupOwnerAddr", info.GetGroupOwnerAddress().c_str(), result); + return result; +} + +napi_value NapiEvent::NapiEvent::CreateResult(const napi_env& env, napi_value placehoders) +{ + return placehoders == nullptr ? UndefinedNapiValue(env) : placehoders; +} + +class WifiNapiDeviceEventCallback : public IWifiDeviceCallBack, public NapiEvent { +public: + WifiNapiDeviceEventCallback() { + } + + virtual ~WifiNapiDeviceEventCallback() { + } + +public: + void OnWifiStateChanged(int state) override { + WIFI_LOGI("sta received state changed event: %{public}d", state); + if (m_wifiStateConvertMap.find(state) == m_wifiStateConvertMap.end()) { + return; + } + CheckAndNotify(EVENT_STA_POWER_STATE_CHANGE, m_wifiStateConvertMap[state]); + } + + void OnWifiConnectionChanged(int state, const WifiLinkedInfo &info) override { + WIFI_LOGI("sta received connection changed event: %{public}d", state); + if (m_connectStateConvertMap.find(state) == m_connectStateConvertMap.end()) { + return; + } + CheckAndNotify(EVENT_STA_CONN_STATE_CHANGE, m_connectStateConvertMap[state]); + } + + void OnWifiRssiChanged(int rssi) override { + WIFI_LOGI("sta received rssi changed event: %{public}d", rssi); + CheckAndNotify(EVENT_STA_RSSI_STATE_CHANGE, rssi); + } + + void OnWifiWpsStateChanged(int state, const std::string &pinCode) override { + } + + void OnStreamChanged(int direction) override { + } + + void OnDeviceConfigChanged(ConfigChange value) override { + WIFI_LOGI("sta received device config changed event: %{public}d", static_cast(value)); + CheckAndNotify(EVENT_STA_DEVICE_CONFIG_CHANGE, static_cast(value)); + } + + OHOS::sptr AsObject() override { + return nullptr; + } + +private: + enum class JsLayerWifiState { + DISABLED = 0, + ENABLED = 1, + ENABLING = 2, + DISABLING = 3 + }; + + enum class JsLayerConnectStatus { + DISCONNECTED = 0, + CONNECTED = 1, + }; + + std::map m_wifiStateConvertMap = { + { static_cast(WifiState::DISABLING), static_cast(JsLayerWifiState::DISABLING) }, + { static_cast(WifiState::DISABLED), static_cast(JsLayerWifiState::DISABLED) }, + { static_cast(WifiState::ENABLING), static_cast(JsLayerWifiState::ENABLING) }, + { static_cast(WifiState::ENABLED), static_cast(JsLayerWifiState::ENABLED) }, + }; + + std::map m_connectStateConvertMap = { + { static_cast(ConnState::CONNECTED), static_cast(JsLayerConnectStatus::CONNECTED) }, + { static_cast(ConnState::DISCONNECTED), static_cast(JsLayerConnectStatus::DISCONNECTED) }, + }; +}; + +class WifiNapiScanEventCallback : public IWifiScanCallback, public NapiEvent { +public: + WifiNapiScanEventCallback() { + } + + virtual ~WifiNapiScanEventCallback() { + } + +public: + void OnWifiScanStateChanged(int state) override { + WIFI_LOGI("scan received state changed event: %{public}d", state); + CheckAndNotify(EVENT_STA_SCAN_STATE_CHANGE, state); + } + + OHOS::sptr AsObject() override { + return nullptr; + } +}; + +class WifiNapiHotspotEventCallback : public IWifiHotspotCallback, public NapiEvent { +public: + WifiNapiHotspotEventCallback() { + } + + virtual ~WifiNapiHotspotEventCallback() { + } + +public: + void OnHotspotStateChanged(int state) override { + WIFI_LOGI("Hotspot received state changed event: %{public}d", state); + if (m_apStateConvertMap.find(state) == m_apStateConvertMap.end()) { + return; + } + + CheckAndNotify(EVENT_HOTSPOT_STATE_CHANGE, m_apStateConvertMap[state]); + } + + void OnHotspotStaJoin(const StationInfo &info) override { + WIFI_LOGI("Hotspot received sta join event"); + CheckAndNotify(EVENT_HOTSPOT_STA_JOIN, info); + } + + void OnHotspotStaLeave(const StationInfo &info) override { + WIFI_LOGI("Hotspot received sta leave event"); + CheckAndNotify(EVENT_HOTSPOT_STA_LEAVE, info); + } + + OHOS::sptr AsObject() override { + return nullptr; + } + +private: + enum class JsLayerApState { + DISABLED = 0, + ENABLED = 1, + ENABLING = 2, + DISABLING = 3 + }; + + std::map m_apStateConvertMap = { + { static_cast(ApState::AP_STATE_STARTING), static_cast(JsLayerApState::ENABLING) }, + { static_cast(ApState::AP_STATE_STARTED), static_cast(JsLayerApState::ENABLED) }, + { static_cast(ApState::AP_STATE_CLOSING), static_cast(JsLayerApState::DISABLING) }, + { static_cast(ApState::AP_STATE_CLOSED), static_cast(JsLayerApState::DISABLED) }, + }; +}; + +class WifiNapiP2pEventCallback : public IWifiP2pCallback, public NapiEvent { +public: + WifiNapiP2pEventCallback() { + } + + virtual ~WifiNapiP2pEventCallback() { + } + +public: + void OnP2pStateChanged(int state) override { + WIFI_LOGI("received p2p state changed event: %{public}d", state); + CheckAndNotify(EVENT_P2P_STATE_CHANGE, state); + } + + void OnP2pPersistentGroupsChanged(void) override { + WIFI_LOGI("received persistent group changed event"); + CheckAndNotify(EVENT_P2P_PERSISTENT_GROUP_CHANGE, nullptr); + } + + void OnP2pThisDeviceChanged(const WifiP2pDevice& device) override { + WIFI_LOGI("received this device changed event"); + CheckAndNotify(EVENT_P2P_DEVICE_STATE_CHANGE, device); + } + + void OnP2pPeersChanged(const std::vector& devices) override { + WIFI_LOGI("received peers changed event: %{public}d", (int)devices.size()); + CheckAndNotify(EVENT_P2P_PEER_DEVICE_CHANGE, devices); + } + + void OnP2pServicesChanged(const std::vector& srvInfo) override { + } + + void OnP2pConnectionChanged(const WifiP2pLinkedInfo& info) override { + WIFI_LOGI("received connection changed event"); + CheckAndNotify(EVENT_P2P_CONN_STATE_CHANGE, info); + } + + void OnP2pDiscoveryChanged(bool isChange) override { + WIFI_LOGI("received discovery state changed event"); + CheckAndNotify(EVENT_P2P_DISCOVERY_CHANGE, (int)isChange); + } + + void OnP2pActionResult(P2pActionCallback action, ErrCode code) override { + } + + void OnConfigChanged(CfgType type, char* data, int dataLen) override { + } + + OHOS::sptr AsObject() override { + return nullptr; + } +}; + +napi_value On(napi_env env, napi_callback_info cbinfo) { + TRACE_FUNC_CALL; + size_t requireArgc = 2; + size_t argc = 2; + napi_value argv[2] = {0}; + napi_value thisVar = 0; + napi_get_cb_info(env, cbinfo, &argc, argv, &thisVar, nullptr); + NAPI_ASSERT(env, argc >= requireArgc, "requires 2 parameter"); + + napi_valuetype eventName = napi_undefined; + napi_typeof(env, argv[0], &eventName); + NAPI_ASSERT(env, eventName == napi_string, "type mismatch for parameter 1"); + + napi_valuetype handler = napi_undefined; + napi_typeof(env, argv[1], &handler); + NAPI_ASSERT(env, handler == napi_function, "type mismatch for parameter 2"); + + char type[64] = {0}; + size_t typeLen = 0; + napi_get_value_string_utf8(env, argv[0], type, sizeof(type), &typeLen); + EventRegister::GetInstance().Register(env, type, argv[1]); + napi_value result = nullptr; + napi_get_undefined(env, &result); + return result; +} + +napi_value Off(napi_env env, napi_callback_info cbinfo) { + TRACE_FUNC_CALL; + size_t requireArgc = 1; + size_t requireArgcWithCb = 2; + size_t argc = 2; + napi_value argv[2] = {0}; + napi_value thisVar = 0; + napi_get_cb_info(env, cbinfo, &argc, argv, &thisVar, nullptr); + NAPI_ASSERT(env, argc >= requireArgc, "requires at least 1 parameter"); + + napi_valuetype eventName = napi_undefined; + napi_typeof(env, argv[0], &eventName); + NAPI_ASSERT(env, eventName == napi_string, "type mismatch for parameter 1"); + + if (argc >= requireArgcWithCb) { + napi_valuetype handler = napi_undefined; + napi_typeof(env, argv[1], &handler); + NAPI_ASSERT(env, handler == napi_function, "type mismatch for parameter 2"); + } + + char type[64] = {0}; + size_t typeLen = 0; + napi_get_value_string_utf8(env, argv[0], type, sizeof(type), &typeLen); + EventRegister::GetInstance().Unregister(env, type, argc >= requireArgcWithCb ? argv[1] : nullptr); + napi_value result = nullptr; + napi_get_undefined(env, &result); + return result; +} + +static int32_t findSysCap(const std::string& type) +{ + int32_t sysCap = SYSCAP_WIFI_STA; + auto iter = g_EventSysCapMap.find(type); + if (iter == g_EventSysCapMap.end()) { + WIFI_LOGI("findSysCap, type:%{public}s, DO NOT find sysCap.", type.c_str()); + return sysCap; + } + sysCap = iter->second; + return sysCap; +} + +sptr wifiDeviceCallback = + sptr(new (std::nothrow) WifiNapiDeviceEventCallback()); + +sptr wifiScanCallback = + sptr(new (std::nothrow) WifiNapiScanEventCallback()); + +sptr wifiHotspotCallback = + sptr(new (std::nothrow) WifiNapiHotspotEventCallback()); + +sptr wifiP2pCallback = + sptr(new (std::nothrow) WifiNapiP2pEventCallback()); + +bool EventRegister::isEventRegistered = false; + +ErrCode EventRegister::RegisterWifiEvents() +{ + std::unique_ptr wifiStaPtr = WifiDevice::GetInstance(WIFI_DEVICE_ABILITY_ID); + if (wifiStaPtr == nullptr) { + WIFI_LOGE("Register sta event get instance failed!"); + return WIFI_OPT_FAILED; + } + ErrCode ret = wifiStaPtr->RegisterCallBack(wifiDeviceCallback); + if (ret != WIFI_OPT_SUCCESS) { + WIFI_LOGE("Register sta event failed!"); + return ret; + } + + std::unique_ptr wifiScanPtr = WifiScan::GetInstance(WIFI_SCAN_ABILITY_ID); + if (wifiScanPtr == nullptr) { + WIFI_LOGE("Register scan event get instance failed!"); + return WIFI_OPT_FAILED; + } + ret = wifiScanPtr->RegisterCallBack(wifiScanCallback); + if (ret != WIFI_OPT_SUCCESS) { + WIFI_LOGE("Register scan event failed!"); + return ret; + } + + std::unique_ptr wifiHotspotPtr = WifiHotspot::GetInstance(WIFI_HOTSPOT_ABILITY_ID); + if (wifiHotspotPtr == nullptr) { + WIFI_LOGE("Register hotspot event get instance failed!"); + return WIFI_OPT_FAILED; + } + ret = wifiHotspotPtr->RegisterCallBack(wifiHotspotCallback); + if (ret != WIFI_OPT_SUCCESS) { + WIFI_LOGE("Register hotspot event failed!"); + return ret; + } + + std::unique_ptr wifiP2pPtr = WifiP2p::GetInstance(WIFI_P2P_ABILITY_ID); + if (wifiP2pPtr == nullptr) { + WIFI_LOGE("Register p2p event get instance failed!"); + return WIFI_OPT_FAILED; + } + ret = wifiP2pPtr->RegisterCallBack(wifiP2pCallback); + if (ret != WIFI_OPT_SUCCESS) { + WIFI_LOGE("Register p2p event failed!"); + return ret; + } + return ret; +} + +EventRegister& EventRegister::GetInstance() +{ + static EventRegister inst; + return inst; +} + +bool EventRegister::IsEventSupport(const std::string& type) +{ + return g_supportEventList.find(type) != g_supportEventList.end(); +} + +int EventRegister::CheckPermission(const std::string& eventType) +{ + auto callerToken = IPCSkeleton::GetCallingTokenID(); + auto tokenType = Security::AccessToken::AccessTokenKit::GetTokenTypeFlag(callerToken); + if (tokenType == Security::AccessToken::ATokenTypeEnum::TOKEN_NATIVE) { + return WIFI_NAPI_PERMISSION_GRANTED; + } + + if (tokenType != Security::AccessToken::ATokenTypeEnum::TOKEN_HAP) { + WIFI_LOGE("Invalid tokenType=%{public}x, permission denied!", tokenType); + return WIFI_NAPI_PERMISSION_DENIED; + } + + std::multimap *permissions = &g_EventPermissionMap; + size_t count = permissions->count(eventType); + if (count <= 0) { + WIFI_LOGE("NO permission defined for tokenType=%{public}x !", tokenType); + return WIFI_NAPI_PERMISSION_DENIED; + } + + std::string permissionName; + int hasPermission = 1; + std::multimap::iterator it = permissions->find(eventType); + for (size_t i = 0; i < count; i++) { + permissionName = (*(it++)).second; + int res = Security::AccessToken::AccessTokenKit::VerifyAccessToken(callerToken, permissionName); + if (permissionName.compare(WIFI_PERMISSION_GET_WIFI_INFO_INTERNAL) == 0) { + if (res == Security::AccessToken::PermissionState::PERMISSION_GRANTED) { + return WIFI_NAPI_PERMISSION_GRANTED; + } + /* NO permission */ + WIFI_LOGE("callerToken=0x%{public}x has no permission=%{public}s", + callerToken, permissionName.c_str()); + return WIFI_NAPI_PERMISSION_DENIED; + } + + if (res != Security::AccessToken::PermissionState::PERMISSION_GRANTED) { + WIFI_LOGW("callerToken=0x%{public}x has no permission=%{public}s", + callerToken, permissionName.c_str()); + hasPermission = 0; + } + } + + return ((hasPermission == 1) ? WIFI_NAPI_PERMISSION_GRANTED : WIFI_NAPI_PERMISSION_DENIED); +} + +void EventRegister::Register(const napi_env& env, const std::string& type, napi_value handler) +{ + int32_t sysCap = findSysCap(type); + WIFI_LOGI("Register event: %{public}s, env: %{private}p, %{public}d.", + type.c_str(), env, (int)sysCap); + if (!IsEventSupport(type)) { + WIFI_LOGE("Register type error or not support!"); +#ifdef ENABLE_NAPI_WIFI_MANAGER + HandleSyncErrCode(env, WIFI_OPT_NOT_SUPPORTED, sysCap); +#endif + return; + } + if (CheckPermission(type) != WIFI_NAPI_PERMISSION_GRANTED) { + WIFI_LOGE("Register fail for NO permission!"); +#ifdef ENABLE_NAPI_WIFI_MANAGER + HandleSyncErrCode(env, WIFI_OPT_PERMISSION_DENIED, sysCap); +#endif + return; + } + std::unique_lock guard(g_regInfoMutex); + if (!isEventRegistered) { + ErrCode ret = RegisterWifiEvents(); + if (ret != WIFI_OPT_SUCCESS) { +#ifdef ENABLE_NAPI_WIFI_MANAGER + HandleSyncErrCode(env, ret, sysCap); +#endif + return; + } + isEventRegistered = true; + } + napi_ref handlerRef = nullptr; + napi_create_reference(env, handler, 1, &handlerRef); + RegObj regObj(env, handlerRef); + auto iter = g_eventRegisterInfo.find(type); + if (iter == g_eventRegisterInfo.end()) { + g_eventRegisterInfo[type] = std::vector{regObj}; + } else { + iter->second.emplace_back(regObj); + } +} + +void EventRegister::DeleteRegisterObj(const napi_env& env, std::vector& vecRegObjs, napi_value& handler) +{ + auto iter = vecRegObjs.begin(); + for (; iter != vecRegObjs.end();) { + if (env == iter->m_regEnv) { + napi_value handlerTemp = nullptr; + napi_get_reference_value(iter->m_regEnv, iter->m_regHanderRef, &handlerTemp); + bool isEqual = false; + napi_strict_equals(iter->m_regEnv, handlerTemp, handler, &isEqual); + if (isEqual) { + uint32_t refCount = INVALID_REF_COUNT; + napi_reference_unref(iter->m_regEnv, iter->m_regHanderRef, &refCount); + WIFI_LOGI("delete ref, m_regEnv: %{private}p, m_regHanderRef: %{private}p, refCount: %{public}d", + iter->m_regEnv, iter->m_regHanderRef, refCount); + if (refCount == 0) { + napi_delete_reference(iter->m_regEnv, iter->m_regHanderRef); + } + WIFI_LOGI("Delete register object ref."); + iter = vecRegObjs.erase(iter); + } else { + ++iter; + } + } else { + WIFI_LOGI("Unregister event, env is not equal %{private}p, : %{private}p", env, iter->m_regEnv); + ++iter; + } + } +} + +void EventRegister::DeleteAllRegisterObj(const napi_env& env, std::vector& vecRegObjs) +{ + auto iter = vecRegObjs.begin(); + for (; iter != vecRegObjs.end();) { + if (env == iter->m_regEnv) { + uint32_t refCount = INVALID_REF_COUNT; + napi_reference_unref(iter->m_regEnv, iter->m_regHanderRef, &refCount); + WIFI_LOGI("delete all ref, m_regEnv: %{private}p, m_regHanderRef: %{private}p, refCount: %{public}d", + iter->m_regEnv, iter->m_regHanderRef, refCount); + if (refCount == 0) { + napi_delete_reference(iter->m_regEnv, iter->m_regHanderRef); + } + iter = vecRegObjs.erase(iter); + } else { + WIFI_LOGI("Unregister all event, env is not equal %{private}p, : %{private}p", env, iter->m_regEnv); + ++iter; + } + } +} + +void EventRegister::Unregister(const napi_env& env, const std::string& type, napi_value handler) +{ + int32_t sysCap = findSysCap(type); + WIFI_LOGI("Unregister event: %{public}s, env: %{private}p, sysCap:%{public}d", + type.c_str(), env, (int)sysCap); + if (!IsEventSupport(type)) { + WIFI_LOGE("Unregister type error or not support!"); +#ifdef ENABLE_NAPI_WIFI_MANAGER + HandleSyncErrCode(env, WIFI_OPT_NOT_SUPPORTED, sysCap); +#endif + return; + } + if (CheckPermission(type) != WIFI_NAPI_PERMISSION_GRANTED) { + WIFI_LOGE("Unregister fail for NO permission!"); +#ifdef ENABLE_NAPI_WIFI_MANAGER + HandleSyncErrCode(env, WIFI_OPT_PERMISSION_DENIED, sysCap); +#endif + return; + } + std::unique_lock guard(g_regInfoMutex); + auto iter = g_eventRegisterInfo.find(type); + if (iter == g_eventRegisterInfo.end()) { + WIFI_LOGE("Unregister type not registered!"); +#ifdef ENABLE_NAPI_WIFI_MANAGER + HandleSyncErrCode(env, WIFI_OPT_NOT_SUPPORTED, sysCap); +#endif + return; + } + if (handler != nullptr) { + DeleteRegisterObj(env, iter->second, handler); + } else { + WIFI_LOGW("Unregister all relevant subscribe for: %{public}s", type.c_str()); + DeleteAllRegisterObj(env, iter->second); + } + if (iter->second.empty()) { + g_eventRegisterInfo.erase(iter); + } +} +} // namespace Wifi +} // namespace OHOS diff --git a/wifi/frameworks/js/napi/src/wifi_napi_hotspot.cpp b/wifi/frameworks/js/napi/src/wifi_napi_hotspot.cpp new file mode 100644 index 0000000000000000000000000000000000000000..ea8d620c5bb17aad7a09a35f4701bff23ad05637 --- /dev/null +++ b/wifi/frameworks/js/napi/src/wifi_napi_hotspot.cpp @@ -0,0 +1,251 @@ +/* + * Copyright (C) 2021-2022 Huawei Device Co., Ltd. + * 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 "wifi_napi_hotspot.h" +#include "wifi_hotspot.h" +#include "wifi_logger.h" +#include +#include +#include "wifi_napi_errcode.h" + +namespace OHOS { +namespace Wifi { +DEFINE_WIFILOG_LABEL("WifiNAPIHotspot"); + +std::unique_ptr wifiHotspotPtr = WifiHotspot::GetInstance(WIFI_HOTSPOT_ABILITY_ID); + +std::map g_mapSecTypeToKeyMgmt = { + {SecTypeJs::SEC_TYPE_OPEN, KeyMgmt::NONE}, + {SecTypeJs::SEC_TYPE_PSK, KeyMgmt::WPA_PSK}, +}; + +napi_value EnableHotspot(napi_env env, napi_callback_info info) +{ + TRACE_FUNC_CALL; + WIFI_NAPI_ASSERT(env, wifiHotspotPtr != nullptr, WIFI_OPT_FAILED, SYSCAP_WIFI_AP_CORE); + ErrCode ret = wifiHotspotPtr->EnableHotspot(); + if (ret != WIFI_OPT_SUCCESS) { + WIFI_LOGE("Enable hotspot error: %{public}d", ret); + } + WIFI_NAPI_RETURN(env, ret == WIFI_OPT_SUCCESS, ret, SYSCAP_WIFI_AP_CORE); +} + +napi_value DisableHotspot(napi_env env, napi_callback_info info) +{ + TRACE_FUNC_CALL; + WIFI_NAPI_ASSERT(env, wifiHotspotPtr != nullptr, WIFI_OPT_FAILED, SYSCAP_WIFI_AP_CORE); + ErrCode ret = wifiHotspotPtr->DisableHotspot(); + if (ret != WIFI_OPT_SUCCESS) { + WIFI_LOGE("Disable hotspot error: %{public}d", ret); + } + WIFI_NAPI_RETURN(env, ret == WIFI_OPT_SUCCESS, ret, SYSCAP_WIFI_AP_CORE); +} + +napi_value IsHotspotActive(napi_env env, napi_callback_info info) +{ + WIFI_NAPI_ASSERT(env, wifiHotspotPtr != nullptr, WIFI_OPT_FAILED, SYSCAP_WIFI_AP_CORE); + bool ret = wifiHotspotPtr->IsHotspotActive(); + WIFI_NAPI_RETURN(env, ret == true, WIFI_OPT_FAILED, SYSCAP_WIFI_AP_CORE); +} + +napi_value IsHotspotDualBandSupported(napi_env env, napi_callback_info info) +{ + WIFI_NAPI_ASSERT(env, wifiHotspotPtr != nullptr, WIFI_OPT_FAILED, SYSCAP_WIFI_AP_CORE); + bool ret = wifiHotspotPtr->IsHotspotDualBandSupported(); + WIFI_NAPI_RETURN(env, ret == true, WIFI_OPT_FAILED, SYSCAP_WIFI_AP_CORE); +} + +static KeyMgmt GetKeyMgmtFromJsSecurityType(int secType) +{ + std::map::iterator iter = g_mapSecTypeToKeyMgmt.find(SecTypeJs(secType)); + return iter == g_mapSecTypeToKeyMgmt.end() ? KeyMgmt::NONE : iter->second; +} + +static int GetJsSecurityTypeFromKeyMgmt(KeyMgmt keyMgmt) +{ + for (auto& each : g_mapSecTypeToKeyMgmt) { + if (each.second == keyMgmt) { + return static_cast(each.first); + } + } + return static_cast(SecTypeJs::SEC_TYPE_OPEN); +} + +static bool IsSecTypeSupported(int secType) +{ + return g_mapSecTypeToKeyMgmt.find(SecTypeJs(secType)) != g_mapSecTypeToKeyMgmt.end(); +} + +static bool GetHotspotconfigFromJs(const napi_env& env, const napi_value& object, HotspotConfig& config) +{ + std::string str = ""; + int value = 0; + JsObjectToString(env, object, "ssid", NAPI_MAX_STR_LENT, str); // 33: ssid max length is 32 + '\0' + config.SetSsid(str); + str = ""; + JsObjectToInt(env, object, "securityType", value); + if (!IsSecTypeSupported(value)) { + WIFI_LOGE("securityType is not supported: %{public}d", value); + return false; + } + config.SetSecurityType(GetKeyMgmtFromJsSecurityType(value)); + value = 0; + JsObjectToInt(env, object, "band", value); + config.SetBand(BandType(value)); // 1: 2.4G, 2: 5G + if (config.GetBand() == BandType::BAND_5GHZ) { + config.SetChannel(AP_CHANNEL_5G_DEFAULT); + } + value = 0; + JsObjectToString(env, object, "preSharedKey", NAPI_MAX_STR_LENT, str); // 64: max length + config.SetPreSharedKey(str); + JsObjectToInt(env, object, "maxConn", value); + config.SetMaxConn(value); + return true; +} + +napi_value SetHotspotConfig(napi_env env, napi_callback_info info) +{ + TRACE_FUNC_CALL; + size_t argc = 1; + napi_value argv[1]; + napi_value thisVar; + NAPI_CALL(env, napi_get_cb_info(env, info, &argc, argv, &thisVar, NULL)); + + napi_valuetype valueType; + napi_typeof(env, argv[0], &valueType); + WIFI_NAPI_ASSERT(env, valueType == napi_object, WIFI_OPT_INVALID_PARAM, SYSCAP_WIFI_AP_CORE); + WIFI_NAPI_ASSERT(env, wifiHotspotPtr != nullptr, WIFI_OPT_FAILED, SYSCAP_WIFI_AP_CORE); + + ErrCode ret = WIFI_OPT_FAILED; + HotspotConfig config; + if (GetHotspotconfigFromJs(env, argv[0], config)) { + ret = wifiHotspotPtr->SetHotspotConfig(config); + if (ret != WIFI_OPT_SUCCESS) { + WIFI_LOGE("Set hotspot config error: %{public}d", ret); + } + } + WIFI_NAPI_RETURN(env, ret == WIFI_OPT_SUCCESS, ret, SYSCAP_WIFI_AP_CORE); +} + +static void HotspotconfigToJs(const napi_env& env, HotspotConfig& cppConfig, napi_value& result) +{ + SetValueUtf8String(env, "ssid", cppConfig.GetSsid().c_str(), result); + SetValueInt32(env, "securityType", GetJsSecurityTypeFromKeyMgmt(cppConfig.GetSecurityType()), result); + SetValueInt32(env, "band", static_cast(cppConfig.GetBand()), result); + SetValueUtf8String(env, "preSharedKey", cppConfig.GetPreSharedKey().c_str(), result); + SetValueInt32(env, "maxConn", cppConfig.GetMaxConn(), result); +} + +napi_value GetHotspotConfig(napi_env env, napi_callback_info info) +{ + TRACE_FUNC_CALL; + WIFI_NAPI_ASSERT(env, wifiHotspotPtr != nullptr, WIFI_OPT_FAILED, SYSCAP_WIFI_AP_CORE); + HotspotConfig config; + ErrCode ret = wifiHotspotPtr->GetHotspotConfig(config); + if (ret != WIFI_OPT_SUCCESS) { + WIFI_LOGE("Get hotspot config error: %{public}d", ret); + } + WIFI_NAPI_ASSERT(env, ret == WIFI_OPT_SUCCESS, ret, SYSCAP_WIFI_AP_CORE); + napi_value result; + napi_create_object(env, &result); + HotspotconfigToJs(env, config, result); + return result; +} + +static void StationInfoToJsArray(const napi_env& env, const std::vector& StationInfo, + const int idx, napi_value& arrayResult) +{ + napi_value result; + napi_create_object(env, &result); + + SetValueUtf8String(env, "name", StationInfo[idx].deviceName.c_str(), result); + SetValueUtf8String(env, "macAddress", StationInfo[idx].bssid.c_str(), result); + SetValueUtf8String(env, "ipAddress", StationInfo[idx].ipAddr.c_str(), result); + napi_status status = napi_set_element(env, arrayResult, idx, result); + if (status != napi_ok) { + WIFI_LOGE("Set station element error: %{public}d", status); + } +} + +napi_value GetStations(napi_env env, napi_callback_info info) +{ + TRACE_FUNC_CALL; + WIFI_NAPI_ASSERT(env, wifiHotspotPtr != nullptr, WIFI_OPT_FAILED, SYSCAP_WIFI_AP_CORE); + std::vector vecStationInfo; + ErrCode ret = wifiHotspotPtr->GetStationList(vecStationInfo); + if (ret != WIFI_OPT_SUCCESS) { + WIFI_LOGE("Get station list error: %{public}d", ret); + } + WIFI_LOGI("Get station list size: %{public}zu", vecStationInfo.size()); + WIFI_NAPI_ASSERT(env, ret == WIFI_OPT_SUCCESS, ret, SYSCAP_WIFI_AP_CORE); + + napi_value arrayResult; + napi_create_array_with_length(env, vecStationInfo.size(), &arrayResult); + for (size_t i = 0; i != vecStationInfo.size(); ++i) { + StationInfoToJsArray(env, vecStationInfo, i, arrayResult); + } + return arrayResult; +} + +napi_value AddBlockList(napi_env env, napi_callback_info info) +{ + TRACE_FUNC_CALL; + size_t argc = 1; + napi_value argv[argc]; + napi_value thisVar; + NAPI_CALL(env, napi_get_cb_info(env, info, &argc, argv, &thisVar, NULL)); + + napi_valuetype valueType; + napi_typeof(env, argv[0], &valueType); + WIFI_NAPI_ASSERT(env, valueType == napi_string, WIFI_OPT_INVALID_PARAM, SYSCAP_WIFI_AP_CORE); + WIFI_NAPI_ASSERT(env, wifiHotspotPtr != nullptr, WIFI_OPT_FAILED, SYSCAP_WIFI_AP_CORE); + + StationInfo stationInfo; + char bssid[WIFI_BSSID_LENGTH] = {0}; + size_t len = 0; + napi_get_value_string_utf8(env, argv[0], bssid, sizeof(bssid), &len); + stationInfo.bssid = bssid; + ErrCode ret = wifiHotspotPtr->AddBlockList(stationInfo); + if (ret != WIFI_OPT_SUCCESS) { + WIFI_LOGE("Add block list fail: %{public}d", ret); + } + WIFI_NAPI_RETURN(env, ret == WIFI_OPT_SUCCESS, ret, SYSCAP_WIFI_AP_CORE); +} + +napi_value DelBlockList(napi_env env, napi_callback_info info) +{ + TRACE_FUNC_CALL; + size_t argc = 1; + napi_value argv[argc]; + napi_value thisVar; + NAPI_CALL(env, napi_get_cb_info(env, info, &argc, argv, &thisVar, NULL)); + napi_valuetype valueType; + napi_typeof(env, argv[0], &valueType); + WIFI_NAPI_ASSERT(env, valueType == napi_string, WIFI_OPT_INVALID_PARAM, SYSCAP_WIFI_AP_CORE); + WIFI_NAPI_ASSERT(env, wifiHotspotPtr != nullptr, WIFI_OPT_FAILED, SYSCAP_WIFI_AP_CORE); + + StationInfo stationInfo; + char bssid[WIFI_BSSID_LENGTH] = {0}; + size_t len = 0; + napi_get_value_string_utf8(env, argv[0], bssid, sizeof(bssid), &len); + stationInfo.bssid = bssid; + ErrCode ret = wifiHotspotPtr->DelBlockList(stationInfo); + if (ret != WIFI_OPT_SUCCESS) { + WIFI_LOGE("Del block list fail: %{public}d", ret); + } + WIFI_NAPI_RETURN(env, ret == WIFI_OPT_SUCCESS, ret, SYSCAP_WIFI_AP_CORE); +} +} // namespace Wifi +} // namespace OHOS diff --git a/wifi/frameworks/js/napi/src/wifi_napi_p2p.cpp b/wifi/frameworks/js/napi/src/wifi_napi_p2p.cpp new file mode 100644 index 0000000000000000000000000000000000000000..0de049165790d1b30bdfb18870f4396b89e6e9a1 --- /dev/null +++ b/wifi/frameworks/js/napi/src/wifi_napi_p2p.cpp @@ -0,0 +1,412 @@ +/* + * Copyright (C) 2021-2022 Huawei Device Co., Ltd. + * 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 "wifi_napi_p2p.h" +#include "wifi_logger.h" +#include "wifi_napi_errcode.h" + +namespace OHOS { +namespace Wifi { +DEFINE_WIFILOG_LABEL("WifiNAPIP2p"); + +std::unique_ptr wifiP2pPtr = WifiP2p::GetInstance(WIFI_P2P_ABILITY_ID); +static void DeviceInfoToJs(const napi_env& env, const WifiP2pDevice& device, napi_value& result) +{ + SetValueUtf8String(env, "deviceName", device.GetDeviceName().c_str(), result); + SetValueUtf8String(env, "deviceAddress", device.GetDeviceAddress().c_str(), result); + SetValueUtf8String(env, "primaryDeviceType", device.GetPrimaryDeviceType().c_str(), result); + SetValueInt32(env, "deviceStatus", static_cast(device.GetP2pDeviceStatus()), result); + SetValueInt32(env, "groupCapabilitys", device.GetGroupCapabilitys(), result); +} + +static ErrCode DevicesToJsArray(const napi_env& env, + const std::vector& vecDevices, napi_value& arrayResult) +{ + uint32_t idx = 0; + for (auto& each : vecDevices) { + napi_value eachObj; + napi_create_object(env, &eachObj); + DeviceInfoToJs(env, each, eachObj); + napi_status status = napi_set_element(env, arrayResult, idx++, eachObj); + if (status != napi_ok) { + WIFI_LOGE("wifi napi set element error: %{public}d, idx: %{public}d", status, idx - 1); + return WIFI_OPT_FAILED; + } + } + return WIFI_OPT_SUCCESS; +} + +static ErrCode GroupInfosToJs(const napi_env& env, const WifiP2pGroupInfo& groupInfo, napi_value& result) +{ + SetValueBool(env, "isP2pGo", groupInfo.IsGroupOwner(), result); + + WifiP2pDevice ownerDevice = groupInfo.GetOwner(); + napi_value owner; + napi_create_object(env, &owner); + DeviceInfoToJs(env, ownerDevice, owner); + napi_status status = napi_set_named_property(env, result, "ownerInfo", owner); + if (status != napi_ok) { + WIFI_LOGE("napi_set_named_property ownerInfo fail"); + return WIFI_OPT_FAILED; + } + + SetValueUtf8String(env, "passphrase", groupInfo.GetPassphrase().c_str(), result); + SetValueUtf8String(env, "interface", groupInfo.GetInterface().c_str(), result); + SetValueUtf8String(env, "groupName", groupInfo.GetGroupName().c_str(), result); + SetValueInt32(env, "networkId", groupInfo.GetNetworkId(), result); + SetValueInt32(env, "frequency", groupInfo.GetFrequency(), result); + + if (!groupInfo.IsClientDevicesEmpty()) { + const std::vector& vecDevices = groupInfo.GetClientDevices(); + napi_value devices; + napi_create_array_with_length(env, vecDevices.size(), &devices); + if (DevicesToJsArray(env, vecDevices, devices) != WIFI_OPT_SUCCESS) { + return WIFI_OPT_FAILED; + } + status = napi_set_named_property(env, result, "clientDevices", devices); + if (status != napi_ok) { + WIFI_LOGE("napi_set_named_property clientDevices fail"); + return WIFI_OPT_FAILED; + } + } + SetValueUtf8String(env, "goIpAddress", groupInfo.GetGoIpAddress().c_str(), result); + return WIFI_OPT_SUCCESS; +} + +static ErrCode GroupsToJsArray(const napi_env& env, + const std::vector& vecGroups, napi_value& arrayResult) +{ + uint32_t idx = 0; + for (auto& each : vecGroups) { + napi_value eachObj; + napi_create_object(env, &eachObj); + int ret = GroupInfosToJs(env, each, eachObj); + if (ret != WIFI_OPT_SUCCESS) { + return WIFI_OPT_FAILED; + } + napi_status status = napi_set_element(env, arrayResult, idx++, eachObj); + if (status != napi_ok) { + WIFI_LOGE("wifi napi set element error: %{public}d, idx: %{public}d", status, idx - 1); + return WIFI_OPT_FAILED; + } + } + return WIFI_OPT_SUCCESS; +} + +napi_value GetCurrentGroup(napi_env env, napi_callback_info info) +{ + TRACE_FUNC_CALL; + size_t argc = 1; + napi_value argv[argc]; + napi_value thisVar = nullptr; + void *data = nullptr; + NAPI_CALL(env, napi_get_cb_info(env, info, &argc, argv, &thisVar, &data)); + WIFI_NAPI_ASSERT(env, wifiP2pPtr != nullptr, WIFI_OPT_FAILED, SYSCAP_WIFI_P2P); + + P2pGroupInfoAsyncContext *asyncContext = new P2pGroupInfoAsyncContext(env); + WIFI_NAPI_ASSERT(env, asyncContext != nullptr, WIFI_OPT_FAILED, SYSCAP_WIFI_P2P); + napi_create_string_latin1(env, "getCurrentGroup", NAPI_AUTO_LENGTH, &asyncContext->resourceName); + + asyncContext->executeFunc = [&](void* data) -> void { + P2pGroupInfoAsyncContext *context = static_cast(data); + TRACE_FUNC_CALL_NAME("wifiP2pPtr->GetCurrentGroup"); + context->errorCode = wifiP2pPtr->GetCurrentGroup(context->groupInfo); + }; + + asyncContext->completeFunc = [&](void* data) -> void { + P2pGroupInfoAsyncContext *context = static_cast(data); + napi_create_object(context->env, &context->result); + context->errorCode = GroupInfosToJs(context->env, context->groupInfo, context->result); + WIFI_LOGI("Push get current group result to client"); + }; + + size_t nonCallbackArgNum = 0; + asyncContext->sysCap = SYSCAP_WIFI_P2P; + return DoAsyncWork(env, asyncContext, argc, argv, nonCallbackArgNum); +} + +napi_value GetP2pGroups(napi_env env, napi_callback_info info) +{ + TRACE_FUNC_CALL; + size_t argc = 1; + napi_value argv[argc]; + napi_value thisVar = nullptr; + void *data = nullptr; + NAPI_CALL(env, napi_get_cb_info(env, info, &argc, argv, &thisVar, &data)); + WIFI_NAPI_ASSERT(env, wifiP2pPtr != nullptr, WIFI_OPT_FAILED, SYSCAP_WIFI_P2P); + + P2pGroupInfoListAsyncContext *asyncContext = new P2pGroupInfoListAsyncContext(env); + WIFI_NAPI_ASSERT(env, asyncContext != nullptr, WIFI_OPT_FAILED, SYSCAP_WIFI_P2P); + napi_create_string_latin1(env, "GetP2pGroups", NAPI_AUTO_LENGTH, &asyncContext->resourceName); + + asyncContext->executeFunc = [&](void* data) -> void { + P2pGroupInfoListAsyncContext *context = static_cast(data); + TRACE_FUNC_CALL_NAME("wifiP2pPtr->QueryP2pGroups"); + context->errorCode = wifiP2pPtr->QueryP2pGroups(context->vecGroupInfoList); + }; + + asyncContext->completeFunc = [&](void* data) -> void { + P2pGroupInfoListAsyncContext *context = static_cast(data); + napi_create_array_with_length(context->env, context->vecGroupInfoList.size(), &context->result); + context->errorCode = GroupsToJsArray(context->env, context->vecGroupInfoList, context->result); + WIFI_LOGI("Push get group info list to client"); + }; + + size_t nonCallbackArgNum = 0; + asyncContext->sysCap = SYSCAP_WIFI_P2P; + return DoAsyncWork(env, asyncContext, argc, argv, nonCallbackArgNum); +} + + +napi_value DeletePersistentGroup(napi_env env, napi_callback_info info) +{ + TRACE_FUNC_CALL; + size_t argc = 1; + napi_value argv[argc]; + napi_value thisVar; + NAPI_CALL(env, napi_get_cb_info(env, info, &argc, argv, &thisVar, NULL)); + WIFI_NAPI_ASSERT(env, wifiP2pPtr != nullptr, WIFI_OPT_FAILED, SYSCAP_WIFI_P2P); + + napi_valuetype valueType; + napi_typeof(env, argv[0], &valueType); + WIFI_NAPI_ASSERT(env, valueType == napi_number, WIFI_OPT_INVALID_PARAM, SYSCAP_WIFI_P2P); + + WifiP2pGroupInfo groupInfo; + int netId = -999; + napi_get_value_int32(env, argv[0], &netId); + groupInfo.SetNetworkId(netId); + ErrCode ret = wifiP2pPtr->DeleteGroup(groupInfo); + WIFI_NAPI_RETURN(env, ret == WIFI_OPT_SUCCESS, ret, SYSCAP_WIFI_P2P); +} + +napi_value StartDiscoverDevices(napi_env env, napi_callback_info info) +{ + TRACE_FUNC_CALL; + WIFI_NAPI_ASSERT(env, wifiP2pPtr != nullptr, WIFI_OPT_FAILED, SYSCAP_WIFI_P2P); + + ErrCode ret = wifiP2pPtr->DiscoverDevices(); + WIFI_NAPI_RETURN(env, ret == WIFI_OPT_SUCCESS, ret, SYSCAP_WIFI_P2P); +} + +napi_value StopDiscoverDevices(napi_env env, napi_callback_info info) +{ + TRACE_FUNC_CALL; + WIFI_NAPI_ASSERT(env, wifiP2pPtr != nullptr, WIFI_OPT_FAILED, SYSCAP_WIFI_P2P); + + ErrCode ret = wifiP2pPtr->StopDiscoverDevices(); + WIFI_NAPI_RETURN(env, ret == WIFI_OPT_SUCCESS, ret, SYSCAP_WIFI_P2P); +} + +napi_value GetP2pDevices(napi_env env, napi_callback_info info) +{ + size_t argc = 1; + napi_value argv[argc]; + napi_value thisVar = nullptr; + void *data = nullptr; + NAPI_CALL(env, napi_get_cb_info(env, info, &argc, argv, &thisVar, &data)); + WIFI_NAPI_ASSERT(env, wifiP2pPtr != nullptr, WIFI_OPT_FAILED, SYSCAP_WIFI_P2P); + + QueryP2pDeviceAsyncContext *asyncContext = new QueryP2pDeviceAsyncContext(env); + WIFI_NAPI_ASSERT(env, asyncContext != nullptr, WIFI_OPT_FAILED, SYSCAP_WIFI_P2P); + napi_create_string_latin1(env, "GetP2pDevices", NAPI_AUTO_LENGTH, &asyncContext->resourceName); + + asyncContext->executeFunc = [&](void* data) -> void { + QueryP2pDeviceAsyncContext *context = static_cast(data); + context->errorCode = wifiP2pPtr->QueryP2pDevices(context->vecP2pDevices); + WIFI_LOGI("GetP2pDeviceList, size: %{public}zu", context->vecP2pDevices.size()); + }; + + asyncContext->completeFunc = [&](void* data) -> void { + QueryP2pDeviceAsyncContext *context = static_cast(data); + napi_create_array_with_length(context->env, context->vecP2pDevices.size(), &context->result); + context->errorCode = DevicesToJsArray(context->env, context->vecP2pDevices, context->result); + WIFI_LOGI("Push P2p Device List to client"); + }; + + size_t nonCallbackArgNum = 0; + asyncContext->sysCap = SYSCAP_WIFI_P2P; + return DoAsyncWork(env, asyncContext, argc, argv, nonCallbackArgNum); +} + +napi_value GetP2pLocalDevice(napi_env env, napi_callback_info info) +{ + TRACE_FUNC_CALL; + size_t argc = 1; + napi_value argv[argc]; + napi_value thisVar = nullptr; + void *data = nullptr; + NAPI_CALL(env, napi_get_cb_info(env, info, &argc, argv, &thisVar, &data)); + WIFI_NAPI_ASSERT(env, wifiP2pPtr != nullptr, WIFI_OPT_FAILED, SYSCAP_WIFI_P2P); + + P2pLocalDeviceAsyncContext *asyncContext = new P2pLocalDeviceAsyncContext(env); + WIFI_NAPI_ASSERT(env, asyncContext != nullptr, WIFI_OPT_FAILED, SYSCAP_WIFI_P2P); + napi_create_string_latin1(env, "GetP2pLocalDevice", NAPI_AUTO_LENGTH, &asyncContext->resourceName); + + asyncContext->executeFunc = [&](void* data) -> void { + P2pLocalDeviceAsyncContext *context = static_cast(data); + TRACE_FUNC_CALL_NAME("wifiP2pPtr->QueryP2pLocalDevice"); + context->errorCode = wifiP2pPtr->QueryP2pLocalDevice(context->deviceInfo); + }; + + asyncContext->completeFunc = [&](void* data) -> void { + P2pLocalDeviceAsyncContext *context = static_cast(data); + napi_create_object(context->env, &context->result); + context->errorCode = WIFI_OPT_SUCCESS; + DeviceInfoToJs(context->env, context->deviceInfo, context->result); + WIFI_LOGI("Push get p2p local device result to client"); + }; + + size_t nonCallbackArgNum = 0; + asyncContext->sysCap = SYSCAP_WIFI_P2P; + return DoAsyncWork(env, asyncContext, argc, argv, nonCallbackArgNum); +} + +napi_value SetDeviceName(napi_env env, napi_callback_info info) +{ + TRACE_FUNC_CALL; + size_t argc = 1; + napi_value argv[1]; + napi_value thisVar; + NAPI_CALL(env, napi_get_cb_info(env, info, &argc, argv, &thisVar, NULL)); + WIFI_NAPI_ASSERT(env, argc == 1, WIFI_OPT_INVALID_PARAM, SYSCAP_WIFI_P2P); + WIFI_NAPI_ASSERT(env, wifiP2pPtr != nullptr, WIFI_OPT_FAILED, SYSCAP_WIFI_P2P); + + napi_valuetype valueType; + napi_typeof(env, argv[0], &valueType); + WIFI_NAPI_ASSERT(env, valueType == napi_string, WIFI_OPT_INVALID_PARAM, SYSCAP_WIFI_P2P); + + char name[64] = {0}; + size_t typeLen = 0; + napi_get_value_string_utf8(env, argv[0], name, sizeof(name), &typeLen); + ErrCode ret = wifiP2pPtr->SetP2pDeviceName(name); + WIFI_NAPI_RETURN(env, ret == WIFI_OPT_SUCCESS, ret, SYSCAP_WIFI_P2P); +} + +static void JsObjToP2pConfig(const napi_env& env, const napi_value& object, WifiP2pConfig& config) +{ + std::string address = ""; + int netId = -1; + std::string passphrase = ""; + std::string groupName = ""; + int band = static_cast(GroupOwnerBand::GO_BAND_AUTO); + JsObjectToString(env, object, "deviceAddress", WIFI_STR_MAC_LENGTH + 1, address); + JsObjectToInt(env, object, "netId", netId); + JsObjectToString(env, object, "passphrase", MAX_PASSPHRASE_LENGTH + 1, passphrase); + JsObjectToString(env, object, "groupName", DEVICE_NAME_LENGTH + 1, groupName); + JsObjectToInt(env, object, "goBand", band); + config.SetDeviceAddress(address); + config.SetNetId(netId); + config.SetPassphrase(passphrase); + config.SetGroupName(groupName); + config.SetGoBand(static_cast(band)); +} + +napi_value P2pConnect(napi_env env, napi_callback_info info) +{ + TRACE_FUNC_CALL; + size_t argc = 1; + napi_value argv[argc]; + napi_value thisVar; + NAPI_CALL(env, napi_get_cb_info(env, info, &argc, argv, &thisVar, NULL)); + WIFI_NAPI_ASSERT(env, wifiP2pPtr != nullptr, WIFI_OPT_FAILED, SYSCAP_WIFI_P2P); + + napi_valuetype valueType; + napi_typeof(env, argv[0], &valueType); + WIFI_NAPI_ASSERT(env, valueType == napi_object, WIFI_OPT_INVALID_PARAM, SYSCAP_WIFI_P2P); + + WifiP2pConfig config; + JsObjToP2pConfig(env, argv[0], config); + ErrCode ret = wifiP2pPtr->P2pConnect(config); + if (ret != WIFI_OPT_SUCCESS) { + WIFI_LOGE("Connect to device fail: %{public}d", ret); + } + WIFI_NAPI_RETURN(env, ret == WIFI_OPT_SUCCESS, ret, SYSCAP_WIFI_P2P); +} + +napi_value P2pCancelConnect(napi_env env, napi_callback_info info) +{ + TRACE_FUNC_CALL; + WIFI_NAPI_ASSERT(env, wifiP2pPtr != nullptr, WIFI_OPT_FAILED, SYSCAP_WIFI_P2P); + ErrCode ret = wifiP2pPtr->P2pCancelConnect(); + WIFI_NAPI_RETURN(env, ret == WIFI_OPT_SUCCESS, ret, SYSCAP_WIFI_P2P); +} + +napi_value CreateGroup(napi_env env, napi_callback_info info) +{ + TRACE_FUNC_CALL; + size_t argc = 1; + napi_value argv[1]; + napi_value thisVar; + NAPI_CALL(env, napi_get_cb_info(env, info, &argc, argv, &thisVar, NULL)); + WIFI_NAPI_ASSERT(env, wifiP2pPtr != nullptr, WIFI_OPT_FAILED, SYSCAP_WIFI_P2P); + + napi_valuetype valueType; + napi_typeof(env, argv[0], &valueType); + WIFI_NAPI_ASSERT(env, valueType == napi_object, WIFI_OPT_INVALID_PARAM, SYSCAP_WIFI_P2P); + + WifiP2pConfig config; + JsObjToP2pConfig(env, argv[0], config); + ErrCode ret = wifiP2pPtr->CreateGroup(config); + WIFI_NAPI_RETURN(env, ret == WIFI_OPT_SUCCESS, ret, SYSCAP_WIFI_P2P); +} + +napi_value RemoveGroup(napi_env env, napi_callback_info info) +{ + TRACE_FUNC_CALL; + WIFI_NAPI_ASSERT(env, wifiP2pPtr != nullptr, WIFI_OPT_FAILED, SYSCAP_WIFI_P2P); + ErrCode ret = wifiP2pPtr->RemoveGroup(); + WIFI_NAPI_RETURN(env, ret == WIFI_OPT_SUCCESS, ret, SYSCAP_WIFI_P2P); +} + +static void LinkedInfoToJs(const napi_env& env, WifiP2pLinkedInfo& linkedInfo, napi_value& result) +{ + SetValueInt32(env, "connectState", static_cast(linkedInfo.GetConnectState()), result); + SetValueBool(env, "isGroupOwner", linkedInfo.IsGroupOwner(), result); + SetValueUtf8String(env, "groupOwnerAddr", linkedInfo.GetGroupOwnerAddress().c_str(), result); +} + +napi_value GetP2pLinkedInfo(napi_env env, napi_callback_info info) +{ + TRACE_FUNC_CALL; + size_t argc = 1; + napi_value argv[argc]; + napi_value thisVar = nullptr; + void *data = nullptr; + NAPI_CALL(env, napi_get_cb_info(env, info, &argc, argv, &thisVar, &data)); + WIFI_NAPI_ASSERT(env, wifiP2pPtr != nullptr, WIFI_OPT_FAILED, SYSCAP_WIFI_P2P); + + P2pLinkedInfoAsyncContext *asyncContext = new P2pLinkedInfoAsyncContext(env); + WIFI_NAPI_ASSERT(env, asyncContext != nullptr, WIFI_OPT_FAILED, SYSCAP_WIFI_P2P); + napi_create_string_latin1(env, "queryP2pLinkedInfo", NAPI_AUTO_LENGTH, &asyncContext->resourceName); + + asyncContext->executeFunc = [&](void* data) -> void { + P2pLinkedInfoAsyncContext *context = static_cast(data); + TRACE_FUNC_CALL_NAME("wifiP2pPtr->QueryP2pLinkedInfo"); + context->errorCode = wifiP2pPtr->QueryP2pLinkedInfo(context->linkedInfo); + }; + + asyncContext->completeFunc = [&](void* data) -> void { + P2pLinkedInfoAsyncContext *context = static_cast(data); + napi_create_object(context->env, &context->result); + LinkedInfoToJs(context->env, context->linkedInfo, context->result); + WIFI_LOGI("Push get linkedInfo result to client"); + }; + + size_t nonCallbackArgNum = 0; + asyncContext->sysCap = SYSCAP_WIFI_P2P; + return DoAsyncWork(env, asyncContext, argc, argv, nonCallbackArgNum); +} +} // namespace Wifi +} // namespace OHOS diff --git a/wifi/frameworks/js/napi/src/wifi_napi_utils.cpp b/wifi/frameworks/js/napi/src/wifi_napi_utils.cpp new file mode 100644 index 0000000000000000000000000000000000000000..a5b3ed8047a900da6b6ff08dadf97628edffad41 --- /dev/null +++ b/wifi/frameworks/js/napi/src/wifi_napi_utils.cpp @@ -0,0 +1,319 @@ +/* + * Copyright (C) 2021-2022 Huawei Device Co., Ltd. + * 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 "wifi_napi_utils.h" +#include "securec.h" +#include "wifi_logger.h" +#include "context.h" +#include "wifi_napi_errcode.h" + +namespace OHOS { +namespace Wifi { +DEFINE_WIFILOG_LABEL("WifiNAPIUtils"); + +TraceFuncCall::TraceFuncCall(std::string funcName): m_funcName(funcName) +{ + if (m_isTrace) { + m_startTime = std::chrono::steady_clock::now(); + WIFI_LOGI("Call wifi func: %{public}s (start)", m_funcName.c_str()); + } +} + +TraceFuncCall::~TraceFuncCall() +{ + if (m_isTrace) { + auto us = std::chrono::duration_cast + (std::chrono::steady_clock::now() - m_startTime).count(); + constexpr int usForPerMs = 1000; + WIFI_LOGI("Call wifi func: %{public}s (end), time cost:%{public}lldus, %{public}lldms", + m_funcName.c_str(), us, us / usForPerMs); + } +} + +napi_value UndefinedNapiValue(const napi_env& env) +{ + napi_value result; + napi_get_undefined(env, &result); + return result; +} + +napi_value JsObjectToString(const napi_env& env, const napi_value& object, + const char* fieldStr, const int bufLen, std::string& fieldRef) +{ + bool hasProperty = false; + NAPI_CALL(env, napi_has_named_property(env, object, fieldStr, &hasProperty)); + if (hasProperty) { + napi_value field; + napi_valuetype valueType; + + napi_get_named_property(env, object, fieldStr, &field); + NAPI_CALL(env, napi_typeof(env, field, &valueType)); + NAPI_ASSERT(env, valueType == napi_string, "Wrong argument type. String expected."); + if (bufLen <= 0) { + goto error; + } + char *buf = (char *)malloc(bufLen); + if (buf == nullptr) { + WIFI_LOGE("Js object to str malloc failed"); + goto error; + } + (void)memset_s(buf, bufLen, 0, bufLen); + size_t result = 0; + NAPI_CALL(env, napi_get_value_string_utf8(env, field, buf, bufLen, &result)); + fieldRef = buf; + free(buf); + buf = nullptr; + } else { + WIFI_LOGW("Js obj to str no property: %{public}s", fieldStr); + } + +error: + return UndefinedNapiValue(env); +} + +napi_value JsObjectToInt(const napi_env& env, const napi_value& object, const char* fieldStr, int& fieldRef) +{ + bool hasProperty = false; + NAPI_CALL(env, napi_has_named_property(env, object, fieldStr, &hasProperty)); + if (hasProperty) { + napi_value field; + napi_valuetype valueType; + + napi_get_named_property(env, object, fieldStr, &field); + NAPI_CALL(env, napi_typeof(env, field, &valueType)); + NAPI_ASSERT(env, valueType == napi_number, "Wrong argument type. Number expected."); + napi_get_value_int32(env, field, &fieldRef); + } else { + WIFI_LOGW("Js to int no property: %{public}s", fieldStr); + } + return UndefinedNapiValue(env); +} + +napi_value JsObjectToUint(const napi_env& env, const napi_value& object, const char* fieldStr, uint32_t& fieldRef) +{ + bool hasProperty = false; + NAPI_CALL(env, napi_has_named_property(env, object, fieldStr, &hasProperty)); + if (hasProperty) { + napi_value field; + napi_valuetype valueType; + + napi_get_named_property(env, object, fieldStr, &field); + NAPI_CALL(env, napi_typeof(env, field, &valueType)); + NAPI_ASSERT(env, valueType == napi_number, "Wrong argument type. Number expected."); + napi_get_value_uint32(env, field, &fieldRef); + } else { + WIFI_LOGW("Js to int no property: %{public}s", fieldStr); + } + return UndefinedNapiValue(env); +} + +napi_value JsObjectToBool(const napi_env& env, const napi_value& object, const char* fieldStr, bool& fieldRef) +{ + bool hasProperty = false; + NAPI_CALL(env, napi_has_named_property(env, object, fieldStr, &hasProperty)); + if (hasProperty) { + napi_value field; + napi_valuetype valueType; + + napi_get_named_property(env, object, fieldStr, &field); + NAPI_CALL(env, napi_typeof(env, field, &valueType)); + NAPI_ASSERT(env, valueType == napi_boolean, "Wrong argument type. Bool expected."); + napi_get_value_bool(env, field, &fieldRef); + } else { + WIFI_LOGW("Js to bool no property: %{public}s", fieldStr); + } + return UndefinedNapiValue(env); +} + +napi_status SetValueUtf8String(const napi_env& env, const char* fieldStr, const char* str, + napi_value& result, size_t strLen) +{ + napi_value value; + size_t len = strLen; + napi_status status = napi_create_string_utf8(env, str, len, &value); + if (status != napi_ok) { + WIFI_LOGE("Set value create utf8 string error! field: %{public}s", fieldStr); + return status; + } + status = napi_set_named_property(env, result, fieldStr, value); + if (status != napi_ok) { + WIFI_LOGE("Set utf8 string named property error! field: %{public}s", fieldStr); + } + return status; +} + +napi_status SetValueInt32(const napi_env& env, const char* fieldStr, const int intValue, napi_value& result) +{ + napi_value value; + napi_status status = napi_create_int32(env, intValue, &value); + if (status != napi_ok) { + WIFI_LOGE("Set value create int32 error! field: %{public}s", fieldStr); + return status; + } + status = napi_set_named_property(env, result, fieldStr, value); + if (status != napi_ok) { + WIFI_LOGE("Set int32 named property error! field: %{public}s", fieldStr); + } + return status; +} + +napi_status SetValueUnsignedInt32(const napi_env& env, const char* fieldStr, const int intValue, napi_value& result) +{ + napi_value value; + napi_status status = napi_create_uint32(env, intValue, &value); + if (status != napi_ok) { + WIFI_LOGE("Set value create unsigned int32 error! field: %{public}s", fieldStr); + return status; + } + status = napi_set_named_property(env, result, fieldStr, value); + if (status != napi_ok) { + WIFI_LOGE("Set unsigned int32 named property error! field: %{public}s", fieldStr); + } + return status; +} + +napi_status SetValueInt64(const napi_env& env, const char* fieldStr, const int64_t intValue, napi_value& result) +{ + napi_value value; + napi_status status = napi_create_int64(env, intValue, &value); + if (status != napi_ok) { + WIFI_LOGE("Set value create int64 error! field: %{public}s", fieldStr); + return status; + } + status = napi_set_named_property(env, result, fieldStr, value); + if (status != napi_ok) { + WIFI_LOGE("Set int64 named property error! field: %{public}s", fieldStr); + } + return status; +} + +napi_status SetValueBool(const napi_env& env, const char* fieldStr, const bool boolvalue, napi_value& result) +{ + napi_value value; + napi_status status = napi_get_boolean(env, boolvalue, &value); + if (status != napi_ok) { + WIFI_LOGE("Set value create boolean error! field: %{public}s", fieldStr); + return status; + } + status = napi_set_named_property(env, result, fieldStr, value); + if (status != napi_ok) { + WIFI_LOGE("Set boolean named property error! field: %{public}s", fieldStr); + } + return status; +} + +static napi_value InitAsyncCallBackEnv(const napi_env& env, AsyncContext *asyncContext, + const size_t argc, const napi_value *argv, const size_t nonCallbackArgNum) +{ + for (size_t i = nonCallbackArgNum; i != argc; ++i) { + napi_valuetype valuetype; + NAPI_CALL(env, napi_typeof(env, argv[i], &valuetype)); + NAPI_ASSERT(env, valuetype == napi_function, "Wrong argument type. Function expected."); + napi_create_reference(env, argv[i], 1, &asyncContext->callback[i - nonCallbackArgNum]); + } + return nullptr; +} + +static napi_value InitAsyncPromiseEnv(const napi_env& env, AsyncContext *asyncContext, napi_value& promise) +{ + napi_deferred deferred; + NAPI_CALL(env, napi_create_promise(env, &deferred, &promise)); + asyncContext->deferred = deferred; + return nullptr; +} + +static napi_value DoCallBackAsyncWork(const napi_env& env, AsyncContext *asyncContext) +{ + napi_create_async_work( + env, + nullptr, + asyncContext->resourceName, + [](napi_env env, void* data) { + if (data == nullptr) { + WIFI_LOGE("Async data parameter is null"); + return; + } + AsyncContext *context = (AsyncContext *)data; + context->executeFunc(context); + }, + [](napi_env env, napi_status status, void* data) { + if (data == nullptr) { + WIFI_LOGE("Async data parameter is null"); + return; + } + AsyncContext *context = (AsyncContext *)data; + context->completeFunc(data); + HandleCallbackErrCode(env, *context); + if (context->callback[0] != nullptr) { + napi_delete_reference(env, context->callback[0]); + } + if (context->callback[1] != nullptr) { + napi_delete_reference(env, context->callback[1]); + } + napi_delete_async_work(env, context->work); + delete context; + }, + (void *)asyncContext, + &asyncContext->work); + NAPI_CALL(env, napi_queue_async_work(env, asyncContext->work)); + return UndefinedNapiValue(env); +} + +static napi_value DoPromiseAsyncWork(const napi_env& env, AsyncContext *asyncContext) +{ + napi_create_async_work( + env, + nullptr, + asyncContext->resourceName, + [](napi_env env, void *data) { + if (data == nullptr) { + WIFI_LOGE("Async data parameter is null"); + return; + } + AsyncContext *context = (AsyncContext *)data; + context->executeFunc(context); + }, + [](napi_env env, napi_status status, void *data) { + if (data == nullptr) { + WIFI_LOGE("Async data parameter is null"); + return; + } + AsyncContext *context = (AsyncContext *)data; + context->completeFunc(data); + HandlePromiseErrCode(env, *context); + napi_delete_async_work(env, context->work); + delete context; + }, + (void *)asyncContext, + &asyncContext->work); + napi_queue_async_work(env, asyncContext->work); + return UndefinedNapiValue(env); +} + +napi_value DoAsyncWork(const napi_env& env, AsyncContext *asyncContext, + const size_t argc, const napi_value *argv, const size_t nonCallbackArgNum) +{ + if (argc > nonCallbackArgNum) { + InitAsyncCallBackEnv(env, asyncContext, argc, argv, nonCallbackArgNum); + return DoCallBackAsyncWork(env, asyncContext); + } else { + napi_value promise; + InitAsyncPromiseEnv(env, asyncContext, promise); + DoPromiseAsyncWork(env, asyncContext); + return promise; + } +} +} // namespace Wifi +} // namespace OHOS diff --git a/wifi/frameworks/native/BUILD.gn b/wifi/frameworks/native/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..4687ead254a4f67897e46abd463d64b9bb8d5835 --- /dev/null +++ b/wifi/frameworks/native/BUILD.gn @@ -0,0 +1,232 @@ +# Copyright (C) 2021-2022 Huawei Device Co., Ltd. +# 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. + +if (defined(ohos_lite)) { + import("//build/lite/config/component/lite_component.gni") + import("//foundation/communication/wifi/wifi/wifi_lite.gni") + + shared_library("wifi_sdk") { + sources = [ + "c_adapter/src/wifi_c_device.cpp", + "c_adapter/src/wifi_c_utils.cpp", + "src/wifi_device.cpp", + "src/wifi_device_callback_stub_lite.cpp", + "src/wifi_device_impl.cpp", + "src/wifi_device_proxy_lite.cpp", + "src/wifi_msg.cpp", + "src/wifi_scan.cpp", + "src/wifi_scan_callback_stub_lite.cpp", + "src/wifi_scan_impl.cpp", + "src/wifi_scan_proxy_lite.cpp", + ] + + include_dirs = [ + "$WIFI_ROOT_DIR/frameworks/native/include", + "$WIFI_ROOT_DIR/frameworks/native/interfaces", + "$WIFI_ROOT_DIR/frameworks/native/c_adapter/inc", + "$WIFI_ROOT_DIR/services/wifi_standard/wifi_framework/wifi_toolkit/log/", + "$WIFI_ROOT_DIR/services/wifi_standard/wifi_framework/wifi_toolkit/include", + "$WIFI_ROOT_DIR/services/wifi_standard/wifi_framework/wifi_toolkit/net_helper", + "$DHCP_ROOT_DIR/interfaces/inner_api/include", + "$DHCP_ROOT_DIR/services/mgr_service/include", + "$WIFI_ROOT_DIR/utils/inc", + "//base/hiviewdfx/hilog_lite/interfaces/native/innerkits", + "//foundation/communication/ipc/interfaces/innerkits/c/ipc/include", + "//foundation/systemabilitymgr/samgr_lite/interfaces/innerkits/registry", + "//foundation/systemabilitymgr/samgr_lite/interfaces/innerkits/samgr", + "//third_party/bounds_checking_function/include", + "//commonlibrary/c_utils/base/include", + ] + + deps = [ + "$WIFI_ROOT_DIR/utils:wifi_utils", + "//base/hiviewdfx/hilog_lite/frameworks/featured:hilog_shared", + "//foundation/communication/ipc/interfaces/innerkits/c/ipc:ipc_single", + "//foundation/systemabilitymgr/samgr_lite/samgr:samgr", + "//third_party/bounds_checking_function:libsec_shared", + ] + + configs -= [ "//build/lite/config:language_cpp" ] + cflags_cc = [ + "-std=c++17", + "-fno-rtti", + ] + defines = [ "OHOS_ARCH_LITE" ] + ldflags = [ + "-fPIC", + "-Wl,-E", + ] + } +} else { + import("//build/ohos.gni") + import("//foundation/communication/wifi/wifi/wifi.gni") + + ################################################################################ + + config("wifi_sdk_header") { + include_dirs = [ + "//commonlibrary/c_utils/base/include", + "//utils/system/safwk/native/include", + "//base/hiviewdfx/hilog/interfaces/native/innerkits/include", + "//foundation/arkui/ace_engine/frameworks/base/utils", + "//foundation/arkui/ace_engine/frameworks", + "//foundation/systemabilitymgr/samgr/interfaces/innerkits/samgr_proxy/include", + "$WIFI_ROOT_DIR/frameworks/native/include", + "$WIFI_ROOT_DIR/frameworks/native/interfaces", + "$WIFI_ROOT_DIR/frameworks/native/c_adapter/inc", + "$WIFI_ROOT_DIR/services/wifi_standard/wifi_framework/wifi_toolkit/net_helper", + "$WIFI_ROOT_DIR/services/wifi_standard/wifi_framework/wifi_toolkit/log/", + "//foundation/systemabilitymgr/samgr/adapter/interfaces/innerkits/include", + "$WIFI_ROOT_DIR/services/wifi_standard/wifi_framework/wifi_toolkit/include", + "$DHCP_ROOT_DIR/interfaces/inner_api/include", + "$DHCP_ROOT_DIR/services/mgr_service/include", + "$WIFI_ROOT_DIR/interfaces/innerkits", + "$WIFI_ROOT_DIR/utils/inc", + ] + } + + config("wifi_sdk_config") { + visibility = [ "//:*" ] + include_dirs = [ ":wifi_fw_common_header" ] + + cflags = [ + "-std=c++17", + "-fno-rtti", + ] + + if (target_cpu == "arm") { + cflags += [ "-DBINDER_IPC_32BIT" ] + } + } + + ohos_source_set("wifi_device_proxy_impl") { + part_name = "wifi" + sources = [ + "src/wifi_device_impl.cpp", + "src/wifi_device_proxy.cpp", + ] + + configs = [ + ":wifi_sdk_config", + ":wifi_sdk_header", + ] + + external_deps = [ "ipc:ipc_core" ] + } + + ohos_source_set("wifi_hotspot_proxy_impl") { + part_name = "wifi" + sources = [ + "src/wifi_hotspot_impl.cpp", + "src/wifi_hotspot_mgr_proxy.cpp", + "src/wifi_hotspot_proxy.cpp", + ] + + configs = [ + ":wifi_sdk_config", + ":wifi_sdk_header", + ] + + external_deps = [ "ipc:ipc_core" ] + } + + ohos_source_set("wifi_scan_proxy_impl") { + part_name = "wifi" + sources = [ + "src/wifi_scan_impl.cpp", + "src/wifi_scan_proxy.cpp", + ] + + configs = [ + ":wifi_sdk_config", + ":wifi_sdk_header", + ] + + external_deps = [ "ipc:ipc_core" ] + } + + ohos_source_set("wifi_p2p_proxy_impl") { + part_name = "wifi" + sources = [ + "src/wifi_p2p_impl.cpp", + "src/wifi_p2p_proxy.cpp", + ] + + configs = [ + ":wifi_sdk_config", + ":wifi_sdk_header", + ] + + external_deps = [ "ipc:ipc_core" ] + } + + ohos_shared_library("wifi_sdk") { + install_enable = true + sources = [ + "c_adapter/src/wifi_c_device.cpp", + "c_adapter/src/wifi_c_event.cpp", + "c_adapter/src/wifi_c_hid2d.cpp", + "c_adapter/src/wifi_c_hotspot.cpp", + "c_adapter/src/wifi_c_p2p.cpp", + "c_adapter/src/wifi_c_utils.cpp", + "src/wifi_device.cpp", + "src/wifi_device_callback_stub.cpp", + "src/wifi_hid2d.cpp", + "src/wifi_hid2d_msg.cpp", + "src/wifi_hotspot.cpp", + "src/wifi_hotspot_callback_stub.cpp", + "src/wifi_msg.cpp", + "src/wifi_p2p.cpp", + "src/wifi_p2p_callback_stub.cpp", + "src/wifi_p2p_msg.cpp", + "src/wifi_scan.cpp", + "src/wifi_scan_callback_stub.cpp", + ] + + deps = [ + ":wifi_device_proxy_impl", + ":wifi_hotspot_proxy_impl", + ":wifi_p2p_proxy_impl", + ":wifi_scan_proxy_impl", + "$WIFI_ROOT_DIR/utils:wifi_utils", + "//base/hiviewdfx/hilog/interfaces/native/innerkits:libhilog", + "//foundation/systemabilitymgr/samgr/interfaces/innerkits/samgr_proxy:samgr_proxy", + "//third_party/bounds_checking_function:libsec_static", + ] + + external_deps = [ + "c_utils:utils", + "ipc:ipc_core", + ] + + defines = [ "AP_INSTANCE_MAX_NUM=$wifi_feature_with_ap_num" ] + + cflags_cc = [ + "-std=c++17", + "-fno-rtti", + ] + + ldflags = [ + "-fPIC", + "-Wl,-E", + ] + + configs = [ + ":wifi_sdk_config", + ":wifi_sdk_header", + ] + + part_name = "wifi" + subsystem_name = "communication" + } +} diff --git a/interfaces/innerkits/native_cpp/wifi_standard/c_adapter/wifi_c_utils.h b/wifi/frameworks/native/c_adapter/inc/wifi_c_utils.h old mode 100755 new mode 100644 similarity index 47% rename from interfaces/innerkits/native_cpp/wifi_standard/c_adapter/wifi_c_utils.h rename to wifi/frameworks/native/c_adapter/inc/wifi_c_utils.h index f1b1958fb43349aa44587cd1fe030f5af69924a8..ca8074867615d19661e7ffecc0a6877f6d9a773f --- a/interfaces/innerkits/native_cpp/wifi_standard/c_adapter/wifi_c_utils.h +++ b/wifi/frameworks/native/c_adapter/inc/wifi_c_utils.h @@ -1,42 +1,75 @@ -/* - * Copyright (C) 2021 Huawei Device Co., Ltd. - * 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 WIFI_C_UTILS_H_ -#define WIFI_C_UTILS_H_ - -#include -#include "native_c/wifi_device_config.h" -#include "native_c/wifi_error_code.h" -#include "securec.h" -#include "wifi_errcode.h" - -namespace OHOS { -namespace Wifi { -#ifndef CHECK_PTR_RETURN -#define CHECK_PTR_RETURN(ptr, retValue) \ - if ((ptr) == nullptr) { \ - WIFI_LOGE("Error: the ptr is null!"); \ - return retValue; \ - } -#endif - -WifiErrorCode GetCErrorCode(ErrCode errCode); -errno_t MacStrToArray(const std::string& strMac, unsigned char mac[WIFI_MAC_LEN]); -std::string MacArrayToStr(const unsigned char mac[WIFI_MAC_LEN]); -bool IsMacArrayEmpty(const unsigned char mac[WIFI_MAC_LEN]); -} // namespace Wifi -} // namespace OHOS - -#endif +/* + * Copyright (C) 2021 Huawei Device Co., Ltd. + * 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 WIFI_C_UTILS_H_ +#define WIFI_C_UTILS_H_ + +#include +#include +#include "../../../interfaces/kits/c/wifi_device_config.h" +#include "../../../interfaces/kits/c/wifi_error_code.h" +#include "wifi_errcode.h" + +#ifndef IPV4_ARRAY_LEN +#define IPV4_ARRAY_LEN 4 +#endif + +namespace OHOS { +namespace Wifi { +#ifndef CHECK_PTR_RETURN +#define CHECK_PTR_RETURN(ptr, retValue) \ + if ((ptr) == nullptr) { \ + WIFI_LOGE("Error: the ptr is null!"); \ + return retValue; \ + } +#endif + +#ifndef CHECK_PTR_RETURN_VOID +#define CHECK_PTR_RETURN_VOID(ptr) \ + if ((ptr) == nullptr) { \ + WIFI_LOGE("Error: the ptr is null!"); \ + return; \ + } +#endif + +/** + * @Description Convert c++ error code to c error code. + * + * @param errCode - c++ error code + * @return WifiErrorCode - c error code + */ +WifiErrorCode GetCErrorCode(ErrCode errCode); + +/** + * @Description Convert IP address from string to int array. + * + * @param str - IP address of string type + * @param ipAddr - Convert result which is a 4-bit int array, example: 127.0.0.1 -> ipAddr[ 127, 0, 0, 1 ] + * @return WifiErrorCode - operation result + */ +WifiErrorCode IpStrToArray(const std::string& str, unsigned int ipAddr[IPV4_ARRAY_LEN]); + +/** + * @Description Convert IP address from int array to string. + * example: ipAddr[ 127, 0, 0, 1 ] -> 127.0.0.1 + * + * @param ipAddr - IP address of int array + * @return std::string - result + */ +std::string IpArrayToStr(const unsigned int ipAddr[IPV4_ARRAY_LEN]); +} // namespace Wifi +} // namespace OHOS + +#endif diff --git a/interfaces/innerkits/native_cpp/wifi_standard/c_adapter/wifi_c_device.cpp b/wifi/frameworks/native/c_adapter/src/wifi_c_device.cpp old mode 100755 new mode 100644 similarity index 81% rename from interfaces/innerkits/native_cpp/wifi_standard/c_adapter/wifi_c_device.cpp rename to wifi/frameworks/native/c_adapter/src/wifi_c_device.cpp index 5fa4d702ed54823f3646d58784efd6cac7ed3040..e6df3336b8b2d5aa7c64b226ec920dbe46559fb5 --- a/interfaces/innerkits/native_cpp/wifi_standard/c_adapter/wifi_c_device.cpp +++ b/wifi/frameworks/native/c_adapter/src/wifi_c_device.cpp @@ -1,332 +1,355 @@ -/* - * Copyright (C) 2021 Huawei Device Co., Ltd. - * 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 "native_c/wifi_device.h" -#include "native_cpp/wifi_standard/include/wifi_device.h" -#include "native_cpp/wifi_standard/include/wifi_scan.h" -#include "native_c/wifi_scan_info.h" -#include "native_c/wifi_device_config.h" -#include "wifi_logger.h" -#include "wifi_c_utils.h" -#include "securec.h" - -DEFINE_WIFILOG_LABEL("WifiCDevice"); - -static std::map g_secTypeKeyMgmtMap = { - {WIFI_SEC_TYPE_OPEN, "NONE"}, - {WIFI_SEC_TYPE_WEP, "WEP"}, - {WIFI_SEC_TYPE_PSK, "WPA-PSK"}, - {WIFI_SEC_TYPE_SAE, "SAE"}, -}; - -std::unique_ptr wifiDevicePtr = OHOS::Wifi::WifiDevice::GetInstance(WIFI_DEVICE_ABILITY_ID); -std::unique_ptr wifiScanPtr = OHOS::Wifi::WifiScan::GetInstance(WIFI_SCAN_ABILITY_ID); - -WifiErrorCode EnableWifi() -{ - CHECK_PTR_RETURN(wifiDevicePtr, ERROR_WIFI_NOT_AVAILABLE); - return GetCErrorCode(wifiDevicePtr->EnableWifi()); -} - -WifiErrorCode DisableWifi() -{ - CHECK_PTR_RETURN(wifiDevicePtr, ERROR_WIFI_NOT_AVAILABLE); - return GetCErrorCode(wifiDevicePtr->DisableWifi()); -} - -int IsWifiActive() -{ - if (wifiDevicePtr == nullptr) { - return false; - } - - bool isActive = false; - OHOS::Wifi::ErrCode ret = wifiDevicePtr->IsWifiActive(isActive); - return (ret == OHOS::Wifi::WIFI_OPT_SUCCESS) && isActive; -} - -WifiErrorCode Scan() -{ - CHECK_PTR_RETURN(wifiScanPtr, ERROR_WIFI_NOT_AVAILABLE); - return GetCErrorCode(wifiScanPtr->Scan()); -} - -WifiErrorCode GetScanInfoList(WifiScanInfo *result, unsigned int *size) -{ - CHECK_PTR_RETURN(wifiScanPtr, ERROR_WIFI_NOT_AVAILABLE); - if (result == nullptr) { - WIFI_LOGE("Scan info receive addr is null!"); - return ERROR_WIFI_UNKNOWN; - } - - std::vector vecScnIanfos; - OHOS::Wifi::ErrCode ret = wifiScanPtr->GetScanInfoList(vecScnIanfos); - *size = (int)vecScnIanfos.size(); - for (auto& each : vecScnIanfos) { - if (memcpy_s(result->ssid, WIFI_MAX_SSID_LEN, each.ssid.c_str(), each.ssid.size() + 1) != EOK) { - return ERROR_WIFI_UNKNOWN; - } - if (OHOS::Wifi::MacStrToArray(each.bssid, result->bssid) != EOK) { - WIFI_LOGE("Scan info convert bssid error!"); - return ERROR_WIFI_UNKNOWN; - } - result->securityType = static_cast(each.securityType); - result->rssi = each.rssi; - result->band = each.band; - result->frequency = each.frequency; - ++result; - } - return GetCErrorCode(ret); -} - -static std::string GetKeyMgmtBySecType(const int securityType) -{ - WifiSecurityType key = WifiSecurityType(securityType); - std::map::const_iterator iter = g_secTypeKeyMgmtMap.find(key); - return iter == g_secTypeKeyMgmtMap.end() ? "NONE" : iter->second; -} - -static int GetSecTypeByKeyMgmt(const std::string& keyMgmt) -{ - for (auto& each : g_secTypeKeyMgmtMap) { - if (each.second == keyMgmt) { - return static_cast(each.first); - } - } - return static_cast(WIFI_SEC_TYPE_OPEN); -} - -static void GetStaticIpFromC(const IpConfig& ipConfig, OHOS::Wifi::StaticIpAddress& staticIp) -{ - /* Just IPV4 now */ - staticIp.ipAddress.address.addressIpv4 = ipConfig.ipAddress; - staticIp.gateway.addressIpv4 = ipConfig.gateway; - if (WIFI_MAX_DNS_NUM > 0) { - staticIp.dnsServer1.addressIpv4 = ipConfig.dnsServers[0]; - } - /* Has backup DNS server */ - if (WIFI_MAX_DNS_NUM > 1) { - staticIp.dnsServer2.addressIpv4 = ipConfig.dnsServers[1]; - } - /* netmask: automatic calculate netmask, don't support customized set this value currently */ -} - -static void GetStaticIpFromCpp(const OHOS::Wifi::StaticIpAddress& staticIp, IpConfig& ipConfig) -{ - /* Just IPV4 now */ - ipConfig.ipAddress = staticIp.ipAddress.address.addressIpv4; - ipConfig.gateway = staticIp.gateway.addressIpv4; - if (WIFI_MAX_DNS_NUM > 0) { - ipConfig.dnsServers[0] = staticIp.dnsServer1.addressIpv4; - } - /* Has backup DNS server */ - if (WIFI_MAX_DNS_NUM > 1) { - ipConfig.dnsServers[1] = staticIp.dnsServer2.addressIpv4; - } - /* netmask: not support now */ -} - -static void ConvertDeviceConfigFromC(const WifiDeviceConfig *config, OHOS::Wifi::WifiDeviceConfig& deviceConfig) -{ - deviceConfig.ssid = config->ssid; - if (OHOS::Wifi::IsMacArrayEmpty(config->bssid)) { - deviceConfig.bssid = ""; - } else { - deviceConfig.bssid = OHOS::Wifi::MacArrayToStr(config->bssid); - } - deviceConfig.preSharedKey = config->preSharedKey; - deviceConfig.keyMgmt = GetKeyMgmtBySecType(config->securityType); - deviceConfig.networkId = config->netId; - deviceConfig.frequency = config->freq; - /* wapiPskType is not support, don't verify now */ - if (config->ipType == DHCP) { - deviceConfig.wifiIpConfig.assignMethod = OHOS::Wifi::AssignIpMethod::DHCP; - } else if (config->ipType == STATIC_IP) { - deviceConfig.wifiIpConfig.assignMethod = OHOS::Wifi::AssignIpMethod::STATIC; - GetStaticIpFromC(config->staticIp, deviceConfig.wifiIpConfig.staticIpAddress); - } else { - deviceConfig.wifiIpConfig.assignMethod = OHOS::Wifi::AssignIpMethod::UNASSIGNED; - } - deviceConfig.hiddenSSID = config->isHiddenSsid; -} - -static OHOS::Wifi::ErrCode ConvertDeviceConfigFromCpp(const OHOS::Wifi::WifiDeviceConfig& deviceConfig, - WifiDeviceConfig *result) -{ - if (memcpy_s(result->ssid, WIFI_MAX_SSID_LEN, deviceConfig.ssid.c_str(), deviceConfig.ssid.size() + 1) != EOK) { - return OHOS::Wifi::WIFI_OPT_FAILED; - } - if (OHOS::Wifi::MacStrToArray(deviceConfig.bssid, result->bssid) != EOK) { - WIFI_LOGE("device config convert bssid error!"); - return OHOS::Wifi::WIFI_OPT_FAILED; - } - if (memcpy_s(result->preSharedKey, WIFI_MAX_KEY_LEN, deviceConfig.preSharedKey.c_str(), WIFI_MAX_KEY_LEN) != EOK) { - return OHOS::Wifi::WIFI_OPT_FAILED; - } - result->securityType = GetSecTypeByKeyMgmt(deviceConfig.keyMgmt); - result->netId = deviceConfig.networkId; - result->freq = deviceConfig.frequency; - /* wapiPskType is not support now */ - if (deviceConfig.wifiIpConfig.assignMethod == OHOS::Wifi::AssignIpMethod::DHCP) { - result->ipType = DHCP; - } else if (deviceConfig.wifiIpConfig.assignMethod == OHOS::Wifi::AssignIpMethod::STATIC) { - result->ipType = STATIC_IP; - GetStaticIpFromCpp(deviceConfig.wifiIpConfig.staticIpAddress, result->staticIp); - } else { - result->ipType = UNKNOWN; - } - result->isHiddenSsid = deviceConfig.hiddenSSID; - return OHOS::Wifi::WIFI_OPT_SUCCESS; -} - -WifiErrorCode AddDeviceConfig(const WifiDeviceConfig *config, int *result) -{ - CHECK_PTR_RETURN(wifiDevicePtr, ERROR_WIFI_NOT_AVAILABLE); - OHOS::Wifi::WifiDeviceConfig deviceConfig; - ConvertDeviceConfigFromC(config, deviceConfig); - int addResult = -1; - OHOS::Wifi::ErrCode ret = wifiDevicePtr->AddDeviceConfig(deviceConfig, addResult); - *result = addResult; - return GetCErrorCode(ret); -} - -WifiErrorCode GetDeviceConfigs(WifiDeviceConfig *result, unsigned int *size) -{ - CHECK_PTR_RETURN(wifiDevicePtr, ERROR_WIFI_NOT_AVAILABLE); - if (result == nullptr) { - WIFI_LOGE("Get device configs result array is null!"); - return ERROR_WIFI_UNKNOWN; - } - - std::vector vecDeviceConfigs; - OHOS::Wifi::ErrCode ret = wifiDevicePtr->GetDeviceConfigs(vecDeviceConfigs); - if (ret != OHOS::Wifi::WIFI_OPT_SUCCESS) { - WIFI_LOGE("Get device configs error!"); - return GetCErrorCode(ret); - } - *size = (int)vecDeviceConfigs.size(); - for (auto& each : vecDeviceConfigs) { - OHOS::Wifi::ErrCode retValue = ConvertDeviceConfigFromCpp(each, result++); - if (retValue != OHOS::Wifi::WIFI_OPT_SUCCESS) { - ret = retValue; - WIFI_LOGE("Convert device configs error!"); - } - } - return GetCErrorCode(ret); -} - -WifiErrorCode RemoveDevice(int networkId) -{ - CHECK_PTR_RETURN(wifiDevicePtr, ERROR_WIFI_NOT_AVAILABLE); - return GetCErrorCode(wifiDevicePtr->RemoveDevice(networkId)); -} - -WifiErrorCode DisableDeviceConfig(int networkId) -{ - return GetCErrorCode(OHOS::Wifi::WIFI_OPT_NOT_SUPPORTED); -} - -WifiErrorCode EnableDeviceConfig(int networkId) -{ - return GetCErrorCode(OHOS::Wifi::WIFI_OPT_NOT_SUPPORTED); -} - -WifiErrorCode ConnectTo(int networkId) -{ - CHECK_PTR_RETURN(wifiDevicePtr, ERROR_WIFI_NOT_AVAILABLE); - return GetCErrorCode(wifiDevicePtr->ConnectToNetwork(networkId)); -} - -WifiErrorCode ConnectToDevice(const WifiDeviceConfig *config) -{ - CHECK_PTR_RETURN(wifiDevicePtr, ERROR_WIFI_NOT_AVAILABLE); - OHOS::Wifi::WifiDeviceConfig deviceConfig; - ConvertDeviceConfigFromC(config, deviceConfig); - return GetCErrorCode(wifiDevicePtr->ConnectToDevice(deviceConfig)); -} - -WifiErrorCode Disconnect() -{ - CHECK_PTR_RETURN(wifiDevicePtr, ERROR_WIFI_NOT_AVAILABLE); - return GetCErrorCode(wifiDevicePtr->Disconnect()); -} - -static OHOS::Wifi::ErrCode GetLinkedInfoFromCpp(const OHOS::Wifi::WifiLinkedInfo& linkedInfo, WifiLinkedInfo *result) -{ - if (memcpy_s(result->ssid, WIFI_MAX_SSID_LEN, linkedInfo.ssid.c_str(), linkedInfo.ssid.size() + 1) != EOK) { - return OHOS::Wifi::WIFI_OPT_FAILED; - } - if (OHOS::Wifi::MacStrToArray(linkedInfo.bssid, result->bssid) != EOK) { - WIFI_LOGE("linked info convert bssid error!"); - return OHOS::Wifi::WIFI_OPT_FAILED; - } - result->rssi = linkedInfo.rssi; - result->band = linkedInfo.band; - result->frequency = linkedInfo.frequency; - result->connState = linkedInfo.connState == OHOS::Wifi::ConnState::CONNECTED ? WIFI_CONNECTED : WIFI_DISCONNECTED; - /* disconnectedReason not support */ - result->ipAddress = linkedInfo.ipAddress; - return OHOS::Wifi::WIFI_OPT_SUCCESS; -} - -WifiErrorCode GetLinkedInfo(WifiLinkedInfo *result) -{ - CHECK_PTR_RETURN(wifiDevicePtr, ERROR_WIFI_NOT_AVAILABLE); - OHOS::Wifi::WifiLinkedInfo linkedInfo; - OHOS::Wifi::ErrCode ret = wifiDevicePtr->GetLinkedInfo(linkedInfo); - if (ret == OHOS::Wifi::WIFI_OPT_SUCCESS) { - OHOS::Wifi::ErrCode retValue = GetLinkedInfoFromCpp(linkedInfo, result); - if (retValue != OHOS::Wifi::WIFI_OPT_SUCCESS) { - WIFI_LOGE("Get linked info from cpp error!"); - ret = retValue; - } - } - return GetCErrorCode(ret); -} - -WifiErrorCode GetDeviceMacAddress(unsigned char *result) -{ - CHECK_PTR_RETURN(wifiDevicePtr, ERROR_WIFI_NOT_AVAILABLE); - std::string mac; - OHOS::Wifi::ErrCode ret = wifiDevicePtr->GetDeviceMacAddress(mac); - if (ret == OHOS::Wifi::WIFI_OPT_SUCCESS) { - if (OHOS::Wifi::MacStrToArray(mac, result) != EOK) { - WIFI_LOGE("get mac convert to array error!"); - return ERROR_WIFI_UNKNOWN; - } - } - return GetCErrorCode(ret); -} - -WifiErrorCode AdvanceScan(WifiScanParams *params) -{ - return GetCErrorCode(OHOS::Wifi::WIFI_OPT_NOT_SUPPORTED); -} - -WifiErrorCode GetIpInfo(IpInfo *info) -{ - return GetCErrorCode(OHOS::Wifi::WIFI_OPT_NOT_SUPPORTED); -} - -int GetSignalLevel(int rssi, int band) -{ - CHECK_PTR_RETURN(wifiDevicePtr, ERROR_WIFI_NOT_AVAILABLE); - int level = -1; - OHOS::Wifi::ErrCode ret = wifiDevicePtr->GetSignalLevel(rssi, band, level); - if (ret != OHOS::Wifi::WIFI_OPT_SUCCESS) { - WIFI_LOGW("Get wifi signal level fail: %{public}d", ret); - } - return level; -} +/* + * Copyright (C) 2021-2022 Huawei Device Co., Ltd. + * 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 "../../../interfaces/kits/c/wifi_device.h" +#include "../../include/wifi_device.h" +#include "../../include/wifi_scan.h" +#include "../../../interfaces/kits/c/wifi_scan_info.h" +#include "../../../interfaces/kits/c/wifi_device_config.h" +#include "wifi_logger.h" +#include "wifi_c_utils.h" +#include "wifi_common_util.h" + +DEFINE_WIFILOG_LABEL("WifiCDevice"); + +static std::map g_secTypeKeyMgmtMap = { + {WIFI_SEC_TYPE_OPEN, "NONE"}, + {WIFI_SEC_TYPE_WEP, "WEP"}, + {WIFI_SEC_TYPE_PSK, "WPA-PSK"}, + {WIFI_SEC_TYPE_SAE, "SAE"}, +}; + +std::unique_ptr wifiDevicePtr = OHOS::Wifi::WifiDevice::GetInstance(WIFI_DEVICE_ABILITY_ID); +std::unique_ptr wifiScanPtr = OHOS::Wifi::WifiScan::GetInstance(WIFI_SCAN_ABILITY_ID); + +WifiErrorCode EnableWifi() +{ + CHECK_PTR_RETURN(wifiDevicePtr, ERROR_WIFI_NOT_AVAILABLE); + return GetCErrorCode(wifiDevicePtr->EnableWifi()); +} + +WifiErrorCode DisableWifi() +{ + CHECK_PTR_RETURN(wifiDevicePtr, ERROR_WIFI_NOT_AVAILABLE); + return GetCErrorCode(wifiDevicePtr->DisableWifi()); +} + +int IsWifiActive() +{ + if (wifiDevicePtr == nullptr) { + return false; + } + + bool isActive = false; + OHOS::Wifi::ErrCode ret = wifiDevicePtr->IsWifiActive(isActive); + return (ret == OHOS::Wifi::WIFI_OPT_SUCCESS) && isActive; +} + +WifiErrorCode Scan() +{ + CHECK_PTR_RETURN(wifiScanPtr, ERROR_WIFI_NOT_AVAILABLE); + return GetCErrorCode(wifiScanPtr->Scan()); +} + +WifiErrorCode GetScanInfoList(WifiScanInfo *result, unsigned int *size) +{ + CHECK_PTR_RETURN(wifiScanPtr, ERROR_WIFI_NOT_AVAILABLE); + if (result == nullptr || size == nullptr) { + WIFI_LOGE("Scan info input parameter is nullptr!"); + return ERROR_WIFI_UNKNOWN; + } + + std::vector vecScanInfos; + OHOS::Wifi::ErrCode ret = wifiScanPtr->GetScanInfoList(vecScanInfos); + int vecSize = (int)vecScanInfos.size(); + for (int i = 0; i < vecSize && i < WIFI_SCAN_HOTSPOT_LIMIT; ++i) { + if (memcpy_s(result->ssid, WIFI_MAX_SSID_LEN, + vecScanInfos[i].ssid.c_str(), vecScanInfos[i].ssid.size() + 1) != EOK) { + return ERROR_WIFI_UNKNOWN; + } + if (OHOS::Wifi::MacStrToArray(vecScanInfos[i].bssid, result->bssid) != EOK) { + WIFI_LOGE("Scan info convert bssid error!"); + return ERROR_WIFI_UNKNOWN; + } + result->securityType = static_cast(vecScanInfos[i].securityType); + result->rssi = vecScanInfos[i].rssi; + result->band = vecScanInfos[i].band; + result->frequency = vecScanInfos[i].frequency; + result->channelWidth = WifiChannelWidth(static_cast(vecScanInfos[i].channelWidth)); + result->centerFrequency0 = vecScanInfos[i].centerFrequency0; + result->centerFrequency1 = vecScanInfos[i].centerFrequency1; + result->timestamp = vecScanInfos[i].timestamp; + ++result; + } + *size = (vecSize < WIFI_SCAN_HOTSPOT_LIMIT) ? vecSize : WIFI_SCAN_HOTSPOT_LIMIT; + return GetCErrorCode(ret); +} + +static std::string GetKeyMgmtBySecType(const int securityType) +{ + WifiSecurityType key = WifiSecurityType(securityType); + std::map::const_iterator iter = g_secTypeKeyMgmtMap.find(key); + return iter == g_secTypeKeyMgmtMap.end() ? "NONE" : iter->second; +} + +static int GetSecTypeByKeyMgmt(const std::string& keyMgmt) +{ + for (auto& each : g_secTypeKeyMgmtMap) { + if (each.second == keyMgmt) { + return static_cast(each.first); + } + } + return static_cast(WIFI_SEC_TYPE_OPEN); +} + +static void GetStaticIpFromC(const IpConfig& ipConfig, OHOS::Wifi::StaticIpAddress& staticIp) +{ + /* Just IPV4 now */ + staticIp.ipAddress.address.addressIpv4 = ipConfig.ipAddress; + staticIp.gateway.addressIpv4 = ipConfig.gateway; + if (WIFI_MAX_DNS_NUM > 0) { + staticIp.dnsServer1.addressIpv4 = ipConfig.dnsServers[0]; + } + /* Has backup DNS server */ + if (WIFI_MAX_DNS_NUM > 1) { + staticIp.dnsServer2.addressIpv4 = ipConfig.dnsServers[1]; + } + /* netmask: automatic calculate netmask, don't support customized set this value currently */ +} + +static void GetStaticIpFromCpp(const OHOS::Wifi::StaticIpAddress& staticIp, IpConfig& ipConfig) +{ + /* Just IPV4 now */ + ipConfig.ipAddress = staticIp.ipAddress.address.addressIpv4; + ipConfig.gateway = staticIp.gateway.addressIpv4; + if (WIFI_MAX_DNS_NUM > 0) { + ipConfig.dnsServers[0] = staticIp.dnsServer1.addressIpv4; + } + /* Has backup DNS server */ + if (WIFI_MAX_DNS_NUM > 1) { + ipConfig.dnsServers[1] = staticIp.dnsServer2.addressIpv4; + } + /* netmask: not support now */ +} + +static void ConvertDeviceConfigFromC(const WifiDeviceConfig *config, OHOS::Wifi::WifiDeviceConfig& deviceConfig) +{ + CHECK_PTR_RETURN_VOID(config); + deviceConfig.ssid = config->ssid; + if (OHOS::Wifi::IsMacArrayEmpty(config->bssid)) { + deviceConfig.bssid = ""; + } else { + deviceConfig.bssid = OHOS::Wifi::MacArrayToStr(config->bssid); + } + deviceConfig.preSharedKey = config->preSharedKey; + deviceConfig.keyMgmt = GetKeyMgmtBySecType(config->securityType); + deviceConfig.networkId = config->netId; + deviceConfig.frequency = config->freq; + /* wapiPskType is not support, don't verify now */ + if (config->ipType == DHCP) { + deviceConfig.wifiIpConfig.assignMethod = OHOS::Wifi::AssignIpMethod::DHCP; + } else if (config->ipType == STATIC_IP) { + deviceConfig.wifiIpConfig.assignMethod = OHOS::Wifi::AssignIpMethod::STATIC; + GetStaticIpFromC(config->staticIp, deviceConfig.wifiIpConfig.staticIpAddress); + } else { + deviceConfig.wifiIpConfig.assignMethod = OHOS::Wifi::AssignIpMethod::UNASSIGNED; + } + deviceConfig.hiddenSSID = config->isHiddenSsid; +} + +static OHOS::Wifi::ErrCode ConvertDeviceConfigFromCpp(const OHOS::Wifi::WifiDeviceConfig& deviceConfig, + WifiDeviceConfig *result) +{ + CHECK_PTR_RETURN(result, OHOS::Wifi::WIFI_OPT_INVALID_PARAM); + if (memcpy_s(result->ssid, WIFI_MAX_SSID_LEN, deviceConfig.ssid.c_str(), deviceConfig.ssid.size() + 1) != EOK) { + return OHOS::Wifi::WIFI_OPT_FAILED; + } + if (OHOS::Wifi::MacStrToArray(deviceConfig.bssid, result->bssid) != EOK) { + WIFI_LOGE("device config convert bssid error!"); + return OHOS::Wifi::WIFI_OPT_FAILED; + } + if (memcpy_s(result->preSharedKey, WIFI_MAX_KEY_LEN, deviceConfig.preSharedKey.c_str(), WIFI_MAX_KEY_LEN) != EOK) { + return OHOS::Wifi::WIFI_OPT_FAILED; + } + result->securityType = GetSecTypeByKeyMgmt(deviceConfig.keyMgmt); + result->netId = deviceConfig.networkId; + result->freq = deviceConfig.frequency; + /* wapiPskType is not support now */ + if (deviceConfig.wifiIpConfig.assignMethod == OHOS::Wifi::AssignIpMethod::DHCP) { + result->ipType = DHCP; + } else if (deviceConfig.wifiIpConfig.assignMethod == OHOS::Wifi::AssignIpMethod::STATIC) { + result->ipType = STATIC_IP; + GetStaticIpFromCpp(deviceConfig.wifiIpConfig.staticIpAddress, result->staticIp); + } else { + result->ipType = UNKNOWN; + } + result->isHiddenSsid = deviceConfig.hiddenSSID; + return OHOS::Wifi::WIFI_OPT_SUCCESS; +} + +WifiErrorCode AddDeviceConfig(const WifiDeviceConfig *config, int *result) +{ + CHECK_PTR_RETURN(wifiDevicePtr, ERROR_WIFI_NOT_AVAILABLE); + CHECK_PTR_RETURN(config, ERROR_WIFI_INVALID_ARGS); + CHECK_PTR_RETURN(result, ERROR_WIFI_INVALID_ARGS); + OHOS::Wifi::WifiDeviceConfig deviceConfig; + ConvertDeviceConfigFromC(config, deviceConfig); + int addResult = -1; + bool isCandidate = false; + OHOS::Wifi::ErrCode ret = wifiDevicePtr->AddDeviceConfig(deviceConfig, addResult, isCandidate); + *result = addResult; + return GetCErrorCode(ret); +} + +WifiErrorCode GetDeviceConfigs(WifiDeviceConfig *result, unsigned int *size) +{ + CHECK_PTR_RETURN(wifiDevicePtr, ERROR_WIFI_NOT_AVAILABLE); + CHECK_PTR_RETURN(result, ERROR_WIFI_INVALID_ARGS); + CHECK_PTR_RETURN(size, ERROR_WIFI_INVALID_ARGS); + std::vector vecDeviceConfigs; + bool isCandidate = false; + OHOS::Wifi::ErrCode ret = wifiDevicePtr->GetDeviceConfigs(vecDeviceConfigs, isCandidate); + if (ret != OHOS::Wifi::WIFI_OPT_SUCCESS) { + WIFI_LOGE("Get device configs error!"); + return GetCErrorCode(ret); + } + *size = (int)vecDeviceConfigs.size(); + for (auto& each : vecDeviceConfigs) { + OHOS::Wifi::ErrCode retValue = ConvertDeviceConfigFromCpp(each, result++); + if (retValue != OHOS::Wifi::WIFI_OPT_SUCCESS) { + ret = retValue; + WIFI_LOGE("Convert device configs error!"); + } + } + return GetCErrorCode(ret); +} + +WifiErrorCode RemoveDevice(int networkId) +{ + CHECK_PTR_RETURN(wifiDevicePtr, ERROR_WIFI_NOT_AVAILABLE); + return GetCErrorCode(wifiDevicePtr->RemoveDevice(networkId)); +} + +WifiErrorCode DisableDeviceConfig(int networkId) +{ + return GetCErrorCode(OHOS::Wifi::WIFI_OPT_NOT_SUPPORTED); +} + +WifiErrorCode EnableDeviceConfig(int networkId) +{ + return GetCErrorCode(OHOS::Wifi::WIFI_OPT_NOT_SUPPORTED); +} + +WifiErrorCode ConnectTo(int networkId) +{ + CHECK_PTR_RETURN(wifiDevicePtr, ERROR_WIFI_NOT_AVAILABLE); + bool isCandidate = false; + return GetCErrorCode(wifiDevicePtr->ConnectToNetwork(networkId, isCandidate)); +} + +WifiErrorCode ConnectToDevice(const WifiDeviceConfig *config) +{ + CHECK_PTR_RETURN(wifiDevicePtr, ERROR_WIFI_NOT_AVAILABLE); + CHECK_PTR_RETURN(config, ERROR_WIFI_INVALID_ARGS); + OHOS::Wifi::WifiDeviceConfig deviceConfig; + ConvertDeviceConfigFromC(config, deviceConfig); + return GetCErrorCode(wifiDevicePtr->ConnectToDevice(deviceConfig)); +} + +WifiErrorCode Disconnect() +{ + CHECK_PTR_RETURN(wifiDevicePtr, ERROR_WIFI_NOT_AVAILABLE); + return GetCErrorCode(wifiDevicePtr->Disconnect()); +} + +static OHOS::Wifi::ErrCode GetLinkedInfoFromCpp(const OHOS::Wifi::WifiLinkedInfo& linkedInfo, WifiLinkedInfo *result) +{ + CHECK_PTR_RETURN(result, OHOS::Wifi::WIFI_OPT_INVALID_PARAM); + if (memcpy_s(result->ssid, WIFI_MAX_SSID_LEN, linkedInfo.ssid.c_str(), linkedInfo.ssid.size() + 1) != EOK) { + return OHOS::Wifi::WIFI_OPT_FAILED; + } + if (OHOS::Wifi::MacStrToArray(linkedInfo.bssid, result->bssid) != EOK) { + WIFI_LOGE("linked info convert bssid error!"); + return OHOS::Wifi::WIFI_OPT_FAILED; + } + result->rssi = linkedInfo.rssi; + result->band = linkedInfo.band; + result->frequency = linkedInfo.frequency; + result->connState = linkedInfo.connState == OHOS::Wifi::ConnState::CONNECTED ? WIFI_CONNECTED : WIFI_DISCONNECTED; + /* disconnectedReason not support */ + result->ipAddress = linkedInfo.ipAddress; + return OHOS::Wifi::WIFI_OPT_SUCCESS; +} + +WifiErrorCode GetLinkedInfo(WifiLinkedInfo *result) +{ + CHECK_PTR_RETURN(wifiDevicePtr, ERROR_WIFI_NOT_AVAILABLE); + CHECK_PTR_RETURN(result, ERROR_WIFI_INVALID_ARGS); + OHOS::Wifi::WifiLinkedInfo linkedInfo; + OHOS::Wifi::ErrCode ret = wifiDevicePtr->GetLinkedInfo(linkedInfo); + if (ret == OHOS::Wifi::WIFI_OPT_SUCCESS) { + OHOS::Wifi::ErrCode retValue = GetLinkedInfoFromCpp(linkedInfo, result); + if (retValue != OHOS::Wifi::WIFI_OPT_SUCCESS) { + WIFI_LOGE("Get linked info from cpp error!"); + ret = retValue; + } + } + return GetCErrorCode(ret); +} + +WifiErrorCode GetDeviceMacAddress(unsigned char *result) +{ + CHECK_PTR_RETURN(wifiDevicePtr, ERROR_WIFI_NOT_AVAILABLE); + CHECK_PTR_RETURN(result, ERROR_WIFI_INVALID_ARGS); + std::string mac; + OHOS::Wifi::ErrCode ret = wifiDevicePtr->GetDeviceMacAddress(mac); + if (ret == OHOS::Wifi::WIFI_OPT_SUCCESS) { + if (OHOS::Wifi::MacStrToArray(mac, result) != EOK) { + WIFI_LOGE("get mac convert to array error!"); + return ERROR_WIFI_UNKNOWN; + } + } + return GetCErrorCode(ret); +} + +WifiErrorCode AdvanceScan(WifiScanParams *params) +{ + CHECK_PTR_RETURN(params, ERROR_WIFI_INVALID_ARGS); + return GetCErrorCode(OHOS::Wifi::WIFI_OPT_NOT_SUPPORTED); +} + +WifiErrorCode GetIpInfo(IpInfo *info) +{ + CHECK_PTR_RETURN(info, ERROR_WIFI_INVALID_ARGS); + return GetCErrorCode(OHOS::Wifi::WIFI_OPT_NOT_SUPPORTED); +} + +int GetSignalLevel(int rssi, int band) +{ + CHECK_PTR_RETURN(wifiDevicePtr, ERROR_WIFI_NOT_AVAILABLE); + int level = -1; + OHOS::Wifi::ErrCode ret = wifiDevicePtr->GetSignalLevel(rssi, band, level); + if (ret != OHOS::Wifi::WIFI_OPT_SUCCESS) { + WIFI_LOGW("Get wifi signal level fail: %{public}d", ret); + } + return level; +} + +WifiErrorCode SetLowLatencyMode(int enabled) +{ + CHECK_PTR_RETURN(wifiDevicePtr, ERROR_WIFI_NOT_AVAILABLE); + bool ret = wifiDevicePtr->SetLowLatencyMode(enabled); + return ret ? WIFI_SUCCESS : ERROR_WIFI_NOT_AVAILABLE; +} diff --git a/wifi/frameworks/native/c_adapter/src/wifi_c_event.cpp b/wifi/frameworks/native/c_adapter/src/wifi_c_event.cpp new file mode 100644 index 0000000000000000000000000000000000000000..9b208acbf647ad12cfc5121c55d4d8b66be867b7 --- /dev/null +++ b/wifi/frameworks/native/c_adapter/src/wifi_c_event.cpp @@ -0,0 +1,243 @@ +/* + * Copyright (C) 2021-2022 Huawei Device Co., Ltd. + * 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 "../../../interfaces/kits/c/wifi_event.h" +#include +#include "../../../interfaces/kits/c/wifi_device.h" +#include "../../../interfaces/kits/c/wifi_scan_info.h" +#include "i_wifi_device_callback.h" +#include "i_wifi_hotspot_callback.h" +#include "i_wifi_scan_callback.h" +#include "wifi_device.h" +#include "wifi_hotspot.h" +#include "wifi_logger.h" +#include "wifi_scan.h" + +DEFINE_WIFILOG_LABEL("WifiCEvent"); +std::set GetEventCallBacks(); + +class WifiCDeviceEventCallback : public OHOS::Wifi::IWifiDeviceCallBack { +public: + WifiCDeviceEventCallback() { + } + + virtual ~WifiCDeviceEventCallback() { + } + +public: + void OnWifiStateChanged(int state) override { + WIFI_LOGI("sta received state changed event: %{public}d", state); + } + + void OnWifiConnectionChanged(int state, const OHOS::Wifi::WifiLinkedInfo &info) override { + WIFI_LOGI("sta received connection changed event: %{public}d", state); + WifiLinkedInfo linkInfo; + WifiErrorCode ret = GetLinkedInfo(&linkInfo); + if (ret != WIFI_SUCCESS) { + WIFI_LOGE("Received event get linked info failed"); + return; + } + std::set setCallbacks = GetEventCallBacks(); + for (auto& callback : setCallbacks) { + if (callback && callback->OnWifiConnectionChanged) { + callback->OnWifiConnectionChanged(state, &linkInfo); + } + } + } + + void OnWifiRssiChanged(int rssi) override { + WIFI_LOGI("sta received rssi changed event: %{public}d", rssi); + } + + void OnWifiWpsStateChanged(int state, const std::string &pinCode) override { + } + + void OnStreamChanged(int direction) override { + } + + void OnDeviceConfigChanged(OHOS::Wifi::ConfigChange value) override { + std::set setCallbacks = GetEventCallBacks(); + for (auto& callback : setCallbacks) { + if (callback && callback->OnDeviceConfigChange) { + callback->OnDeviceConfigChange(ConfigChange(static_cast(value))); + } + } + } + + OHOS::sptr AsObject() override { + return nullptr; + } +}; + +class WifiCScanEventCallback : public OHOS::Wifi::IWifiScanCallback { +public: + WifiCScanEventCallback() { + } + + virtual ~WifiCScanEventCallback() { + } + +public: + void OnWifiScanStateChanged(int state) override { + WIFI_LOGI("scan received state changed event: %{public}d", state); + std::set setCallbacks = GetEventCallBacks(); + for (auto& callback : setCallbacks) { + if (callback && callback->OnWifiScanStateChanged) { + callback->OnWifiScanStateChanged(state, WIFI_SCAN_HOTSPOT_LIMIT); + } + } + } + + OHOS::sptr AsObject() override { + return nullptr; + } +}; + +class WifiCHotspotEventCallback : public OHOS::Wifi::IWifiHotspotCallback { +public: + WifiCHotspotEventCallback() { + } + + virtual ~WifiCHotspotEventCallback() { + } + +public: + void OnHotspotStateChanged(int state) override { + WIFI_LOGI("Hotspot received state changed event: %{public}d", state); + std::set setCallbacks = GetEventCallBacks(); + for (auto& callback : setCallbacks) { + if (callback && callback->OnHotspotStateChanged) { + callback->OnHotspotStateChanged(state); + } + } + } + + void OnHotspotStaJoin(const OHOS::Wifi::StationInfo &info) override { + WIFI_LOGI("Hotspot received sta join event"); + } + + void OnHotspotStaLeave(const OHOS::Wifi::StationInfo &info) override { + WIFI_LOGI("Hotspot received sta leave event"); + } + + OHOS::sptr AsObject() override { + return nullptr; + } +}; + +OHOS::sptr wifiCDeviceCallback = + OHOS::sptr(new (std::nothrow) WifiCDeviceEventCallback()); +OHOS::sptr wifiCScanCallback = + OHOS::sptr(new (std::nothrow) WifiCScanEventCallback()); +OHOS::sptr wifiCHotspotCallback = + OHOS::sptr(new (std::nothrow) WifiCHotspotEventCallback()); + +class EventManager { +public: + EventManager() { + } + + virtual ~EventManager() { + } + + bool AddEventCallback(WifiEvent *cb) { + if (cb == NULL) { + return false; + } + return m_setEventCallback.insert(cb).second; + } + + void RemoveEventCallback(WifiEvent *cb) { + m_setEventCallback.erase(cb); + } + + WifiErrorCode RegisterWifiEvents() { + using namespace OHOS::Wifi; + std::unique_ptr wifiStaPtr = WifiDevice::GetInstance(WIFI_DEVICE_ABILITY_ID); + if (wifiStaPtr == nullptr) { + WIFI_LOGE("Register sta event get instance failed!"); + return ERROR_WIFI_UNKNOWN; + } + ErrCode ret = wifiStaPtr->RegisterCallBack(wifiCDeviceCallback); + if (ret != WIFI_OPT_SUCCESS) { + WIFI_LOGE("Register sta event failed!"); + return ERROR_WIFI_UNKNOWN; + } + + std::unique_ptr wifiScanPtr = WifiScan::GetInstance(WIFI_SCAN_ABILITY_ID); + if (wifiScanPtr == nullptr) { + WIFI_LOGE("Register scan event get instance failed!"); + return ERROR_WIFI_UNKNOWN; + } + ret = wifiScanPtr->RegisterCallBack(wifiCScanCallback); + if (ret != WIFI_OPT_SUCCESS) { + WIFI_LOGE("Register scan event failed!"); + return ERROR_WIFI_UNKNOWN; + } + + std::unique_ptr wifiHotspotPtr = WifiHotspot::GetInstance(WIFI_HOTSPOT_ABILITY_ID); + if (wifiHotspotPtr == nullptr) { + WIFI_LOGE("Register hotspot event get instance failed!"); + return ERROR_WIFI_UNKNOWN; + } + ret = wifiHotspotPtr->RegisterCallBack(wifiCHotspotCallback); + if (ret != WIFI_OPT_SUCCESS) { + WIFI_LOGE("Register hotspot event failed!"); + return ERROR_WIFI_UNKNOWN; + } + return WIFI_SUCCESS; + } + + bool IsEventRegistered() { + return m_isEventRegistered; + } + + void SetIsEventRegistrated(bool isEventRegistered) { + m_isEventRegistered = isEventRegistered; + } + + std::set GetEventCallBacks() { + return m_setEventCallback; + } + +private: + static std::set m_setEventCallback; + static bool m_isEventRegistered; +}; +std::set EventManager::m_setEventCallback; +bool EventManager::m_isEventRegistered = false; +static EventManager g_eventManager; + +std::set GetEventCallBacks() { + return g_eventManager.GetEventCallBacks(); +} + +WifiErrorCode RegisterWifiEvent(WifiEvent *event) { + WIFI_LOGI("Register wifi event"); + if (!g_eventManager.IsEventRegistered()) { + if (g_eventManager.RegisterWifiEvents() != WIFI_SUCCESS) { + WIFI_LOGE("Wifi event register failed!"); + return ERROR_WIFI_UNKNOWN; + } + g_eventManager.SetIsEventRegistrated(true); + } + return g_eventManager.AddEventCallback(event) ? WIFI_SUCCESS : ERROR_WIFI_INVALID_ARGS; +} + +WifiErrorCode UnRegisterWifiEvent(WifiEvent *event) { + WIFI_LOGI("Unregister wifi event"); + g_eventManager.RemoveEventCallback(event); + return WIFI_SUCCESS; +} diff --git a/wifi/frameworks/native/c_adapter/src/wifi_c_hid2d.cpp b/wifi/frameworks/native/c_adapter/src/wifi_c_hid2d.cpp new file mode 100644 index 0000000000000000000000000000000000000000..84d745c1f42a4a861f7294b0b9ffaacac87c156c --- /dev/null +++ b/wifi/frameworks/native/c_adapter/src/wifi_c_hid2d.cpp @@ -0,0 +1,190 @@ +/* + * Copyright (C) 2022 Huawei Device Co., Ltd. + * 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 "../../../interfaces/kits/c/wifi_hid2d.h" +#include "../../include/wifi_hid2d.h" +#include "define.h" +#include "wifi_logger.h" +#include "wifi_c_utils.h" +#include "wifi_common_util.h" +#include "../../../interfaces/kits/c/wifi_device.h" + +DEFINE_WIFILOG_LABEL("WifiCHid2d"); + +std::unique_ptr wifiHid2dPtr = OHOS::Wifi::Hid2d::GetInstance(WIFI_P2P_ABILITY_ID); + +WifiErrorCode Hid2dRequestGcIp(const unsigned char gcMac[MAC_LEN], unsigned int ipAddr[IPV4_ARRAY_LEN]) +{ + CHECK_PTR_RETURN(wifiHid2dPtr, ERROR_WIFI_NOT_AVAILABLE); + + std::string strMac = OHOS::Wifi::MacArrayToStr(gcMac); + std::string strIpAddr; + OHOS::Wifi::ErrCode ret = wifiHid2dPtr->Hid2dRequestGcIp(strMac, strIpAddr); + if (ret != OHOS::Wifi::WIFI_OPT_SUCCESS) { + WIFI_LOGE("Request gc ip failed!"); + return ERROR_WIFI_UNKNOWN; + } + return OHOS::Wifi::IpStrToArray(strIpAddr, ipAddr); +} + +WifiErrorCode Hid2dSharedlinkIncrease(void) +{ + CHECK_PTR_RETURN(wifiHid2dPtr, ERROR_WIFI_NOT_AVAILABLE); + return GetCErrorCode(wifiHid2dPtr->Hid2dSharedlinkIncrease()); +} + +WifiErrorCode Hid2dSharedlinkDecrease(void) +{ + CHECK_PTR_RETURN(wifiHid2dPtr, ERROR_WIFI_NOT_AVAILABLE); + return GetCErrorCode(wifiHid2dPtr->Hid2dSharedlinkDecrease()); +} + +WifiErrorCode Hid2dCreateGroup(const int frequency, FreqType type) +{ + CHECK_PTR_RETURN(wifiHid2dPtr, ERROR_WIFI_NOT_AVAILABLE); + return GetCErrorCode(wifiHid2dPtr->Hid2dCreateGroup(frequency, OHOS::Wifi::FreqType(static_cast(type)))); +} + +WifiErrorCode Hid2dRemoveGcGroup(const char gcIfName[IF_NAME_LEN]) +{ + CHECK_PTR_RETURN(wifiHid2dPtr, ERROR_WIFI_NOT_AVAILABLE); + return GetCErrorCode(wifiHid2dPtr->Hid2dRemoveGcGroup(gcIfName)); +} + +WifiErrorCode Hid2dConnect(const Hid2dConnectConfig *config) +{ + CHECK_PTR_RETURN(wifiHid2dPtr, ERROR_WIFI_NOT_AVAILABLE); + CHECK_PTR_RETURN(config, ERROR_WIFI_INVALID_ARGS); + + OHOS::Wifi::Hid2dConnectConfig cppConfig; + cppConfig.SetSsid(config->ssid); + cppConfig.SetBssid(OHOS::Wifi::MacArrayToStr(config->bssid)); + cppConfig.SetPreSharedKey(config->preSharedKey); + cppConfig.SetFrequency(config->frequency); + cppConfig.SetDhcpMode(OHOS::Wifi::DhcpMode(static_cast(config->dhcpMode))); + return GetCErrorCode(wifiHid2dPtr->Hid2dConnect(cppConfig)); +} + +WifiErrorCode Hid2dConfigIPAddr(const char ifName[IF_NAME_LEN], const IpAddrInfo* ipInfo) +{ + CHECK_PTR_RETURN(wifiHid2dPtr, ERROR_WIFI_NOT_AVAILABLE); + CHECK_PTR_RETURN(ipInfo, ERROR_WIFI_INVALID_ARGS); + + OHOS::Wifi::IpAddrInfo ipAddrInfo; + ipAddrInfo.ip = OHOS::Wifi::IpArrayToStr(ipInfo->ip); + ipAddrInfo.gateway = OHOS::Wifi::IpArrayToStr(ipInfo->gateway); + ipAddrInfo.netmask = OHOS::Wifi::IpArrayToStr(ipInfo->netmask); + return GetCErrorCode(wifiHid2dPtr->Hid2dConfigIPAddr(ifName, ipAddrInfo)); +} + +WifiErrorCode Hid2dReleaseIPAddr(const char ifName[IF_NAME_LEN]) +{ + CHECK_PTR_RETURN(wifiHid2dPtr, ERROR_WIFI_NOT_AVAILABLE); + return GetCErrorCode(wifiHid2dPtr->Hid2dReleaseIPAddr(ifName)); +} + +static void ConvertRecommendChannelRequest(const RecommendChannelRequest *request, + OHOS::Wifi::RecommendChannelRequest& req) +{ + CHECK_PTR_RETURN_VOID(request); + req.remoteIfName = request->remoteIfName; + req.remoteIfMode = request->remoteIfMode; + req.localIfName = request->localIfName; + req.localIfMode = request->localIfMode; + req.prefBand = request->prefBand; + req.prefBandwidth = OHOS::Wifi::PreferBandwidth(static_cast(request->prefBandwidth)); +} + +static void ConvertRecommendChannelResponse(const OHOS::Wifi::RecommendChannelResponse& rsp, + RecommendChannelResponse* response) +{ + CHECK_PTR_RETURN_VOID(response); + response->status = RecommendStatus(static_cast(rsp.status)); + response->index = rsp.index; + response->centerFreq = rsp.centerFreq; + response->centerFreq1 = rsp.centerFreq1; + response->centerFreq2 = rsp.centerFreq2; + response->bandwidth = rsp.bandwidth; +} + +WifiErrorCode Hid2dGetRecommendChannel(const RecommendChannelRequest *request, RecommendChannelResponse *response) +{ + CHECK_PTR_RETURN(wifiHid2dPtr, ERROR_WIFI_NOT_AVAILABLE); + CHECK_PTR_RETURN(request, ERROR_WIFI_INVALID_ARGS); + CHECK_PTR_RETURN(response, ERROR_WIFI_INVALID_ARGS); + OHOS::Wifi::RecommendChannelRequest req; + OHOS::Wifi::RecommendChannelResponse rsp; + ConvertRecommendChannelRequest(request, req); + OHOS::Wifi::ErrCode retCode = wifiHid2dPtr->Hid2dGetRecommendChannel(req, rsp); + if (retCode != OHOS::Wifi::WIFI_OPT_SUCCESS) { + return GetCErrorCode(retCode); + } + ConvertRecommendChannelResponse(rsp, response); + return WIFI_SUCCESS; +} + +WifiErrorCode Hid2dGetChannelListFor5G(int *chanList, int len) +{ + CHECK_PTR_RETURN(wifiHid2dPtr, ERROR_WIFI_NOT_AVAILABLE); + CHECK_PTR_RETURN(chanList, ERROR_WIFI_INVALID_ARGS); + + std::vector vecChannelList; + OHOS::Wifi::ErrCode ret = wifiHid2dPtr->Hid2dGetChannelListFor5G(vecChannelList); + if (ret == OHOS::Wifi::WIFI_OPT_SUCCESS) { + size_t idx = 0; + for (; idx != vecChannelList.size() && (int)(idx + 1) < len; ++idx) { + *chanList = vecChannelList[idx]; + ++chanList; + } + if (idx != vecChannelList.size()) { + WIFI_LOGW("Get channel list for 5G, `chanList` is too small!"); + } + *chanList = 0; + } + return GetCErrorCode(ret); +} + +WifiErrorCode Hid2dGetSelfWifiCfgInfo(SelfCfgType cfgType, char cfgData[CFG_DATA_MAX_BYTES], int* getDatValidLen) +{ + CHECK_PTR_RETURN(wifiHid2dPtr, ERROR_WIFI_NOT_AVAILABLE); + CHECK_PTR_RETURN(getDatValidLen, ERROR_WIFI_INVALID_ARGS); + return GetCErrorCode(wifiHid2dPtr->Hid2dGetSelfWifiCfgInfo( + OHOS::Wifi::SelfCfgType(static_cast(cfgType)), cfgData, getDatValidLen)); +} + +WifiErrorCode Hid2dSetPeerWifiCfgInfo(PeerCfgType cfgType, char cfgData[CFG_DATA_MAX_BYTES], int setDataValidLen) +{ + CHECK_PTR_RETURN(wifiHid2dPtr, ERROR_WIFI_NOT_AVAILABLE); + return GetCErrorCode(wifiHid2dPtr->Hid2dSetPeerWifiCfgInfo( + OHOS::Wifi::PeerCfgType(static_cast(cfgType)), cfgData, setDataValidLen)); +} + +int Hid2dIsWideBandwidthSupported(void) +{ + constexpr int NOT_SUPPORT = 0; // false + return NOT_SUPPORT; +} + +WifiErrorCode Hid2dSetUpperScene(const char ifName[IF_NAME_LEN], const Hid2dUpperScene *scene) +{ + CHECK_PTR_RETURN(wifiHid2dPtr, ERROR_WIFI_NOT_AVAILABLE); + CHECK_PTR_RETURN(scene, ERROR_WIFI_INVALID_ARGS); + OHOS::Wifi::Hid2dUpperScene upperScene; + upperScene.mac = OHOS::Wifi::MacArrayToStr(scene->mac); + upperScene.scene = scene->scene; + upperScene.fps = scene->fps; + upperScene.bw = scene->bw; + return GetCErrorCode(wifiHid2dPtr->Hid2dSetUpperScene(ifName, upperScene)); +} diff --git a/interfaces/innerkits/native_cpp/wifi_standard/c_adapter/wifi_c_hotspot.cpp b/wifi/frameworks/native/c_adapter/src/wifi_c_hotspot.cpp old mode 100755 new mode 100644 similarity index 81% rename from interfaces/innerkits/native_cpp/wifi_standard/c_adapter/wifi_c_hotspot.cpp rename to wifi/frameworks/native/c_adapter/src/wifi_c_hotspot.cpp index 863ed3a5570e178b43bb0863136b31107eaf9d49..680224d46c203ab13872df56fb9a4b044248e647 --- a/interfaces/innerkits/native_cpp/wifi_standard/c_adapter/wifi_c_hotspot.cpp +++ b/wifi/frameworks/native/c_adapter/src/wifi_c_hotspot.cpp @@ -1,179 +1,191 @@ -/* - * Copyright (C) 2021 Huawei Device Co., Ltd. - * 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 "native_c/wifi_hotspot.h" -#include "native_c/wifi_hotspot_config.h" -#include "native_c/wifi_device_config.h" -#include "native_cpp/wifi_standard/include/wifi_hotspot.h" -#include "wifi_logger.h" -#include "wifi_c_utils.h" -#include "securec.h" -#include "ip_tools.h" - -DEFINE_WIFILOG_LABEL("WifiCHotspot"); - -std::unique_ptr hotspotPtr = OHOS::Wifi::WifiHotspot::GetInstance(WIFI_HOTSPOT_ABILITY_ID); - -WifiErrorCode EnableHotspot() -{ - CHECK_PTR_RETURN(hotspotPtr, ERROR_WIFI_NOT_AVAILABLE); - return GetCErrorCode(hotspotPtr->EnableHotspot()); -} - -WifiErrorCode DisableHotspot() -{ - CHECK_PTR_RETURN(hotspotPtr, ERROR_WIFI_NOT_AVAILABLE); - return GetCErrorCode(hotspotPtr->DisableHotspot()); -} - -int IsHotspotActive(void) -{ - if (hotspotPtr == nullptr) { - return false; - } - return hotspotPtr->IsHotspotActive(); -} - -/* Others type is not support for AP */ -static std::map g_mapSecTypeToKeyMgmt = { - {WifiSecurityType::WIFI_SEC_TYPE_OPEN, OHOS::Wifi::KeyMgmt::NONE}, - {WifiSecurityType::WIFI_SEC_TYPE_PSK, OHOS::Wifi::KeyMgmt::WPA_PSK}, -}; - -static OHOS::Wifi::KeyMgmt GetKeyMgmtFromSecurityType(int secType) -{ - WifiSecurityType key = WifiSecurityType(secType); - std::map::iterator iter = g_mapSecTypeToKeyMgmt.find(key); - return iter == g_mapSecTypeToKeyMgmt.end() ? OHOS::Wifi::KeyMgmt::NONE : iter->second; -} - -static int GetSecurityTypeFromKeyMgmt(OHOS::Wifi::KeyMgmt keyMgmt) -{ - for (auto& each : g_mapSecTypeToKeyMgmt) { - if (each.second == keyMgmt) { - return static_cast(each.first); - } - } - return static_cast(WifiSecurityType::WIFI_SEC_TYPE_OPEN); -} - -static bool IsSecurityTypeSupported(int secType) -{ - WifiSecurityType key = WifiSecurityType(secType); - std::map::iterator iter = g_mapSecTypeToKeyMgmt.find(key); - return iter != g_mapSecTypeToKeyMgmt.end(); -} - -static WifiErrorCode GetHotspotConfigFromC(const HotspotConfig *config, OHOS::Wifi::HotspotConfig& hotspotConfig) -{ - hotspotConfig.SetSsid(config->ssid); - if (!IsSecurityTypeSupported(config->securityType)) { - WIFI_LOGE("Ap security is not supported!"); - return ERROR_WIFI_NOT_SUPPORTED; - } - hotspotConfig.SetSecurityType(GetKeyMgmtFromSecurityType(config->securityType)); - hotspotConfig.SetBand(OHOS::Wifi::BandType(config->band)); - hotspotConfig.SetChannel(config->channelNum); - hotspotConfig.SetPreSharedKey(config->preSharedKey); - return WIFI_SUCCESS; -} - -static WifiErrorCode GetHotspotConfigFromCpp(const OHOS::Wifi::HotspotConfig& hotspotConfig, HotspotConfig *result) -{ - if (memcpy_s(result->ssid, WIFI_MAX_SSID_LEN, - hotspotConfig.GetSsid().c_str(), hotspotConfig.GetSsid().size() + 1) != EOK) { - return ERROR_WIFI_UNKNOWN; - } - result->securityType = GetSecurityTypeFromKeyMgmt(hotspotConfig.GetSecurityType()); - result->band = static_cast(hotspotConfig.GetBand()); - result->channelNum = hotspotConfig.GetChannel(); - if (memcpy_s(result->preSharedKey, WIFI_MAX_KEY_LEN, - hotspotConfig.GetPreSharedKey().c_str(), hotspotConfig.GetPreSharedKey().size() + 1) != EOK) { - return ERROR_WIFI_UNKNOWN; - } - return WIFI_SUCCESS; -} - -WifiErrorCode SetHotspotConfig(const HotspotConfig *config) -{ - CHECK_PTR_RETURN(hotspotPtr, ERROR_WIFI_NOT_AVAILABLE); - OHOS::Wifi::HotspotConfig hotspotConfig; - WifiErrorCode ret = GetHotspotConfigFromC(config, hotspotConfig); - if (ret != WIFI_SUCCESS) { - return ret; - } - return GetCErrorCode(hotspotPtr->SetHotspotConfig(hotspotConfig)); -} - -WifiErrorCode GetHotspotConfig(HotspotConfig *result) -{ - CHECK_PTR_RETURN(hotspotPtr, ERROR_WIFI_NOT_AVAILABLE); - OHOS::Wifi::HotspotConfig hotspotConfig; - OHOS::Wifi::ErrCode ret = hotspotPtr->GetHotspotConfig(hotspotConfig); - if (ret == OHOS::Wifi::WIFI_OPT_SUCCESS) { - WifiErrorCode retValue = GetHotspotConfigFromCpp(hotspotConfig, result); - if (retValue != WIFI_SUCCESS) { - WIFI_LOGE("Get hotspot config from cpp error!"); - return retValue; - } - } - return GetCErrorCode(ret); -} - -static WifiErrorCode GetStaListFromCpp(const std::vector& vecStaList, StationInfo *result) -{ - for (auto& each : vecStaList) { - if (memcpy_s(result->name, DEVICE_NAME_LEN, each.deviceName.c_str(), each.deviceName.size() + 1) != EOK) { - return ERROR_WIFI_UNKNOWN; - } - if (OHOS::Wifi::MacStrToArray(each.bssid, result->macAddress) != EOK) { - WIFI_LOGE("Get sta list convert bssid error!"); - return ERROR_WIFI_UNKNOWN; - } - result->ipAddress = OHOS::Wifi::IpTools::ConvertIpv4Address(each.ipAddr); - } - return WIFI_SUCCESS; -} - -WifiErrorCode GetStationList(StationInfo *result, unsigned int *size) -{ - if (result == nullptr) { - WIFI_LOGE("Station info list receive addr is null!"); - return ERROR_WIFI_UNKNOWN; - } - CHECK_PTR_RETURN(hotspotPtr, ERROR_WIFI_NOT_AVAILABLE); - - std::vector vecStaList; - OHOS::Wifi::ErrCode ret = hotspotPtr->GetStationList(vecStaList); - *size = (int)vecStaList.size(); - if (ret == OHOS::Wifi::WIFI_OPT_SUCCESS) { - WifiErrorCode retValue = GetStaListFromCpp(vecStaList, result); - if (retValue != WIFI_SUCCESS) { - WIFI_LOGE("Get station list from cpp error!"); - return retValue; - } - } - return GetCErrorCode(ret); -} - -WifiErrorCode DisassociateSta(unsigned char *mac, int macLen) -{ - return GetCErrorCode(OHOS::Wifi::WIFI_OPT_NOT_SUPPORTED); -} - -WifiErrorCode AddTxPowerInfo(int power) -{ - return GetCErrorCode(OHOS::Wifi::WIFI_OPT_NOT_SUPPORTED); -} +/* + * Copyright (C) 2021-2022 Huawei Device Co., Ltd. + * 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 "../../../interfaces/kits/c/wifi_hotspot.h" +#include "../../../interfaces/kits/c/wifi_hotspot_config.h" +#include "../../../interfaces/kits/c/wifi_device_config.h" +#include "../../include/wifi_hotspot.h" +#include "wifi_logger.h" +#include "wifi_c_utils.h" +#include "ip_tools.h" +#include "wifi_common_util.h" + +DEFINE_WIFILOG_LABEL("WifiCHotspot"); + +std::unique_ptr hotspotPtr = OHOS::Wifi::WifiHotspot::GetInstance(WIFI_HOTSPOT_ABILITY_ID); + +WifiErrorCode EnableHotspot() +{ + CHECK_PTR_RETURN(hotspotPtr, ERROR_WIFI_NOT_AVAILABLE); + return GetCErrorCode(hotspotPtr->EnableHotspot()); +} + +WifiErrorCode DisableHotspot() +{ + CHECK_PTR_RETURN(hotspotPtr, ERROR_WIFI_NOT_AVAILABLE); + return GetCErrorCode(hotspotPtr->DisableHotspot()); +} + +int IsHotspotActive(void) +{ + CHECK_PTR_RETURN(hotspotPtr, ERROR_WIFI_NOT_AVAILABLE); + return hotspotPtr->IsHotspotActive(); +} + +int IsHotspotDualBandSupported(void) +{ + CHECK_PTR_RETURN(hotspotPtr, ERROR_WIFI_NOT_AVAILABLE); + return hotspotPtr->IsHotspotDualBandSupported(); +} + +/* Others type is not support for AP */ +static std::map g_mapSecTypeToKeyMgmt = { + {WifiSecurityType::WIFI_SEC_TYPE_OPEN, OHOS::Wifi::KeyMgmt::NONE}, + {WifiSecurityType::WIFI_SEC_TYPE_PSK, OHOS::Wifi::KeyMgmt::WPA_PSK}, +}; + +static OHOS::Wifi::KeyMgmt GetKeyMgmtFromSecurityType(int secType) +{ + WifiSecurityType key = WifiSecurityType(secType); + std::map::iterator iter = g_mapSecTypeToKeyMgmt.find(key); + return iter == g_mapSecTypeToKeyMgmt.end() ? OHOS::Wifi::KeyMgmt::NONE : iter->second; +} + +static int GetSecurityTypeFromKeyMgmt(OHOS::Wifi::KeyMgmt keyMgmt) +{ + for (auto& each : g_mapSecTypeToKeyMgmt) { + if (each.second == keyMgmt) { + return static_cast(each.first); + } + } + return static_cast(WifiSecurityType::WIFI_SEC_TYPE_OPEN); +} + +static bool IsSecurityTypeSupported(int secType) +{ + WifiSecurityType key = WifiSecurityType(secType); + std::map::iterator iter = g_mapSecTypeToKeyMgmt.find(key); + return iter != g_mapSecTypeToKeyMgmt.end(); +} + +static WifiErrorCode GetHotspotConfigFromC(const HotspotConfig *config, OHOS::Wifi::HotspotConfig& hotspotConfig) +{ + CHECK_PTR_RETURN(config, ERROR_WIFI_INVALID_ARGS); + hotspotConfig.SetSsid(config->ssid); + if (!IsSecurityTypeSupported(config->securityType)) { + WIFI_LOGE("Ap security is not supported!"); + return ERROR_WIFI_NOT_SUPPORTED; + } + hotspotConfig.SetSecurityType(GetKeyMgmtFromSecurityType(config->securityType)); + hotspotConfig.SetBand(OHOS::Wifi::BandType(config->band)); + hotspotConfig.SetChannel(config->channelNum); + hotspotConfig.SetPreSharedKey(config->preSharedKey); + return WIFI_SUCCESS; +} + +static WifiErrorCode GetHotspotConfigFromCpp(const OHOS::Wifi::HotspotConfig& hotspotConfig, HotspotConfig *result) +{ + CHECK_PTR_RETURN(result, ERROR_WIFI_INVALID_ARGS); + if (memcpy_s(result->ssid, WIFI_MAX_SSID_LEN, + hotspotConfig.GetSsid().c_str(), hotspotConfig.GetSsid().size() + 1) != EOK) { + return ERROR_WIFI_UNKNOWN; + } + result->securityType = GetSecurityTypeFromKeyMgmt(hotspotConfig.GetSecurityType()); + result->band = static_cast(hotspotConfig.GetBand()); + result->channelNum = hotspotConfig.GetChannel(); + if (memcpy_s(result->preSharedKey, WIFI_MAX_KEY_LEN, + hotspotConfig.GetPreSharedKey().c_str(), hotspotConfig.GetPreSharedKey().size() + 1) != EOK) { + return ERROR_WIFI_UNKNOWN; + } + return WIFI_SUCCESS; +} + +WifiErrorCode SetHotspotConfig(const HotspotConfig *config) +{ + CHECK_PTR_RETURN(config, ERROR_WIFI_INVALID_ARGS); + CHECK_PTR_RETURN(hotspotPtr, ERROR_WIFI_NOT_AVAILABLE); + OHOS::Wifi::HotspotConfig hotspotConfig; + WifiErrorCode ret = GetHotspotConfigFromC(config, hotspotConfig); + if (ret != WIFI_SUCCESS) { + return ret; + } + return GetCErrorCode(hotspotPtr->SetHotspotConfig(hotspotConfig)); +} + +WifiErrorCode GetHotspotConfig(HotspotConfig *result) +{ + CHECK_PTR_RETURN(hotspotPtr, ERROR_WIFI_NOT_AVAILABLE); + CHECK_PTR_RETURN(result, ERROR_WIFI_INVALID_ARGS); + OHOS::Wifi::HotspotConfig hotspotConfig; + OHOS::Wifi::ErrCode ret = hotspotPtr->GetHotspotConfig(hotspotConfig); + if (ret == OHOS::Wifi::WIFI_OPT_SUCCESS) { + WifiErrorCode retValue = GetHotspotConfigFromCpp(hotspotConfig, result); + if (retValue != WIFI_SUCCESS) { + WIFI_LOGE("Get hotspot config from cpp error!"); + return retValue; + } + } + return GetCErrorCode(ret); +} + +static WifiErrorCode GetStaListFromCpp(const std::vector& vecStaList, StationInfo *result) +{ + CHECK_PTR_RETURN(result, ERROR_WIFI_INVALID_ARGS); + for (auto& each : vecStaList) { + if (result->name != nullptr) { + if (memcpy_s(result->name, DEVICE_NAME_LEN, each.deviceName.c_str(), each.deviceName.size() + 1) != EOK) { + return ERROR_WIFI_UNKNOWN; + } + } else { + WIFI_LOGE("WARN: device name is not pre-allocate memory!"); + } + + if (OHOS::Wifi::MacStrToArray(each.bssid, result->macAddress) != EOK) { + WIFI_LOGE("Get sta list convert bssid error!"); + return ERROR_WIFI_UNKNOWN; + } + result->ipAddress = OHOS::Wifi::Ip2Number(each.ipAddr); + } + return WIFI_SUCCESS; +} + +WifiErrorCode GetStationList(StationInfo *result, unsigned int *size) +{ + CHECK_PTR_RETURN(hotspotPtr, ERROR_WIFI_NOT_AVAILABLE); + CHECK_PTR_RETURN(result, ERROR_WIFI_INVALID_ARGS); + CHECK_PTR_RETURN(size, ERROR_WIFI_INVALID_ARGS); + std::vector vecStaList; + OHOS::Wifi::ErrCode ret = hotspotPtr->GetStationList(vecStaList); + *size = (int)vecStaList.size(); + if (ret == OHOS::Wifi::WIFI_OPT_SUCCESS) { + WifiErrorCode retValue = GetStaListFromCpp(vecStaList, result); + if (retValue != WIFI_SUCCESS) { + WIFI_LOGE("Get station list from cpp error!"); + return retValue; + } + } + return GetCErrorCode(ret); +} + +WifiErrorCode DisassociateSta(unsigned char *mac, int macLen) +{ + CHECK_PTR_RETURN(mac, ERROR_WIFI_INVALID_ARGS); + return GetCErrorCode(OHOS::Wifi::WIFI_OPT_NOT_SUPPORTED); +} + +WifiErrorCode AddTxPowerInfo(int power) +{ + return GetCErrorCode(OHOS::Wifi::WIFI_OPT_NOT_SUPPORTED); +} diff --git a/wifi/frameworks/native/c_adapter/src/wifi_c_p2p.cpp b/wifi/frameworks/native/c_adapter/src/wifi_c_p2p.cpp new file mode 100644 index 0000000000000000000000000000000000000000..d063f8e78e2ef2e50b54ccf95c3518902bf9937b --- /dev/null +++ b/wifi/frameworks/native/c_adapter/src/wifi_c_p2p.cpp @@ -0,0 +1,499 @@ +/* + * Copyright (C) 2022 Huawei Device Co., Ltd. + * 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 "../../../interfaces/kits/c/wifi_p2p.h" +#include "../../../interfaces/kits/c/wifi_hid2d.h" +#include "wifi_logger.h" +#include "../../../frameworks/native/include/wifi_p2p.h" +#include "wifi_c_utils.h" +#include "wifi_common_util.h" + +constexpr int INVALID_VALUE = -1; + +DEFINE_WIFILOG_LABEL("WifiCP2P"); +std::unique_ptr wifiP2pPtr = OHOS::Wifi::WifiP2p::GetInstance(WIFI_P2P_ABILITY_ID); + +WifiErrorCode EnableP2p() +{ + CHECK_PTR_RETURN(wifiP2pPtr, ERROR_WIFI_NOT_AVAILABLE); + return GetCErrorCode(wifiP2pPtr->EnableP2p()); +} + +WifiErrorCode DisableP2p() +{ + CHECK_PTR_RETURN(wifiP2pPtr, ERROR_WIFI_NOT_AVAILABLE); + return GetCErrorCode(wifiP2pPtr->DisableP2p()); +} + +WifiErrorCode GetP2pEnableStatus(P2pState* state) +{ + CHECK_PTR_RETURN(state, ERROR_WIFI_INVALID_ARGS); + CHECK_PTR_RETURN(wifiP2pPtr, ERROR_WIFI_NOT_AVAILABLE); + + int p2pEnableStatus = INVALID_VALUE; + OHOS::Wifi::ErrCode ret = wifiP2pPtr->GetP2pEnableStatus(p2pEnableStatus); + *state = P2pState(p2pEnableStatus); + return GetCErrorCode(ret); +} + +WifiErrorCode DiscoverDevices() +{ + CHECK_PTR_RETURN(wifiP2pPtr, ERROR_WIFI_NOT_AVAILABLE); + return GetCErrorCode(wifiP2pPtr->DiscoverDevices()); +} + +WifiErrorCode StopDiscoverDevices() +{ + CHECK_PTR_RETURN(wifiP2pPtr, ERROR_WIFI_NOT_AVAILABLE); + return GetCErrorCode(wifiP2pPtr->StopDiscoverDevices()); +} + +WifiErrorCode DiscoverServices() +{ + CHECK_PTR_RETURN(wifiP2pPtr, ERROR_WIFI_NOT_AVAILABLE); + return GetCErrorCode(wifiP2pPtr->DiscoverServices()); +} + +WifiErrorCode StopDiscoverServices() +{ + CHECK_PTR_RETURN(wifiP2pPtr, ERROR_WIFI_NOT_AVAILABLE); + return GetCErrorCode(wifiP2pPtr->StopDiscoverServices()); +} + +WifiErrorCode StartP2pListen(int period, int interval) +{ + CHECK_PTR_RETURN(wifiP2pPtr, ERROR_WIFI_NOT_AVAILABLE); + return GetCErrorCode(wifiP2pPtr->StartP2pListen(period, interval)); +} + +WifiErrorCode StopP2pListen() +{ + CHECK_PTR_RETURN(wifiP2pPtr, ERROR_WIFI_NOT_AVAILABLE); + return GetCErrorCode(wifiP2pPtr->StopP2pListen()); +} + +static void ConvertConfigCToCpp(const WifiP2pConfig* config, OHOS::Wifi::WifiP2pConfig& cppConfig) +{ + CHECK_PTR_RETURN_VOID(config); + cppConfig.SetDeviceAddress(OHOS::Wifi::MacArrayToStr(config->devAddr)); + cppConfig.SetGoBand(OHOS::Wifi::GroupOwnerBand(static_cast(config->goBand))); + cppConfig.SetNetId(config->netId); + cppConfig.SetPassphrase(config->passphrase); + cppConfig.SetGroupOwnerIntent(config->groupOwnerIntent); + cppConfig.SetGroupName(config->groupName); +} + +WifiErrorCode CreateGroup(const WifiP2pConfig* config) +{ + CHECK_PTR_RETURN(wifiP2pPtr, ERROR_WIFI_NOT_AVAILABLE); + CHECK_PTR_RETURN(config, ERROR_WIFI_INVALID_ARGS); + OHOS::Wifi::WifiP2pConfig cppConfig; + ConvertConfigCToCpp(config, cppConfig); + return GetCErrorCode(wifiP2pPtr->CreateGroup(cppConfig)); +} + +WifiErrorCode RemoveGroup() +{ + CHECK_PTR_RETURN(wifiP2pPtr, ERROR_WIFI_NOT_AVAILABLE); + return GetCErrorCode(wifiP2pPtr->RemoveGroup()); +} + +static void ConvertP2PDeviceCToCpp(const WifiP2pDevice& p2pDevice, OHOS::Wifi::WifiP2pDevice& cppDevice) +{ + cppDevice.SetDeviceName(p2pDevice.deviceName); + cppDevice.SetDeviceAddress(OHOS::Wifi::MacArrayToStr(p2pDevice.devAddr)); + cppDevice.SetPrimaryDeviceType(p2pDevice.primaryDeviceType); + cppDevice.SetSecondaryDeviceType(p2pDevice.secondaryDeviceType); + cppDevice.SetP2pDeviceStatus(OHOS::Wifi::P2pDeviceStatus(static_cast(p2pDevice.status))); + + OHOS::Wifi::WifiP2pWfdInfo wfdInfo; + wfdInfo.SetWfdEnabled((bool)p2pDevice.wfdInfo.wfdEnabled); + wfdInfo.SetDeviceInfo(p2pDevice.wfdInfo.deviceInfo); + wfdInfo.SetCtrlPort(p2pDevice.wfdInfo.ctrlPort); + wfdInfo.SetMaxThroughput(p2pDevice.wfdInfo.maxThroughput); + cppDevice.SetWfdInfo(wfdInfo); + + cppDevice.SetWpsConfigMethod(p2pDevice.supportWpsConfigMethods); + cppDevice.SetDeviceCapabilitys(p2pDevice.deviceCapabilitys); + cppDevice.SetGroupCapabilitys(p2pDevice.groupCapabilitys); +} + +static void ConvertGroupInfoCToCpp(const WifiP2pGroupInfo* group, OHOS::Wifi::WifiP2pGroupInfo& cppGroup) +{ + CHECK_PTR_RETURN_VOID(group); + OHOS::Wifi::WifiP2pDevice owner; + ConvertP2PDeviceCToCpp(group->owner, owner); + cppGroup.SetOwner(owner); + cppGroup.SetIsGroupOwner((bool)group->isP2pGroupOwner); + cppGroup.SetPassphrase(group->passphrase); + cppGroup.SetInterface(group->interface); + cppGroup.SetGroupName(group->groupName); + cppGroup.SetNetworkId(group->networkId); + cppGroup.SetFrequency(group->frequency); + cppGroup.SetIsPersistent((bool)group->isP2pPersistent); + cppGroup.SetP2pGroupStatus(OHOS::Wifi::P2pGroupStatus(static_cast(group->groupStatus))); + std::vector clientDevices; + for (int i = 0; i != group->clientDevicesSize && i < MAX_DEVICES_NUM; ++i) { + OHOS::Wifi::WifiP2pDevice p2pDevice; + ConvertP2PDeviceCToCpp(group->clientDevices[i], p2pDevice); + clientDevices.emplace_back(p2pDevice); + } + cppGroup.SetClientDevices(clientDevices); + cppGroup.SetGoIpAddress(group->goIpAddress); +} + +WifiErrorCode DeleteGroup(const WifiP2pGroupInfo* group) +{ + CHECK_PTR_RETURN(wifiP2pPtr, ERROR_WIFI_NOT_AVAILABLE); + CHECK_PTR_RETURN(group, ERROR_WIFI_INVALID_ARGS); + OHOS::Wifi::WifiP2pGroupInfo groupInfo; + ConvertGroupInfoCToCpp(group, groupInfo); + return GetCErrorCode(wifiP2pPtr->DeleteGroup(groupInfo)); +} + +WifiErrorCode P2pConnect(const WifiP2pConfig* config) +{ + CHECK_PTR_RETURN(wifiP2pPtr, ERROR_WIFI_NOT_AVAILABLE); + CHECK_PTR_RETURN(config, ERROR_WIFI_INVALID_ARGS); + OHOS::Wifi::WifiP2pConfig deviceConfig; + ConvertConfigCToCpp(config, deviceConfig); + return GetCErrorCode(wifiP2pPtr->P2pConnect(deviceConfig)); +} + +WifiErrorCode P2pCancelConnect() +{ + CHECK_PTR_RETURN(wifiP2pPtr, ERROR_WIFI_NOT_AVAILABLE); + return GetCErrorCode(wifiP2pPtr->P2pCancelConnect()); +} + +static OHOS::Wifi::ErrCode ConvertP2PDeviceCppToC(const OHOS::Wifi::WifiP2pDevice& cppDevice, WifiP2pDevice* p2pDevice) +{ + CHECK_PTR_RETURN(p2pDevice, OHOS::Wifi::WIFI_OPT_INVALID_PARAM); + if (memcpy_s(p2pDevice->deviceName, P2P_NAME_LENGTH, + cppDevice.GetDeviceName().c_str(), cppDevice.GetDeviceName().size() + 1) != EOK) { + WIFI_LOGE("memcpy_s device name failed!"); + return OHOS::Wifi::WIFI_OPT_FAILED; + } + if (OHOS::Wifi::MacStrToArray(cppDevice.GetDeviceAddress(), p2pDevice->devAddr) != EOK) { + WIFI_LOGE("Mac str to array failed!"); + return OHOS::Wifi::WIFI_OPT_FAILED; + } + if (memcpy_s(p2pDevice->primaryDeviceType, DEVICE_TYPE_LENGTH, + cppDevice.GetPrimaryDeviceType().c_str(), cppDevice.GetPrimaryDeviceType().size() + 1) != EOK) { + WIFI_LOGE("memcpy_s primary device type failed!"); + return OHOS::Wifi::WIFI_OPT_FAILED; + } + if (memcpy_s(p2pDevice->secondaryDeviceType, DEVICE_TYPE_LENGTH, + cppDevice.GetSecondaryDeviceType().c_str(), cppDevice.GetSecondaryDeviceType().size() + 1) != EOK) { + WIFI_LOGE("memcpy_s secondary device type failed!"); + return OHOS::Wifi::WIFI_OPT_FAILED; + } + + p2pDevice->status = P2pDeviceStatus(static_cast(cppDevice.GetP2pDeviceStatus())); + p2pDevice->wfdInfo.wfdEnabled = cppDevice.GetWfdInfo().GetWfdEnabled(); + p2pDevice->wfdInfo.deviceInfo = cppDevice.GetWfdInfo().GetDeviceInfo(); + p2pDevice->wfdInfo.ctrlPort = cppDevice.GetWfdInfo().GetCtrlPort(); + p2pDevice->wfdInfo.maxThroughput = cppDevice.GetWfdInfo().GetMaxThroughput(); + p2pDevice->supportWpsConfigMethods = cppDevice.GetWpsConfigMethod(); + p2pDevice->deviceCapabilitys = cppDevice.GetDeviceCapabilitys(); + p2pDevice->groupCapabilitys = cppDevice.GetGroupCapabilitys(); + return OHOS::Wifi::WIFI_OPT_SUCCESS; +} + +static OHOS::Wifi::ErrCode ConvertGroupInfoCppToC(const OHOS::Wifi::WifiP2pGroupInfo& cppGroup, WifiP2pGroupInfo* group) +{ + CHECK_PTR_RETURN(group, OHOS::Wifi::WIFI_OPT_INVALID_PARAM); + if (ConvertP2PDeviceCppToC(cppGroup.GetOwner(), &group->owner) != OHOS::Wifi::WIFI_OPT_SUCCESS) { + return OHOS::Wifi::WIFI_OPT_FAILED; + } + group->isP2pGroupOwner = cppGroup.IsGroupOwner(); + if (memcpy_s(group->passphrase, PASSPHRASE_LENGTH, + cppGroup.GetPassphrase().c_str(), cppGroup.GetPassphrase().size() + 1) != EOK) { + WIFI_LOGE("memcpy_s passphrase failed!"); + return OHOS::Wifi::WIFI_OPT_FAILED; + } + if (memcpy_s(group->interface, INTERFACE_LENGTH, + cppGroup.GetInterface().c_str(), cppGroup.GetInterface().size() + 1) != EOK) { + WIFI_LOGE("memcpy_s interface failed!"); + return OHOS::Wifi::WIFI_OPT_FAILED; + } + if (memcpy_s(group->groupName, P2P_NAME_LENGTH, + cppGroup.GetGroupName().c_str(), cppGroup.GetGroupName().size() + 1) != EOK) { + WIFI_LOGE("memcpy_s group name failed!"); + return OHOS::Wifi::WIFI_OPT_FAILED; + } + group->networkId = cppGroup.GetNetworkId(); + group->frequency = cppGroup.GetFrequency(); + group->isP2pPersistent = cppGroup.IsPersistent(); + group->groupStatus = P2pGroupStatus(static_cast(cppGroup.GetP2pGroupStatus())); + const std::vector& vecDevices = cppGroup.GetClientDevices(); + for (size_t i = 0; i != vecDevices.size() && i < MAX_DEVICES_NUM; ++i) { + if (ConvertP2PDeviceCppToC(vecDevices[i], &group->clientDevices[i]) != OHOS::Wifi::WIFI_OPT_SUCCESS) { + WIFI_LOGE("convert p2p device failed!"); + return OHOS::Wifi::WIFI_OPT_FAILED; + } + } + group->clientDevicesSize = (int)vecDevices.size(); + if (memcpy_s(group->goIpAddress, IP_ADDR_STR_LEN, + cppGroup.GetGoIpAddress().c_str(), cppGroup.GetGoIpAddress().size() + 1) != EOK) { + WIFI_LOGE("memcpy_s interface failed!"); + return OHOS::Wifi::WIFI_OPT_FAILED; + } + return OHOS::Wifi::WIFI_OPT_SUCCESS; +} + +WifiErrorCode GetCurrentGroup(WifiP2pGroupInfo* groupInfo) +{ + CHECK_PTR_RETURN(wifiP2pPtr, ERROR_WIFI_NOT_AVAILABLE); + CHECK_PTR_RETURN(groupInfo, ERROR_WIFI_INVALID_ARGS); + OHOS::Wifi::WifiP2pGroupInfo cppGroupInfo; + OHOS::Wifi::ErrCode ret = wifiP2pPtr->GetCurrentGroup(cppGroupInfo); + if (ret != OHOS::Wifi::WIFI_OPT_SUCCESS) { + WIFI_LOGE("get current group info failed!"); + return ERROR_WIFI_NOT_AVAILABLE; + } + return GetCErrorCode(ConvertGroupInfoCppToC(cppGroupInfo, groupInfo)); +} + +WifiErrorCode GetP2pConnectedStatus(int* status) +{ + CHECK_PTR_RETURN(wifiP2pPtr, ERROR_WIFI_NOT_AVAILABLE); + CHECK_PTR_RETURN(status, ERROR_WIFI_INVALID_ARGS); + int p2pStatus = -1; + OHOS::Wifi::ErrCode ret = wifiP2pPtr->GetP2pConnectedStatus(p2pStatus); + if (ret != OHOS::Wifi::WIFI_OPT_SUCCESS) { + WIFI_LOGE("get p2p status failed!"); + } + *status = p2pStatus; + return GetCErrorCode(ret); +} + +WifiErrorCode QueryP2pLocalDevice(WifiP2pDevice* deviceInfo) +{ + CHECK_PTR_RETURN(wifiP2pPtr, ERROR_WIFI_NOT_AVAILABLE); + CHECK_PTR_RETURN(deviceInfo, ERROR_WIFI_INVALID_ARGS); + OHOS::Wifi::WifiP2pDevice cppDeviceInfo; + OHOS::Wifi::ErrCode ret = wifiP2pPtr->QueryP2pLocalDevice(cppDeviceInfo); + if (ret != OHOS::Wifi::WIFI_OPT_SUCCESS) { + WIFI_LOGE("QueryP2pLocalDevice return failed!"); + } + return GetCErrorCode(ConvertP2PDeviceCppToC(cppDeviceInfo, deviceInfo)); +} + +WifiErrorCode QueryP2pDevices(WifiP2pDevice* clientDevices, int size, int* retSize) +{ + CHECK_PTR_RETURN(wifiP2pPtr, ERROR_WIFI_NOT_AVAILABLE); + CHECK_PTR_RETURN(clientDevices, ERROR_WIFI_INVALID_ARGS); + CHECK_PTR_RETURN(retSize, ERROR_WIFI_INVALID_ARGS); + std::vector vecDevices; + OHOS::Wifi::ErrCode ret = wifiP2pPtr->QueryP2pDevices(vecDevices); + if (ret != OHOS::Wifi::WIFI_OPT_SUCCESS) { + WIFI_LOGE("query p2p devices failed!"); + return ERROR_WIFI_UNKNOWN; + } + + for (int i = 0; i != (int)vecDevices.size() && i < size; ++i) { + if (ConvertP2PDeviceCppToC(vecDevices[i], clientDevices++) != OHOS::Wifi::WIFI_OPT_SUCCESS) { + WIFI_LOGE("convert p2p device failed!"); + return ERROR_WIFI_UNKNOWN; + } + } + *retSize = std::min(size, (int)vecDevices.size()); + return WIFI_SUCCESS; +} + +WifiErrorCode QueryP2pGroups(WifiP2pGroupInfo* groupInfo, int size) +{ + CHECK_PTR_RETURN(wifiP2pPtr, ERROR_WIFI_NOT_AVAILABLE); + CHECK_PTR_RETURN(groupInfo, ERROR_WIFI_INVALID_ARGS); + std::vector groups; + OHOS::Wifi::ErrCode ret = wifiP2pPtr->QueryP2pGroups(groups); + if (ret != OHOS::Wifi::WIFI_OPT_SUCCESS) { + WIFI_LOGE("query p2p devices failed!"); + return ERROR_WIFI_UNKNOWN; + } + + for (int i = 0; i != (int)groups.size() && i < size; ++i) { + ret = ConvertGroupInfoCppToC(groups[i], groupInfo++); + if (ret != OHOS::Wifi::WIFI_OPT_SUCCESS) { + WIFI_LOGE("convert group info failed!"); + return ERROR_WIFI_UNKNOWN; + } + } + return WIFI_SUCCESS; +} + +class WifiP2pCEventCallback : public OHOS::Wifi::IWifiP2pCallback +{ +public: + void OnP2pStateChanged(int state) override { + WIFI_LOGI("received state changed event: %{public}d", state); + if (stateChangeCb != nullptr) { + stateChangeCb(P2pState(state)); + } + } + + void OnP2pPersistentGroupsChanged(void) override { + WIFI_LOGI("received group changed event"); + if (groupChangeCb != nullptr) { + groupChangeCb(); + } + } + + void OnP2pThisDeviceChanged(const OHOS::Wifi::WifiP2pDevice &device) override { + } + + void OnP2pPeersChanged(const std::vector &devices) override { + WIFI_LOGI("received peers changed event: %{public}d", (int)devices.size()); + WifiP2pDevice *devicePtr = nullptr; + if (!devices.empty()) { + devicePtr = new (std::nothrow) WifiP2pDevice[(int)devices.size()]; + if (devicePtr == nullptr) { + WIFI_LOGE("new WifiP2pDevice failed!"); + return; + } + WifiP2pDevice *p = devicePtr; + for (auto& each : devices) { + if (ConvertP2PDeviceCppToC(each, p++) != OHOS::Wifi::WIFI_OPT_SUCCESS) { + WIFI_LOGE("peers changed convert p2p device failed!"); + delete[] devicePtr; + return; + } + } + } + if (peersChangeCb != nullptr) { + peersChangeCb(devicePtr, (int)devices.size()); + } + if (devicePtr != nullptr) { + delete[] devicePtr; + devicePtr = nullptr; + } + } + + void OnP2pServicesChanged(const std::vector &srvInfo) override { + } + + void OnP2pConnectionChanged(const OHOS::Wifi::WifiP2pLinkedInfo &info) override { + WIFI_LOGI("received connection changed event"); + if (connectionChangeCb != nullptr) { + connectionChangeCb(ConvertP2pLinkedInfo(info)); + } + } + + void OnP2pDiscoveryChanged(bool isChange) override { + } + + void OnP2pActionResult(OHOS::Wifi::P2pActionCallback action, OHOS::Wifi::ErrCode code) override { + } + + void OnConfigChanged(OHOS::Wifi::CfgType type, char* data, int dataLen) override { + WIFI_LOGI("received config change event: %{public}d", static_cast(type)); + if (cfgChangeCallback != nullptr) { + cfgChangeCallback(CfgType(type), data, dataLen); + } + } + + OHOS::sptr AsObject() override { + return nullptr; + } + +public: + WifiP2pCEventCallback() { + stateChangeCb = nullptr; + groupChangeCb = nullptr; + connectionChangeCb = nullptr; + peersChangeCb = nullptr; + cfgChangeCallback = nullptr; + } + + virtual ~WifiP2pCEventCallback() { + } + +public: + P2pStateChangedCallback stateChangeCb; + P2pPersistentGroupsChangedCallback groupChangeCb; + P2pConnectionChangedCallback connectionChangeCb; + P2pPeersChangedCallback peersChangeCb; + WifiCfgChangCallback cfgChangeCallback; + +private: + WifiP2pLinkedInfo ConvertP2pLinkedInfo(const OHOS::Wifi::WifiP2pLinkedInfo& linkedInfo) { + WifiP2pLinkedInfo info; + info.connectState = P2pConnectionState(static_cast(linkedInfo.GetConnectState())); + info.isP2pGroupOwner = linkedInfo.IsGroupOwner(); + OHOS::Wifi::MacStrToArray(linkedInfo.GetGroupOwnerAddress(), info.groupOwnerAddress); + return info; + } +}; + +OHOS::sptr sptrCallback = + OHOS::sptr(new (std::nothrow) WifiP2pCEventCallback()); + +WifiErrorCode RegisterP2pStateChangedCallback(const P2pStateChangedCallback callback) +{ + CHECK_PTR_RETURN(callback, ERROR_WIFI_INVALID_ARGS); + CHECK_PTR_RETURN(wifiP2pPtr, ERROR_WIFI_NOT_AVAILABLE); + CHECK_PTR_RETURN(sptrCallback, ERROR_WIFI_NOT_AVAILABLE); + sptrCallback->stateChangeCb = callback; + wifiP2pPtr->RegisterCallBack(sptrCallback); + return WIFI_SUCCESS; +} + +WifiErrorCode RegisterP2pPersistentGroupsChangedCallback(const P2pPersistentGroupsChangedCallback callback) +{ + CHECK_PTR_RETURN(callback, ERROR_WIFI_INVALID_ARGS); + CHECK_PTR_RETURN(wifiP2pPtr, ERROR_WIFI_NOT_AVAILABLE); + CHECK_PTR_RETURN(sptrCallback, ERROR_WIFI_NOT_AVAILABLE); + sptrCallback->groupChangeCb = callback; + wifiP2pPtr->RegisterCallBack(sptrCallback); + return WIFI_SUCCESS; +} + +WifiErrorCode RegisterP2pConnectionChangedCallback(const P2pConnectionChangedCallback callback) +{ + CHECK_PTR_RETURN(callback, ERROR_WIFI_INVALID_ARGS); + CHECK_PTR_RETURN(wifiP2pPtr, ERROR_WIFI_NOT_AVAILABLE); + CHECK_PTR_RETURN(sptrCallback, ERROR_WIFI_NOT_AVAILABLE); + sptrCallback->connectionChangeCb = callback; + wifiP2pPtr->RegisterCallBack(sptrCallback); + return WIFI_SUCCESS; +} + +WifiErrorCode RegisterP2pPeersChangedCallback(const P2pPeersChangedCallback callback) +{ + CHECK_PTR_RETURN(callback, ERROR_WIFI_INVALID_ARGS); + CHECK_PTR_RETURN(wifiP2pPtr, ERROR_WIFI_NOT_AVAILABLE); + CHECK_PTR_RETURN(sptrCallback, ERROR_WIFI_NOT_AVAILABLE); + sptrCallback->peersChangeCb = callback; + wifiP2pPtr->RegisterCallBack(sptrCallback); + return WIFI_SUCCESS; +} + +WifiErrorCode RegisterCfgChangCallback(const WifiCfgChangCallback callback) +{ + CHECK_PTR_RETURN(callback, ERROR_WIFI_INVALID_ARGS); + CHECK_PTR_RETURN(wifiP2pPtr, ERROR_WIFI_NOT_AVAILABLE); + CHECK_PTR_RETURN(sptrCallback, ERROR_WIFI_NOT_AVAILABLE); + sptrCallback->cfgChangeCallback = callback; + wifiP2pPtr->RegisterCallBack(sptrCallback); + return WIFI_SUCCESS; +} + +WifiErrorCode UnregisterCfgChangCallback(void) +{ + CHECK_PTR_RETURN(sptrCallback, ERROR_WIFI_NOT_AVAILABLE); + sptrCallback->cfgChangeCallback = nullptr; + return WIFI_SUCCESS; +} \ No newline at end of file diff --git a/interfaces/innerkits/native_cpp/wifi_standard/c_adapter/wifi_c_utils.cpp b/wifi/frameworks/native/c_adapter/src/wifi_c_utils.cpp old mode 100755 new mode 100644 similarity index 48% rename from interfaces/innerkits/native_cpp/wifi_standard/c_adapter/wifi_c_utils.cpp rename to wifi/frameworks/native/c_adapter/src/wifi_c_utils.cpp index 822a4f15329a63dc4f6bb1997e86cc0726d9bf7b..3909607d49675cbaadd8f01ca076cd310d8cc519 --- a/interfaces/innerkits/native_cpp/wifi_standard/c_adapter/wifi_c_utils.cpp +++ b/wifi/frameworks/native/c_adapter/src/wifi_c_utils.cpp @@ -1,118 +1,68 @@ -/* - * Copyright (C) 2021 Huawei Device Co., Ltd. - * 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 "wifi_c_utils.h" -#include -#include - -namespace OHOS { -namespace Wifi { -static std::map g_ErrCodeMap = { - {WIFI_OPT_SUCCESS, WIFI_SUCCESS}, - {WIFI_OPT_FAILED, ERROR_WIFI_UNKNOWN}, - {WIFI_OPT_NOT_SUPPORTED, ERROR_WIFI_NOT_SUPPORTED}, - {WIFI_OPT_INVALID_PARAM, ERROR_WIFI_INVALID_ARGS}, - {WIFI_OPT_FORBID_AIRPLANE, ERROR_WIFI_NOT_AVAILABLE}, - {WIFI_OPT_FORBID_POWSAVING, ERROR_WIFI_NOT_AVAILABLE}, - {WIFI_OPT_PERMISSION_DENIED, ERROR_WIFI_UNKNOWN}, - {WIFI_OPT_OPEN_FAIL_WHEN_CLOSING, ERROR_WIFI_BUSY}, - {WIFI_OPT_OPEN_SUCC_WHEN_OPENED, ERROR_WIFI_BUSY}, - {WIFI_OPT_CLOSE_FAIL_WHEN_OPENING, ERROR_WIFI_BUSY}, - {WIFI_OPT_CLOSE_SUCC_WHEN_CLOSED, ERROR_WIFI_BUSY}, - {WIFI_OPT_STA_NOT_OPENED, ERROR_WIFI_NOT_STARTED}, - {WIFI_OPT_SCAN_NOT_OPENED, ERROR_WIFI_NOT_STARTED}, - {WIFI_OPT_AP_NOT_OPENED, ERROR_WIFI_NOT_STARTED}, - {WIFI_OPT_INVALID_CONFIG, ERROR_WIFI_UNKNOWN} -}; - -WifiErrorCode GetCErrorCode(ErrCode errCode) -{ - std::map::const_iterator iter = g_ErrCodeMap.find(errCode); - return iter == g_ErrCodeMap.end() ? ERROR_WIFI_UNKNOWN : iter->second; -} - -static unsigned char ConvertStrChar(char ch) -{ - constexpr int numDiffForHexAlphabet = 10; - if (ch >= '0' && ch <= '9') { - return (ch - '0'); - } - if (ch >= 'A' && ch <= 'F') { - return (ch - 'A' + numDiffForHexAlphabet); - } - if (ch >= 'a' && ch <= 'f') { - return (ch - 'a' + numDiffForHexAlphabet); - } - return 0; -} - -errno_t MacStrToArray(const std::string& strMac, unsigned char mac[WIFI_MAC_LEN]) -{ - constexpr int strMacLen = 18; - char tempArray[strMacLen] = { 0 }; - errno_t ret = memcpy_s(tempArray, strMacLen, strMac.c_str(), strMac.size() + 1); - if (ret != EOK) { - return ret; - } - - int idx = 0; - constexpr int bitWidth = 4; - char *ptr = nullptr; - char *p = strtok_s(tempArray, ":", &ptr); - while (p != nullptr) { - mac[idx++] = (ConvertStrChar(*p) << bitWidth) | ConvertStrChar(*(p + 1)); - p = strtok_s(nullptr, ":", &ptr); - } - return EOK; -} - -static char ConvertArrayChar(unsigned char ch) -{ - constexpr int maxDecNum = 9; - constexpr int numDiffForHexAlphabet = 10; - if (ch >= 0 && ch <= maxDecNum) { - return '0' + ch; - } - if (ch >= 0xa && ch <= 0xf) { - return ch + 'a' - numDiffForHexAlphabet; - } - return '0'; -} - -std::string MacArrayToStr(const unsigned char mac[WIFI_MAC_LEN]) -{ - constexpr int bitWidth = 4; - constexpr int noColonBit = 5; - std::stringstream ss; - for (int i = 0; i != WIFI_MAC_LEN; ++i) { - ss << ConvertArrayChar(mac[i] >> bitWidth) << ConvertArrayChar(mac[i] & 0xf); - if (i != noColonBit) { - ss << ":"; - } - } - return ss.str(); -} - -bool IsMacArrayEmpty(const unsigned char mac[WIFI_MAC_LEN]) -{ - for (int i = 0; i != WIFI_MAC_LEN; ++i) { - if (mac[i] != 0) { - return false; - } - } - return true; -} -} // namespace Wifi -} // namespace OHOS +/* + * Copyright (C) 2021 Huawei Device Co., Ltd. + * 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 "wifi_c_utils.h" +#include +#include "wifi_common_util.h" + +namespace OHOS { +namespace Wifi { +static std::map g_ErrCodeMap = { + {WIFI_OPT_SUCCESS, WIFI_SUCCESS}, + {WIFI_OPT_FAILED, ERROR_WIFI_UNKNOWN}, + {WIFI_OPT_NOT_SUPPORTED, ERROR_WIFI_NOT_SUPPORTED}, + {WIFI_OPT_INVALID_PARAM, ERROR_WIFI_INVALID_ARGS}, + {WIFI_OPT_FORBID_AIRPLANE, ERROR_WIFI_NOT_AVAILABLE}, + {WIFI_OPT_FORBID_POWSAVING, ERROR_WIFI_NOT_AVAILABLE}, + {WIFI_OPT_PERMISSION_DENIED, ERROR_WIFI_UNKNOWN}, + {WIFI_OPT_OPEN_FAIL_WHEN_CLOSING, ERROR_WIFI_BUSY}, + {WIFI_OPT_OPEN_SUCC_WHEN_OPENED, ERROR_WIFI_BUSY}, + {WIFI_OPT_CLOSE_FAIL_WHEN_OPENING, ERROR_WIFI_BUSY}, + {WIFI_OPT_CLOSE_SUCC_WHEN_CLOSED, ERROR_WIFI_BUSY}, + {WIFI_OPT_STA_NOT_OPENED, ERROR_WIFI_NOT_STARTED}, + {WIFI_OPT_SCAN_NOT_OPENED, ERROR_WIFI_NOT_STARTED}, + {WIFI_OPT_AP_NOT_OPENED, ERROR_WIFI_NOT_STARTED}, + {WIFI_OPT_INVALID_CONFIG, ERROR_WIFI_UNKNOWN} +}; + +WifiErrorCode GetCErrorCode(ErrCode errCode) +{ + std::map::const_iterator iter = g_ErrCodeMap.find(errCode); + return iter == g_ErrCodeMap.end() ? ERROR_WIFI_UNKNOWN : iter->second; +} + +WifiErrorCode IpStrToArray(const std::string& str, unsigned int ipAddr[IPV4_ARRAY_LEN]) { + std::vector vec = StrSplit(str, "\\."); + if (vec.size() != IPV4_ARRAY_LEN) { + return ERROR_WIFI_INVALID_ARGS; + } + for (int i = 0; i != IPV4_ARRAY_LEN && i != (int)vec.size(); ++i) { + ipAddr[i] = std::stoi(vec[i]); + } + return WIFI_SUCCESS; +} + +std::string IpArrayToStr(const unsigned int ipAddr[IPV4_ARRAY_LEN]) { + std::string str = ""; + for (int i = 0; i != IPV4_ARRAY_LEN; ++i) { + str += std::to_string(ipAddr[i]); + if (i != IPV4_ARRAY_LEN - 1) { + str += "."; + } + } + return str; +} +} // namespace Wifi +} // namespace OHOS diff --git a/interfaces/innerkits/native_cpp/wifi_standard/include/wifi_device.h b/wifi/frameworks/native/include/wifi_device.h similarity index 56% rename from interfaces/innerkits/native_cpp/wifi_standard/include/wifi_device.h rename to wifi/frameworks/native/include/wifi_device.h index aa71abcbef53cc54a850f930cf2fbf331ecdd861..c6b5126f67a1b55853e3affe14d0ce3c078db339 100644 --- a/interfaces/innerkits/native_cpp/wifi_standard/include/wifi_device.h +++ b/wifi/frameworks/native/include/wifi_device.h @@ -1,5 +1,5 @@ /* - * Copyright (C) 2021 Huawei Device Co., Ltd. + * Copyright (C) 2021-2022 Huawei Device Co., Ltd. * 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 @@ -42,15 +42,66 @@ public: * @return ErrCode - operation result */ virtual ErrCode DisableWifi() = 0; + /** + * @Description create the Wi-Fi protect. + * + * @param protectType - WifiProtectMode object + * @param protectName - the protect name + * @return ErrCode - operation result + */ + virtual ErrCode InitWifiProtect(const WifiProtectType &protectType, const std::string &protectName) = 0; + + /** + * @Description Acquire the Wi-Fi protect mode. + * + * @param protectMode - WifiProtectMode object + * @param protectName - the protect name + * @return ErrCode - operation result + */ + virtual ErrCode GetWifiProtectRef(const WifiProtectMode &protectMode, const std::string &protectName) = 0; + + /** + * @Description Release the Wi-Fi protect mode. + * + * @param protectName - the protect name + * @return ErrCode - operation result + */ + virtual ErrCode PutWifiProtectRef(const std::string &protectName) = 0; + + /** + * @Description Remove the wifi candidate device config equals to input network id + * + * @param networkId - the candidate device network id + * @return ErrCode - operation result + */ + virtual ErrCode RemoveCandidateConfig(int networkId) = 0; + + /** + * @Description Remove a specified candidate hotspot configuration. + * + * @param config - WifiDeviceConfig object + * @return ErrCode - operation result + */ + virtual ErrCode RemoveCandidateConfig(const WifiDeviceConfig &config) = 0; /** * @Description Add a wifi device configuration. * * @param config - WifiDeviceConfig object * @param result - the device configuration's network id + * @param isCandidate - Whether is candidate + * @return ErrCode - operation result + */ + virtual ErrCode AddDeviceConfig(const WifiDeviceConfig &config, int &result, bool isCandidate) = 0; + + /** + * @Description Update a wifi device configuration. + * + * @param config - WifiDeviceConfig object + * @param result - the device configuration's network id after updated * @return ErrCode - operation result */ - virtual ErrCode AddDeviceConfig(const WifiDeviceConfig &config, int &result) = 0; + virtual ErrCode UpdateDeviceConfig(const WifiDeviceConfig &config, int &result) = 0; /** * @Description Remove the wifi device config equals to input network id. @@ -71,17 +122,19 @@ public: * @Description Get all the device configs. * * @param result - Get result vector of WifiDeviceConfig + * @param isCandidate - Whether is candidate * @return ErrCode - operation result */ - virtual ErrCode GetDeviceConfigs(std::vector &result) = 0; + virtual ErrCode GetDeviceConfigs(std::vector &result, bool isCandidate) = 0; /** * @Description Connecting to a Specified Network. * * @param networkId - network id + * @param isCandidate - Whether is candidate * @return ErrCode - operation result */ - virtual ErrCode ConnectToNetwork(int networkId) = 0; + virtual ErrCode ConnectToNetwork(int networkId, bool isCandidate) = 0; /** * @Description Connect To a network base WifiDeviceConfig object. @@ -91,6 +144,13 @@ public: */ virtual ErrCode ConnectToDevice(const WifiDeviceConfig &config) = 0; + /** + * @Description Check whether Wi-Fi is connected. + * + * @return bool - true: connected, false: not connected + */ + virtual bool IsConnected() = 0; + /** * @Description Disconnect. * @@ -144,7 +204,11 @@ public: * @param callback - IWifiDeviceCallBack object * @return ErrCode - operation result */ +#ifdef OHOS_ARCH_LITE + virtual ErrCode RegisterCallBack(const std::shared_ptr &callback) = 0; +#else virtual ErrCode RegisterCallBack(const sptr &callback) = 0; +#endif /** * @Description Get the signal level object. @@ -168,11 +232,49 @@ public: * @Description Check if supported input feature * * @param feature - input feature - * @return true - supported - * @return false - unsupported + * @return bool - true if supported, false if unsupported */ virtual bool IsFeatureSupported(long feature) = 0; + /** + * @Description Enable device config, when set attemptEnable, disable other device config + * + * @param networkId - need enable device config's network id + * @param attemptEnable - if set true, disable other device config + * @return ErrCode - operation result + */ + virtual ErrCode EnableDeviceConfig(int networkId, bool attemptEnable) = 0; + + /** + * @Description Disable Wi-Fi device configuration. + * + * @param networkId - device config's network id + * @return ErrCode - operation result + */ + virtual ErrCode DisableDeviceConfig(int networkId) = 0; + + /** + * @Description Obtaining ip Request Information + * + * @param info - IpInfo object + * @return ErrCode - operation result + */ + virtual ErrCode GetIpInfo(IpInfo &info) = 0; + + /** + * @Description Reconnect to the currently active network + * + * @return ErrCode - operation result + */ + virtual ErrCode ReConnect() = 0; + + /** + * @Description ReAssociate network + * + * @return ErrCode - operation result + */ + virtual ErrCode ReAssociate() = 0; + /** * @Description Get the device MAC address. * @@ -180,7 +282,15 @@ public: * @return ErrCode - operation result */ virtual ErrCode GetDeviceMacAddress(std::string &result) = 0; + + /** + * @Description set low latency mode + * + * @param enabled - true: enable low latency, false: disable low latency + * @return bool - operation result + */ + virtual bool SetLowLatencyMode(bool enabled) = 0; }; } // namespace Wifi } // namespace OHOS -#endif \ No newline at end of file +#endif diff --git a/wifi/frameworks/native/include/wifi_hid2d.h b/wifi/frameworks/native/include/wifi_hid2d.h new file mode 100644 index 0000000000000000000000000000000000000000..24d90f1ebe76bfb9a06e3b93a76b053962aae17b --- /dev/null +++ b/wifi/frameworks/native/include/wifi_hid2d.h @@ -0,0 +1,148 @@ +/* + * Copyright (C) 2022 Huawei Device Co., Ltd. + * 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 OHOS_WIFI_HID2D_H +#define OHOS_WIFI_HID2D_H + +#include "wifi_errcode.h" +#include +#include "wifi_hid2d_msg.h" + +namespace OHOS { +namespace Wifi { +class Hid2d { +public: + static std::unique_ptr CreateWifiHid2d(int system_ability_id); + static std::unique_ptr GetInstance(int system_ability_id); + + virtual ~Hid2d(); + + /** + * @Description Request an IP address to the Gc from the IP address pool, used on the GO side. + * + * @param gcMac - gc mac address + * @param ipAddr - applied ip address + * @return ErrCode - operation result + */ + virtual ErrCode Hid2dRequestGcIp(const std::string& gcMac, std::string& ipAddr) = 0; + + /** + * @Description Increase(+1) hid2d shared link reference counting + * + * @return ErrCode - operation result + */ + virtual ErrCode Hid2dSharedlinkIncrease() = 0; + + /** + * @Description Decrease(-1) hid2d shared link reference counting + * + * @return ErrCode - operation result + */ + virtual ErrCode Hid2dSharedlinkDecrease() = 0; + + /** + * @Description Create hid2d group, used on the GO side. + * + * @param frequency - frequency + * @param type - frequency type + * @return ErrCode - operation result + */ + virtual ErrCode Hid2dCreateGroup(const int frequency, FreqType type) = 0; + + /** + * @Description The GC side actively disconnects from the GO, used on the GC side. + * + * @param gcIfName - network interface name + * @return ErrCode - operation result + */ + virtual ErrCode Hid2dRemoveGcGroup(const std::string& gcIfName) = 0; + + /** + * @Description Connect to a specified group using hid2d, used on the GC side. + * + * @param config - connection parameters + * @return ErrCode - operation result + */ + virtual ErrCode Hid2dConnect(const Hid2dConnectConfig& config) = 0; + + /** + * @Description Configuring IP addresses for P2P network interfaces, used on the GC side. + * + * @param ifName - network interface name + * @param ipInfo - IP infos + * @return ErrCode - operation result + */ + virtual ErrCode Hid2dConfigIPAddr(const std::string& ifName, const IpAddrInfo& ipInfo) = 0; + + /** + * @Description Clear IP address when the P2P connection is disconnected, used on the GC side. + * + * @param ifName - network interface name + * @return ErrCode - operation result + */ + virtual ErrCode Hid2dReleaseIPAddr(const std::string& ifName) = 0; + + /** + * @Description Obtain the recommended channel and bandwidth for link setup + * + * @param request - request data + * @param response - response result + * @return ErrCode - operation result + */ + virtual ErrCode Hid2dGetRecommendChannel(const RecommendChannelRequest& request, + RecommendChannelResponse& response) = 0; + + /** + * @Description get 5G channel list + * + * @param vecChannelList - result for channel list + * @return ErrCode - operation result + */ + virtual ErrCode Hid2dGetChannelListFor5G(std::vector& vecChannelList) = 0; + + /** + * @Description get the self wifi configuration information + * + * @param cfgType - configuration type + * @param cfgData - the queried data of wifi configuration + * @param getDatValidLen - the valid data length in the array `cfgData` + * @return ErrCode - operation result + */ + virtual ErrCode Hid2dGetSelfWifiCfgInfo(SelfCfgType cfgType, + char cfgData[CFG_DATA_MAX_BYTES], int* getDatValidLen) = 0; + + /** + * @Description set the peer wifi configuration information + * + * @param cfgType - configuration type + * @param cfgData - the wifi configuration data to be set + * @param setDataValidLen - the valid data length in the array `cfgData` + * @return ErrCode - operation result + */ + virtual ErrCode Hid2dSetPeerWifiCfgInfo(PeerCfgType cfgType, + char cfgData[CFG_DATA_MAX_BYTES], int setDataValidLen) = 0; + + /** + * @Description Set the scene of upper layer + * + * @param ifName - interface name + * @param scene - scene + * @return ErrCode - operate result + */ + virtual ErrCode Hid2dSetUpperScene(const std::string& ifName, const Hid2dUpperScene& scene) = 0; +}; +} // namespace Wifi +} // namespace OHOS +#endif \ No newline at end of file diff --git a/interfaces/innerkits/native_cpp/wifi_standard/include/wifi_hotspot.h b/wifi/frameworks/native/include/wifi_hotspot.h similarity index 77% rename from interfaces/innerkits/native_cpp/wifi_standard/include/wifi_hotspot.h rename to wifi/frameworks/native/include/wifi_hotspot.h index 375b427e1c58d590ee0f32b1fd474d624a8f4c60..c821345a93ee2532fc9e928392b89f68bfeceacd 100644 --- a/interfaces/innerkits/native_cpp/wifi_standard/include/wifi_hotspot.h +++ b/wifi/frameworks/native/include/wifi_hotspot.h @@ -1,5 +1,5 @@ /* - * Copyright (C) 2021 Huawei Device Co., Ltd. + * Copyright (C) 2021-2022 Huawei Device Co., Ltd. * 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 @@ -16,21 +16,20 @@ #ifndef OHOS_WIFI_HOTSPOT_H #define OHOS_WIFI_HOTSPOT_H +#include #include #include -#include - #include "wifi_errcode.h" -#include "wifi_msg.h" +#include "wifi_ap_msg.h" #include "i_wifi_hotspot_callback.h" namespace OHOS { namespace Wifi { class WifiHotspot { public: - static std::unique_ptr CreateWifiHotspot(int system_ability_id); + static std::unique_ptr CreateWifiHotspot(int system_ability_id, int id = 0); - static std::unique_ptr GetInstance(int system_ability_id); + static std::unique_ptr GetInstance(int system_ability_id, int id = 0); virtual ~WifiHotspot(); @@ -41,6 +40,13 @@ public: */ virtual bool IsHotspotActive(void) = 0; + /** + * @Description Check whether the hotspot supports dual band. + * + * @return bool - operation result + */ + virtual bool IsHotspotDualBandSupported(void) = 0; + /** * @Description Get the Hotspot Config object * @@ -84,16 +90,18 @@ public: /** * @Description Enable Hotspot * + * @param type - service type * @return ErrCode - operation result */ - virtual ErrCode EnableHotspot(void) = 0; + virtual ErrCode EnableHotspot(const ServiceType type = ServiceType::DEFAULT) = 0; /** * @Description Disable Hotspot * + * @param type - service type * @return ErrCode - operation result */ - virtual ErrCode DisableHotspot(void) = 0; + virtual ErrCode DisableHotspot(const ServiceType type = ServiceType::DEFAULT) = 0; /** * @Description Get the Block Lists object @@ -156,10 +164,33 @@ public: * @Description Check if supported input feature * * @param feature - input feature - * @return true - supported - * @return false - unsupported + * @return bool - true if supported, false if unsupported */ virtual bool IsFeatureSupported(long feature) = 0; + + /** + * @Description Get supported power model list + * + * @param setPowerModelList - supported power model list + * @return ErrCode - operation result + */ + virtual ErrCode GetSupportedPowerModel(std::set& setPowerModelList) = 0; + + /** + * @Description Get power model + * + * @param model - current power model + * @return ErrCode - operation result + */ + virtual ErrCode GetPowerModel(PowerModel& model) = 0; + + /** + * @Description Get supported power model list + * + * @param model - the model to be set + * @return ErrCode - operation result + */ + virtual ErrCode SetPowerModel(const PowerModel& model) = 0; }; } // namespace Wifi } // namespace OHOS diff --git a/wifi/frameworks/native/include/wifi_ipc_lite_adapter.h b/wifi/frameworks/native/include/wifi_ipc_lite_adapter.h new file mode 100644 index 0000000000000000000000000000000000000000..8149748fcd338652e6eafb4bbc327da464e2fb4b --- /dev/null +++ b/wifi/frameworks/native/include/wifi_ipc_lite_adapter.h @@ -0,0 +1,35 @@ +/* + * Copyright (C) 2022 Huawei Device Co., Ltd. + * 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 OHOS_WIFI_IPC_LITE_ADAPTER_H +#define OHOS_WIFI_IPC_LITE_ADAPTER_H + +#define WIFI_SERVICE_LITE "wifisrvlite" +#define WIFI_FEATURE_DEVICE "wifidevice" +#define WIFI_FEATRUE_SCAN "wifiscan" + +#define IPC_DATA_SIZE_BIG 2048 +#define IPC_DATA_SIZE_MID 512 +#define IPC_DATA_SIZE_SMALL 256 +#define MAX_IPC_OBJ_COUNT 5 + +struct IpcOwner { + int funcId; + int exception; + int retCode; + void *variable; +}; + +#endif \ No newline at end of file diff --git a/interfaces/innerkits/native_cpp/wifi_standard/include/wifi_p2p.h b/wifi/frameworks/native/include/wifi_p2p.h similarity index 74% rename from interfaces/innerkits/native_cpp/wifi_standard/include/wifi_p2p.h rename to wifi/frameworks/native/include/wifi_p2p.h index 5d3d7f26da5f38a3c1017079499073454ba47e2a..9a1c878a0a20e79745da02e141275c3a88801791 100644 --- a/interfaces/innerkits/native_cpp/wifi_standard/include/wifi_p2p.h +++ b/wifi/frameworks/native/include/wifi_p2p.h @@ -1,5 +1,5 @@ /* - * Copyright (C) 2021 Huawei Device Co., Ltd. + * Copyright (C) 2021-2022 Huawei Device Co., Ltd. * 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 @@ -12,6 +12,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + #ifndef OHOS_WIFI_P2P_H #define OHOS_WIFI_P2P_H @@ -31,42 +32,42 @@ public: /** * @Description Enabling the P2P Mode. * - * @return ErrCode - operate result + * @return ErrCode - operation result */ virtual ErrCode EnableP2p(void) = 0; /** * @Description Disable the P2P mode. * - * @return ErrCode - operate result + * @return ErrCode - operation result */ virtual ErrCode DisableP2p(void) = 0; /** * @Description Start Wi-Fi P2P device search. * - * @return ErrCode - operate result + * @return ErrCode - operation result */ virtual ErrCode DiscoverDevices(void) = 0; /** * @Description Stop Wi-Fi P2P device search. * - * @return ErrCode - operate result + * @return ErrCode - operation result */ virtual ErrCode StopDiscoverDevices(void) = 0; /** * @Description Start the search for the Wi-Fi P2P service. * - * @return ErrCode - operate result + * @return ErrCode - operation result */ virtual ErrCode DiscoverServices(void) = 0; /** * @Description Stop the search for the Wi-Fi P2P service. * - * @return ErrCode - operate result + * @return ErrCode - operation result */ virtual ErrCode StopDiscoverServices(void) = 0; @@ -75,7 +76,7 @@ public: * * @param device - WifiP2pDevice object * @param request - WifiP2pServiceRequest object - * @return ErrCode - operate result + * @return ErrCode - operation result */ virtual ErrCode RequestService(const WifiP2pDevice &device, const WifiP2pServiceRequest &request) = 0; @@ -83,7 +84,7 @@ public: * @Description Register the local P2P service. * * @param srvInfo - WifiP2pServiceInfo object - * @return ErrCode - operate result + * @return ErrCode - operation result */ virtual ErrCode PutLocalP2pService(const WifiP2pServiceInfo &srvInfo) = 0; @@ -91,7 +92,7 @@ public: * @Description Delete the local P2P service. * * @param srvInfo - WifiP2pServiceInfo object - * @return ErrCode - operate result + * @return ErrCode - operation result */ virtual ErrCode DeleteLocalP2pService(const WifiP2pServiceInfo &srvInfo) = 0; @@ -100,29 +101,29 @@ public: * * @param period - period * @param interval - interval - * @return ErrCode - operate result + * @return ErrCode - operation result */ virtual ErrCode StartP2pListen(int period, int interval) = 0; /** * @Description Disable Wi-Fi P2P listening. * - * @return ErrCode - operate result + * @return ErrCode - operation result */ virtual ErrCode StopP2pListen(void) = 0; /** * @Description Creating a P2P Group. * - * @param config - WifiP2pGroupInfo object - * @return ErrCode - operate result + * @param config - WifiP2pConfig object + * @return ErrCode - operation result */ - virtual ErrCode FormGroup(const WifiP2pConfig &config) = 0; + virtual ErrCode CreateGroup(const WifiP2pConfig &config) = 0; /** * @Description Remove a P2P Group. * - * @return ErrCode - operate result + * @return ErrCode - operation result */ virtual ErrCode RemoveGroup(void) = 0; @@ -130,7 +131,7 @@ public: * @Description Delete a p2p Group. * * @param group - WifiP2pGroupInfo object - * @return ErrCode - operate result + * @return ErrCode - operation result */ virtual ErrCode DeleteGroup(const WifiP2pGroupInfo &group) = 0; @@ -138,30 +139,30 @@ public: * @Description P2P connection. * * @param config - WifiP2pConfig object - * @return ErrCode - operate result + * @return ErrCode - operation result */ virtual ErrCode P2pConnect(const WifiP2pConfig &config) = 0; /** - * @Description P2P disconnection. + * @Description Canceling a P2P connection. * - * @return ErrCode - operate result + * @return ErrCode - operation result */ - virtual ErrCode P2pDisConnect(void) = 0; + virtual ErrCode P2pCancelConnect(void) = 0; /** * @Description Querying Wi-Fi P2P Connection Information. * - * @param connInfo - Get the WifiP2pInfo msg - * @return ErrCode - operate result + * @param linkedInfo - Get the WifiP2pLinkedInfo msg + * @return ErrCode - operation result */ - virtual ErrCode QueryP2pInfo(WifiP2pInfo &connInfo) = 0; + virtual ErrCode QueryP2pLinkedInfo(WifiP2pLinkedInfo &linkedInfo) = 0; /** * @Description Get the Current Group object. * * @param group - the WifiP2pGroupInfo object - * @return ErrCode - operate result + * @return ErrCode - operation result */ virtual ErrCode GetCurrentGroup(WifiP2pGroupInfo &group) = 0; @@ -169,7 +170,7 @@ public: * @Description Obtains the P2P switch status. * * @param status - the P2P switch status - * @return ErrCode - operate result + * @return ErrCode - operation result */ virtual ErrCode GetP2pEnableStatus(int &status) = 0; @@ -177,7 +178,7 @@ public: * @Description Obtains the P2P discovery status. * * @param status - the P2P discovery status - * @return ErrCode + * @return ErrCode - operation result */ virtual ErrCode GetP2pDiscoverStatus(int &status) = 0; @@ -185,23 +186,31 @@ public: * @Description Obtains the P2P connection status. * * @param status - the P2P connection status - * @return ErrCode - operate result + * @return ErrCode - operation result */ virtual ErrCode GetP2pConnectedStatus(int &status) = 0; + /** + * @Description Query the local device information. + * + * @param devives - Get result of WifiP2pDevice + * @return ErrCode - operation result + */ + virtual ErrCode QueryP2pLocalDevice(WifiP2pDevice &device) = 0; + /** * @Description Query the information about the found devices. * - * @param devives - Get result vector of WifiP2pDevice - * @return ErrCode - operate result + * @param devices - Get result vector of WifiP2pDevice + * @return ErrCode - operation result */ - virtual ErrCode QueryP2pDevices(std::vector &devives) = 0; + virtual ErrCode QueryP2pDevices(std::vector &devices) = 0; /** * @Description Query the information about the found groups. * * @param groups - Get result vector of WifiP2pGroupInfo - * @return ErrCode - operate result + * @return ErrCode - operation result */ virtual ErrCode QueryP2pGroups(std::vector &groups) = 0; @@ -209,7 +218,7 @@ public: * @Description Query the service information. * * @param services - Get result vector of Device - * @return ErrCode - operate result + * @return ErrCode - operation result */ virtual ErrCode QueryP2pServices(std::vector &services) = 0; @@ -217,7 +226,7 @@ public: * @Description Register callback function. * * @param callback - IWifiP2pCallback object - * @return ErrCode - operate result + * @return ErrCode - operation result */ virtual ErrCode RegisterCallBack(const sptr &callback) = 0; @@ -233,8 +242,7 @@ public: * @Description Check if supported input feature * * @param feature - input feature - * @return true - supported - * @return false - unsupported + * @return bool - true if supported, false if unsupported */ virtual bool IsFeatureSupported(long feature) = 0; @@ -242,7 +250,7 @@ public: * @Description set the device name * * @param deviceName - device name - * @return ErrCode - operate result + * @return ErrCode - operation result */ virtual ErrCode SetP2pDeviceName(const std::string &deviceName) = 0; @@ -250,7 +258,7 @@ public: * @Description set p2p wifi display info * * @param wfdInfo - wifi display info - * @return ErrCode - operate result + * @return ErrCode - operation result */ virtual ErrCode SetP2pWfdInfo(const WifiP2pWfdInfo &wfdInfo) = 0; }; diff --git a/interfaces/innerkits/native_cpp/wifi_standard/include/wifi_scan.h b/wifi/frameworks/native/include/wifi_scan.h similarity index 85% rename from interfaces/innerkits/native_cpp/wifi_standard/include/wifi_scan.h rename to wifi/frameworks/native/include/wifi_scan.h index 419789c6a3c9784c8305ff56d91b30f685a19f29..f39c4323d2a349335453b3c64e0e1895cdc23c49 100644 --- a/interfaces/innerkits/native_cpp/wifi_standard/include/wifi_scan.h +++ b/wifi/frameworks/native/include/wifi_scan.h @@ -1,5 +1,5 @@ /* - * Copyright (C) 2021 Huawei Device Co., Ltd. + * Copyright (C) 2021-2022 Huawei Device Co., Ltd. * 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 @@ -16,8 +16,8 @@ #ifndef OHOS_WIFI_SCAN_H #define OHOS_WIFI_SCAN_H -#include "wifi_msg.h" #include "wifi_errcode.h" +#include "wifi_scan_msg.h" #include "i_wifi_scan_callback.h" namespace OHOS { @@ -48,12 +48,16 @@ public: /** * @Description Obtain the scanning result * - * @param result - Get result venctor of WifiScanInfo + * @param result - Get result vector of WifiScanInfo * @return ErrCode - operation result */ virtual ErrCode GetScanInfoList(std::vector &result) = 0; +#ifdef OHOS_ARCH_LITE + virtual ErrCode RegisterCallBack(const std::shared_ptr &callback) = 0; +#else virtual ErrCode RegisterCallBack(const sptr &callback) = 0; +#endif /** * @Description Get supported features @@ -67,8 +71,7 @@ public: * @Description Check if supported input feature * * @param feature - input feature - * @return true - supported - * @return false - unsupported + * @return bool - true if supported, false if unsupported */ virtual bool IsFeatureSupported(long feature) = 0; }; diff --git a/interfaces/innerkits/native_cpp/wifi_standard/interfaces/define.h b/wifi/frameworks/native/interfaces/define.h similarity index 70% rename from interfaces/innerkits/native_cpp/wifi_standard/interfaces/define.h rename to wifi/frameworks/native/interfaces/define.h index 98546a208b85803876c14969cfe269b02cd745af..e5f816a2331f22509108792b3d0e8725338fedb7 100644 --- a/interfaces/innerkits/native_cpp/wifi_standard/interfaces/define.h +++ b/wifi/frameworks/native/interfaces/define.h @@ -1,5 +1,5 @@ /* - * Copyright (C) 2021 Huawei Device Co., Ltd. + * Copyright (C) 2021-2022 Huawei Device Co., Ltd. * 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 @@ -49,7 +49,12 @@ #define WIFI_SVR_CMD_REMOVE_ALL_DEVICE_CONFIG 0x1020 /* remove all network configs */ #define WIFI_SVR_CMD_GET_SUPPORTED_FEATURES 0x1021 /* get supported features */ #define WIFI_SVR_CMD_GET_DERVICE_MAC_ADD 0x1022 /* get mac address */ - +#define WIFI_SVR_CMD_INIT_WIFI_PROTECT 0x1023 /* init the Wi-Fi protect. */ +#define WIFI_SVR_CMD_GET_WIFI_PROTECT 0x1024 /* get the Wi-Fi protect. */ +#define WIFI_SVR_CMD_PUT_WIFI_PROTECT 0x1025 /* put the Wi-Fi protect. */ +#define WIFI_SVR_CMD_IS_WIFI_CONNECTED 0x1026 /* is Wi-Fi connected */ +#define WIFI_SVR_CMD_SET_LOW_LATENCY_MODE 0x1027 /* set low latency mode */ +#define WIFI_SVR_CMD_REMOVE_CANDIDATE_CONFIG 0x1028 /* remove an candidate network config */ /* -------------ap module message define----------------- */ #define WIFI_SVR_CMD_ENABLE_WIFI_AP 0x1100 /* open ap */ #define WIFI_SVR_CMD_DISABLE_WIFI_AP 0x1101 /* close ap */ @@ -67,6 +72,10 @@ #define WIFI_SVR_CMD_GET_VALID_BANDS 0X110E /* get current valid frequency according band */ #define WIFI_SVR_CMD_GET_VALID_CHANNELS 0X110F /* get current valid channels associated with the band */ #define WIFI_SVR_CMD_REGISTER_HOTSPOT_CALLBACK 0X1110 /* register scan callback */ +#define WIFI_SVR_CMD_GET_SUPPORTED_POWER_MODEL 0X1111 /* get supported power model */ +#define WIFI_SVR_CMD_GET_POWER_MODEL 0X1112 /* get power model */ +#define WIFI_SVR_CMD_SET_POWER_MODEL 0X1113 /* set power model */ +#define WIFI_SVR_CMD_IS_HOTSPOT_DUAL_BAND_SUPPORTED 0X1114 /* whether dual band is supported */ /* -------------p2p module message define----------------- */ #define WIFI_SVR_CMD_P2P_ENABLE 0x2000 /* open p2p */ @@ -80,11 +89,11 @@ #define WIFI_SVR_CMD_P2P_DELETE_LOCAL_SERVICES 0x2008 /* remove local P2P service */ #define WIFI_SVR_CMD_P2P_START_LISTEN 0x2009 /* enable Wi-Fi P2P listening */ #define WIFI_SVR_CMD_P2P_STOP_LISTEN 0x200A /* disable Wi-Fi P2P listening */ -#define WIFI_SVR_CMD_P2P_FORM_GROUP 0x200B /* creating a P2P Group */ +#define WIFI_SVR_CMD_P2P_CREATE_GROUP 0x200B /* creating a P2P Group */ #define WIFI_SVR_CMD_P2P_REMOVE_GROUP 0x200C /* remove a P2P Group */ #define WIFI_SVR_CMD_P2P_DELETE_GROUP 0x200D /* delete a P2P Group */ #define WIFI_SVR_CMD_P2P_CONNECT 0x200E /* p2p connect */ -#define WIFI_SVR_CMD_P2P_DISCONNECT 0x200F /* p2p disconnect */ +#define WIFI_SVR_CMD_P2P_CANCEL_CONNECT 0x200F /* p2p cancel connect */ #define WIFI_SVR_CMD_P2P_QUERY_INFO 0x2010 /* querying Wi-Fi P2P Connection Information */ #define WIFI_SVR_CMD_P2P_GET_CURRENT_GROUP 0x2011 /* get the P2P current group */ #define WIFI_SVR_CMD_P2P_GET_ENABLE_STATUS 0x2012 /* obtains the P2P switch status */ @@ -96,6 +105,20 @@ #define WIFI_SVR_CMD_P2P_REGISTER_CALLBACK 0x2018 #define WIFI_SVR_CMD_P2P_SET_DEVICE_NAME 0x2019 /* set device name */ #define WIFI_SVR_CMD_P2P_SET_WFD_INFO 0x201A /* set p2p wifi display info */ +#define WIFI_SVR_CMD_P2P_HID2D_APPLY_IP 0x201B /* hid2d apply ip */ +#define WIFI_SVR_CMD_P2P_HID2D_SHARED_LINK_INCREASE 0x201C /* hid2d shared link increase */ +#define WIFI_SVR_CMD_P2P_HID2D_SHARED_LINK_DECREASE 0x201D /* hid2d shared link decrease */ +#define WIFI_SVR_CMD_P2P_HID2D_CREATE_GROUP 0x201E /* hid2d create group */ +#define WIFI_SVR_CMD_P2P_HID2D_REMOVE_GC_GROUP 0x201F /* hid2d remove GC group */ +#define WIFI_SVR_CMD_P2P_HID2D_CONNECT 0x2020 /* hid2d connect to group */ +#define WIFI_SVR_CMD_P2P_HID2D_CONFIG_IP 0x2021 /* hid2d configure IP address */ +#define WIFI_SVR_CMD_P2P_HID2D_RELEASE_IP 0x2022 /* hid2d release IP address */ +#define WIFI_SVR_CMD_GET_P2P_RECOMMENDED_CHANNEL 0x2023 /* get recommended channel */ +#define WIFI_SVR_CMD_GET_5G_CHANNEL_LIST 0x2024 /* get recommended channel */ +#define WIFI_SVR_CMD_GET_SELF_WIFI_CFG 0x2025 /* get self wifi configuration */ +#define WIFI_SVR_CMD_SET_PEER_WIFI_CFG 0x2026 /* set peer wifi configuration */ +#define WIFI_SVR_CMD_P2P_QUERY_LOCAL_DEVICE 0x2027 /* query the information about the local device */ +#define WIFI_SVR_CMD_SET_UPPER_SCENE 0x2028 /* set the scene of upper layer */ /* -----------register event type and message define-------------- */ #define WIFI_CBK_CMD_STATE_CHANGE 0x1001 /* STA state change event */ @@ -107,6 +130,7 @@ #define WIFI_CBK_CMD_HOTSPOT_STATE_LEAVE 0x1007 /* AP leave a sta event */ #define WIFI_CBK_CMD_STREAM_DIRECTION 0x1008 /* traffic up/down state event */ #define WIFI_CBK_CMD_WPS_STATE_CHANGE 0x1009 /* wps state change event */ +#define WIFI_CBK_CMD_DEVICE_CONFIG_CHANGE 0x100A /* device config change event */ #define WIFI_CBK_CMD_P2P_STATE_CHANGE 0x1010 /* p2p state change event */ #define WIFI_CBK_CMD_PERSISTENT_GROUPS_CHANGE 0x1011 /* Persistent Group Updated */ @@ -116,24 +140,34 @@ #define WIFI_CBK_CMD_CONNECT_CHANGE 0x1015 #define WIFI_CBK_CMD_DISCOVERY_CHANGE 0x1016 #define WIFI_CBK_CMD_P2P_ACTION_RESULT 0x1017 +#define WIFI_CBK_CMD_CFG_CHANGE 0x1018 +/* The response message ID of callback */ #define WIFI_CBK_MSG_STATE_CHANGE 0x1001 #define WIFI_CBK_MSG_CONNECTION_CHANGE 0x1002 #define WIFI_CBK_MSG_RSSI_CHANGE 0x1003 #define WIFI_CBK_MSG_STREAM_DIRECTION 0x1004 #define WIFI_CBK_MSG_WPS_STATE_CHANGE 0x1005 -#define WIFI_CBK_MSG_SCAN_STATE_CHANGE 0x1006 -#define WIFI_CBK_MSG_HOTSPOT_STATE_CHANGE 0x1007 -#define WIFI_CBK_MSG_HOTSPOT_STATE_JOIN 0x1008 -#define WIFI_CBK_MSG_HOTSPOT_STATE_LEAVE 0x1009 -#define WIFI_CBK_MSG_P2P_STATE_CHANGE 0x1010 -#define WIFI_CBK_MSG_PERSISTENT_GROUPS_CHANGE 0x1011 /* Persistent Group Updated */ -#define WIFI_CBK_MSG_THIS_DEVICE_CHANGE 0x1012 -#define WIFI_CBK_MSG_PEER_CHANGE 0x1013 -#define WIFI_CBK_MSG_SERVICE_CHANGE 0x1014 -#define WIFI_CBK_MSG_CONNECT_CHANGE 0x1015 -#define WIFI_CBK_MSG_DISCOVERY_CHANGE 0x1016 -#define WIFI_CBK_MSG_P2P_ACTION_RESULT 0x1017 +#define WIFI_CBK_MSG_DEVICE_CONFIG_CHANGE 0x1006 +#define WIFI_CBK_MSG_MAX_INVALID_STA 0x1FFF /* STA invalid value */ + +#define WIFI_CBK_MSG_SCAN_STATE_CHANGE 0x2001 + +#define WIFI_CBK_MSG_HOTSPOT_STATE_CHANGE 0x3001 +#define WIFI_CBK_MSG_HOTSPOT_STATE_JOIN 0x3002 +#define WIFI_CBK_MSG_HOTSPOT_STATE_LEAVE 0x3003 +#define WIFI_CBK_MSG_MAX_INVALID_HOTSPOT 0x3FFF /* HOTSPOT invalid value */ + +#define WIFI_CBK_MSG_P2P_STATE_CHANGE 0x4001 +#define WIFI_CBK_MSG_PERSISTENT_GROUPS_CHANGE 0x4002 /* Persistent Group Updated */ +#define WIFI_CBK_MSG_THIS_DEVICE_CHANGE 0x4003 +#define WIFI_CBK_MSG_PEER_CHANGE 0x4004 +#define WIFI_CBK_MSG_SERVICE_CHANGE 0x4005 +#define WIFI_CBK_MSG_CONNECT_CHANGE 0x4006 +#define WIFI_CBK_MSG_DISCOVERY_CHANGE 0x4007 +#define WIFI_CBK_MSG_P2P_ACTION_RESULT 0x4008 +#define WIFI_CBK_MSG_CFG_CHANGE 0x4009 +#define WIFI_CBK_MSG_MAX_INVALID_P2P 0x4FFF /* P2P invalid value */ /* -----------Feature service name-------------- */ #define WIFI_SERVICE_STA "StaService" /* STA */ @@ -143,9 +177,19 @@ #define WIFI_SERVICE_AWARE "AwareService" /* AWARE */ /* ---------Feature service ability id */ -#define WIFI_DEVICE_ABILITY_ID 1125 -#define WIFI_SCAN_ABILITY_ID 1126 -#define WIFI_HOTSPOT_ABILITY_ID 1127 -#define WIFI_P2P_ABILITY_ID 1128 +#define WIFI_DEVICE_ABILITY_ID 1120 +#define WIFI_HOTSPOT_ABILITY_ID 1121 +#define WIFI_P2P_ABILITY_ID 1123 +#define WIFI_SCAN_ABILITY_ID 1124 + +#define MODE_STATE_SCREEN (1) +#define MODE_STATE_AIR_PLANE (2) +#define MODE_STATE_APP_RUN (3) +#define MODE_STATE_POWER_SAVING (4) +#define MODE_STATE_FREEZE (5) +#define MODE_STATE_NO_CHARGER_PLUG (6) + +#define MODE_STATE_OPEN (1) +#define MODE_STATE_CLOSE (2) #endif \ No newline at end of file diff --git a/interfaces/innerkits/native_cpp/wifi_standard/interfaces/i_wifi_device.h b/wifi/frameworks/native/interfaces/i_wifi_device.h similarity index 69% rename from interfaces/innerkits/native_cpp/wifi_standard/interfaces/i_wifi_device.h rename to wifi/frameworks/native/interfaces/i_wifi_device.h index 244c0f468a1b481be17640a15b7adcb7e331eae5..b6a96f1e190152176e7e9a85be55129122c4afde 100644 --- a/interfaces/innerkits/native_cpp/wifi_standard/interfaces/i_wifi_device.h +++ b/wifi/frameworks/native/interfaces/i_wifi_device.h @@ -1,5 +1,5 @@ /* - * Copyright (C) 2021 Huawei Device Co., Ltd. + * Copyright (C) 2021-2022 Huawei Device Co., Ltd. * 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 @@ -16,15 +16,21 @@ #define OHOS_I_WIFI_DEVICE_H #include "wifi_errcode.h" +#ifndef OHOS_ARCH_LITE #include "iremote_broker.h" #include "message_parcel.h" #include "message_option.h" +#endif #include "i_wifi_device_callback.h" #include "wifi_errcode.h" namespace OHOS { namespace Wifi { +#ifdef OHOS_ARCH_LITE +class IWifiDevice { +#else class IWifiDevice : public IRemoteBroker { +#endif public: virtual ~IWifiDevice() {} @@ -42,15 +48,67 @@ public: * @return ErrCode - operation result */ virtual ErrCode DisableWifi() = 0; + + /** + * @Description create the Wi-Fi protect. + * + * @param protectType - WifiProtectMode object + * @param protectName - the protect name + * @return ErrCode - operation result + */ + virtual ErrCode InitWifiProtect(const WifiProtectType &protectType, const std::string &protectName) = 0; + + /** + * @Description Acquire the Wi-Fi protect mode. + * + * @param protectMode - WifiProtectMode object + * @param protectName - the protect name + * @return ErrCode - operation result + */ + virtual ErrCode GetWifiProtectRef(const WifiProtectMode &protectMode, const std::string &protectName) = 0; + + /** + * @Description Release the Wi-Fi protect mode. + * + * @param protectName - the protect name + * @return ErrCode - operation result + */ + virtual ErrCode PutWifiProtectRef(const std::string &protectName) = 0; + + /** + * @Description Remove the wifi candidate device config equals to input network id + * + * @param networkId - the candidate device network id + * @return ErrCode - operation result + */ + virtual ErrCode RemoveCandidateConfig(int networkId) = 0; + + /** + * @Description Remove the wifi candidate device config by WifiDeviceConfig + * + * @param config - the candidate config to be removed + * @return ErrCode - operation result + */ + virtual ErrCode RemoveCandidateConfig(const WifiDeviceConfig &config) = 0; /** * @Description Add a wifi device configuration. * * @param config - WifiDeviceConfig object * @param result - the device configuration's network id + * @param isCandidate - Whether is candidate * @return ErrCode - operation result */ - virtual ErrCode AddDeviceConfig(const WifiDeviceConfig &config, int &result) = 0; + virtual ErrCode AddDeviceConfig(const WifiDeviceConfig &config, int &result, bool isCandidate) = 0; + + /** + * @Description Update a wifi device configuration. + * + * @param config - WifiDeviceConfig object + * @param result - the device configuration's network id after updated + * @return ErrCode - operation result + */ + virtual ErrCode UpdateDeviceConfig(const WifiDeviceConfig &config, int &result) = 0; /** * @Description Remove the wifi device config equals to input network id @@ -71,9 +129,10 @@ public: * @Description Get all the device configs * * @param result - Get result vector of WifiDeviceConfig + * @param isCandidate - Whether is candidate * @return ErrCode - operation result */ - virtual ErrCode GetDeviceConfigs(std::vector &result) = 0; + virtual ErrCode GetDeviceConfigs(std::vector &result, bool isCandidate) = 0; /** * @Description Enable device config, when set attemptEnable, disable other device config @@ -96,9 +155,10 @@ public: * @Description Connecting to a Specified Network * * @param networkId - network id + * @param isCandidate - Whether is candidate * @return ErrCode - operation result */ - virtual ErrCode ConnectToNetwork(int networkId) = 0; + virtual ErrCode ConnectToNetwork(int networkId, bool isCandidate) = 0; /** * @Description Connect To a network base WifiDeviceConfig object @@ -108,6 +168,13 @@ public: */ virtual ErrCode ConnectToDevice(const WifiDeviceConfig &config) = 0; + /** + * @Description Check whether Wi-Fi is connected. + * + * @return bool - true: connected, false: not connected + */ + virtual bool IsConnected() = 0; + /** * @Description Reconnect to the currently active network * @@ -198,7 +265,11 @@ public: * @param callback - IWifiDeviceCallBack object * @return ErrCode - operation result */ +#ifdef OHOS_ARCH_LITE + virtual ErrCode RegisterCallBack(const std::shared_ptr &callback) = 0; +#else virtual ErrCode RegisterCallBack(const sptr &callback) = 0; +#endif /** * @Description Get the Signal Level object @@ -226,8 +297,18 @@ public: */ virtual ErrCode GetDeviceMacAddress(std::string &result) = 0; + /** + * @Description set low latency mode + * + * @param enabled - true: enable low latency, false: disable low latency + * @return bool - operation result + */ + virtual bool SetLowLatencyMode(bool enabled) = 0; + +#ifndef OHOS_ARCH_LITE public: DECLARE_INTERFACE_DESCRIPTOR(u"ohos.wifi.IWifiDeviceService"); +#endif }; } // namespace Wifi } // namespace OHOS diff --git a/interfaces/innerkits/native_cpp/wifi_standard/interfaces/i_wifi_device_callback.h b/wifi/frameworks/native/interfaces/i_wifi_device_callback.h similarity index 86% rename from interfaces/innerkits/native_cpp/wifi_standard/interfaces/i_wifi_device_callback.h rename to wifi/frameworks/native/interfaces/i_wifi_device_callback.h index 87e86c939d5552aafa47844f013938fd4932530d..5b438e8f8021cbd34ba5a5624898d0eae875a3ff 100644 --- a/interfaces/innerkits/native_cpp/wifi_standard/interfaces/i_wifi_device_callback.h +++ b/wifi/frameworks/native/interfaces/i_wifi_device_callback.h @@ -16,17 +16,23 @@ #define OHOS_I_WIFI_DEVICE_CALLBACK_H #include +#ifndef OHOS_ARCH_LITE #include #include #include "message_parcel.h" #include "message_option.h" +#endif #include "wifi_msg.h" #include "define.h" namespace OHOS { namespace Wifi { +#ifdef OHOS_ARCH_LITE +class IWifiDeviceCallBack { +#else class IWifiDeviceCallBack : public IRemoteBroker { +#endif public: /** * @Description Deal wifi state change message @@ -65,8 +71,17 @@ public: */ virtual void OnStreamChanged(int direction) = 0; + /** + * @Description Deal device config change message + * + * @param ConfigChange - change type of config + */ + virtual void OnDeviceConfigChanged(ConfigChange value) = 0; + +#ifndef OHOS_ARCH_LITE public: DECLARE_INTERFACE_DESCRIPTOR(u"ohos.wifi.IWifiDeviceCallBack"); +#endif }; } // namespace Wifi } // namespace OHOS diff --git a/interfaces/innerkits/native_cpp/wifi_standard/interfaces/i_wifi_hotspot.h b/wifi/frameworks/native/interfaces/i_wifi_hotspot.h similarity index 77% rename from interfaces/innerkits/native_cpp/wifi_standard/interfaces/i_wifi_hotspot.h rename to wifi/frameworks/native/interfaces/i_wifi_hotspot.h index 3469e00c1e72fe3a5f2e53913e86c5887ddfb552..210624c44486c33123d47f036db24d030c25f93b 100644 --- a/interfaces/innerkits/native_cpp/wifi_standard/interfaces/i_wifi_hotspot.h +++ b/wifi/frameworks/native/interfaces/i_wifi_hotspot.h @@ -1,5 +1,5 @@ /* - * Copyright (C) 2021 Huawei Device Co., Ltd. + * Copyright (C) 2021-2022 Huawei Device Co., Ltd. * 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 @@ -20,7 +20,7 @@ #include "message_parcel.h" #include "message_option.h" #include "wifi_errcode.h" -#include "wifi_msg.h" +#include "wifi_ap_msg.h" #include "define.h" #include "wifi_errcode.h" #include "i_wifi_hotspot_callback.h" @@ -40,6 +40,14 @@ public: */ virtual ErrCode IsHotspotActive(bool &bActive) = 0; + /** + * @Description Check whether the hotspot supports dual band. + * + * @param isSupported - Supported / NOT supported + * @return ErrCode - operation result + */ + virtual ErrCode IsHotspotDualBandSupported(bool &isSupported) = 0; + /** * @Description Get the Hotspot Config object * @@ -83,16 +91,18 @@ public: /** * @Description Enable Hotspot * + * @param type - service type * @return ErrCode - operation result */ - virtual ErrCode EnableHotspot(void) = 0; + virtual ErrCode EnableHotspot(const ServiceType type = ServiceType::DEFAULT) = 0; /** * @Description Disable Hotspot * + * @param type - service type * @return ErrCode - operation result */ - virtual ErrCode DisableHotspot(void) = 0; + virtual ErrCode DisableHotspot(const ServiceType type = ServiceType::DEFAULT) = 0; /** * @Description Get the Block Lists object @@ -150,6 +160,30 @@ public: * @return ErrCode - operation result */ virtual ErrCode GetSupportedFeatures(long &features) = 0; + + /** + * @Description Get supported power model list + * + * @param setPowerModelList - supported power model list + * @return ErrCode - operation result + */ + virtual ErrCode GetSupportedPowerModel(std::set& setPowerModelList) = 0; + + /** + * @Description Get power model + * + * @param model - current power model + * @return ErrCode - operation result + */ + virtual ErrCode GetPowerModel(PowerModel& model) = 0; + + /** + * @Description Get supported power model list + * + * @param model - the model to be set + * @return ErrCode - operation result + */ + virtual ErrCode SetPowerModel(const PowerModel& model) = 0; public: DECLARE_INTERFACE_DESCRIPTOR(u"ohos.wifi.IWifiHotspotService"); }; diff --git a/interfaces/innerkits/native_cpp/wifi_standard/interfaces/i_wifi_hotspot_callback.h b/wifi/frameworks/native/interfaces/i_wifi_hotspot_callback.h similarity index 94% rename from interfaces/innerkits/native_cpp/wifi_standard/interfaces/i_wifi_hotspot_callback.h rename to wifi/frameworks/native/interfaces/i_wifi_hotspot_callback.h index 98804f4c902df2a982b111d1adf74c2f6befac2b..ff5c5c1cf53817dad9747220b991363dec6f8b8c 100644 --- a/interfaces/innerkits/native_cpp/wifi_standard/interfaces/i_wifi_hotspot_callback.h +++ b/wifi/frameworks/native/interfaces/i_wifi_hotspot_callback.h @@ -1,5 +1,5 @@ /* - * Copyright (C) 2021 Huawei Device Co., Ltd. + * Copyright (C) 2021-2022 Huawei Device Co., Ltd. * 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 @@ -21,7 +21,7 @@ #include #include "message_parcel.h" #include "message_option.h" -#include "wifi_msg.h" +#include "wifi_ap_msg.h" #include "define.h" namespace OHOS { @@ -54,4 +54,4 @@ public: }; } // namespace Wifi } // namespace OHOS -#endif \ No newline at end of file +#endif diff --git a/wifi/frameworks/native/interfaces/i_wifi_hotspot_mgr.h b/wifi/frameworks/native/interfaces/i_wifi_hotspot_mgr.h new file mode 100644 index 0000000000000000000000000000000000000000..d9e690380f003b77c6fe69995cc33e575ed7aa31 --- /dev/null +++ b/wifi/frameworks/native/interfaces/i_wifi_hotspot_mgr.h @@ -0,0 +1,42 @@ +/* + * Copyright (C) 2022 Huawei Device Co., Ltd. + * 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 OHOS_I_WIFI_HOTSPOT_MGR_H +#define OHOS_I_WIFI_HOTSPOT_MGR_H + +#include "iremote_broker.h" + +namespace OHOS { +namespace Wifi { +class IWifiHotspotMgr : public IRemoteBroker { +public: + IWifiHotspotMgr() {} + virtual ~IWifiHotspotMgr() {} + /** + * @Description get remote ap obj. + * + * @param id - obj id + * @return IRemoteObject - ap obj + */ + virtual sptr GetWifiRemote(int id) = 0; +public: + DECLARE_INTERFACE_DESCRIPTOR(u"ohos.wifi.IWifiHotspotMgr"); + enum Code { + WIFI_MGR_GET_HOTSPOT_SERVICE = 0, + }; +}; +} // namespace Wifi +} // namespace OHOS +#endif \ No newline at end of file diff --git a/interfaces/innerkits/native_cpp/wifi_standard/interfaces/i_wifi_p2p.h b/wifi/frameworks/native/interfaces/i_wifi_p2p.h similarity index 49% rename from interfaces/innerkits/native_cpp/wifi_standard/interfaces/i_wifi_p2p.h rename to wifi/frameworks/native/interfaces/i_wifi_p2p.h index 2e180f621c6f925bf21b29ced6c47ca90d22b45f..b1a59d1b2f4698664fc2ab64869ec8a36f56f5f7 100644 --- a/interfaces/innerkits/native_cpp/wifi_standard/interfaces/i_wifi_p2p.h +++ b/wifi/frameworks/native/interfaces/i_wifi_p2p.h @@ -1,5 +1,5 @@ /* - * Copyright (C) 2021 Huawei Device Co., Ltd. + * Copyright (C) 2021-2022 Huawei Device Co., Ltd. * 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 @@ -21,6 +21,7 @@ #include "message_option.h" #include "wifi_p2p_msg.h" #include "i_wifi_p2p_callback.h" +#include "wifi_hid2d_msg.h" namespace OHOS { namespace Wifi { @@ -32,42 +33,42 @@ public: /** * @Description Enabling the P2P Mode. * - * @return ErrCode - operate result + * @return ErrCode - operation result */ virtual ErrCode EnableP2p(void) = 0; /** * @Description Disable the P2P mode. * - * @return ErrCode - operate result + * @return ErrCode - operation result */ virtual ErrCode DisableP2p(void) = 0; /** * @Description Start Wi-Fi P2P device search. * - * @return ErrCode - operate result + * @return ErrCode - operation result */ virtual ErrCode DiscoverDevices(void) = 0; /** * @Description Stop Wi-Fi P2P device search. * - * @return ErrCode - operate result + * @return ErrCode - operation result */ virtual ErrCode StopDiscoverDevices(void) = 0; /** * @Description Start the search for the Wi-Fi P2P service. * - * @return ErrCode - operate result + * @return ErrCode - operation result */ virtual ErrCode DiscoverServices(void) = 0; /** * @Description Stop the search for the Wi-Fi P2P service. * - * @return ErrCode - operate result + * @return ErrCode - operation result */ virtual ErrCode StopDiscoverServices(void) = 0; @@ -76,7 +77,7 @@ public: * * @param device - WifiP2pDevice object * @param request - WifiP2pServiceRequest object - * @return ErrCode - operate result + * @return ErrCode - operation result */ virtual ErrCode RequestService(const WifiP2pDevice &device, const WifiP2pServiceRequest &request) = 0; @@ -84,7 +85,7 @@ public: * @Description Register the local P2P service. * * @param srvInfo - WifiP2pServiceInfo object - * @return ErrCode - operate result + * @return ErrCode - operation result */ virtual ErrCode PutLocalP2pService(const WifiP2pServiceInfo &srvInfo) = 0; @@ -92,7 +93,7 @@ public: * @Description Delete the local P2P service. * * @param srvInfo - WifiP2pServiceInfo object - * @return ErrCode - operate result + * @return ErrCode - operation result */ virtual ErrCode DeleteLocalP2pService(const WifiP2pServiceInfo &srvInfo) = 0; @@ -101,14 +102,14 @@ public: * * @param period - period * @param interval - interval - * @return ErrCode - operate result + * @return ErrCode - operation result */ virtual ErrCode StartP2pListen(int period, int interval) = 0; /** * @Description Disable Wi-Fi P2P listening. * - * @return ErrCode - operate result + * @return ErrCode - operation result */ virtual ErrCode StopP2pListen(void) = 0; @@ -116,14 +117,14 @@ public: * @Description Creating a P2P Group. * * @param config - WifiP2pGroupInfo object - * @return ErrCode - operate result + * @return ErrCode - operation result */ - virtual ErrCode FormGroup(const WifiP2pConfig &config) = 0; + virtual ErrCode CreateGroup(const WifiP2pConfig &config) = 0; /** * @Description Remove a P2P Group. * - * @return ErrCode - operate result + * @return ErrCode - operation result */ virtual ErrCode RemoveGroup(void) = 0; @@ -131,7 +132,7 @@ public: * @Description Delete a p2p Group. * * @param group - WifiP2pGroupInfo object - * @return ErrCode - operate result + * @return ErrCode - operation result */ virtual ErrCode DeleteGroup(const WifiP2pGroupInfo &group) = 0; @@ -139,30 +140,30 @@ public: * @Description P2P connection. * * @param config - WifiP2pConfig object - * @return ErrCode - operate result + * @return ErrCode - operation result */ virtual ErrCode P2pConnect(const WifiP2pConfig &config) = 0; /** - * @Description P2P disconnection. + * @Description Canceling a P2P connection. * - * @return ErrCode - operate result + * @return ErrCode - operation result */ - virtual ErrCode P2pDisConnect(void) = 0; + virtual ErrCode P2pCancelConnect(void) = 0; /** * @Description Querying Wi-Fi P2P Connection Information. * - * @param connInfo - Get the WifiP2pInfo msg - * @return ErrCode - operate result + * @param linkedInfo - Get the WifiP2pLinkedInfo msg + * @return ErrCode - operation result */ - virtual ErrCode QueryP2pInfo(WifiP2pInfo &connInfo) = 0; + virtual ErrCode QueryP2pLinkedInfo(WifiP2pLinkedInfo& linkedInfo) = 0; /** * @Description Get the Current Group object. * * @param group - the WifiP2pGroupInfo object - * @return ErrCode - operate result + * @return ErrCode - operation result */ virtual ErrCode GetCurrentGroup(WifiP2pGroupInfo &group) = 0; @@ -170,7 +171,7 @@ public: * @Description Obtains the P2P switch status. * * @param status - the P2P switch status - * @return ErrCode - operate result + * @return ErrCode - operation result */ virtual ErrCode GetP2pEnableStatus(int &status) = 0; @@ -186,23 +187,30 @@ public: * @Description Obtains the P2P connection status. * * @param status - the P2P connection status - * @return ErrCode - operate result + * @return ErrCode - operation result */ virtual ErrCode GetP2pConnectedStatus(int &status) = 0; /** * @Description Query the information about the found devices. * - * @param devives - Get result vector of WifiP2pDevice - * @return ErrCode - operate result + * @param devices - Get result vector of WifiP2pDevice + * @return ErrCode - operation result + */ + virtual ErrCode QueryP2pDevices(std::vector &devices) = 0; + + /** + * @Description - Query the information about own device. + * @param device - own device + * @return ErrCode - operation result */ - virtual ErrCode QueryP2pDevices(std::vector &devives) = 0; + virtual ErrCode QueryP2pLocalDevice(WifiP2pDevice &device) = 0; /** * @Description Query the information about the found groups. * * @param groups - Get result vector of WifiP2pGroupInfo - * @return ErrCode - operate result + * @return ErrCode - operation result */ virtual ErrCode QueryP2pGroups(std::vector &groups) = 0; @@ -210,7 +218,7 @@ public: * @Description Query the service information. * * @param services - Get result vector of Device - * @return ErrCode - operate result + * @return ErrCode - operation result */ virtual ErrCode QueryP2pServices(std::vector &services) = 0; @@ -218,7 +226,7 @@ public: * @Description Register callback function. * * @param callback - IWifiP2pCallback object - * @return ErrCode - operate result + * @return ErrCode - operation result */ virtual ErrCode RegisterCallBack(const sptr &callback) = 0; @@ -234,7 +242,7 @@ public: * @Description set the device name * * @param deviceName - device name - * @return ErrCode - operate result + * @return ErrCode - operation result */ virtual ErrCode SetP2pDeviceName(const std::string &deviceName) = 0; @@ -242,10 +250,124 @@ public: * @Description set p2p wifi display info * * @param wfdInfo - wifi display info - * @return ErrCode - operate result + * @return ErrCode - operation result */ virtual ErrCode SetP2pWfdInfo(const WifiP2pWfdInfo &wfdInfo) = 0; + /** + * @Description Request an IP address to the Gc from the IP address pool, used on the GO side. + * + * @param gcMac - gc mac address + * @param ipAddr - applied ip address + * @return ErrCode - operation result + */ + virtual ErrCode Hid2dRequestGcIp(const std::string& gcMac, std::string& ipAddr) = 0; + + /** + * @Description Increase(+1) hid2d shared link reference counting + * + * @return ErrCode - operation result + */ + virtual ErrCode Hid2dSharedlinkIncrease() = 0; + + /** + * @Description Decrease(-1) hid2d shared link reference counting + * + * @return ErrCode - operation result + */ + virtual ErrCode Hid2dSharedlinkDecrease() = 0; + + /** + * @Description Create hid2d group, used on the GO side. + * + * @param frequency - frequency + * @param type - frequency type + * @return ErrCode - operation result + */ + virtual ErrCode Hid2dCreateGroup(const int frequency, FreqType type) = 0; + + /** + * @Description The GC side actively disconnects from the GO, used on the GC side. + * + * @param gcIfName - network interface name + * @return ErrCode - operation result + */ + virtual ErrCode Hid2dRemoveGcGroup(const std::string& gcIfName) = 0; + + /** + * @Description Connect to a specified group using hid2d, used on the GC side. + * + * @param config - connection parameters + * @return ErrCode - operation result + */ + virtual ErrCode Hid2dConnect(const Hid2dConnectConfig& config) = 0; + + /** + * @Description Configuring IP addresses for P2P network interfaces, used on the GC side. + * + * @param ifName - network interface name + * @param ipInfo - IP infos + * @return ErrCode - operation result + */ + virtual ErrCode Hid2dConfigIPAddr(const std::string& ifName, const IpAddrInfo& ipInfo) = 0; + + /** + * @Description Clear IP address when the P2P connection is disconnected, used on the GC side. + * + * @param ifName - network interface name + * @return ErrCode - operation result + */ + virtual ErrCode Hid2dReleaseIPAddr(const std::string& ifName) = 0; + + /** + * @Description Obtain the recommended channel and bandwidth for link setup + * + * @param request - request data + * @param response - response result + * @return ErrCode - operation result + */ + virtual ErrCode Hid2dGetRecommendChannel(const RecommendChannelRequest& request, + RecommendChannelResponse& response) = 0; + + /** + * @Description get 5G channel list + * + * @param vecChannelList - result for channel list + * @return ErrCode - operation result + */ + virtual ErrCode Hid2dGetChannelListFor5G(std::vector& vecChannelList) = 0; + + /** + * @Description get the self wifi configuration information + * + * @param cfgType - configuration type + * @param cfgData - the queried data of wifi configuration + * @param getDatValidLen - the valid data length in the array `cfgData` + * @return ErrCode - operation result + */ + virtual ErrCode Hid2dGetSelfWifiCfgInfo(SelfCfgType cfgType, + char cfgData[CFG_DATA_MAX_BYTES], int* getDatValidLen) = 0; + + /** + * @Description set the peer wifi configuration information + * + * @param cfgType - configuration type + * @param cfgData - the wifi configuration data to be set + * @param setDataValidLen - the valid data length in the array `cfgData` + * @return ErrCode - operation result + */ + virtual ErrCode Hid2dSetPeerWifiCfgInfo(PeerCfgType cfgType, + char cfgData[CFG_DATA_MAX_BYTES], int setDataValidLen) = 0; + + /** + * @Description Set the scene of upper layer + * + * @param ifName - interface name + * @param scene - scene + * @return ErrCode - operate result + */ + virtual ErrCode Hid2dSetUpperScene(const std::string& ifName, const Hid2dUpperScene& scene) = 0; + public: DECLARE_INTERFACE_DESCRIPTOR(u"ohos.wifi.IWifiP2pService"); }; diff --git a/interfaces/innerkits/native_cpp/wifi_standard/interfaces/i_wifi_p2p_callback.h b/wifi/frameworks/native/interfaces/i_wifi_p2p_callback.h similarity index 84% rename from interfaces/innerkits/native_cpp/wifi_standard/interfaces/i_wifi_p2p_callback.h rename to wifi/frameworks/native/interfaces/i_wifi_p2p_callback.h index 188ba6463173e39c428e54d53756e307ab560b7f..d50bd51a8e04560f0dd128b0244e03ba0cdb8abe 100644 --- a/interfaces/innerkits/native_cpp/wifi_standard/interfaces/i_wifi_p2p_callback.h +++ b/wifi/frameworks/native/interfaces/i_wifi_p2p_callback.h @@ -17,11 +17,12 @@ #include #include -#include "message_parcel.h" -#include "message_option.h" -#include "wifi_p2p_msg.h" #include "define.h" +#include "message_option.h" +#include "message_parcel.h" #include "wifi_errcode.h" +#include "wifi_hid2d_msg.h" +#include "wifi_p2p_msg.h" namespace OHOS { namespace Wifi { @@ -65,9 +66,9 @@ public: /** * @Description Connection status change. * - * @param info - WifiP2pInfo object + * @param info - WifiP2pLinkedInfo object */ - virtual void OnP2pConnectionChanged(const WifiP2pInfo &info) = 0; + virtual void OnP2pConnectionChanged(const WifiP2pLinkedInfo &info) = 0; /** * @Description Discover status change. @@ -80,12 +81,21 @@ public: * @Description P2p callback result. * * @param action - DiscoverDevices/StopDiscoverDevices/DiscoverServices/StopDiscoverServices - * /PutLocalP2pService/StartP2pListen/StopP2pListen/FormGroup/RemoveGroup - * /DeleteGroup/P2pConnect/P2pDisConnect + * /PutLocalP2pService/StartP2pListen/StopP2pListen/CreateGroup/RemoveGroup + * /DeleteGroup/P2pConnect/P2pCancelConnect * @param code - Return code */ virtual void OnP2pActionResult(P2pActionCallback action, ErrCode code) = 0; + /** + * @Description Config changed callback. + * + * @param type - Config type + * @param data - Config data + * @param len - Config data length + */ + virtual void OnConfigChanged(CfgType type, char* data, int dataLen) = 0; + public: DECLARE_INTERFACE_DESCRIPTOR(u"ohos.wifi.IWifiP2pCallback"); }; diff --git a/interfaces/innerkits/native_cpp/wifi_standard/interfaces/i_wifi_scan.h b/wifi/frameworks/native/interfaces/i_wifi_scan.h similarity index 87% rename from interfaces/innerkits/native_cpp/wifi_standard/interfaces/i_wifi_scan.h rename to wifi/frameworks/native/interfaces/i_wifi_scan.h index 093fb572e5f9f1192433cc3e736753cc65ef5ded..6cc16ec4e3a2c7c54ee2004d4b41afe7972560e7 100644 --- a/interfaces/innerkits/native_cpp/wifi_standard/interfaces/i_wifi_scan.h +++ b/wifi/frameworks/native/interfaces/i_wifi_scan.h @@ -1,5 +1,5 @@ /* - * Copyright (C) 2021 Huawei Device Co., Ltd. + * Copyright (C) 2021-2022 Huawei Device Co., Ltd. * 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 @@ -16,20 +16,28 @@ #ifndef I_WIFI_SCAN_H #define I_WIFI_SCAN_H +#ifdef OHOS_ARCH_LITE +#include "iproxy_client.h" +#else #include #include -#include "wifi_errcode.h" #include "message_parcel.h" #include "message_option.h" -#include "wifi_msg.h" +#endif +#include "wifi_scan_msg.h" #include "wifi_errcode.h" #include "i_wifi_scan_callback.h" namespace OHOS { namespace Wifi { +#ifdef OHOS_ARCH_LITE +class IWifiScan { +public: +#else class IWifiScan : public IRemoteBroker { public: DECLARE_INTERFACE_DESCRIPTOR(u"ohos.wifi.IWifiScan"); +#endif virtual ~IWifiScan() {} @@ -72,7 +80,11 @@ public: */ virtual ErrCode GetScanInfoList(std::vector &result) = 0; +#ifdef OHOS_ARCH_LITE + virtual ErrCode RegisterCallBack(const std::shared_ptr &callback) = 0; +#else virtual ErrCode RegisterCallBack(const sptr &callback) = 0; +#endif /** * @Description Get supported features diff --git a/interfaces/innerkits/native_cpp/wifi_standard/interfaces/i_wifi_scan_callback.h b/wifi/frameworks/native/interfaces/i_wifi_scan_callback.h similarity index 86% rename from interfaces/innerkits/native_cpp/wifi_standard/interfaces/i_wifi_scan_callback.h rename to wifi/frameworks/native/interfaces/i_wifi_scan_callback.h index 56051bc2d3ccac62110bed3058764d1d98c10bc4..a7f13e5ca795db6877d9a2d2c03055e6cc71eda5 100644 --- a/interfaces/innerkits/native_cpp/wifi_standard/interfaces/i_wifi_scan_callback.h +++ b/wifi/frameworks/native/interfaces/i_wifi_scan_callback.h @@ -1,5 +1,5 @@ /* - * Copyright (C) 2021 Huawei Device Co., Ltd. + * Copyright (C) 2021-2022 Huawei Device Co., Ltd. * 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 @@ -16,22 +16,30 @@ #define OHOS_I_WIFI_SCAN_CALLBACK_H #include +#ifndef OHOS_ARCH_LITE #include #include #include "message_parcel.h" #include "message_option.h" +#endif #include "wifi_errcode.h" #include "wifi_msg.h" #include "define.h" namespace OHOS { namespace Wifi { +#ifdef OHOS_ARCH_LITE +class IWifiScanCallback { +#else class IWifiScanCallback : public IRemoteBroker { +#endif public: virtual void OnWifiScanStateChanged(int state) = 0; +#ifndef OHOS_ARCH_LITE public: DECLARE_INTERFACE_DESCRIPTOR(u"ohos.wifi.IWifiScanCallback"); +#endif }; } // namespace Wifi } // namespace OHOS diff --git a/interfaces/innerkits/native_cpp/wifi_standard/interfaces/wifi_ap_msg.h b/wifi/frameworks/native/interfaces/wifi_ap_msg.h similarity index 90% rename from interfaces/innerkits/native_cpp/wifi_standard/interfaces/wifi_ap_msg.h rename to wifi/frameworks/native/interfaces/wifi_ap_msg.h index 4ccefe084313033e3b50195b5b4ff35cabb5b7bc..68b4b3ab7b9be7b1e2d374dc4ad3f5573b99e830 100644 --- a/interfaces/innerkits/native_cpp/wifi_standard/interfaces/wifi_ap_msg.h +++ b/wifi/frameworks/native/interfaces/wifi_ap_msg.h @@ -1,5 +1,5 @@ /* - * Copyright (C) 2021 Huawei Device Co., Ltd. + * Copyright (C) 2021-2022 Huawei Device Co., Ltd. * 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 @@ -16,11 +16,15 @@ #ifndef OHOS_WIFI_AP_MSG_H #define OHOS_WIFI_AP_MSG_H #include +#include #include +#include "wifi_common_msg.h" namespace OHOS { namespace Wifi { #define AP_CHANNEL_DEFAULT 6 +#define AP_CHANNEL_5G_DEFAULT 149 +#define WIFI_BSSID_LENGTH 18 enum class ApState { AP_STATE_NONE = 0, AP_STATE_IDLE, @@ -49,6 +53,12 @@ enum class BandType { BAND_ANY = 3 /* Dual-mode frequency band */ }; +enum class PowerModel { + SLEEPING = 0, /* Sleeping model. */ + GENERAL = 1, /* General model. */ + THROUGH_WALL = 2, /* Through wall model. */ +}; + struct HotspotConfig { HotspotConfig() { diff --git a/interfaces/innerkits/native_cpp/napi/wifi_napi_p2p.h b/wifi/frameworks/native/interfaces/wifi_common_msg.h old mode 100755 new mode 100644 similarity index 78% rename from interfaces/innerkits/native_cpp/napi/wifi_napi_p2p.h rename to wifi/frameworks/native/interfaces/wifi_common_msg.h index 775c951f4e0a78d6ed96261463d918081b26aa11..db96583529e7d31b0d1cc30cec0892dea4460013 --- a/interfaces/innerkits/native_cpp/napi/wifi_napi_p2p.h +++ b/wifi/frameworks/native/interfaces/wifi_common_msg.h @@ -1,27 +1,27 @@ -/* - * Copyright (C) 2021 Huawei Device Co., Ltd. - * 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 WIFI_NAPI_P2P_H_ -#define WIFI_NAPI_P2P_H_ - -#include "wifi_napi_utils.h" - -namespace OHOS { -namespace Wifi { - -} // namespace Wifi -} // namespace OHOS - -#endif +/* + * Copyright (C) 2022 Huawei Device Co., Ltd. + * 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 OHOS_WIFI_COMMON_MSG_H +#define OHOS_WIFI_COMMON_MSG_H + +namespace OHOS { +namespace Wifi { +enum class ServiceType { + DEFAULT = 0, + WIFI_EXT = 1, +}; +} // namespace Wifi +} // namespace OHOS +#endif \ No newline at end of file diff --git a/interfaces/innerkits/native_cpp/wifi_standard/interfaces/wifi_errcode.h b/wifi/frameworks/native/interfaces/wifi_errcode.h similarity index 96% rename from interfaces/innerkits/native_cpp/wifi_standard/interfaces/wifi_errcode.h rename to wifi/frameworks/native/interfaces/wifi_errcode.h index f172ad149054a1ac9efe348b6b20f430b4ce9c4a..6d2eb764827879ac5023b9bbc4e19b5825d66c19 100644 --- a/interfaces/innerkits/native_cpp/wifi_standard/interfaces/wifi_errcode.h +++ b/wifi/frameworks/native/interfaces/wifi_errcode.h @@ -40,6 +40,7 @@ enum ErrCode { WIFI_OPT_P2P_ERR_MAC_FORMAT, WIFI_OPT_P2P_ERR_INTENT, WIFI_OPT_P2P_ERR_SIZE_NW_NAME, + WIFI_OPT_MOVING_FREEZE_CTRL, /* moving freeze scanning control */ }; } // namespace Wifi } // namespace OHOS diff --git a/wifi/frameworks/native/interfaces/wifi_hid2d_msg.h b/wifi/frameworks/native/interfaces/wifi_hid2d_msg.h new file mode 100644 index 0000000000000000000000000000000000000000..143ba12797e8a5796c93ee79d54ec95ffdea894c --- /dev/null +++ b/wifi/frameworks/native/interfaces/wifi_hid2d_msg.h @@ -0,0 +1,170 @@ +/* + * Copyright (C) 2022 Huawei Device Co., Ltd. + * 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 OHOS_WIFI_HID2D_MSG_H +#define OHOS_WIFI_HID2D_MSG_H + +#include + +#ifndef MAC_LEN +#define MAC_LEN 6 +#endif + +#ifndef CFG_DATA_MAX_BYTES +#define CFG_DATA_MAX_BYTES 255 +#endif + +namespace OHOS { +namespace Wifi { +enum class DhcpMode { + CONNECT_GO_NODHCP = 0, + CONNECT_AP_DHCP = 1, + CONNECT_AP_NODHCP = 2, + CONNECT_MODE_INVALID = 0xff +}; + +enum class FreqType { + FREQUENCY_DEFAULT = 0, + FREQUENCY_160M = 1, +}; + +enum class SelfCfgType { + TYPE_OF_GET_SELF_CONFIG = 1, + TYPE_OF_GET_SELF_CONFIG_WITH_PASSWORD = 2 +}; + +enum class PeerCfgType { + TYPE_OF_SET_PEER_CONFIG = 1, + TYPE_OF_SET_PEER_STATE_CHANGE = 2 +}; + +enum class PreferBandwidth { + /** default */ + BW_DEFAULT, + /** indicates the ultimate bandwidth, corresponding to 160 Mbit/s or 320 Mbit/s in the future. */ + BW_EXTRAM, + /** high throughput. The default value is 80 Mbit/s. */ + BW_HIGH_PERF, + /** low-latency service type, 40 Mbit/s/80 Mbit/s, + * which needs to be determined based on the current channel status. */ + BW_LOW_LATENCY +}; + +enum class RecommendStatus { + RS_SUCCESS, + RS_LOCAL_ADJUST, + RS_REMOTE_ADJUST, + RS_FAILURE +}; + +#define CFG_CALLBACK_BYTE 4 + +enum class CfgType { + CFG_INVALID = -1, + GET_SELF_CONFIG = 1, +}; + +class Hid2dConnectConfig { +public: + Hid2dConnectConfig() : m_ssid(""), m_bssid(""), m_preSharedKey(""), + m_frequency(-1), m_dhcpMode(DhcpMode::CONNECT_MODE_INVALID) { + } + ~Hid2dConnectConfig() { + } + + void SetSsid(const std::string& ssid); + std::string GetSsid() const; + void SetBssid(const std::string& bssid); + std::string GetBssid() const; + void SetPreSharedKey(const std::string& preSharedKey); + std::string GetPreSharedKey() const; + void SetFrequency(const int frequency); + int GetFrequency() const; + void SetDhcpMode(const DhcpMode dhcpMode); + DhcpMode GetDhcpMode() const; + +private: + std::string m_ssid; + std::string m_bssid; + std::string m_preSharedKey; + int m_frequency; + DhcpMode m_dhcpMode; +}; + +class IpAddrInfo { +public: + std::string ip; + std::string gateway; + std::string netmask; +}; + +class RecommendChannelRequest { +public: + RecommendChannelRequest() : remoteIfName(""), remoteIfMode(-1), localIfName(""), + localIfMode(-1), prefBand(0), prefBandwidth(PreferBandwidth::BW_DEFAULT) { + } + + ~RecommendChannelRequest() { + } + + /** the interface name of the remote device */ + std::string remoteIfName; + /** the mode of the interface on the remote device */ + int remoteIfMode; + /** interface name of the local device */ + std::string localIfName; + /** the mode of the interface on the local device */ + int localIfMode; + /** preferred frequency band */ + int prefBand; + /** preferred bandwidth type (enumerated) */ + PreferBandwidth prefBandwidth; +}; + +class RecommendChannelResponse { +public: + RecommendChannelResponse() : status(RecommendStatus::RS_FAILURE), index(-1), + centerFreq(0), centerFreq1(0), centerFreq2(0), bandwidth(0) { + } + ~RecommendChannelResponse() { + } + + /** 0: success; 1: local adjustment; 2: remote adjustment; –1: failure */ + RecommendStatus status; + /* -1 fails. 0-N corresponds to the input array subscript (that is, the interface to be connected) */ + int index; + /* optional 20 Mbit/s bandwidth */ + int centerFreq; + /* optional frequency one */ + int centerFreq1; + /* optional frequency two */ + int centerFreq2; + /* band width */ + int bandwidth; +}; + +class Hid2dUpperScene { +public: + /* The mac address of the device */ + std::string mac; + /* The scene of upper layer, hexadecimal digit, currently bit 0-2 is valid, 0: video, 1: audio, 2: file */ + unsigned int scene; + /* Frame rate, -1/30/60 is valid */ + int fps; + /* band width, valid only in video scenes, the default value is 0 */ + unsigned int bw; +}; +} // namespace Wifi +} // namespace OHOS +#endif diff --git a/interfaces/innerkits/native_cpp/wifi_standard/interfaces/wifi_msg.h b/wifi/frameworks/native/interfaces/wifi_msg.h old mode 100755 new mode 100644 similarity index 70% rename from interfaces/innerkits/native_cpp/wifi_standard/interfaces/wifi_msg.h rename to wifi/frameworks/native/interfaces/wifi_msg.h index e2dbde2e7e22fab5e54c9b8b118e35215b2cc2a8..53f494e40cad0d4b19994b752ba42498e8e42ba5 --- a/interfaces/innerkits/native_cpp/wifi_standard/interfaces/wifi_msg.h +++ b/wifi/frameworks/native/interfaces/wifi_msg.h @@ -1,5 +1,5 @@ /* - * Copyright (C) 2021 Huawei Device Co., Ltd. + * Copyright (C) 2021-2022 Huawei Device Co., Ltd. * 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 @@ -17,24 +17,33 @@ #include #include +#include #include #include #include #include #include #include "ip_tools.h" -#include "wifi_ap_msg.h" -#include "wifi_scan_msg.h" -#include "wifi_p2p_msg.h" namespace OHOS { namespace Wifi { #define WIFI_COUNTRY_CODE_LEN 2 #define WEPKEYS_SIZE 4 #define INVALID_NETWORK_ID (-1) +#define WIFI_INVALID_UID (-1) #define IPV4_ADDRESS_TYPE 0 #define IPV6_ADDRESS_TYPE 1 -#define DEVICE_NAME_LENGTH 32 + +const std::string KEY_MGMT_NONE = "NONE"; +const std::string KEY_MGMT_WEP = "WEP"; +const std::string KEY_MGMT_WPA_PSK = "WPA-PSK"; +const std::string KEY_MGMT_SAE = "SAE"; +const std::string KEY_MGMT_EAP = "WPA-EAP"; + +const std::string EAP_METHOD_TLS = "TLS"; +const std::string EAP_METHOD_TTLS = "TTLS"; +const std::string EAP_METHOD_SIM = "SIM"; +const std::string EAP_METHOD_PEAP = "PEAP"; enum class SupplicantState { DISCONNECTED = 0, @@ -68,21 +77,38 @@ enum class DetailedState { SCANNING = 12, SUSPENDED = 13, VERIFYING_POOR_LINK = 14, - + PASSWORD_ERROR = 15, + CONNECTION_REJECT = 16, + CONNECTION_FULL = 17, + CONNECTION_TIMEOUT = 18, + OBTAINING_IPADDR_FAIL = 19, INVALID = 0xFF, }; -enum class ConnState { - IDLE, +enum ConnState { + /** The device is searching for an available AP. */ SCANNING, + + /** The Wi-Fi connection is being set up. */ CONNECTING, + + /** The Wi-Fi connection is being authenticated. */ AUTHENTICATING, + + /** The IP address of the Wi-Fi connection is being obtained. */ OBTAINING_IPADDR, + + /** The Wi-Fi connection has been set up. */ CONNECTED, - SUSPENDED, + + /** The Wi-Fi connection is being torn down. */ DISCONNECTING, + + /** The Wi-Fi connection has been torn down. */ DISCONNECTED, - FAILED + + /** Failed to set up the Wi-Fi connection. */ + UNKNOWN }; struct WifiLinkedInfo { @@ -94,13 +120,16 @@ struct WifiLinkedInfo { int frequency; int linkSpeed; /* units: Mbps */ std::string macAddress; + int macType; unsigned int ipAddress; ConnState connState; bool ifHiddenSSID; - std::string rxLinkSpeed; /* Downstream network speed */ - std::string txLinkSpeed; /* Upstream network speed */ + int rxLinkSpeed; /* Downstream network speed */ + int txLinkSpeed; /* Upstream network speed */ int chload; int snr; /* Signal-to-Noise Ratio */ + int isDataRestricted; + std::string portalUrl; SupplicantState supplicantState; /* wpa_supplicant state */ DetailedState detailedState; /* connection state */ @@ -112,10 +141,11 @@ struct WifiLinkedInfo { frequency = 0; linkSpeed = 0; ipAddress = 0; - connState = ConnState::FAILED; + connState = ConnState::UNKNOWN; ifHiddenSSID = false; chload = 0; snr = 0; + isDataRestricted = 0; supplicantState = SupplicantState::INVALID; detailedState = DetailedState::INVALID; } @@ -143,16 +173,19 @@ struct WpsConfig { }; enum class WifiDeviceConfigStatus { - INVALID = -1, /* invalid */ - CURRENT = 0, /* using */ - DISABLED = 1, /* disabled */ - ENABLED = 2, /* enable */ - + ENABLED, /* enable */ + DISABLED, /* disabled */ UNKNOWN }; enum class AssignIpMethod { DHCP, STATIC, UNASSIGNED }; +enum class ConfigChange { + CONFIG_ADD = 0, + CONFIG_UPDATE = 1, + CONFIG_REMOVE = 2, +}; + class WifiIpAddress { public: int family; /* ip type */ @@ -175,8 +208,10 @@ public: void SetIpv4Address(const std::string &address) { - family = IPV4_ADDRESS_TYPE; addressIpv4 = IpTools::ConvertIpv4Address(address); + if (addressIpv4 != 0) { + family = IPV4_ADDRESS_TYPE; + } return; } @@ -187,8 +222,10 @@ public: void SetIpv6Address(const std::string &address) { - family = IPV6_ADDRESS_TYPE; IpTools::ConvertIpv6Address(address, addressIpv6); + if (addressIpv6.size() != 0) { + family = IPV6_ADDRESS_TYPE; + } return; } }; @@ -243,11 +280,33 @@ public: {} }; +enum class Phase2Method { NONE, PAP, MSCHAP, MSCHAPV2, GTC, SIM, AKA, AKA_PRIME }; + class WifiEapConfig { public: std::string eap; /* EAP mode Encryption Mode: PEAP/TLS/TTLS/PWD/SIM/AKA/AKA */ std::string identity; /* EAP mode identity */ std::string password; /* EAP mode password */ + std::string clientCert; /* EAP mode client certificate */ + std::string privateKey; /* EAP mode client private key */ + Phase2Method phase2Method; + + /** + * @Description convert Phase2Method to string + * + * @param eap - eap method + * @param method - phase2method + * @return string + */ + static std::string Phase2MethodToStr(const std::string& eap, const int& method); + + /** + * @Description convert string to Phase2Method + * + * @param str - phase2method string + * @return Phase2Method + */ + static Phase2Method Phase2MethodFromStr(const std::string& str); }; enum class ConfigureProxyMethod { AUTOCONFIGUE, MANUALCONFIGUE, CLOSED }; @@ -334,6 +393,10 @@ struct WifiDeviceConfig { bool hiddenSSID; /* Random mac address */ std::string macAddress; + int uid; + time_t lastConnectTime; + int numRebootsSinceLastUse; + int numAssociation; WifiIpConfig wifiIpConfig; WifiEapConfig wifiEapConfig; WifiProxyConfig wifiProxyconfig; @@ -342,7 +405,7 @@ struct WifiDeviceConfig { WifiDeviceConfig() { networkId = INVALID_NETWORK_ID; - status = static_cast(WifiDeviceConfigStatus::INVALID); + status = static_cast(WifiDeviceConfigStatus::DISABLED); band = 0; channel = 0; frequency = 0; @@ -354,30 +417,15 @@ struct WifiDeviceConfig { hiddenSSID = false; wifiPrivacySetting = WifiPrivacyConfig::RANDOMMAC; rssi = -100; + uid = WIFI_INVALID_UID; + lastConnectTime = -1; + numRebootsSinceLastUse = 0; + numAssociation = 0; } }; enum class WifiState { DISABLING = 0, DISABLED = 1, ENABLING = 2, ENABLED = 3, UNKNOWN = 4 }; -enum class ConnectionState { - CONNECT_CONNECTING = 0, - CONNECT_AP_CONNECTED = 1, - CONNECT_CHECK_PORTAL = 2, - CONNECT_NETWORK_ENABLED = 3, - CONNECT_NETWORK_DISABLED = 4, - DISCONNECT_DISCONNECTING = 5, - DISCONNECT_DISCONNECT_FAILED = 6, - DISCONNECT_DISCONNECTED = 7, - CONNECT_PASSWORD_WRONG = 8, - CONNECT_CONNECTING_TIMEOUT = 9, - CONNECT_OBTAINING_IP = 10, - CONNECT_OBTAINING_IP_FAILED = 11, - CONNECT_ASSOCIATING = 12, - CONNECT_ASSOCIATED = 13, - - UNKNOWN, -}; - /* wps state */ enum class WpsStartState { START_PBC_SUCCEED = 0, @@ -393,6 +441,10 @@ enum class WpsStartState { START_PBC_FAILED_OVERLAP = 10, START_WPS_FAILED = 11, WPS_TIME_OUT = 12, + START_AP_PIN_SUCCEED = 13, + START_AP_PIN_FAILED = 14, + STOP_AP_PIN_SUCCEED = 15, + STOP_AP_PIN_FAILED = 16, }; enum class StreamDirection { @@ -401,15 +453,30 @@ enum class StreamDirection { UNKNOWN, }; +/* WifiProtectType */ +enum class WifiProtectType { + WIFI_PROTECT_MULTICAST = 0, + WIFI_PROTECT_COMMON = 1 +}; + +/* WifiProtectMode */ +enum class WifiProtectMode { + WIFI_PROTECT_FULL = 0, + WIFI_PROTECT_SCAN_ONLY = 1, + WIFI_PROTECT_FULL_HIGH_PERF = 2, + WIFI_PROTECT_FULL_LOW_LATENCY = 3, + WIFI_PROTECT_NO_HELD = 4 +}; + /* DHCP info */ struct IpInfo { - int ipAddress; /* ip address */ - int gateway; /* gate */ - int netmask; /* mask */ - int primaryDns; /* main dns */ - int secondDns; /* backup dns */ - int serverIp; /* DHCP server's address */ - int leaseDuration; + unsigned int ipAddress; /* ip address */ + unsigned int gateway; /* gate */ + unsigned int netmask; /* mask */ + unsigned int primaryDns; /* main dns */ + unsigned int secondDns; /* backup dns */ + unsigned int serverIp; /* DHCP server's address */ + unsigned int leaseDuration; IpInfo() { @@ -424,4 +491,4 @@ struct IpInfo { }; } // namespace Wifi } // namespace OHOS -#endif \ No newline at end of file +#endif diff --git a/interfaces/innerkits/native_cpp/wifi_standard/interfaces/wifi_p2p_msg.h b/wifi/frameworks/native/interfaces/wifi_p2p_msg.h similarity index 88% rename from interfaces/innerkits/native_cpp/wifi_standard/interfaces/wifi_p2p_msg.h rename to wifi/frameworks/native/interfaces/wifi_p2p_msg.h index 4f6d9d9c90e30b650448c452dde66f02a62549cc..357d493c2830728e23411d6194245800c78fe1d5 100644 --- a/interfaces/innerkits/native_cpp/wifi_standard/interfaces/wifi_p2p_msg.h +++ b/wifi/frameworks/native/interfaces/wifi_p2p_msg.h @@ -1,5 +1,5 @@ /* - * Copyright (C) 2021 Huawei Device Co., Ltd. + * Copyright (C) 2021-2022 Huawei Device Co., Ltd. * 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 @@ -12,6 +12,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + #ifndef OHOS_WIFI_P2P_MSG_H #define OHOS_WIFI_P2P_MSG_H @@ -22,6 +23,10 @@ namespace OHOS { namespace Wifi { +constexpr int WIFI_STR_MAC_LENGTH = 17; +constexpr int MAX_PASSPHRASE_LENGTH = 127; +constexpr int DEVICE_NAME_LENGTH = 32; + enum class P2pGroupStatus { GS_CREATING, GS_CREATED, GS_STARTED, GS_REMOVING, GS_INVALID }; enum class P2pServiceStatus : unsigned char { PSRS_SUCCESS, @@ -48,12 +53,14 @@ enum class P2pActionCallback : unsigned char { RequestService, StartP2pListen, StopP2pListen, - FormGroup, + CreateGroup, RemoveGroup, DeleteGroup, P2pConnect, - P2pDisConnect, + P2pCancelConnect, P2pSetDeviceName, + CreateHid2dGroup, + Hid2dConnect, UNKNOWN }; @@ -124,6 +131,7 @@ enum class P2pGroupCapability { }; enum class GroupOwnerBand { GO_BAND_AUTO, GO_BAND_2GHZ, GO_BAND_5GHZ }; + const int MAX_WFD_SUBELEMS = 12; const char DeviceInfoSubelemLenHex[] = {"0006"}; class WifiP2pWfdInfo { @@ -158,6 +166,7 @@ class WifiP2pDevice { public: WifiP2pDevice() : deviceName(""), + networkName(""), mDeviceAddress(""), primaryDeviceType(""), secondaryDeviceType(""), @@ -170,6 +179,8 @@ public: {} void SetDeviceName(const std::string &setDeviceName); const std::string &GetDeviceName() const; + void SetNetworkName(const std::string &name); + const std::string &GetNetworkName() const; void SetDeviceAddress(const std::string &deviceAddress); const std::string &GetDeviceAddress() const; void SetPrimaryDeviceType(const std::string &setPrimaryDeviceType); @@ -196,10 +207,10 @@ public: bool WpsPbcSupported() const; bool WpsDisplaySupported() const; bool WpKeypadSupported() const; - bool isGroupOwner() const; private: std::string deviceName; /* the value range is 0 to 32 characters. */ + std::string networkName; /* oper_ssid of peer device */ std::string mDeviceAddress; /* the device MAC address, the length is 17 characters. */ std::string primaryDeviceType; std::string secondaryDeviceType; @@ -220,7 +231,8 @@ public: networkId(INVALID_NET_ID), frequency(0), isP2pPersistent(0), - groupStatus(P2pGroupStatus::GS_INVALID) + groupStatus(P2pGroupStatus::GS_INVALID), + explicitGroup(false) {} ~WifiP2pGroupInfo() {} @@ -253,6 +265,8 @@ public: const std::vector &GetClientDevices() const; void SetClientDevices(const std::vector &devices); void ClearClientDevices(); + bool IsExplicitGroup(void) const; + void SetExplicitGroup(bool isExplicit); private: WifiP2pDevice owner; @@ -266,6 +280,7 @@ private: P2pGroupStatus groupStatus; std::vector clientDevices; std::string goIpAddress; + bool explicitGroup; }; class WpsInfo { @@ -287,8 +302,10 @@ private: std::string bssid; /* the length is 17 characters. */ std::string pin; /* the length is 4 or 8 characters. */ }; -const int MAX_GROUP_OWNER_INTENT = 15; -const int MIN_GROUP_OWNER_INTENT = 0; + +const int AUTO_GROUP_OWNER_VALUE = -1; +const int MIN_GROUP_OWNER_VALUE = 0; +const int MAX_GROUP_OWNER_VALUE = 15; class WifiP2pConfig { public: WifiP2pConfig() @@ -296,11 +313,17 @@ public: goBand(GroupOwnerBand::GO_BAND_AUTO), netId(-1), passphrase(""), - groupOwnerIntent(-1), - networkName("") - { - wpsInfo.SetWpsMethod(WpsMethod::WPS_METHOD_PBC); - } + groupOwnerIntent(AUTO_GROUP_OWNER_VALUE), + groupName("") + {} + WifiP2pConfig(const WifiP2pConfig &config) + : mDeviceAddress(config.GetDeviceAddress()), + goBand(config.GetGoBand()), + netId(config.GetNetId()), + passphrase(config.GetPassphrase()), + groupOwnerIntent(config.GetGroupOwnerIntent()), + groupName(config.GetGroupName()) + {} ~WifiP2pConfig() {} void SetDeviceAddress(const std::string &deviceAddress); @@ -311,28 +334,50 @@ public: int GetNetId() const; void SetPassphrase(const std::string &newPassphrase); const std::string &GetPassphrase() const; - void SetWpsInfo(const WpsInfo &info); - const WpsInfo &GetWpsInfo() const; void SetGroupOwnerIntent(int intent); int GetGroupOwnerIntent() const; - void SetNetworkName(const std::string &setNetworkName); - const std::string &GetNetworkName() const; + void SetGroupName(const std::string &setGroupName); + const std::string &GetGroupName() const; private: std::string mDeviceAddress; /* the device MAC address, the length is 17 characters. */ GroupOwnerBand goBand; int netId; /* network id, when -2 means persistent and -1 means temporary, else need >= 0 */ std::string passphrase; /* the value ranges from 8 to 63. */ - WpsInfo wpsInfo; int groupOwnerIntent; /* the value is -1.(A value of -1 indicates the system can choose an appropriate value.) */ - std::string networkName; /* the value ranges from 1 to 32. */ + std::string groupName; /* the value ranges from 1 to 32. */ +}; + +class WifiP2pConfigInternal : public WifiP2pConfig { +public: + WifiP2pConfigInternal(): WifiP2pConfig() + { + wpsInfo.SetWpsMethod(WpsMethod::WPS_METHOD_INVALID); + } + WifiP2pConfigInternal(WifiP2pConfig config): WifiP2pConfig(config) + { + wpsInfo.SetWpsMethod(WpsMethod::WPS_METHOD_INVALID); + } + ~WifiP2pConfigInternal() + {} + inline void SetWpsInfo(const WpsInfo &info) + { + wpsInfo = info; + } + inline const WpsInfo &GetWpsInfo() const + { + return wpsInfo; + } + +private: + WpsInfo wpsInfo; }; -class WifiP2pInfo { +class WifiP2pLinkedInfo { public: - WifiP2pInfo() : connectState(P2pConnectedState::P2P_DISCONNECTED), isP2pGroupOwner(false) + WifiP2pLinkedInfo() : connectState(P2pConnectedState::P2P_DISCONNECTED), isP2pGroupOwner(false) {} - ~WifiP2pInfo() + ~WifiP2pLinkedInfo() {} void SetConnectState(P2pConnectedState setConnectState); P2pConnectedState GetConnectState() const; diff --git a/interfaces/innerkits/native_cpp/wifi_standard/interfaces/wifi_scan_msg.h b/wifi/frameworks/native/interfaces/wifi_scan_msg.h old mode 100755 new mode 100644 similarity index 87% rename from interfaces/innerkits/native_cpp/wifi_standard/interfaces/wifi_scan_msg.h rename to wifi/frameworks/native/interfaces/wifi_scan_msg.h index 61244ce296033d5fe748b131df084a5d54a3f438..11b42b2341eb64323162885c99dffdda81973e7e --- a/interfaces/innerkits/native_cpp/wifi_standard/interfaces/wifi_scan_msg.h +++ b/wifi/frameworks/native/interfaces/wifi_scan_msg.h @@ -26,18 +26,23 @@ namespace OHOS { namespace Wifi { #define MIN_SCAN_INTERVAL 20 #define DEFAULT_MAX_SCAN_INTERVAL 160 -#define SCAN_SCENE_SCREEN_OFF 0 -#define SCAN_SCENE_SCANNING 1 -#define SCAN_SCENE_CONNECTING 2 -#define SCAN_SCENE_DISCONNCTED 3 -#define SCAN_SCENE_CONNECTED 4 -#define SCAN_SCENE_ASSOCIATING 5 -#define SCAN_SCENE_ASSOCIATED 6 -#define SCAN_SCENE_OBTAINING_IP 7 -#define SCAN_SCENE_DEEP_SLEEP 8 -/* 8~253 Custom Scenario */ +#define SCAN_SCENE_SCREEN_OFF 0 // Screen off state +#define SCAN_SCENE_SCANNING 1 // scanning state +#define SCAN_SCENE_CONNECTING 2 // connecting state +#define SCAN_SCENE_DISCONNCTED 3 // disconnected state +#define SCAN_SCENE_CONNECTED 4 // connected state +#define SCAN_SCENE_ASSOCIATING 5 // associating state +#define SCAN_SCENE_ASSOCIATED 6 // associated state +#define SCAN_SCENE_OBTAINING_IP 7 // Obtaining IP state +#define SCAN_SCENE_DEEP_SLEEP 8 // Deep sleep state +#define SCAN_SCENE_FREQUENCY_ORIGIN 9 // Scan frequency, origin. +#define SCAN_SCENE_FREQUENCY_CUSTOM 10 // Scan frequency, custom. +#define SCAN_SCENE_CUSTOM (SCAN_SCENE_FREQUENCY_CUSTOM + 1) + +/* SCAN_SCENE_CUSTOM~253 Custom Scenario */ #define SCAN_SCENE_ALL 254 /* all Scenario */ #define SCAN_SCENE_MAX 255 /* invalid value */ + /* Scanning mode of the control policy */ enum class ScanMode { APP_FOREGROUND_SCAN = 0, /* Scan initiated by the foreground application */ @@ -87,8 +92,8 @@ struct WifiInfoElem { }; enum class ScanHandleNotify { - SCAN_OK = 0, - SCAN_FAIL, + SCAN_FAIL = 0, + SCAN_OK = 1, }; struct WifiScanParams { @@ -141,6 +146,7 @@ struct WifiScanInfo { }; typedef struct tagScanForbidMode { + int scanScene; /* current scanned scene */ int forbidTime; /* * Specifies the scanning duration. * If the value is 0, all invalid values are restricted. @@ -156,6 +162,9 @@ typedef struct tagScanForbidMode { forbidCount = 0; scanMode = ScanMode::SCAN_MODE_MAX; } + + ~tagScanForbidMode() + {} } ScanForbidMode; enum class IntervalMode { @@ -214,11 +223,11 @@ typedef struct tagScanIntervalMode { } } ScanIntervalMode; -typedef std::map> ScanForbidMap; +typedef std::vector ScanForbidList; typedef std::vector ScanIntervalList; typedef struct tagScanControlInfo { - ScanForbidMap scanForbidMap; /* Scanning forbidden list corresponding to the scenario */ + ScanForbidList scanForbidList; /* Scanning forbidden list corresponding to the scenario */ ScanIntervalList scanIntervalList; /* * Interval for scanning mode. * The value cannot be set to 2.4 GHz, 5 GHz, or anytime scan. diff --git a/interfaces/innerkits/native_cpp/wifi_standard/src/wifi_device.cpp b/wifi/frameworks/native/src/wifi_device.cpp similarity index 100% rename from interfaces/innerkits/native_cpp/wifi_standard/src/wifi_device.cpp rename to wifi/frameworks/native/src/wifi_device.cpp diff --git a/interfaces/innerkits/native_cpp/wifi_standard/src/wifi_device_callback_stub.cpp b/wifi/frameworks/native/src/wifi_device_callback_stub.cpp similarity index 74% rename from interfaces/innerkits/native_cpp/wifi_standard/src/wifi_device_callback_stub.cpp rename to wifi/frameworks/native/src/wifi_device_callback_stub.cpp index 8927eb0cb8dba6aafff55c5eb4d848d7d6c59e29..bc08d175d7e2f44454df739f2a8a667c788c2fb0 100644 --- a/interfaces/innerkits/native_cpp/wifi_standard/src/wifi_device_callback_stub.cpp +++ b/wifi/frameworks/native/src/wifi_device_callback_stub.cpp @@ -1,5 +1,5 @@ /* - * Copyright (C) 2021 Huawei Device Co., Ltd. + * Copyright (C) 2021-2022 Huawei Device Co., Ltd. * 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 @@ -13,10 +13,11 @@ * limitations under the License. */ #include "wifi_device_callback_stub.h" +#include "define.h" +#include "wifi_hisysevent.h" #include "wifi_logger.h" #include "wifi_msg.h" #include "wifi_errcode.h" -#include "define.h" DEFINE_WIFILOG_LABEL("WifiDeviceCallBackStub"); namespace OHOS { @@ -30,11 +31,17 @@ WifiDeviceCallBackStub::~WifiDeviceCallBackStub() int WifiDeviceCallBackStub::OnRemoteRequest( uint32_t code, MessageParcel &data, MessageParcel &reply, MessageOption &option) { - WIFI_LOGD("WifiDeviceCallBackStub::OnRemoteRequest!"); + WIFI_LOGI("WifiDeviceCallBackStub::OnRemoteRequest, code:%{public}u!", code); if (mRemoteDied) { - WIFI_LOGD("Failed to `%{public}s`,Remote service is died!", __func__); + WIFI_LOGE("Failed to `%{public}s`,Remote service is died!", __func__); return -1; } + + if (data.ReadInterfaceToken() != GetDescriptor()) { + WIFI_LOGE("Sta callback stub token verification error: %{public}d", code); + return WIFI_OPT_FAILED; + } + int exception = data.ReadInt32(); if (exception) { WIFI_LOGE("WifiDeviceCallBackStub::OnRemoteRequest, got exception: %{public}d!", exception); @@ -62,6 +69,10 @@ int WifiDeviceCallBackStub::OnRemoteRequest( ret = RemoteOnStreamChanged(code, data, reply); break; } + case WIFI_CBK_CMD_DEVICE_CONFIG_CHANGE: { + ret = RemoteOnDeviceConfigChanged(code, data, reply); + break; + } default: { ret = IPCObjectStub::OnRemoteRequest(code, data, reply, option); break; @@ -73,7 +84,8 @@ int WifiDeviceCallBackStub::OnRemoteRequest( void WifiDeviceCallBackStub::RegisterUserCallBack(const sptr &callBack) { if (callBack == nullptr) { - WIFI_LOGD("RegisterUserCallBack:callBack is nullptr!"); + WIFI_LOGE("RegisterUserCallBack:callBack is nullptr!"); + return; } callback_ = callBack; } @@ -90,32 +102,35 @@ void WifiDeviceCallBackStub::SetRemoteDied(bool val) void WifiDeviceCallBackStub::OnWifiStateChanged(int state) { - WIFI_LOGD("WifiDeviceCallBackStub::OnWifiStateChanged"); + WIFI_LOGI("WifiDeviceCallBackStub::OnWifiStateChanged, state:%{public}d!", state); if (callback_) { callback_->OnWifiStateChanged(state); } + WriteWifiEventReceivedHiSysEvent(HISYS_STA_POWER_STATE_CHANGE, state); } void WifiDeviceCallBackStub::OnWifiConnectionChanged(int state, const WifiLinkedInfo &info) { - WIFI_LOGD("WifiDeviceCallBackStub::OnWifiConnectionChanged"); + WIFI_LOGI("WifiDeviceCallBackStub::OnWifiConnectionChanged, state:%{public}d!", state); if (callback_) { callback_->OnWifiConnectionChanged(state, info); } + WriteWifiEventReceivedHiSysEvent(HISYS_STA_CONN_STATE_CHANGE, state); } void WifiDeviceCallBackStub::OnWifiRssiChanged(int rssi) { - WIFI_LOGD("WifiDeviceCallBackStub::OnWifiRssiChanged"); + WIFI_LOGI("WifiDeviceCallBackStub::OnWifiRssiChanged, rssi:%{public}d!", rssi); if (callback_) { callback_->OnWifiRssiChanged(rssi); } + WriteWifiEventReceivedHiSysEvent(HISYS_STA_RSSI_STATE_CHANGE, rssi); } void WifiDeviceCallBackStub::OnWifiWpsStateChanged(int state, const std::string &pinCode) { - WIFI_LOGD("WifiDeviceCallBackStub::OnWifiWpsStateChanged"); + WIFI_LOGI("WifiDeviceCallBackStub::OnWifiWpsStateChanged, state:%{public}d!", state); if (callback_) { callback_->OnWifiWpsStateChanged(state, pinCode); } @@ -123,12 +138,20 @@ void WifiDeviceCallBackStub::OnWifiWpsStateChanged(int state, const std::string void WifiDeviceCallBackStub::OnStreamChanged(int direction) { - WIFI_LOGD("WifiDeviceCallBackStub::OnStreamChanged"); + WIFI_LOGI("WifiDeviceCallBackStub::OnStreamChanged, direction:%{public}d!", direction); if (callback_) { callback_->OnStreamChanged(direction); } } +void WifiDeviceCallBackStub::OnDeviceConfigChanged(ConfigChange value) +{ + WIFI_LOGI("WifiDeviceCallBackStub::OnDeviceConfigChanged, value:%{public}d!", value); + if (callback_) { + callback_->OnDeviceConfigChanged(value); + } +} + int WifiDeviceCallBackStub::RemoteOnWifiStateChanged(uint32_t code, MessageParcel &data, MessageParcel &reply) { WIFI_LOGD("run %{public}s code %{public}u, datasize %{public}zu", __func__, code, data.GetRawDataSize()); @@ -153,16 +176,18 @@ int WifiDeviceCallBackStub::RemoteOnWifiConnectionChanged(uint32_t code, Message info.macAddress = data.ReadCString(); info.ipAddress = data.ReadInt32(); int tmpConnState = data.ReadInt32(); - if (tmpConnState >= 0 && tmpConnState <= int(ConnState::FAILED)) { + if (tmpConnState >= 0 && tmpConnState <= int(ConnState::UNKNOWN)) { info.connState = ConnState(tmpConnState); } else { - info.connState = ConnState::FAILED; + info.connState = ConnState::UNKNOWN; } info.ifHiddenSSID = data.ReadBool(); - info.rxLinkSpeed = data.ReadCString(); - info.txLinkSpeed = data.ReadCString(); + info.rxLinkSpeed = data.ReadInt32(); + info.txLinkSpeed = data.ReadInt32(); info.chload = data.ReadInt32(); info.snr = data.ReadInt32(); + info.isDataRestricted = data.ReadInt32(); + info.portalUrl = data.ReadCString(); int tmpState = data.ReadInt32(); if (tmpState >= 0 && tmpState <= int(SupplicantState::INVALID)) { info.supplicantState = SupplicantState(tmpState); @@ -208,5 +233,14 @@ int WifiDeviceCallBackStub::RemoteOnStreamChanged(uint32_t code, MessageParcel & reply.WriteInt32(0); /* Reply 0 to indicate that no exception occurs. */ return 0; } + +int WifiDeviceCallBackStub::RemoteOnDeviceConfigChanged(uint32_t code, MessageParcel &data, MessageParcel &reply) +{ + WIFI_LOGD("run %{public}s code %{public}u, datasize %{public}zu", __func__, code, data.GetRawDataSize()); + int value = data.ReadInt32(); + OnDeviceConfigChanged(ConfigChange(value)); + reply.WriteInt32(0); /* Reply 0 to indicate that no exception occurs. */ + return 0; +} } // namespace Wifi } // namespace OHOS \ No newline at end of file diff --git a/interfaces/innerkits/native_cpp/wifi_standard/src/wifi_device_callback_stub.h b/wifi/frameworks/native/src/wifi_device_callback_stub.h similarity index 93% rename from interfaces/innerkits/native_cpp/wifi_standard/src/wifi_device_callback_stub.h rename to wifi/frameworks/native/src/wifi_device_callback_stub.h index aa89a49858eac5216c29ccf19bac3b2f532b030e..7af7aa74bf217057446ad9611afc3c93abdf19b1 100644 --- a/interfaces/innerkits/native_cpp/wifi_standard/src/wifi_device_callback_stub.h +++ b/wifi/frameworks/native/src/wifi_device_callback_stub.h @@ -35,6 +35,7 @@ public: void OnWifiRssiChanged(int rssi) override; void OnWifiWpsStateChanged(int state, const std::string &pinCode) override; void OnStreamChanged(int direction) override; + void OnDeviceConfigChanged(ConfigChange value) override; void RegisterUserCallBack(const sptr &callBack); bool IsRemoteDied() const; void SetRemoteDied(bool val); @@ -45,6 +46,7 @@ private: int RemoteOnWifiRssiChanged(uint32_t code, MessageParcel &data, MessageParcel &reply); int RemoteOnWifiWpsStateChanged(uint32_t code, MessageParcel &data, MessageParcel &reply); int RemoteOnStreamChanged(uint32_t code, MessageParcel &data, MessageParcel &reply); + int RemoteOnDeviceConfigChanged(uint32_t code, MessageParcel &data, MessageParcel &reply); sptr callback_; diff --git a/wifi/frameworks/native/src/wifi_device_callback_stub_lite.cpp b/wifi/frameworks/native/src/wifi_device_callback_stub_lite.cpp new file mode 100644 index 0000000000000000000000000000000000000000..bf38b83c267460b58e00edc6b3becb074bdd0681 --- /dev/null +++ b/wifi/frameworks/native/src/wifi_device_callback_stub_lite.cpp @@ -0,0 +1,242 @@ +/* + * Copyright (C) 2022 Huawei Device Co., Ltd. + * 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 "wifi_device_callback_stub_lite.h" +#include "define.h" +#include "wifi_logger.h" +#include "wifi_msg.h" +#include "wifi_errcode.h" + +DEFINE_WIFILOG_LABEL("WifiDeviceCallBackStub"); +namespace OHOS { +namespace Wifi { +WifiDeviceCallBackStub::WifiDeviceCallBackStub() : callback_(nullptr), mRemoteDied(false) +{} + +WifiDeviceCallBackStub::~WifiDeviceCallBackStub() +{} + +int WifiDeviceCallBackStub::OnRemoteRequest(uint32_t code, IpcIo *data) +{ + int ret = WIFI_OPT_FAILED; + WIFI_LOGD("OnRemoteRequest code:%{public}u!", code); + if (mRemoteDied || data == nullptr) { + WIFI_LOGE("Failed to %{public}s,mRemoteDied:%{public}d data:%{public}d!", + __func__, mRemoteDied, data == nullptr); + return ret; + } + + int exception = WIFI_OPT_FAILED; + (void)ReadInt32(data, &exception); + if (exception) { + WIFI_LOGE("WifiDeviceCallBackStub::OnRemoteRequest, got exception: %{public}d!", exception); + return ret; + } + switch (code) { + case WIFI_CBK_CMD_STATE_CHANGE: { + ret = RemoteOnWifiStateChanged(code, data); + break; + } + case WIFI_CBK_CMD_CONNECTION_CHANGE: { + ret = RemoteOnWifiConnectionChanged(code, data); + break; + } + case WIFI_CBK_CMD_RSSI_CHANGE: { + ret = RemoteOnWifiRssiChanged(code, data); + break; + } + case WIFI_CBK_CMD_WPS_STATE_CHANGE: { + ret = RemoteOnWifiWpsStateChanged(code, data); + break; + } + case WIFI_CBK_CMD_STREAM_DIRECTION: { + ret = RemoteOnStreamChanged(code, data); + break; + } + case WIFI_CBK_CMD_DEVICE_CONFIG_CHANGE: { + ret = RemoteOnDeviceConfigChanged(code, data); + break; + } + default: { + ret = WIFI_OPT_FAILED; + } + } + return ret; +} + +void WifiDeviceCallBackStub::RegisterUserCallBack(const std::shared_ptr &callBack) +{ + if (callBack == nullptr) { + WIFI_LOGE("RegisterUserCallBack:callBack is nullptr!"); + return; + } + callback_ = callBack; +} + +bool WifiDeviceCallBackStub::IsRemoteDied() const +{ + return mRemoteDied; +} + +void WifiDeviceCallBackStub::SetRemoteDied(bool val) +{ + mRemoteDied = val; +} + +void WifiDeviceCallBackStub::OnWifiStateChanged(int state) +{ + WIFI_LOGD("WifiDeviceCallBackStub::OnWifiStateChanged"); + + if (callback_) { + callback_->OnWifiStateChanged(state); + } +} + +void WifiDeviceCallBackStub::OnWifiConnectionChanged(int state, const WifiLinkedInfo &info) +{ + WIFI_LOGD("WifiDeviceCallBackStub::OnWifiConnectionChanged"); + if (callback_) { + callback_->OnWifiConnectionChanged(state, info); + } +} + +void WifiDeviceCallBackStub::OnWifiRssiChanged(int rssi) +{ + WIFI_LOGD("WifiDeviceCallBackStub::OnWifiRssiChanged"); + if (callback_) { + callback_->OnWifiRssiChanged(rssi); + } +} + +void WifiDeviceCallBackStub::OnWifiWpsStateChanged(int state, const std::string &pinCode) +{ + WIFI_LOGD("WifiDeviceCallBackStub::OnWifiWpsStateChanged"); + if (callback_) { + callback_->OnWifiWpsStateChanged(state, pinCode); + } +} + +void WifiDeviceCallBackStub::OnStreamChanged(int direction) +{ + WIFI_LOGD("WifiDeviceCallBackStub::OnStreamChanged"); + if (callback_) { + callback_->OnStreamChanged(direction); + } +} + +void WifiDeviceCallBackStub::OnDeviceConfigChanged(ConfigChange state) +{ + WIFI_LOGD("WifiDeviceCallBackStub::OnDeviceConfigChanged"); + if (callback_) { + callback_->OnDeviceConfigChanged(state); + } +} + +int WifiDeviceCallBackStub::RemoteOnWifiStateChanged(uint32_t code, IpcIo *data) +{ + WIFI_LOGD("run %{public}s code %{public}u", __func__, code); + int state = 0; + (void)ReadInt32(data, &state); + OnWifiStateChanged(state); + return 0; +} + +int WifiDeviceCallBackStub::RemoteOnWifiConnectionChanged(uint32_t code, IpcIo *data) +{ + WIFI_LOGD("run %{public}s code %{public}u", __func__, code); + size_t readLen; + int state = 0; + (void)ReadInt32(data, &state); + WifiLinkedInfo info; + (void)ReadInt32(data, &info.networkId); + info.ssid = (char *)ReadString(data, &readLen); + info.bssid = (char *)ReadString(data, &readLen); + (void)ReadInt32(data, &info.rssi); + (void)ReadInt32(data, &info.band); + (void)ReadInt32(data, &info.frequency); + (void)ReadInt32(data, &info.linkSpeed); + info.macAddress = (char *)ReadString(data, &readLen); + (void)ReadUint32(data, &info.ipAddress); + int tmpConnState = 0; + (void)ReadInt32(data, &tmpConnState); + if (tmpConnState >= 0 && tmpConnState <= int(ConnState::UNKNOWN)) { + info.connState = ConnState(tmpConnState); + } else { + info.connState = ConnState::UNKNOWN; + } + (void)ReadBool(data, &info.ifHiddenSSID); + (void)ReadInt32(data, &info.rxLinkSpeed); + (void)ReadInt32(data, &info.txLinkSpeed); + (void)ReadInt32(data, &info.chload); + (void)ReadInt32(data, &info.snr); + (void)ReadInt32(data, &info.isDataRestricted); + info.portalUrl = (char *)ReadString(data, &readLen); + int tmpState = 0; + (void)ReadInt32(data, &tmpState); + if (tmpState >= 0 && tmpState <= int(SupplicantState::INVALID)) { + info.supplicantState = SupplicantState(tmpState); + } else { + info.supplicantState = SupplicantState::INVALID; + } + + int tmpDetailState = 0; + (void)ReadInt32(data, &tmpDetailState); + if (tmpDetailState >= 0 && tmpDetailState <= int(DetailedState::INVALID)) { + info.detailedState = DetailedState(tmpDetailState); + } else { + info.detailedState = DetailedState::INVALID; + } + OnWifiConnectionChanged(state, info); + return 0; +} + +int WifiDeviceCallBackStub::RemoteOnWifiRssiChanged(uint32_t code, IpcIo *data) +{ + WIFI_LOGD("run %{public}s code %{public}u", __func__, code); + int rssi = 0; + (void)ReadInt32(data, &rssi); + OnWifiRssiChanged(rssi); + return 0; +} + +int WifiDeviceCallBackStub::RemoteOnWifiWpsStateChanged(uint32_t code, IpcIo *data) +{ + WIFI_LOGD("run %{public}s code %{public}u", __func__, code); + size_t readLen; + int state = 0; + (void)ReadInt32(data, &state); + std::string pinCode = (char *)ReadString(data, &readLen); + OnWifiWpsStateChanged(state, pinCode); + return 0; +} + +int WifiDeviceCallBackStub::RemoteOnStreamChanged(uint32_t code, IpcIo *data) +{ + WIFI_LOGD("run %{public}s code %{public}u", __func__, code); + int direction = 0; + (void)ReadInt32(data, &direction); + OnStreamChanged(direction); + return 0; +} + +int WifiDeviceCallBackStub::RemoteOnDeviceConfigChanged(uint32_t code, IpcIo *data) +{ + WIFI_LOGD("run %{public}s code %{public}u", __func__, code); + int state = 0; + (void)ReadInt32(data, &state); + OnDeviceConfigChanged(ConfigChange(state)); + return 0; +} +} // namespace Wifi +} // namespace OHOS diff --git a/wifi/frameworks/native/src/wifi_device_callback_stub_lite.h b/wifi/frameworks/native/src/wifi_device_callback_stub_lite.h new file mode 100644 index 0000000000000000000000000000000000000000..406175fa1e1d284fc62e8f3fc3d01f0f05eec287 --- /dev/null +++ b/wifi/frameworks/native/src/wifi_device_callback_stub_lite.h @@ -0,0 +1,54 @@ +/* + * Copyright (C) 2022 Huawei Device Co., Ltd. + * 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 OHOS_WIFI_DEVICE_CALLBACK_STUB_LITE_H +#define OHOS_WIFI_DEVICE_CALLBACK_STUB_LITE_H + +#include "serializer.h" +#include "i_wifi_device_callback.h" + +namespace OHOS { +namespace Wifi { +class WifiDeviceCallBackStub : public IWifiDeviceCallBack { +public: + WifiDeviceCallBackStub(); + virtual ~WifiDeviceCallBackStub(); + + int OnRemoteRequest(uint32_t code, IpcIo *data); + + void OnWifiStateChanged(int state) override; + void OnWifiConnectionChanged(int state, const WifiLinkedInfo &info) override; + void OnWifiRssiChanged(int rssi) override; + void OnWifiWpsStateChanged(int state, const std::string &pinCode) override; + void OnStreamChanged(int direction) override; + void OnDeviceConfigChanged(ConfigChange state) override; + void RegisterUserCallBack(const std::shared_ptr &callBack); + bool IsRemoteDied() const; + void SetRemoteDied(bool val); + +private: + int RemoteOnWifiStateChanged(uint32_t code, IpcIo *data); + int RemoteOnWifiConnectionChanged(uint32_t code, IpcIo *data); + int RemoteOnWifiRssiChanged(uint32_t code, IpcIo *data); + int RemoteOnWifiWpsStateChanged(uint32_t code, IpcIo *data); + int RemoteOnStreamChanged(uint32_t code, IpcIo *data); + int RemoteOnDeviceConfigChanged(uint32_t code, IpcIo *data); + + std::shared_ptr callback_; + + bool mRemoteDied; +}; +} // namespace Wifi +} // namespace OHOS +#endif diff --git a/interfaces/innerkits/native_cpp/wifi_standard/src/wifi_device_impl.cpp b/wifi/frameworks/native/src/wifi_device_impl.cpp similarity index 68% rename from interfaces/innerkits/native_cpp/wifi_standard/src/wifi_device_impl.cpp rename to wifi/frameworks/native/src/wifi_device_impl.cpp index 856507b94339ebe08a7f40f7f89260d5b5ef23c2..e8aa1beb92cbb14c75fc268b4c1acb5fd7e883c5 100644 --- a/interfaces/innerkits/native_cpp/wifi_standard/src/wifi_device_impl.cpp +++ b/wifi/frameworks/native/src/wifi_device_impl.cpp @@ -1,5 +1,5 @@ /* - * Copyright (C) 2021 Huawei Device Co., Ltd. + * Copyright (C) 2021-2022 Huawei Device Co., Ltd. * 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 @@ -12,8 +12,15 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + #include "wifi_device_impl.h" +#include +#ifndef OHOS_ARCH_LITE +#include "iremote_broker.h" +#include "iremote_object.h" #include "iservice_registry.h" +#endif +#include "wifi_device_proxy.h" #include "wifi_logger.h" DEFINE_WIFILOG_LABEL("WifiDeviceImpl"); @@ -28,14 +35,31 @@ namespace Wifi { } \ } while (0) -WifiDeviceImpl::WifiDeviceImpl(int systemAbilityId) : systemAbilityId_(systemAbilityId) +WifiDeviceImpl::WifiDeviceImpl(int systemAbilityId) : systemAbilityId_(systemAbilityId), client_(nullptr) {} WifiDeviceImpl::~WifiDeviceImpl() -{} +{ +#ifdef OHOS_ARCH_LITE + WifiDeviceProxy::ReleaseInstance(); +#endif +} bool WifiDeviceImpl::Init() { +#ifdef OHOS_ARCH_LITE + WifiDeviceProxy *deviceProxy = WifiDeviceProxy::GetInstance(); + if (deviceProxy == nullptr) { + WIFI_LOGE("get wifi device proxy failed."); + return false; + } + if (deviceProxy->Init() != WIFI_OPT_SUCCESS) { + WIFI_LOGE("wifi device proxy init failed."); + WifiDeviceProxy::ReleaseInstance(); + return false; + } + client_ = deviceProxy; +#else sptr sa_mgr = SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager(); if (sa_mgr == nullptr) { WIFI_LOGE("failed to get SystemAbilityManager"); @@ -52,12 +76,11 @@ bool WifiDeviceImpl::Init() if (client_ == nullptr) { client_ = new (std::nothrow) WifiDeviceProxy(object); } - if (client_ == nullptr) { WIFI_LOGE("wifi device init failed. %{public}d", systemAbilityId_); return false; } - +#endif return true; } @@ -73,10 +96,46 @@ ErrCode WifiDeviceImpl::DisableWifi() return client_->DisableWifi(); } -ErrCode WifiDeviceImpl::AddDeviceConfig(const WifiDeviceConfig &config, int &result) +ErrCode WifiDeviceImpl::InitWifiProtect(const WifiProtectType &protectType, const std::string &protectName) +{ + RETURN_IF_FAIL(client_); + return client_->InitWifiProtect(protectType, protectName); +} + +ErrCode WifiDeviceImpl::GetWifiProtectRef(const WifiProtectMode &protectMode, const std::string &protectName) +{ + RETURN_IF_FAIL(client_); + return client_->GetWifiProtectRef(protectMode, protectName); +} + +ErrCode WifiDeviceImpl::PutWifiProtectRef(const std::string &protectName) +{ + RETURN_IF_FAIL(client_); + return client_->PutWifiProtectRef(protectName); +} + +ErrCode WifiDeviceImpl::RemoveCandidateConfig(int networkId) +{ + RETURN_IF_FAIL(client_); + return client_->RemoveCandidateConfig(networkId); +} + +ErrCode WifiDeviceImpl::RemoveCandidateConfig(const WifiDeviceConfig &config) { RETURN_IF_FAIL(client_); - return client_->AddDeviceConfig(config, result); + return client_->RemoveCandidateConfig(config); +} + +ErrCode WifiDeviceImpl::AddDeviceConfig(const WifiDeviceConfig &config, int &result, bool isCandidate) +{ + RETURN_IF_FAIL(client_); + return client_->AddDeviceConfig(config, result, isCandidate); +} + +ErrCode WifiDeviceImpl::UpdateDeviceConfig(const WifiDeviceConfig &config, int &result) +{ + RETURN_IF_FAIL(client_); + return client_->UpdateDeviceConfig(config, result); } ErrCode WifiDeviceImpl::RemoveDevice(int networkId) @@ -91,10 +150,10 @@ ErrCode WifiDeviceImpl::RemoveAllDevice() return client_->RemoveAllDevice(); } -ErrCode WifiDeviceImpl::GetDeviceConfigs(std::vector &result) +ErrCode WifiDeviceImpl::GetDeviceConfigs(std::vector &result, bool isCandidate) { RETURN_IF_FAIL(client_); - return client_->GetDeviceConfigs(result); + return client_->GetDeviceConfigs(result, isCandidate); } ErrCode WifiDeviceImpl::EnableDeviceConfig(int networkId, bool attemptEnable) @@ -109,10 +168,10 @@ ErrCode WifiDeviceImpl::DisableDeviceConfig(int networkId) return client_->DisableDeviceConfig(networkId); } -ErrCode WifiDeviceImpl::ConnectToNetwork(int networkId) +ErrCode WifiDeviceImpl::ConnectToNetwork(int networkId, bool isCandidate) { RETURN_IF_FAIL(client_); - return client_->ConnectToNetwork(networkId); + return client_->ConnectToNetwork(networkId, isCandidate); } ErrCode WifiDeviceImpl::ConnectToDevice(const WifiDeviceConfig &config) @@ -121,6 +180,12 @@ ErrCode WifiDeviceImpl::ConnectToDevice(const WifiDeviceConfig &config) return client_->ConnectToDevice(config); } +bool WifiDeviceImpl::IsConnected() +{ + RETURN_IF_FAIL(client_); + return client_->IsConnected(); +} + ErrCode WifiDeviceImpl::ReConnect() { RETURN_IF_FAIL(client_); @@ -193,7 +258,11 @@ ErrCode WifiDeviceImpl::GetSignalLevel(const int &rssi, const int &band, int &le return client_->GetSignalLevel(rssi, band, level); } +#ifdef OHOS_ARCH_LITE +ErrCode WifiDeviceImpl::RegisterCallBack(const std::shared_ptr &callback) +#else ErrCode WifiDeviceImpl::RegisterCallBack(const sptr &callback) +#endif { RETURN_IF_FAIL(client_); return client_->RegisterCallBack(callback); @@ -220,5 +289,11 @@ ErrCode WifiDeviceImpl::GetDeviceMacAddress(std::string &result) RETURN_IF_FAIL(client_); return client_->GetDeviceMacAddress(result); } + +bool WifiDeviceImpl::SetLowLatencyMode(bool enabled) +{ + RETURN_IF_FAIL(client_); + return client_->SetLowLatencyMode(enabled); +} } // namespace Wifi -} // namespace OHOS \ No newline at end of file +} // namespace OHOS diff --git a/interfaces/innerkits/native_cpp/wifi_standard/src/wifi_device_impl.h b/wifi/frameworks/native/src/wifi_device_impl.h similarity index 67% rename from interfaces/innerkits/native_cpp/wifi_standard/src/wifi_device_impl.h rename to wifi/frameworks/native/src/wifi_device_impl.h index aa2576611854a2d2996318e31cbac58692824de9..546fd314cd1b496d9400c888c023982b83a411c8 100644 --- a/interfaces/innerkits/native_cpp/wifi_standard/src/wifi_device_impl.h +++ b/wifi/frameworks/native/src/wifi_device_impl.h @@ -1,5 +1,5 @@ /* - * Copyright (C) 2021 Huawei Device Co., Ltd. + * Copyright (C) 2021-2022 Huawei Device Co., Ltd. * 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 @@ -15,8 +15,14 @@ #ifndef OHOS_WIFI_DEVICE_IMPL_H #define OHOS_WIFI_DEVICE_IMPL_H +#include +#include +#include "i_wifi_device.h" +#include "i_wifi_device_callback.h" +#include "refbase.h" #include "wifi_device.h" -#include "wifi_device_proxy.h" +#include "wifi_errcode.h" +#include "wifi_msg.h" namespace OHOS { namespace Wifi { @@ -41,14 +47,66 @@ public: */ ErrCode DisableWifi() override; + /** + * @Description create the Wi-Fi protect. + * + * @param protectType - WifiProtectMode object + * @param protectName - the protect name + * @return ErrCode - operation result + */ + ErrCode InitWifiProtect(const WifiProtectType &protectType, const std::string &protectName) override; + + /** + * @Description Acquire the Wi-Fi protect mode. + * + * @param protectMode - WifiProtectMode object + * @param protectName - the protect name + * @return ErrCode - operation result + */ + ErrCode GetWifiProtectRef(const WifiProtectMode &protectMode, const std::string &protectName) override; + + /** + * @Description Release the Wi-Fi protect mode. + * + * @param protectName - the protect name + * @return ErrCode - operation result + */ + ErrCode PutWifiProtectRef(const std::string &protectName) override; + + /** + * @Description Remove the wifi candidate device config equals to input network id + * + * @param networkId - the candidate device network id + * @return ErrCode - operation result + */ + virtual ErrCode RemoveCandidateConfig(int networkId) override; + + /** + * @Description Remove a specified candidate hotspot configuration. + * + * @param config - WifiDeviceConfig object + * @return ErrCode - operation result + */ + virtual ErrCode RemoveCandidateConfig(const WifiDeviceConfig &config) override; + /** * @Description Add a wifi device configuration. * * @param config - WifiDeviceConfig object * @param result - the device configuration's network id + * @param isCandidate - Whether is candidate + * @return ErrCode - operation result + */ + ErrCode AddDeviceConfig(const WifiDeviceConfig &config, int &result, bool isCandidate) override; + + /** + * @Description Update a wifi device configuration. + * + * @param config - WifiDeviceConfig object + * @param result - the device configuration's network id after updated * @return ErrCode - operation result */ - ErrCode AddDeviceConfig(const WifiDeviceConfig &config, int &result) override; + ErrCode UpdateDeviceConfig(const WifiDeviceConfig &config, int &result) override; /** * @Description Remove the wifi device config equals to input network id @@ -69,17 +127,19 @@ public: * @Description Get all the device configs * * @param result - Get result vector of WifiDeviceConfig + * @param isCandidate - Whether is candidate * @return ErrCode - operation result */ - ErrCode GetDeviceConfigs(std::vector &result) override; + ErrCode GetDeviceConfigs(std::vector &result, bool isCandidate) override; /** * @Description Connecting to a Specified Network * * @param networkId - network id + * @param isCandidate - Whether is candidate * @return ErrCode - operation result */ - ErrCode ConnectToNetwork(int networkId) override; + ErrCode ConnectToNetwork(int networkId, bool isCandidate) override; /** * @Description Connect To a network base WifiDeviceConfig object @@ -89,6 +149,13 @@ public: */ ErrCode ConnectToDevice(const WifiDeviceConfig &config) override; + /** + * @Description Check whether Wi-Fi is connected. + * + * @return bool - true: connected, false: not connected + */ + bool IsConnected() override; + /** * @Description Disconnect * @@ -142,7 +209,11 @@ public: * @param callback - IWifiDeviceCallBack object * @return ErrCode - operation result */ +#ifdef OHOS_ARCH_LITE + ErrCode RegisterCallBack(const std::shared_ptr &callback) override; +#else ErrCode RegisterCallBack(const sptr &callback) override; +#endif /** * @Description Get the Signal Level object @@ -178,7 +249,7 @@ public: * @param attemptEnable - if set true, disable other device config * @return ErrCode - operation result */ - ErrCode EnableDeviceConfig(int networkId, bool attemptEnable); + ErrCode EnableDeviceConfig(int networkId, bool attemptEnable) override; /** * @Description Disable Wi-Fi device configuration. @@ -186,7 +257,7 @@ public: * @param networkId - device config's network id * @return ErrCode - operation result */ - ErrCode DisableDeviceConfig(int networkId); + ErrCode DisableDeviceConfig(int networkId) override; /** * @Description Obtaining ip Request Information @@ -194,21 +265,21 @@ public: * @param info - IpInfo object * @return ErrCode - operation result */ - ErrCode GetIpInfo(IpInfo &info); + ErrCode GetIpInfo(IpInfo &info) override; /** * @Description Reconnect to the currently active network * * @return ErrCode - operation result */ - ErrCode ReConnect(); + ErrCode ReConnect() override; /** * @Description ReAssociate network * * @return ErrCode - operation result */ - ErrCode ReAssociate(void); + ErrCode ReAssociate() override; /** * @Description Enable WPS connection @@ -233,10 +304,22 @@ public: */ ErrCode GetDeviceMacAddress(std::string &result) override; + /** + * @Description set low latency mode + * + * @param enabled - true: enable low latency, false: disable low latency + * @return bool - operation result + */ + bool SetLowLatencyMode(bool enabled) override; + private: int systemAbilityId_; +#ifdef OHOS_ARCH_LITE + IWifiDevice *client_; +#else sptr client_; +#endif }; } // namespace Wifi } // namespace OHOS -#endif \ No newline at end of file +#endif diff --git a/interfaces/innerkits/native_cpp/wifi_standard/src/wifi_device_proxy.cpp b/wifi/frameworks/native/src/wifi_device_proxy.cpp similarity index 61% rename from interfaces/innerkits/native_cpp/wifi_standard/src/wifi_device_proxy.cpp rename to wifi/frameworks/native/src/wifi_device_proxy.cpp index 32ecac118bba710cdc24b44f73f6417d6f0317a4..2ea1e3fde32ba4bd3b2f1db82a157f26f95de15b 100644 --- a/interfaces/innerkits/native_cpp/wifi_standard/src/wifi_device_proxy.cpp +++ b/wifi/frameworks/native/src/wifi_device_proxy.cpp @@ -1,5 +1,5 @@ /* - * Copyright (C) 2021 Huawei Device Co., Ltd. + * Copyright (C) 2021-2022 Huawei Device Co., Ltd. * 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 @@ -12,16 +12,21 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + #include "wifi_device_proxy.h" +#include "define.h" +#include "wifi_common_util.h" #include "wifi_device_callback_stub.h" +#include "wifi_hisysevent.h" #include "wifi_logger.h" -#include "define.h" DEFINE_WIFILOG_LABEL("WifiDeviceProxy"); namespace OHOS { namespace Wifi { -static WifiDeviceCallBackStub* g_deviceCallBackStub = new WifiDeviceCallBackStub; +static sptr g_deviceCallBackStub = + sptr(new (std::nothrow) WifiDeviceCallBackStub()); + WifiDeviceProxy::WifiDeviceProxy(const sptr &impl) : IRemoteProxy(impl), mRemoteDied(false) { if (impl) { @@ -39,14 +44,17 @@ WifiDeviceProxy::~WifiDeviceProxy() ErrCode WifiDeviceProxy::EnableWifi() { if (mRemoteDied) { - WIFI_LOGD("failed to `%{public}s`,remote service is died!", __func__); + WIFI_LOGE("failed to `%{public}s`,remote service is died!", __func__); return WIFI_OPT_FAILED; } MessageOption option; MessageParcel data; MessageParcel reply; + if (!data.WriteInterfaceToken(GetDescriptor())) { + WIFI_LOGE("Write interface token error: %{public}s", __func__); + return WIFI_OPT_FAILED; + } data.WriteInt32(0); - int error = Remote()->SendRequest(WIFI_SVR_CMD_ENABLE_WIFI, data, reply, option); if (error != ERR_NONE) { WIFI_LOGE("Set Attr(%{public}d) failed,error code is %{public}d", WIFI_SVR_CMD_ENABLE_WIFI, error); @@ -57,19 +65,23 @@ ErrCode WifiDeviceProxy::EnableWifi() if (exception) { return WIFI_OPT_FAILED; } + WriteWifiStateHiSysEvent(HISYS_SERVICE_TYPE_STA, WifiOperType::ENABLE); return ErrCode(reply.ReadInt32()); } ErrCode WifiDeviceProxy::DisableWifi() { if (mRemoteDied) { - WIFI_LOGD("failed to `%{public}s`,remote service is died!", __func__); + WIFI_LOGE("failed to `%{public}s`,remote service is died!", __func__); return WIFI_OPT_FAILED; } MessageOption option; MessageParcel data, reply; + if (!data.WriteInterfaceToken(GetDescriptor())) { + WIFI_LOGE("Write interface token error: %{public}s", __func__); + return WIFI_OPT_FAILED; + } data.WriteInt32(0); - int error = Remote()->SendRequest(WIFI_SVR_CMD_DISABLE_WIFI, data, reply, option); if (error != ERR_NONE) { WIFI_LOGE("Set Attr(%{public}d) failed,error code is %{public}d", WIFI_SVR_CMD_DISABLE_WIFI, error); @@ -79,9 +91,105 @@ ErrCode WifiDeviceProxy::DisableWifi() if (exception) { return WIFI_OPT_FAILED; } + WriteWifiStateHiSysEvent(HISYS_SERVICE_TYPE_STA, WifiOperType::DISABLE); return ErrCode(reply.ReadInt32()); } +ErrCode WifiDeviceProxy::InitWifiProtect(const WifiProtectType &protectType, const std::string &protectName) +{ + if (mRemoteDied) { + WIFI_LOGE("failed to `%{public}s`,remote service is died!", __func__); + return WIFI_OPT_FAILED; + } + MessageOption option; + MessageParcel data, reply; + if (!data.WriteInterfaceToken(GetDescriptor())) { + WIFI_LOGE("Write interface token error: %{public}s", __func__); + return WIFI_OPT_FAILED; + } + data.WriteInt32(0); + data.WriteInt32((int)protectType); + data.WriteCString(protectName.c_str()); + int error = Remote()->SendRequest(WIFI_SVR_CMD_INIT_WIFI_PROTECT, data, reply, option); + if (error != ERR_NONE) { + WIFI_LOGE("Set Attr(%{public}d) failed,error code is %{public}d", WIFI_SVR_CMD_INIT_WIFI_PROTECT, error); + return ErrCode(error); + } + int exception = reply.ReadInt32(); + if (exception) { + return WIFI_OPT_FAILED; + } + int ret = reply.ReadInt32(); + if (ret != WIFI_OPT_SUCCESS) { + return ErrCode(ret); + } + + return WIFI_OPT_SUCCESS; +} + +ErrCode WifiDeviceProxy::GetWifiProtectRef(const WifiProtectMode &protectMode, const std::string &protectName) +{ + if (mRemoteDied) { + WIFI_LOGE("failed to `%{public}s`,remote service is died!", __func__); + return WIFI_OPT_FAILED; + } + MessageOption option; + MessageParcel data, reply; + if (!data.WriteInterfaceToken(GetDescriptor())) { + WIFI_LOGE("Write interface token error: %{public}s", __func__); + return WIFI_OPT_FAILED; + } + data.WriteInt32(0); + data.WriteInt32((int)protectMode); + data.WriteCString(protectName.c_str()); + int error = Remote()->SendRequest(WIFI_SVR_CMD_GET_WIFI_PROTECT, data, reply, option); + if (error != ERR_NONE) { + WIFI_LOGE("Set Attr(%{public}d) failed,error code is %{public}d", WIFI_SVR_CMD_GET_WIFI_PROTECT, error); + return ErrCode(error); + } + int exception = reply.ReadInt32(); + if (exception) { + return WIFI_OPT_FAILED; + } + int ret = reply.ReadInt32(); + if (ret != WIFI_OPT_SUCCESS) { + return ErrCode(ret); + } + + return WIFI_OPT_SUCCESS; +} + +ErrCode WifiDeviceProxy::PutWifiProtectRef(const std::string &protectName) +{ + if (mRemoteDied) { + WIFI_LOGE("failed to `%{public}s`,remote service is died!", __func__); + return WIFI_OPT_FAILED; + } + MessageOption option; + MessageParcel data, reply; + if (!data.WriteInterfaceToken(GetDescriptor())) { + WIFI_LOGE("Write interface token error: %{public}s", __func__); + return WIFI_OPT_FAILED; + } + data.WriteInt32(0); + data.WriteCString(protectName.c_str()); + int error = Remote()->SendRequest(WIFI_SVR_CMD_PUT_WIFI_PROTECT, data, reply, option); + if (error != ERR_NONE) { + WIFI_LOGE("Set Attr(%{public}d) failed,error code is %{public}d", WIFI_SVR_CMD_PUT_WIFI_PROTECT, error); + return ErrCode(error); + } + int exception = reply.ReadInt32(); + if (exception) { + return WIFI_OPT_FAILED; + } + int ret = reply.ReadInt32(); + if (ret != WIFI_OPT_SUCCESS) { + return ErrCode(ret); + } + + return WIFI_OPT_SUCCESS; +} + void WifiDeviceProxy::WriteIpAddress(MessageParcel &data, const WifiIpAddress &address) { data.WriteInt32(address.family); @@ -126,6 +234,9 @@ void WifiDeviceProxy::WriteDeviceConfig(const WifiDeviceConfig &config, MessageP data.WriteCString(config.wifiEapConfig.eap.c_str()); data.WriteCString(config.wifiEapConfig.identity.c_str()); data.WriteCString(config.wifiEapConfig.password.c_str()); + data.WriteCString(config.wifiEapConfig.clientCert.c_str()); + data.WriteCString(config.wifiEapConfig.privateKey.c_str()); + data.WriteInt32(static_cast(config.wifiEapConfig.phase2Method)); data.WriteInt32((int)config.wifiProxyconfig.configureMethod); data.WriteCString(config.wifiProxyconfig.autoProxyConfig.pacWebAddress.c_str()); data.WriteCString(config.wifiProxyconfig.manualProxyConfig.serverHostName.c_str()); @@ -134,17 +245,83 @@ void WifiDeviceProxy::WriteDeviceConfig(const WifiDeviceConfig &config, MessageP data.WriteInt32((int)config.wifiPrivacySetting); } -ErrCode WifiDeviceProxy::AddDeviceConfig(const WifiDeviceConfig &config, int &result) +ErrCode WifiDeviceProxy::RemoveCandidateConfig(const WifiDeviceConfig &config) { if (mRemoteDied) { - WIFI_LOGD("failed to `%{public}s`,remote service is died!", __func__); + WIFI_LOGE("failed to `%{public}s`,remote service is died!", __func__); return WIFI_OPT_FAILED; } MessageOption option; MessageParcel data, reply; + if (!data.WriteInterfaceToken(GetDescriptor())) { + WIFI_LOGE("Write interface token error: %{public}s", __func__); + return WIFI_OPT_FAILED; + } data.WriteInt32(0); + /* Write a flag: 1-remove config by networkId, 2-remove config by WifiDeviceConfig */ + data.WriteInt32(2); WriteDeviceConfig(config, data); + int error = Remote()->SendRequest(WIFI_SVR_CMD_REMOVE_CANDIDATE_CONFIG, data, reply, option); + if (error != ERR_NONE) { + WIFI_LOGE("Set Attr(%{public}d) failed,error=%{public}d", WIFI_SVR_CMD_REMOVE_CANDIDATE_CONFIG, error); + return WIFI_OPT_FAILED; + } + int exception = reply.ReadInt32(); + if (exception) { + return WIFI_OPT_FAILED; + } + int ret = reply.ReadInt32(); + if (ret != WIFI_OPT_SUCCESS) { + return ErrCode(ret); + } + + return WIFI_OPT_SUCCESS; +} + +ErrCode WifiDeviceProxy::RemoveCandidateConfig(int networkId) +{ + if (mRemoteDied) { + WIFI_LOGE("failed to `%{public}s`,remote service is died!", __func__); + return WIFI_OPT_FAILED; + } + MessageOption option; + MessageParcel data, reply; + if (!data.WriteInterfaceToken(GetDescriptor())) { + WIFI_LOGE("Write interface token error: %{public}s", __func__); + return WIFI_OPT_FAILED; + } + data.WriteInt32(0); + /* Write a flag: 1-remove config by networkId, 2-remove config by WifiDeviceConfig */ + data.WriteInt32(1); + data.WriteInt32(networkId); + int error = Remote()->SendRequest(WIFI_SVR_CMD_REMOVE_CANDIDATE_CONFIG, data, reply, option); + if (error != ERR_NONE) { + WIFI_LOGE("Set Attr(%{public}d) failed,error=%{public}d", WIFI_SVR_CMD_REMOVE_CANDIDATE_CONFIG, error); + return WIFI_OPT_FAILED; + } + int exception = reply.ReadInt32(); + if (exception) { + return WIFI_OPT_FAILED; + } + return ErrCode(reply.ReadInt32()); +} +ErrCode WifiDeviceProxy::AddDeviceConfig(const WifiDeviceConfig &config, int &result, bool isCandidate) +{ + if (mRemoteDied) { + WIFI_LOGE("failed to `%{public}s`,remote service is died!", __func__); + return WIFI_OPT_FAILED; + } + MessageOption option; + MessageParcel data, reply; + if (!data.WriteInterfaceToken(GetDescriptor())) { + WIFI_LOGE("Write interface token error: %{public}s", __func__); + return WIFI_OPT_FAILED; + } + data.WriteInt32(0); + /* true-candidate config, false-normal config */ + data.WriteBool(isCandidate); + WriteDeviceConfig(config, data); int error = Remote()->SendRequest(WIFI_SVR_CMD_ADD_DEVICE_CONFIG, data, reply, option); if (error != ERR_NONE) { WIFI_LOGE("Set Attr(%{public}d) failed,error code is %{public}d", WIFI_SVR_CMD_ADD_DEVICE_CONFIG, error); @@ -163,17 +340,52 @@ ErrCode WifiDeviceProxy::AddDeviceConfig(const WifiDeviceConfig &config, int &re return WIFI_OPT_SUCCESS; } +ErrCode WifiDeviceProxy::UpdateDeviceConfig(const WifiDeviceConfig &config, int &result) +{ + if (mRemoteDied) { + WIFI_LOGE("failed to `%{public}s`,remote service is died!", __func__); + return WIFI_OPT_FAILED; + } + + MessageOption option; + MessageParcel data, reply; + if (!data.WriteInterfaceToken(GetDescriptor())) { + WIFI_LOGE("Write interface token error: %{public}s", __func__); + return WIFI_OPT_FAILED; + } + data.WriteInt32(0); + WriteDeviceConfig(config, data); + int error = Remote()->SendRequest(WIFI_SVR_CMD_UPDATE_DEVICE_CONFIG, data, reply, option); + if (error != ERR_NONE) { + WIFI_LOGE("Set Attr(%{public}d) failed,error code is %{public}d", WIFI_SVR_CMD_UPDATE_DEVICE_CONFIG, error); + return WIFI_OPT_FAILED; + } + int exception = reply.ReadInt32(); + if (exception) { + return WIFI_OPT_FAILED; + } + int ret = reply.ReadInt32(); + if (ret != WIFI_OPT_SUCCESS) { + return ErrCode(ret); + } + result = reply.ReadInt32(); + return WIFI_OPT_SUCCESS; +} + ErrCode WifiDeviceProxy::RemoveDevice(int networkId) { if (mRemoteDied) { - WIFI_LOGD("failed to `%{public}s`,remote service is died!", __func__); + WIFI_LOGE("failed to `%{public}s`,remote service is died!", __func__); return WIFI_OPT_FAILED; } MessageOption option; MessageParcel data, reply; + if (!data.WriteInterfaceToken(GetDescriptor())) { + WIFI_LOGE("Write interface token error: %{public}s", __func__); + return WIFI_OPT_FAILED; + } data.WriteInt32(0); data.WriteInt32(networkId); - int error = Remote()->SendRequest(WIFI_SVR_CMD_REMOVE_DEVICE_CONFIG, data, reply, option); if (error != ERR_NONE) { WIFI_LOGE("Set Attr(%{public}d) failed,error code is %{public}d", WIFI_SVR_CMD_REMOVE_DEVICE_CONFIG, error); @@ -189,14 +401,17 @@ ErrCode WifiDeviceProxy::RemoveDevice(int networkId) ErrCode WifiDeviceProxy::RemoveAllDevice() { if (mRemoteDied) { - WIFI_LOGD("failed to `%{public}s`,remote service is died!", __func__); + WIFI_LOGE("failed to `%{public}s`,remote service is died!", __func__); return WIFI_OPT_FAILED; } MessageOption option; MessageParcel data; MessageParcel reply; + if (!data.WriteInterfaceToken(GetDescriptor())) { + WIFI_LOGE("Write interface token error: %{public}s", __func__); + return WIFI_OPT_FAILED; + } data.WriteInt32(0); - int error = Remote()->SendRequest(WIFI_SVR_CMD_REMOVE_ALL_DEVICE_CONFIG, data, reply, option); if (error != ERR_NONE) { WIFI_LOGE("Set Attr(%{public}d) failed,error code is %{public}d", WIFI_SVR_CMD_REMOVE_ALL_DEVICE_CONFIG, error); @@ -212,19 +427,28 @@ ErrCode WifiDeviceProxy::RemoveAllDevice() void WifiDeviceProxy::ReadIpAddress(MessageParcel &reply, WifiIpAddress &address) { + constexpr int MAX_SIZE = 256; address.family = reply.ReadInt32(); address.addressIpv4 = reply.ReadInt32(); int size = reply.ReadInt32(); + if (size > MAX_SIZE) { + WIFI_LOGE("Read IP address size error: %{public}d", size); + return; + } for (int i = 0; i < size; i++) { address.addressIpv6.push_back(reply.ReadInt8()); } - return; } void WifiDeviceProxy::ParseDeviceConfigs(MessageParcel &reply, std::vector &result) { + constexpr int MAX_DEVICE_CONFIG_SIZE = 1024; int retSize = reply.ReadInt32(); + if (retSize > MAX_DEVICE_CONFIG_SIZE) { + WIFI_LOGE("Parse device config size error: %{public}d", retSize); + return; + } for (int i = 0; i < retSize; ++i) { WifiDeviceConfig config; config.networkId = reply.ReadInt32(); @@ -257,28 +481,37 @@ void WifiDeviceProxy::ParseDeviceConfigs(MessageParcel &reply, std::vector &result) +ErrCode WifiDeviceProxy::GetDeviceConfigs(std::vector &result, bool isCandidate) { if (mRemoteDied) { - WIFI_LOGD("failed to `%{public}s`,remote service is died!", __func__); + WIFI_LOGE("failed to `%{public}s`,remote service is died!", __func__); return WIFI_OPT_FAILED; } MessageOption option; MessageParcel data; MessageParcel reply; + if (!data.WriteInterfaceToken(GetDescriptor())) { + WIFI_LOGE("Write interface token error: %{public}s", __func__); + return WIFI_OPT_FAILED; + } data.WriteInt32(0); - + /* true-candidate config, false-normal config */ + data.WriteBool(isCandidate); int error = Remote()->SendRequest(WIFI_SVR_CMD_GET_DEVICE_CONFIGS, data, reply, option); if (error != ERR_NONE) { WIFI_LOGE("Set Attr(%{public}d) failed,error code is %{public}d", WIFI_SVR_CMD_GET_DEVICE_CONFIGS, error); @@ -300,15 +533,18 @@ ErrCode WifiDeviceProxy::GetDeviceConfigs(std::vector &result) ErrCode WifiDeviceProxy::EnableDeviceConfig(int networkId, bool attemptEnable) { if (mRemoteDied) { - WIFI_LOGD("failed to `%{public}s`,remote service is died!", __func__); + WIFI_LOGE("failed to `%{public}s`,remote service is died!", __func__); return WIFI_OPT_FAILED; } MessageOption option; MessageParcel data, reply; + if (!data.WriteInterfaceToken(GetDescriptor())) { + WIFI_LOGE("Write interface token error: %{public}s", __func__); + return WIFI_OPT_FAILED; + } data.WriteInt32(0); data.WriteInt32(networkId); data.WriteInt32(attemptEnable); - int error = Remote()->SendRequest(WIFI_SVR_CMD_ENABLE_DEVICE, data, reply, option); if (error != ERR_NONE) { WIFI_LOGE("Set Attr(%{public}d) failed,error code is %{public}d", WIFI_SVR_CMD_ENABLE_DEVICE, error); @@ -324,14 +560,17 @@ ErrCode WifiDeviceProxy::EnableDeviceConfig(int networkId, bool attemptEnable) ErrCode WifiDeviceProxy::DisableDeviceConfig(int networkId) { if (mRemoteDied) { - WIFI_LOGD("failed to `%{public}s`,remote service is died!", __func__); + WIFI_LOGE("failed to `%{public}s`,remote service is died!", __func__); return WIFI_OPT_FAILED; } MessageOption option; MessageParcel data, reply; + if (!data.WriteInterfaceToken(GetDescriptor())) { + WIFI_LOGE("Write interface token error: %{public}s", __func__); + return WIFI_OPT_FAILED; + } data.WriteInt32(0); data.WriteInt32(networkId); - int error = Remote()->SendRequest(WIFI_SVR_CMD_DISABLE_DEVICE, data, reply, option); if (error != ERR_NONE) { WIFI_LOGE("Set Attr(%{public}d) failed,error code is %{public}d", WIFI_SVR_CMD_DISABLE_DEVICE, error); @@ -344,17 +583,22 @@ ErrCode WifiDeviceProxy::DisableDeviceConfig(int networkId) return ErrCode(reply.ReadInt32()); } -ErrCode WifiDeviceProxy::ConnectToNetwork(int networkId) +ErrCode WifiDeviceProxy::ConnectToNetwork(int networkId, bool isCandidate) { if (mRemoteDied) { - WIFI_LOGD("failed to `%{public}s`,remote service is died!", __func__); + WIFI_LOGE("failed to `%{public}s`,remote service is died!", __func__); return WIFI_OPT_FAILED; } MessageOption option; MessageParcel data, reply; + if (!data.WriteInterfaceToken(GetDescriptor())) { + WIFI_LOGE("Write interface token error: %{public}s", __func__); + return WIFI_OPT_FAILED; + } data.WriteInt32(0); + /* true-candidate config, false-normal config */ + data.WriteBool(isCandidate); data.WriteInt32(networkId); - int error = Remote()->SendRequest(WIFI_SVR_CMD_CONNECT_TO, data, reply, option); if (error != ERR_NONE) { WIFI_LOGE("Set Attr(%{public}d) failed,error code is %{public}d", WIFI_SVR_CMD_CONNECT_TO, error); @@ -364,20 +608,24 @@ ErrCode WifiDeviceProxy::ConnectToNetwork(int networkId) if (exception) { return WIFI_OPT_FAILED; } + WriteWifiConnectionHiSysEvent(WifiConnectionType::CONNECT, GetBundleName()); return ErrCode(reply.ReadInt32()); } ErrCode WifiDeviceProxy::ConnectToDevice(const WifiDeviceConfig &config) { if (mRemoteDied) { - WIFI_LOGD("failed to `%{public}s`,remote service is died!", __func__); + WIFI_LOGE("failed to `%{public}s`,remote service is died!", __func__); return WIFI_OPT_FAILED; } MessageOption option; MessageParcel data, reply; + if (!data.WriteInterfaceToken(GetDescriptor())) { + WIFI_LOGE("Write interface token error: %{public}s", __func__); + return WIFI_OPT_FAILED; + } data.WriteInt32(0); WriteDeviceConfig(config, data); - int error = Remote()->SendRequest(WIFI_SVR_CMD_CONNECT2_TO, data, reply, option); if (error != ERR_NONE) { WIFI_LOGE("Set Attr(%{public}d) failed,error code is %{public}d", WIFI_SVR_CMD_CONNECT2_TO, error); @@ -387,19 +635,48 @@ ErrCode WifiDeviceProxy::ConnectToDevice(const WifiDeviceConfig &config) if (exception) { return WIFI_OPT_FAILED; } + WriteWifiConnectionHiSysEvent(WifiConnectionType::CONNECT, GetBundleName()); return ErrCode(reply.ReadInt32()); } -ErrCode WifiDeviceProxy::ReConnect() +bool WifiDeviceProxy::IsConnected() { if (mRemoteDied) { - WIFI_LOGD("failed to `%{public}s`,remote service is died!", __func__); + WIFI_LOGE("failed to `%{public}s`,remote service is died!", __func__); return WIFI_OPT_FAILED; } MessageOption option; MessageParcel data, reply; + if (!data.WriteInterfaceToken(GetDescriptor())) { + WIFI_LOGE("Write interface token error: %{public}s", __func__); + return WIFI_OPT_FAILED; + } data.WriteInt32(0); + int error = Remote()->SendRequest(WIFI_SVR_CMD_IS_WIFI_CONNECTED, data, reply, option); + if (error != ERR_NONE) { + WIFI_LOGE("Set Attr(%{public}d) failed,error code is %{public}d", WIFI_SVR_CMD_IS_WIFI_CONNECTED, error); + return WIFI_OPT_FAILED; + } + int exception = reply.ReadInt32(); + if (exception) { + return false; + } + return reply.ReadBool(); +} +ErrCode WifiDeviceProxy::ReConnect() +{ + if (mRemoteDied) { + WIFI_LOGE("failed to `%{public}s`,remote service is died!", __func__); + return WIFI_OPT_FAILED; + } + MessageOption option; + MessageParcel data, reply; + if (!data.WriteInterfaceToken(GetDescriptor())) { + WIFI_LOGE("Write interface token error: %{public}s", __func__); + return WIFI_OPT_FAILED; + } + data.WriteInt32(0); int error = Remote()->SendRequest(WIFI_SVR_CMD_RECONNECT, data, reply, option); if (error != ERR_NONE) { WIFI_LOGE("Set Attr(%{public}d) failed,error code is %{public}d", WIFI_SVR_CMD_RECONNECT, error); @@ -409,19 +686,23 @@ ErrCode WifiDeviceProxy::ReConnect() if (exception) { return WIFI_OPT_FAILED; } + WriteWifiConnectionHiSysEvent(WifiConnectionType::CONNECT, GetBundleName()); return ErrCode(reply.ReadInt32()); } ErrCode WifiDeviceProxy::ReAssociate(void) { if (mRemoteDied) { - WIFI_LOGD("failed to `%{public}s`,remote service is died!", __func__); + WIFI_LOGE("failed to `%{public}s`,remote service is died!", __func__); return WIFI_OPT_FAILED; } MessageOption option; MessageParcel data, reply; + if (!data.WriteInterfaceToken(GetDescriptor())) { + WIFI_LOGE("Write interface token error: %{public}s", __func__); + return WIFI_OPT_FAILED; + } data.WriteInt32(0); - int error = Remote()->SendRequest(WIFI_SVR_CMD_REASSOCIATE, data, reply, option); if (error != ERR_NONE) { WIFI_LOGE("Set Attr(%{public}d) failed,error code is %{public}d", WIFI_SVR_CMD_REASSOCIATE, error); @@ -431,19 +712,23 @@ ErrCode WifiDeviceProxy::ReAssociate(void) if (exception) { return WIFI_OPT_FAILED; } + WriteWifiConnectionHiSysEvent(WifiConnectionType::CONNECT, GetBundleName()); return ErrCode(reply.ReadInt32()); } ErrCode WifiDeviceProxy::Disconnect(void) { if (mRemoteDied) { - WIFI_LOGD("failed to `%{public}s`,remote service is died!", __func__); + WIFI_LOGE("failed to `%{public}s`,remote service is died!", __func__); return WIFI_OPT_FAILED; } MessageOption option; MessageParcel data, reply; + if (!data.WriteInterfaceToken(GetDescriptor())) { + WIFI_LOGE("Write interface token error: %{public}s", __func__); + return WIFI_OPT_FAILED; + } data.WriteInt32(0); - int error = Remote()->SendRequest(WIFI_SVR_CMD_DISCONNECT, data, reply, option); if (error != ERR_NONE) { WIFI_LOGE("Set Attr(%{public}d) failed,error code is %{public}d", WIFI_SVR_CMD_DISCONNECT, error); @@ -453,22 +738,26 @@ ErrCode WifiDeviceProxy::Disconnect(void) if (exception) { return WIFI_OPT_FAILED; } + WriteWifiConnectionHiSysEvent(WifiConnectionType::DISCONNECT, GetBundleName()); return ErrCode(reply.ReadInt32()); } ErrCode WifiDeviceProxy::StartWps(const WpsConfig &config) { if (mRemoteDied) { - WIFI_LOGD("failed to `%{public}s`,remote service is died!", __func__); + WIFI_LOGE("failed to `%{public}s`,remote service is died!", __func__); return WIFI_OPT_FAILED; } MessageOption option; MessageParcel data, reply; + if (!data.WriteInterfaceToken(GetDescriptor())) { + WIFI_LOGE("Write interface token error: %{public}s", __func__); + return WIFI_OPT_FAILED; + } data.WriteInt32(0); data.WriteInt32(static_cast(config.setup)); data.WriteCString(config.pin.c_str()); data.WriteCString(config.bssid.c_str()); - int error = Remote()->SendRequest(WIFI_SVR_CMD_START_WPS, data, reply, option); if (error != ERR_NONE) { WIFI_LOGE("Set Attr(%{public}d) failed,error code is %{public}d", WIFI_SVR_CMD_START_WPS, error); @@ -484,13 +773,16 @@ ErrCode WifiDeviceProxy::StartWps(const WpsConfig &config) ErrCode WifiDeviceProxy::CancelWps(void) { if (mRemoteDied) { - WIFI_LOGD("failed to `%{public}s`,remote service is died!", __func__); + WIFI_LOGE("failed to `%{public}s`,remote service is died!", __func__); return WIFI_OPT_FAILED; } MessageOption option; MessageParcel data, reply; + if (!data.WriteInterfaceToken(GetDescriptor())) { + WIFI_LOGE("Write interface token error: %{public}s", __func__); + return WIFI_OPT_FAILED; + } data.WriteInt32(0); - int error = Remote()->SendRequest(WIFI_SVR_CMD_CANCEL_WPS, data, reply, option); if (error != ERR_NONE) { WIFI_LOGE("Set Attr(%{public}d) failed,error code is %{public}d", WIFI_SVR_CMD_CANCEL_WPS, error); @@ -506,13 +798,16 @@ ErrCode WifiDeviceProxy::CancelWps(void) ErrCode WifiDeviceProxy::IsWifiActive(bool &bActive) { if (mRemoteDied) { - WIFI_LOGD("failed to `%{public}s`,remote service is died!", __func__); + WIFI_LOGE("failed to `%{public}s`,remote service is died!", __func__); return WIFI_OPT_FAILED; } MessageOption option; MessageParcel data, reply; + if (!data.WriteInterfaceToken(GetDescriptor())) { + WIFI_LOGE("Write interface token error: %{public}s", __func__); + return WIFI_OPT_FAILED; + } data.WriteInt32(0); - int error = Remote()->SendRequest(WIFI_SVR_CMD_IS_WIFI_ACTIVE, data, reply, option); if (error != ERR_NONE) { WIFI_LOGE("Set Attr(%{public}d) failed,error code is %{public}d", WIFI_SVR_CMD_IS_WIFI_ACTIVE, error); @@ -534,13 +829,16 @@ ErrCode WifiDeviceProxy::IsWifiActive(bool &bActive) ErrCode WifiDeviceProxy::GetWifiState(int &state) { if (mRemoteDied) { - WIFI_LOGD("failed to `%{public}s`,remote service is died!", __func__); + WIFI_LOGE("failed to `%{public}s`,remote service is died!", __func__); return WIFI_OPT_FAILED; } MessageOption option; MessageParcel data, reply; + if (!data.WriteInterfaceToken(GetDescriptor())) { + WIFI_LOGE("Write interface token error: %{public}s", __func__); + return WIFI_OPT_FAILED; + } data.WriteInt32(0); - int error = Remote()->SendRequest(WIFI_SVR_CMD_GET_WIFI_STATE, data, reply, option); if (error != ERR_NONE) { WIFI_LOGE("Set Attr(%{public}d) failed,error code is %{public}d", WIFI_SVR_CMD_GET_WIFI_STATE, error); @@ -569,18 +867,21 @@ void WifiDeviceProxy::ReadLinkedInfo(MessageParcel &reply, WifiLinkedInfo &info) info.frequency = reply.ReadInt32(); info.linkSpeed = reply.ReadInt32(); info.macAddress = reply.ReadCString(); + info.macType = reply.ReadInt32(); info.ipAddress = reply.ReadInt32(); int tmpConnState = reply.ReadInt32(); - if ((tmpConnState >= 0) && (tmpConnState <= (int)ConnState::FAILED)) { - info.connState = (ConnState)tmpConnState; + if ((tmpConnState >= 0) && (tmpConnState <= (int)ConnState::UNKNOWN)) { + info.connState = ConnState(tmpConnState); } else { - info.connState = ConnState::FAILED; + info.connState = ConnState::UNKNOWN; } info.ifHiddenSSID = reply.ReadBool(); - info.rxLinkSpeed = reply.ReadCString(); - info.txLinkSpeed = reply.ReadCString(); + info.rxLinkSpeed = reply.ReadInt32(); + info.txLinkSpeed = reply.ReadInt32(); info.chload = reply.ReadInt32(); info.snr = reply.ReadInt32(); + info.isDataRestricted = reply.ReadInt32(); + info.portalUrl = reply.ReadCString(); int tmpState = reply.ReadInt32(); if ((tmpState >= 0) && (tmpState <= (int)SupplicantState::INVALID)) { @@ -600,13 +901,16 @@ void WifiDeviceProxy::ReadLinkedInfo(MessageParcel &reply, WifiLinkedInfo &info) ErrCode WifiDeviceProxy::GetLinkedInfo(WifiLinkedInfo &info) { if (mRemoteDied) { - WIFI_LOGD("failed to `%{public}s`,remote service is died!", __func__); + WIFI_LOGE("failed to `%{public}s`,remote service is died!", __func__); return WIFI_OPT_FAILED; } MessageOption option; MessageParcel data, reply; + if (!data.WriteInterfaceToken(GetDescriptor())) { + WIFI_LOGE("Write interface token error: %{public}s", __func__); + return WIFI_OPT_FAILED; + } data.WriteInt32(0); - int error = Remote()->SendRequest(WIFI_SVR_CMD_GET_LINKED_INFO, data, reply, option); if (error != ERR_NONE) { WIFI_LOGE("Set Attr(%{public}d) failed,error code is %{public}d", WIFI_SVR_CMD_GET_LINKED_INFO, error); @@ -629,13 +933,16 @@ ErrCode WifiDeviceProxy::GetLinkedInfo(WifiLinkedInfo &info) ErrCode WifiDeviceProxy::GetIpInfo(IpInfo &info) { if (mRemoteDied) { - WIFI_LOGD("failed to `%{public}s`,remote service is died!", __func__); + WIFI_LOGE("failed to `%{public}s`,remote service is died!", __func__); return WIFI_OPT_FAILED; } MessageOption option; MessageParcel data, reply; + if (!data.WriteInterfaceToken(GetDescriptor())) { + WIFI_LOGE("Write interface token error: %{public}s", __func__); + return WIFI_OPT_FAILED; + } data.WriteInt32(0); - int error = Remote()->SendRequest(WIFI_SVR_CMD_GET_DHCP_INFO, data, reply, option); if (error != ERR_NONE) { WIFI_LOGE("Set Attr(%{public}d) failed,error code is %{public}d", WIFI_SVR_CMD_GET_DHCP_INFO, error); @@ -663,14 +970,17 @@ ErrCode WifiDeviceProxy::GetIpInfo(IpInfo &info) ErrCode WifiDeviceProxy::SetCountryCode(const std::string &countryCode) { if (mRemoteDied) { - WIFI_LOGD("failed to `%{public}s`,remote service is died!", __func__); + WIFI_LOGE("failed to `%{public}s`,remote service is died!", __func__); return WIFI_OPT_FAILED; } MessageOption option; MessageParcel data, reply; + if (!data.WriteInterfaceToken(GetDescriptor())) { + WIFI_LOGE("Write interface token error: %{public}s", __func__); + return WIFI_OPT_FAILED; + } data.WriteInt32(0); data.WriteCString(countryCode.c_str()); - int error = Remote()->SendRequest(WIFI_SVR_CMD_SET_COUNTRY_CODE, data, reply, option); if (error != ERR_NONE) { WIFI_LOGE("Set Attr(%{public}d) failed,error code is %{public}d", WIFI_SVR_CMD_SET_COUNTRY_CODE, error); @@ -686,11 +996,15 @@ ErrCode WifiDeviceProxy::SetCountryCode(const std::string &countryCode) ErrCode WifiDeviceProxy::GetCountryCode(std::string &countryCode) { if (mRemoteDied) { - WIFI_LOGD("failed to `%{public}s`,remote service is died!", __func__); + WIFI_LOGE("failed to `%{public}s`,remote service is died!", __func__); return WIFI_OPT_FAILED; } MessageOption option; MessageParcel data, reply; + if (!data.WriteInterfaceToken(GetDescriptor())) { + WIFI_LOGE("Write interface token error: %{public}s", __func__); + return WIFI_OPT_FAILED; + } data.WriteInt32(0); int error = Remote()->SendRequest(WIFI_SVR_CMD_GET_COUNTRY_CODE, data, reply, option); if (error != ERR_NONE) { @@ -713,13 +1027,21 @@ ErrCode WifiDeviceProxy::GetCountryCode(std::string &countryCode) ErrCode WifiDeviceProxy::RegisterCallBack(const sptr &callback) { if (mRemoteDied) { - WIFI_LOGD("failed to `%{public}s`,remote service is died!", __func__); + WIFI_LOGE("failed to `%{public}s`,remote service is died!", __func__); return WIFI_OPT_FAILED; } MessageParcel data, reply; MessageOption option(MessageOption::TF_ASYNC); + if (!data.WriteInterfaceToken(GetDescriptor())) { + WIFI_LOGE("Write interface token error: %{public}s", __func__); + return WIFI_OPT_FAILED; + } data.WriteInt32(0); + if (g_deviceCallBackStub == nullptr) { + WIFI_LOGE("g_deviceCallBackStub is nullptr"); + return WIFI_OPT_FAILED; + } g_deviceCallBackStub->RegisterUserCallBack(callback); if (!data.WriteRemoteObject(g_deviceCallBackStub->AsObject())) { @@ -742,15 +1064,18 @@ ErrCode WifiDeviceProxy::RegisterCallBack(const sptr &callb ErrCode WifiDeviceProxy::GetSignalLevel(const int &rssi, const int &band, int &level) { if (mRemoteDied) { - WIFI_LOGD("failed to `%{public}s`,remote service is died!", __func__); + WIFI_LOGE("failed to `%{public}s`,remote service is died!", __func__); return WIFI_OPT_FAILED; } MessageOption option; MessageParcel data, reply; + if (!data.WriteInterfaceToken(GetDescriptor())) { + WIFI_LOGE("Write interface token error: %{public}s", __func__); + return WIFI_OPT_FAILED; + } data.WriteInt32(0); data.WriteInt32(rssi); data.WriteInt32(band); - int error = Remote()->SendRequest(WIFI_SVR_CMD_GET_SIGNAL_LEVEL, data, reply, option); if (error != ERR_NONE) { WIFI_LOGE("Set Attr(%{public}d) failed,error code is %{public}d", WIFI_SVR_CMD_GET_SIGNAL_LEVEL, error); @@ -772,11 +1097,15 @@ ErrCode WifiDeviceProxy::GetSignalLevel(const int &rssi, const int &band, int &l ErrCode WifiDeviceProxy::GetSupportedFeatures(long &features) { if (mRemoteDied) { - WIFI_LOGD("failed to `%{public}s`,remote service is died!", __func__); + WIFI_LOGE("failed to `%{public}s`,remote service is died!", __func__); return WIFI_OPT_FAILED; } MessageOption option; MessageParcel data, reply; + if (!data.WriteInterfaceToken(GetDescriptor())) { + WIFI_LOGE("Write interface token error: %{public}s", __func__); + return WIFI_OPT_FAILED; + } data.WriteInt32(0); int error = Remote()->SendRequest(WIFI_SVR_CMD_GET_SUPPORTED_FEATURES, data, reply, option); if (error != ERR_NONE) { @@ -799,14 +1128,17 @@ ErrCode WifiDeviceProxy::GetSupportedFeatures(long &features) ErrCode WifiDeviceProxy::GetDeviceMacAddress(std::string &result) { if (mRemoteDied) { - WIFI_LOGD("failed to `%{public}s`,remote service is died!", __func__); + WIFI_LOGE("failed to `%{public}s`,remote service is died!", __func__); return WIFI_OPT_FAILED; } MessageOption option; MessageParcel data; MessageParcel reply; + if (!data.WriteInterfaceToken(GetDescriptor())) { + WIFI_LOGE("Write interface token error: %{public}s", __func__); + return WIFI_OPT_FAILED; + } data.WriteInt32(0); - int error = Remote()->SendRequest(WIFI_SVR_CMD_GET_DERVICE_MAC_ADD, data, reply, option); if (error != ERR_NONE) { WIFI_LOGE("Set Attr(%{public}d) failed", WIFI_SVR_CMD_GET_DERVICE_MAC_ADD); @@ -825,13 +1157,44 @@ ErrCode WifiDeviceProxy::GetDeviceMacAddress(std::string &result) return WIFI_OPT_SUCCESS; } +bool WifiDeviceProxy::SetLowLatencyMode(bool enabled) +{ + if (mRemoteDied) { + WIFI_LOGE("failed to `%{public}s`,remote service is died!", __func__); + return WIFI_OPT_FAILED; + } + MessageOption option; + MessageParcel data; + MessageParcel reply; + if (!data.WriteInterfaceToken(GetDescriptor())) { + WIFI_LOGE("Write interface token error: %{public}s", __func__); + return WIFI_OPT_FAILED; + } + data.WriteInt32(0); + data.WriteBool(enabled); + int error = Remote()->SendRequest(WIFI_SVR_CMD_SET_LOW_LATENCY_MODE, data, reply, option); + if (error != ERR_NONE) { + WIFI_LOGE("Set Attr(%{public}d) failed,error code is %{public}d", WIFI_SVR_CMD_SET_LOW_LATENCY_MODE, error); + return WIFI_OPT_FAILED; + } + int exception = reply.ReadInt32(); + if (exception) { + return WIFI_OPT_FAILED; + } + return reply.ReadBool(); +} + void WifiDeviceProxy::OnRemoteDied(const wptr &remoteObject) { - WIFI_LOGD("Remote service is died!"); + WIFI_LOGW("Remote service is died!"); mRemoteDied = true; + if (g_deviceCallBackStub == nullptr) { + WIFI_LOGE("g_deviceCallBackStub is nullptr"); + return; + } if (g_deviceCallBackStub != nullptr) { g_deviceCallBackStub->SetRemoteDied(true); } } } // namespace Wifi -} // namespace OHOS \ No newline at end of file +} // namespace OHOS diff --git a/interfaces/innerkits/native_cpp/wifi_standard/src/wifi_device_proxy.h b/wifi/frameworks/native/src/wifi_device_proxy.h similarity index 66% rename from interfaces/innerkits/native_cpp/wifi_standard/src/wifi_device_proxy.h rename to wifi/frameworks/native/src/wifi_device_proxy.h index b27c3dea07c25f357bacdfff891b09c5d28374af..cfb630dcd2a45a14f552c4fdc1f01bc9642a5fc1 100644 --- a/interfaces/innerkits/native_cpp/wifi_standard/src/wifi_device_proxy.h +++ b/wifi/frameworks/native/src/wifi_device_proxy.h @@ -1,5 +1,5 @@ /* - * Copyright (C) 2021 Huawei Device Co., Ltd. + * Copyright (C) 2021-2022 Huawei Device Co., Ltd. * 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 @@ -15,16 +15,30 @@ #ifndef OHOS_WIFI_DEVICE_PROXY_H #define OHOS_WIFI_DEVICE_PROXY_H -#include "i_wifi_device.h" +#ifdef OHOS_ARCH_LITE +#include "iproxy_client.h" +#include "serializer.h" +#else #include "iremote_proxy.h" +#endif +#include "i_wifi_device.h" #include "wifi_errcode.h" #include "wifi_msg.h" namespace OHOS { namespace Wifi { +#ifdef OHOS_ARCH_LITE +class WifiDeviceProxy : public IWifiDevice { +public: + static WifiDeviceProxy *GetInstance(void); + static void ReleaseInstance(void); + explicit WifiDeviceProxy(); + ErrCode Init(void); +#else class WifiDeviceProxy : public IRemoteProxy, public IRemoteObject::DeathRecipient { public: explicit WifiDeviceProxy(const sptr &impl); +#endif ~WifiDeviceProxy(); /** @@ -41,14 +55,66 @@ public: */ ErrCode DisableWifi() override; + /** + * @Description create the Wi-Fi protect. + * + * @param protectType - WifiProtectMode object + * @param protectName - the protect name + * @return ErrCode - operation result + */ + ErrCode InitWifiProtect(const WifiProtectType &protectType, const std::string &protectName) override; + + /** + * @Description Acquire the Wi-Fi protect mode. + * + * @param protectMode - WifiProtectMode object + * @param protectName - the protect name + * @return ErrCode - operation result + */ + ErrCode GetWifiProtectRef(const WifiProtectMode &protectMode, const std::string &protectName) override; + + /** + * @Description Release the Wi-Fi protect mode. + * + * @param protectName - the protect name + * @return ErrCode - operation result + */ + ErrCode PutWifiProtectRef(const std::string &protectName) override; + + /** + * @Description Remove a specified untrusted hotspot configuration. + * + * @param config - WifiDeviceConfig object + * @return ErrCode - operation result + */ + ErrCode RemoveCandidateConfig(const WifiDeviceConfig &config) override; + + /** + * @Description Remove the wifi Untrusted device config equals to input network id + * + * @param networkId - the untrusted device network id + * @return ErrCode - operation result + */ + ErrCode RemoveCandidateConfig(int networkId) override; + /** * @Description Add a wifi device configuration. * * @param config - WifiDeviceConfig object * @param result - the device configuration's network id + * @param isCandidate - Whether is candidate * @return ErrCode - operation result */ - ErrCode AddDeviceConfig(const WifiDeviceConfig &config, int &result) override; + ErrCode AddDeviceConfig(const WifiDeviceConfig &config, int &result, bool isCandidate) override; + + /** + * @Description Update a wifi device configuration. + * + * @param config - WifiDeviceConfig object + * @param result - the device configuration's network id after updated + * @return ErrCode - operation result + */ + ErrCode UpdateDeviceConfig(const WifiDeviceConfig &config, int &result) override; /** * @Description Remove the wifi device config equals to input network id @@ -69,9 +135,10 @@ public: * @Description Get all the device configs * * @param result - Get result vector of WifiDeviceConfig + * @param isCandidate - Whether is candidate * @return ErrCode - operation result */ - ErrCode GetDeviceConfigs(std::vector &result) override; + ErrCode GetDeviceConfigs(std::vector &result, bool isCandidate) override; /** * @Description Enable device config, when set attemptEnable, disable other device config @@ -94,9 +161,10 @@ public: * @Description Connecting to a Specified Network * * @param networkId - network id + * @param isCandidate - Whether is candidate * @return ErrCode - operation result */ - ErrCode ConnectToNetwork(int networkId) override; + ErrCode ConnectToNetwork(int networkId, bool isCandidate) override; /** * @Description Connect To a network base WifiDeviceConfig object @@ -106,6 +174,13 @@ public: */ ErrCode ConnectToDevice(const WifiDeviceConfig &config) override; + /** + * @Description Check whether Wi-Fi is connected. + * + * @return bool - true: connected, false: not connected + */ + bool IsConnected() override; + /** * @Description Reconnect to the currently active network * @@ -196,7 +271,11 @@ public: * @param callback - IWifiDeviceCallBack object * @return ErrCode - operation result */ +#ifdef OHOS_ARCH_LITE + ErrCode RegisterCallBack(const std::shared_ptr &callback) override; +#else ErrCode RegisterCallBack(const sptr &callback) override; +#endif /** * @Description Get the Signal Level object @@ -224,6 +303,31 @@ public: */ ErrCode GetDeviceMacAddress(std::string &result) override; + /** + * @Description set low latency mode + * + * @param enabled - true: enable low latency, false: disable low latency + * @return bool - operation result + */ + bool SetLowLatencyMode(bool enabled) override; + +#ifdef OHOS_ARCH_LITE + /** + * @Description Handle remote object died event. + */ + void OnRemoteDied(void); +private: + static WifiDeviceProxy *g_instance; + IClientProxy *remote_ = nullptr; + SvcIdentity svcIdentity_ = { 0 }; + bool remoteDied_; + void WriteIpAddress(IpcIo &req, const WifiIpAddress &address); + void WriteDeviceConfig(const WifiDeviceConfig &config, IpcIo &req); +#else + /** + * @Description Handle remote object died event. + * @param remoteObject remote object. + */ void OnRemoteDied(const wptr &remoteObject) override; private: @@ -233,8 +337,8 @@ private: void WriteDeviceConfig(const WifiDeviceConfig &config, MessageParcel &data); void ParseDeviceConfigs(MessageParcel &reply, std::vector &result); static BrokerDelegator g_delegator; - bool mRemoteDied; +#endif }; } // namespace Wifi } // namespace OHOS diff --git a/wifi/frameworks/native/src/wifi_device_proxy_lite.cpp b/wifi/frameworks/native/src/wifi_device_proxy_lite.cpp new file mode 100644 index 0000000000000000000000000000000000000000..c6cdd48408b4e94c896add2699e56f9f10e8603f --- /dev/null +++ b/wifi/frameworks/native/src/wifi_device_proxy_lite.cpp @@ -0,0 +1,1259 @@ +/* + * Copyright (C) 2022 Huawei Device Co., Ltd. + * 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 "wifi_device_proxy.h" +#include "define.h" +#include "ipc_skeleton.h" +#include "rpc_errno.h" +#include "serializer.h" +#include "samgr_lite.h" +#include "wifi_ipc_lite_adapter.h" +#include "wifi_device_callback_stub_lite.h" +#include "wifi_logger.h" + +DEFINE_WIFILOG_LABEL("WifiDeviceProxyLite"); + +namespace OHOS { +namespace Wifi { +static SvcIdentity g_sid; +static IpcObjectStub g_objStub; +static WifiDeviceCallBackStub g_deviceCallBackStub; +static void ReadIpAddress(IpcIo *reply, WifiIpAddress &address) +{ + constexpr int MAX_SIZE = 256; + (void)ReadInt32(reply, &address.family); + (void)ReadUint32(reply, &address.addressIpv4); + int size = 0; + (void)ReadInt32(reply, &size); + if (size > MAX_SIZE) { + WIFI_LOGE("Read IP address size error: %{public}d", size); + return; + } + int tmpAddress = 0; + for (int i = 0; i < size; i++) { + (void)ReadInt8(reply, (int8_t *)&tmpAddress); + address.addressIpv6.push_back(tmpAddress); + } + return; +} + +static void ParseDeviceConfigs(IpcIo *reply, std::vector &result) +{ + size_t readLen; + constexpr int MAX_DEVICE_CONFIG_SIZE = 1024; + int retSize = 0; + (void)ReadInt32(reply, &retSize); + if (retSize > MAX_DEVICE_CONFIG_SIZE) { + WIFI_LOGE("Parse device config size error: %{public}d", retSize); + return; + } + for (int i = 0; i < retSize; ++i) { + WifiDeviceConfig config; + (void)ReadInt32(reply, &config.networkId); + (void)ReadInt32(reply, &config.status); + config.bssid = (char *)ReadString(reply, &readLen); + config.ssid = (char *)ReadString(reply, &readLen); + (void)ReadInt32(reply, &config.band); + (void)ReadInt32(reply, &config.channel); + (void)ReadInt32(reply, &config.frequency); + (void)ReadInt32(reply, &config.level); + (void)ReadBool(reply, &config.isPasspoint); + (void)ReadBool(reply, &config.isEphemeral); + config.preSharedKey = (char *)ReadString(reply, &readLen); + config.keyMgmt = (char *)ReadString(reply, &readLen); + for (int j = 0; j < WEPKEYS_SIZE; j++) { + config.wepKeys[j] = (char *)ReadString(reply, &readLen); + } + (void)ReadInt32(reply, &config.wepTxKeyIndex); + (void)ReadInt32(reply, &config.priority); + (void)ReadBool(reply, &config.hiddenSSID); + int ipMethod = 0; + (void)ReadInt32(reply, &ipMethod); + config.wifiIpConfig.assignMethod = AssignIpMethod(ipMethod); + ReadIpAddress(reply, config.wifiIpConfig.staticIpAddress.ipAddress.address); + (void)ReadInt32(reply, &config.wifiIpConfig.staticIpAddress.ipAddress.prefixLength); + (void)ReadInt32(reply, &config.wifiIpConfig.staticIpAddress.ipAddress.flags); + (void)ReadInt32(reply, &config.wifiIpConfig.staticIpAddress.ipAddress.scope); + ReadIpAddress(reply, config.wifiIpConfig.staticIpAddress.gateway); + ReadIpAddress(reply, config.wifiIpConfig.staticIpAddress.dnsServer1); + ReadIpAddress(reply, config.wifiIpConfig.staticIpAddress.dnsServer2); + config.wifiIpConfig.staticIpAddress.domains = (char *)ReadString(reply, &readLen); + config.wifiEapConfig.eap = (char *)ReadString(reply, &readLen); + config.wifiEapConfig.identity = (char *)ReadString(reply, &readLen); + config.wifiEapConfig.password = (char *)ReadString(reply, &readLen); + int proxyMethod = 0; + (void)ReadInt32(reply, &proxyMethod); + config.wifiProxyconfig.configureMethod = ConfigureProxyMethod(proxyMethod); + config.wifiProxyconfig.autoProxyConfig.pacWebAddress = (char *)ReadString(reply, &readLen); + config.wifiProxyconfig.manualProxyConfig.serverHostName = (char *)ReadString(reply, &readLen); + (void)ReadInt32(reply, &config.wifiProxyconfig.manualProxyConfig.serverPort); + config.wifiProxyconfig.manualProxyConfig.exclusionObjectList = (char *)ReadString(reply, &readLen); + int privacyConfig = 0; + (void)ReadInt32(reply, &privacyConfig); + config.wifiPrivacySetting = WifiPrivacyConfig(privacyConfig); + (void)ReadInt32(reply, &config.uid); + + result.emplace_back(config); + } +} + +static void ReadLinkedInfo(IpcIo *reply, WifiLinkedInfo &info) +{ + size_t readLen; + (void)ReadInt32(reply, &info.networkId); + info.ssid = (char *)ReadString(reply, &readLen); + info.bssid = (char *)ReadString(reply, &readLen); + (void)ReadInt32(reply, &info.rssi); + (void)ReadInt32(reply, &info.band); + (void)ReadInt32(reply, &info.frequency); + (void)ReadInt32(reply, &info.linkSpeed); + info.macAddress = (char *)ReadString(reply, &readLen); + (void)ReadUint32(reply, &info.ipAddress); + int tmpConnState = 0; + (void)ReadInt32(reply, &tmpConnState); + if ((tmpConnState >= 0) && (tmpConnState <= (int)ConnState::UNKNOWN)) { + info.connState = ConnState(tmpConnState); + } else { + info.connState = ConnState::UNKNOWN; + } + (void)ReadBool(reply, &info.ifHiddenSSID); + (void)ReadInt32(reply, &info.rxLinkSpeed); + (void)ReadInt32(reply, &info.txLinkSpeed); + (void)ReadInt32(reply, &info.chload); + (void)ReadInt32(reply, &info.snr); + (void)ReadInt32(reply, &info.isDataRestricted); + info.portalUrl = (char *)ReadString(reply, &readLen); + + int tmpState = 0; + (void)ReadInt32(reply, &tmpState); + if ((tmpState >= 0) && (tmpState <= (int)SupplicantState::INVALID)) { + info.supplicantState = (SupplicantState)tmpState; + } else { + info.supplicantState = SupplicantState::INVALID; + } + + int tmpDetailState = 0; + (void)ReadInt32(reply, &tmpDetailState); + if ((tmpDetailState >= 0) && (tmpDetailState <= (int)DetailedState::INVALID)) { + info.detailedState = (DetailedState)tmpDetailState; + } else { + info.detailedState = DetailedState::INVALID; + } +} + +static void ReadDhcpInfo(IpcIo *reply, IpInfo &info) +{ + (void)ReadUint32(reply, &info.ipAddress); + (void)ReadUint32(reply, &info.gateway); + (void)ReadUint32(reply, &info.netmask); + (void)ReadUint32(reply, &info.primaryDns); + (void)ReadUint32(reply, &info.secondDns); + (void)ReadUint32(reply, &info.serverIp); + (void)ReadUint32(reply, &info.leaseDuration); +} + +static int IpcCallback(void *owner, int code, IpcIo *reply) +{ + if (code != 0 || owner == nullptr || reply == nullptr) { + WIFI_LOGE("Callback error, code:%{public}d, owner:%{public}d, reply:%{public}d", + code, owner == nullptr, reply == nullptr); + return ERR_FAILED; + } + + struct IpcOwner *data = (struct IpcOwner *)owner; + (void)ReadInt32(reply, &data->exception); + (void)ReadInt32(reply, &data->retCode); + if (data->exception != 0 || data->retCode != WIFI_OPT_SUCCESS || data->variable == nullptr) { + return ERR_NONE; + } + + switch (data->funcId) { + case WIFI_SVR_CMD_ADD_DEVICE_CONFIG: + case WIFI_SVR_CMD_UPDATE_DEVICE_CONFIG: + case WIFI_SVR_CMD_GET_WIFI_STATE: + case WIFI_SVR_CMD_GET_SIGNAL_LEVEL: { + (void)ReadInt32(reply, (int32_t *)data->variable); + break; + } + case WIFI_SVR_CMD_IS_WIFI_CONNECTED: + case WIFI_SVR_CMD_IS_WIFI_ACTIVE: + case WIFI_SVR_CMD_SET_LOW_LATENCY_MODE: { + (void)ReadBool(reply, (bool *)data->variable); + break; + } + case WIFI_SVR_CMD_GET_COUNTRY_CODE: + case WIFI_SVR_CMD_GET_DERVICE_MAC_ADD: { + size_t readLen = 0; + *((std::string *)data->variable) = (char *)ReadString(reply, &readLen); + break; + } + case WIFI_SVR_CMD_GET_SUPPORTED_FEATURES: { + int64_t features = 0; + ReadInt64(reply, &features); + *((long *)data->variable) = features; + break; + } + case WIFI_SVR_CMD_GET_DEVICE_CONFIGS: { + ParseDeviceConfigs(reply, *((std::vector *)data->variable)); + break; + } + case WIFI_SVR_CMD_GET_LINKED_INFO: { + ReadLinkedInfo(reply, *((WifiLinkedInfo *)data->variable)); + break; + } + case WIFI_SVR_CMD_GET_DHCP_INFO: { + ReadDhcpInfo(reply, *((IpInfo *)data->variable)); + break; + } + default: + break; + } + + return ERR_NONE; +} + +static int AsyncCallback(uint32_t code, IpcIo *data, IpcIo *reply, MessageOption option) +{ + if (data == nullptr) { + WIFI_LOGE("AsyncCallback error, data is null"); + return ERR_FAILED; + } + return g_deviceCallBackStub.OnRemoteRequest(code, data); +} + +static void OnRemoteSrvDied(void *arg) +{ + WIFI_LOGE("%{public}s called.", __func__); + WifiDeviceProxy *client = WifiDeviceProxy::GetInstance(); + if (client != nullptr) { + client->OnRemoteDied(); + } + return; +} + +WifiDeviceProxy *WifiDeviceProxy::g_instance = nullptr; +WifiDeviceProxy::WifiDeviceProxy() : remoteDied_(false) +{} + +WifiDeviceProxy::~WifiDeviceProxy() +{} + +WifiDeviceProxy *WifiDeviceProxy::GetInstance(void) +{ + if (g_instance != nullptr) { + return g_instance; + } + + WifiDeviceProxy *tempInstance = new(std::nothrow) WifiDeviceProxy(); + g_instance = tempInstance; + return g_instance; +} + +void WifiDeviceProxy::ReleaseInstance(void) +{ + if (g_instance != nullptr) { + delete g_instance; + g_instance = nullptr; + } +} + +ErrCode WifiDeviceProxy::Init() +{ + IUnknown *iUnknown = SAMGR_GetInstance()->GetFeatureApi(WIFI_SERVICE_LITE, WIFI_FEATURE_DEVICE); + if (iUnknown == nullptr) { + WIFI_LOGE("GetFeatureApi failed."); + return WIFI_OPT_FAILED; + } + IClientProxy *proxy = nullptr; + int result = iUnknown->QueryInterface(iUnknown, CLIENT_PROXY_VER, reinterpret_cast(&proxy)); + if (result != 0) { + WIFI_LOGE("QueryInterface failed."); + return WIFI_OPT_FAILED; + } + remote_ = proxy; + + // Register SA Death Callback + uint32_t deadId = 0; + svcIdentity_ = SAMGR_GetRemoteIdentity(WIFI_SERVICE_LITE, WIFI_FEATURE_DEVICE); + result = AddDeathRecipient(svcIdentity_, OnRemoteSrvDied, nullptr, &deadId); + if (result != 0) { + WIFI_LOGE("Register SA Death Callback failed, errorCode[%d]", result); + } + return WIFI_OPT_SUCCESS; +} + +ErrCode WifiDeviceProxy::EnableWifi() +{ + if (remoteDied_ || remote_ == nullptr) { + WIFI_LOGE("failed to %{public}s, remoteDied_: %{public}d, remote_: %{public}d", + __func__, remoteDied_, remote_ == nullptr); + return WIFI_OPT_FAILED; + } + + IpcIo req; + char data[IPC_DATA_SIZE_SMALL]; + struct IpcOwner owner = {.exception = -1, .retCode = 0, .variable = nullptr}; + + IpcIoInit(&req, data, IPC_DATA_SIZE_SMALL, MAX_IPC_OBJ_COUNT); + (void)WriteInt32(&req, 0); + owner.funcId = WIFI_SVR_CMD_ENABLE_WIFI; + int error = remote_->Invoke(remote_, WIFI_SVR_CMD_ENABLE_WIFI, &req, &owner, IpcCallback); + if (error != EC_SUCCESS) { + WIFI_LOGE("Set Attr(%{public}d) failed,error code is %{public}d", WIFI_SVR_CMD_ENABLE_WIFI, error); + return WIFI_OPT_FAILED; + } + + if (owner.exception) { + return WIFI_OPT_FAILED; + } + return ErrCode(owner.retCode); +} + +ErrCode WifiDeviceProxy::DisableWifi() +{ + if (remoteDied_ || remote_ == nullptr) { + WIFI_LOGE("failed to %{public}s, remoteDied_: %{public}d, remote_: %{public}d", + __func__, remoteDied_, remote_ == nullptr); + return WIFI_OPT_FAILED; + } + + IpcIo req; + char data[IPC_DATA_SIZE_SMALL]; + struct IpcOwner owner = {.exception = -1, .retCode = 0, .variable = nullptr}; + + IpcIoInit(&req, data, IPC_DATA_SIZE_SMALL, MAX_IPC_OBJ_COUNT); + (void)WriteInt32(&req, 0); + owner.funcId = WIFI_SVR_CMD_DISABLE_WIFI; + int error = remote_->Invoke(remote_, WIFI_SVR_CMD_DISABLE_WIFI, &req, &owner, IpcCallback); + if (error != EC_SUCCESS) { + WIFI_LOGE("Set Attr(%{public}d) failed,error code is %{public}d", WIFI_SVR_CMD_DISABLE_WIFI, error); + return WIFI_OPT_FAILED; + } + + if (owner.exception) { + return WIFI_OPT_FAILED; + } + return ErrCode(owner.retCode); +} + +ErrCode WifiDeviceProxy::InitWifiProtect(const WifiProtectType &protectType, const std::string &protectName) +{ + if (remoteDied_ || remote_ == nullptr) { + WIFI_LOGE("failed to %{public}s, remoteDied_: %{public}d, remote_: %{public}d", + __func__, remoteDied_, remote_ == nullptr); + return WIFI_OPT_FAILED; + } + + IpcIo req; + char data[IPC_DATA_SIZE_SMALL]; + struct IpcOwner owner = {.exception = -1, .retCode = 0, .variable = nullptr}; + + IpcIoInit(&req, data, IPC_DATA_SIZE_SMALL, MAX_IPC_OBJ_COUNT); + (void)WriteInt32(&req, 0); + (void)WriteInt32(&req, (int)protectType); + (void)WriteString(&req, protectName.c_str()); + owner.funcId = WIFI_SVR_CMD_INIT_WIFI_PROTECT; + int error = remote_->Invoke(remote_, WIFI_SVR_CMD_INIT_WIFI_PROTECT, &req, &owner, IpcCallback); + if (error != EC_SUCCESS) { + WIFI_LOGE("Set Attr(%{public}d) failed,error code is %{public}d", WIFI_SVR_CMD_INIT_WIFI_PROTECT, error); + return ErrCode(error); + } + + if (owner.exception) { + return WIFI_OPT_FAILED; + } + return ErrCode(owner.retCode); +} + +ErrCode WifiDeviceProxy::GetWifiProtectRef(const WifiProtectMode &protectMode, const std::string &protectName) +{ + if (remoteDied_ || remote_ == nullptr) { + WIFI_LOGE("failed to %{public}s, remoteDied_: %{public}d, remote_: %{public}d", + __func__, remoteDied_, remote_ == nullptr); + return WIFI_OPT_FAILED; + } + + IpcIo req; + char data[IPC_DATA_SIZE_SMALL]; + struct IpcOwner owner = {.exception = -1, .retCode = 0, .variable = nullptr}; + + IpcIoInit(&req, data, IPC_DATA_SIZE_SMALL, MAX_IPC_OBJ_COUNT); + (void)WriteInt32(&req, 0); + (void)WriteInt32(&req, (int)protectMode); + (void)WriteString(&req, protectName.c_str()); + owner.funcId = WIFI_SVR_CMD_GET_WIFI_PROTECT; + int error = remote_->Invoke(remote_, WIFI_SVR_CMD_GET_WIFI_PROTECT, &req, &owner, IpcCallback); + if (error != EC_SUCCESS) { + WIFI_LOGE("Set Attr(%{public}d) failed,error code is %{public}d", WIFI_SVR_CMD_GET_WIFI_PROTECT, error); + return ErrCode(error); + } + + if (owner.exception) { + return WIFI_OPT_FAILED; + } + return ErrCode(owner.retCode); +} + +ErrCode WifiDeviceProxy::PutWifiProtectRef(const std::string &protectName) +{ + if (remoteDied_ || remote_ == nullptr) { + WIFI_LOGE("failed to %{public}s, remoteDied_: %{public}d, remote_: %{public}d", + __func__, remoteDied_, remote_ == nullptr); + return WIFI_OPT_FAILED; + } + + IpcIo req; + char data[IPC_DATA_SIZE_SMALL]; + struct IpcOwner owner = {.exception = -1, .retCode = 0, .variable = nullptr}; + + IpcIoInit(&req, data, IPC_DATA_SIZE_SMALL, MAX_IPC_OBJ_COUNT); + (void)WriteInt32(&req, 0); + (void)WriteString(&req, protectName.c_str()); + owner.funcId = WIFI_SVR_CMD_PUT_WIFI_PROTECT; + int error = remote_->Invoke(remote_, WIFI_SVR_CMD_PUT_WIFI_PROTECT, &req, &owner, IpcCallback); + if (error != EC_SUCCESS) { + WIFI_LOGE("Set Attr(%{public}d) failed,error code is %{public}d", WIFI_SVR_CMD_PUT_WIFI_PROTECT, error); + return ErrCode(error); + } + + if (owner.exception) { + return WIFI_OPT_FAILED; + } + return ErrCode(owner.retCode); +} + +ErrCode WifiDeviceProxy::RemoveCandidateConfig(int networkId) +{ + (void)networkId; + return WIFI_OPT_NOT_SUPPORTED; +} + +ErrCode WifiDeviceProxy::RemoveCandidateConfig(const WifiDeviceConfig &config) +{ + (void)config; + return WIFI_OPT_NOT_SUPPORTED; +} + +void WifiDeviceProxy::WriteIpAddress(IpcIo &req, const WifiIpAddress &address) +{ + (void)WriteInt32(&req, address.family); + (void)WriteUint32(&req, address.addressIpv4); + int size = address.addressIpv6.size(); + (void)WriteInt32(&req, size); + for (int i = 0; i < size; i++) { + (void)WriteInt8(&req, address.addressIpv6[i]); + } + return; +} + +void WifiDeviceProxy::WriteDeviceConfig(const WifiDeviceConfig &config, IpcIo &req) +{ + (void)WriteInt32(&req, config.networkId); + (void)WriteInt32(&req, config.status); + (void)WriteString(&req, config.bssid.c_str()); + (void)WriteString(&req, config.ssid.c_str()); + (void)WriteInt32(&req, config.band); + (void)WriteInt32(&req, config.channel); + (void)WriteInt32(&req, config.frequency); + (void)WriteInt32(&req, config.level); + (void)WriteBool(&req, config.isPasspoint); + (void)WriteBool(&req, config.isEphemeral); + (void)WriteString(&req, config.preSharedKey.c_str()); + (void)WriteString(&req, config.keyMgmt.c_str()); + for (int i = 0; i < WEPKEYS_SIZE; i++) { + (void)WriteString(&req, config.wepKeys[i].c_str()); + } + (void)WriteInt32(&req, config.wepTxKeyIndex); + (void)WriteInt32(&req, config.priority); + (void)WriteBool(&req, config.hiddenSSID); + (void)WriteInt32(&req, (int)config.wifiIpConfig.assignMethod); + WriteIpAddress(req, config.wifiIpConfig.staticIpAddress.ipAddress.address); + (void)WriteInt32(&req, config.wifiIpConfig.staticIpAddress.ipAddress.prefixLength); + (void)WriteInt32(&req, config.wifiIpConfig.staticIpAddress.ipAddress.flags); + (void)WriteInt32(&req, config.wifiIpConfig.staticIpAddress.ipAddress.scope); + WriteIpAddress(req, config.wifiIpConfig.staticIpAddress.gateway); + WriteIpAddress(req, config.wifiIpConfig.staticIpAddress.dnsServer1); + WriteIpAddress(req, config.wifiIpConfig.staticIpAddress.dnsServer2); + (void)WriteString(&req, config.wifiIpConfig.staticIpAddress.domains.c_str()); + (void)WriteString(&req, config.wifiEapConfig.eap.c_str()); + (void)WriteString(&req, config.wifiEapConfig.identity.c_str()); + (void)WriteString(&req, config.wifiEapConfig.password.c_str()); + (void)WriteInt32(&req, (int)config.wifiProxyconfig.configureMethod); + (void)WriteString(&req, config.wifiProxyconfig.autoProxyConfig.pacWebAddress.c_str()); + (void)WriteString(&req, config.wifiProxyconfig.manualProxyConfig.serverHostName.c_str()); + (void)WriteInt32(&req, config.wifiProxyconfig.manualProxyConfig.serverPort); + (void)WriteString(&req, config.wifiProxyconfig.manualProxyConfig.exclusionObjectList.c_str()); + (void)WriteInt32(&req, (int)config.wifiPrivacySetting); +} + +ErrCode WifiDeviceProxy::AddDeviceConfig(const WifiDeviceConfig &config, int &result, bool isCandidate) +{ + if (remoteDied_ || remote_ == nullptr) { + WIFI_LOGE("failed to %{public}s, remoteDied_: %{public}d, remote_: %{public}d", + __func__, remoteDied_, remote_ == nullptr); + return WIFI_OPT_FAILED; + } + + IpcIo req; + char data[IPC_DATA_SIZE_BIG]; + struct IpcOwner owner = {.exception = -1, .retCode = 0, .variable = nullptr}; + + IpcIoInit(&req, data, IPC_DATA_SIZE_BIG, MAX_IPC_OBJ_COUNT); + (void)WriteInt32(&req, 0); + (void)WriteBool(&req, isCandidate); + WriteDeviceConfig(config, req); + owner.variable = &result; + owner.funcId = WIFI_SVR_CMD_ADD_DEVICE_CONFIG; + int error = remote_->Invoke(remote_, WIFI_SVR_CMD_ADD_DEVICE_CONFIG, &req, &owner, IpcCallback); + if (error != EC_SUCCESS) { + WIFI_LOGE("Set Attr(%{public}d) failed,error code is %{public}d", WIFI_SVR_CMD_ADD_DEVICE_CONFIG, error); + return WIFI_OPT_FAILED; + } + + if (owner.exception) { + return WIFI_OPT_FAILED; + } + return ErrCode(owner.retCode); +} + +ErrCode WifiDeviceProxy::UpdateDeviceConfig(const WifiDeviceConfig &config, int &result) +{ + if (remoteDied_ || remote_ == nullptr) { + WIFI_LOGE("failed to %{public}s, remoteDied_: %{public}d, remote_: %{public}d", + __func__, remoteDied_, remote_ == nullptr); + return WIFI_OPT_FAILED; + } + + IpcIo req; + char data[IPC_DATA_SIZE_BIG]; + struct IpcOwner owner = {.exception = -1, .retCode = 0, .variable = nullptr}; + + IpcIoInit(&req, data, IPC_DATA_SIZE_BIG, MAX_IPC_OBJ_COUNT); + (void)WriteInt32(&req, 0); + WriteDeviceConfig(config, req); + owner.variable = &result; + owner.funcId = WIFI_SVR_CMD_UPDATE_DEVICE_CONFIG; + int error = remote_->Invoke(remote_, WIFI_SVR_CMD_UPDATE_DEVICE_CONFIG, &req, &owner, IpcCallback); + if (error != EC_SUCCESS) { + WIFI_LOGE("Set Attr(%{public}d) failed,error code is %{public}d", WIFI_SVR_CMD_UPDATE_DEVICE_CONFIG, error); + return WIFI_OPT_FAILED; + } + + if (owner.exception) { + return WIFI_OPT_FAILED; + } + return ErrCode(owner.retCode); +} + +ErrCode WifiDeviceProxy::RemoveDevice(int networkId) +{ + if (remoteDied_ || remote_ == nullptr) { + WIFI_LOGE("failed to %{public}s, remoteDied_: %{public}d, remote_: %{public}d", + __func__, remoteDied_, remote_ == nullptr); + return WIFI_OPT_FAILED; + } + + IpcIo req; + char data[IPC_DATA_SIZE_SMALL]; + struct IpcOwner owner = {.exception = -1, .retCode = 0, .variable = nullptr}; + + IpcIoInit(&req, data, IPC_DATA_SIZE_SMALL, MAX_IPC_OBJ_COUNT); + (void)WriteInt32(&req, 0); + (void)WriteInt32(&req, networkId); + owner.funcId = WIFI_SVR_CMD_REMOVE_DEVICE_CONFIG; + int error = remote_->Invoke(remote_, WIFI_SVR_CMD_REMOVE_DEVICE_CONFIG, &req, &owner, IpcCallback); + if (error != EC_SUCCESS) { + WIFI_LOGE("Set Attr(%{public}d) failed,error code is %{public}d", WIFI_SVR_CMD_REMOVE_DEVICE_CONFIG, error); + return WIFI_OPT_FAILED; + } + + if (owner.exception) { + return WIFI_OPT_FAILED; + } + return ErrCode(owner.retCode); +} + +ErrCode WifiDeviceProxy::RemoveAllDevice() +{ + if (remoteDied_ || remote_ == nullptr) { + WIFI_LOGE("failed to %{public}s, remoteDied_: %{public}d, remote_: %{public}d", + __func__, remoteDied_, remote_ == nullptr); + return WIFI_OPT_FAILED; + } + + IpcIo req; + char data[IPC_DATA_SIZE_SMALL]; + struct IpcOwner owner = {.exception = -1, .retCode = 0, .variable = nullptr}; + + IpcIoInit(&req, data, IPC_DATA_SIZE_SMALL, MAX_IPC_OBJ_COUNT); + (void)WriteInt32(&req, 0); + owner.funcId = WIFI_SVR_CMD_REMOVE_ALL_DEVICE_CONFIG; + int error = remote_->Invoke(remote_, WIFI_SVR_CMD_REMOVE_ALL_DEVICE_CONFIG, &req, &owner, IpcCallback); + if (error != EC_SUCCESS) { + WIFI_LOGE("Set Attr(%{public}d) failed,error code is %{public}d", WIFI_SVR_CMD_REMOVE_ALL_DEVICE_CONFIG, error); + return WIFI_OPT_FAILED; + } + + if (owner.exception) { + return WIFI_OPT_FAILED; + } + return ErrCode(owner.retCode); +} + +ErrCode WifiDeviceProxy::GetDeviceConfigs(std::vector &result, bool isCandidate) +{ + if (remoteDied_ || remote_ == nullptr) { + WIFI_LOGE("failed to %{public}s, remoteDied_: %{public}d, remote_: %{public}d", + __func__, remoteDied_, remote_ == nullptr); + return WIFI_OPT_FAILED; + } + + IpcIo req; + char data[IPC_DATA_SIZE_SMALL]; + struct IpcOwner owner = {.exception = -1, .retCode = 0, .variable = nullptr}; + + IpcIoInit(&req, data, IPC_DATA_SIZE_SMALL, MAX_IPC_OBJ_COUNT); + (void)WriteInt32(&req, 0); + (void)WriteBool(&req, isCandidate); + owner.variable = &result; + owner.funcId = WIFI_SVR_CMD_GET_DEVICE_CONFIGS; + int error = remote_->Invoke(remote_, WIFI_SVR_CMD_GET_DEVICE_CONFIGS, &req, &owner, IpcCallback); + if (error != EC_SUCCESS) { + WIFI_LOGE("Set Attr(%{public}d) failed,error code is %{public}d", WIFI_SVR_CMD_GET_DEVICE_CONFIGS, error); + return WIFI_OPT_FAILED; + } + + if (owner.exception) { + return WIFI_OPT_FAILED; + } + + return ErrCode(owner.retCode); +} + +ErrCode WifiDeviceProxy::EnableDeviceConfig(int networkId, bool attemptEnable) +{ + if (remoteDied_ || remote_ == nullptr) { + WIFI_LOGE("failed to %{public}s, remoteDied_: %{public}d, remote_: %{public}d", + __func__, remoteDied_, remote_ == nullptr); + return WIFI_OPT_FAILED; + } + + IpcIo req; + char data[IPC_DATA_SIZE_SMALL]; + struct IpcOwner owner = {.exception = -1, .retCode = 0, .variable = nullptr}; + + IpcIoInit(&req, data, IPC_DATA_SIZE_SMALL, MAX_IPC_OBJ_COUNT); + (void)WriteInt32(&req, 0); + (void)WriteInt32(&req, networkId); + (void)WriteInt32(&req, attemptEnable); + owner.funcId = WIFI_SVR_CMD_ENABLE_DEVICE; + int error = remote_->Invoke(remote_, WIFI_SVR_CMD_ENABLE_DEVICE, &req, &owner, IpcCallback); + if (error != EC_SUCCESS) { + WIFI_LOGE("Set Attr(%{public}d) failed,error code is %{public}d", WIFI_SVR_CMD_ENABLE_DEVICE, error); + return WIFI_OPT_FAILED; + } + + if (owner.exception) { + return WIFI_OPT_FAILED; + } + return ErrCode(owner.retCode); +} + +ErrCode WifiDeviceProxy::DisableDeviceConfig(int networkId) +{ + if (remoteDied_ || remote_ == nullptr) { + WIFI_LOGE("failed to %{public}s, remoteDied_: %{public}d, remote_: %{public}d", + __func__, remoteDied_, remote_ == nullptr); + return WIFI_OPT_FAILED; + } + + IpcIo req; + char data[IPC_DATA_SIZE_SMALL]; + struct IpcOwner owner = {.exception = -1, .retCode = 0, .variable = nullptr}; + + IpcIoInit(&req, data, IPC_DATA_SIZE_SMALL, MAX_IPC_OBJ_COUNT); + (void)WriteInt32(&req, 0); + (void)WriteInt32(&req, networkId); + owner.funcId = WIFI_SVR_CMD_DISABLE_DEVICE; + int error = remote_->Invoke(remote_, WIFI_SVR_CMD_DISABLE_DEVICE, &req, &owner, IpcCallback); + if (error != EC_SUCCESS) { + WIFI_LOGE("Set Attr(%{public}d) failed,error code is %{public}d", WIFI_SVR_CMD_DISABLE_DEVICE, error); + return WIFI_OPT_FAILED; + } + + if (owner.exception) { + return WIFI_OPT_FAILED; + } + return ErrCode(owner.retCode); +} + +ErrCode WifiDeviceProxy::ConnectToNetwork(int networkId, bool isCandidate) +{ + if (remoteDied_ || remote_ == nullptr) { + WIFI_LOGE("failed to %{public}s, remoteDied_: %{public}d, remote_: %{public}d", + __func__, remoteDied_, remote_ == nullptr); + return WIFI_OPT_FAILED; + } + + IpcIo req; + char data[IPC_DATA_SIZE_SMALL]; + struct IpcOwner owner = {.exception = -1, .retCode = 0, .variable = nullptr}; + + IpcIoInit(&req, data, IPC_DATA_SIZE_SMALL, MAX_IPC_OBJ_COUNT); + (void)WriteInt32(&req, 0); + (void)WriteBool(&req, isCandidate); + (void)WriteInt32(&req, networkId); + owner.funcId = WIFI_SVR_CMD_CONNECT_TO; + int error = remote_->Invoke(remote_, WIFI_SVR_CMD_CONNECT_TO, &req, &owner, IpcCallback); + if (error != EC_SUCCESS) { + WIFI_LOGE("Set Attr(%{public}d) failed,error code is %{public}d", WIFI_SVR_CMD_CONNECT_TO, error); + return WIFI_OPT_FAILED; + } + + if (owner.exception) { + return WIFI_OPT_FAILED; + } + return ErrCode(owner.retCode); +} + +ErrCode WifiDeviceProxy::ConnectToDevice(const WifiDeviceConfig &config) +{ + if (remoteDied_ || remote_ == nullptr) { + WIFI_LOGE("failed to %{public}s, remoteDied_: %{public}d, remote_: %{public}d", + __func__, remoteDied_, remote_ == nullptr); + return WIFI_OPT_FAILED; + } + + IpcIo req; + char data[IPC_DATA_SIZE_BIG]; + struct IpcOwner owner = {.exception = -1, .retCode = 0, .variable = nullptr}; + + IpcIoInit(&req, data, IPC_DATA_SIZE_BIG, MAX_IPC_OBJ_COUNT); + (void)WriteInt32(&req, 0); + WriteDeviceConfig(config, req); + owner.funcId = WIFI_SVR_CMD_CONNECT2_TO; + int error = remote_->Invoke(remote_, WIFI_SVR_CMD_CONNECT2_TO, &req, &owner, IpcCallback); + if (error != EC_SUCCESS) { + WIFI_LOGE("Set Attr(%{public}d) failed,error code is %{public}d", WIFI_SVR_CMD_CONNECT2_TO, error); + return WIFI_OPT_FAILED; + } + + if (owner.exception) { + return WIFI_OPT_FAILED; + } + return ErrCode(owner.retCode); +} + +bool WifiDeviceProxy::IsConnected() +{ + if (remoteDied_ || remote_ == nullptr) { + WIFI_LOGE("failed to %{public}s, remoteDied_: %{public}d, remote_: %{public}d", + __func__, remoteDied_, remote_ == nullptr); + return WIFI_OPT_FAILED; + } + + bool result = false; + IpcIo req; + char data[IPC_DATA_SIZE_SMALL]; + struct IpcOwner owner = {.exception = -1, .retCode = 0, .variable = nullptr}; + + IpcIoInit(&req, data, IPC_DATA_SIZE_SMALL, MAX_IPC_OBJ_COUNT); + (void)WriteInt32(&req, 0); + owner.variable = &result; + owner.funcId = WIFI_SVR_CMD_IS_WIFI_CONNECTED; + int error = remote_->Invoke(remote_, WIFI_SVR_CMD_IS_WIFI_CONNECTED, &req, &owner, IpcCallback); + if (error != EC_SUCCESS) { + WIFI_LOGE("Set Attr(%{public}d) failed,error code is %{public}d", WIFI_SVR_CMD_IS_WIFI_CONNECTED, error); + return WIFI_OPT_FAILED; + } + + if (owner.exception) { + return false; + } + return result; +} + +ErrCode WifiDeviceProxy::ReConnect() +{ + if (remoteDied_ || remote_ == nullptr) { + WIFI_LOGE("failed to %{public}s, remoteDied_: %{public}d, remote_: %{public}d", + __func__, remoteDied_, remote_ == nullptr); + return WIFI_OPT_FAILED; + } + + IpcIo req; + char data[IPC_DATA_SIZE_SMALL]; + struct IpcOwner owner = {.exception = -1, .retCode = 0, .variable = nullptr}; + + IpcIoInit(&req, data, IPC_DATA_SIZE_SMALL, MAX_IPC_OBJ_COUNT); + (void)WriteInt32(&req, 0); + owner.funcId = WIFI_SVR_CMD_RECONNECT; + int error = remote_->Invoke(remote_, WIFI_SVR_CMD_RECONNECT, &req, &owner, IpcCallback); + if (error != EC_SUCCESS) { + WIFI_LOGE("Set Attr(%{public}d) failed,error code is %{public}d", WIFI_SVR_CMD_RECONNECT, error); + return WIFI_OPT_FAILED; + } + + if (owner.exception) { + return WIFI_OPT_FAILED; + } + return ErrCode(owner.retCode); +} + +ErrCode WifiDeviceProxy::ReAssociate(void) +{ + if (remoteDied_ || remote_ == nullptr) { + WIFI_LOGE("failed to %{public}s, remoteDied_: %{public}d, remote_: %{public}d", + __func__, remoteDied_, remote_ == nullptr); + return WIFI_OPT_FAILED; + } + + IpcIo req; + char data[IPC_DATA_SIZE_SMALL]; + struct IpcOwner owner = {.exception = -1, .retCode = 0, .variable = nullptr}; + + IpcIoInit(&req, data, IPC_DATA_SIZE_SMALL, MAX_IPC_OBJ_COUNT); + (void)WriteInt32(&req, 0); + owner.funcId = WIFI_SVR_CMD_REASSOCIATE; + int error = remote_->Invoke(remote_, WIFI_SVR_CMD_REASSOCIATE, &req, &owner, IpcCallback); + if (error != EC_SUCCESS) { + WIFI_LOGE("Set Attr(%{public}d) failed,error code is %{public}d", WIFI_SVR_CMD_REASSOCIATE, error); + return WIFI_OPT_FAILED; + } + + if (owner.exception) { + return WIFI_OPT_FAILED; + } + return ErrCode(owner.retCode); +} + +ErrCode WifiDeviceProxy::Disconnect(void) +{ + if (remoteDied_ || remote_ == nullptr) { + WIFI_LOGE("failed to %{public}s, remoteDied_: %{public}d, remote_: %{public}d", + __func__, remoteDied_, remote_ == nullptr); + return WIFI_OPT_FAILED; + } + + IpcIo req; + char data[IPC_DATA_SIZE_SMALL]; + struct IpcOwner owner = {.exception = -1, .retCode = 0, .variable = nullptr}; + + IpcIoInit(&req, data, IPC_DATA_SIZE_SMALL, MAX_IPC_OBJ_COUNT); + (void)WriteInt32(&req, 0); + owner.funcId = WIFI_SVR_CMD_DISCONNECT; + int error = remote_->Invoke(remote_, WIFI_SVR_CMD_DISCONNECT, &req, &owner, IpcCallback); + if (error != EC_SUCCESS) { + WIFI_LOGE("Set Attr(%{public}d) failed,error code is %{public}d", WIFI_SVR_CMD_DISCONNECT, error); + return WIFI_OPT_FAILED; + } + + if (owner.exception) { + return WIFI_OPT_FAILED; + } + return ErrCode(owner.retCode); +} + +ErrCode WifiDeviceProxy::StartWps(const WpsConfig &config) +{ + if (remoteDied_ || remote_ == nullptr) { + WIFI_LOGE("failed to %{public}s, remoteDied_: %{public}d, remote_: %{public}d", + __func__, remoteDied_, remote_ == nullptr); + return WIFI_OPT_FAILED; + } + + IpcIo req; + char data[IPC_DATA_SIZE_SMALL]; + struct IpcOwner owner = {.exception = -1, .retCode = 0, .variable = nullptr}; + + IpcIoInit(&req, data, IPC_DATA_SIZE_SMALL, MAX_IPC_OBJ_COUNT); + (void)WriteInt32(&req, 0); + (void)WriteInt32(&req, static_cast(config.setup)); + (void)WriteString(&req, config.pin.c_str()); + (void)WriteString(&req, config.bssid.c_str()); + owner.funcId = WIFI_SVR_CMD_START_WPS; + int error = remote_->Invoke(remote_, WIFI_SVR_CMD_START_WPS, &req, &owner, IpcCallback); + if (error != EC_SUCCESS) { + WIFI_LOGE("Set Attr(%{public}d) failed,error code is %{public}d", WIFI_SVR_CMD_START_WPS, error); + return WIFI_OPT_FAILED; + } + + if (owner.exception) { + return WIFI_OPT_FAILED; + } + return ErrCode(owner.retCode); +} + +ErrCode WifiDeviceProxy::CancelWps(void) +{ + if (remoteDied_ || remote_ == nullptr) { + WIFI_LOGE("failed to %{public}s, remoteDied_: %{public}d, remote_: %{public}d", + __func__, remoteDied_, remote_ == nullptr); + return WIFI_OPT_FAILED; + } + + IpcIo req; + char data[IPC_DATA_SIZE_SMALL]; + struct IpcOwner owner = {.exception = -1, .retCode = 0, .variable = nullptr}; + + IpcIoInit(&req, data, IPC_DATA_SIZE_SMALL, MAX_IPC_OBJ_COUNT); + (void)WriteInt32(&req, 0); + owner.funcId = WIFI_SVR_CMD_CANCEL_WPS; + int error = remote_->Invoke(remote_, WIFI_SVR_CMD_CANCEL_WPS, &req, &owner, IpcCallback); + if (error != EC_SUCCESS) { + WIFI_LOGE("Set Attr(%{public}d) failed,error code is %{public}d", WIFI_SVR_CMD_CANCEL_WPS, error); + return WIFI_OPT_FAILED; + } + + if (owner.exception) { + return WIFI_OPT_FAILED; + } + return ErrCode(owner.retCode); +} + +ErrCode WifiDeviceProxy::IsWifiActive(bool &bActive) +{ + if (remoteDied_ || remote_ == nullptr) { + WIFI_LOGE("failed to %{public}s, remoteDied_: %{public}d, remote_: %{public}d", + __func__, remoteDied_, remote_ == nullptr); + return WIFI_OPT_FAILED; + } + + IpcIo req; + char data[IPC_DATA_SIZE_SMALL]; + struct IpcOwner owner = {.exception = -1, .retCode = 0, .variable = nullptr}; + + IpcIoInit(&req, data, IPC_DATA_SIZE_SMALL, MAX_IPC_OBJ_COUNT); + (void)WriteInt32(&req, 0); + owner.variable = &bActive; + owner.funcId = WIFI_SVR_CMD_IS_WIFI_ACTIVE; + int error = remote_->Invoke(remote_, WIFI_SVR_CMD_IS_WIFI_ACTIVE, &req, &owner, IpcCallback); + if (error != EC_SUCCESS) { + WIFI_LOGE("Set Attr(%{public}d) failed,error code is %{public}d", WIFI_SVR_CMD_IS_WIFI_ACTIVE, error); + return WIFI_OPT_FAILED; + } + + if (owner.exception) { + return WIFI_OPT_FAILED; + } + return ErrCode(owner.retCode); +} + +ErrCode WifiDeviceProxy::GetWifiState(int &state) +{ + if (remoteDied_ || remote_ == nullptr) { + WIFI_LOGE("failed to %{public}s, remoteDied_: %{public}d, remote_: %{public}d", + __func__, remoteDied_, remote_ == nullptr); + return WIFI_OPT_FAILED; + } + + IpcIo req; + char data[IPC_DATA_SIZE_SMALL]; + struct IpcOwner owner = {.exception = -1, .retCode = 0, .variable = nullptr}; + + IpcIoInit(&req, data, IPC_DATA_SIZE_SMALL, MAX_IPC_OBJ_COUNT); + (void)WriteInt32(&req, 0); + owner.variable = &state; + owner.funcId = WIFI_SVR_CMD_GET_WIFI_STATE; + int error = remote_->Invoke(remote_, WIFI_SVR_CMD_GET_WIFI_STATE, &req, &owner, IpcCallback); + if (error != EC_SUCCESS) { + WIFI_LOGE("Set Attr(%{public}d) failed,error code is %{public}d", WIFI_SVR_CMD_GET_WIFI_STATE, error); + return WIFI_OPT_FAILED; + } + + if (owner.exception) { + return WIFI_OPT_FAILED; + } + return ErrCode(owner.retCode); +} + +ErrCode WifiDeviceProxy::GetLinkedInfo(WifiLinkedInfo &info) +{ + if (remoteDied_ || remote_ == nullptr) { + WIFI_LOGE("failed to %{public}s, remoteDied_: %{public}d, remote_: %{public}d", + __func__, remoteDied_, remote_ == nullptr); + return WIFI_OPT_FAILED; + } + + IpcIo req; + char data[IPC_DATA_SIZE_SMALL]; + struct IpcOwner owner = {.exception = -1, .retCode = 0, .variable = nullptr}; + + IpcIoInit(&req, data, IPC_DATA_SIZE_SMALL, MAX_IPC_OBJ_COUNT); + (void)WriteInt32(&req, 0); + owner.variable = &info; + owner.funcId = WIFI_SVR_CMD_GET_LINKED_INFO; + int error = remote_->Invoke(remote_, WIFI_SVR_CMD_GET_LINKED_INFO, &req, &owner, IpcCallback); + if (error != EC_SUCCESS) { + WIFI_LOGE("Set Attr(%{public}d) failed,error code is %{public}d", WIFI_SVR_CMD_GET_LINKED_INFO, error); + return WIFI_OPT_FAILED; + } + + if (owner.exception) { + return WIFI_OPT_FAILED; + } + return ErrCode(owner.retCode); +} + +ErrCode WifiDeviceProxy::GetIpInfo(IpInfo &info) +{ + if (remoteDied_ || remote_ == nullptr) { + WIFI_LOGE("failed to %{public}s, remoteDied_: %{public}d, remote_: %{public}d", + __func__, remoteDied_, remote_ == nullptr); + return WIFI_OPT_FAILED; + } + + IpcIo req; + char data[IPC_DATA_SIZE_SMALL]; + struct IpcOwner owner = {.exception = -1, .retCode = 0, .variable = nullptr}; + + IpcIoInit(&req, data, IPC_DATA_SIZE_SMALL, MAX_IPC_OBJ_COUNT); + (void)WriteInt32(&req, 0); + owner.variable = &info; + owner.funcId = WIFI_SVR_CMD_GET_DHCP_INFO; + int error = remote_->Invoke(remote_, WIFI_SVR_CMD_GET_DHCP_INFO, &req, &owner, IpcCallback); + if (error != EC_SUCCESS) { + WIFI_LOGE("Set Attr(%{public}d) failed,error code is %{public}d", WIFI_SVR_CMD_GET_DHCP_INFO, error); + return WIFI_OPT_FAILED; + } + + if (owner.exception) { + return WIFI_OPT_FAILED; + } + return ErrCode(owner.retCode); +} + +ErrCode WifiDeviceProxy::SetCountryCode(const std::string &countryCode) +{ + if (remoteDied_ || remote_ == nullptr) { + WIFI_LOGE("failed to %{public}s, remoteDied_: %{public}d, remote_: %{public}d", + __func__, remoteDied_, remote_ == nullptr); + return WIFI_OPT_FAILED; + } + + IpcIo req; + char data[IPC_DATA_SIZE_SMALL]; + struct IpcOwner owner = {.exception = -1, .retCode = 0, .variable = nullptr}; + + IpcIoInit(&req, data, IPC_DATA_SIZE_SMALL, MAX_IPC_OBJ_COUNT); + (void)WriteInt32(&req, 0); + (void)WriteString(&req, countryCode.c_str()); + owner.funcId = WIFI_SVR_CMD_SET_COUNTRY_CODE; + int error = remote_->Invoke(remote_, WIFI_SVR_CMD_SET_COUNTRY_CODE, &req, &owner, IpcCallback); + if (error != EC_SUCCESS) { + WIFI_LOGE("Set Attr(%{public}d) failed,error code is %{public}d", WIFI_SVR_CMD_SET_COUNTRY_CODE, error); + return WIFI_OPT_FAILED; + } + + if (owner.exception) { + return WIFI_OPT_FAILED; + } + return ErrCode(owner.retCode); +} + +ErrCode WifiDeviceProxy::GetCountryCode(std::string &countryCode) +{ + if (remoteDied_ || remote_ == nullptr) { + WIFI_LOGE("failed to %{public}s, remoteDied_: %{public}d, remote_: %{public}d", + __func__, remoteDied_, remote_ == nullptr); + return WIFI_OPT_FAILED; + } + + IpcIo req; + char data[IPC_DATA_SIZE_SMALL]; + struct IpcOwner owner = {.exception = -1, .retCode = 0, .variable = nullptr}; + + IpcIoInit(&req, data, IPC_DATA_SIZE_SMALL, MAX_IPC_OBJ_COUNT); + (void)WriteInt32(&req, 0); + owner.variable = &countryCode; + owner.funcId = WIFI_SVR_CMD_GET_COUNTRY_CODE; + int error = remote_->Invoke(remote_, WIFI_SVR_CMD_GET_COUNTRY_CODE, &req, &owner, IpcCallback); + if (error != EC_SUCCESS) { + WIFI_LOGE("Set Attr(%{public}d) failed,error code is %{public}d", WIFI_SVR_CMD_GET_COUNTRY_CODE, error); + return WIFI_OPT_FAILED; + } + + if (owner.exception) { + return WIFI_OPT_FAILED; + } + return ErrCode(owner.retCode); +} + +ErrCode WifiDeviceProxy::RegisterCallBack(const std::shared_ptr &callback) +{ + if (remoteDied_ || remote_ == nullptr) { + WIFI_LOGE("failed to %{public}s, remoteDied_: %{public}d, remote_: %{public}d", + __func__, remoteDied_, remote_ == nullptr); + return WIFI_OPT_FAILED; + } + WIFI_LOGD("RegisterCallBack start!"); + g_objStub.func = AsyncCallback; + g_objStub.args = nullptr; + g_objStub.isRemote = false; + + g_sid.handle = IPC_INVALID_HANDLE; + g_sid.token = SERVICE_TYPE_ANONYMOUS; + g_sid.cookie = (uintptr_t)&g_objStub; + + IpcIo req; + char data[IPC_DATA_SIZE_SMALL]; + struct IpcOwner owner = {.exception = -1, .retCode = 0, .variable = nullptr}; + + IpcIoInit(&req, data, IPC_DATA_SIZE_SMALL, MAX_IPC_OBJ_COUNT); + (void)WriteInt32(&req, 0); + bool writeRemote = WriteRemoteObject(&req, &g_sid); + if (!writeRemote) { + WIFI_LOGE("WriteRemoteObject failed."); + return WIFI_OPT_FAILED; + } + + owner.funcId = WIFI_SVR_CMD_REGISTER_CALLBACK_CLIENT; + int error = remote_->Invoke(remote_, WIFI_SVR_CMD_REGISTER_CALLBACK_CLIENT, &req, &owner, IpcCallback); + if (error != EC_SUCCESS) { + WIFI_LOGE("Set Attr(%{public}d) failed, code is %{public}d", WIFI_SVR_CMD_REGISTER_CALLBACK_CLIENT, error); + return WIFI_OPT_FAILED; + } + + if (owner.exception) { + return WIFI_OPT_FAILED; + } + g_deviceCallBackStub.RegisterUserCallBack(callback); + return ErrCode(owner.retCode); +} + +ErrCode WifiDeviceProxy::GetSignalLevel(const int &rssi, const int &band, int &level) +{ + if (remoteDied_ || remote_ == nullptr) { + WIFI_LOGE("failed to %{public}s, remoteDied_: %{public}d, remote_: %{public}d", + __func__, remoteDied_, remote_ == nullptr); + return WIFI_OPT_FAILED; + } + + IpcIo req; + char data[IPC_DATA_SIZE_SMALL]; + struct IpcOwner owner = {.exception = -1, .retCode = 0, .variable = nullptr}; + + IpcIoInit(&req, data, IPC_DATA_SIZE_SMALL, MAX_IPC_OBJ_COUNT); + (void)WriteInt32(&req, 0); + (void)WriteInt32(&req, rssi); + (void)WriteInt32(&req, band); + owner.variable = &level; + owner.funcId = WIFI_SVR_CMD_GET_SIGNAL_LEVEL; + int error = remote_->Invoke(remote_, WIFI_SVR_CMD_GET_SIGNAL_LEVEL, &req, &owner, IpcCallback); + if (error != EC_SUCCESS) { + WIFI_LOGE("Set Attr(%{public}d) failed,error code is %{public}d", WIFI_SVR_CMD_GET_SIGNAL_LEVEL, error); + return WIFI_OPT_FAILED; + } + + if (owner.exception) { + return WIFI_OPT_FAILED; + } + return ErrCode(owner.retCode); +} + +ErrCode WifiDeviceProxy::GetSupportedFeatures(long &features) +{ + if (remoteDied_ || remote_ == nullptr) { + WIFI_LOGE("failed to %{public}s, remoteDied_: %{public}d, remote_: %{public}d", + __func__, remoteDied_, remote_ == nullptr); + return WIFI_OPT_FAILED; + } + + IpcIo req; + char data[IPC_DATA_SIZE_SMALL]; + struct IpcOwner owner = {.exception = -1, .retCode = 0, .variable = nullptr}; + + IpcIoInit(&req, data, IPC_DATA_SIZE_SMALL, MAX_IPC_OBJ_COUNT); + (void)WriteInt32(&req, 0); + owner.variable = &features; + owner.funcId = WIFI_SVR_CMD_GET_SUPPORTED_FEATURES; + int error = remote_->Invoke(remote_, WIFI_SVR_CMD_GET_SUPPORTED_FEATURES, &req, &owner, IpcCallback); + if (error != EC_SUCCESS) { + WIFI_LOGE("Set Attr(%{public}d) failed,error code is %{public}d", WIFI_SVR_CMD_GET_SUPPORTED_FEATURES, error); + return WIFI_OPT_FAILED; + } + + if (owner.exception) { + return WIFI_OPT_FAILED; + } + return ErrCode(owner.retCode); +} + +ErrCode WifiDeviceProxy::GetDeviceMacAddress(std::string &result) +{ + if (remoteDied_ || remote_ == nullptr) { + WIFI_LOGE("failed to %{public}s, remoteDied_: %{public}d, remote_: %{public}d", + __func__, remoteDied_, remote_ == nullptr); + return WIFI_OPT_FAILED; + } + + IpcIo req; + char data[IPC_DATA_SIZE_SMALL]; + struct IpcOwner owner = {.exception = -1, .retCode = 0, .variable = nullptr}; + + IpcIoInit(&req, data, IPC_DATA_SIZE_SMALL, MAX_IPC_OBJ_COUNT); + (void)WriteInt32(&req, 0); + owner.variable = &result; + owner.funcId = WIFI_SVR_CMD_GET_DERVICE_MAC_ADD; + int error = remote_->Invoke(remote_, WIFI_SVR_CMD_GET_DERVICE_MAC_ADD, &req, &owner, IpcCallback); + if (error != EC_SUCCESS) { + WIFI_LOGE("Set Attr(%{public}d) failed", WIFI_SVR_CMD_GET_DERVICE_MAC_ADD); + return WIFI_OPT_FAILED; + } + + if (owner.exception) { + return WIFI_OPT_FAILED; + } + return ErrCode(owner.retCode); +} + +bool WifiDeviceProxy::SetLowLatencyMode(bool enabled) +{ + if (remoteDied_ || remote_ == nullptr) { + WIFI_LOGE("failed to %{public}s, remoteDied_: %{public}d, remote_: %{public}d", + __func__, remoteDied_, remote_ == nullptr); + return WIFI_OPT_FAILED; + } + + bool result = false; + IpcIo req; + char data[IPC_DATA_SIZE_SMALL]; + struct IpcOwner owner = {.exception = -1, .retCode = 0, .variable = nullptr}; + + IpcIoInit(&req, data, IPC_DATA_SIZE_SMALL, MAX_IPC_OBJ_COUNT); + (void)WriteInt32(&req, 0); + (void)WriteBool(&req, enabled); + owner.variable = &result; + owner.funcId = WIFI_SVR_CMD_SET_LOW_LATENCY_MODE; + int error = remote_->Invoke(remote_, WIFI_SVR_CMD_SET_LOW_LATENCY_MODE, &req, &owner, IpcCallback); + if (error != EC_SUCCESS) { + WIFI_LOGE("Set Attr(%{public}d) failed,error code is %{public}d", WIFI_SVR_CMD_SET_LOW_LATENCY_MODE, error); + return WIFI_OPT_FAILED; + } + + if (owner.exception) { + return WIFI_OPT_FAILED; + } + return result; +} + +void WifiDeviceProxy::OnRemoteDied(void) +{ + WIFI_LOGW("Remote service is died!"); + remoteDied_ = true; + g_deviceCallBackStub.SetRemoteDied(true); +} +} // namespace Wifi +} // namespace OHOS diff --git a/wifi/frameworks/native/src/wifi_hid2d.cpp b/wifi/frameworks/native/src/wifi_hid2d.cpp new file mode 100644 index 0000000000000000000000000000000000000000..a130d6811596a340bf0c0c990e78b4fb158c60ef --- /dev/null +++ b/wifi/frameworks/native/src/wifi_hid2d.cpp @@ -0,0 +1,55 @@ +/* + * Copyright (C) 2022 Huawei Device Co., Ltd. + * 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 "wifi_hid2d.h" +#include "wifi_p2p_impl.h" +#include "wifi_logger.h" + +DEFINE_WIFILOG_LABEL("Hid2d"); + +namespace OHOS { +namespace Wifi { +std::unique_ptr Hid2d::CreateWifiHid2d(int systemAbilityId) +{ + std::unique_ptr impl = std::make_unique(systemAbilityId); + if (impl != nullptr) { + if (impl->Init()) { + WIFI_LOGI("new hid2d successfully!"); + return impl; + } + } + + WIFI_LOGE("new wifi hid2d failed"); + return nullptr; +} + +std::unique_ptr Hid2d::GetInstance(int systemAbilityId) +{ + std::unique_ptr impl = std::make_unique(systemAbilityId); + if (impl != nullptr) { + if (impl->Init()) { + WIFI_LOGI("init hid2d successfully!"); + return impl; + } + } + + WIFI_LOGE("new wifi hid2d failed"); + return nullptr; +} + +Hid2d::~Hid2d() +{} +} // namespace Wifi +} // namespace OHOS \ No newline at end of file diff --git a/wifi/frameworks/native/src/wifi_hid2d_msg.cpp b/wifi/frameworks/native/src/wifi_hid2d_msg.cpp new file mode 100644 index 0000000000000000000000000000000000000000..31021dc130b76d7155aa064c4377e20225ec5a42 --- /dev/null +++ b/wifi/frameworks/native/src/wifi_hid2d_msg.cpp @@ -0,0 +1,61 @@ +/* + * Copyright (C) 2022 Huawei Device Co., Ltd. + * 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 "wifi_hid2d_msg.h" +#include + +namespace OHOS { +namespace Wifi { + void Hid2dConnectConfig::SetSsid(const std::string& ssid) { + m_ssid = ssid; + } + + std::string Hid2dConnectConfig::GetSsid() const { + return m_ssid; + } + + void Hid2dConnectConfig::SetBssid(const std::string& bssid) { + m_bssid = bssid; + } + + std::string Hid2dConnectConfig::GetBssid() const { + return m_bssid; + } + + void Hid2dConnectConfig::SetPreSharedKey(const std::string& preSharedKey) { + m_preSharedKey = preSharedKey; + } + + std::string Hid2dConnectConfig::GetPreSharedKey() const { + return m_preSharedKey; + } + + void Hid2dConnectConfig::SetFrequency(const int frequency) { + m_frequency = frequency; + } + + int Hid2dConnectConfig::GetFrequency() const { + return m_frequency; + } + + void Hid2dConnectConfig::SetDhcpMode(const DhcpMode dhcpMode) { + m_dhcpMode = dhcpMode; + } + + DhcpMode Hid2dConnectConfig::GetDhcpMode() const { + return m_dhcpMode; + } +} // namespace Wifi +} // namespace OHOS diff --git a/interfaces/innerkits/native_cpp/wifi_standard/src/wifi_hotspot.cpp b/wifi/frameworks/native/src/wifi_hotspot.cpp similarity index 60% rename from interfaces/innerkits/native_cpp/wifi_standard/src/wifi_hotspot.cpp rename to wifi/frameworks/native/src/wifi_hotspot.cpp index 5bce45a5dc79b68adb56087a47590922455eb920..4a247ab9d6731847b967d6bea6917407ab0e891a 100644 --- a/interfaces/innerkits/native_cpp/wifi_standard/src/wifi_hotspot.cpp +++ b/wifi/frameworks/native/src/wifi_hotspot.cpp @@ -21,31 +21,43 @@ DEFINE_WIFILOG_HOTSPOT_LABEL("WifiHotspot"); namespace OHOS { namespace Wifi { -std::unique_ptr WifiHotspot::CreateWifiHotspot(int systemAbilityId) +std::unique_ptr WifiHotspot::CreateWifiHotspot(int systemAbilityId, int id) { + if (id >= AP_INSTANCE_MAX_NUM) { + WIFI_LOGE("the max obj id is %{public}d, current id is %{public}d", AP_INSTANCE_MAX_NUM, id); + return nullptr; + } + std::unique_ptr hotspot = std::make_unique(systemAbilityId); if (hotspot != nullptr) { - if (hotspot->Init()) { - WIFI_LOGI("succeeded"); + if (hotspot->Init(id)) { + WIFI_LOGI("ap obj id:%{public}d succeeded", id); return hotspot; } + WIFI_LOGE("init wifi hotspot id:%{public}d failed", id); } - WIFI_LOGE("new wifi hotspot failed"); + WIFI_LOGE("new wifi hotspot id:%{public}d failed, sa id:%{public}d", id, systemAbilityId); return nullptr; } -std::unique_ptr WifiHotspot::GetInstance(int systemAbilityId) +std::unique_ptr WifiHotspot::GetInstance(int systemAbilityId, int id) { + if (id >= AP_INSTANCE_MAX_NUM) { + WIFI_LOGE("the max obj id is %{public}d, current id is %{public}d", AP_INSTANCE_MAX_NUM, id); + return nullptr; + } + std::unique_ptr hotspot = std::make_unique(systemAbilityId); if (hotspot != nullptr) { - if (hotspot->Init()) { - WIFI_LOGI("hotspot init succeeded"); + if (hotspot->Init(id)) { + WIFI_LOGI("ap obj id:%{public}d succeeded", id); return hotspot; } + WIFI_LOGE("init wifi hotspot id:%{public}d failed", id); } - WIFI_LOGE("new wifi hotspot failed"); + WIFI_LOGE("new wifi hotspot id:%{public}d failed, sa id:%{public}d", id, systemAbilityId); return nullptr; } diff --git a/interfaces/innerkits/native_cpp/wifi_standard/src/wifi_hotspot_callback_stub.cpp b/wifi/frameworks/native/src/wifi_hotspot_callback_stub.cpp similarity index 82% rename from interfaces/innerkits/native_cpp/wifi_standard/src/wifi_hotspot_callback_stub.cpp rename to wifi/frameworks/native/src/wifi_hotspot_callback_stub.cpp index 1de0a6eca4d1aba78c3221f0337277191f0e8342..5ea421e189c812298ea349d79fbd20ef28e44c26 100644 --- a/interfaces/innerkits/native_cpp/wifi_standard/src/wifi_hotspot_callback_stub.cpp +++ b/wifi/frameworks/native/src/wifi_hotspot_callback_stub.cpp @@ -1,5 +1,5 @@ /* - * Copyright (C) 2021 Huawei Device Co., Ltd. + * Copyright (C) 2021-2022 Huawei Device Co., Ltd. * 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 @@ -14,9 +14,11 @@ */ #include "wifi_hotspot_callback_stub.h" +#include "define.h" +#include "wifi_hisysevent.h" #include "wifi_logger.h" #include "wifi_msg.h" -#include "define.h" +#include "wifi_errcode.h" DEFINE_WIFILOG_HOTSPOT_LABEL("WifiHotspotCallbackStub"); namespace OHOS { @@ -32,9 +34,15 @@ int WifiHotspotCallbackStub::OnRemoteRequest( { WIFI_LOGD("WifiHotspotCallbackStub::OnRemoteRequest!"); if (mRemoteDied) { - WIFI_LOGD("Failed to `%{public}s`,remote service is died!", __func__); + WIFI_LOGE("Failed to `%{public}s`,remote service is died!", __func__); return -1; } + + if (data.ReadInterfaceToken() != GetDescriptor()) { + WIFI_LOGE("Hotspot callback stub token verification error: %{public}d", code); + return WIFI_OPT_FAILED; + } + int exception = data.ReadInt32(); if (exception) { return -1; @@ -98,33 +106,36 @@ void WifiHotspotCallbackStub::RegisterCallBack(const sptr { if (callBack == nullptr) { WIFI_LOGD("RegisterCallBack:callBack is nullptr!"); + return; } userCallback_ = callBack; - return; } void WifiHotspotCallbackStub::OnHotspotStateChanged(int state) { - WIFI_LOGD("WifiHotspotCallbackStub::OnHotspotStateChanged"); + WIFI_LOGI("WifiHotspotCallbackStub::OnHotspotStateChanged, state:%{public}d.", state); if (userCallback_) { userCallback_->OnHotspotStateChanged(state); } + WriteWifiEventReceivedHiSysEvent(HISYS_HOTSPOT_STATE_CHANGE, state); } void WifiHotspotCallbackStub::OnHotspotStaJoin(const StationInfo &info) { - WIFI_LOGD("WifiHotspotCallbackStub::OnHotspotStaJoin"); + WIFI_LOGI("WifiHotspotCallbackStub::OnHotspotStaJoin"); if (userCallback_) { userCallback_->OnHotspotStaJoin(info); } + WriteWifiEventReceivedHiSysEvent(HISYS_HOTSPOT_STA_JOIN, HISYS_EVENT_DEFAULT_VALUE); } void WifiHotspotCallbackStub::OnHotspotStaLeave(const StationInfo &info) { - WIFI_LOGD("WifiHotspotCallbackStub::OnHotspotStaLeave"); + WIFI_LOGI("WifiHotspotCallbackStub::OnHotspotStaLeave"); if (userCallback_) { userCallback_->OnHotspotStaLeave(info); } + WriteWifiEventReceivedHiSysEvent(HISYS_HOTSPOT_STA_LEAVE, HISYS_EVENT_DEFAULT_VALUE); } bool WifiHotspotCallbackStub::IsRemoteDied() const diff --git a/interfaces/innerkits/native_cpp/wifi_standard/src/wifi_hotspot_callback_stub.h b/wifi/frameworks/native/src/wifi_hotspot_callback_stub.h similarity index 100% rename from interfaces/innerkits/native_cpp/wifi_standard/src/wifi_hotspot_callback_stub.h rename to wifi/frameworks/native/src/wifi_hotspot_callback_stub.h diff --git a/interfaces/innerkits/native_cpp/wifi_standard/src/wifi_hotspot_impl.cpp b/wifi/frameworks/native/src/wifi_hotspot_impl.cpp similarity index 68% rename from interfaces/innerkits/native_cpp/wifi_standard/src/wifi_hotspot_impl.cpp rename to wifi/frameworks/native/src/wifi_hotspot_impl.cpp index 612d21147365ac8be881a7160035af7c9b08034e..e53842f336d6f2887450ccdedc7a891754317fc0 100644 --- a/interfaces/innerkits/native_cpp/wifi_standard/src/wifi_hotspot_impl.cpp +++ b/wifi/frameworks/native/src/wifi_hotspot_impl.cpp @@ -1,5 +1,5 @@ /* - * Copyright (C) 2021 Huawei Device Co., Ltd. + * Copyright (C) 2021-2022 Huawei Device Co., Ltd. * 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 @@ -12,8 +12,15 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + #include "wifi_hotspot_impl.h" +#include +#include "wifi_hotspot_proxy.h" +#include "i_wifi_hotspot_mgr.h" +#include "iremote_broker.h" +#include "iremote_object.h" #include "iservice_registry.h" +#include "wifi_hotspot_mgr_proxy.h" #include "wifi_logger.h" DEFINE_WIFILOG_HOTSPOT_LABEL("WifiHotspotImpl"); @@ -34,7 +41,7 @@ WifiHotspotImpl::WifiHotspotImpl(int systemAbilityId) : systemAbilityId_(systemA WifiHotspotImpl::~WifiHotspotImpl() {} -bool WifiHotspotImpl::Init() +bool WifiHotspotImpl::Init(int id) { sptr sa_mgr = SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager(); if (sa_mgr == nullptr) { @@ -44,17 +51,27 @@ bool WifiHotspotImpl::Init() sptr object = sa_mgr->GetSystemAbility(systemAbilityId_); if (object == nullptr) { - WIFI_LOGE("failed to get HOTSPOT_SERVICE"); + WIFI_LOGE("failed to get hotspot mgr"); return false; } - client_ = iface_cast(object); - if (client_ == nullptr) { - client_ = new (std::nothrow) WifiHotspotProxy(object); + sptr hotspotMgr = iface_cast(object); + if (hotspotMgr == nullptr) { + hotspotMgr = new (std::nothrow) WifiHotspotMgrProxy(object); + } + if (hotspotMgr == nullptr) { + WIFI_LOGE("wifi hotspot init failed, %{public}d", systemAbilityId_); + return false; } + sptr service = hotspotMgr->GetWifiRemote(id); + if (service == nullptr) { + WIFI_LOGE("wifi device remote obj is null, %{public}d", id); + return false; + } + client_ = new (std::nothrow) WifiHotspotProxy(service); if (client_ == nullptr) { - WIFI_LOGE("wifi device init failed. %{public}d", systemAbilityId_); + WIFI_LOGE("wifi device id init failed., %{public}d", systemAbilityId_); return false; } @@ -72,11 +89,20 @@ bool WifiHotspotImpl::IsHotspotActive(void) return bActive; } +bool WifiHotspotImpl::IsHotspotDualBandSupported(void) +{ + RETURN_IF_FAIL(client_); + bool isSupported = false; + client_->IsHotspotDualBandSupported(isSupported); + return isSupported; +} + ErrCode WifiHotspotImpl::GetHotspotState(int &state) { RETURN_IF_FAIL(client_); return client_->GetHotspotState(state); } + ErrCode WifiHotspotImpl::GetHotspotConfig(HotspotConfig &config) { RETURN_IF_FAIL(client_); @@ -101,16 +127,16 @@ ErrCode WifiHotspotImpl::DisassociateSta(const StationInfo &info) return client_->DisassociateSta(info); } -ErrCode WifiHotspotImpl::EnableHotspot(void) +ErrCode WifiHotspotImpl::EnableHotspot(const ServiceType type) { RETURN_IF_FAIL(client_); - return client_->EnableHotspot(); + return client_->EnableHotspot(type); } -ErrCode WifiHotspotImpl::DisableHotspot(void) +ErrCode WifiHotspotImpl::DisableHotspot(const ServiceType type) { RETURN_IF_FAIL(client_); - return client_->DisableHotspot(); + return client_->DisableHotspot(type); } ErrCode WifiHotspotImpl::GetBlockLists(std::vector &infos) @@ -164,5 +190,23 @@ bool WifiHotspotImpl::IsFeatureSupported(long feature) } return ((tmpFeatures & feature) == feature); } + +ErrCode WifiHotspotImpl::GetSupportedPowerModel(std::set& setPowerModelList) +{ + RETURN_IF_FAIL(client_); + return client_->GetSupportedPowerModel(setPowerModelList); +} + +ErrCode WifiHotspotImpl::GetPowerModel(PowerModel& model) +{ + RETURN_IF_FAIL(client_); + return client_->GetPowerModel(model); +} + +ErrCode WifiHotspotImpl::SetPowerModel(const PowerModel& model) +{ + RETURN_IF_FAIL(client_); + return client_->SetPowerModel(model); +} } // namespace Wifi -} // namespace OHOS \ No newline at end of file +} // namespace OHOS diff --git a/interfaces/innerkits/native_cpp/wifi_standard/src/wifi_hotspot_impl.h b/wifi/frameworks/native/src/wifi_hotspot_impl.h similarity index 74% rename from interfaces/innerkits/native_cpp/wifi_standard/src/wifi_hotspot_impl.h rename to wifi/frameworks/native/src/wifi_hotspot_impl.h index d4f7c3040d7a675b3ac20314948a75f4580c730b..bea341c35c3fd17d7273425d14cf918854333f99 100644 --- a/interfaces/innerkits/native_cpp/wifi_standard/src/wifi_hotspot_impl.h +++ b/wifi/frameworks/native/src/wifi_hotspot_impl.h @@ -1,5 +1,5 @@ /* - * Copyright (C) 2021 Huawei Device Co., Ltd. + * Copyright (C) 2021-2022 Huawei Device Co., Ltd. * 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 @@ -16,8 +16,16 @@ #ifndef OHOS_WIFI_HOTSPOT_IMPL_H #define OHOS_WIFI_HOTSPOT_IMPL_H +#include +#include +#include +#include "i_wifi_hotspot.h" +#include "i_wifi_hotspot_callback.h" +#include "refbase.h" +#include "wifi_ap_msg.h" +#include "wifi_common_msg.h" +#include "wifi_errcode.h" #include "wifi_hotspot.h" -#include "wifi_hotspot_proxy.h" namespace OHOS { namespace Wifi { @@ -26,7 +34,12 @@ public: explicit WifiHotspotImpl(int systemAbilityId); ~WifiHotspotImpl(); - bool Init(); + /** + * @Description init ap client. + * + * @return bool - operation result + */ + bool Init(int id); /** * @Description Check whether the hotspot is active. @@ -35,6 +48,13 @@ public: */ bool IsHotspotActive(void) override; + /** + * @Description Check whether the hotspot supports dual band. + * + * @return bool - operation result + */ + bool IsHotspotDualBandSupported(void) override; + /** * @Description Get the Hotspot Config object * @@ -78,16 +98,18 @@ public: /** * @Description Enable Hotspot * + * @param type - service type * @return ErrCode - operation result */ - ErrCode EnableHotspot(void) override; + ErrCode EnableHotspot(const ServiceType type = ServiceType::DEFAULT) override; /** * @Description Disable Hotspot * + * @param type - service type * @return ErrCode - operation result */ - ErrCode DisableHotspot(void) override; + ErrCode DisableHotspot(const ServiceType type = ServiceType::DEFAULT) override; /** * @Description Get the Block Lists object @@ -154,10 +176,34 @@ public: * @return false - unsupported */ bool IsFeatureSupported(long feature) override; + + /** + * @Description Get supported power model list + * + * @param setPowerModelList - supported power model list + * @return ErrCode - operation result + */ + ErrCode GetSupportedPowerModel(std::set& setPowerModelList) override; + + /** + * @Description Get power model + * + * @param model - current power model + * @return ErrCode - operation result + */ + ErrCode GetPowerModel(PowerModel& model) override; + + /** + * @Description Get supported power model list + * + * @param model - the model to be set + * @return ErrCode - operation result + */ + ErrCode SetPowerModel(const PowerModel& model) override; private: int systemAbilityId_; sptr client_; }; } // namespace Wifi } // namespace OHOS -#endif \ No newline at end of file +#endif diff --git a/wifi/frameworks/native/src/wifi_hotspot_mgr_proxy.cpp b/wifi/frameworks/native/src/wifi_hotspot_mgr_proxy.cpp new file mode 100644 index 0000000000000000000000000000000000000000..db48d5a9ee5b2d2ff5151709cac5c71f73bdf788 --- /dev/null +++ b/wifi/frameworks/native/src/wifi_hotspot_mgr_proxy.cpp @@ -0,0 +1,44 @@ +/* + * Copyright (C) 2022 Huawei Device Co., Ltd. + * 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 "wifi_hotspot_mgr_proxy.h" +#include "ipc_types.h" +#include "message_option.h" +#include "message_parcel.h" +#include "wifi_logger.h" + +DEFINE_WIFILOG_HOTSPOT_LABEL("WifiHotspotMgrProxy"); +namespace OHOS { +namespace Wifi { +sptr WifiHotspotMgrProxy::GetWifiRemote(int id) +{ + MessageOption option; + MessageParcel data; + MessageParcel reply; + if (!data.WriteInterfaceToken(GetDescriptor())) { + WIFI_LOGE("Write interface token error: %{public}s", __func__); + return nullptr; + } + data.WriteInt32(id); + int error = Remote()->SendRequest(WIFI_MGR_GET_HOTSPOT_SERVICE, data, reply, option); + if (error != ERR_NONE) { + WIFI_LOGE("Get remote object id %{public}d failed,error code is %{public}d", id, error); + return nullptr; + } + + return reply.ReadRemoteObject(); +} +} // namespace Wifi +} // namespace OHOS diff --git a/wifi/frameworks/native/src/wifi_hotspot_mgr_proxy.h b/wifi/frameworks/native/src/wifi_hotspot_mgr_proxy.h new file mode 100644 index 0000000000000000000000000000000000000000..ec3db0e14e0057df710fa687195b32814c3624cf --- /dev/null +++ b/wifi/frameworks/native/src/wifi_hotspot_mgr_proxy.h @@ -0,0 +1,40 @@ +/* + * Copyright (C) 2022 Huawei Device Co., Ltd. + * 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 OHOS_WIFI_HOTSPOT_MGR_PROXY_H +#define OHOS_WIFI_HOTSPOT_MGR_PROXY_H + +#include "i_wifi_hotspot_mgr.h" +#include "iremote_broker.h" +#include "iremote_object.h" +#include "iremote_proxy.h" +#include "refbase.h" + +namespace OHOS { +namespace Wifi { +class WifiHotspotMgrProxy : public IRemoteProxy { +public: + explicit WifiHotspotMgrProxy(const sptr& remote) + : IRemoteProxy(remote) + {} + virtual ~WifiHotspotMgrProxy() + {} + sptr GetWifiRemote(int id) override; +private: + static BrokerDelegator g_delegator; +}; +} // namespace Wifi +} // namespace OHOS +#endif diff --git a/interfaces/innerkits/native_cpp/wifi_standard/src/wifi_hotspot_proxy.cpp b/wifi/frameworks/native/src/wifi_hotspot_proxy.cpp similarity index 60% rename from interfaces/innerkits/native_cpp/wifi_standard/src/wifi_hotspot_proxy.cpp rename to wifi/frameworks/native/src/wifi_hotspot_proxy.cpp index 9adb814e475e0b75fbaf73fe01448f1f1a8b44d1..8d09663aa360cfe84d1071a0fa30918d9f3ad0bd 100644 --- a/interfaces/innerkits/native_cpp/wifi_standard/src/wifi_hotspot_proxy.cpp +++ b/wifi/frameworks/native/src/wifi_hotspot_proxy.cpp @@ -1,5 +1,5 @@ /* - * Copyright (C) 2021 Huawei Device Co., Ltd. + * Copyright (C) 2021-2022 Huawei Device Co., Ltd. * 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 @@ -12,17 +12,21 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + #include "wifi_hotspot_proxy.h" #include "string_ex.h" #include "iservice_registry.h" #include "system_ability_definition.h" -#include "wifi_logger.h" +#include "wifi_hisysevent.h" #include "wifi_hotspot_callback_stub.h" +#include "wifi_logger.h" DEFINE_WIFILOG_HOTSPOT_LABEL("WifiHotspotProxy"); namespace OHOS { namespace Wifi { -static WifiHotspotCallbackStub *g_wifiHotspotCallbackStub = new WifiHotspotCallbackStub; +static sptr g_wifiHotspotCallbackStub = + sptr(new (std::nothrow) WifiHotspotCallbackStub()); + WifiHotspotProxy::WifiHotspotProxy(const sptr &impl) : IRemoteProxy(impl), mRemoteDied(false) { @@ -41,12 +45,16 @@ WifiHotspotProxy::~WifiHotspotProxy() ErrCode WifiHotspotProxy::IsHotspotActive(bool &bActive) { if (mRemoteDied) { - WIFI_LOGD("failed to `%{public}s`,remote service is died!", __func__); + WIFI_LOGE("failed to `%{public}s`,remote service is died!", __func__); return WIFI_OPT_FAILED; } MessageOption option; MessageParcel data; MessageParcel reply; + if (!data.WriteInterfaceToken(GetDescriptor())) { + WIFI_LOGE("Write interface token error: %{public}s", __func__); + return WIFI_OPT_FAILED; + } data.WriteInt32(0); int error = Remote()->SendRequest(WIFI_SVR_CMD_IS_HOTSPOT_ACTIVE, data, reply, option); if (error != ERR_NONE) { @@ -65,15 +73,51 @@ ErrCode WifiHotspotProxy::IsHotspotActive(bool &bActive) return WIFI_OPT_SUCCESS; } +ErrCode WifiHotspotProxy::IsHotspotDualBandSupported(bool &isSupported) +{ + if (mRemoteDied) { + WIFI_LOGE("failed to `%{public}s`,remote service is died!", __func__); + return WIFI_OPT_FAILED; + } + MessageOption option; + MessageParcel data; + MessageParcel reply; + if (!data.WriteInterfaceToken(GetDescriptor())) { + WIFI_LOGE("Write interface token error: %{public}s", __func__); + return WIFI_OPT_FAILED; + } + data.WriteInt32(0); + int error = Remote()->SendRequest(WIFI_SVR_CMD_IS_HOTSPOT_DUAL_BAND_SUPPORTED, data, reply, option); + if (error != ERR_NONE) { + WIFI_LOGE("Set Attr(%{public}d) failed", WIFI_SVR_CMD_IS_HOTSPOT_DUAL_BAND_SUPPORTED); + return WIFI_OPT_FAILED; + } + int exception = reply.ReadInt32(); + if (exception) { + return WIFI_OPT_FAILED; + } + int ret = reply.ReadInt32(); + if (ErrCode(ret) != WIFI_OPT_SUCCESS) { + WIFI_LOGE("reply failed: %d", ret); + return ErrCode(ret); + } + isSupported = ((reply.ReadInt32() == 1) ? true : false); + return WIFI_OPT_SUCCESS; +} + ErrCode WifiHotspotProxy::GetHotspotState(int &state) { if (mRemoteDied) { - WIFI_LOGD("failed to `%{public}s`,remote service is died!", __func__); + WIFI_LOGW("failed to `%{public}s`,remote service is died!", __func__); return WIFI_OPT_FAILED; } MessageOption option; MessageParcel data; MessageParcel reply; + if (!data.WriteInterfaceToken(GetDescriptor())) { + WIFI_LOGE("Write interface token error: %{public}s", __func__); + return WIFI_OPT_FAILED; + } data.WriteInt32(0); int error = Remote()->SendRequest(WIFI_SVR_CMD_GETAPSTATE_WIFI, data, reply, option); if (error != ERR_NONE) { @@ -96,12 +140,16 @@ ErrCode WifiHotspotProxy::GetHotspotState(int &state) ErrCode WifiHotspotProxy::GetHotspotConfig(HotspotConfig &result) { if (mRemoteDied) { - WIFI_LOGD("failed to `%{public}s`,remote service is died!", __func__); + WIFI_LOGW("failed to `%{public}s`,remote service is died!", __func__); return WIFI_OPT_FAILED; } MessageOption option; MessageParcel data; MessageParcel reply; + if (!data.WriteInterfaceToken(GetDescriptor())) { + WIFI_LOGE("Write interface token error: %{public}s", __func__); + return WIFI_OPT_FAILED; + } data.WriteInt32(0); int error = Remote()->SendRequest(WIFI_SVR_CMD_GET_HOTSPOT_CONFIG, data, reply, option); if (error != ERR_NONE) { @@ -131,12 +179,16 @@ ErrCode WifiHotspotProxy::GetHotspotConfig(HotspotConfig &result) ErrCode WifiHotspotProxy::SetHotspotConfig(const HotspotConfig &config) { if (mRemoteDied) { - WIFI_LOGD("failed to `%{public}s`,remote service is died!", __func__); + WIFI_LOGW("failed to `%{public}s`,remote service is died!", __func__); return WIFI_OPT_FAILED; } MessageOption option; MessageParcel data; MessageParcel reply; + if (!data.WriteInterfaceToken(GetDescriptor())) { + WIFI_LOGE("Write interface token error: %{public}s", __func__); + return WIFI_OPT_FAILED; + } data.WriteInt32(0); data.WriteCString(config.GetSsid().c_str()); data.WriteInt32(static_cast(config.GetSecurityType())); @@ -160,12 +212,16 @@ ErrCode WifiHotspotProxy::SetHotspotConfig(const HotspotConfig &config) ErrCode WifiHotspotProxy::GetStationList(std::vector &result) { if (mRemoteDied) { - WIFI_LOGD("failed to `%{public}s`,remote service is died!", __func__); + WIFI_LOGW("failed to `%{public}s`,remote service is died!", __func__); return WIFI_OPT_FAILED; } MessageOption option; MessageParcel data; MessageParcel reply; + if (!data.WriteInterfaceToken(GetDescriptor())) { + WIFI_LOGE("Write interface token error: %{public}s", __func__); + return WIFI_OPT_FAILED; + } data.WriteInt32(0); int error = Remote()->SendRequest(WIFI_SVR_CMD_GET_STATION_LIST, data, reply, option); if (error != ERR_NONE) { @@ -181,7 +237,12 @@ ErrCode WifiHotspotProxy::GetStationList(std::vector &result) if (ErrCode(ret) != WIFI_OPT_SUCCESS) { return ErrCode(ret); } + constexpr int MAX_SIZE = 512; int size = reply.ReadInt32(); + if (size > MAX_SIZE) { + WIFI_LOGE("Station list size error: %{public}d", size); + return WIFI_OPT_FAILED; + } for (int i = 0; i < size; i++) { StationInfo info; info.deviceName = reply.ReadCString(); @@ -196,12 +257,16 @@ ErrCode WifiHotspotProxy::GetStationList(std::vector &result) ErrCode WifiHotspotProxy::DisassociateSta(const StationInfo &info) { if (mRemoteDied) { - WIFI_LOGD("failed to `%{public}s`,remote service is died!", __func__); + WIFI_LOGW("failed to `%{public}s`,remote service is died!", __func__); return WIFI_OPT_FAILED; } MessageOption option; MessageParcel data; MessageParcel reply; + if (!data.WriteInterfaceToken(GetDescriptor())) { + WIFI_LOGE("Write interface token error: %{public}s", __func__); + return WIFI_OPT_FAILED; + } data.WriteInt32(0); data.WriteCString(info.deviceName.c_str()); data.WriteCString(info.bssid.c_str()); @@ -219,12 +284,17 @@ ErrCode WifiHotspotProxy::DisassociateSta(const StationInfo &info) return ErrCode(reply.ReadInt32()); } -ErrCode WifiHotspotProxy::EnableHotspot(void) +ErrCode WifiHotspotProxy::EnableHotspot(const ServiceType type) { MessageOption option; MessageParcel data; MessageParcel reply; + if (!data.WriteInterfaceToken(GetDescriptor())) { + WIFI_LOGE("Write interface token error: %{public}s", __func__); + return WIFI_OPT_FAILED; + } data.WriteInt32(0); + data.WriteInt32(static_cast(type)); int error = Remote()->SendRequest(WIFI_SVR_CMD_ENABLE_WIFI_AP, data, reply, option); if (error != ERR_NONE) { WIFI_LOGE("Set Attr(%{public}d) failed", WIFI_SVR_CMD_ENABLE_WIFI_AP); @@ -235,19 +305,25 @@ ErrCode WifiHotspotProxy::EnableHotspot(void) if (exception) { return WIFI_OPT_FAILED; } + WriteWifiStateHiSysEvent(HISYS_SERVICE_TYPE_AP, WifiOperType::ENABLE); return ErrCode(reply.ReadInt32()); } -ErrCode WifiHotspotProxy::DisableHotspot(void) +ErrCode WifiHotspotProxy::DisableHotspot(const ServiceType type) { if (mRemoteDied) { - WIFI_LOGD("failed to `%{public}s`,remote service is died!", __func__); + WIFI_LOGW("failed to `%{public}s`,remote service is died!", __func__); return WIFI_OPT_FAILED; } MessageOption option; MessageParcel data; MessageParcel reply; + if (!data.WriteInterfaceToken(GetDescriptor())) { + WIFI_LOGE("Write interface token error: %{public}s", __func__); + return WIFI_OPT_FAILED; + } data.WriteInt32(0); + data.WriteInt32(static_cast(type)); int error = Remote()->SendRequest(WIFI_SVR_CMD_DISABLE_WIFI_AP, data, reply, option); if (error != ERR_NONE) { WIFI_LOGE("Set Attr(%{public}d) failed", WIFI_SVR_CMD_DISABLE_WIFI_AP); @@ -258,18 +334,23 @@ ErrCode WifiHotspotProxy::DisableHotspot(void) if (exception) { return WIFI_OPT_FAILED; } + WriteWifiStateHiSysEvent(HISYS_SERVICE_TYPE_AP, WifiOperType::DISABLE); return ErrCode(reply.ReadInt32()); } ErrCode WifiHotspotProxy::GetBlockLists(std::vector &infos) { if (mRemoteDied) { - WIFI_LOGD("failed to `%{public}s`,remote service is died!", __func__); + WIFI_LOGW("failed to `%{public}s`,remote service is died!", __func__); return WIFI_OPT_FAILED; } MessageOption option; MessageParcel data; MessageParcel reply; + if (!data.WriteInterfaceToken(GetDescriptor())) { + WIFI_LOGE("Write interface token error: %{public}s", __func__); + return WIFI_OPT_FAILED; + } data.WriteInt32(0); int error = Remote()->SendRequest(WIFI_SVR_CMD_GET_BLOCK_LISTS, data, reply, option); if (error != ERR_NONE) { @@ -285,7 +366,14 @@ ErrCode WifiHotspotProxy::GetBlockLists(std::vector &infos) if (err != WIFI_OPT_SUCCESS) { return ErrCode(err); } + + constexpr int MAX_SIZE = 512; int size = reply.ReadInt32(); + if (size > MAX_SIZE) { + WIFI_LOGE("Get block size error: %{public}d", size); + return WIFI_OPT_FAILED; + } + for (int i = 0; i < size; i++) { StationInfo info; info.deviceName = reply.ReadCString(); @@ -299,12 +387,16 @@ ErrCode WifiHotspotProxy::GetBlockLists(std::vector &infos) ErrCode WifiHotspotProxy::AddBlockList(const StationInfo &info) { if (mRemoteDied) { - WIFI_LOGD("failed to `%{public}s`,remote service is died!", __func__); + WIFI_LOGW("failed to `%{public}s`,remote service is died!", __func__); return WIFI_OPT_FAILED; } MessageOption option; MessageParcel data; MessageParcel reply; + if (!data.WriteInterfaceToken(GetDescriptor())) { + WIFI_LOGE("Write interface token error: %{public}s", __func__); + return WIFI_OPT_FAILED; + } data.WriteInt32(0); data.WriteCString(info.deviceName.c_str()); data.WriteCString(info.bssid.c_str()); @@ -325,12 +417,16 @@ ErrCode WifiHotspotProxy::AddBlockList(const StationInfo &info) ErrCode WifiHotspotProxy::DelBlockList(const StationInfo &info) { if (mRemoteDied) { - WIFI_LOGD("failed to `%{public}s`,remote service is died!", __func__); + WIFI_LOGW("failed to `%{public}s`,remote service is died!", __func__); return WIFI_OPT_FAILED; } MessageOption option; MessageParcel data; MessageParcel reply; + if (!data.WriteInterfaceToken(GetDescriptor())) { + WIFI_LOGE("Write interface token error: %{public}s", __func__); + return WIFI_OPT_FAILED; + } data.WriteInt32(0); data.WriteCString(info.deviceName.c_str()); data.WriteCString(info.bssid.c_str()); @@ -351,12 +447,16 @@ ErrCode WifiHotspotProxy::DelBlockList(const StationInfo &info) ErrCode WifiHotspotProxy::GetValidBands(std::vector &bands) { if (mRemoteDied) { - WIFI_LOGD("failed to `%{public}s`,remote service is died!", __func__); + WIFI_LOGW("failed to `%{public}s`,remote service is died!", __func__); return WIFI_OPT_FAILED; } MessageOption option; MessageParcel data; MessageParcel reply; + if (!data.WriteInterfaceToken(GetDescriptor())) { + WIFI_LOGE("Write interface token error: %{public}s", __func__); + return WIFI_OPT_FAILED; + } data.WriteInt32(0); int error = Remote()->SendRequest(WIFI_SVR_CMD_GET_VALID_BANDS, data, reply, option); if (error != ERR_NONE) { @@ -372,7 +472,13 @@ ErrCode WifiHotspotProxy::GetValidBands(std::vector &bands) if (err != WIFI_OPT_SUCCESS) { return ErrCode(err); } + + constexpr int MAX_BAND_SIZE = 512; int count = reply.ReadInt32(); + if (count > MAX_BAND_SIZE) { + WIFI_LOGE("Band size error: %{public}d", count); + return WIFI_OPT_FAILED; + } for (int i = 0; i < count; i++) { int val = reply.ReadInt32(); bands.push_back(BandType(val)); @@ -383,12 +489,16 @@ ErrCode WifiHotspotProxy::GetValidBands(std::vector &bands) ErrCode WifiHotspotProxy::GetValidChannels(BandType band, std::vector &validchannels) { if (mRemoteDied) { - WIFI_LOGD("failed to `%{public}s`,remote service is died!", __func__); + WIFI_LOGW("failed to `%{public}s`,remote service is died!", __func__); return WIFI_OPT_FAILED; } MessageOption option; MessageParcel data; MessageParcel reply; + if (!data.WriteInterfaceToken(GetDescriptor())) { + WIFI_LOGE("Write interface token error: %{public}s", __func__); + return WIFI_OPT_FAILED; + } data.WriteInt32(0); data.WriteInt32((int)band); int error = Remote()->SendRequest(WIFI_SVR_CMD_GET_VALID_CHANNELS, data, reply, option); @@ -405,7 +515,13 @@ ErrCode WifiHotspotProxy::GetValidChannels(BandType band, std::vector & if (err != WIFI_OPT_SUCCESS) { return ErrCode(err); } + + constexpr int MAX_CHANNELS_SIZE = 512; int count = reply.ReadInt32(); + if (count > MAX_CHANNELS_SIZE) { + WIFI_LOGE("Channel size error: %{public}d", count); + return WIFI_OPT_FAILED; + } for (int i = 0; i < count; i++) { int val = reply.ReadInt32(); validchannels.push_back(val); @@ -421,6 +537,10 @@ ErrCode WifiHotspotProxy::RegisterCallBack(const sptr &cal MessageOption option(MessageOption::TF_ASYNC); g_wifiHotspotCallbackStub->RegisterCallBack(callback); + if (!data.WriteInterfaceToken(GetDescriptor())) { + WIFI_LOGE("Write interface token error: %{public}s", __func__); + return WIFI_OPT_FAILED; + } data.WriteInt32(0); if (!data.WriteRemoteObject(g_wifiHotspotCallbackStub->AsObject())) { WIFI_LOGE("WifiHotspotProxy::RegisterCallBack WriteDate fail, write callback."); @@ -443,11 +563,15 @@ ErrCode WifiHotspotProxy::RegisterCallBack(const sptr &cal ErrCode WifiHotspotProxy::GetSupportedFeatures(long &features) { if (mRemoteDied) { - WIFI_LOGD("failed to `%{public}s`,remote service is died!", __func__); + WIFI_LOGW("failed to `%{public}s`,remote service is died!", __func__); return WIFI_OPT_FAILED; } MessageOption option; MessageParcel data, reply; + if (!data.WriteInterfaceToken(GetDescriptor())) { + WIFI_LOGE("Write interface token error: %{public}s", __func__); + return WIFI_OPT_FAILED; + } data.WriteInt32(0); int error = Remote()->SendRequest(WIFI_SVR_CMD_GET_SUPPORTED_FEATURES, data, reply, option); if (error != ERR_NONE) { @@ -467,9 +591,111 @@ ErrCode WifiHotspotProxy::GetSupportedFeatures(long &features) return WIFI_OPT_SUCCESS; } +ErrCode WifiHotspotProxy::GetSupportedPowerModel(std::set& setPowerModelList) +{ + if (mRemoteDied) { + WIFI_LOGW("failed to `%{public}s`,remote service is died!", __func__); + return WIFI_OPT_FAILED; + } + MessageOption option; + MessageParcel data; + MessageParcel reply; + if (!data.WriteInterfaceToken(GetDescriptor())) { + WIFI_LOGE("Write interface token error: %{public}s", __func__); + return WIFI_OPT_FAILED; + } + data.WriteInt32(0); + int error = Remote()->SendRequest(WIFI_SVR_CMD_GET_SUPPORTED_POWER_MODEL, data, reply, option); + if (error != ERR_NONE) { + WIFI_LOGE("Set Attr(%{public}d) failed", WIFI_SVR_CMD_GET_SUPPORTED_POWER_MODEL); + return WIFI_OPT_FAILED; + } + + int exception = reply.ReadInt32(); + if (exception) { + return WIFI_OPT_FAILED; + } + int err = reply.ReadInt32(); + if (err != WIFI_OPT_SUCCESS) { + return ErrCode(err); + } + + constexpr int MAX_SIZE = 32; + int size = reply.ReadInt32(); + if (size > MAX_SIZE) { + WIFI_LOGE("size error: %{public}d", size); + return WIFI_OPT_FAILED; + } + for (int i = 0; i < size; i++) { + int val = reply.ReadInt32(); + setPowerModelList.insert(PowerModel(val)); + } + return WIFI_OPT_SUCCESS; +} + +ErrCode WifiHotspotProxy::GetPowerModel(PowerModel& model) +{ + if (mRemoteDied) { + WIFI_LOGW("failed to `%{public}s`,remote service is died!", __func__); + return WIFI_OPT_FAILED; + } + MessageOption option; + MessageParcel data; + MessageParcel reply; + if (!data.WriteInterfaceToken(GetDescriptor())) { + WIFI_LOGE("Write interface token error: %{public}s", __func__); + return WIFI_OPT_FAILED; + } + data.WriteInt32(0); + int error = Remote()->SendRequest(WIFI_SVR_CMD_GET_POWER_MODEL, data, reply, option); + if (error != ERR_NONE) { + WIFI_LOGE("Set Attr(%{public}d) failed", WIFI_SVR_CMD_GET_POWER_MODEL); + return WIFI_OPT_FAILED; + } + + int exception = reply.ReadInt32(); + if (exception) { + return WIFI_OPT_FAILED; + } + int err = reply.ReadInt32(); + if (err != WIFI_OPT_SUCCESS) { + return ErrCode(err); + } + model = PowerModel(reply.ReadInt32()); + return WIFI_OPT_SUCCESS; +} + +ErrCode WifiHotspotProxy::SetPowerModel(const PowerModel& model) +{ + if (mRemoteDied) { + WIFI_LOGW("failed to `%{public}s`,remote service is died!", __func__); + return WIFI_OPT_FAILED; + } + MessageOption option; + MessageParcel data; + MessageParcel reply; + if (!data.WriteInterfaceToken(GetDescriptor())) { + WIFI_LOGE("Write interface token error: %{public}s", __func__); + return WIFI_OPT_FAILED; + } + data.WriteInt32(0); + data.WriteInt32(static_cast(model)); + int error = Remote()->SendRequest(WIFI_SVR_CMD_SET_POWER_MODEL, data, reply, option); + if (error != ERR_NONE) { + WIFI_LOGE("Set Attr(%{public}d) failed", WIFI_SVR_CMD_SET_POWER_MODEL); + return WIFI_OPT_FAILED; + } + + int exception = reply.ReadInt32(); + if (exception) { + return WIFI_OPT_FAILED; + } + return ErrCode(reply.ReadInt32()); +} + void WifiHotspotProxy::OnRemoteDied(const wptr& remoteObject) { - WIFI_LOGD("Remote service is died!"); + WIFI_LOGW("Remote service is died!"); mRemoteDied = true; if (g_wifiHotspotCallbackStub != nullptr) { g_wifiHotspotCallbackStub->SetRemoteDied(true); diff --git a/interfaces/innerkits/native_cpp/wifi_standard/src/wifi_hotspot_proxy.h b/wifi/frameworks/native/src/wifi_hotspot_proxy.h similarity index 76% rename from interfaces/innerkits/native_cpp/wifi_standard/src/wifi_hotspot_proxy.h rename to wifi/frameworks/native/src/wifi_hotspot_proxy.h index 573b5535e4b750aa1994a71843ab4ef79b310bd9..6bb1b69d9cfa73b4560ac411a702696a41eebb6b 100644 --- a/interfaces/innerkits/native_cpp/wifi_standard/src/wifi_hotspot_proxy.h +++ b/wifi/frameworks/native/src/wifi_hotspot_proxy.h @@ -1,5 +1,5 @@ /* - * Copyright (C) 2021 Huawei Device Co., Ltd. + * Copyright (C) 2021-2022 Huawei Device Co., Ltd. * 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 @@ -37,6 +37,14 @@ public: */ ErrCode IsHotspotActive(bool &bActive) override; + /** + * @Description Check whether the hotspot supports dual band. + * + * @param isSupported - Supported / NOT Supported + * @return ErrCode - operation result + */ + ErrCode IsHotspotDualBandSupported(bool &isSupported) override; + /** * @Description Get the Hotspot Config object * @@ -80,16 +88,18 @@ public: /** * @Description Enable Hotspot * + * @param type - service type * @return ErrCode - operation result */ - ErrCode EnableHotspot(void) override; + ErrCode EnableHotspot(const ServiceType type = ServiceType::DEFAULT) override; /** * @Description Disable Hotspot * + * @param type - service type * @return ErrCode - operation result */ - ErrCode DisableHotspot(void) override; + ErrCode DisableHotspot(const ServiceType type = ServiceType::DEFAULT) override; /** * @Description Get the Block Lists object @@ -148,7 +158,36 @@ public: */ ErrCode GetSupportedFeatures(long &features) override; + /** + * @Description Handle remote object died event. + * @param remoteObject remote object. + */ void OnRemoteDied(const wptr& remoteObject) override; + + /** + * @Description Get supported power model list + * + * @param setPowerModelList - supported power model list + * @return ErrCode - operation result + */ + ErrCode GetSupportedPowerModel(std::set& setPowerModelList) override; + + /** + * @Description Get power model + * + * @param model - current power model + * @return ErrCode - operation result + */ + ErrCode GetPowerModel(PowerModel& model) override; + + /** + * @Description Get supported power model list + * + * @param model - the model to be set + * @return ErrCode - operation result + */ + ErrCode SetPowerModel(const PowerModel& model) override; + private: static BrokerDelegator g_delegator; diff --git a/interfaces/innerkits/native_cpp/wifi_standard/src/wifi_logger.h b/wifi/frameworks/native/src/wifi_logger.h similarity index 88% rename from interfaces/innerkits/native_cpp/wifi_standard/src/wifi_logger.h rename to wifi/frameworks/native/src/wifi_logger.h index 00e62e8f81a740c11cb0c88d2a8cb356723f7d49..8ff810eddc0a9c23c2d0a73d3702e684fe9f9086 100644 --- a/interfaces/innerkits/native_cpp/wifi_standard/src/wifi_logger.h +++ b/wifi/frameworks/native/src/wifi_logger.h @@ -1,5 +1,5 @@ /* - * Copyright (C) 2021 Huawei Device Co., Ltd. + * Copyright (C) 2021-2022 Huawei Device Co., Ltd. * 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 @@ -12,11 +12,16 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + #ifndef OHOS_WIFI_LOGGER_H #define OHOS_WIFI_LOGGER_H +#ifdef OHOS_ARCH_LITE +#include "hilog/log.h" +#else #include "hilog/log_c.h" #include "hilog/log_cpp.h" +#endif namespace OHOS { namespace Wifi { @@ -45,6 +50,14 @@ const unsigned int LOG_ID_WIFI_DHCP = LOG_ID_WIFI | 0x05; #define WIFI_LOGW(...) (void)OHOS::HiviewDFX::HiLog::Warn(WIFI_LOG_LABEL, ##__VA_ARGS__) #define WIFI_LOGI(...) (void)OHOS::HiviewDFX::HiLog::Info(WIFI_LOG_LABEL, ##__VA_ARGS__) #define WIFI_LOGD(...) (void)OHOS::HiviewDFX::HiLog::Debug(WIFI_LOG_LABEL, ##__VA_ARGS__) + +#ifndef CHECK_NULL_AND_RETURN +#define CHECK_NULL_AND_RETURN(ptr, retValue) \ +if (!(ptr)) { \ + WIFI_LOGI("Pointer %{public}s in %{public}s is NULL!", #ptr, __func__); \ + return retValue; \ +} +#endif } // namespace Wifi } // namespace OHOS #endif \ No newline at end of file diff --git a/wifi/frameworks/native/src/wifi_msg.cpp b/wifi/frameworks/native/src/wifi_msg.cpp new file mode 100644 index 0000000000000000000000000000000000000000..cae9e2fe3283b35a3ad7565a4b4289ce7b9dceff --- /dev/null +++ b/wifi/frameworks/native/src/wifi_msg.cpp @@ -0,0 +1,54 @@ +/* + * Copyright (C) 2022 Huawei Device Co., Ltd. + * 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 "wifi_msg.h" +#include + +namespace OHOS { +namespace Wifi { +static const std::string PREFIX_AUTH = "auth="; +static const std::string PREFIX_AUTHEAP = "autheap="; +static const std::string METHOD_STRS[] = { "NONE", "PAP", "MSCHAP", "MSCHAPV2", "GTC", "SIM", "AKA", "AKA'" }; + +std::string WifiEapConfig::Phase2MethodToStr(const std::string& eap, const int& method) +{ + if (method < 0 || method > (sizeof(METHOD_STRS) / sizeof(METHOD_STRS[0]))) { + return "auth=NONE"; + } + std::string prefix = (eap == EAP_METHOD_TTLS && method == static_cast(Phase2Method::GTC)) ? + PREFIX_AUTHEAP : PREFIX_AUTH; + return prefix + METHOD_STRS[method]; +} + +Phase2Method WifiEapConfig::Phase2MethodFromStr(const std::string& str) +{ + std::string methodStr; + if (str.find(PREFIX_AUTH) == 0) { + methodStr = str.substr(PREFIX_AUTH.length()); + } else if (str.find(PREFIX_AUTHEAP) == 0) { + methodStr = str.substr(PREFIX_AUTHEAP.length()); + } else { + return Phase2Method::NONE; + } + int len = sizeof(METHOD_STRS) / sizeof(METHOD_STRS[0]); + for (int i = 0; i < len; i++) { + if (METHOD_STRS[i] == methodStr) { + return Phase2Method(i); + } + } + return Phase2Method::NONE; +} +} // namespace Wifi +} // namespace OHOS diff --git a/interfaces/innerkits/native_cpp/wifi_standard/src/wifi_p2p.cpp b/wifi/frameworks/native/src/wifi_p2p.cpp similarity index 100% rename from interfaces/innerkits/native_cpp/wifi_standard/src/wifi_p2p.cpp rename to wifi/frameworks/native/src/wifi_p2p.cpp diff --git a/interfaces/innerkits/native_cpp/wifi_standard/src/wifi_p2p_callback_stub.cpp b/wifi/frameworks/native/src/wifi_p2p_callback_stub.cpp similarity index 71% rename from interfaces/innerkits/native_cpp/wifi_standard/src/wifi_p2p_callback_stub.cpp rename to wifi/frameworks/native/src/wifi_p2p_callback_stub.cpp index b4e4c9f3c554d40fdf1d3dbfda8085629a1bd57a..630fe7eb0db2cfdc24efc3b1b76534279031cee7 100644 --- a/interfaces/innerkits/native_cpp/wifi_standard/src/wifi_p2p_callback_stub.cpp +++ b/wifi/frameworks/native/src/wifi_p2p_callback_stub.cpp @@ -1,5 +1,5 @@ /* - * Copyright (C) 2021 Huawei Device Co., Ltd. + * Copyright (C) 2021-2022 Huawei Device Co., Ltd. * 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 @@ -12,14 +12,15 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + #include "wifi_p2p_callback_stub.h" #include "define.h" -#include "wifi_p2p_msg.h" #include "wifi_errcode.h" +#include "wifi_hisysevent.h" #include "wifi_logger.h" +#include "wifi_p2p_msg.h" DEFINE_WIFILOG_P2P_LABEL("WifiP2pCallbackStub"); - namespace OHOS { namespace Wifi { WifiP2pCallbackStub::WifiP2pCallbackStub() : userCallback_(nullptr), mRemoteDied(false) @@ -40,6 +41,7 @@ void WifiP2pCallbackStub::InitHandleMap() handleFuncMap[WIFI_CBK_CMD_CONNECT_CHANGE] = &WifiP2pCallbackStub::RemoteOnP2pConnectionChanged; handleFuncMap[WIFI_CBK_CMD_DISCOVERY_CHANGE] = &WifiP2pCallbackStub::RemoteOnP2pDiscoveryChanged; handleFuncMap[WIFI_CBK_CMD_P2P_ACTION_RESULT] = &WifiP2pCallbackStub::RemoteOnP2pActionResult; + handleFuncMap[WIFI_CBK_CMD_CFG_CHANGE] = &WifiP2pCallbackStub::RemoteOnConfigChanged; return; } @@ -51,6 +53,12 @@ int WifiP2pCallbackStub::OnRemoteRequest( WIFI_LOGD("Failed to `%{public}s`,remote service is died!", __func__); return -1; } + + if (data.ReadInterfaceToken() != GetDescriptor()) { + WIFI_LOGE("P2p callback stub token verification error: %{public}d", code); + return WIFI_OPT_FAILED; + } + int exception = data.ReadInt32(); if (exception) { WIFI_LOGD("WifiP2pCallbackStub::OnRemoteRequest exception! %{public}d!", exception); @@ -88,74 +96,80 @@ void WifiP2pCallbackStub::SetRemoteDied(bool val) void WifiP2pCallbackStub::OnP2pStateChanged(int state) { - WIFI_LOGD("WifiP2pCallbackStub::OnP2pStateChanged"); + WIFI_LOGI("WifiP2pCallbackStub::OnP2pStateChanged: %{public}d", state); if (userCallback_) { userCallback_->OnP2pStateChanged(state); } - return; + WriteWifiEventReceivedHiSysEvent(HISYS_P2P_STATE_CHANGE, state); } void WifiP2pCallbackStub::OnP2pPersistentGroupsChanged(void) { - WIFI_LOGD("WifiP2pCallbackStub::OnP2pPersistentGroupsChanged"); + WIFI_LOGI("WifiP2pCallbackStub::OnP2pPersistentGroupsChanged"); if (userCallback_) { userCallback_->OnP2pPersistentGroupsChanged(); } - return; + WriteWifiEventReceivedHiSysEvent(HISYS_P2P_PERSISTENT_GROUP_CHANGE, HISYS_EVENT_DEFAULT_VALUE); } void WifiP2pCallbackStub::OnP2pThisDeviceChanged(const WifiP2pDevice &device) { - WIFI_LOGD("WifiP2pCallbackStub::OnP2pThisDeviceChanged"); + WIFI_LOGI("WifiP2pCallbackStub::OnP2pThisDeviceChanged"); if (userCallback_) { userCallback_->OnP2pThisDeviceChanged(device); } - return; + WriteWifiEventReceivedHiSysEvent(HISYS_P2P_DEVICE_STATE_CHANGE, HISYS_EVENT_DEFAULT_VALUE); } void WifiP2pCallbackStub::OnP2pPeersChanged(const std::vector &device) { - WIFI_LOGD("WifiP2pCallbackStub::OnP2pPeersChanged"); + WIFI_LOGI("WifiP2pCallbackStub::OnP2pPeersChanged"); if (userCallback_) { userCallback_->OnP2pPeersChanged(device); } - return; + WriteWifiEventReceivedHiSysEvent(HISYS_P2P_PEER_DEVICE_CHANGE, HISYS_EVENT_DEFAULT_VALUE); } void WifiP2pCallbackStub::OnP2pServicesChanged(const std::vector &srvInfo) { - WIFI_LOGD("WifiP2pCallbackStub::OnP2pServicesChanged"); + WIFI_LOGI("WifiP2pCallbackStub::OnP2pServicesChanged"); if (userCallback_) { userCallback_->OnP2pServicesChanged(srvInfo); } - return; } -void WifiP2pCallbackStub::OnP2pConnectionChanged(const WifiP2pInfo &info) +void WifiP2pCallbackStub::OnP2pConnectionChanged(const WifiP2pLinkedInfo &info) { - WIFI_LOGD("WifiP2pCallbackStub::OnP2pConnectionChanged"); + WIFI_LOGI("WifiP2pCallbackStub::OnP2pConnectionChanged: %{public}d", static_cast(info.GetConnectState())); if (userCallback_) { userCallback_->OnP2pConnectionChanged(info); } - return; + WriteWifiEventReceivedHiSysEvent(HISYS_P2P_CONN_STATE_CHANGE, static_cast(info.GetConnectState())); } void WifiP2pCallbackStub::OnP2pDiscoveryChanged(bool isChange) { - WIFI_LOGD("WifiP2pCallbackStub::OnP2pDiscoveryChanged"); + WIFI_LOGI("WifiP2pCallbackStub::OnP2pDiscoveryChanged, isChange:%{public}d", isChange); if (userCallback_) { userCallback_->OnP2pDiscoveryChanged(isChange); } - return; + WriteWifiEventReceivedHiSysEvent(HISYS_P2P_DISCOVERY_CHANGE, isChange); } void WifiP2pCallbackStub::OnP2pActionResult(P2pActionCallback action, ErrCode code) { - WIFI_LOGD("WifiP2pCallbackStub::OnP2pActionResult"); + WIFI_LOGI("WifiP2pCallbackStub::OnP2pActionResult"); if (userCallback_) { userCallback_->OnP2pActionResult(action, code); } - return; +} + +void WifiP2pCallbackStub::OnConfigChanged(CfgType type, char* data, int dataLen) +{ + WIFI_LOGI("WifiP2pCallbackStub::OnConfigChanged"); + if (userCallback_) { + userCallback_->OnConfigChanged(type, data, dataLen); + } } void WifiP2pCallbackStub::RemoteOnP2pStateChanged(uint32_t code, MessageParcel &data, MessageParcel &reply) @@ -164,7 +178,6 @@ void WifiP2pCallbackStub::RemoteOnP2pStateChanged(uint32_t code, MessageParcel & int state = data.ReadInt32(); OnP2pStateChanged(state); reply.WriteInt32(0); - return; } void WifiP2pCallbackStub::RemoteOnP2pPersistentGroupsChanged(uint32_t code, MessageParcel &data, MessageParcel &reply) @@ -172,7 +185,6 @@ void WifiP2pCallbackStub::RemoteOnP2pPersistentGroupsChanged(uint32_t code, Mess WIFI_LOGD("run %{public}s code %{public}u, datasize %{public}zu", __func__, code, data.GetRawDataSize()); OnP2pPersistentGroupsChanged(); reply.WriteInt32(0); - return; } void WifiP2pCallbackStub::ReadWifiP2pDeviceData(MessageParcel &data, WifiP2pDevice &device) @@ -191,7 +203,6 @@ void WifiP2pCallbackStub::ReadWifiP2pDeviceData(MessageParcel &data, WifiP2pDevi device.SetWpsConfigMethod(data.ReadInt32()); device.SetDeviceCapabilitys(data.ReadInt32()); device.SetGroupCapabilitys(data.ReadInt32()); - return; } void WifiP2pCallbackStub::RemoteOnP2pThisDeviceChanged(uint32_t code, MessageParcel &data, MessageParcel &reply) @@ -201,14 +212,19 @@ void WifiP2pCallbackStub::RemoteOnP2pThisDeviceChanged(uint32_t code, MessagePar ReadWifiP2pDeviceData(data, config); OnP2pThisDeviceChanged(config); reply.WriteInt32(0); - return; } void WifiP2pCallbackStub::RemoteOnP2pPeersChanged(uint32_t code, MessageParcel &data, MessageParcel &reply) { WIFI_LOGD("run %{public}s code %{public}u, datasize %{public}zu", __func__, code, data.GetRawDataSize()); + constexpr int MAX_DEVICE_SIZE = 512; std::vector device; int size = data.ReadInt32(); + if (size > MAX_DEVICE_SIZE) { + WIFI_LOGE("Peers change list size error: %{public}d", size); + reply.WriteInt32(0); + return; + } for (int i = 0; i < size; ++i) { WifiP2pDevice config; ReadWifiP2pDeviceData(data, config); @@ -216,14 +232,19 @@ void WifiP2pCallbackStub::RemoteOnP2pPeersChanged(uint32_t code, MessageParcel & } OnP2pPeersChanged(device); reply.WriteInt32(0); - return; } void WifiP2pCallbackStub::RemoteOnP2pServicesChanged(uint32_t code, MessageParcel &data, MessageParcel &reply) { WIFI_LOGD("run %{public}s code %{public}u, datasize %{public}zu", __func__, code, data.GetRawDataSize()); + constexpr int MAX_SIZE = 512; std::vector srvInfo; int size = data.ReadInt32(); + if (size > MAX_SIZE) { + WIFI_LOGE("Service change size error: %{public}d", size); + reply.WriteInt32(0); + return; + } for (int i = 0; i < size; ++i) { WifiP2pServiceInfo info; info.SetServiceName(data.ReadCString()); @@ -239,19 +260,17 @@ void WifiP2pCallbackStub::RemoteOnP2pServicesChanged(uint32_t code, MessageParce } OnP2pServicesChanged(srvInfo); reply.WriteInt32(0); - return; } void WifiP2pCallbackStub::RemoteOnP2pConnectionChanged(uint32_t code, MessageParcel &data, MessageParcel &reply) { WIFI_LOGD("run %{public}s code %{public}u, datasize %{public}zu", __func__, code, data.GetRawDataSize()); - WifiP2pInfo info; + WifiP2pLinkedInfo info; info.SetConnectState(static_cast(data.ReadInt32())); info.SetIsGroupOwner(data.ReadBool()); info.SetIsGroupOwnerAddress(data.ReadCString()); OnP2pConnectionChanged(info); reply.WriteInt32(0); - return; } void WifiP2pCallbackStub::RemoteOnP2pDiscoveryChanged(uint32_t code, MessageParcel &data, MessageParcel &reply) @@ -260,7 +279,6 @@ void WifiP2pCallbackStub::RemoteOnP2pDiscoveryChanged(uint32_t code, MessageParc bool isChange = data.ReadBool(); OnP2pDiscoveryChanged(isChange); reply.WriteInt32(0); - return; } void WifiP2pCallbackStub::RemoteOnP2pActionResult(uint32_t code, MessageParcel &data, MessageParcel &reply) @@ -270,7 +288,41 @@ void WifiP2pCallbackStub::RemoteOnP2pActionResult(uint32_t code, MessageParcel & ErrCode errCode = static_cast(data.ReadInt32()); OnP2pActionResult(action, errCode); reply.WriteInt32(0); - return; +} + +void WifiP2pCallbackStub::RemoteOnConfigChanged(uint32_t code, MessageParcel &data, MessageParcel &reply) +{ + WIFI_LOGD("run %{public}s code %{public}u, datasize %{public}zu", __func__, code, data.GetRawDataSize()); + + CfgType cfgType = static_cast(data.ReadInt32()); + int cfgLen = data.ReadInt32(); + if (cfgLen <= 0) { + WIFI_LOGE("Config change size error: %{public}d", cfgLen); + reply.WriteInt32(static_cast(WIFI_OPT_INVALID_PARAM)); + return; + } + + const char *dataBuffer = (const char *)reply.ReadBuffer(cfgLen); + if (dataBuffer == nullptr) { + WIFI_LOGE("read buffer error!"); + reply.WriteInt32(static_cast(WIFI_OPT_FAILED)); + return; + } + + char* cfgData = new (std::nothrow) char[cfgLen]; + if (cfgData == nullptr) { + WIFI_LOGE("new buffer error!"); + reply.WriteInt32(static_cast(WIFI_OPT_FAILED)); + return; + } + if (memcpy_s(cfgData, cfgLen, dataBuffer, cfgLen) != EOK) { + WIFI_LOGE("memcpy_s failed!"); + reply.WriteInt32(static_cast(WIFI_OPT_FAILED)); + return; + } + OnConfigChanged(cfgType, cfgData, cfgLen); + delete[] cfgData; + reply.WriteInt32(0); } } // namespace Wifi } // namespace OHOS \ No newline at end of file diff --git a/interfaces/innerkits/native_cpp/wifi_standard/src/wifi_p2p_callback_stub.h b/wifi/frameworks/native/src/wifi_p2p_callback_stub.h similarity index 87% rename from interfaces/innerkits/native_cpp/wifi_standard/src/wifi_p2p_callback_stub.h rename to wifi/frameworks/native/src/wifi_p2p_callback_stub.h index e29501566e2a9daf712c446438d506c4d29ae0ef..d76335daad725c0c023f9a47555219d1d39676d7 100644 --- a/interfaces/innerkits/native_cpp/wifi_standard/src/wifi_p2p_callback_stub.h +++ b/wifi/frameworks/native/src/wifi_p2p_callback_stub.h @@ -70,9 +70,9 @@ public: /** * @Description Connection status change * - * @param info - WifiP2pInfo object + * @param info - WifiP2pLinkedInfo object */ - void OnP2pConnectionChanged(const WifiP2pInfo &info) override; + void OnP2pConnectionChanged(const WifiP2pLinkedInfo &info) override; /** * @Description Discover status change @@ -85,12 +85,21 @@ public: * @Description P2p callback result * * @param action - DiscoverDevices/StopDiscoverDevices/DiscoverServices/StopDiscoverServices - * /PutLocalP2pService/StartP2pListen/StopP2pListen/FormGroup/RemoveGroup - * /DeleteGroup/P2pConnect/P2pDisConnect + * /PutLocalP2pService/StartP2pListen/StopP2pListen/CreateGroup/RemoveGroup + * /DeleteGroup/P2pConnect/P2pCancelConnect * @param code - Return code */ void OnP2pActionResult(P2pActionCallback action, ErrCode code) override; + /** + * @Description Config changed callback. + * + * @param type - Config type + * @param data - Config data + * @param len - Config data length + */ + void OnConfigChanged(CfgType type, char* data, int dataLen) override; + void RegisterCallBack(const sptr &userCallback); bool IsRemoteDied() const; void SetRemoteDied(bool val); @@ -106,6 +115,7 @@ private: void RemoteOnP2pConnectionChanged(uint32_t code, MessageParcel &data, MessageParcel &reply); void RemoteOnP2pDiscoveryChanged(uint32_t code, MessageParcel &data, MessageParcel &reply); void RemoteOnP2pActionResult(uint32_t code, MessageParcel &data, MessageParcel &reply); + void RemoteOnConfigChanged(uint32_t code, MessageParcel &data, MessageParcel &reply); private: HandleFuncMap handleFuncMap; diff --git a/interfaces/innerkits/native_cpp/wifi_standard/src/wifi_p2p_impl.cpp b/wifi/frameworks/native/src/wifi_p2p_impl.cpp similarity index 66% rename from interfaces/innerkits/native_cpp/wifi_standard/src/wifi_p2p_impl.cpp rename to wifi/frameworks/native/src/wifi_p2p_impl.cpp index f8946fea8ec241c2c962567f83dd81a36b5a9f00..1a42bfbcaabbce15d0c70cb035c26bd4b6f5bee2 100644 --- a/interfaces/innerkits/native_cpp/wifi_standard/src/wifi_p2p_impl.cpp +++ b/wifi/frameworks/native/src/wifi_p2p_impl.cpp @@ -1,5 +1,5 @@ /* - * Copyright (C) 2021 Huawei Device Co., Ltd. + * Copyright (C) 2021-2022 Huawei Device Co., Ltd. * 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 @@ -14,6 +14,8 @@ */ #include "wifi_p2p_impl.h" #include "iservice_registry.h" +#include "if_config.h" +#include "mac_address.h" #include "wifi_logger.h" DEFINE_WIFILOG_P2P_LABEL("WifiP2pImpl"); @@ -127,10 +129,10 @@ ErrCode WifiP2pImpl::StopP2pListen(void) return client_->StopP2pListen(); } -ErrCode WifiP2pImpl::FormGroup(const WifiP2pConfig &config) +ErrCode WifiP2pImpl::CreateGroup(const WifiP2pConfig &config) { RETURN_IF_FAIL(client_); - return client_->FormGroup(config); + return client_->CreateGroup(config); } ErrCode WifiP2pImpl::RemoveGroup(void) @@ -151,16 +153,16 @@ ErrCode WifiP2pImpl::P2pConnect(const WifiP2pConfig &config) return client_->P2pConnect(config); } -ErrCode WifiP2pImpl::P2pDisConnect(void) +ErrCode WifiP2pImpl::P2pCancelConnect(void) { RETURN_IF_FAIL(client_); - return client_->P2pDisConnect(); + return client_->P2pCancelConnect(); } -ErrCode WifiP2pImpl::QueryP2pInfo(WifiP2pInfo &connInfo) +ErrCode WifiP2pImpl::QueryP2pLinkedInfo(WifiP2pLinkedInfo &linkedInfo) { RETURN_IF_FAIL(client_); - return client_->QueryP2pInfo(connInfo); + return client_->QueryP2pLinkedInfo(linkedInfo); } ErrCode WifiP2pImpl::GetCurrentGroup(WifiP2pGroupInfo &group) @@ -187,10 +189,16 @@ ErrCode WifiP2pImpl::GetP2pConnectedStatus(int &status) return client_->GetP2pConnectedStatus(status); } -ErrCode WifiP2pImpl::QueryP2pDevices(std::vector &devives) +ErrCode WifiP2pImpl::QueryP2pDevices(std::vector &devices) { RETURN_IF_FAIL(client_); - return client_->QueryP2pDevices(devives); + return client_->QueryP2pDevices(devices); +} + +ErrCode WifiP2pImpl::QueryP2pLocalDevice(WifiP2pDevice &devices) +{ + RETURN_IF_FAIL(client_); + return client_->QueryP2pLocalDevice(devices); } ErrCode WifiP2pImpl::QueryP2pGroups(std::vector &groups) @@ -226,15 +234,96 @@ bool WifiP2pImpl::IsFeatureSupported(long feature) } return ((tmpFeatures & feature) == feature); } + ErrCode WifiP2pImpl::SetP2pDeviceName(const std::string &deviceName) { RETURN_IF_FAIL(client_); return client_->SetP2pDeviceName(deviceName); } + ErrCode WifiP2pImpl::SetP2pWfdInfo(const WifiP2pWfdInfo &wfdInfo) { RETURN_IF_FAIL(client_); return client_->SetP2pWfdInfo(wfdInfo); } + +ErrCode WifiP2pImpl::Hid2dRequestGcIp(const std::string& gcMac, std::string& ipAddr) +{ + RETURN_IF_FAIL(client_); + return client_->Hid2dRequestGcIp(gcMac, ipAddr); +} + +ErrCode WifiP2pImpl::Hid2dSharedlinkIncrease() +{ + RETURN_IF_FAIL(client_); + return client_->Hid2dSharedlinkIncrease(); +} + +ErrCode WifiP2pImpl::Hid2dSharedlinkDecrease() +{ + RETURN_IF_FAIL(client_); + return client_->Hid2dSharedlinkDecrease(); +} + +ErrCode WifiP2pImpl::Hid2dCreateGroup(const int frequency, FreqType type) +{ + RETURN_IF_FAIL(client_); + return client_->Hid2dCreateGroup(frequency, type); +} + +ErrCode WifiP2pImpl::Hid2dRemoveGcGroup(const std::string& gcIfName) +{ + RETURN_IF_FAIL(client_); + return client_->Hid2dRemoveGcGroup(gcIfName); +} + +ErrCode WifiP2pImpl::Hid2dConnect(const Hid2dConnectConfig& config) +{ + RETURN_IF_FAIL(client_); + return client_->Hid2dConnect(config); +} + +ErrCode WifiP2pImpl::Hid2dConfigIPAddr(const std::string& ifName, const IpAddrInfo& ipInfo) +{ + RETURN_IF_FAIL(client_); + return client_->Hid2dConfigIPAddr(ifName, ipInfo); +} + +ErrCode WifiP2pImpl::Hid2dReleaseIPAddr(const std::string& ifName) +{ + RETURN_IF_FAIL(client_); + return client_->Hid2dReleaseIPAddr(ifName); +} + +ErrCode WifiP2pImpl::Hid2dGetRecommendChannel(const RecommendChannelRequest& request, + RecommendChannelResponse& response) +{ + RETURN_IF_FAIL(client_); + return client_->Hid2dGetRecommendChannel(request, response); +} + +ErrCode WifiP2pImpl::Hid2dGetChannelListFor5G(std::vector& vecChannelList) +{ + RETURN_IF_FAIL(client_); + return client_->Hid2dGetChannelListFor5G(vecChannelList); +} + +ErrCode WifiP2pImpl::Hid2dGetSelfWifiCfgInfo(SelfCfgType cfgType, char cfgData[CFG_DATA_MAX_BYTES], int* getDatValidLen) +{ + RETURN_IF_FAIL(client_); + return client_->Hid2dGetSelfWifiCfgInfo(cfgType, cfgData, getDatValidLen); +} + +ErrCode WifiP2pImpl::Hid2dSetPeerWifiCfgInfo(PeerCfgType cfgType, char cfgData[CFG_DATA_MAX_BYTES], int setDataValidLen) +{ + RETURN_IF_FAIL(client_); + return client_->Hid2dSetPeerWifiCfgInfo(cfgType, cfgData, setDataValidLen); +} + +ErrCode WifiP2pImpl::Hid2dSetUpperScene(const std::string& ifName, const Hid2dUpperScene& scene) +{ + RETURN_IF_FAIL(client_); + return client_->Hid2dSetUpperScene(ifName, scene); +} } // namespace Wifi } // namespace OHOS \ No newline at end of file diff --git a/interfaces/innerkits/native_cpp/wifi_standard/src/wifi_p2p_impl.h b/wifi/frameworks/native/src/wifi_p2p_impl.h similarity index 49% rename from interfaces/innerkits/native_cpp/wifi_standard/src/wifi_p2p_impl.h rename to wifi/frameworks/native/src/wifi_p2p_impl.h index 595ee4db928887c4cb109a5170935f90ffd42d0b..65d6d2674ad09f9e76bea2dccbcd5b7143f7bf65 100644 --- a/interfaces/innerkits/native_cpp/wifi_standard/src/wifi_p2p_impl.h +++ b/wifi/frameworks/native/src/wifi_p2p_impl.h @@ -1,5 +1,5 @@ /* - * Copyright (C) 2021 Huawei Device Co., Ltd. + * Copyright (C) 2021-2022 Huawei Device Co., Ltd. * 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 @@ -17,10 +17,11 @@ #include "wifi_p2p.h" #include "wifi_p2p_proxy.h" +#include "wifi_hid2d.h" namespace OHOS { namespace Wifi { -class WifiP2pImpl : public WifiP2p { +class WifiP2pImpl : public WifiP2p, public Hid2d { public: explicit WifiP2pImpl(int systemAbilityId); ~WifiP2pImpl(); @@ -30,42 +31,42 @@ public: /** * @Description Enabling the P2P Mode * - * @return ErrCode - operate result + * @return ErrCode - operation result */ ErrCode EnableP2p(void) override; /** * @Description Disable the P2P mode * - * @return ErrCode - operate result + * @return ErrCode - operation result */ ErrCode DisableP2p(void) override; /** * @Description Start Wi-Fi P2P device search * - * @return ErrCode - operate result + * @return ErrCode - operation result */ ErrCode DiscoverDevices(void) override; /** * @Description Stop Wi-Fi P2P device search * - * @return ErrCode - operate result + * @return ErrCode - operation result */ ErrCode StopDiscoverDevices(void) override; /** * @Description Start the search for the Wi-Fi P2P service * - * @return ErrCode - operate result + * @return ErrCode - operation result */ ErrCode DiscoverServices(void) override; /** * @Description Stop the search for the Wi-Fi P2P service * - * @return ErrCode - operate result + * @return ErrCode - operation result */ ErrCode StopDiscoverServices(void) override; @@ -74,7 +75,7 @@ public: * * @param device - WifiP2pDevice object * @param request - WifiP2pServiceRequest object - * @return ErrCode - operate result + * @return ErrCode - operation result */ ErrCode RequestService(const WifiP2pDevice &device, const WifiP2pServiceRequest &request) override; @@ -82,7 +83,7 @@ public: * @Description Register the local P2P service * * @param srvInfo - WifiP2pServiceInfo object - * @return ErrCode - operate result + * @return ErrCode - operation result */ ErrCode PutLocalP2pService(const WifiP2pServiceInfo &srvInfo) override; @@ -90,7 +91,7 @@ public: * @Description Delete the local P2P service * * @param srvInfo - WifiP2pServiceInfo object - * @return ErrCode - operate result + * @return ErrCode - operation result */ ErrCode DeleteLocalP2pService(const WifiP2pServiceInfo &srvInfo) override; @@ -99,14 +100,14 @@ public: * * @param period - period * @param interval - interval - * @return ErrCode - operate result + * @return ErrCode - operation result */ ErrCode StartP2pListen(int period, int interval) override; /** * @Description Disable Wi-Fi P2P listening * - * @return ErrCode - operate result + * @return ErrCode - operation result */ ErrCode StopP2pListen(void) override; @@ -114,15 +115,15 @@ public: * @Description Creating a P2P Group * * @param config - WifiP2pGroupInfo object - * @return ErrCode - operate result + * @return ErrCode - operation result */ - ErrCode FormGroup(const WifiP2pConfig &config) override; + ErrCode CreateGroup(const WifiP2pConfig &config) override; /** * @Description Remove a P2P Group * * - * @return ErrCode - operate result + * @return ErrCode - operation result */ ErrCode RemoveGroup(void) override; @@ -130,7 +131,7 @@ public: * @Description Delete a p2p Group * * @param group - WifiP2pGroupInfo object - * @return ErrCode - operate result + * @return ErrCode - operation result */ ErrCode DeleteGroup(const WifiP2pGroupInfo &group) override; @@ -138,30 +139,30 @@ public: * @Description P2P connection * * @param config - WifiP2pConfig object - * @return ErrCode - operate result + * @return ErrCode - operation result */ ErrCode P2pConnect(const WifiP2pConfig &config) override; /** - * @Description P2P disconnection + * @Description Canceling a P2P connection * - * @return ErrCode - operate result + * @return ErrCode - operation result */ - ErrCode P2pDisConnect(void) override; + ErrCode P2pCancelConnect(void) override; /** * @Description Querying Wi-Fi P2P Connection Information * - * @param connInfo - Get the WifiP2pInfo msg - * @return ErrCode - operate result + * @param linkedInfo - Get the WifiP2pLinkedInfo msg + * @return ErrCode - operation result */ - ErrCode QueryP2pInfo(WifiP2pInfo &connInfo) override; + ErrCode QueryP2pLinkedInfo(WifiP2pLinkedInfo &linkedInfo) override; /** * @Description Get the Current Group object * * @param group - the WifiP2pGroupInfo object - * @return ErrCode - operate result + * @return ErrCode - operation result */ ErrCode GetCurrentGroup(WifiP2pGroupInfo &group) override; @@ -169,7 +170,7 @@ public: * @Description Obtains the P2P switch status * * @param status - the P2P switch status - * @return ErrCode - operate result + * @return ErrCode - operation result */ ErrCode GetP2pEnableStatus(int &status) override; @@ -185,23 +186,31 @@ public: * @Description Obtains the P2P connection status * * @param status - the P2P connection status - * @return ErrCode - operate result + * @return ErrCode - operation result */ ErrCode GetP2pConnectedStatus(int &status) override; /** * @Description Query the information about the found devices * - * @param devives - Get result vector of WifiP2pDevice - * @return ErrCode - operate result + * @param devices - Get result vector of WifiP2pDevice + * @return ErrCode - operation result + */ + ErrCode QueryP2pDevices(std::vector &devices) override; + + /** + * @Description Query the information about the local device + * + * @param devives - Get result of WifiP2pDevice + * @return ErrCode - operation result */ - ErrCode QueryP2pDevices(std::vector &devives) override; + ErrCode QueryP2pLocalDevice(WifiP2pDevice &devive) override; /** * @Description Query the information about the found groups * * @param groups - Get result vector of WifiP2pGroupInfo - * @return ErrCode - operate result + * @return ErrCode - operation result */ ErrCode QueryP2pGroups(std::vector &groups) override; @@ -209,7 +218,7 @@ public: * @Description Query the service information * * @param services - Get result vector of Device - * @return ErrCode - operate result + * @return ErrCode - operation result */ ErrCode QueryP2pServices(std::vector &services) override; @@ -217,7 +226,7 @@ public: * @Description Register callback function * * @param callback - IWifiP2pCallback object - * @return ErrCode - operate result + * @return ErrCode - operation result */ ErrCode RegisterCallBack(const sptr &callback) override; @@ -242,7 +251,7 @@ public: * @Description set the device name * * @param deviceName - device name - * @return ErrCode - operate result + * @return ErrCode - operation result */ ErrCode SetP2pDeviceName(const std::string &deviceName) override; @@ -250,10 +259,124 @@ public: * @Description set p2p wifi display info * * @param wfdInfo - wifi display info - * @return ErrCode - operate result + * @return ErrCode - operation result */ ErrCode SetP2pWfdInfo(const WifiP2pWfdInfo &wfdInfo) override; + /** + * @Description Request an IP address to the Gc from the IP address pool, used on the GO side. + * + * @param gcMac - gc mac address + * @param ipAddr - applied ip address + * @return ErrCode - operation result + */ + ErrCode Hid2dRequestGcIp(const std::string& gcMac, std::string& ipAddr) override; + + /** + * @Description Increase(+1) hid2d shared link reference counting + * + * @return ErrCode - operation result + */ + ErrCode Hid2dSharedlinkIncrease() override; + + /** + * @Description Decrease(-1) hid2d shared link reference counting + * + * @return ErrCode - operation result + */ + ErrCode Hid2dSharedlinkDecrease() override; + + /** + * @Description Create hid2d group, used on the GO side. + * + * @param frequency - frequency + * @param type - frequency type + * @return ErrCode - operation result + */ + ErrCode Hid2dCreateGroup(const int frequency, FreqType type) override; + + /** + * @Description The GC side actively disconnects from the GO, used on the GC side. + * + * @param gcIfName - network interface name + * @return ErrCode - operation result + */ + ErrCode Hid2dRemoveGcGroup(const std::string& gcIfName) override; + + /** + * @Description Connect to a specified group using hid2d, used on the GC side. + * + * @param config - connection parameters + * @return ErrCode - operation result + */ + ErrCode Hid2dConnect(const Hid2dConnectConfig& config) override; + + /** + * @Description Configuring IP addresses for P2P network interfaces, used on the GC side. + * + * @param ifName - network interface name + * @param ipInfo - IP infos + * @return ErrCode - operation result + */ + ErrCode Hid2dConfigIPAddr(const std::string& ifName, const IpAddrInfo& ipInfo) override; + + /** + * @Description Clear IP address when the P2P connection is disconnected, used on the GC side. + * + * @param ifName - network interface name + * @return ErrCode - operation result + */ + ErrCode Hid2dReleaseIPAddr(const std::string& ifName) override; + + /** + * @Description Obtain the recommended channel and bandwidth for link setup + * + * @param request - request data + * @param response - response result + * @return ErrCode - operation result + */ + ErrCode Hid2dGetRecommendChannel(const RecommendChannelRequest& request, + RecommendChannelResponse& response) override; + + /** + * @Description get 5G channel list + * + * @param vecChannelList - result for channel list + * @return ErrCode - operation result + */ + ErrCode Hid2dGetChannelListFor5G(std::vector& vecChannelList) override; + + /** + * @Description get the self wifi configuration information + * + * @param cfgType - configuration type + * @param cfgData - the queried data of wifi configuration + * @param getDatValidLen - the valid data length in the array `cfgData` + * @return ErrCode - operation result + */ + ErrCode Hid2dGetSelfWifiCfgInfo(SelfCfgType cfgType, + char cfgData[CFG_DATA_MAX_BYTES], int* getDatValidLen) override; + + /** + * @Description set the peer wifi configuration information + * + * @param cfgType - configuration type + * @param cfgData - the wifi configuration data to be set + * @param setDataValidLen - the valid data length in the array `cfgData` + * @return ErrCode - operation result + */ + ErrCode Hid2dSetPeerWifiCfgInfo(PeerCfgType cfgType, + char cfgData[CFG_DATA_MAX_BYTES], int setDataValidLen) override; + + /** + * @Description Set the scene of upper layer + * + * @param ifName - interface name + * @param scene - scene + * @return ErrCode - operate result + */ + ErrCode Hid2dSetUpperScene(const std::string& ifName, const Hid2dUpperScene& scene) override; + private: int systemAbilityId_; sptr client_; diff --git a/interfaces/innerkits/native_cpp/wifi_standard/src/wifi_p2p_msg.cpp b/wifi/frameworks/native/src/wifi_p2p_msg.cpp similarity index 95% rename from interfaces/innerkits/native_cpp/wifi_standard/src/wifi_p2p_msg.cpp rename to wifi/frameworks/native/src/wifi_p2p_msg.cpp index 9945f237fe58b60c0baa775aa72e0f70b1c59f0a..9fffd2342ddb2b8a3e6d2f6e1506fd0e5340c1c4 100644 --- a/interfaces/innerkits/native_cpp/wifi_standard/src/wifi_p2p_msg.cpp +++ b/wifi/frameworks/native/src/wifi_p2p_msg.cpp @@ -93,6 +93,16 @@ const std::string &WifiP2pDevice::GetDeviceName() const return deviceName; } +void WifiP2pDevice::SetNetworkName(const std::string &name) +{ + networkName = name; +} + +const std::string &WifiP2pDevice::GetNetworkName() const +{ + return networkName; +} + void WifiP2pDevice::SetDeviceAddress(const std::string &deviceAddress) { mDeviceAddress = deviceAddress; @@ -226,11 +236,6 @@ bool WifiP2pDevice::WpKeypadSupported() const return (supportWpsConfigMethods & static_cast(WpsConfigMethod::WPS_CFG_KEYPAD)) != 0; } -bool WifiP2pDevice::isGroupOwner() const -{ - return (groupCapabilitys & static_cast(P2pGroupCapability::PGC_GROUP_OWNER)) != 0; -} - bool WifiP2pGroupInfo::operator==(const WifiP2pGroupInfo &group) const { return networkId == group.GetNetworkId(); @@ -382,6 +387,16 @@ bool WifiP2pGroupInfo::IsClientDevicesEmpty() const return clientDevices.empty(); } +bool WifiP2pGroupInfo::IsExplicitGroup(void) const +{ + return explicitGroup; +} + +void WifiP2pGroupInfo::SetExplicitGroup(bool isExplicit) +{ + explicitGroup = isExplicit; +} + const std::vector &WifiP2pGroupInfo::GetClientDevices() const { return clientDevices; @@ -467,16 +482,6 @@ const std::string &WifiP2pConfig::GetPassphrase() const return passphrase; } -void WifiP2pConfig::SetWpsInfo(const WpsInfo &info) -{ - wpsInfo = info; -} - -const WpsInfo &WifiP2pConfig::GetWpsInfo() const -{ - return wpsInfo; -} - void WifiP2pConfig::SetGroupOwnerIntent(int intent) { groupOwnerIntent = intent; @@ -487,42 +492,42 @@ int WifiP2pConfig::GetGroupOwnerIntent() const return groupOwnerIntent; } -void WifiP2pConfig::SetNetworkName(const std::string &setNetworkName) +void WifiP2pConfig::SetGroupName(const std::string &setGroupName) { - networkName = setNetworkName; + groupName = setGroupName; } -const std::string &WifiP2pConfig::GetNetworkName() const +const std::string &WifiP2pConfig::GetGroupName() const { - return networkName; + return groupName; } -void WifiP2pInfo::SetConnectState(P2pConnectedState setConnectState) +void WifiP2pLinkedInfo::SetConnectState(P2pConnectedState setConnectState) { connectState = setConnectState; } -P2pConnectedState WifiP2pInfo::GetConnectState() const +P2pConnectedState WifiP2pLinkedInfo::GetConnectState() const { return connectState; } -void WifiP2pInfo::SetIsGroupOwner(bool isGroupOwner) +void WifiP2pLinkedInfo::SetIsGroupOwner(bool isGroupOwner) { isP2pGroupOwner = isGroupOwner; } -const bool &WifiP2pInfo::IsGroupOwner() const +const bool &WifiP2pLinkedInfo::IsGroupOwner() const { return isP2pGroupOwner; } -void WifiP2pInfo::SetIsGroupOwnerAddress(const std::string &setGroupOwnerAddress) +void WifiP2pLinkedInfo::SetIsGroupOwnerAddress(const std::string &setGroupOwnerAddress) { groupOwnerAddress = setGroupOwnerAddress; } -const std::string &WifiP2pInfo::GetGroupOwnerAddress() const +const std::string &WifiP2pLinkedInfo::GetGroupOwnerAddress() const { return groupOwnerAddress; } @@ -825,4 +830,4 @@ void P2pVendorConfig::SetSecondaryDeviceType(const std::string &setSecondaryDevi secondaryDeviceType = setSecondaryDeviceType; } } // namespace Wifi -} // namespace OHOS \ No newline at end of file +} // namespace OHOS diff --git a/interfaces/innerkits/native_cpp/wifi_standard/src/wifi_p2p_proxy.cpp b/wifi/frameworks/native/src/wifi_p2p_proxy.cpp similarity index 52% rename from interfaces/innerkits/native_cpp/wifi_standard/src/wifi_p2p_proxy.cpp rename to wifi/frameworks/native/src/wifi_p2p_proxy.cpp index 8950ce0772ef654c036b9fa4f0e5d0dac5de41ce..7ec88adab2ed233e5e5d8e7cb396216deb8eae2d 100644 --- a/interfaces/innerkits/native_cpp/wifi_standard/src/wifi_p2p_proxy.cpp +++ b/wifi/frameworks/native/src/wifi_p2p_proxy.cpp @@ -1,5 +1,5 @@ /* - * Copyright (C) 2021 Huawei Device Co., Ltd. + * Copyright (C) 2021-2022 Huawei Device Co., Ltd. * 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 @@ -21,7 +21,8 @@ namespace OHOS { namespace Wifi { DEFINE_WIFILOG_P2P_LABEL("WifiP2pProxy"); -static WifiP2pCallbackStub g_wifiP2pCallbackStub; +static sptr g_wifiP2pCallbackStub = + sptr(new (std::nothrow) WifiP2pCallbackStub()); WifiP2pProxy::WifiP2pProxy(const sptr &impl) : IRemoteProxy(impl), mRemoteDied(false) { if (impl) { @@ -39,12 +40,16 @@ WifiP2pProxy::~WifiP2pProxy() ErrCode WifiP2pProxy::EnableP2p(void) { if (mRemoteDied) { - WIFI_LOGD("failed to `%{public}s`,remote service is died!", __func__); + WIFI_LOGW("failed to `%{public}s`,remote service is died!", __func__); return WIFI_OPT_FAILED; } MessageOption option; MessageParcel data; MessageParcel reply; + if (!data.WriteInterfaceToken(GetDescriptor())) { + WIFI_LOGE("Write interface token error: %{public}s", __func__); + return WIFI_OPT_FAILED; + } data.WriteInt32(0); int error = Remote()->SendRequest(WIFI_SVR_CMD_P2P_ENABLE, data, reply, option); if (error != ERR_NONE) { @@ -61,12 +66,16 @@ ErrCode WifiP2pProxy::EnableP2p(void) ErrCode WifiP2pProxy::DisableP2p(void) { if (mRemoteDied) { - WIFI_LOGD("failed to `%{public}s`,remote service is died!", __func__); + WIFI_LOGW("failed to `%{public}s`,remote service is died!", __func__); return WIFI_OPT_FAILED; } MessageOption option; MessageParcel data; MessageParcel reply; + if (!data.WriteInterfaceToken(GetDescriptor())) { + WIFI_LOGE("Write interface token error: %{public}s", __func__); + return WIFI_OPT_FAILED; + } data.WriteInt32(0); int error = Remote()->SendRequest(WIFI_SVR_CMD_P2P_DISABLE, data, reply, option); if (error != ERR_NONE) { @@ -84,12 +93,16 @@ ErrCode WifiP2pProxy::DisableP2p(void) ErrCode WifiP2pProxy::DiscoverDevices(void) { if (mRemoteDied) { - WIFI_LOGD("failed to `%{public}s`,remote service is died!", __func__); + WIFI_LOGW("failed to `%{public}s`,remote service is died!", __func__); return WIFI_OPT_FAILED; } MessageOption option; MessageParcel data; MessageParcel reply; + if (!data.WriteInterfaceToken(GetDescriptor())) { + WIFI_LOGE("Write interface token error: %{public}s", __func__); + return WIFI_OPT_FAILED; + } data.WriteInt32(0); int error = Remote()->SendRequest(WIFI_SVR_CMD_P2P_DISCOVER_DEVICES, data, reply, option); if (error != ERR_NONE) { @@ -107,12 +120,16 @@ ErrCode WifiP2pProxy::DiscoverDevices(void) ErrCode WifiP2pProxy::StopDiscoverDevices(void) { if (mRemoteDied) { - WIFI_LOGD("failed to `%{public}s`,remote service is died!", __func__); + WIFI_LOGW("failed to `%{public}s`,remote service is died!", __func__); return WIFI_OPT_FAILED; } MessageOption option; MessageParcel data; MessageParcel reply; + if (!data.WriteInterfaceToken(GetDescriptor())) { + WIFI_LOGE("Write interface token error: %{public}s", __func__); + return WIFI_OPT_FAILED; + } data.WriteInt32(0); int error = Remote()->SendRequest(WIFI_SVR_CMD_P2P_STOP_DISCOVER_DEVICES, data, reply, option); if (error != ERR_NONE) { @@ -131,12 +148,16 @@ ErrCode WifiP2pProxy::StopDiscoverDevices(void) ErrCode WifiP2pProxy::DiscoverServices(void) { if (mRemoteDied) { - WIFI_LOGD("failed to `%{public}s`,remote service is died!", __func__); + WIFI_LOGW("failed to `%{public}s`,remote service is died!", __func__); return WIFI_OPT_FAILED; } MessageOption option; MessageParcel data; MessageParcel reply; + if (!data.WriteInterfaceToken(GetDescriptor())) { + WIFI_LOGE("Write interface token error: %{public}s", __func__); + return WIFI_OPT_FAILED; + } data.WriteInt32(0); int error = Remote()->SendRequest(WIFI_SVR_CMD_P2P_DISCOVER_SERVICES, data, reply, option); if (error != ERR_NONE) { @@ -154,12 +175,16 @@ ErrCode WifiP2pProxy::DiscoverServices(void) ErrCode WifiP2pProxy::StopDiscoverServices(void) { if (mRemoteDied) { - WIFI_LOGD("failed to `%{public}s`,remote service is died!", __func__); + WIFI_LOGW("failed to `%{public}s`,remote service is died!", __func__); return WIFI_OPT_FAILED; } MessageOption option; MessageParcel data; MessageParcel reply; + if (!data.WriteInterfaceToken(GetDescriptor())) { + WIFI_LOGE("Write interface token error: %{public}s", __func__); + return WIFI_OPT_FAILED; + } data.WriteInt32(0); int error = Remote()->SendRequest(WIFI_SVR_CMD_P2P_STOP_DISCOVER_SERVICES, data, reply, option); if (error != ERR_NONE) { @@ -178,12 +203,16 @@ ErrCode WifiP2pProxy::StopDiscoverServices(void) ErrCode WifiP2pProxy::RequestService(const WifiP2pDevice &device, const WifiP2pServiceRequest &request) { if (mRemoteDied) { - WIFI_LOGD("failed to `%{public}s`,remote service is died!", __func__); + WIFI_LOGW("failed to `%{public}s`,remote service is died!", __func__); return WIFI_OPT_FAILED; } MessageOption option; MessageParcel data; MessageParcel reply; + if (!data.WriteInterfaceToken(GetDescriptor())) { + WIFI_LOGE("Write interface token error: %{public}s", __func__); + return WIFI_OPT_FAILED; + } data.WriteInt32(0); WriteWifiP2pServiceRequest(data, device, request); int error = Remote()->SendRequest(WIFI_SVR_CMD_P2P_REQUEST_SERVICES, data, reply, option); @@ -202,12 +231,16 @@ ErrCode WifiP2pProxy::RequestService(const WifiP2pDevice &device, const WifiP2pS ErrCode WifiP2pProxy::PutLocalP2pService(const WifiP2pServiceInfo &srvInfo) { if (mRemoteDied) { - WIFI_LOGD("failed to `%{public}s`,remote service is died!", __func__); + WIFI_LOGW("failed to `%{public}s`,remote service is died!", __func__); return WIFI_OPT_FAILED; } MessageOption option; MessageParcel data; MessageParcel reply; + if (!data.WriteInterfaceToken(GetDescriptor())) { + WIFI_LOGE("Write interface token error: %{public}s", __func__); + return WIFI_OPT_FAILED; + } data.WriteInt32(0); WriteWifiP2pServiceInfo(data, srvInfo); int error = Remote()->SendRequest(WIFI_SVR_CMD_P2P_PUT_LOCAL_SERVICES, data, reply, option); @@ -226,12 +259,16 @@ ErrCode WifiP2pProxy::PutLocalP2pService(const WifiP2pServiceInfo &srvInfo) ErrCode WifiP2pProxy::DeleteLocalP2pService(const WifiP2pServiceInfo &srvInfo) { if (mRemoteDied) { - WIFI_LOGD("failed to `%{public}s`,remote service is died!", __func__); + WIFI_LOGW("failed to `%{public}s`,remote service is died!", __func__); return WIFI_OPT_FAILED; } MessageOption option; MessageParcel data; MessageParcel reply; + if (!data.WriteInterfaceToken(GetDescriptor())) { + WIFI_LOGE("Write interface token error: %{public}s", __func__); + return WIFI_OPT_FAILED; + } data.WriteInt32(0); WriteWifiP2pServiceInfo(data, srvInfo); int error = Remote()->SendRequest(WIFI_SVR_CMD_P2P_DELETE_LOCAL_SERVICES, data, reply, option); @@ -251,12 +288,16 @@ ErrCode WifiP2pProxy::DeleteLocalP2pService(const WifiP2pServiceInfo &srvInfo) ErrCode WifiP2pProxy::StartP2pListen(int period, int interval) { if (mRemoteDied) { - WIFI_LOGD("failed to `%{public}s`,remote service is died!", __func__); + WIFI_LOGW("failed to `%{public}s`,remote service is died!", __func__); return WIFI_OPT_FAILED; } MessageOption option; MessageParcel data; MessageParcel reply; + if (!data.WriteInterfaceToken(GetDescriptor())) { + WIFI_LOGE("Write interface token error: %{public}s", __func__); + return WIFI_OPT_FAILED; + } data.WriteInt32(0); data.WriteInt32(period); data.WriteInt32(interval); @@ -276,12 +317,16 @@ ErrCode WifiP2pProxy::StartP2pListen(int period, int interval) ErrCode WifiP2pProxy::StopP2pListen(void) { if (mRemoteDied) { - WIFI_LOGD("failed to `%{public}s`,remote service is died!", __func__); + WIFI_LOGW("failed to `%{public}s`,remote service is died!", __func__); return WIFI_OPT_FAILED; } MessageOption option; MessageParcel data; MessageParcel reply; + if (!data.WriteInterfaceToken(GetDescriptor())) { + WIFI_LOGE("Write interface token error: %{public}s", __func__); + return WIFI_OPT_FAILED; + } data.WriteInt32(0); int error = Remote()->SendRequest(WIFI_SVR_CMD_P2P_STOP_LISTEN, data, reply, option); if (error != ERR_NONE) { @@ -296,20 +341,24 @@ ErrCode WifiP2pProxy::StopP2pListen(void) return ErrCode(reply.ReadInt32()); } -ErrCode WifiP2pProxy::FormGroup(const WifiP2pConfig &config) +ErrCode WifiP2pProxy::CreateGroup(const WifiP2pConfig &config) { if (mRemoteDied) { - WIFI_LOGD("failed to `%{public}s`,remote service is died!", __func__); + WIFI_LOGW("failed to `%{public}s`,remote service is died!", __func__); return WIFI_OPT_FAILED; } MessageOption option; MessageParcel data; MessageParcel reply; + if (!data.WriteInterfaceToken(GetDescriptor())) { + WIFI_LOGE("Write interface token error: %{public}s", __func__); + return WIFI_OPT_FAILED; + } data.WriteInt32(0); WriteWifiP2pConfigData(data, config); - int error = Remote()->SendRequest(WIFI_SVR_CMD_P2P_FORM_GROUP, data, reply, option); + int error = Remote()->SendRequest(WIFI_SVR_CMD_P2P_CREATE_GROUP, data, reply, option); if (error != ERR_NONE) { - WIFI_LOGE("Set Attr(%{public}d) failed,error code is %{public}d", WIFI_SVR_CMD_P2P_FORM_GROUP, error); + WIFI_LOGE("Set Attr(%{public}d) failed,error code is %{public}d", WIFI_SVR_CMD_P2P_CREATE_GROUP, error); return WIFI_OPT_FAILED; } @@ -323,12 +372,16 @@ ErrCode WifiP2pProxy::FormGroup(const WifiP2pConfig &config) ErrCode WifiP2pProxy::RemoveGroup() { if (mRemoteDied) { - WIFI_LOGD("failed to `%{public}s`,remote service is died!", __func__); + WIFI_LOGW("failed to `%{public}s`,remote service is died!", __func__); return WIFI_OPT_FAILED; } MessageOption option; MessageParcel data; MessageParcel reply; + if (!data.WriteInterfaceToken(GetDescriptor())) { + WIFI_LOGE("Write interface token error: %{public}s", __func__); + return WIFI_OPT_FAILED; + } data.WriteInt32(0); int error = Remote()->SendRequest(WIFI_SVR_CMD_P2P_REMOVE_GROUP, data, reply, option); if (error != ERR_NONE) { @@ -345,12 +398,16 @@ ErrCode WifiP2pProxy::RemoveGroup() ErrCode WifiP2pProxy::DeleteGroup(const WifiP2pGroupInfo &group) { if (mRemoteDied) { - WIFI_LOGD("failed to `%{public}s`,remote service is died!", __func__); + WIFI_LOGW("failed to `%{public}s`,remote service is died!", __func__); return WIFI_OPT_FAILED; } MessageOption option; MessageParcel data; MessageParcel reply; + if (!data.WriteInterfaceToken(GetDescriptor())) { + WIFI_LOGE("Write interface token error: %{public}s", __func__); + return WIFI_OPT_FAILED; + } data.WriteInt32(0); WriteWifiP2pGroupData(data, group); int error = Remote()->SendRequest(WIFI_SVR_CMD_P2P_DELETE_GROUP, data, reply, option); @@ -371,7 +428,13 @@ void WifiP2pProxy::ReadWifiP2pServiceInfo(MessageParcel &reply, WifiP2pServiceIn info.SetDeviceAddress(reply.ReadCString()); info.SetServicerProtocolType(static_cast(reply.ReadInt32())); std::vector queryList; + + constexpr int MAX_SIZE = 512; int size = reply.ReadInt32(); + if (size > MAX_SIZE) { + WIFI_LOGE("P2p service size error: %{public}d", size); + return; + } for (int i = 0; i < size; i++) { std::string str = reply.ReadCString(); queryList.push_back(str); @@ -475,7 +538,13 @@ void WifiP2pProxy::ReadWifiP2pGroupData(MessageParcel &reply, WifiP2pGroupInfo & info.SetP2pGroupStatus(static_cast(reply.ReadInt32())); info.SetNetworkId(reply.ReadInt32()); info.SetGoIpAddress(reply.ReadCString()); + + constexpr int MAX_SIZE = 512; int size = reply.ReadInt32(); + if (size > MAX_SIZE) { + WIFI_LOGE("Group info device size error: %{public}d", size); + return; + } for (auto it = 0; it < size; ++it) { WifiP2pDevice cliDev; ReadWifiP2pDeviceData(reply, cliDev); @@ -487,24 +556,25 @@ void WifiP2pProxy::WriteWifiP2pConfigData(MessageParcel &data, const WifiP2pConf { data.WriteCString(config.GetDeviceAddress().c_str()); data.WriteCString(config.GetPassphrase().c_str()); - data.WriteCString(config.GetNetworkName().c_str()); + data.WriteCString(config.GetGroupName().c_str()); data.WriteInt32(static_cast(config.GetGoBand())); data.WriteInt32(config.GetNetId()); data.WriteInt32(config.GetGroupOwnerIntent()); - data.WriteInt32(static_cast(config.GetWpsInfo().GetWpsMethod())); - data.WriteCString(config.GetWpsInfo().GetBssid().c_str()); - data.WriteCString(config.GetWpsInfo().GetPin().c_str()); } ErrCode WifiP2pProxy::P2pConnect(const WifiP2pConfig &config) { if (mRemoteDied) { - WIFI_LOGD("failed to `%{public}s`,remote service is died!", __func__); + WIFI_LOGW("failed to `%{public}s`,remote service is died!", __func__); return WIFI_OPT_FAILED; } MessageOption option; MessageParcel data; MessageParcel reply; + if (!data.WriteInterfaceToken(GetDescriptor())) { + WIFI_LOGE("Write interface token error: %{public}s", __func__); + return WIFI_OPT_FAILED; + } data.WriteInt32(0); WriteWifiP2pConfigData(data, config); int error = Remote()->SendRequest(WIFI_SVR_CMD_P2P_CONNECT, data, reply, option); @@ -520,19 +590,23 @@ ErrCode WifiP2pProxy::P2pConnect(const WifiP2pConfig &config) return ErrCode(reply.ReadInt32()); } -ErrCode WifiP2pProxy::P2pDisConnect() +ErrCode WifiP2pProxy::P2pCancelConnect() { if (mRemoteDied) { - WIFI_LOGD("failed to `%{public}s`,remote service is died!", __func__); + WIFI_LOGW("failed to `%{public}s`,remote service is died!", __func__); return WIFI_OPT_FAILED; } MessageOption option; MessageParcel data; MessageParcel reply; + if (!data.WriteInterfaceToken(GetDescriptor())) { + WIFI_LOGE("Write interface token error: %{public}s", __func__); + return WIFI_OPT_FAILED; + } data.WriteInt32(0); - int error = Remote()->SendRequest(WIFI_SVR_CMD_P2P_DISCONNECT, data, reply, option); + int error = Remote()->SendRequest(WIFI_SVR_CMD_P2P_CANCEL_CONNECT, data, reply, option); if (error != ERR_NONE) { - WIFI_LOGE("Set Attr(%{public}d) failed,error code is %{public}d", WIFI_SVR_CMD_P2P_DISCONNECT, error); + WIFI_LOGE("Set Attr(%{public}d) failed,error code is %{public}d", WIFI_SVR_CMD_P2P_CANCEL_CONNECT, error); return WIFI_OPT_FAILED; } @@ -543,15 +617,19 @@ ErrCode WifiP2pProxy::P2pDisConnect() return ErrCode(reply.ReadInt32()); } -ErrCode WifiP2pProxy::QueryP2pInfo(WifiP2pInfo &connInfo) +ErrCode WifiP2pProxy::QueryP2pLinkedInfo(WifiP2pLinkedInfo &linkedInfo) { if (mRemoteDied) { - WIFI_LOGD("failed to `%{public}s`,remote service is died!", __func__); + WIFI_LOGW("failed to `%{public}s`,remote service is died!", __func__); return WIFI_OPT_FAILED; } MessageOption option; MessageParcel data; MessageParcel reply; + if (!data.WriteInterfaceToken(GetDescriptor())) { + WIFI_LOGE("Write interface token error: %{public}s", __func__); + return WIFI_OPT_FAILED; + } data.WriteInt32(0); int error = Remote()->SendRequest(WIFI_SVR_CMD_P2P_QUERY_INFO, data, reply, option); if (error != ERR_NONE) { @@ -567,9 +645,9 @@ ErrCode WifiP2pProxy::QueryP2pInfo(WifiP2pInfo &connInfo) if (ErrCode(ret) != WIFI_OPT_SUCCESS) { return ErrCode(ret); } - connInfo.SetConnectState(static_cast(reply.ReadInt32())); - connInfo.SetIsGroupOwner(reply.ReadBool()); - connInfo.SetIsGroupOwnerAddress(reply.ReadCString()); + linkedInfo.SetConnectState(static_cast(reply.ReadInt32())); + linkedInfo.SetIsGroupOwner(reply.ReadBool()); + linkedInfo.SetIsGroupOwnerAddress(reply.ReadCString()); return WIFI_OPT_SUCCESS; } @@ -577,12 +655,16 @@ ErrCode WifiP2pProxy::QueryP2pInfo(WifiP2pInfo &connInfo) ErrCode WifiP2pProxy::GetCurrentGroup(WifiP2pGroupInfo &group) { if (mRemoteDied) { - WIFI_LOGD("failed to `%{public}s`,remote service is died!", __func__); + WIFI_LOGW("failed to `%{public}s`,remote service is died!", __func__); return WIFI_OPT_FAILED; } MessageOption option; MessageParcel data; MessageParcel reply; + if (!data.WriteInterfaceToken(GetDescriptor())) { + WIFI_LOGE("Write interface token error: %{public}s", __func__); + return WIFI_OPT_FAILED; + } data.WriteInt32(0); int error = Remote()->SendRequest(WIFI_SVR_CMD_P2P_GET_CURRENT_GROUP, data, reply, option); if (error != ERR_NONE) { @@ -605,12 +687,16 @@ ErrCode WifiP2pProxy::GetCurrentGroup(WifiP2pGroupInfo &group) ErrCode WifiP2pProxy::GetP2pEnableStatus(int &status) { if (mRemoteDied) { - WIFI_LOGD("failed to `%{public}s`,remote service is died!", __func__); + WIFI_LOGW("failed to `%{public}s`,remote service is died!", __func__); return WIFI_OPT_FAILED; } MessageOption option; MessageParcel data; MessageParcel reply; + if (!data.WriteInterfaceToken(GetDescriptor())) { + WIFI_LOGE("Write interface token error: %{public}s", __func__); + return WIFI_OPT_FAILED; + } data.WriteInt32(0); int error = Remote()->SendRequest(WIFI_SVR_CMD_P2P_GET_ENABLE_STATUS, data, reply, option); if (error != ERR_NONE) { @@ -633,12 +719,16 @@ ErrCode WifiP2pProxy::GetP2pEnableStatus(int &status) ErrCode WifiP2pProxy::GetP2pDiscoverStatus(int &status) { if (mRemoteDied) { - WIFI_LOGD("failed to `%{public}s`,remote service is died!", __func__); + WIFI_LOGW("failed to `%{public}s`,remote service is died!", __func__); return WIFI_OPT_FAILED; } MessageOption option; MessageParcel data; MessageParcel reply; + if (!data.WriteInterfaceToken(GetDescriptor())) { + WIFI_LOGE("Write interface token error: %{public}s", __func__); + return WIFI_OPT_FAILED; + } data.WriteInt32(0); int error = Remote()->SendRequest(WIFI_SVR_CMD_P2P_GET_DISCOVER_STATUS, data, reply, option); if (error != ERR_NONE) { @@ -661,12 +751,16 @@ ErrCode WifiP2pProxy::GetP2pDiscoverStatus(int &status) ErrCode WifiP2pProxy::GetP2pConnectedStatus(int &status) { if (mRemoteDied) { - WIFI_LOGD("failed to `%{public}s`,remote service is died!", __func__); + WIFI_LOGW("failed to `%{public}s`,remote service is died!", __func__); return WIFI_OPT_FAILED; } MessageOption option; MessageParcel data; MessageParcel reply; + if (!data.WriteInterfaceToken(GetDescriptor())) { + WIFI_LOGE("Write interface token error: %{public}s", __func__); + return WIFI_OPT_FAILED; + } data.WriteInt32(0); int error = Remote()->SendRequest(WIFI_SVR_CMD_P2P_GET_CONNECTED_STATUS, data, reply, option); if (error != ERR_NONE) { @@ -689,12 +783,16 @@ ErrCode WifiP2pProxy::GetP2pConnectedStatus(int &status) ErrCode WifiP2pProxy::QueryP2pDevices(std::vector &devices) { if (mRemoteDied) { - WIFI_LOGD("failed to `%{public}s`,remote service is died!", __func__); + WIFI_LOGW("failed to `%{public}s`,remote service is died!", __func__); return WIFI_OPT_FAILED; } MessageOption option; MessageParcel data; MessageParcel reply; + if (!data.WriteInterfaceToken(GetDescriptor())) { + WIFI_LOGE("Write interface token error: %{public}s", __func__); + return WIFI_OPT_FAILED; + } data.WriteInt32(0); int error = Remote()->SendRequest(WIFI_SVR_CMD_P2P_QUERY_DEVICES, data, reply, option); if (error != ERR_NONE) { @@ -711,7 +809,12 @@ ErrCode WifiP2pProxy::QueryP2pDevices(std::vector &devices) return ErrCode(ret); } + constexpr int MAX_SIZE = 512; int size = reply.ReadInt32(); + if (size > MAX_SIZE) { + WIFI_LOGE("Get p2p devices size error: %{public}d", size); + return WIFI_OPT_FAILED; + } for (int i = 0; i < size; ++i) { WifiP2pDevice config; ReadWifiP2pDeviceData(reply, config); @@ -720,15 +823,51 @@ ErrCode WifiP2pProxy::QueryP2pDevices(std::vector &devices) return WIFI_OPT_SUCCESS; } +ErrCode WifiP2pProxy::QueryP2pLocalDevice(WifiP2pDevice &device) +{ + if (mRemoteDied) { + WIFI_LOGE("failed to `%{public}s`,remote service is died!", __func__); + return WIFI_OPT_FAILED; + } + MessageOption option; + MessageParcel data; + MessageParcel reply; + if (!data.WriteInterfaceToken(GetDescriptor())) { + WIFI_LOGE("Write interface token error: %{public}s", __func__); + return WIFI_OPT_FAILED; + } + data.WriteInt32(0); + int error = Remote()->SendRequest(WIFI_SVR_CMD_P2P_QUERY_LOCAL_DEVICE, data, reply, option); + if (error != ERR_NONE) { + WIFI_LOGE("Set Attr(%{public}d) failed,error code is %{public}d", WIFI_SVR_CMD_P2P_QUERY_LOCAL_DEVICE, error); + return WIFI_OPT_FAILED; + } + + int exception = reply.ReadInt32(); + if (exception) { + return WIFI_OPT_FAILED; + } + int ret = reply.ReadInt32(); + if (ErrCode(ret) != WIFI_OPT_SUCCESS) { + return ErrCode(ret); + } + ReadWifiP2pDeviceData(reply, device); + return WIFI_OPT_SUCCESS; +} + ErrCode WifiP2pProxy::QueryP2pGroups(std::vector &groups) { if (mRemoteDied) { - WIFI_LOGD("failed to `%{public}s`,remote service is died!", __func__); + WIFI_LOGW("failed to `%{public}s`,remote service is died!", __func__); return WIFI_OPT_FAILED; } MessageOption option; MessageParcel data; MessageParcel reply; + if (!data.WriteInterfaceToken(GetDescriptor())) { + WIFI_LOGE("Write interface token error: %{public}s", __func__); + return WIFI_OPT_FAILED; + } data.WriteInt32(0); int error = Remote()->SendRequest(WIFI_SVR_CMD_P2P_QUERY_GROUPS, data, reply, option); if (error != ERR_NONE) { @@ -745,7 +884,12 @@ ErrCode WifiP2pProxy::QueryP2pGroups(std::vector &groups) return ErrCode(ret); } + constexpr int MAX_SIZE = 512; int size = reply.ReadInt32(); + if (size > MAX_SIZE) { + WIFI_LOGE("Get p2p group size error: %{public}d", size); + return WIFI_OPT_FAILED; + } for (int i = 0; i < size; ++i) { WifiP2pGroupInfo group; ReadWifiP2pGroupData(reply, group); @@ -757,12 +901,16 @@ ErrCode WifiP2pProxy::QueryP2pGroups(std::vector &groups) ErrCode WifiP2pProxy::QueryP2pServices(std::vector &services) { if (mRemoteDied) { - WIFI_LOGD("failed to `%{public}s`,remote service is died!", __func__); + WIFI_LOGW("failed to `%{public}s`,remote service is died!", __func__); return WIFI_OPT_FAILED; } MessageOption option; MessageParcel data; MessageParcel reply; + if (!data.WriteInterfaceToken(GetDescriptor())) { + WIFI_LOGE("Write interface token error: %{public}s", __func__); + return WIFI_OPT_FAILED; + } data.WriteInt32(0); int error = Remote()->SendRequest(WIFI_SVR_CMD_P2P_QUERY_SERVICES, data, reply, option); if (error != ERR_NONE) { @@ -778,7 +926,13 @@ ErrCode WifiP2pProxy::QueryP2pServices(std::vector &services if (ErrCode(ret) != WIFI_OPT_SUCCESS) { return ErrCode(ret); } + + constexpr int MAX_SIZE = 512; int size = reply.ReadInt32(); + if (size > MAX_SIZE) { + WIFI_LOGE("Get p2p service size error: %{public}d", size); + return WIFI_OPT_FAILED; + } for (int i = 0; i < size; ++i) { WifiP2pServiceInfo info; ReadWifiP2pServiceInfo(reply, info); @@ -790,12 +944,16 @@ ErrCode WifiP2pProxy::QueryP2pServices(std::vector &services ErrCode WifiP2pProxy::SetP2pDeviceName(const std::string &deviceName) { if (mRemoteDied) { - WIFI_LOGD("failed to `%{public}s`,remote service is died!", __func__); + WIFI_LOGW("failed to `%{public}s`,remote service is died!", __func__); return WIFI_OPT_FAILED; } MessageOption option; MessageParcel data; MessageParcel reply; + if (!data.WriteInterfaceToken(GetDescriptor())) { + WIFI_LOGE("Write interface token error: %{public}s", __func__); + return WIFI_OPT_FAILED; + } data.WriteInt32(0); data.WriteCString(deviceName.c_str()); int error = Remote()->SendRequest(WIFI_SVR_CMD_P2P_SET_DEVICE_NAME, data, reply, option); @@ -817,12 +975,16 @@ ErrCode WifiP2pProxy::SetP2pDeviceName(const std::string &deviceName) ErrCode WifiP2pProxy::SetP2pWfdInfo(const WifiP2pWfdInfo &wfdInfo) { if (mRemoteDied) { - WIFI_LOGD("failed to `%{public}s`,remote service is died!", __func__); + WIFI_LOGW("failed to `%{public}s`,remote service is died!", __func__); return WIFI_OPT_FAILED; } MessageOption option; MessageParcel data; MessageParcel reply; + if (!data.WriteInterfaceToken(GetDescriptor())) { + WIFI_LOGE("Write interface token error: %{public}s", __func__); + return WIFI_OPT_FAILED; + } data.WriteInt32(0); data.WriteBool(wfdInfo.GetWfdEnabled()); data.WriteInt32(wfdInfo.GetDeviceInfo()); @@ -849,16 +1011,24 @@ ErrCode WifiP2pProxy::SetP2pWfdInfo(const WifiP2pWfdInfo &wfdInfo) ErrCode WifiP2pProxy::RegisterCallBack(const sptr &callback) { if (mRemoteDied) { - WIFI_LOGD("failed to `%{public}s`,remote service is died!", __func__); + WIFI_LOGW("failed to `%{public}s`,remote service is died!", __func__); return WIFI_OPT_FAILED; } MessageParcel data; MessageParcel reply; MessageOption option(MessageOption::TF_ASYNC); - g_wifiP2pCallbackStub.RegisterCallBack(callback); + if (g_wifiP2pCallbackStub == nullptr) { + WIFI_LOGE("g_wifiP2pCallbackStub is nullptr"); + return WIFI_OPT_FAILED; + } + g_wifiP2pCallbackStub->RegisterCallBack(callback); + if (!data.WriteInterfaceToken(GetDescriptor())) { + WIFI_LOGE("Write interface token error: %{public}s", __func__); + return WIFI_OPT_FAILED; + } data.WriteInt32(0); - if (!data.WriteRemoteObject(g_wifiP2pCallbackStub.AsObject())) { + if (!data.WriteRemoteObject(g_wifiP2pCallbackStub->AsObject())) { WIFI_LOGE("RegisterCallBack WriteRemoteObject failed!"); return WIFI_OPT_FAILED; } @@ -880,11 +1050,15 @@ ErrCode WifiP2pProxy::RegisterCallBack(const sptr &callback) ErrCode WifiP2pProxy::GetSupportedFeatures(long &features) { if (mRemoteDied) { - WIFI_LOGD("failed to `%{public}s`,remote service is died!", __func__); + WIFI_LOGW("failed to `%{public}s`,remote service is died!", __func__); return WIFI_OPT_FAILED; } MessageOption option; MessageParcel data, reply; + if (!data.WriteInterfaceToken(GetDescriptor())) { + WIFI_LOGE("Write interface token error: %{public}s", __func__); + return WIFI_OPT_FAILED; + } data.WriteInt32(0); int error = Remote()->SendRequest(WIFI_SVR_CMD_GET_SUPPORTED_FEATURES, data, reply, option); if (error != ERR_NONE) { @@ -904,11 +1078,453 @@ ErrCode WifiP2pProxy::GetSupportedFeatures(long &features) return WIFI_OPT_SUCCESS; } +ErrCode WifiP2pProxy::Hid2dRequestGcIp(const std::string& gcMac, std::string& ipAddr) +{ + if (mRemoteDied) { + WIFI_LOGW("failed to `%{public}s`,remote service is died!", __func__); + return WIFI_OPT_FAILED; + } + MessageOption option; + MessageParcel data; + MessageParcel reply; + if (!data.WriteInterfaceToken(GetDescriptor())) { + WIFI_LOGE("Write interface token error: %{public}s", __func__); + return WIFI_OPT_FAILED; + } + data.WriteInt32(0); + data.WriteCString(gcMac.c_str()); + int error = Remote()->SendRequest(WIFI_SVR_CMD_P2P_HID2D_APPLY_IP, data, reply, option); + if (error != ERR_NONE) { + WIFI_LOGE("Set Attr(%{public}d) failed,error code is %{public}d", WIFI_SVR_CMD_P2P_HID2D_APPLY_IP, error); + return WIFI_OPT_FAILED; + } + int exception = reply.ReadInt32(); + if (exception) { + return WIFI_OPT_FAILED; + } + int ret = reply.ReadInt32(); + if (ErrCode(ret) != WIFI_OPT_SUCCESS) { + return ErrCode(ret); + } + ipAddr = reply.ReadCString(); + return WIFI_OPT_SUCCESS; +} + +ErrCode WifiP2pProxy::Hid2dSharedlinkIncrease() +{ + if (mRemoteDied) { + WIFI_LOGW("failed to `%{public}s`,remote service is died!", __func__); + return WIFI_OPT_FAILED; + } + MessageOption option; + MessageParcel data; + MessageParcel reply; + if (!data.WriteInterfaceToken(GetDescriptor())) { + WIFI_LOGE("Write interface token error: %{public}s", __func__); + return WIFI_OPT_FAILED; + } + data.WriteInt32(0); + int error = Remote()->SendRequest(WIFI_SVR_CMD_P2P_HID2D_SHARED_LINK_INCREASE, data, reply, option); + if (error != ERR_NONE) { + WIFI_LOGE("Set Attr(%{public}d) failed,error code is %{public}d", + WIFI_SVR_CMD_P2P_HID2D_SHARED_LINK_INCREASE, error); + return WIFI_OPT_FAILED; + } + int exception = reply.ReadInt32(); + if (exception) { + return WIFI_OPT_FAILED; + } + return ErrCode(reply.ReadInt32()); +} + +ErrCode WifiP2pProxy::Hid2dSharedlinkDecrease() +{ + if (mRemoteDied) { + WIFI_LOGW("failed to `%{public}s`,remote service is died!", __func__); + return WIFI_OPT_FAILED; + } + MessageOption option; + MessageParcel data; + MessageParcel reply; + if (!data.WriteInterfaceToken(GetDescriptor())) { + WIFI_LOGE("Write interface token error: %{public}s", __func__); + return WIFI_OPT_FAILED; + } + data.WriteInt32(0); + int error = Remote()->SendRequest(WIFI_SVR_CMD_P2P_HID2D_SHARED_LINK_DECREASE, data, reply, option); + if (error != ERR_NONE) { + WIFI_LOGE("Set Attr(%{public}d) failed,error code is %{public}d", + WIFI_SVR_CMD_P2P_HID2D_SHARED_LINK_DECREASE, error); + return WIFI_OPT_FAILED; + } + int exception = reply.ReadInt32(); + if (exception) { + return WIFI_OPT_FAILED; + } + return ErrCode(reply.ReadInt32()); +} + +ErrCode WifiP2pProxy::Hid2dCreateGroup(const int frequency, FreqType type) +{ + WIFI_LOGI("Request hid2d create group"); + + if (mRemoteDied) { + WIFI_LOGW("failed to `%{public}s`,remote service is died!", __func__); + return WIFI_OPT_FAILED; + } + MessageOption option; + MessageParcel data; + MessageParcel reply; + if (!data.WriteInterfaceToken(GetDescriptor())) { + WIFI_LOGE("Write interface token error: %{public}s", __func__); + return WIFI_OPT_FAILED; + } + data.WriteInt32(0); + data.WriteInt32(frequency); + data.WriteInt32(static_cast(type)); + int error = Remote()->SendRequest(WIFI_SVR_CMD_P2P_HID2D_CREATE_GROUP, data, reply, option); + if (error != ERR_NONE) { + WIFI_LOGE("Set Attr(%{public}d) failed,error code is %{public}d", + WIFI_SVR_CMD_P2P_HID2D_CREATE_GROUP, error); + return WIFI_OPT_FAILED; + } + int exception = reply.ReadInt32(); + if (exception) { + return WIFI_OPT_FAILED; + } + return ErrCode(reply.ReadInt32()); +} + +ErrCode WifiP2pProxy::Hid2dRemoveGcGroup(const std::string& gcIfName) +{ + WIFI_LOGI("Request hid2d remove group"); + + if (mRemoteDied) { + WIFI_LOGW("failed to `%{public}s`,remote service is died!", __func__); + return WIFI_OPT_FAILED; + } + MessageOption option; + MessageParcel data; + MessageParcel reply; + if (!data.WriteInterfaceToken(GetDescriptor())) { + WIFI_LOGE("Write interface token error: %{public}s", __func__); + return WIFI_OPT_FAILED; + } + data.WriteInt32(0); + data.WriteCString(gcIfName.c_str()); + int error = Remote()->SendRequest(WIFI_SVR_CMD_P2P_HID2D_REMOVE_GC_GROUP, data, reply, option); + if (error != ERR_NONE) { + WIFI_LOGE("Set Attr(%{public}d) failed,error code is %{public}d", + WIFI_SVR_CMD_P2P_HID2D_REMOVE_GC_GROUP, error); + return WIFI_OPT_FAILED; + } + int exception = reply.ReadInt32(); + if (exception) { + return WIFI_OPT_FAILED; + } + return ErrCode(reply.ReadInt32()); +} + +ErrCode WifiP2pProxy::Hid2dConnect(const Hid2dConnectConfig& config) +{ + WIFI_LOGI("Request hid2d connect"); + + if (mRemoteDied) { + WIFI_LOGW("failed to `%{public}s`,remote service is died!", __func__); + return WIFI_OPT_FAILED; + } + MessageOption option; + MessageParcel data; + MessageParcel reply; + if (!data.WriteInterfaceToken(GetDescriptor())) { + WIFI_LOGE("Write interface token error: %{public}s", __func__); + return WIFI_OPT_FAILED; + } + data.WriteInt32(0); + data.WriteCString(config.GetSsid().c_str()); + data.WriteCString(config.GetBssid().c_str()); + data.WriteCString(config.GetPreSharedKey().c_str()); + data.WriteInt32(config.GetFrequency()); + data.WriteInt32(static_cast(config.GetDhcpMode())); + int error = Remote()->SendRequest(WIFI_SVR_CMD_P2P_HID2D_CONNECT, data, reply, option); + if (error != ERR_NONE) { + WIFI_LOGE("Set Attr(%{public}d) failed,error code is %{public}d", + WIFI_SVR_CMD_P2P_HID2D_CONNECT, error); + return WIFI_OPT_FAILED; + } + int exception = reply.ReadInt32(); + if (exception) { + return WIFI_OPT_FAILED; + } + return ErrCode(reply.ReadInt32()); +} + +ErrCode WifiP2pProxy::Hid2dConfigIPAddr(const std::string& ifName, const IpAddrInfo& ipInfo) +{ + if (mRemoteDied) { + WIFI_LOGW("failed to `%{public}s`,remote service is died!", __func__); + return WIFI_OPT_FAILED; + } + MessageOption option; + MessageParcel data; + MessageParcel reply; + if (!data.WriteInterfaceToken(GetDescriptor())) { + WIFI_LOGE("Write interface token error: %{public}s", __func__); + return WIFI_OPT_FAILED; + } + data.WriteInt32(0); + data.WriteCString(ifName.c_str()); + data.WriteCString(ipInfo.ip.c_str()); + data.WriteCString(ipInfo.gateway.c_str()); + data.WriteCString(ipInfo.netmask.c_str()); + int error = Remote()->SendRequest(WIFI_SVR_CMD_P2P_HID2D_CONFIG_IP, data, reply, option); + if (error != ERR_NONE) { + WIFI_LOGE("Set Attr(%{public}d) failed,error code is %{public}d", + WIFI_SVR_CMD_P2P_HID2D_CONFIG_IP, error); + return WIFI_OPT_FAILED; + } + int exception = reply.ReadInt32(); + if (exception) { + return WIFI_OPT_FAILED; + } + return ErrCode(reply.ReadInt32()); +} + +ErrCode WifiP2pProxy::Hid2dReleaseIPAddr(const std::string& ifName) +{ + if (mRemoteDied) { + WIFI_LOGW("failed to `%{public}s`,remote service is died!", __func__); + return WIFI_OPT_FAILED; + } + MessageOption option; + MessageParcel data; + MessageParcel reply; + if (!data.WriteInterfaceToken(GetDescriptor())) { + WIFI_LOGE("Write interface token error: %{public}s", __func__); + return WIFI_OPT_FAILED; + } + data.WriteInt32(0); + data.WriteCString(ifName.c_str()); + int error = Remote()->SendRequest(WIFI_SVR_CMD_P2P_HID2D_RELEASE_IP, data, reply, option); + if (error != ERR_NONE) { + WIFI_LOGE("Set Attr(%{public}d) failed,error code is %{public}d", + WIFI_SVR_CMD_P2P_HID2D_RELEASE_IP, error); + return WIFI_OPT_FAILED; + } + int exception = reply.ReadInt32(); + if (exception) { + return WIFI_OPT_FAILED; + } + return ErrCode(reply.ReadInt32()); +} + +ErrCode WifiP2pProxy::Hid2dGetRecommendChannel(const RecommendChannelRequest& request, + RecommendChannelResponse& response) +{ + if (mRemoteDied) { + WIFI_LOGW("failed to `%{public}s`,remote service is died!", __func__); + return WIFI_OPT_FAILED; + } + MessageOption option; + MessageParcel data, reply; + if (!data.WriteInterfaceToken(GetDescriptor())) { + WIFI_LOGE("Write interface token error: %{public}s", __func__); + return WIFI_OPT_FAILED; + } + data.WriteInt32(0); + data.WriteCString(request.remoteIfName.c_str()); + data.WriteInt32(request.remoteIfMode); + data.WriteCString(request.localIfName.c_str()); + data.WriteInt32(request.localIfMode); + data.WriteInt32(request.prefBand); + data.WriteInt32(static_cast(request.prefBandwidth)); + int error = Remote()->SendRequest(WIFI_SVR_CMD_GET_P2P_RECOMMENDED_CHANNEL, data, reply, option); + if (error != ERR_NONE) { + WIFI_LOGE("Set Attr(%{public}d) failed,error code is %{public}d", + WIFI_SVR_CMD_GET_P2P_RECOMMENDED_CHANNEL, error); + return ErrCode(error); + } + int exception = reply.ReadInt32(); + if (exception) { + return WIFI_OPT_FAILED; + } + int ret = reply.ReadInt32(); + if (ErrCode(ret) != WIFI_OPT_SUCCESS) { + return ErrCode(ret); + } + response.status = RecommendStatus(reply.ReadInt32()); + response.index = reply.ReadInt32(); + response.centerFreq = reply.ReadInt32(); + response.centerFreq1 = reply.ReadInt32(); + response.centerFreq2 = reply.ReadInt32(); + response.bandwidth = reply.ReadInt32(); + return WIFI_OPT_SUCCESS; +} + +ErrCode WifiP2pProxy::Hid2dGetChannelListFor5G(std::vector& vecChannelList) +{ + if (mRemoteDied) { + WIFI_LOGW("failed to `%{public}s`,remote service is died!", __func__); + return WIFI_OPT_FAILED; + } + MessageOption option; + MessageParcel data; + MessageParcel reply; + if (!data.WriteInterfaceToken(GetDescriptor())) { + WIFI_LOGE("Write interface token error: %{public}s", __func__); + return WIFI_OPT_FAILED; + } + data.WriteInt32(0); + int error = Remote()->SendRequest(WIFI_SVR_CMD_GET_5G_CHANNEL_LIST, data, reply, option); + if (error != ERR_NONE) { + WIFI_LOGW("Set Attr(%{public}d) failed", WIFI_SVR_CMD_GET_5G_CHANNEL_LIST); + return WIFI_OPT_FAILED; + } + int exception = reply.ReadInt32(); + if (exception) { + return WIFI_OPT_FAILED; + } + int ret = reply.ReadInt32(); + if (ErrCode(ret) != WIFI_OPT_SUCCESS) { + return ErrCode(ret); + } + + constexpr int MAX_SIZE = 512; + int listSize = reply.ReadInt32(); + if (listSize > MAX_SIZE) { + WIFI_LOGE("Get channel list for 5G size error: %{public}d", listSize); + return WIFI_OPT_FAILED; + } + for (int i = 0; i < listSize; ++i) { + vecChannelList.emplace_back(reply.ReadInt32()); + } + return WIFI_OPT_SUCCESS; +} + +ErrCode WifiP2pProxy::Hid2dGetSelfWifiCfgInfo(SelfCfgType cfgType, + char cfgData[CFG_DATA_MAX_BYTES], int* getDatValidLen) +{ + if (getDatValidLen == nullptr) { + WIFI_LOGE("getDatValidLen is nullptr!"); + return WIFI_OPT_FAILED; + } + + if (mRemoteDied) { + WIFI_LOGW("failed to `%{public}s`,remote service is died!", __func__); + return WIFI_OPT_FAILED; + } + MessageOption option; + MessageParcel data; + MessageParcel reply; + if (!data.WriteInterfaceToken(GetDescriptor())) { + WIFI_LOGE("Write interface token error: %{public}s", __func__); + return WIFI_OPT_FAILED; + } + data.WriteInt32(0); + data.WriteInt32(static_cast(cfgType)); + int error = Remote()->SendRequest(WIFI_SVR_CMD_GET_SELF_WIFI_CFG, data, reply, option); + if (error != ERR_NONE) { + WIFI_LOGW("Set Attr(%{public}d) failed", WIFI_SVR_CMD_GET_SELF_WIFI_CFG); + return WIFI_OPT_FAILED; + } + int exception = reply.ReadInt32(); + if (exception) { + return WIFI_OPT_FAILED; + } + int ret = reply.ReadInt32(); + if (ErrCode(ret) != WIFI_OPT_SUCCESS) { + return WIFI_OPT_FAILED; + } + + *getDatValidLen = reply.ReadInt32(); + if (*getDatValidLen > 0) { + const char *dataBuffer = (const char *)reply.ReadBuffer(*getDatValidLen); + if (dataBuffer == nullptr) { + WIFI_LOGE("`%{public}s` inner communication error!", __func__); + return WIFI_OPT_FAILED; + } + if (memcpy_s(cfgData, CFG_DATA_MAX_BYTES, dataBuffer, *getDatValidLen) != EOK) { + WIFI_LOGE("`%{public}s` memcpy_s failed!", __func__); + return WIFI_OPT_FAILED; + } + } + return WIFI_OPT_SUCCESS; +} + +ErrCode WifiP2pProxy::Hid2dSetPeerWifiCfgInfo(PeerCfgType cfgType, + char cfgData[CFG_DATA_MAX_BYTES], int setDataValidLen) +{ + if (setDataValidLen <= 0) { + WIFI_LOGE("`%{public}s` parameter is error!", __func__); + return WIFI_OPT_INVALID_PARAM; + } + if (mRemoteDied) { + WIFI_LOGW("failed to `%{public}s`,remote service is died!", __func__); + return WIFI_OPT_FAILED; + } + MessageOption option; + MessageParcel data; + MessageParcel reply; + if (!data.WriteInterfaceToken(GetDescriptor())) { + WIFI_LOGE("Write interface token error: %{public}s", __func__); + return WIFI_OPT_FAILED; + } + data.WriteInt32(0); + data.WriteInt32(static_cast(cfgType)); + data.WriteInt32(setDataValidLen); + data.WriteBuffer(cfgData, setDataValidLen); + int error = Remote()->SendRequest(WIFI_SVR_CMD_SET_PEER_WIFI_CFG, data, reply, option); + if (error != ERR_NONE) { + WIFI_LOGW("Set Attr(%{public}d) failed", WIFI_SVR_CMD_SET_PEER_WIFI_CFG); + return WIFI_OPT_FAILED; + } + int exception = reply.ReadInt32(); + if (exception) { + return WIFI_OPT_FAILED; + } + return ErrCode(reply.ReadInt32()); +} + +ErrCode WifiP2pProxy::Hid2dSetUpperScene(const std::string& ifName, const Hid2dUpperScene& scene) +{ + if (mRemoteDied) { + WIFI_LOGW("failed to `%{public}s`,remote service is died!", __func__); + return WIFI_OPT_FAILED; + } + MessageOption option; + MessageParcel data; + MessageParcel reply; + if (!data.WriteInterfaceToken(GetDescriptor())) { + WIFI_LOGE("Write interface token error: %{public}s", __func__); + return WIFI_OPT_FAILED; + } + data.WriteInt32(0); + data.WriteCString(ifName.c_str()); + data.WriteCString(scene.mac.c_str()); + data.WriteUint32(scene.scene); + data.WriteInt32(scene.fps); + data.WriteUint32(scene.bw); + int error = Remote()->SendRequest(WIFI_SVR_CMD_SET_UPPER_SCENE, data, reply, option); + if (error != ERR_NONE) { + WIFI_LOGW("Set Attr(%{public}d) failed", WIFI_SVR_CMD_SET_UPPER_SCENE); + return WIFI_OPT_FAILED; + } + int exception = reply.ReadInt32(); + if (exception) { + return WIFI_OPT_FAILED; + } + return ErrCode(reply.ReadInt32()); +} + void WifiP2pProxy::OnRemoteDied(const wptr& remoteObject) { - WIFI_LOGD("Remote service is died!"); + WIFI_LOGE("Remote service is died!"); mRemoteDied = true; - g_wifiP2pCallbackStub.SetRemoteDied(true); + if (g_wifiP2pCallbackStub == nullptr) { + WIFI_LOGE("g_wifiP2pCallbackStub is nullptr"); + return; + } + g_wifiP2pCallbackStub->SetRemoteDied(true); } } // namespace Wifi -} // namespace OHOS \ No newline at end of file +} // namespace OHOS diff --git a/interfaces/innerkits/native_cpp/wifi_standard/src/wifi_p2p_proxy.h b/wifi/frameworks/native/src/wifi_p2p_proxy.h similarity index 53% rename from interfaces/innerkits/native_cpp/wifi_standard/src/wifi_p2p_proxy.h rename to wifi/frameworks/native/src/wifi_p2p_proxy.h index 5bdd76458232c089f39ef9844a82a69e40082d54..fc6c102ee051a8528445db244ba6985cfe8f7b86 100644 --- a/interfaces/innerkits/native_cpp/wifi_standard/src/wifi_p2p_proxy.h +++ b/wifi/frameworks/native/src/wifi_p2p_proxy.h @@ -1,5 +1,5 @@ /* - * Copyright (C) 2021 Huawei Device Co., Ltd. + * Copyright (C) 2021-2022 Huawei Device Co., Ltd. * 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 @@ -30,42 +30,42 @@ public: /** * @Description Enabling the P2P Mode * - * @return ErrCode - operate result + * @return ErrCode - operation result */ ErrCode EnableP2p(void) override; /** * @Description Disable the P2P mode * - * @return ErrCode - operate result + * @return ErrCode - operation result */ ErrCode DisableP2p(void) override; /** * @Description Start Wi-Fi P2P device search * - * @return ErrCode - operate result + * @return ErrCode - operation result */ ErrCode DiscoverDevices(void) override; /** * @Description Stop Wi-Fi P2P device search * - * @return ErrCode - operate result + * @return ErrCode - operation result */ ErrCode StopDiscoverDevices(void) override; /** * @Description Start the search for the Wi-Fi P2P service * - * @return ErrCode - operate result + * @return ErrCode - operation result */ ErrCode DiscoverServices(void) override; /** * @Description Stop the search for the Wi-Fi P2P service * - * @return ErrCode - operate result + * @return ErrCode - operation result */ ErrCode StopDiscoverServices(void) override; @@ -74,7 +74,7 @@ public: * * @param device - WifiP2pDevice object * @param request - WifiP2pServiceRequest object - * @return ErrCode - operate result + * @return ErrCode - operation result */ ErrCode RequestService(const WifiP2pDevice &device, const WifiP2pServiceRequest &request) override; @@ -82,7 +82,7 @@ public: * @Description Register the local P2P service * * @param srvInfo - WifiP2pServiceInfo object - * @return ErrCode - operate result + * @return ErrCode - operation result */ ErrCode PutLocalP2pService(const WifiP2pServiceInfo &srvInfo) override; @@ -90,7 +90,7 @@ public: * @Description Delete the local P2P service * * @param srvInfo - WifiP2pServiceInfo object - * @return ErrCode - operate result + * @return ErrCode - operation result */ ErrCode DeleteLocalP2pService(const WifiP2pServiceInfo &srvInfo) override; @@ -99,14 +99,14 @@ public: * * @param period - period * @param interval - interval - * @return ErrCode - operate result + * @return ErrCode - operation result */ ErrCode StartP2pListen(int period, int interval) override; /** * @Description Disable Wi-Fi P2P listening * - * @return ErrCode - operate result + * @return ErrCode - operation result */ ErrCode StopP2pListen(void) override; @@ -114,15 +114,15 @@ public: * @Description Creating a P2P Group * * @param config - WifiP2pGroupInfo object - * @return ErrCode - operate result + * @return ErrCode - operation result */ - ErrCode FormGroup(const WifiP2pConfig &config) override; + ErrCode CreateGroup(const WifiP2pConfig &config) override; /** * @Description Remove a P2P Group * * - * @return ErrCode - operate result + * @return ErrCode - operation result */ ErrCode RemoveGroup(void) override; @@ -130,7 +130,7 @@ public: * @Description Delete a p2p Group * * @param group - WifiP2pGroupInfo object - * @return ErrCode - operate result + * @return ErrCode - operation result */ ErrCode DeleteGroup(const WifiP2pGroupInfo &group) override; @@ -138,30 +138,30 @@ public: * @Description P2P connection * * @param config - WifiP2pConfig object - * @return ErrCode - operate result + * @return ErrCode - operation result */ ErrCode P2pConnect(const WifiP2pConfig &config) override; /** - * @Description P2P disconnection + * @Description Canceling a P2P connection * - * @return ErrCode - operate result + * @return ErrCode - operation result */ - ErrCode P2pDisConnect(void) override; + ErrCode P2pCancelConnect(void) override; /** * @Description Querying Wi-Fi P2P Connection Information * - * @param connInfo - Get the WifiP2pInfo msg - * @return ErrCode - operate result + * @param linkedInfo - Get the WifiP2pLinkedInfo msg + * @return ErrCode - operation result */ - ErrCode QueryP2pInfo(WifiP2pInfo &connInfo) override; + ErrCode QueryP2pLinkedInfo(WifiP2pLinkedInfo &linkedInfo) override; /** * @Description Get the Current Group object * * @param group - the WifiP2pGroupInfo object - * @return ErrCode - operate result + * @return ErrCode - operation result */ ErrCode GetCurrentGroup(WifiP2pGroupInfo &group) override; @@ -169,7 +169,7 @@ public: * @Description Obtains the P2P switch status * * @param status - the P2P switch status - * @return ErrCode - operate result + * @return ErrCode - operation result */ ErrCode GetP2pEnableStatus(int &status) override; @@ -185,7 +185,7 @@ public: * @Description Obtains the P2P connection status * * @param status - the P2P connection status - * @return ErrCode - operate result + * @return ErrCode - operation result */ ErrCode GetP2pConnectedStatus(int &status) override; @@ -193,15 +193,23 @@ public: * @Description Query the information about the found devices * * @param devices - Get result vector of WifiP2pDevice - * @return ErrCode - operate result + * @return ErrCode - operation result */ ErrCode QueryP2pDevices(std::vector &devices) override; + /** + * @Description Query the information about local device info + * + * @param devices - Get result of WifiP2pDevice + * @return ErrCode - operation result + */ + ErrCode QueryP2pLocalDevice(WifiP2pDevice &device) override; + /** * @Description Query the information about the found groups * * @param groups - Get result vector of WifiP2pGroupInfo - * @return ErrCode - operate result + * @return ErrCode - operation result */ ErrCode QueryP2pGroups(std::vector &groups) override; @@ -209,7 +217,7 @@ public: * @Description Query the service information * * @param services - Get result vector of Device - * @return ErrCode - operate result + * @return ErrCode - operation result */ ErrCode QueryP2pServices(std::vector &services) override; @@ -217,7 +225,7 @@ public: * @Description Register callback function * * @param callback - IWifiP2pCallback object - * @return ErrCode - operate result + * @return ErrCode - operation result */ ErrCode RegisterCallBack(const sptr &callback) override; @@ -233,7 +241,7 @@ public: * @Description set the device name * * @param deviceName - device name - * @return ErrCode - operate result + * @return ErrCode - operation result */ ErrCode SetP2pDeviceName(const std::string &deviceName) override; @@ -241,10 +249,128 @@ public: * @Description set p2p wifi display info * * @param wfdInfo - wifi display info - * @return ErrCode - operate result + * @return ErrCode - operation result */ ErrCode SetP2pWfdInfo(const WifiP2pWfdInfo &wfdInfo) override; + /** + * @Description Request an IP address to the Gc from the IP address pool, used on the GO side. + * + * @param gcMac - gc mac address + * @param ipAddr - applied ip address + * @return ErrCode - operation result + */ + ErrCode Hid2dRequestGcIp(const std::string& gcMac, std::string& ipAddr) override; + + /** + * @Description Increase(+1) hid2d shared link reference counting + * + * @return ErrCode - operation result + */ + ErrCode Hid2dSharedlinkIncrease() override; + + /** + * @Description Decrease(-1) hid2d shared link reference counting + * + * @return ErrCode - operation result + */ + ErrCode Hid2dSharedlinkDecrease() override; + + /** + * @Description Create hid2d group, used on the GO side. + * + * @param frequency - frequency + * @param type - frequency type + * @return ErrCode - operation result + */ + ErrCode Hid2dCreateGroup(const int frequency, FreqType type) override; + + /** + * @Description The GC side actively disconnects from the GO, used on the GC side. + * + * @param gcIfName - network interface name + * @return ErrCode - operation result + */ + ErrCode Hid2dRemoveGcGroup(const std::string& gcIfName) override; + + /** + * @Description Connect to a specified group using hid2d, used on the GC side. + * + * @param config - connection parameters + * @return ErrCode - operation result + */ + ErrCode Hid2dConnect(const Hid2dConnectConfig& config) override; + + /** + * @Description Configuring IP addresses for P2P network interfaces, used on the GC side. + * + * @param ifName - network interface name + * @param ipInfo - IP infos + * @return ErrCode - operation result + */ + ErrCode Hid2dConfigIPAddr(const std::string& ifName, const IpAddrInfo& ipInfo) override; + + /** + * @Description Clear IP address when the P2P connection is disconnected, used on the GC side. + * + * @param ifName - network interface name + * @return ErrCode - operation result + */ + ErrCode Hid2dReleaseIPAddr(const std::string& ifName) override; + + /** + * @Description Obtain the recommended channel and bandwidth for link setup + * + * @param request - request data + * @param response - response result + * @return ErrCode - operation result + */ + ErrCode Hid2dGetRecommendChannel(const RecommendChannelRequest& request, + RecommendChannelResponse& response) override; + + /** + * @Description get 5G channel list + * + * @param vecChannelList - result for channel list + * @return ErrCode - operation result + */ + ErrCode Hid2dGetChannelListFor5G(std::vector& vecChannelList) override; + + /** + * @Description get the self wifi configuration information + * + * @param cfgType - configuration type + * @param cfgData - the queried data of wifi configuration + * @param getDatValidLen - the valid data length in the array `cfgData` + * @return ErrCode - operation result + */ + ErrCode Hid2dGetSelfWifiCfgInfo(SelfCfgType cfgType, + char cfgData[CFG_DATA_MAX_BYTES], int* getDatValidLen) override; + + /** + * @Description set the peer wifi configuration information + * + * @param cfgType - configuration type + * @param cfgData - the wifi configuration data to be set + * @param setDataValidLen - the valid data length in the array `cfgData` + * @return ErrCode - operation result + */ + ErrCode Hid2dSetPeerWifiCfgInfo(PeerCfgType cfgType, + char cfgData[CFG_DATA_MAX_BYTES], int setDataValidLen) override; + + /** + * @Description Set the scene of upper layer + * + * @param ifName - interface name + * @param scene - scene + * @return ErrCode - operate result + */ + ErrCode Hid2dSetUpperScene(const std::string& ifName, const Hid2dUpperScene& scene) override; + + /** + * @Description Handle remote object died event. + * @param remoteObject remote object. + */ void OnRemoteDied(const wptr &remoteObject) override; private: diff --git a/interfaces/innerkits/native_cpp/wifi_standard/src/wifi_scan.cpp b/wifi/frameworks/native/src/wifi_scan.cpp similarity index 98% rename from interfaces/innerkits/native_cpp/wifi_standard/src/wifi_scan.cpp rename to wifi/frameworks/native/src/wifi_scan.cpp index c733d224f0d701c7ac176e8871b7e7f97ff15f95..24f59b2c6a62825d30c0e6531e28cfa4d4dac768 100644 --- a/interfaces/innerkits/native_cpp/wifi_standard/src/wifi_scan.cpp +++ b/wifi/frameworks/native/src/wifi_scan.cpp @@ -13,7 +13,9 @@ * limitations under the License. */ #include "wifi_scan.h" +#ifndef OHOS_ARCH_LITE #include "iremote_broker.h" +#endif #include "wifi_logger.h" #include "wifi_scan_impl.h" diff --git a/interfaces/innerkits/native_cpp/wifi_standard/src/wifi_scan_callback_stub.cpp b/wifi/frameworks/native/src/wifi_scan_callback_stub.cpp similarity index 82% rename from interfaces/innerkits/native_cpp/wifi_standard/src/wifi_scan_callback_stub.cpp rename to wifi/frameworks/native/src/wifi_scan_callback_stub.cpp index cd1df8c40180f0c6c7678f4f6ecc1573f7f547ca..a19cf3ddff7df46ac88b48a65f68afef8f122dee 100644 --- a/interfaces/innerkits/native_cpp/wifi_standard/src/wifi_scan_callback_stub.cpp +++ b/wifi/frameworks/native/src/wifi_scan_callback_stub.cpp @@ -1,5 +1,5 @@ /* - * Copyright (C) 2021 Huawei Device Co., Ltd. + * Copyright (C) 2021-2022 Huawei Device Co., Ltd. * 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 @@ -12,13 +12,14 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + #include "wifi_scan_callback_stub.h" +#include "define.h" +#include "wifi_hisysevent.h" #include "wifi_logger.h" #include "wifi_msg.h" -#include "define.h" DEFINE_WIFILOG_SCAN_LABEL("WifiScanCallbackStub"); - namespace OHOS { namespace Wifi { WifiScanCallbackStub::WifiScanCallbackStub() : userCallback_(nullptr), mRemoteDied(false) @@ -32,12 +33,18 @@ int WifiScanCallbackStub::OnRemoteRequest( { WIFI_LOGD("WifiScanCallbackStub::OnRemoteRequest code:%{public}u!", code); if (mRemoteDied) { - WIFI_LOGD("Failed to `%{public}s`,remote service is died!", __func__); + WIFI_LOGE("Failed to `%{public}s`,remote service is died!", __func__); return -1; } + + if (data.ReadInterfaceToken() != GetDescriptor()) { + WIFI_LOGE("Scan callback stub token verification error: %{public}d", code); + return WIFI_OPT_FAILED; + } + int exception = data.ReadInt32(); if (exception) { - WIFI_LOGD("WifiScanCallbackStub::OnRemoteRequest exception! %{public}d!", exception); + WIFI_LOGE("WifiScanCallbackStub::OnRemoteRequest exception! %{public}d!", exception); return WIFI_OPT_FAILED; } int ret = -1; @@ -57,7 +64,7 @@ int WifiScanCallbackStub::OnRemoteRequest( void WifiScanCallbackStub::RegisterCallBack(const sptr &userCallback) { if (userCallback_ != nullptr) { - WIFI_LOGD("Callback has registered!"); + WIFI_LOGE("Callback has registered!"); return; } userCallback_ = userCallback; @@ -75,11 +82,12 @@ void WifiScanCallbackStub::SetRemoteDied(bool val) void WifiScanCallbackStub::OnWifiScanStateChanged(int state) { - WIFI_LOGD("WifiScanCallbackStub::OnWifiScanStateChanged,state:%{public}d", state); + WIFI_LOGI("WifiScanCallbackStub::OnWifiScanStateChanged,state:%{public}d", state); if (userCallback_) { userCallback_->OnWifiScanStateChanged(state); } + WriteWifiEventReceivedHiSysEvent(HISYS_STA_SCAN_STATE_CHANGE, state); } int WifiScanCallbackStub::RemoteOnWifiScanStateChanged(uint32_t code, MessageParcel &data, MessageParcel &reply) diff --git a/interfaces/innerkits/native_cpp/wifi_standard/src/wifi_scan_callback_stub.h b/wifi/frameworks/native/src/wifi_scan_callback_stub.h similarity index 71% rename from interfaces/innerkits/native_cpp/wifi_standard/src/wifi_scan_callback_stub.h rename to wifi/frameworks/native/src/wifi_scan_callback_stub.h index c9a51dca569435639f2c3ac1cddca0afa8a0a20a..fc50709eccc70c7046e06ea488a5a3840d0adf98 100644 --- a/interfaces/innerkits/native_cpp/wifi_standard/src/wifi_scan_callback_stub.h +++ b/wifi/frameworks/native/src/wifi_scan_callback_stub.h @@ -1,5 +1,5 @@ /* - * Copyright (C) 2021 Huawei Device Co., Ltd. + * Copyright (C) 2021-2022 Huawei Device Co., Ltd. * 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 @@ -15,26 +15,46 @@ #ifndef OHOS_I_WIFI_SCAN_CALLBACK_STUB_H #define OHOS_I_WIFI_SCAN_CALLBACK_STUB_H +#ifdef OHOS_ARCH_LITE +#include "serializer.h" +#else #include "iremote_stub.h" +#endif #include "i_wifi_scan_callback.h" namespace OHOS { namespace Wifi { +#ifdef OHOS_ARCH_LITE +class WifiScanCallbackStub : public IWifiScanCallback { +#else class WifiScanCallbackStub : public IRemoteStub { +#endif public: WifiScanCallbackStub(); virtual ~WifiScanCallbackStub(); - +#ifdef OHOS_ARCH_LITE + int OnRemoteRequest(uint32_t code, IpcIo *data); +#else virtual int OnRemoteRequest( uint32_t code, MessageParcel &data, MessageParcel &reply, MessageOption &option) override; +#endif void OnWifiScanStateChanged(int state) override; +#ifdef OHOS_ARCH_LITE + void RegisterCallBack(const std::shared_ptr &userCallback); +#else void RegisterCallBack(const sptr &userCallback); +#endif bool IsRemoteDied() const; void SetRemoteDied(bool val); private: +#ifdef OHOS_ARCH_LITE + int RemoteOnWifiScanStateChanged(uint32_t code, IpcIo *data); + std::shared_ptr userCallback_; +#else int RemoteOnWifiScanStateChanged(uint32_t code, MessageParcel &data, MessageParcel &reply); sptr userCallback_; +#endif bool mRemoteDied; }; diff --git a/wifi/frameworks/native/src/wifi_scan_callback_stub_lite.cpp b/wifi/frameworks/native/src/wifi_scan_callback_stub_lite.cpp new file mode 100644 index 0000000000000000000000000000000000000000..19c7ca198692ae5b7499318f06391cca6487d02a --- /dev/null +++ b/wifi/frameworks/native/src/wifi_scan_callback_stub_lite.cpp @@ -0,0 +1,97 @@ +/* + * Copyright (C) 2022 Huawei Device Co., Ltd. + * 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 "wifi_scan_callback_stub.h" +#include "define.h" +#include "wifi_errcode.h" +#include "wifi_logger.h" +#include "wifi_msg.h" + +DEFINE_WIFILOG_SCAN_LABEL("WifiScanCallbackStubLite"); +namespace OHOS { +namespace Wifi { +WifiScanCallbackStub::WifiScanCallbackStub() : userCallback_(nullptr), mRemoteDied(false) +{} + +WifiScanCallbackStub::~WifiScanCallbackStub() +{} + +int WifiScanCallbackStub::OnRemoteRequest(uint32_t code, IpcIo *data) +{ + int ret = WIFI_OPT_FAILED; + WIFI_LOGD("OnRemoteRequest code:%{public}u!", code); + if (mRemoteDied || data == nullptr) { + WIFI_LOGD("Failed to %{public}s,mRemoteDied:%{public}d data:%{public}d!", + __func__, mRemoteDied, data == nullptr); + return ret; + } + + int exception = WIFI_OPT_FAILED; + (void)ReadInt32(data, &exception); + if (exception) { + WIFI_LOGD("OnRemoteRequest exception! %{public}d!", exception); + return ret; + } + switch (code) { + case WIFI_CBK_CMD_SCAN_STATE_CHANGE: { + WIFI_LOGD("OnRemoteRequest code:%{public}u", code); + ret = RemoteOnWifiScanStateChanged(code, data); + break; + } + default: { + ret = WIFI_OPT_FAILED; + } + } + return ret; +} + +void WifiScanCallbackStub::RegisterCallBack(const std::shared_ptr &userCallback) +{ + if (userCallback_ != nullptr) { + WIFI_LOGD("Callback has registered!"); + return; + } + userCallback_ = userCallback; +} + +bool WifiScanCallbackStub::IsRemoteDied() const +{ + return mRemoteDied; +} + +void WifiScanCallbackStub::SetRemoteDied(bool val) +{ + mRemoteDied = val; +} + +void WifiScanCallbackStub::OnWifiScanStateChanged(int state) +{ + WIFI_LOGD("OnWifiScanStateChanged,state:%{public}d", state); + + if (userCallback_) { + userCallback_->OnWifiScanStateChanged(state); + } +} + +int WifiScanCallbackStub::RemoteOnWifiScanStateChanged(uint32_t code, IpcIo *data) +{ + WIFI_LOGD("run %{public}s code %{public}u", __func__, code); + int stateCode = 0; + (void)ReadInt32(data, &stateCode); + OnWifiScanStateChanged(stateCode); + return 0; +} +} // namespace Wifi +} // namespace OHOS diff --git a/interfaces/innerkits/native_cpp/wifi_standard/src/wifi_scan_impl.cpp b/wifi/frameworks/native/src/wifi_scan_impl.cpp similarity index 84% rename from interfaces/innerkits/native_cpp/wifi_standard/src/wifi_scan_impl.cpp rename to wifi/frameworks/native/src/wifi_scan_impl.cpp index 9b25955c9e09e1fbf0b2d6c8fe6a1a00594e5b1e..4300855a8ec567088f3e04b5957610b2e4eda33a 100644 --- a/interfaces/innerkits/native_cpp/wifi_standard/src/wifi_scan_impl.cpp +++ b/wifi/frameworks/native/src/wifi_scan_impl.cpp @@ -15,7 +15,9 @@ #include "wifi_scan_impl.h" #include "i_wifi_scan.h" +#ifndef OHOS_ARCH_LITE #include "iservice_registry.h" +#endif #include "wifi_logger.h" #include "wifi_scan_proxy.h" @@ -35,10 +37,27 @@ WifiScanImpl::WifiScanImpl(int systemAbilityId) : systemAbilityId_(systemAbility {} WifiScanImpl::~WifiScanImpl() -{} +{ +#ifdef OHOS_ARCH_LITE + WifiScanProxy::ReleaseInstance(); +#endif +} bool WifiScanImpl::Init() { +#ifdef OHOS_ARCH_LITE + WifiScanProxy *scanProxy = WifiScanProxy::GetInstance(); + if (scanProxy == nullptr) { + WIFI_LOGE("get wifi scan proxy failed."); + return false; + } + if (scanProxy->Init() != WIFI_OPT_SUCCESS) { + WIFI_LOGE("wifi scan proxy init failed."); + WifiScanProxy::ReleaseInstance(); + return false; + } + client_ = scanProxy; +#else sptr sa_mgr = SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager(); if (sa_mgr == nullptr) { WIFI_LOGE("failed to get SystemAbilityManager"); @@ -57,6 +76,7 @@ bool WifiScanImpl::Init() WIFI_LOGE("wifi scan init failed. %{public}d", systemAbilityId_); return false; } +#endif return true; } @@ -90,7 +110,11 @@ ErrCode WifiScanImpl::GetScanInfoList(std::vector &result) return client_->GetScanInfoList(result); } +#ifdef OHOS_ARCH_LITE +ErrCode WifiScanImpl::RegisterCallBack(const std::shared_ptr &callback) +#else ErrCode WifiScanImpl::RegisterCallBack(const sptr &callback) +#endif { RETURN_IF_FAIL(client_); return client_->RegisterCallBack(callback); diff --git a/interfaces/innerkits/native_cpp/wifi_standard/src/wifi_scan_impl.h b/wifi/frameworks/native/src/wifi_scan_impl.h similarity index 93% rename from interfaces/innerkits/native_cpp/wifi_standard/src/wifi_scan_impl.h rename to wifi/frameworks/native/src/wifi_scan_impl.h index 349613b001e44f5bf6c118508538c406c8044073..fcfbac7ef90c9011b712d0214a09194e7c17ced8 100644 --- a/interfaces/innerkits/native_cpp/wifi_standard/src/wifi_scan_impl.h +++ b/wifi/frameworks/native/src/wifi_scan_impl.h @@ -50,7 +50,11 @@ public: */ virtual ErrCode GetScanInfoList(std::vector &result) override; +#ifdef OHOS_ARCH_LITE + virtual ErrCode RegisterCallBack(const std::shared_ptr &callback) override; +#else virtual ErrCode RegisterCallBack(const sptr &callback) override; +#endif /** * @Description Get supported features @@ -87,7 +91,11 @@ public: private: int systemAbilityId_; +#ifdef OHOS_ARCH_LITE + IWifiScan *client_; +#else sptr client_; +#endif }; } // namespace Wifi } // namespace OHOS diff --git a/interfaces/innerkits/native_cpp/wifi_standard/src/wifi_scan_proxy.cpp b/wifi/frameworks/native/src/wifi_scan_proxy.cpp old mode 100755 new mode 100644 similarity index 69% rename from interfaces/innerkits/native_cpp/wifi_standard/src/wifi_scan_proxy.cpp rename to wifi/frameworks/native/src/wifi_scan_proxy.cpp index 51638c45c9995358300d418a7ee1e288bd7fa996..ef2b5fd085bcfb32a1385f3b9665764a4e07e48f --- a/interfaces/innerkits/native_cpp/wifi_standard/src/wifi_scan_proxy.cpp +++ b/wifi/frameworks/native/src/wifi_scan_proxy.cpp @@ -1,5 +1,5 @@ /* - * Copyright (C) 2021 Huawei Device Co., Ltd. + * Copyright (C) 2021-2022 Huawei Device Co., Ltd. * 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 @@ -12,15 +12,27 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + #include "wifi_scan_proxy.h" +#include +#include +#include +#include #include "define.h" +#include "ipc_types.h" +#include "iremote_proxy.h" +#include "message_option.h" +#include "message_parcel.h" +#include "wifi_common_util.h" +#include "wifi_hisysevent.h" #include "wifi_logger.h" #include "wifi_scan_callback_stub.h" namespace OHOS { DEFINE_WIFILOG_SCAN_LABEL("WifiScanProxy"); namespace Wifi { -static WifiScanCallbackStub g_wifiScanCallbackStub; +static sptr g_wifiScanCallbackStub = + sptr(new (std::nothrow) WifiScanCallbackStub()); WifiScanProxy::WifiScanProxy(const sptr &remote) : IRemoteProxy(remote), mRemoteDied(false) { @@ -39,32 +51,31 @@ WifiScanProxy::~WifiScanProxy() ErrCode WifiScanProxy::SetScanControlInfo(const ScanControlInfo &info) { if (mRemoteDied) { - WIFI_LOGD("failed to `%{public}s`,remote service is died!", __func__); + WIFI_LOGW("failed to `%{public}s`,remote service is died!", __func__); return WIFI_OPT_FAILED; } MessageOption option; MessageParcel data; MessageParcel reply; + if (!data.WriteInterfaceToken(GetDescriptor())) { + WIFI_LOGE("Write interface token error: %{public}s", __func__); + return WIFI_OPT_FAILED; + } data.WriteInt32(0); - data.WriteInt32(info.scanForbidMap.size()); - auto iter = info.scanForbidMap.begin(); - for (; iter != info.scanForbidMap.end(); iter++) { - data.WriteInt32((int)iter->first); - data.WriteInt32(iter->second.size()); - for (std::size_t i = 0; i < iter->second.size(); i++) { - data.WriteInt32((int)iter->second[i].scanMode); - data.WriteInt32(iter->second[i].forbidTime); - data.WriteInt32(iter->second[i].forbidCount); - } + data.WriteInt32(info.scanForbidList.size()); + for (auto iter = info.scanForbidList.begin(); iter != info.scanForbidList.end(); iter++) { + data.WriteInt32(iter->scanScene); + data.WriteInt32(static_cast(iter->scanMode)); + data.WriteInt32(iter->forbidTime); + data.WriteInt32(iter->forbidCount); } data.WriteInt32(info.scanIntervalList.size()); - auto iter2 = info.scanIntervalList.begin(); - for (; iter2 != info.scanIntervalList.end(); iter2++) { + for (auto iter2 = info.scanIntervalList.begin(); iter2 != info.scanIntervalList.end(); iter2++) { data.WriteInt32(iter2->scanScene); - data.WriteInt32((int)iter2->scanMode); - data.WriteInt32((int)iter2->isSingle); - data.WriteInt32((int)iter2->intervalMode); + data.WriteInt32(static_cast(iter2->scanMode)); + data.WriteBool(iter2->isSingle); + data.WriteInt32(static_cast(iter2->intervalMode)); data.WriteInt32(iter2->interval); data.WriteInt32(iter2->count); } @@ -89,12 +100,16 @@ ErrCode WifiScanProxy::SetScanControlInfo(const ScanControlInfo &info) ErrCode WifiScanProxy::Scan() { if (mRemoteDied) { - WIFI_LOGD("failed to `%{public}s`,remote service is died!", __func__); + WIFI_LOGW("failed to `%{public}s`,remote service is died!", __func__); return WIFI_OPT_FAILED; } MessageOption option; MessageParcel data; MessageParcel reply; + if (!data.WriteInterfaceToken(GetDescriptor())) { + WIFI_LOGE("Write interface token error: %{public}s", __func__); + return WIFI_OPT_FAILED; + } data.WriteInt32(0); int error = Remote()->SendRequest(WIFI_SVR_CMD_FULL_SCAN, data, reply, option); if (error != ERR_NONE) { @@ -106,22 +121,27 @@ ErrCode WifiScanProxy::Scan() return WIFI_OPT_FAILED; } int ret = reply.ReadInt32(); + /* Record sysevent for scan */ + WriteWifiScanHiSysEvent(static_cast(ret), GetBundleName()); if (ErrCode(ret) != WIFI_OPT_SUCCESS) { return ErrCode(ret); } - return WIFI_OPT_SUCCESS; } ErrCode WifiScanProxy::AdvanceScan(const WifiScanParams ¶ms) { if (mRemoteDied) { - WIFI_LOGD("failed to `%{public}s`,remote service is died!", __func__); + WIFI_LOGW("failed to `%{public}s`,remote service is died!", __func__); return WIFI_OPT_FAILED; } MessageOption option; MessageParcel data; MessageParcel reply; + if (!data.WriteInterfaceToken(GetDescriptor())) { + WIFI_LOGE("Write interface token error: %{public}s", __func__); + return WIFI_OPT_FAILED; + } data.WriteInt32(0); data.WriteCString(params.ssid.c_str()); data.WriteCString(params.bssid.c_str()); @@ -141,22 +161,27 @@ ErrCode WifiScanProxy::AdvanceScan(const WifiScanParams ¶ms) return WIFI_OPT_FAILED; } int ret = reply.ReadInt32(); + /* Record sysevent for scan */ + WriteWifiScanHiSysEvent(static_cast(ret), GetBundleName()); if (ErrCode(ret) != WIFI_OPT_SUCCESS) { return ErrCode(ret); } - return WIFI_OPT_SUCCESS; } ErrCode WifiScanProxy::IsWifiClosedScan(bool &bOpen) { if (mRemoteDied) { - WIFI_LOGD("failed to `%{public}s`,remote service is died!", __func__); + WIFI_LOGW("failed to `%{public}s`,remote service is died!", __func__); return WIFI_OPT_FAILED; } MessageOption option; MessageParcel data; MessageParcel reply; + if (!data.WriteInterfaceToken(GetDescriptor())) { + WIFI_LOGE("Write interface token error: %{public}s", __func__); + return WIFI_OPT_FAILED; + } data.WriteInt32(0); int error = Remote()->SendRequest(WIFI_SVR_CMD_IS_SCAN_ALWAYS_ACTIVE, data, reply, option); if (error != ERR_NONE) { @@ -178,12 +203,16 @@ ErrCode WifiScanProxy::IsWifiClosedScan(bool &bOpen) ErrCode WifiScanProxy::GetScanInfoList(std::vector &result) { if (mRemoteDied) { - WIFI_LOGD("failed to `%{public}s`,remote service is died!", __func__); + WIFI_LOGW("failed to `%{public}s`,remote service is died!", __func__); return WIFI_OPT_FAILED; } MessageOption option; MessageParcel data; MessageParcel reply; + if (!data.WriteInterfaceToken(GetDescriptor())) { + WIFI_LOGE("Write interface token error: %{public}s", __func__); + return WIFI_OPT_FAILED; + } data.WriteInt32(0); int error = Remote()->SendRequest(WIFI_SVR_CMD_GET_SCAN_INFO_LIST, data, reply, option); if (error != ERR_NONE) { @@ -198,7 +227,13 @@ ErrCode WifiScanProxy::GetScanInfoList(std::vector &result) if (ErrCode(ret) != WIFI_OPT_SUCCESS) { return ErrCode(ret); } + + constexpr int MAX_SIZE = 4096; int tmpsize = reply.ReadInt32(); + if (tmpsize > MAX_SIZE) { + WIFI_LOGE("Scan info size exceeds maximum allowed size: %{public}d", tmpsize); + return WIFI_OPT_FAILED; + } for (int i = 0; i < tmpsize; ++i) { WifiScanInfo info; info.bssid = reply.ReadCString(); @@ -213,7 +248,13 @@ ErrCode WifiScanProxy::GetScanInfoList(std::vector &result) info.centerFrequency0 = reply.ReadInt32(); info.centerFrequency1 = reply.ReadInt32(); info.features = reply.ReadInt64(); + + constexpr int IE_SIZE_MAX = 256; int ieSize = reply.ReadInt32(); + if (ieSize > IE_SIZE_MAX) { + WIFI_LOGE("ie size error: %{public}d", ieSize); + return WIFI_OPT_FAILED; + } for (int m = 0; m < ieSize; ++m) { WifiInfoElem tempWifiInfoElem; tempWifiInfoElem.id = reply.ReadInt32(); @@ -232,7 +273,7 @@ ErrCode WifiScanProxy::GetScanInfoList(std::vector &result) ErrCode WifiScanProxy::RegisterCallBack(const sptr &callback) { if (mRemoteDied) { - WIFI_LOGD("failed to `%{public}s`,remote service is died!", __func__); + WIFI_LOGW("failed to `%{public}s`,remote service is died!", __func__); return WIFI_OPT_FAILED; } WIFI_LOGD("RegisterCallBack start!"); @@ -240,9 +281,17 @@ ErrCode WifiScanProxy::RegisterCallBack(const sptr &callback) MessageParcel reply; MessageOption option(MessageOption::TF_ASYNC); - g_wifiScanCallbackStub.RegisterCallBack(callback); + if (g_wifiScanCallbackStub == nullptr) { + WIFI_LOGE("g_wifiScanCallbackStub is nullptr!"); + return WIFI_OPT_FAILED; + } + g_wifiScanCallbackStub->RegisterCallBack(callback); + if (!data.WriteInterfaceToken(GetDescriptor())) { + WIFI_LOGE("Write interface token error: %{public}s", __func__); + return WIFI_OPT_FAILED; + } data.WriteInt32(0); - if (!data.WriteRemoteObject(g_wifiScanCallbackStub.AsObject())) { + if (!data.WriteRemoteObject(g_wifiScanCallbackStub->AsObject())) { WIFI_LOGE("RegisterCallBack WriteRemoteObject failed!"); return WIFI_OPT_FAILED; } @@ -260,11 +309,15 @@ ErrCode WifiScanProxy::RegisterCallBack(const sptr &callback) ErrCode WifiScanProxy::GetSupportedFeatures(long &features) { if (mRemoteDied) { - WIFI_LOGD("failed to `%{public}s`,remote service is died!", __func__); + WIFI_LOGW("failed to `%{public}s`,remote service is died!", __func__); return WIFI_OPT_FAILED; } MessageOption option; MessageParcel data, reply; + if (!data.WriteInterfaceToken(GetDescriptor())) { + WIFI_LOGE("Write interface token error: %{public}s", __func__); + return WIFI_OPT_FAILED; + } data.WriteInt32(0); int error = Remote()->SendRequest(WIFI_SVR_CMD_GET_SUPPORTED_FEATURES, data, reply, option); if (error != ERR_NONE) { @@ -286,9 +339,13 @@ ErrCode WifiScanProxy::GetSupportedFeatures(long &features) void WifiScanProxy::OnRemoteDied(const wptr& remoteObject) { - WIFI_LOGD("Remote service is died!"); + WIFI_LOGW("Remote service is died!"); mRemoteDied = true; - g_wifiScanCallbackStub.SetRemoteDied(true); + if (g_wifiScanCallbackStub == nullptr) { + WIFI_LOGE("g_wifiScanCallbackStub is nullptr!"); + return; + } + g_wifiScanCallbackStub->SetRemoteDied(true); } } // namespace Wifi } // namespace OHOS diff --git a/interfaces/innerkits/native_cpp/wifi_standard/src/wifi_scan_proxy.h b/wifi/frameworks/native/src/wifi_scan_proxy.h similarity index 75% rename from interfaces/innerkits/native_cpp/wifi_standard/src/wifi_scan_proxy.h rename to wifi/frameworks/native/src/wifi_scan_proxy.h index a582b50d5aa0a6e5357152f226a326572e03cc9a..1bc16e38fb9dec87e9aeb2ea0c4617ea126312c9 100644 --- a/interfaces/innerkits/native_cpp/wifi_standard/src/wifi_scan_proxy.h +++ b/wifi/frameworks/native/src/wifi_scan_proxy.h @@ -1,5 +1,5 @@ /* - * Copyright (C) 2021 Huawei Device Co., Ltd. + * Copyright (C) 2021-2022 Huawei Device Co., Ltd. * 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 @@ -16,16 +16,33 @@ #ifndef WIFI_SCAN_PROXY #define WIFI_SCAN_PROXY -#include +#include +#ifdef OHOS_ARCH_LITE +#include "iproxy_client.h" +#else +#include "iremote_broker.h" +#include "iremote_object.h" +#include "iremote_proxy.h" +#endif #include "i_wifi_scan.h" +#include "i_wifi_scan_callback.h" +#include "refbase.h" #include "wifi_errcode.h" #include "wifi_scan_msg.h" namespace OHOS { namespace Wifi { +#ifdef OHOS_ARCH_LITE +class WifiScanProxy : public IWifiScan { +public:static WifiScanProxy *GetInstance(void); + static void ReleaseInstance(void); + explicit WifiScanProxy(void); + ErrCode Init(void); +#else class WifiScanProxy : public IRemoteProxy, public IRemoteObject::DeathRecipient { public: explicit WifiScanProxy(const sptr &remote); +#endif virtual ~WifiScanProxy(); /** @@ -67,7 +84,11 @@ public: */ virtual ErrCode GetScanInfoList(std::vector &result) override; +#ifdef OHOS_ARCH_LITE + virtual ErrCode RegisterCallBack(const std::shared_ptr &callback) override; +#else virtual ErrCode RegisterCallBack(const sptr &callback) override; +#endif /** * @Description Get supported features @@ -77,10 +98,19 @@ public: */ ErrCode GetSupportedFeatures(long &features) override; +#ifdef OHOS_ARCH_LITE + void OnRemoteDied(void); +private: + static WifiScanProxy *g_instance; + IClientProxy *remote_ = nullptr; + SvcIdentity svcIdentity_ = { 0 }; + bool remoteDied_; +#else void OnRemoteDied(const wptr& remoteObject) override; private: static BrokerDelegator g_delegator; bool mRemoteDied; +#endif }; } // namespace Wifi } // namespace OHOS diff --git a/wifi/frameworks/native/src/wifi_scan_proxy_lite.cpp b/wifi/frameworks/native/src/wifi_scan_proxy_lite.cpp new file mode 100644 index 0000000000000000000000000000000000000000..637565db291e65da6c76f55ecba0b3b4754cf59a --- /dev/null +++ b/wifi/frameworks/native/src/wifi_scan_proxy_lite.cpp @@ -0,0 +1,436 @@ +/* + * Copyright (C) 2022 Huawei Device Co., Ltd. + * 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 "wifi_scan_proxy.h" +#include "define.h" +#include "ipc_skeleton.h" +#include "rpc_errno.h" +#include "serializer.h" +#include "samgr_lite.h" +#include "wifi_ipc_lite_adapter.h" +#include "wifi_logger.h" +#include "wifi_scan_callback_stub.h" + +DEFINE_WIFILOG_SCAN_LABEL("WifiScanProxyLite"); +namespace OHOS { +namespace Wifi { +static SvcIdentity g_sid; +static IpcObjectStub g_objStub; +static WifiScanCallbackStub g_wifiScanCallbackStub; + +static ErrCode ParseScanInfos(IpcIo *reply, std::vector &infos) +{ + constexpr int MAX_SIZE = 4096; + int tmpsize = 0; + (void)ReadInt32(reply, &tmpsize); + if (tmpsize > MAX_SIZE) { + WIFI_LOGE("Scan info size exceeds maximum allowed size: %{public}d", tmpsize); + return WIFI_OPT_FAILED; + } + + unsigned int readLen; + for (int i = 0; i < tmpsize; ++i) { + WifiScanInfo info; + info.bssid = (char *)ReadString(reply, &readLen); + info.ssid = (char *)ReadString(reply, &readLen); + info.capabilities = (char *)ReadString(reply, &readLen); + (void)ReadInt32(reply, &info.frequency); + (void)ReadInt32(reply, &info.rssi); + int64_t timestamp = 0; + (void)ReadInt64(reply, ×tamp); + info.timestamp = timestamp; + (void)ReadInt32(reply, &info.band); + int securityType = 0; + (void)ReadInt32(reply, &securityType); + info.securityType = static_cast(securityType); + int channelWidth = 0; + (void)ReadInt32(reply, &channelWidth); + info.channelWidth = static_cast(channelWidth); + (void)ReadInt32(reply, &info.centerFrequency0); + (void)ReadInt32(reply, &info.centerFrequency1); + int64_t features = 0; + (void)ReadInt64(reply, &features); + info.features = features; + + constexpr int IE_SIZE_MAX = 256; + int ieSize = 0; + (void)ReadInt32(reply, &ieSize); + if (ieSize > IE_SIZE_MAX) { + WIFI_LOGE("ie size error: %{public}d", ieSize); + return WIFI_OPT_FAILED; + } + for (int m = 0; m < ieSize; ++m) { + WifiInfoElem tempWifiInfoElem; + (void)ReadUint32(reply, &tempWifiInfoElem.id); + int contentSize = 0; + (void)ReadInt32(reply, &contentSize); + int8_t tmpInt8 = 0; + for (int n = 0; n < contentSize; n++) { + (void)ReadInt8(reply, &tmpInt8); + char tempChar = static_cast(tmpInt8); + tempWifiInfoElem.content.emplace_back(tempChar); + } + info.infoElems.emplace_back(tempWifiInfoElem); + } + infos.emplace_back(info); + } + return WIFI_OPT_SUCCESS; +} + +static int IpcCallback(void *owner, int code, IpcIo *reply) +{ + if (code != 0 || owner == nullptr || reply == nullptr) { + WIFI_LOGE("Callback error, code:%{public}d, owner:%{public}d, reply:%{public}d", + code, owner == nullptr, reply == nullptr); + return ERR_FAILED; + } + + struct IpcOwner *data = (struct IpcOwner *)owner; + (void)ReadInt32(reply, &data->exception); + (void)ReadInt32(reply, &data->retCode); + if (data->exception != 0 || data->retCode != WIFI_OPT_SUCCESS || data->variable == nullptr) { + return ERR_NONE; + } + + switch (data->funcId) { + case WIFI_SVR_CMD_IS_SCAN_ALWAYS_ACTIVE: { + (void)ReadBool(reply, (bool *)data->variable); + break; + } + case WIFI_SVR_CMD_GET_SUPPORTED_FEATURES: { + int64_t features = 0; + (void)ReadInt64(reply, &features); + *((long *)data->variable) = features; + break; + } + case WIFI_SVR_CMD_GET_SCAN_INFO_LIST: { + data->retCode = ParseScanInfos(reply, *((std::vector *)data->variable)); + break; + } + default: + break; + } + return ERR_NONE; +} + +static int AsyncCallback(uint32_t code, IpcIo *data, IpcIo *reply, MessageOption option) +{ + if (data == nullptr) { + WIFI_LOGE("AsyncCallback error, data is null"); + return ERR_FAILED; + } + return g_wifiScanCallbackStub.OnRemoteRequest(code, data); +} + +static void OnRemoteSrvDied(void *arg) +{ + WIFI_LOGE("%{public}s called.", __func__); + WifiScanProxy *client = WifiScanProxy::GetInstance(); + if (client != nullptr) { + client->OnRemoteDied(); + } + return; +} + +WifiScanProxy *WifiScanProxy::g_instance = nullptr; +WifiScanProxy::WifiScanProxy() : remote_(nullptr), remoteDied_(false) +{} + +WifiScanProxy::~WifiScanProxy() +{} + +WifiScanProxy *WifiScanProxy::GetInstance(void) +{ + if (g_instance != nullptr) { + return g_instance; + } + + WifiScanProxy *tempInstance = new(std::nothrow) WifiScanProxy(); + g_instance = tempInstance; + return g_instance; +} + +void WifiScanProxy::ReleaseInstance(void) +{ + if (g_instance != nullptr) { + delete g_instance; + g_instance = nullptr; + } +} + +ErrCode WifiScanProxy::Init(void) +{ + IUnknown *iUnknown = SAMGR_GetInstance()->GetFeatureApi(WIFI_SERVICE_LITE, WIFI_FEATRUE_SCAN); + if (iUnknown == nullptr) { + WIFI_LOGE("GetFeatureApi failed."); + return WIFI_OPT_FAILED; + } + IClientProxy *proxy = nullptr; + int result = iUnknown->QueryInterface(iUnknown, CLIENT_PROXY_VER, reinterpret_cast(&proxy)); + if (result != 0) { + WIFI_LOGE("QueryInterface failed."); + return WIFI_OPT_FAILED; + } + remote_ = proxy; + + // Register SA Death Callback + uint32_t deadId = 0; + svcIdentity_ = SAMGR_GetRemoteIdentity(WIFI_SERVICE_LITE, WIFI_FEATRUE_SCAN); + result = AddDeathRecipient(svcIdentity_, OnRemoteSrvDied, nullptr, &deadId); + if (result != 0) { + WIFI_LOGE("Register SA Death Callback failed, errorCode[%d]", result); + } + return WIFI_OPT_SUCCESS; +} + +ErrCode WifiScanProxy::SetScanControlInfo(const ScanControlInfo &info) +{ + if (remoteDied_ || remote_ == nullptr) { + WIFI_LOGE("failed to %{public}s, remoteDied_: %{public}d, remote_: %{public}d", + __func__, remoteDied_, remote_ == nullptr); + return WIFI_OPT_FAILED; + } + + IpcIo request; + char data[IPC_DATA_SIZE_BIG]; + struct IpcOwner owner = {.exception = -1, .retCode = 0, .variable = nullptr}; + + IpcIoInit(&request, data, IPC_DATA_SIZE_BIG, MAX_IPC_OBJ_COUNT); + (void)WriteInt32(&request, 0); + (void)WriteInt32(&request, info.scanForbidList.size()); + for (auto iter = info.scanForbidList.begin(); iter != info.scanForbidList.end(); iter++) { + (void)WriteInt32(&request, iter->scanScene); + (void)WriteInt32(&request, static_cast(iter->scanMode)); + (void)WriteInt32(&request, iter->forbidTime); + (void)WriteInt32(&request, iter->forbidCount); + } + + (void)WriteInt32(&request, info.scanIntervalList.size()); + for (auto iter2 = info.scanIntervalList.begin(); iter2 != info.scanIntervalList.end(); iter2++) { + (void)WriteInt32(&request, iter2->scanScene); + (void)WriteInt32(&request, static_cast(iter2->scanMode)); + (void)WriteBool(&request, iter2->isSingle); + (void)WriteInt32(&request, static_cast(iter2->intervalMode)); + (void)WriteInt32(&request, iter2->interval); + (void)WriteInt32(&request, iter2->count); + } + + owner.funcId = WIFI_SVR_CMD_SET_SCAN_CONTROL_INFO; + int error = remote_->Invoke(remote_, WIFI_SVR_CMD_SET_SCAN_CONTROL_INFO, &request, &owner, IpcCallback); + if (error != EC_SUCCESS) { + WIFI_LOGW("Set Attr(%{public}d) failed", WIFI_SVR_CMD_SET_SCAN_CONTROL_INFO); + return WIFI_OPT_FAILED; + } + + if (owner.exception) { + return WIFI_OPT_FAILED; + } + return ErrCode(owner.retCode); +} + +ErrCode WifiScanProxy::Scan() +{ + if (remoteDied_ || remote_ == nullptr) { + WIFI_LOGE("failed to %{public}s, remoteDied_: %{public}d, remote_: %{public}d", + __func__, remoteDied_, remote_ == nullptr); + return WIFI_OPT_FAILED; + } + + IpcIo request; + char data[IPC_DATA_SIZE_SMALL]; + struct IpcOwner owner = {.exception = -1, .retCode = 0, .variable = nullptr}; + + IpcIoInit(&request, data, IPC_DATA_SIZE_SMALL, MAX_IPC_OBJ_COUNT); + (void)WriteInt32(&request, 0); + + owner.funcId = WIFI_SVR_CMD_FULL_SCAN; + int error = remote_->Invoke(remote_, WIFI_SVR_CMD_FULL_SCAN, &request, &owner, IpcCallback); + if (error != EC_SUCCESS) { + WIFI_LOGW("Set Attr(%{public}d) failed", WIFI_SVR_CMD_FULL_SCAN); + return WIFI_OPT_FAILED; + } + + if (owner.exception) { + return WIFI_OPT_FAILED; + } + return ErrCode(owner.retCode); +} + +ErrCode WifiScanProxy::AdvanceScan(const WifiScanParams ¶ms) +{ + if (remoteDied_ || remote_ == nullptr) { + WIFI_LOGE("failed to %{public}s, remoteDied_: %{public}d, remote_: %{public}d", + __func__, remoteDied_, remote_ == nullptr); + return WIFI_OPT_FAILED; + } + + IpcIo request; + char data[IPC_DATA_SIZE_MID]; + struct IpcOwner owner = {.exception = -1, .retCode = 0, .variable = nullptr}; + + IpcIoInit(&request, data, IPC_DATA_SIZE_MID, MAX_IPC_OBJ_COUNT); + (void)WriteInt32(&request, 0); + (void)WriteString(&request, params.ssid.c_str()); + (void)WriteString(&request, params.bssid.c_str()); + (void)WriteInt32(&request, params.freqs.size()); + for (std::size_t i = 0; i < params.freqs.size(); i++) { + (void)WriteInt32(&request, params.freqs[i]); + } + (void)WriteUint32(&request, params.band); + + owner.funcId = WIFI_SVR_CMD_SPECIFIED_PARAMS_SCAN; + int error = remote_->Invoke(remote_, WIFI_SVR_CMD_SPECIFIED_PARAMS_SCAN, &request, &owner, IpcCallback); + if (error != EC_SUCCESS) { + WIFI_LOGW("Set Attr(%{public}d) failed", WIFI_SVR_CMD_SPECIFIED_PARAMS_SCAN); + return WIFI_OPT_FAILED; + } + + if (owner.exception) { + return WIFI_OPT_FAILED; + } + + return ErrCode(owner.retCode); +} + +ErrCode WifiScanProxy::IsWifiClosedScan(bool &bOpen) +{ + if (remoteDied_ || remote_ == nullptr) { + WIFI_LOGE("failed to %{public}s, remoteDied_: %{public}d, remote_: %{public}d", + __func__, remoteDied_, remote_ == nullptr); + return WIFI_OPT_FAILED; + } + + IpcIo request; + char data[IPC_DATA_SIZE_SMALL]; + struct IpcOwner owner = {.exception = -1, .retCode = 0, .variable = nullptr}; + + IpcIoInit(&request, data, IPC_DATA_SIZE_SMALL, MAX_IPC_OBJ_COUNT); + (void)WriteInt32(&request, 0); + owner.variable = &bOpen; + owner.funcId = WIFI_SVR_CMD_IS_SCAN_ALWAYS_ACTIVE; + int error = remote_->Invoke(remote_, WIFI_SVR_CMD_IS_SCAN_ALWAYS_ACTIVE, &request, &owner, IpcCallback); + if (error != EC_SUCCESS) { + WIFI_LOGW("Set Attr(%{public}d) failed", WIFI_SVR_CMD_IS_SCAN_ALWAYS_ACTIVE); + return WIFI_OPT_FAILED; + } + + if (owner.exception) { + return WIFI_OPT_FAILED; + } + return ErrCode(owner.retCode); +} + +ErrCode WifiScanProxy::GetScanInfoList(std::vector &result) +{ + if (remoteDied_ || remote_ == nullptr) { + WIFI_LOGE("failed to %{public}s, remoteDied_: %{public}d, remote_: %{public}d", + __func__, remoteDied_, remote_ == nullptr); + return WIFI_OPT_FAILED; + } + + IpcIo request; + char data[IPC_DATA_SIZE_SMALL]; + struct IpcOwner owner = {.exception = -1, .retCode = 0, .variable = nullptr}; + + IpcIoInit(&request, data, IPC_DATA_SIZE_SMALL, MAX_IPC_OBJ_COUNT); + (void)WriteInt32(&request, 0); + owner.variable = &result; + owner.funcId = WIFI_SVR_CMD_GET_SCAN_INFO_LIST; + int error = remote_->Invoke(remote_, WIFI_SVR_CMD_GET_SCAN_INFO_LIST, &request, &owner, IpcCallback); + if (error != EC_SUCCESS) { + WIFI_LOGW("Set Attr(%{public}d) failed", WIFI_SVR_CMD_GET_SCAN_INFO_LIST); + return WIFI_OPT_FAILED; + } + + if (owner.exception) { + return WIFI_OPT_FAILED; + } + return ErrCode(owner.retCode); +} + +ErrCode WifiScanProxy::RegisterCallBack(const std::shared_ptr &callback) +{ + if (remoteDied_ || remote_ == nullptr) { + WIFI_LOGE("failed to %{public}s, remoteDied_: %{public}d, remote_: %{public}d", + __func__, remoteDied_, remote_ == nullptr); + return WIFI_OPT_FAILED; + } + WIFI_LOGD("RegisterCallBack start!"); + g_objStub.func = AsyncCallback; + g_objStub.args = nullptr; + g_objStub.isRemote = false; + + g_sid.handle = IPC_INVALID_HANDLE; + g_sid.token = SERVICE_TYPE_ANONYMOUS; + g_sid.cookie = (uintptr_t)&g_objStub; + + IpcIo request; + char data[IPC_DATA_SIZE_SMALL]; + struct IpcOwner owner = {.exception = -1, .retCode = 0, .variable = nullptr}; + + IpcIoInit(&request, data, IPC_DATA_SIZE_SMALL, MAX_IPC_OBJ_COUNT); + (void)WriteInt32(&request, 0); + (void)WriteRemoteObject(&request, &g_sid); + + owner.funcId = WIFI_SVR_CMD_REGISTER_SCAN_CALLBACK; + int error = remote_->Invoke(remote_, WIFI_SVR_CMD_REGISTER_SCAN_CALLBACK, &request, &owner, IpcCallback); + if (error != EC_SUCCESS) { + WIFI_LOGE("RegisterCallBack failed, error code is %{public}d", error); + return WIFI_OPT_FAILED; + } + WIFI_LOGD("RegisterCallBack is finished: result=%{public}d", owner.exception); + if (owner.exception) { + return WIFI_OPT_FAILED; + } + g_wifiScanCallbackStub.RegisterCallBack(callback); + return WIFI_OPT_SUCCESS; +} + +ErrCode WifiScanProxy::GetSupportedFeatures(long &features) +{ + if (remoteDied_ || remote_ == nullptr) { + WIFI_LOGE("failed to %{public}s, remoteDied_: %{public}d, remote_: %{public}d", + __func__, remoteDied_, remote_ == nullptr); + return WIFI_OPT_FAILED; + } + + IpcIo request; + char data[IPC_DATA_SIZE_SMALL]; + struct IpcOwner owner = {.exception = -1, .retCode = 0, .variable = nullptr}; + + IpcIoInit(&request, data, IPC_DATA_SIZE_SMALL, MAX_IPC_OBJ_COUNT); + (void)WriteInt32(&request, 0); + owner.variable = &features; + owner.funcId = WIFI_SVR_CMD_GET_SUPPORTED_FEATURES; + int error = remote_->Invoke(remote_, WIFI_SVR_CMD_GET_SUPPORTED_FEATURES, &request, &owner, IpcCallback); + if (error != EC_SUCCESS) { + WIFI_LOGE("Set Attr(%{public}d) failed,error code is %{public}d", WIFI_SVR_CMD_GET_SUPPORTED_FEATURES, error); + return ErrCode(error); + } + + if (owner.exception) { + return WIFI_OPT_FAILED; + } + return ErrCode(owner.retCode); +} + +void WifiScanProxy::OnRemoteDied(void) +{ + WIFI_LOGW("Remote service is died!"); + remoteDied_ = true; + g_wifiScanCallbackStub.SetRemoteDied(true); +} +} // namespace Wifi +} // namespace OHOS diff --git a/wifi/hisysevent.yaml b/wifi/hisysevent.yaml new file mode 100644 index 0000000000000000000000000000000000000000..b07a2379a04e93956958100f5c2d66e57ba73a68 --- /dev/null +++ b/wifi/hisysevent.yaml @@ -0,0 +1,38 @@ +# Copyright (C) 2022 Huawei Device Co., Ltd. +# 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. + +domain: COMMUNICATION + +# Start or stop Wi-Fi switch +WIFI_STATE: + __BASE: {type: STATISTIC, level: MINOR, tag: PowerStats, desc: Wifi enable or disable event} + TYPE: {type: STRING, desc: Service type} + OPER_TYPE: {type: INT32, desc: 0 is enable and 1 is disable} + +# Connect or disconnect Wi-Fi +WIFI_CONNECTION: + __BASE: {type: STATISTIC, level: MINOR, tag: PowerStats, desc: Wifi connection event} + TYPE: {type: INT32, desc: 0 is connect and 1 is disconnect} + PACKAGE_NAME: {type: STRING, desc: Package name} + +# Scans Wi-Fi hotspots +WIFI_SCAN: + __BASE: {type: STATISTIC, level: MINOR, tag: PowerStats, desc: Wifi scan event} + EXECUTE_RESULT: {type: INT32, desc: 0 is scan fail and 1 is scan success} + PACKAGE_NAME: {type: STRING, desc: Package name} + +# Wi-Fi event received +WIFI_EVENT_RECEIVED: + __BASE: {type: STATISTIC, level: MINOR, tag: PowerStats, desc: Wifi event} + EVENT_TYPE: {type: STRING, desc: Event type} + VALUE: {type: INT32, desc: Event value} diff --git a/interfaces/innerkits/native_c/station_info.h b/wifi/interfaces/kits/c/station_info.h old mode 100755 new mode 100644 similarity index 88% rename from interfaces/innerkits/native_c/station_info.h rename to wifi/interfaces/kits/c/station_info.h index 4fafb4a0adce18140f3589feff8028cf6fa738a9..93f14ed56fb18df218d576de97c07cc3acbb48a7 --- a/interfaces/innerkits/native_c/station_info.h +++ b/wifi/interfaces/kits/c/station_info.h @@ -1,61 +1,61 @@ -/* - * Copyright (c) 2020 Huawei Device Co., Ltd. - * 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. - */ - -/** - * @addtogroup wifiservice - * @{ - * - * @brief Provides functions for the Wi-Fi station and hotspot modes. - * - * You can use this module to enable and disable the Wi-Fi station or hotspot mode, connect to and disconnect from a - * station or hotspot, query the station or hotspot status, and listen for events. \n - * - * @since 7 - */ - -/** - * @file station_info.h - * - * @brief Defines the structure and macro of the station information contained in the event information. - * - * The station information is passed to {@link OnHotspotStaJoin} or {@link OnHotspotStaLeave} invoked when a specified - * event occurs. - * - * @since 7 - */ - -#ifndef HARMONY_OS_LITE_WIFI_STATION_INFO_H -#define HARMONY_OS_LITE_WIFI_STATION_INFO_H -#include "wifi_device_config.h" - -/** - * @brief Represents the station information. - * - * The station information is returned when {@link OnHotspotStaJoin} or {@link OnHotspotStaLeave} is called. \n - * - * @since 7 - */ -typedef struct { - /** Network name of the station */ - char *name; - /** MAC address. For its length, see {@link WIFI_MAC_LEN}. */ - unsigned char macAddress[WIFI_MAC_LEN]; - /** IP address of the station */ - unsigned int ipAddress; - unsigned short disconnectedReason; -} StationInfo; - -#endif // HARMONY_OS_LITE_WIFI_STATION_INFO_H -/** @} */ +/* + * Copyright (c) 2020 Huawei Device Co., Ltd. + * 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. + */ + +/** + * @addtogroup wifiservice + * @{ + * + * @brief Provides functions for the Wi-Fi station and hotspot modes. + * + * You can use this module to enable and disable the Wi-Fi station or hotspot mode, connect to and disconnect from a + * station or hotspot, query the station or hotspot status, and listen for events. \n + * + * @since 7 + */ + +/** + * @file station_info.h + * + * @brief Defines the structure and macro of the station information contained in the event information. + * + * The station information is passed to {@link OnHotspotStaJoin} or {@link OnHotspotStaLeave} invoked when a specified + * event occurs. + * + * @since 7 + */ + +#ifndef WIFI_LITE_WIFI_STATION_INFO_H +#define WIFI_LITE_WIFI_STATION_INFO_H +#include "wifi_device_config.h" + +/** + * @brief Represents the station information. + * + * The station information is returned when {@link OnHotspotStaJoin} or {@link OnHotspotStaLeave} is called. \n + * + * @since 7 + */ +typedef struct { + /** Network name of the station. Notice: please pre-allocate memory for "name" */ + char *name; + /** MAC address. For its length, see {@link WIFI_MAC_LEN}. */ + unsigned char macAddress[WIFI_MAC_LEN]; + /** IP address of the station */ + unsigned int ipAddress; + unsigned short disconnectedReason; +} StationInfo; + +#endif // WIFI_LITE_WIFI_STATION_INFO_H +/** @} */ diff --git a/interfaces/innerkits/native_c/wifi_device.h b/wifi/interfaces/kits/c/wifi_device.h old mode 100755 new mode 100644 similarity index 95% rename from interfaces/innerkits/native_c/wifi_device.h rename to wifi/interfaces/kits/c/wifi_device.h index 03e4d81cf0fda6016badaddaddb25bff4811d081..406302b79ced04167880bbcadde374de9ecf8728 --- a/interfaces/innerkits/native_c/wifi_device.h +++ b/wifi/interfaces/kits/c/wifi_device.h @@ -1,273 +1,282 @@ -/* - * Copyright (c) 2020 Huawei Device Co., Ltd. - * 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. - */ - -/** - * @addtogroup wifiservice - * @{ - * - * @brief Provides functions for the Wi-Fi station and hotspot modes. - * - * You can use this module to enable and disable the Wi-Fi station or hotspot mode, connect to and disconnect from a - * station or hotspot, query the station or hotspot status, and listen for events. \n - * - * @since 7 - */ - -/** - * @file wifi_device.h - * - * @brief Provides capabilities to enable and disable the station mode, connect to and disconnect from a station, - * query the station status, and listen for events. - * - * @since 7 - */ - -#ifndef WIFI_DEVICE_C_H -#define WIFI_DEVICE_C_H -#include "wifi_event.h" -#include "station_info.h" -#include "wifi_scan_info.h" -#include "wifi_error_code.h" -#include "wifi_linked_info.h" -#include "wifi_device_config.h" - -#ifdef __cplusplus -extern "C" { -#endif - -/** - * @brief Enables the station mode. - * - * @return Returns {@link WIFI_SUCCESS} if the station mode is enabled; returns an error code defined in - * {@link WifiErrorCode} otherwise. - * @since 7 - */ -WifiErrorCode EnableWifi(void); - -/** - * @brief Disables the station mode. - * - * @return Returns {@link WIFI_SUCCESS} if the station mode is disabled; returns an error code defined in - * {@link WifiErrorCode} otherwise. - * @since 7 - */ -WifiErrorCode DisableWifi(void); - -/** - * @brief Checks whether the station mode is enabled. - * - * @return Returns {@link WIFI_STA_ACTIVE} if the station mode is enabled; returns {@link WIFI_STA_NOT_ACTIVE} - * otherwise. - * @since 7 - */ -int IsWifiActive(void); - -/** - * @brief Starts a Wi-Fi scan. - * - * @return Returns {@link WIFI_SUCCESS} if the Wi-Fi scan is started; returns an error code defined in - * {@link WifiErrorCode} otherwise. - * @since 7 - */ -WifiErrorCode Scan(void); - -/** - * @brief Obtains an array of hotspots detected in a Wi-Fi scan. - * - * The array of hotspots can be obtained only after the Wi-Fi scan is complete. \n - * - * @param result Indicates the array of hotspots detected in a Wi-Fi scan. The array is requested and released by the - * caller. The value must be greater than or equal to {@link WIFI_SCAN_HOTSPOT_LIMIT}. - * @param size Indicates the size of the array. - * @return Returns {@link WIFI_SUCCESS} if the array of hotspots detected in the Wi-Fi scan is obtained; returns an - * error code defined in {@link WifiErrorCode} otherwise. - * @since 7 - */ -WifiErrorCode GetScanInfoList(WifiScanInfo *result, unsigned int *size); - -/** - * @brief Adds a specified hotspot configuration for connecting to a hotspot. - * - * This function generates a networkId. \n - * - * @param config Indicates the hotspot configuration to add. - * @param result Indicates the generated networkId. Each networkId matches a hotspot configuration. - * @return Returns {@link WIFI_SUCCESS} if the specified hotspot configuration is added; returns an error code defined - * in {@link WifiErrorCode} otherwise. - * @since 7 - */ -WifiErrorCode AddDeviceConfig(const WifiDeviceConfig *config, int *result); - -/** - * @brief Obtains all hotspot configurations. - * - * Hotspot configurations were added using {@link AddDeviceConfig}. \n - * - * @param result Indicates the array of all hotspot configurations. The array is requested and released by the caller. - * The value must be greater than or equal to {@link WIFI_MAX_CONFIG_SIZE}. - * @param size Indicates the size of the array. - * @return Returns {@link WIFI_SUCCESS} if all hotspot configurations are obtained; returns an error code defined in - * {@link WifiErrorCode} otherwise. - * @since 7 - */ -WifiErrorCode GetDeviceConfigs(WifiDeviceConfig *result, unsigned int *size); - -/** - * @brief Removes a hotspot configuration matching a specified networkId. - * - * @param networkId Indicates the networkId matching the hotspot configuration to remove. - * @return Returns {@link WIFI_SUCCESS} if the hotspot configuration is removed; returns an error code defined in - * {@link WifiErrorCode} otherwise. - * @since 7 - */ -WifiErrorCode RemoveDevice(int networkId); - -/** - * @brief Disable a hotspot configuration matching a specified networkId. If the config is diabled, it will - * not be auto connected. - * - * @param networkId Indicates the networkId matching the hotspot configuration to disable. - * @return Returns {@link WIFI_SUCCESS} if the hotspot configuration is disabled; returns an error code defined in - * {@link WifiErrorCode} otherwise. - * @since 7 - */ -WifiErrorCode DisableDeviceConfig(int networkId); - -/** - * @brief Enable a hotspot configuration matching a specified networkId. If the config is enabled, it will - * be connected automatically when wifi is enabled. When the config is added, it is enabled in default. - * - * @param networkId Indicates the networkId matching the hotspot configuration to enable. - * @return Returns {@link WIFI_SUCCESS} if the hotspot configuration is enabled; returns an error code defined in - * {@link WifiErrorCode} otherwise. - * @since 7 - */ -WifiErrorCode EnableDeviceConfig(int networkId); - -/** - * @brief Connects to a hotspot matching a specified networkId. - * - * Before calling this function, call {@link AddDeviceConfig} to add a hotspot configuration. \n - * - * @param networkId Indicates the networkId matching the target hotspot. - * @return Returns {@link WIFI_SUCCESS} if the hotspot is connected; returns an error code defined in - * {@link WifiErrorCode} otherwise. - * @since 7 - */ -WifiErrorCode ConnectTo(int networkId); - -/** - * @brief Connect to a hotspot by config. - * - * @param config is device configuration to connect the Wi-Fi network. - * @return Returns {@link WIFI_SUCCESS} if the hotspot is connected; returns an error code defined in - * {@link WifiErrorCode} otherwise. - * @since 7 - */ -WifiErrorCode ConnectToDevice(const WifiDeviceConfig *config); - -/** - * @brief Disconnects this Wi-Fi connection. - * - * @return Returns {@link WIFI_SUCCESS} if this Wi-Fi connection is disconnected; returns an error code defined - * in {@link WifiErrorCode} otherwise. - * @since 7 - */ -WifiErrorCode Disconnect(void); - -/** - * @brief Obtains information about the connected hotspot. - * - * @param result Indicates the information about the connected hotspot. - * @return Returns {@link WIFI_SUCCESS} if the information about the connected hotspot is obtained; returns an error - * code defined in {@link WifiErrorCode} otherwise. - * @since 7 - */ -WifiErrorCode GetLinkedInfo(WifiLinkedInfo *result); - -/** - * @brief Obtains the MAC address of this device. - * - * @param result Indicates the MAC address of this device. It is a char array whose length is 6. - * @return Returns {@link WIFI_SUCCESS} if the MAC address of this device is obtained; returns an error code defined - * in {@link WifiErrorCode} otherwise. - * @since 7 - */ -WifiErrorCode GetDeviceMacAddress(unsigned char *result); - -/** - * @brief Starts a Wi-Fi scan based on a specified parameter. - * - * Only results matching the specified parameter will be returned for the Wi-Fi scan.\n - * - * @param params Indicates the pointer to the parameter for starting the Wi-Fi scan. - * For details, see {@link WifiScanParams}. - * @return Returns {@link WIFI_SUCCESS} if the Wi-Fi scan is started successfully; - * returns an error code defined in {@link WifiErrorCode} otherwise. - * @since 7 - */ -WifiErrorCode AdvanceScan(WifiScanParams *params); - -/* - * @brief get the ip address. - * - * @return Returns {@link WIFI_SUCCESS} if the IP is got; returns an error code defined - * in {@link WifiErrorCode} otherwise. - * @since 7 - */ -WifiErrorCode GetIpInfo(IpInfo *info); - -/** - * @brief Obtains the signal level indicated by a specified received signal strength indicator (RSSI) and frequency - * band. - * - * - * Based on the signal level, you can display the signal strength represented by the number of signal bars. \n - * - * @param rssi Indicates the RSSI. - * @param band Indicates the frequency band, either {@link HOTSPOT_BAND_TYPE_5G} or {@link HOTSPOT_BAND_TYPE_2G}. - * @return Returns the signal level if it is obtained; returns -1 otherwise. - * @since 7 - */ -int GetSignalLevel(int rssi, int band); - -/** - * @brief Registers a callback for a specified Wi-Fi event. - * - * The registered callback will be invoked when the Wi-Fi event defined in {@link WifiEvent} occurs. \n - * - * @param event Indicates the event for which the callback is to be registered. - * @return Returns {@link WIFI_SUCCESS} if the callback is registered successfully; returns an error code defined - * in {@link WifiErrorCode} otherwise. - * @since 7 - */ -WifiErrorCode RegisterWifiEvent(WifiEvent *event); - -/** - * @brief Unregisters a callback previously registered for a specified Wi-Fi event. - * - * @param event Indicates the event for which the callback is to be unregistered. - * @return Returns {@link WIFI_SUCCESS} if the callback is unregistered successfully; returns an error code defined - * in {@link WifiErrorCode} otherwise. - * @since 7 - */ -WifiErrorCode UnRegisterWifiEvent(const WifiEvent *event); - -#ifdef __cplusplus -} -#endif - -#endif // WIFI_DEVICE_C_H -/** @} */ +/* + * Copyright (C) 2020-2022 Huawei Device Co., Ltd. + * 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. + */ + +/** + * @addtogroup wifiservice + * @{ + * + * @brief Provides functions for the Wi-Fi station and hotspot modes. + * + * You can use this module to enable and disable the Wi-Fi station or hotspot mode, connect to and disconnect from a + * station or hotspot, query the station or hotspot status, and listen for events. \n + * + * @since 7 + */ + +/** + * @file wifi_device.h + * + * @brief Provides capabilities to enable and disable the station mode, connect to and disconnect from a station, + * query the station status, and listen for events. + * + * @since 7 + */ + +#ifndef WIFI_DEVICE_C_H +#define WIFI_DEVICE_C_H +#include "wifi_event.h" +#include "station_info.h" +#include "wifi_scan_info.h" +#include "wifi_error_code.h" +#include "wifi_linked_info.h" +#include "wifi_device_config.h" + +#ifdef __cplusplus +extern "C" { +#endif + +/** + * @brief Enables the station mode. + * + * @return Returns {@link WIFI_SUCCESS} if the station mode is enabled; returns an error code defined in + * {@link WifiErrorCode} otherwise. + * @since 7 + */ +WifiErrorCode EnableWifi(void); + +/** + * @brief Disables the station mode. + * + * @return Returns {@link WIFI_SUCCESS} if the station mode is disabled; returns an error code defined in + * {@link WifiErrorCode} otherwise. + * @since 7 + */ +WifiErrorCode DisableWifi(void); + +/** + * @brief Checks whether the station mode is enabled. + * + * @return Returns {@link WIFI_STA_ACTIVE} if the station mode is enabled; returns {@link WIFI_STA_NOT_ACTIVE} + * otherwise. + * @since 7 + */ +int IsWifiActive(void); + +/** + * @brief Starts a Wi-Fi scan. + * + * @return Returns {@link WIFI_SUCCESS} if the Wi-Fi scan is started; returns an error code defined in + * {@link WifiErrorCode} otherwise. + * @since 7 + */ +WifiErrorCode Scan(void); + +/** + * @brief Obtains an array of hotspots detected in a Wi-Fi scan. + * + * The array of hotspots can be obtained only after the Wi-Fi scan is complete. \n + * + * @param result Indicates the array of hotspots detected in a Wi-Fi scan. The array is requested and released by the + * caller. The value must be greater than or equal to {@link WIFI_SCAN_HOTSPOT_LIMIT}. + * @param size Indicates the size of the array. + * @return Returns {@link WIFI_SUCCESS} if the array of hotspots detected in the Wi-Fi scan is obtained; returns an + * error code defined in {@link WifiErrorCode} otherwise. + * @since 7 + */ +WifiErrorCode GetScanInfoList(WifiScanInfo *result, unsigned int *size); + +/** + * @brief Adds a specified hotspot configuration for connecting to a hotspot. + * + * This function generates a networkId. \n + * + * @param config Indicates the hotspot configuration to add. + * @param result Indicates the generated networkId. Each networkId matches a hotspot configuration. + * @return Returns {@link WIFI_SUCCESS} if the specified hotspot configuration is added; returns an error code defined + * in {@link WifiErrorCode} otherwise. + * @since 7 + */ +WifiErrorCode AddDeviceConfig(const WifiDeviceConfig *config, int *result); + +/** + * @brief Obtains all hotspot configurations. + * + * Hotspot configurations were added using {@link AddDeviceConfig}. \n + * + * @param result Indicates the array of all hotspot configurations. The array is requested and released by the caller. + * The value must be greater than or equal to {@link WIFI_MAX_CONFIG_SIZE}. + * @param size Indicates the size of the array. + * @return Returns {@link WIFI_SUCCESS} if all hotspot configurations are obtained; returns an error code defined in + * {@link WifiErrorCode} otherwise. + * @since 7 + */ +WifiErrorCode GetDeviceConfigs(WifiDeviceConfig *result, unsigned int *size); + +/** + * @brief Removes a hotspot configuration matching a specified networkId. + * + * @param networkId Indicates the networkId matching the hotspot configuration to remove. + * @return Returns {@link WIFI_SUCCESS} if the hotspot configuration is removed; returns an error code defined in + * {@link WifiErrorCode} otherwise. + * @since 7 + */ +WifiErrorCode RemoveDevice(int networkId); + +/** + * @brief Disable a hotspot configuration matching a specified networkId. If the config is disabled, it will + * not be auto connected. + * + * @param networkId Indicates the networkId matching the hotspot configuration to disable. + * @return Returns {@link WIFI_SUCCESS} if the hotspot configuration is disabled; returns an error code defined in + * {@link WifiErrorCode} otherwise. + * @since 7 + */ +WifiErrorCode DisableDeviceConfig(int networkId); + +/** + * @brief Enable a hotspot configuration matching a specified networkId. If the config is enabled, it will + * be connected automatically when wifi is enabled. When the config is added, it is enabled in default. + * + * @param networkId Indicates the networkId matching the hotspot configuration to enable. + * @return Returns {@link WIFI_SUCCESS} if the hotspot configuration is enabled; returns an error code defined in + * {@link WifiErrorCode} otherwise. + * @since 7 + */ +WifiErrorCode EnableDeviceConfig(int networkId); + +/** + * @brief Connects to a hotspot matching a specified networkId. + * + * Before calling this function, call {@link AddDeviceConfig} to add a hotspot configuration. \n + * + * @param networkId Indicates the networkId matching the target hotspot. + * @return Returns {@link WIFI_SUCCESS} if the hotspot is connected; returns an error code defined in + * {@link WifiErrorCode} otherwise. + * @since 7 + */ +WifiErrorCode ConnectTo(int networkId); + +/** + * @brief Connect to a hotspot by config. + * + * @param config is device configuration to connect the Wi-Fi network. + * @return Returns {@link WIFI_SUCCESS} if the hotspot is connected; returns an error code defined in + * {@link WifiErrorCode} otherwise. + * @since 7 + */ +WifiErrorCode ConnectToDevice(const WifiDeviceConfig *config); + +/** + * @brief Disconnects this Wi-Fi connection. + * + * @return Returns {@link WIFI_SUCCESS} if this Wi-Fi connection is disconnected; returns an error code defined + * in {@link WifiErrorCode} otherwise. + * @since 7 + */ +WifiErrorCode Disconnect(void); + +/** + * @brief Obtains information about the connected hotspot. + * + * @param result Indicates the information about the connected hotspot. + * @return Returns {@link WIFI_SUCCESS} if the information about the connected hotspot is obtained; returns an error + * code defined in {@link WifiErrorCode} otherwise. + * @since 7 + */ +WifiErrorCode GetLinkedInfo(WifiLinkedInfo *result); + +/** + * @brief Obtains the MAC address of this device. + * + * @param result Indicates the MAC address of this device. It is a char array whose length is 6. + * @return Returns {@link WIFI_SUCCESS} if the MAC address of this device is obtained; returns an error code defined + * in {@link WifiErrorCode} otherwise. + * @since 7 + */ +WifiErrorCode GetDeviceMacAddress(unsigned char *result); + +/** + * @brief Starts a Wi-Fi scan based on a specified parameter. + * + * Only results matching the specified parameter will be returned for the Wi-Fi scan.\n + * + * @param params Indicates the pointer to the parameter for starting the Wi-Fi scan. + * For details, see {@link WifiScanParams}. + * @return Returns {@link WIFI_SUCCESS} if the Wi-Fi scan is started successfully; + * returns an error code defined in {@link WifiErrorCode} otherwise. + * @since 7 + */ +WifiErrorCode AdvanceScan(WifiScanParams *params); + +/* + * @brief get the ip address. + * + * @return Returns {@link WIFI_SUCCESS} if the IP is got; returns an error code defined + * in {@link WifiErrorCode} otherwise. + * @since 7 + */ +WifiErrorCode GetIpInfo(IpInfo *info); + +/** + * @brief Obtains the signal level indicated by a specified received signal strength indicator (RSSI) and frequency + * band. + * + * + * Based on the signal level, you can display the signal strength represented by the number of signal bars. \n + * + * @param rssi Indicates the RSSI. + * @param band Indicates the frequency band, either {@link HOTSPOT_BAND_TYPE_5G} or {@link HOTSPOT_BAND_TYPE_2G}. + * @return Returns the signal level if it is obtained; returns -1 otherwise. + * @since 7 + */ +int GetSignalLevel(int rssi, int band); + +/** + * @brief set low latency mode + * + * @param enabled 0: disable low latency, 1: enable low latency + * @return Returns {@link WIFI_SUCCESS} if set success; returns an error code defined + * in {@link WifiErrorCode} otherwise. + * @since 8 + */ +WifiErrorCode SetLowLatencyMode(int enabled); + +/** + * @brief Registers a callback for a specified Wi-Fi event. + * + * The registered callback will be invoked when the Wi-Fi event defined in {@link WifiEvent} occurs. \n + * + * @param event Indicates the event for which the callback is to be registered. + * @return Returns {@link WIFI_SUCCESS} if the callback is registered successfully; returns an error code defined + * in {@link WifiErrorCode} otherwise. + * @since 7 + */ +WifiErrorCode RegisterWifiEvent(WifiEvent *event); + +/** + * @brief Unregisters a callback previously registered for a specified Wi-Fi event. + * + * @param event Indicates the event for which the callback is to be unregistered. + * @return Returns {@link WIFI_SUCCESS} if the callback is unregistered successfully; returns an error code defined + * in {@link WifiErrorCode} otherwise. + * @since 7 + */ +WifiErrorCode UnRegisterWifiEvent(WifiEvent *event); +#ifdef __cplusplus +} +#endif + +#endif // WIFI_DEVICE_C_H +/** @} */ diff --git a/interfaces/innerkits/native_c/wifi_device_config.h b/wifi/interfaces/kits/c/wifi_device_config.h old mode 100755 new mode 100644 similarity index 91% rename from interfaces/innerkits/native_c/wifi_device_config.h rename to wifi/interfaces/kits/c/wifi_device_config.h index 32167b98081112aa0a6293344dc8d3d6204854cc..537f5197c9ba4305ccdf1191b1f5b11dcb073639 --- a/interfaces/innerkits/native_c/wifi_device_config.h +++ b/wifi/interfaces/kits/c/wifi_device_config.h @@ -1,233 +1,243 @@ -/* - * Copyright (c) 2020 Huawei Device Co., Ltd. - * 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. - */ - -/** - * @addtogroup wifiservice - * @{ - * - * @brief Provides functions for the Wi-Fi station and hotspot modes. - * - * You can use this module to enable and disable the Wi-Fi station or hotspot mode, connect to and disconnect from a - * station or hotspot, query the station or hotspot status, and listen for events. \n - * - * @since 7 - */ - -/** - * @file wifi_device_config.h - * - * @brief Defines the Wi-Fi station configuration. - * - * The Wi-Fi station configuration includes the security type and data length. \n - * - * @since 7 - */ - -#ifndef HARMONY_OS_LITE_WIFI_DEVICE_CONFIG_H -#define HARMONY_OS_LITE_WIFI_DEVICE_CONFIG_H - -/** - * @brief Indicates the maximum number of Wi-Fi station configurations that can be added using {@link AddDeviceConfig}. - * - * If the maximum number is reached, an error will be returned. In this case, you must delete at least one - * configuration before you can add new ones. \n - */ -#define WIFI_MAX_CONFIG_SIZE 10 -/** - * @brief Indicates the value of networkId when the configuration file is unavailable. - * - * Generally, the configuration file is unavailable because the configuration matching the networkId is - * uninitialized. \n - */ -#define WIFI_CONFIG_INVALID (-1) -/** - * @brief Indicates the maximum length of a Wi-Fi SSID. - * - * The maximum length is 32, and the last bit is reserved and set to \0. \n - */ -#define WIFI_MAX_SSID_LEN 33 // 32 + \0 -/** - * @brief Indicates the maximum length of a Wi-Fi key. - * - * The maximum length is 64, and the last bit is reserved and set to \0. \n - */ -#define WIFI_MAX_KEY_LEN 65 // 64 + \0 -/** - * @brief Indicates the maximum length of a Wi-Fi MAC address or a Wi-Fi BSSID. - * - */ -#define WIFI_MAC_LEN 6 - -/** - * @brief Indicates the maximum length of a Wi-Fi PSK. - * - */ -#define WIFI_PSK_LEN 32 - -/** - * @brief Indicates the maximum number of DNS servers. - * - * A maximum of two DNS servers are allowed. \n - */ -#define WIFI_MAX_DNS_NUM 2 - -/** - * @brief Indicates the maximum length of a device name. - * - */ -#define DEVICE_NAME_LEN 128 - -/** - * @brief Enumerates Wi-Fi security types. - * - * @since 7 - */ -typedef enum { - /** Invalid security type */ - WIFI_SEC_TYPE_INVALID = -1, - /** Open */ - WIFI_SEC_TYPE_OPEN, - /** Wired Equivalent Privacy (WEP) */ - WIFI_SEC_TYPE_WEP, - /** Pre-shared key (PSK) */ - WIFI_SEC_TYPE_PSK, - /** Simultaneous Authentication of Equals (SAE) */ - WIFI_SEC_TYPE_SAE, -} WifiSecurityType; - -/** - * @brief Enumerates psk encryption types. - * - * @since 7 - */ -typedef enum { - /** Indicates that the ascii type of psk encryption type */ - WIFI_PSK_TYPE_ASCII = 0, - /** Indicates that the hex type of psk encryption type */ - WIFI_PSK_TYPE_HEX, -} WifiPskType; - -/** - * @brief Defines the IP configuration of the Wi-Fi device. - * - * The IP configuration is mainly used for connecting to the device. \n - * - * @since 3 - */ -typedef struct { - /** IP address of the Wi-Fi device */ - unsigned int ipAddress; - /** Gateway of the Wi-Fi device */ - unsigned int gateway; - /** DNS server addresses for the Wi-Fi device */ - unsigned int dnsServers[WIFI_MAX_DNS_NUM]; - /** Subnet mask of the Wi-Fi device */ - unsigned int netmask; -} IpConfig; - -/** - * @brief Enumerates IP address types for the Wi-Fi device. - * - * @since 3 - */ -typedef enum { - /** Static IP address */ - STATIC_IP, - /** IP address dynamically assigned by DHCP */ - DHCP, - /** Unknown IP address type */ - UNKNOWN -} IpType; - -/** - * @brief Represents the Wi-Fi station configuration used to connect to a specified Wi-Fi device. - * - * @since 7 - */ -typedef struct WifiDeviceConfig { - /** Service set ID (SSID). For its length, see {@link WIFI_MAX_SSID_LEN}. */ - char ssid[WIFI_MAX_SSID_LEN]; - /** Basic service set ID (BSSID). For its length, see {@link WIFI_MAC_LEN}. */ - unsigned char bssid[WIFI_MAC_LEN]; - /** Key. For its length, see {@link WIFI_MAX_KEY_LEN}. */ - char preSharedKey[WIFI_MAX_KEY_LEN]; - /** Security type. It is defined in {@link WifiSecurityType}. */ - int securityType; - /** Allocated networkId */ - int netId; - /** Frequency */ - unsigned int freq; - /** PSK type, see {@link WifiPskType}. */ - int wapiPskType; - /** IP address type */ - IpType ipType; - /** Static IP address */ - IpConfig staticIp; - /* 1 for hidden config */ - int isHiddenSsid; -} WifiDeviceConfig; - -/** - * @brief Enumerates Wi-Fi scan types. - * - * @since 7 - */ -typedef enum { - /** A scan based on a specified frequency. */ - WIFI_FREQ_SCAN, - /** A scan based on a specified SSID. */ - WIFI_SSID_SCAN, - /** A scan based on a specified BSSID. */ - WIFI_BSSID_SCAN, - /** A scan based on a specified frequency band. */ - WIFI_BAND_SCAN -} WifiScanType; - -/** - * @brief Represents the Wi-Fi station configuration used to connect to a specified Wi-Fi device. - * - * @since 7 - */ -typedef struct { - /** Service set ID (SSID). Its maximum length is defined by {@link WIFI_MAX_SSID_LEN}. */ - char ssid[WIFI_MAX_SSID_LEN]; - /** Length of the SSID. */ - char ssidLen; - /** Basic service set ID (BSSID). Its length is defined by {@link WIFI_MAC_LEN}. */ - char bssid[WIFI_MAC_LEN]; - /** Frequency. */ - int freqs; - /** Frequency band. */ - int band; - /** Wi-Fi scan type, which is defined by {@link WifiScanType}. */ - WifiScanType scanType; -} WifiScanParams; - -/** - * @brief IP info - * - * @since 7 - */ -typedef struct { - unsigned int ipAddress; - unsigned int netMask; - unsigned int netGate; - unsigned int dns1; - unsigned int dns2; - unsigned int serverAddress; - int leaseDuration; -} IpInfo; -#endif // HARMONY_OS_LITE_WIFI_DEVICE_CONFIG_H -/** @} */ +/* + * Copyright (c) 2020 Huawei Device Co., Ltd. + * 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. + */ + +/** + * @addtogroup wifiservice + * @{ + * + * @brief Provides functions for the Wi-Fi station and hotspot modes. + * + * You can use this module to enable and disable the Wi-Fi station or hotspot mode, connect to and disconnect from a + * station or hotspot, query the station or hotspot status, and listen for events. \n + * + * @since 7 + */ + +/** + * @file wifi_device_config.h + * + * @brief Defines the Wi-Fi station configuration. + * + * The Wi-Fi station configuration includes the security type and data length. \n + * + * @since 7 + */ + +#ifndef WIFI_LITE_WIFI_DEVICE_CONFIG_H +#define WIFI_LITE_WIFI_DEVICE_CONFIG_H + +/** + * @brief Indicates the maximum number of Wi-Fi station configurations that can be added using {@link AddDeviceConfig}. + * + * If the maximum number is reached, an error will be returned. In this case, you must delete at least one + * configuration before you can add new ones. \n + */ +#define WIFI_MAX_CONFIG_SIZE 10 +/** + * @brief Indicates the value of networkId when the configuration file is unavailable. + * + * Generally, the configuration file is unavailable because the configuration matching the networkId is + * uninitialized. \n + */ +#define WIFI_CONFIG_INVALID (-1) +/** + * @brief Indicates the maximum length of a Wi-Fi SSID. + * + * The maximum length is 32, and the last bit is reserved and set to \0. \n + */ +#define WIFI_MAX_SSID_LEN 33 // 32 + \0 +/** + * @brief Indicates the maximum length of a Wi-Fi key. + * + * The maximum length is 64, and the last bit is reserved and set to \0. \n + */ +#define WIFI_MAX_KEY_LEN 65 // 64 + \0 +/** + * @brief Indicates the maximum length of a Wi-Fi MAC address or a Wi-Fi BSSID. + * + */ +#define WIFI_MAC_LEN 6 + +/** + * @brief Indicates the maximum length of a Wi-Fi PSK. + * + */ +#define WIFI_PSK_LEN 32 + +/** + * @brief Indicates the maximum number of DNS servers. + * + * A maximum of two DNS servers are allowed. \n + */ +#define WIFI_MAX_DNS_NUM 2 + +/** + * @brief Indicates the maximum length of a device name. + * + */ +#define DEVICE_NAME_LEN 128 + +/** + * @brief Enumerates Wi-Fi security types. + * + * @since 7 + */ +typedef enum { + /** Invalid security type */ + WIFI_SEC_TYPE_INVALID = -1, + /** Open */ + WIFI_SEC_TYPE_OPEN = 0, + /** Wired Equivalent Privacy (WEP) */ + WIFI_SEC_TYPE_WEP = 1, + /** Pre-shared key (PSK) */ + WIFI_SEC_TYPE_PSK = 2, + /** Ethernet Automatic Protection (EAP) */ + WIFI_SEC_TYPE_EAP = 3, + /** Simultaneous Authentication of Equals (SAE) */ + WIFI_SEC_TYPE_SAE = 4, + /** EAP suite B */ + WIFI_SEC_TYPE_EAP_SUITE_B = 5, + /** Opportunistic Wireless Encryption (OWE) */ + WIFI_SEC_TYPE_OWE = 6, + /** WAPI cert */ + WIFI_SEC_TYPE_WAPI_CERT = 7, + /** WAPI PSK */ + WIFI_SEC_TYPE_WAPI_PSK = 8, +} WifiSecurityType; + +/** + * @brief Enumerates psk encryption types. + * + * @since 7 + */ +typedef enum { + /** Indicates that the ascii type of psk encryption type */ + WIFI_PSK_TYPE_ASCII = 0, + /** Indicates that the hex type of psk encryption type */ + WIFI_PSK_TYPE_HEX, +} WifiPskType; + +/** + * @brief Defines the IP configuration of the Wi-Fi device. + * + * The IP configuration is mainly used for connecting to the device. \n + * + * @since 3 + */ +typedef struct { + /** IP address of the Wi-Fi device */ + unsigned int ipAddress; + /** Gateway of the Wi-Fi device */ + unsigned int gateway; + /** DNS server addresses for the Wi-Fi device */ + unsigned int dnsServers[WIFI_MAX_DNS_NUM]; + /** Subnet mask of the Wi-Fi device */ + unsigned int netmask; +} IpConfig; + +/** + * @brief Enumerates IP address types for the Wi-Fi device. + * + * @since 3 + */ +typedef enum { + /** Static IP address */ + STATIC_IP, + /** IP address dynamically assigned by DHCP */ + DHCP, + /** Unknown IP address type */ + UNKNOWN +} IpType; + +/** + * @brief Represents the Wi-Fi station configuration used to connect to a specified Wi-Fi device. + * + * @since 7 + */ +typedef struct WifiDeviceConfig { + /** Service set ID (SSID). For its length, see {@link WIFI_MAX_SSID_LEN}. */ + char ssid[WIFI_MAX_SSID_LEN]; + /** Basic service set ID (BSSID). For its length, see {@link WIFI_MAC_LEN}. */ + unsigned char bssid[WIFI_MAC_LEN]; + /** Key. For its length, see {@link WIFI_MAX_KEY_LEN}. */ + char preSharedKey[WIFI_MAX_KEY_LEN]; + /** Security type. It is defined in {@link WifiSecurityType}. */ + int securityType; + /** Allocated networkId */ + int netId; + /** Frequency */ + unsigned int freq; + /** PSK type, see {@link WifiPskType}. */ + int wapiPskType; + /** IP address type */ + IpType ipType; + /** Static IP address */ + IpConfig staticIp; + /* 1 for hidden config */ + int isHiddenSsid; +} WifiDeviceConfig; + +/** + * @brief Enumerates Wi-Fi scan types. + * + * @since 7 + */ +typedef enum { + /** A scan based on a specified frequency. */ + WIFI_FREQ_SCAN, + /** A scan based on a specified SSID. */ + WIFI_SSID_SCAN, + /** A scan based on a specified BSSID. */ + WIFI_BSSID_SCAN, + /** A scan based on a specified frequency band. */ + WIFI_BAND_SCAN +} WifiScanType; + +/** + * @brief Represents the Wi-Fi station configuration used to connect to a specified Wi-Fi device. + * + * @since 7 + */ +typedef struct { + /** Service set ID (SSID). Its maximum length is defined by {@link WIFI_MAX_SSID_LEN}. */ + char ssid[WIFI_MAX_SSID_LEN]; + /** Length of the SSID. */ + char ssidLen; + /** Basic service set ID (BSSID). Its length is defined by {@link WIFI_MAC_LEN}. */ + char bssid[WIFI_MAC_LEN]; + /** Frequency. */ + int freqs; + /** Frequency band. */ + int band; + /** Wi-Fi scan type, which is defined by {@link WifiScanType}. */ + WifiScanType scanType; +} WifiScanParams; + +/** + * @brief IP info + * + * @since 7 + */ +typedef struct { + unsigned int ipAddress; + unsigned int netMask; + unsigned int netGate; + unsigned int dns1; + unsigned int dns2; + unsigned int serverAddress; + int leaseDuration; +} IpInfo; +#endif // WIFI_LITE_WIFI_DEVICE_CONFIG_H +/** @} */ diff --git a/interfaces/innerkits/native_c/wifi_error_code.h b/wifi/interfaces/kits/c/wifi_error_code.h old mode 100755 new mode 100644 similarity index 96% rename from interfaces/innerkits/native_c/wifi_error_code.h rename to wifi/interfaces/kits/c/wifi_error_code.h index de6e24006f62592d64e446f10b4af55a1b9e87fe..a48fd1e11c557a0f56f52a0ca1d54994e299b8cc --- a/interfaces/innerkits/native_c/wifi_error_code.h +++ b/wifi/interfaces/kits/c/wifi_error_code.h @@ -1,70 +1,70 @@ -/* - * Copyright (c) 2020 Huawei Device Co., Ltd. - * 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. - */ - -/** - * @addtogroup wifiservice - * @{ - * - * @brief Provides functions for the Wi-Fi station and hotspot modes. - * - * You can use this module to enable and disable the Wi-Fi station or hotspot mode, connect to and disconnect from a - * station or hotspot, query the station or hotspot status, and listen for events. \n - * - * @since 7 - */ - -/** - * @file wifi_error_code.h - * - * @brief Defines error codes of the Wi-Fi service. - * - * @since 7 - */ - -#ifndef WIFI_ERROR_CODE_C_H -#define WIFI_ERROR_CODE_C_H - -/** - * @brief Enumerates Wi-Fi error codes. - * - * @since 7 - */ -typedef enum { - /** No errors. */ - WIFI_SUCCESS = 0, - /** Invalid parameters */ - ERROR_WIFI_INVALID_ARGS = -1, - /** Invalid chip */ - ERROR_WIFI_CHIP_INVALID = -2, - /** Invalid Wi-Fi interface */ - ERROR_WIFI_IFACE_INVALID = -3, - /** Invalid RTT controller */ - ERROR_WIFI_RTT_CONTROLLER_INVALID = -4, - /** Wi-Fi not supported by the current version or device */ - ERROR_WIFI_NOT_SUPPORTED = -5, - /** Wi-Fi unavailable */ - ERROR_WIFI_NOT_AVAILABLE = -6, - /** Wi-Fi not initialized or started */ - ERROR_WIFI_NOT_STARTED = -7, - /** System busy */ - ERROR_WIFI_BUSY = -8, - /** Wi-Fi invalid password */ - ERROR_WIFI_INVALID_PASSWORD = -9, - /** Unknown error */ - ERROR_WIFI_UNKNOWN = -128 -} WifiErrorCode; - -#endif // WIFI_ERROR_CODE_C_H +/* + * Copyright (c) 2020 Huawei Device Co., Ltd. + * 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. + */ + +/** + * @addtogroup wifiservice + * @{ + * + * @brief Provides functions for the Wi-Fi station and hotspot modes. + * + * You can use this module to enable and disable the Wi-Fi station or hotspot mode, connect to and disconnect from a + * station or hotspot, query the station or hotspot status, and listen for events. \n + * + * @since 7 + */ + +/** + * @file wifi_error_code.h + * + * @brief Defines error codes of the Wi-Fi service. + * + * @since 7 + */ + +#ifndef WIFI_ERROR_CODE_C_H +#define WIFI_ERROR_CODE_C_H + +/** + * @brief Enumerates Wi-Fi error codes. + * + * @since 7 + */ +typedef enum { + /** No errors. */ + WIFI_SUCCESS = 0, + /** Invalid parameters */ + ERROR_WIFI_INVALID_ARGS = -1, + /** Invalid chip */ + ERROR_WIFI_CHIP_INVALID = -2, + /** Invalid Wi-Fi interface */ + ERROR_WIFI_IFACE_INVALID = -3, + /** Invalid RTT controller */ + ERROR_WIFI_RTT_CONTROLLER_INVALID = -4, + /** Wi-Fi not supported by the current version or device */ + ERROR_WIFI_NOT_SUPPORTED = -5, + /** Wi-Fi unavailable */ + ERROR_WIFI_NOT_AVAILABLE = -6, + /** Wi-Fi not initialized or started */ + ERROR_WIFI_NOT_STARTED = -7, + /** System busy */ + ERROR_WIFI_BUSY = -8, + /** Wi-Fi invalid password */ + ERROR_WIFI_INVALID_PASSWORD = -9, + /** Unknown error */ + ERROR_WIFI_UNKNOWN = -128 +} WifiErrorCode; + +#endif // WIFI_ERROR_CODE_C_H /** @} */ \ No newline at end of file diff --git a/interfaces/innerkits/native_c/wifi_event.h b/wifi/interfaces/kits/c/wifi_event.h old mode 100755 new mode 100644 similarity index 88% rename from interfaces/innerkits/native_c/wifi_event.h rename to wifi/interfaces/kits/c/wifi_event.h index a4459beb14896870c5165c634c55fc1317be1fa3..0bc11c30f933d07ba3dededb05414d82ea784bfa --- a/interfaces/innerkits/native_c/wifi_event.h +++ b/wifi/interfaces/kits/c/wifi_event.h @@ -1,117 +1,115 @@ -/* - * Copyright (c) 2020 Huawei Device Co., Ltd. - * 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. - */ - -/** - * @addtogroup wifiservice - * @{ - * - * @brief Provides functions for the Wi-Fi station and hotspot modes. - * - * You can use this module to enable and disable the Wi-Fi station or hotspot mode, connect to and disconnect from a - * station or hotspot, query the station or hotspot status, and listen for events. \n - * - * @since 7 - */ - -/** - * @file wifi_event.h - * - * @brief Defines callbacks and structure of Wi-Fi events. - * - * {@link RegisterWifiEvent} can be used to listen for Wi-Fi connection, disconnection, and scan events. \n - * - * @since 7 - */ -#ifndef WIFI_EVENT_C_H -#define WIFI_EVENT_C_H - -#include "wifi_linked_info.h" -#include "station_info.h" -#include "wifi_error_code.h" - -#ifdef __cplusplus -extern "C" { -#endif - -/** - * @brief Indicates that the Wi-Fi station mode is enabled. - * - */ -#define WIFI_STA_ACTIVE 1 -/** - * @brief Indicates that the Wi-Fi station mode is disabled. - * - */ -#define WIFI_STA_NOT_ACTIVE 0 - -/** - * @brief Indicates that the Wi-Fi hotspot mode is enabled. - * - */ -#define WIFI_HOTSPOT_ACTIVE 1 -/** - * @brief Indicates that the Wi-Fi hotspot mode is disabled. - * - */ -#define WIFI_HOTSPOT_NOT_ACTIVE 0 - -/** - * @brief Indicates the maximum number of event listeners that can be registered using {@link RegisterWifiEvent}. - * - * When the maximum number is reached, you need to unregister at least one listener before registering new ones. \n - */ -#define WIFI_MAX_EVENT_SIZE 10 - -/** - * @brief Represents the pointer to a Wi-Fi event callback for station and hotspot connection, disconnection, or scan. - * - * - * If you do not need a callback, set the value of its pointer to NULL. \n - * - * @since 7 - */ -typedef struct { - /** Connection state change */ - void (*OnWifiConnectionChanged)(int state, WifiLinkedInfo *info); - /** Scan state change */ - void (*OnWifiScanStateChanged)(int state, int size); - /** Hotspot state change */ - void (*OnHotspotStateChanged)(int state); - /** Station connected */ - void (*OnHotspotStaJoin)(StationInfo *info); - /** Station disconnected */ - void (*OnHotspotStaLeave)(StationInfo *info); -} WifiEvent; - -/** - * @brief Enumerates states in Wi-Fi events. - * - * - * - * @since 7 - */ -typedef enum { - /** Unavailable state */ - WIFI_STATE_NOT_AVALIABLE = 0, - /** Available state */ - WIFI_STATE_AVALIABLE -} WifiEventState; - -#ifdef __cplusplus -} -#endif - -#endif // WIFI_EVENT_C_H -/** @} */ +/* + * Copyright (c) 2020-2022 Huawei Device Co., Ltd. + * 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. + */ + +/** + * @addtogroup wifiservice + * @{ + * + * @brief Provides functions for the Wi-Fi station and hotspot modes. + * + * You can use this module to enable and disable the Wi-Fi station or hotspot mode, connect to and disconnect from a + * station or hotspot, query the station or hotspot status, and listen for events. \n + * + * @since 7 + */ + +/** + * @file wifi_event.h + * + * @brief Defines callbacks and structure of Wi-Fi events. + * + * {@link RegisterWifiEvent} can be used to listen for Wi-Fi connection, disconnection, and scan events. \n + * + * @since 7 + */ +#ifndef WIFI_EVENT_C_H +#define WIFI_EVENT_C_H + +#include "wifi_linked_info.h" +#include "station_info.h" +#include "wifi_error_code.h" + +#ifdef __cplusplus +extern "C" { +#endif + +/** + * @brief Indicates that the Wi-Fi station mode is enabled. + * + */ +#define WIFI_STA_ACTIVE 1 +/** + * @brief Indicates that the Wi-Fi station mode is disabled. + * + */ +#define WIFI_STA_NOT_ACTIVE 0 + +/** + * @brief Indicates that the Wi-Fi hotspot mode is enabled. + * + */ +#define WIFI_HOTSPOT_ACTIVE 1 +/** + * @brief Indicates that the Wi-Fi hotspot mode is disabled. + * + */ +#define WIFI_HOTSPOT_NOT_ACTIVE 0 + +/** + * @brief Indicates the maximum number of event listeners that can be registered using {@link RegisterWifiEvent}. + * + * When the maximum number is reached, you need to unregister at least one listener before registering new ones. \n + */ +#define WIFI_MAX_EVENT_SIZE 10 + +/** + * @brief Enumerates of device configuration change. + * + * @since 9 + */ +typedef enum { + CONFIG_ADD = 0, + CONFIG_UPDATE = 1, + CONFIG_REMOVE = 2, +} ConfigChange; + +/** + * @brief Represents the pointer to a Wi-Fi event callback for station and hotspot connection, disconnection, or scan. + * + * + * If you do not need a callback, set the value of its pointer to NULL. \n + * + * @since 7 + */ +typedef struct { + /** Connection state change */ + void (*OnWifiConnectionChanged)(int state, WifiLinkedInfo *info); + /** Scan state change */ + void (*OnWifiScanStateChanged)(int state, int size); + /** Hotspot state change */ + void (*OnHotspotStateChanged)(int state); + /** Station connected */ + void (*OnHotspotStaJoin)(StationInfo *info); + /** Station disconnected */ + void (*OnHotspotStaLeave)(StationInfo *info); + /** Device config change */ + void (*OnDeviceConfigChange)(ConfigChange state); +} WifiEvent; +#ifdef __cplusplus +} +#endif + +#endif // WIFI_EVENT_C_H +/** @} */ diff --git a/wifi/interfaces/kits/c/wifi_hid2d.h b/wifi/interfaces/kits/c/wifi_hid2d.h new file mode 100644 index 0000000000000000000000000000000000000000..926c54aac339c813daf1d750c1ae832d88c35a07 --- /dev/null +++ b/wifi/interfaces/kits/c/wifi_hid2d.h @@ -0,0 +1,301 @@ +/* + * Copyright (C) 2022 Huawei Device Co., Ltd. + * 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 OHOS_C_HID2D_H +#define OHOS_C_HID2D_H + +#include "wifi_error_code.h" + +#ifdef __cplusplus +extern "C" { +#endif + +#ifndef MAC_LEN +#define MAC_LEN 6 +#endif + +#define IPV4_ARRAY_LEN 4 + +#ifndef IF_NAME_LEN +#define IF_NAME_LEN 32 +#endif + +#define MAX_SSID_LEN 33 // max length: 32 + \0 +#define MAX_KEY_LEN 65 // max length: 64 + \0 + +#define CFG_DATA_MAX_BYTES 255 + +#define CFG_CALLBACK_BYTE 4 + +typedef enum CfgType { + CFG_INVALID = -1, + GET_SELF_CONFIG = 0, +} CfgType; + +typedef void (*WifiCfgChangCallback)(CfgType, char* data, int dataLen); + +typedef enum DhcpMode { + CONNECT_GO_NODHCP = 0, + CONNECT_AP_DHCP = 1, + CONNECT_AP_NODHCP = 2 +} DhcpMode; + +typedef enum FreqType { + FREQUENCY_DEFAULT = 0, + FREQUENCY_160M = 1, +} FreqType; + +typedef enum SelfCfgType { + TYPE_OF_GET_SELF_CONFIG = 1, + TYPE_OF_GET_SELF_CONFIG_WITH_PASSWORD = 2 +} SelfCfgType; + +typedef enum PeerCfgType { + TYPE_OF_SET_PEER_CONFIG = 1, + TYPE_OF_SET_PEER_STATE_CHANGE = 2 +} PeerCfgType; + +typedef enum PreferBandwidth { + /** default */ + BW_DEFAULT, + /** indicates the ultimate bandwidth, corresponding to 160 Mbit/s or 320 Mbit/s in the future. */ + BW_EXTRAM, + /** high throughput. The default value is 80 Mbit/s. */ + BW_HIGH_PERF, + /** low-latency service type, 40 Mbit/s/80 Mbit/s, + * which needs to be determined based on the current channel status. */ + BW_LOW_LATENCY +} PreferBandwidth; + +typedef enum RecommendStatus { + RS_SUCCESS, + RS_LOCAL_ADJUST, + RS_REMOTE_ADJUST, + RS_FAILURE +} RecommendStatus; + +typedef struct Hid2dConnectConfig { + /** Service set ID (SSID). */ + char ssid[MAX_SSID_LEN]; + /** Basic service set ID (BSSID). */ + unsigned char bssid[MAC_LEN]; + /** Key. */ + char preSharedKey[MAX_KEY_LEN]; + /** group frequency. */ + int frequency; + /** connection mode. */ + DhcpMode dhcpMode; +} Hid2dConnectConfig; + +/** + * @Description Ip address info structure, the element format is a 4-bit int array. + * example: 127.0.0.1 -> int[ 127, 0, 0, 1 ] + */ +typedef struct IpAddrInfo { + unsigned int ip[IPV4_ARRAY_LEN]; + unsigned int gateway[IPV4_ARRAY_LEN]; + unsigned int netmask[IPV4_ARRAY_LEN]; +} IpAddrInfo; + +typedef struct RecommendChannelRequest { + /** the interface name of the remote device */ + char remoteIfName[IF_NAME_LEN]; + /** the mode of the interface on the remote device */ + int remoteIfMode; + /** interface name of the local device */ + char localIfName[IF_NAME_LEN]; + /** the mode of the interface on the local device */ + int localIfMode; + /** preferred frequency band */ + int prefBand; + /** preferred bandwidth type (enumerated) */ + PreferBandwidth prefBandwidth; +} RecommendChannelRequest; + +typedef struct RecommendChannelResponse { + /** 0: success; 1: local adjustment; 2: remote adjustment; –1: failure */ + RecommendStatus status; + /* 1 fails. 0-N corresponds to the input array subscript (that is, the interface to be connected) */ + int index; + /* The primary 20 MHz frequency of the channel */ + int centerFreq; + /** + * Do not used if the access point bandwidth is 20 MHz + * If the AP use 40, 80 or 160 MHz, this is the center frequency, if the AP use 80 + 80 MHz, + * this is the center frequency of the first segment + */ + int centerFreq1; + /** + * Only used if the AP bandwidth is 80 + 80 MHz + * if the AP use 80 + 80 MHz, this is the center frequency of the second segment + */ + int centerFreq2; + /* band width */ + int bandwidth; +} RecommendChannelResponse; + +typedef struct Hid2dUpperScene { + /* The mac address of the device */ + unsigned char mac[MAC_LEN]; + /* The scene of upper layer, hexadecimal digit, currently bit 0-2 is valid, 0: video, 1: audio, 2: file */ + unsigned int scene; + /* Frame rate, -1/30/60 is valid */ + int fps; + /* band width, valid only in video scenes, the default value is 0 */ + unsigned int bw; +} Hid2dUpperScene; + +/** + * @Description Request an IP address to the Gc from the IP address pool, used on the GO side. + * + * @param gcMac - gc mac address + * @param ipAddr - Indicates the applied IP address, which is a 4-bit int array. + * example: 127.0.0.1 -> ipAddr[ 127, 0, 0, 1 ] + * @return WifiErrorCode - operation result + */ +WifiErrorCode Hid2dRequestGcIp(const unsigned char gcMac[MAC_LEN], unsigned int ipAddr[IPV4_ARRAY_LEN]); + +/** + * @Description Increase(+1) shared link reference counting + * + * @return WifiErrorCode - operation result + */ +WifiErrorCode Hid2dSharedlinkIncrease(void); + +/** + * @Description Decrease(-1) shared link reference counting + * + * @return WifiErrorCode - operation result + */ +WifiErrorCode Hid2dSharedlinkDecrease(void); + +/** + * @Description Create hid2d group, used on the GO side. + * + * @param frequency - frequency + * @param type - frequency type + * @return WifiErrorCode - operation result + */ +WifiErrorCode Hid2dCreateGroup(const int frequency, FreqType type); + +/** + * @Description The GC side actively disconnects from the GO, used on the GC side. + * + * @param gcIfName - network interface name + * @return WifiErrorCode - operation result + */ +WifiErrorCode Hid2dRemoveGcGroup(const char gcIfName[IF_NAME_LEN]); + +/** + * @Description Connect to a specified group using hid2d, used on the GC side. + * + * @param config - connection parameters + * @return WifiErrorCode - operation result + */ +WifiErrorCode Hid2dConnect(const Hid2dConnectConfig *config); + +/** + * @Description Configuring IP addresses for P2P network interfaces, used on the GC side. + * + * @param ifName - network interface name + * @param ipInfo - IP infos + * @return WifiErrorCode - operation result + */ +WifiErrorCode Hid2dConfigIPAddr(const char ifName[IF_NAME_LEN], const IpAddrInfo *ipInfo); + +/** + * @Description Clear IP address when the P2P connection is disconnected, used on the GC side. + * + * @param ifName - network interface name + * @return WifiErrorCode - operation result + */ +WifiErrorCode Hid2dReleaseIPAddr(const char ifName[IF_NAME_LEN]); + +/** + * @Description Obtain the recommended channel and bandwidth for link setup + * + * @param request - request data + * @param response - response result + * + * @return WifiErrorCode - operation result + */ +WifiErrorCode Hid2dGetRecommendChannel(const RecommendChannelRequest *request, RecommendChannelResponse *response); + +/** + * @Description Get 5G channel list + * + * @param chanList - An array of pre-allocated memory for storing channel list results, + * Use the '0' to indicates the end of valid data in the "chanList" array. + * + * @param len - the length of the pre-alloc "chanList" + * @return WifiErrorCode - operation result + */ +WifiErrorCode Hid2dGetChannelListFor5G(int *chanList, int len); + +/** + * @Description get the self wifi configuration information + * + * @param cfgType - configuration type + * @param cfgData - the queried data of wifi configuration + * @param getDatValidLen - the valid data length in the array `cfgData` + * @return WifiErrorCode - operation result + */ +WifiErrorCode Hid2dGetSelfWifiCfgInfo(SelfCfgType cfgType, char cfgData[CFG_DATA_MAX_BYTES], int *getDatValidLen); + +/** + * @Description set the peer wifi configuration information + * + * @param cfgType - configuration type + * @param cfgData - the wifi configuration data to be set + * @param setDataValidLen - the valid data length in the array `cfgData` + * @return WifiErrorCode - operation result + */ +WifiErrorCode Hid2dSetPeerWifiCfgInfo(PeerCfgType cfgType, char cfgData[CFG_DATA_MAX_BYTES], int setDataValidLen); + +/** + * @Description Querying the support capability of wide bandwidth + * + * @return int - 0: not supported, 1: supported + */ +int Hid2dIsWideBandwidthSupported(void); + +/** + * @Description Set the scene of upper layer + * + * @param ifName - interface name + * @param scene - scene + * @return WifiErrorCode - operate result + */ +WifiErrorCode Hid2dSetUpperScene(const char ifName[IF_NAME_LEN], const Hid2dUpperScene *scene); + +/** + * @Description Register config change callback + * + * @param callback - callback + * @return WifiErrorCode - operate result + */ +WifiErrorCode RegisterCfgChangCallback(const WifiCfgChangCallback callback); + +/** + * @Description Unregister config change callback + * + * @return WifiErrorCode - operate result + */ +WifiErrorCode UnregisterCfgChangCallback(void); +#ifdef __cplusplus +} +#endif + +#endif diff --git a/interfaces/innerkits/native_c/wifi_hotspot.h b/wifi/interfaces/kits/c/wifi_hotspot.h old mode 100755 new mode 100644 similarity index 94% rename from interfaces/innerkits/native_c/wifi_hotspot.h rename to wifi/interfaces/kits/c/wifi_hotspot.h index 2aee5e2649aea94e5ff601aa7fa9b65d477650f3..e8780509d20e0c7422bd38d6cf9f79b483712573 --- a/interfaces/innerkits/native_c/wifi_hotspot.h +++ b/wifi/interfaces/kits/c/wifi_hotspot.h @@ -1,152 +1,152 @@ -/* - * Copyright (c) 2020 Huawei Device Co., Ltd. - * 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. - */ - -/** - * @addtogroup wifiservice - * @{ - * - * @brief Provides functions for the Wi-Fi station and hotspot modes. - * - * You can use this module to enable and disable the Wi-Fi station or hotspot mode, connect to and disconnect from a - * station or hotspot, query the station or hotspot status, and listen for events. \n - * - * @since 7 - */ - -/** - * @file wifi_hotspot.h - * - * @brief Provides capabilities to enable and disable the hotspot mode, connect to and disconnect from a hotspot, query - * the hotspot status, and listen for events. - * - * @since 7 - */ - -#ifndef HARMONY_OS_LITE_WIFI_HOTSPOT_H -#define HARMONY_OS_LITE_WIFI_HOTSPOT_H -#include "wifi_device.h" -#include "wifi_error_code.h" -#include "wifi_hotspot_config.h" -#include "wifi_event.h" - -#ifdef __cplusplus -extern "C" { -#endif - -/** - * @brief Defines the default channel of the hotspot mode. - */ -#define HOTSPOT_DEFAULT_CHANNEL 6 - -/** - * @brief Enables the hotspot mode. - * - * Before using this function, you need to invoke {@link SetHotspotConfig} and set at least the SSID, security type, - * and key. \n - * - * @return Returns {@link WIFI_SUCCESS} if the hotspot mode is enabled; returns an error code defined in - * {@link WifiErrorCode} otherwise. - * @since 7 - */ -WifiErrorCode EnableHotspot(void); - -/** - * @brief Disables the hotspot mode. - * - * @return Returns {@link WIFI_SUCCESS} if the hotspot mode is disabled; returns an error code defined in - * {@link WifiErrorCode} otherwise. - * @since 7 - */ -WifiErrorCode DisableHotspot(void); - -/** - * @brief Sets a specified hotspot configuration. - * - * The hotspot configuration includes the SSID, security type, and key. The configuration set overwrites the existing - * configuration and takes effect after the hotspot mode is re-enabled. \n - * Before enabling the hotspot mode for the first time, you must call this function. \n - * - * @param config Indicates the hotspot configuration to set. - * @return Returns {@link WIFI_SUCCESS} if the hotspot configuration is set; returns an error code defined in - * {@link WifiErrorCode} otherwise. - * @since 7 - */ -WifiErrorCode SetHotspotConfig(const HotspotConfig *config); - -/** - * @brief Obtains a specified hotspot configuration. - * - * The hotspot configuration includes the SSID, security type, and key. \n - * - * @param result Indicates the obtained hotspot configuration. - * @return Returns {@link WIFI_SUCCESS} if the hotspot configuration is obtained; returns an error code defined in - * {@link WifiErrorCode} otherwise. - * @since 7 - */ -WifiErrorCode GetHotspotConfig(HotspotConfig *result); - -/** - * @brief Checks whether the hotspot mode is enabled. - * - * @return Returns {@link WIFI_HOTSPOT_ACTIVE} if the hotspot mode is enabled; returns {@link WIFI_HOTSPOT_NOT_ACTIVE} - * otherwise. - * @since 7 - */ -int IsHotspotActive(void); - -/** - * @brief Obtains an array of stations connected to this hotspot. - * - * The station information is defined in {@link StationInfo}. \n - * - * @param result Indicates the array of stations connected to this hotspot. The array is requested and released by the - * caller. The value must be greater than or equal to {@link WIFI_MAX_STA_NUM}. - * @param size Indicates the size of the array. - * @return Returns {@link WIFI_SUCCESS} if the array of stations connected to this hotspot is obtained; returns an error - * code defined in {@link WifiErrorCode} otherwise. - * @since 7 - */ -WifiErrorCode GetStationList(StationInfo *result, unsigned int *size); - -/** - * @brief Disconnects from the station with a specified MAC address. - * - * @param mac Indicates the pointer to the MAC address of the station. - * @param macLen Indicates the length of the MAC address of the station. - * @return Returns {@link WIFI_SUCCESS} if the function is successfully called; - * returns an error code defined in {@link WifiErrorCode} otherwise. - * @since 7 - */ -WifiErrorCode DisassociateSta(unsigned char *mac, int macLen); - -/** - * @brief Adds the hotspot transmit power to the beacon. - * - * After the transmit power is added, the beacon must contain specified IEs. If the minimum transmit power - * 0xFFFFFFFF is added, the beacon does not contain the IEs. \n - * The transmit power is added to the ie field only, exerting no impacts on the transmit power. \n - * @param power Indicates the transmit power to add. - * @return Returns {@link WIFI_SUCCESS} if the function is successfully called; returns an error code defined - * in {@link WifiErrorCode} otherwise. - * @since 7 - */ -WifiErrorCode AddTxPowerInfo(int power); - -#ifdef __cplusplus -} -#endif - -#endif // HARMONY_OS_LITE_WIFI_HOTSPOT_H_ -/** @} */ +/* + * Copyright (c) 2020 Huawei Device Co., Ltd. + * 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. + */ + +/** + * @addtogroup wifiservice + * @{ + * + * @brief Provides functions for the Wi-Fi station and hotspot modes. + * + * You can use this module to enable and disable the Wi-Fi station or hotspot mode, connect to and disconnect from a + * station or hotspot, query the station or hotspot status, and listen for events. \n + * + * @since 7 + */ + +/** + * @file wifi_hotspot.h + * + * @brief Provides capabilities to enable and disable the hotspot mode, connect to and disconnect from a hotspot, query + * the hotspot status, and listen for events. + * + * @since 7 + */ + +#ifndef WIFI_LITE_WIFI_HOTSPOT_H +#define WIFI_LITE_WIFI_HOTSPOT_H +#include "wifi_device.h" +#include "wifi_error_code.h" +#include "wifi_hotspot_config.h" +#include "wifi_event.h" + +#ifdef __cplusplus +extern "C" { +#endif + +/** + * @brief Defines the default channel of the hotspot mode. + */ +#define HOTSPOT_DEFAULT_CHANNEL 6 + +/** + * @brief Enables the hotspot mode. + * + * Before using this function, you need to invoke {@link SetHotspotConfig} and set at least the SSID, security type, + * and key. \n + * + * @return Returns {@link WIFI_SUCCESS} if the hotspot mode is enabled; returns an error code defined in + * {@link WifiErrorCode} otherwise. + * @since 7 + */ +WifiErrorCode EnableHotspot(void); + +/** + * @brief Disables the hotspot mode. + * + * @return Returns {@link WIFI_SUCCESS} if the hotspot mode is disabled; returns an error code defined in + * {@link WifiErrorCode} otherwise. + * @since 7 + */ +WifiErrorCode DisableHotspot(void); + +/** + * @brief Sets a specified hotspot configuration. + * + * The hotspot configuration includes the SSID, security type, and key. The configuration set overwrites the existing + * configuration and takes effect after the hotspot mode is re-enabled. \n + * Before enabling the hotspot mode for the first time, you must call this function. \n + * + * @param config Indicates the hotspot configuration to set. + * @return Returns {@link WIFI_SUCCESS} if the hotspot configuration is set; returns an error code defined in + * {@link WifiErrorCode} otherwise. + * @since 7 + */ +WifiErrorCode SetHotspotConfig(const HotspotConfig *config); + +/** + * @brief Obtains a specified hotspot configuration. + * + * The hotspot configuration includes the SSID, security type, and key. \n + * + * @param result Indicates the obtained hotspot configuration. + * @return Returns {@link WIFI_SUCCESS} if the hotspot configuration is obtained; returns an error code defined in + * {@link WifiErrorCode} otherwise. + * @since 7 + */ +WifiErrorCode GetHotspotConfig(HotspotConfig *result); + +/** + * @brief Checks whether the hotspot mode is enabled. + * + * @return Returns {@link WIFI_HOTSPOT_ACTIVE} if the hotspot mode is enabled; returns {@link WIFI_HOTSPOT_NOT_ACTIVE} + * otherwise. + * @since 7 + */ +int IsHotspotActive(void); + +/** + * @brief Obtains an array of stations connected to this hotspot. + * + * The station information is defined in {@link StationInfo}. \n + * + * @param result Indicates the array of stations connected to this hotspot. The array is requested and released by the + * caller. The value must be greater than or equal to {@link WIFI_MAX_STA_NUM}. + * @param size Indicates the size of the array. + * @return Returns {@link WIFI_SUCCESS} if the array of stations connected to this hotspot is obtained; returns an error + * code defined in {@link WifiErrorCode} otherwise. + * @since 7 + */ +WifiErrorCode GetStationList(StationInfo *result, unsigned int *size); + +/** + * @brief Disconnects from the station with a specified MAC address. + * + * @param mac Indicates the pointer to the MAC address of the station. + * @param macLen Indicates the length of the MAC address of the station. + * @return Returns {@link WIFI_SUCCESS} if the function is successfully called; + * returns an error code defined in {@link WifiErrorCode} otherwise. + * @since 7 + */ +WifiErrorCode DisassociateSta(unsigned char *mac, int macLen); + +/** + * @brief Adds the hotspot transmit power to the beacon. + * + * After the transmit power is added, the beacon must contain specified IEs. If the minimum transmit power + * 0xFFFFFFFF is added, the beacon does not contain the IEs. \n + * The transmit power is added to the ie field only, exerting no impacts on the transmit power. \n + * @param power Indicates the transmit power to add. + * @return Returns {@link WIFI_SUCCESS} if the function is successfully called; returns an error code defined + * in {@link WifiErrorCode} otherwise. + * @since 7 + */ +WifiErrorCode AddTxPowerInfo(int power); + +#ifdef __cplusplus +} +#endif + +#endif // WIFI_LITE_WIFI_HOTSPOT_H_ +/** @} */ diff --git a/interfaces/innerkits/native_c/wifi_hotspot_config.h b/wifi/interfaces/kits/c/wifi_hotspot_config.h old mode 100755 new mode 100644 similarity index 96% rename from interfaces/innerkits/native_c/wifi_hotspot_config.h rename to wifi/interfaces/kits/c/wifi_hotspot_config.h index fef32e742d431d23375deb56051a86e95c88934b..51ecc2e379e9fc5c9cfdae9f4740973ffcb155d5 --- a/interfaces/innerkits/native_c/wifi_hotspot_config.h +++ b/wifi/interfaces/kits/c/wifi_hotspot_config.h @@ -1,121 +1,121 @@ -/* - * Copyright (c) 2020 Huawei Device Co., Ltd. - * 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. - */ - -/** - * @addtogroup wifiservice - * @{ - * - * @brief Provides functions for the Wi-Fi station and hotspot modes. - * - * You can use this module to enable and disable the Wi-Fi station or hotspot mode, connect to and disconnect from a - * station or hotspot, query the station or hotspot status, and listen for events. \n - * - * @since 7 - */ - -/** - * @file wifi_hotspot_config.h - * - * @brief Defines the Wi-Fi hotspot configuration. - * - * @since 7 - */ - -#ifndef WIFI_HOTSPOT_CONFIG_C_H -#define WIFI_HOTSPOT_CONFIG_C_H - -#include "wifi_device_config.h" -#include "wifi_error_code.h" - -/** - * @brief Defines the maximum number of stations connected to a hotspot. - */ -#define WIFI_MAX_STA_NUM 6 - -/** - * @brief Enumerates received signal strength indicator (RSSI) levels. - * - * Four RSSI levels are available: 1 to 4. The higher the RSSI level, the stronger the Wi-Fi signal. - * - * @since 7 - */ -typedef enum { - /** Level 1. The RSSI value for a 2.4 GHz hotspot ranges from -88 (included) to -82 (excluded), - * and that for a 5 GHz hotspot ranges from -85 (included) to -79 (excluded). */ - RSSI_LEVEL_1 = 1, - /** Level 2. The RSSI value for a 2.4 GHz hotspot ranges from -82 (included) to -75 (excluded), - * and that for a 5 GHz hotspot ranges from -79 (included) to -72 (excluded). */ - RSSI_LEVEL_2 = 2, - /** Level 3. The RSSI value for a 2.4 GHz hotspot ranges from -75 (included) to -65 (excluded), - * and that for a 5 GHz hotspot ranges from -72 (included) to -65 (excluded). */ - RSSI_LEVEL_3 = 3, - /** Level 4. The RSSI value for a 2.4 GHz or 5 GHz hotspot is greater than or equal to -65. */ - RSSI_LEVEL_4 = 4, -} RssiLevel; - -/** - * @brief Enumerates frequency bands supported by the Wi-Fi hotspot mode. - * - * @since 7 - */ -typedef enum { - /** 2.4 GHz */ - HOTSPOT_BAND_TYPE_2G = 1, - /** 5 GHz */ - HOTSPOT_BAND_TYPE_5G = 2, -} HotspotBandType; - -/** - * @brief Represents the hotspot configuration. - * - * A hotspot configuration must contain the SSID (or BSSID), security type, and key (if the security type is open). \n - * - * @since 7 - */ -typedef struct { - /** Service set ID (SSID). For its length, see {@link WIFI_MAX_SSID_LEN}. */ - char ssid[WIFI_MAX_SSID_LEN]; - /** Security type */ - int securityType; - /** Frequency band */ - int band; - /** Channel number */ - int channelNum; - /** Key. For its length, see {@link WIFI_MAX_SSID_LEN}. */ - char preSharedKey[WIFI_MAX_KEY_LEN]; -} HotspotConfig; - -/** - * @brief Sets the frequency band for this hotspot. - * - * @param band Indicates the frequency band to set. - * @return Returns {@link WIFI_SUCCESS} if the frequency band is set; returns an error code defined in - * {@link WifiErrorCode} otherwise. - * @since 7 - */ -WifiErrorCode SetBand(int band); - -/** - * @brief Obtains the frequency band of this hotspot. - * - * @param result Indicates the obtained frequency band. - * @return Returns {@link WIFI_SUCCESS} if the frequency band is obtained; returns an error code defined in - * {@link WifiErrorCode} otherwise. - * @since 7 - */ -WifiErrorCode GetBand(int *result); - -#endif // WIFI_HOTSPOT_CONFIG_C_H -/** @} */ +/* + * Copyright (c) 2020 Huawei Device Co., Ltd. + * 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. + */ + +/** + * @addtogroup wifiservice + * @{ + * + * @brief Provides functions for the Wi-Fi station and hotspot modes. + * + * You can use this module to enable and disable the Wi-Fi station or hotspot mode, connect to and disconnect from a + * station or hotspot, query the station or hotspot status, and listen for events. \n + * + * @since 7 + */ + +/** + * @file wifi_hotspot_config.h + * + * @brief Defines the Wi-Fi hotspot configuration. + * + * @since 7 + */ + +#ifndef WIFI_HOTSPOT_CONFIG_C_H +#define WIFI_HOTSPOT_CONFIG_C_H + +#include "wifi_device_config.h" +#include "wifi_error_code.h" + +/** + * @brief Defines the maximum number of stations connected to a hotspot. + */ +#define WIFI_MAX_STA_NUM 6 + +/** + * @brief Enumerates received signal strength indicator (RSSI) levels. + * + * Four RSSI levels are available: 1 to 4. The higher the RSSI level, the stronger the Wi-Fi signal. + * + * @since 7 + */ +typedef enum { + /** Level 1. The RSSI value for a 2.4 GHz hotspot ranges from -88 (included) to -82 (excluded), + * and that for a 5 GHz hotspot ranges from -85 (included) to -79 (excluded). */ + RSSI_LEVEL_1 = 1, + /** Level 2. The RSSI value for a 2.4 GHz hotspot ranges from -82 (included) to -75 (excluded), + * and that for a 5 GHz hotspot ranges from -79 (included) to -72 (excluded). */ + RSSI_LEVEL_2 = 2, + /** Level 3. The RSSI value for a 2.4 GHz hotspot ranges from -75 (included) to -65 (excluded), + * and that for a 5 GHz hotspot ranges from -72 (included) to -65 (excluded). */ + RSSI_LEVEL_3 = 3, + /** Level 4. The RSSI value for a 2.4 GHz or 5 GHz hotspot is greater than or equal to -65. */ + RSSI_LEVEL_4 = 4, +} RssiLevel; + +/** + * @brief Enumerates frequency bands supported by the Wi-Fi hotspot mode. + * + * @since 7 + */ +typedef enum { + /** 2.4 GHz */ + HOTSPOT_BAND_TYPE_2G = 1, + /** 5 GHz */ + HOTSPOT_BAND_TYPE_5G = 2, +} HotspotBandType; + +/** + * @brief Represents the hotspot configuration. + * + * A hotspot configuration must contain the SSID (or BSSID), security type, and key (if the security type is open). \n + * + * @since 7 + */ +typedef struct { + /** Service set ID (SSID). For its length, see {@link WIFI_MAX_SSID_LEN}. */ + char ssid[WIFI_MAX_SSID_LEN]; + /** Security type */ + int securityType; + /** Frequency band */ + int band; + /** Channel number */ + int channelNum; + /** Key. For its length, see {@link WIFI_MAX_SSID_LEN}. */ + char preSharedKey[WIFI_MAX_KEY_LEN]; +} HotspotConfig; + +/** + * @brief Sets the frequency band for this hotspot. + * + * @param band Indicates the frequency band to set. + * @return Returns {@link WIFI_SUCCESS} if the frequency band is set; returns an error code defined in + * {@link WifiErrorCode} otherwise. + * @since 7 + */ +WifiErrorCode SetBand(int band); + +/** + * @brief Obtains the frequency band of this hotspot. + * + * @param result Indicates the obtained frequency band. + * @return Returns {@link WIFI_SUCCESS} if the frequency band is obtained; returns an error code defined in + * {@link WifiErrorCode} otherwise. + * @since 7 + */ +WifiErrorCode GetBand(int *result); + +#endif // WIFI_HOTSPOT_CONFIG_C_H +/** @} */ diff --git a/interfaces/innerkits/native_c/wifi_linked_info.h b/wifi/interfaces/kits/c/wifi_linked_info.h old mode 100755 new mode 100644 similarity index 91% rename from interfaces/innerkits/native_c/wifi_linked_info.h rename to wifi/interfaces/kits/c/wifi_linked_info.h index 0e6ea3c4d3dcab45c1cb1401825458913b9d7fb6..af77232c908e7fbac84b12e0a9fa1e69145e3897 --- a/interfaces/innerkits/native_c/wifi_linked_info.h +++ b/wifi/interfaces/kits/c/wifi_linked_info.h @@ -1,79 +1,79 @@ -/* - * Copyright (c) 2020 Huawei Device Co., Ltd. - * 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. - */ - -/** - * @addtogroup wifiservice - * @{ - * - * @brief Provides functions for the Wi-Fi station and hotspot modes. - * - * You can use this module to enable and disable the Wi-Fi station or hotspot mode, connect to and disconnect from a - * station or hotspot, query the station or hotspot status, and listen for events. \n - * - * @since 7 - */ - -/** - * @file wifi_linked_info.h - * - * @brief Defines the data structure and macro of the Wi-Fi connection information. - * - * @since 7 - */ - -#ifndef HARMONY_OS_LITE_WIFI_LINKED_INFO_H -#define HARMONY_OS_LITE_WIFI_LINKED_INFO_H -#include "wifi_device_config.h" - -/** - * @brief Enumerates Wi-Fi connection states. - * - * @since 7 - */ -typedef enum { - /** Disconnected */ - WIFI_DISCONNECTED, - /** Connected */ - WIFI_CONNECTED -} WifiConnState; - -/** - * @brief Represents the Wi-Fi connection information. - * - * This refers to the information about the hotspot connected to this station. The information is obtained using - * {@link GetLinkedInfo}. - * - * @since 7 - */ -typedef struct { - /** Service set ID (SSID). For its length, see {@link WIFI_MAX_SSID_LEN}. */ - char ssid[WIFI_MAX_SSID_LEN]; - /** Basic service set ID (BSSID). For its length, see {@link WIFI_MAC_LEN}. */ - unsigned char bssid[WIFI_MAC_LEN]; - /** Received signal strength indicator (RSSI) */ - int rssi; - /** Wi-Fi band information of hotspot */ - int band; - /** Wi-Fi frequency information of hotspot */ - int frequency; - /** Wi-Fi connection state, which is defined in {@link WifiConnState} */ - WifiConnState connState; - /** Reason for Wi-Fi disconnection */ - unsigned short disconnectedReason; - /** IP address of the connected hotspot */ - unsigned int ipAddress; -} WifiLinkedInfo; -#endif // HARMONY_OS_LITE_WIFI_LINKED_INFO_H -/** @} */ +/* + * Copyright (c) 2020 Huawei Device Co., Ltd. + * 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. + */ + +/** + * @addtogroup wifiservice + * @{ + * + * @brief Provides functions for the Wi-Fi station and hotspot modes. + * + * You can use this module to enable and disable the Wi-Fi station or hotspot mode, connect to and disconnect from a + * station or hotspot, query the station or hotspot status, and listen for events. \n + * + * @since 7 + */ + +/** + * @file wifi_linked_info.h + * + * @brief Defines the data structure and macro of the Wi-Fi connection information. + * + * @since 7 + */ + +#ifndef WIFI_LITE_WIFI_LINKED_INFO_H +#define WIFI_LITE_WIFI_LINKED_INFO_H +#include "wifi_device_config.h" + +/** + * @brief Enumerates Wi-Fi connection states. + * + * @since 7 + */ +typedef enum { + /** Disconnected */ + WIFI_DISCONNECTED, + /** Connected */ + WIFI_CONNECTED +} WifiConnState; + +/** + * @brief Represents the Wi-Fi connection information. + * + * This refers to the information about the hotspot connected to this station. The information is obtained using + * {@link GetLinkedInfo}. + * + * @since 7 + */ +typedef struct { + /** Service set ID (SSID). For its length, see {@link WIFI_MAX_SSID_LEN}. */ + char ssid[WIFI_MAX_SSID_LEN]; + /** Basic service set ID (BSSID). For its length, see {@link WIFI_MAC_LEN}. */ + unsigned char bssid[WIFI_MAC_LEN]; + /** Received signal strength indicator (RSSI) */ + int rssi; + /** Wi-Fi band information of hotspot */ + int band; + /** Wi-Fi frequency information of hotspot */ + int frequency; + /** Wi-Fi connection state, which is defined in {@link WifiConnState} */ + WifiConnState connState; + /** Reason for Wi-Fi disconnection */ + unsigned short disconnectedReason; + /** IP address of the connected hotspot */ + unsigned int ipAddress; +} WifiLinkedInfo; +#endif // WIFI_LITE_WIFI_LINKED_INFO_H +/** @} */ diff --git a/wifi/interfaces/kits/c/wifi_p2p.h b/wifi/interfaces/kits/c/wifi_p2p.h new file mode 100644 index 0000000000000000000000000000000000000000..bbea11f3682e3c45b2904385104edb307f8fdba6 --- /dev/null +++ b/wifi/interfaces/kits/c/wifi_p2p.h @@ -0,0 +1,214 @@ +/* + * Copyright (C) 2022 Huawei Device Co., Ltd. + * 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 OHOS_C_P2P_H +#define OHOS_C_P2P_H + +#include "wifi_error_code.h" +#include "wifi_p2p_config.h" + +#ifdef __cplusplus +extern "C" { +#endif + +typedef void (*P2pStateChangedCallback)(P2pState state); +typedef void (*P2pPersistentGroupsChangedCallback)(void); +typedef void (*P2pConnectionChangedCallback)(const WifiP2pLinkedInfo info); +typedef void (*P2pPeersChangedCallback)(WifiP2pDevice* devices, int len); + +/** + * @Description Enabling the P2P Mode. + * + * @return WifiErrorCode - operation result + */ +WifiErrorCode EnableP2p(); + +/** + * @Description Disable the P2P mode. + * + * @return WifiErrorCode - operation result + */ +WifiErrorCode DisableP2p(); + +/** + * @Description Get p2p enable status + * + * @param state - enable status + * @return WifiErrorCode - operation result + */ +WifiErrorCode GetP2pEnableStatus(P2pState* state); + +/** + * @Description Start Wi-Fi P2P device search. + * + * @return WifiErrorCode - operation result + */ +WifiErrorCode DiscoverDevices(); + +/** + * @Description Stop Wi-Fi P2P device search. + * + * @return WifiErrorCode - operation result + */ +WifiErrorCode StopDiscoverDevices(); + +/** + * @Description Start the search for the Wi-Fi P2P service. + * + * @return WifiErrorCode - operation result + */ +WifiErrorCode DiscoverServices(); + +/** + * @Description Stop the search for the Wi-Fi P2P service. + * + * @return WifiErrorCode - operation result + */ +WifiErrorCode StopDiscoverServices(); + +/** + * @Description Enable Wi-Fi P2P listening. + * + * @param period - period + * @param interval - interval + * @return WifiErrorCode - operation result + */ +WifiErrorCode StartP2pListen(int period, int interval); + +/** + * @Description Disable Wi-Fi P2P listening. + * + * @return ErrCode - operation result + */ +WifiErrorCode StopP2pListen(); + +/** + * @Description Creating a P2P Group. + * + * @param config - WifiP2pConfig object + * @return WifiErrorCode - operation result + */ +WifiErrorCode CreateGroup(const WifiP2pConfig* config); + +/** + * @Description Remove a P2P Group. + * + * @return WifiErrorCode - operation result + */ +WifiErrorCode RemoveGroup(); + +/** + * @Description Delete a p2p Group. + * + * @param group - WifiP2pGroupInfo object + * @return ErrCode - operation result + */ +WifiErrorCode DeleteGroup(const WifiP2pGroupInfo* group); + +/** + * @Description P2P connection. + * + * @param config - WifiP2pConfig object + * @return WifiErrorCode - operation result + */ +WifiErrorCode P2pConnect(const WifiP2pConfig* config); + +/** + * @Description Cancel a P2P connection. + * + * @return WifiErrorCode - operation result + */ +WifiErrorCode P2pCancelConnect(); + +/** + * @Description Get the Current Group object. + * + * @param groupInfo - the WifiP2pGroupInfo object + * @return WifiErrorCode - operation result + */ +WifiErrorCode GetCurrentGroup(WifiP2pGroupInfo* groupInfo); + +/** + * @Description Obtains the P2P connection status. + * + * @param status - the P2P connection status + * @return WifiErrorCode - operation result + */ +WifiErrorCode GetP2pConnectedStatus(int* status); + +/** + * @Description Query the information about the found devices. + * + * @param clientDevices - pre-allocate memory for client devices + * @param size - the allocate size for clientDevices + * @param retSize - the queryed size of the client devices, used for return. + * @return WifiErrorCode - operation result + */ +WifiErrorCode QueryP2pDevices(WifiP2pDevice* clientDevices, int size, int* retSize); + +/** + * @Description Query the information about the local device info. + * + * @param deviceInfo - the WifiP2pDevice object + * @return ErrCode - operation result + */ +WifiErrorCode QueryP2pLocalDevice(WifiP2pDevice* deviceInfo); + +/** + * @Description Query the information about the found groups. + * + * @param groupInfo - pre-allocate memory for group size + * @param size - the allocate size for groupInfo + * @return ErrCode - operation result + */ +WifiErrorCode QueryP2pGroups(WifiP2pGroupInfo* groupInfo, int size); + +/** + * @Description register p2p state changed event + * + * @param callback - callback function + * @return ErrCode - operation result + */ +WifiErrorCode RegisterP2pStateChangedCallback(const P2pStateChangedCallback callback); + +/** + * @Description register p2p persistent group change event + * + * @param callback - callback function + * @return ErrCode - operation result + */ +WifiErrorCode RegisterP2pPersistentGroupsChangedCallback(const P2pPersistentGroupsChangedCallback callback); + +/** + * @Description register p2p connection change event + * + * @param callback - callback function + * @return ErrCode - operation result + */ +WifiErrorCode RegisterP2pConnectionChangedCallback(const P2pConnectionChangedCallback callback); + +/** + * @Description register p2p peers change event + * + * @param callback - callback function + * @return ErrCode - operation result + */ +WifiErrorCode RegisterP2pPeersChangedCallback(const P2pPeersChangedCallback callback); + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/wifi/interfaces/kits/c/wifi_p2p_config.h b/wifi/interfaces/kits/c/wifi_p2p_config.h new file mode 100644 index 0000000000000000000000000000000000000000..6dd5991778d47b6f31b37e59cdd1182e1f34c2dd --- /dev/null +++ b/wifi/interfaces/kits/c/wifi_p2p_config.h @@ -0,0 +1,122 @@ +/* + * Copyright (C) 2022 Huawei Device Co., Ltd. + * 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 OHOS_C_P2P_CONFIG_H +#define OHOS_C_P2P_CONFIG_H + +#ifdef __cplusplus +extern "C" { +#endif + +#ifndef COMMON_MAC_LEN +#define COMMON_MAC_LEN 6 +#endif + +#define PASSPHRASE_LENGTH 64 +#define P2P_NAME_LENGTH 33 +#define INTERFACE_LENGTH 16 +#define DEVICE_TYPE_LENGTH 128 +#define MAX_DEVICES_NUM 256 +#define IP_ADDR_STR_LEN 16 + +typedef enum GroupOwnerBand { + GO_BAND_AUTO, + GO_BAND_2GHZ, + GO_BAND_5GHZ +} GroupOwnerBand; + +typedef struct WifiP2pConfig { + unsigned char devAddr[COMMON_MAC_LEN]; /* the device MAC address */ + GroupOwnerBand goBand; + int netId; /* network id, when -2 means persistent and -1 means temporary, else need >= 0 */ + char passphrase[PASSPHRASE_LENGTH]; /* the value ranges from 8 to 63. */ + int groupOwnerIntent; /* the value is -1.(A value of -1 indicates the system can choose an appropriate value.) */ + char groupName[P2P_NAME_LENGTH]; /* the value ranges from 1 to 32. */ +} WifiP2pConfig; + +typedef enum P2pGroupStatus { + GS_CREATING, + GS_CREATED, + GS_STARTED, + GS_REMOVING, + GS_INVALID +} P2pGroupStatus; + +typedef enum P2pDeviceStatus { + PDS_CONNECTED, + PDS_INVITED, + PDS_FAILED, + PDS_AVAILABLE, + PDS_UNAVAILABLE +} P2pDeviceStatus; + +typedef enum P2pState { + P2P_STATE_NONE = 0, + P2P_STATE_IDLE, + P2P_STATE_STARTING, + P2P_STATE_STARTED, + P2P_STATE_CLOSING, + P2P_STATE_CLOSED, +} P2pState; + +typedef enum P2pConnectionState { + P2P_DISCONNECTED = 0, + P2P_CONNECTED, +} P2pConnectionState; + +typedef struct WifiP2pWfdInfo { + int wfdEnabled; /* 0: false, 1: true */ + int deviceInfo; + int ctrlPort; + int maxThroughput; +} WifiP2pWfdInfo; + +typedef struct WifiP2pDevice { + char deviceName[P2P_NAME_LENGTH]; /* the value range is 0 to 32 characters. */ + unsigned char devAddr[COMMON_MAC_LEN]; /* the device MAC address */ + char primaryDeviceType[DEVICE_TYPE_LENGTH]; + char secondaryDeviceType[DEVICE_TYPE_LENGTH]; + P2pDeviceStatus status; + WifiP2pWfdInfo wfdInfo; + unsigned int supportWpsConfigMethods; + int deviceCapabilitys; + int groupCapabilitys; +} WifiP2pDevice; + +typedef struct WifiP2pGroupInfo { + WifiP2pDevice owner; + int isP2pGroupOwner; /* 0: false, 1: true */ + char passphrase[PASSPHRASE_LENGTH]; /* the value ranges from 8 to 63. */ + char interface[INTERFACE_LENGTH]; + char groupName[P2P_NAME_LENGTH]; + int networkId; + int frequency; /* for example : freq=2412 to select 2.4 GHz channel 1.(Based on 2.4 GHz or 5 GHz) */ + int isP2pPersistent; /* 0: false, 1: true */ + P2pGroupStatus groupStatus; + WifiP2pDevice clientDevices[MAX_DEVICES_NUM]; + int clientDevicesSize; /* the true size of clientDevices array */ + char goIpAddress[IP_ADDR_STR_LEN]; +} WifiP2pGroupInfo; + +typedef struct WifiP2pLinkedInfo { + P2pConnectionState connectState; + int isP2pGroupOwner; + unsigned char groupOwnerAddress[COMMON_MAC_LEN]; +} WifiP2pLinkedInfo; +#ifdef __cplusplus +} +#endif + +#endif diff --git a/interfaces/innerkits/native_c/wifi_scan_info.h b/wifi/interfaces/kits/c/wifi_scan_info.h old mode 100755 new mode 100644 similarity index 79% rename from interfaces/innerkits/native_c/wifi_scan_info.h rename to wifi/interfaces/kits/c/wifi_scan_info.h index c7fededc91265f46c5591bdcd8524ad969bdf060..04af5c3306f5575323ab08b212f2621b295a030a --- a/interfaces/innerkits/native_c/wifi_scan_info.h +++ b/wifi/interfaces/kits/c/wifi_scan_info.h @@ -1,67 +1,85 @@ -/* - * Copyright (c) 2020 Huawei Device Co., Ltd. - * 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. - */ - -/** - * @addtogroup wifiservice - * @{ - * - * @brief Provides functions for the Wi-Fi station and hotspot modes. - * - * You can use this module to enable and disable the Wi-Fi station or hotspot mode, connect to and disconnect from a - * station or hotspot, query the station or hotspot status, and listen for events. \n - * - * @since 7 - */ - -/** - * @file wifi_scan_info.h - * - * @brief Defines the data structure and macro of the Wi-Fi scan result information. - * - * @since 7 - */ - -#ifndef WIFI_SCAN_INFO_C_H -#define WIFI_SCAN_INFO_C_H - -#include "wifi_device_config.h" - -/** - * @brief Indicates the maximum number of hotspots that can be detected in a Wi-Fi scan. - */ -#define WIFI_SCAN_HOTSPOT_LIMIT 64 - -/** - * @brief Represents the Wi-Fi scan result information. - * - * @since 7 - */ -typedef struct { - /** Service set ID (SSID). For its length, see {@link WIFI_MAX_SSID_LEN}. */ - char ssid[WIFI_MAX_SSID_LEN]; - /** Basic service set ID (BSSID). For its length, see {@link WIFI_MAC_LEN}. */ - unsigned char bssid[WIFI_MAC_LEN]; - /** Security type. For details, see {@link WifiSecurityType}. */ - int securityType; - /** Received signal strength indicator (RSSI) */ - int rssi; - /** Frequency band */ - int band; - /** Frequency in MHz */ - int frequency; -} WifiScanInfo; - -#endif // WIFI_SCAN_INFO_C_H -/** @} */ +/* + * Copyright (c) 2020 Huawei Device Co., Ltd. + * 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. + */ + +/** + * @addtogroup wifiservice + * @{ + * + * @brief Provides functions for the Wi-Fi station and hotspot modes. + * + * You can use this module to enable and disable the Wi-Fi station or hotspot mode, connect to and disconnect from a + * station or hotspot, query the station or hotspot status, and listen for events. \n + * + * @since 7 + */ + +/** + * @file wifi_scan_info.h + * + * @brief Defines the data structure and macro of the Wi-Fi scan result information. + * + * @since 7 + */ + +#ifndef WIFI_SCAN_INFO_C_H +#define WIFI_SCAN_INFO_C_H + +#include +#include "wifi_device_config.h" + +/** + * @brief Indicates the maximum number of hotspots that can be detected in a Wi-Fi scan. + */ +#define WIFI_SCAN_HOTSPOT_LIMIT 128 + +typedef enum { + WIDTH_20MHZ = 0, + WIDTH_40MHZ = 1, + WIDTH_80MHZ = 2, + WIDTH_160MHZ = 3, + WIDTH_80MHZ_PLUS = 4, + WIDTH_INVALID +} WifiChannelWidth; + +/** + * @brief Represents the Wi-Fi scan result information. + * + * @since 7 + */ +typedef struct { + /** Service set ID (SSID). For its length, see {@link WIFI_MAX_SSID_LEN}. */ + char ssid[WIFI_MAX_SSID_LEN]; + /** Basic service set ID (BSSID). For its length, see {@link WIFI_MAC_LEN}. */ + unsigned char bssid[WIFI_MAC_LEN]; + /** Security type. For details, see {@link WifiSecurityType}. */ + int securityType; + /** Received signal strength indicator (RSSI) */ + int rssi; + /** Frequency band */ + int band; + /** Frequency in MHz */ + int frequency; + /** Wifi channel width. For details, see {@link WifiChannelWidth}. */ + WifiChannelWidth channelWidth; + /** Center frequency in MHz */ + int centerFrequency0; + /** Center frequency in MHz */ + int centerFrequency1; + /** Time stamp */ + int64_t timestamp; +} WifiScanInfo; + +#endif // WIFI_SCAN_INFO_C_H +/** @} */ diff --git a/services/wifi_standard/etc/init/BUILD.gn b/wifi/services/wifi_standard/etc/init/BUILD.gn old mode 100755 new mode 100644 similarity index 72% rename from services/wifi_standard/etc/init/BUILD.gn rename to wifi/services/wifi_standard/etc/init/BUILD.gn index 5ea04da825a0371c6a677041985072da5f95b5e2..7fb5b20fe121ac1d9c7527d679e93929b29746f6 --- a/services/wifi_standard/etc/init/BUILD.gn +++ b/wifi/services/wifi_standard/etc/init/BUILD.gn @@ -1,4 +1,4 @@ -# Copyright (C) 2021 Huawei Device Co., Ltd. +# Copyright (C) 2022 Huawei Device Co., Ltd. # 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 @@ -14,18 +14,12 @@ import("//build/ohos.gni") group("etc") { - deps = [ - ":wifi_standard.rc" - ] + deps = [ ":wifi_standard.cfg" ] } -ohos_prebuilt_etc("wifi_standard.rc") { - if (use_musl) { - source = "wifi_standard.cfg" - } else { - source = "wifi_standard.rc" - } +ohos_prebuilt_etc("wifi_standard.cfg") { + source = "wifi_standard.cfg" relative_install_dir = "init" - part_name = "wifi_standard" + part_name = "wifi" subsystem_name = "communication" -} \ No newline at end of file +} diff --git a/services/wifi_standard/etc/init/wifi_standard.cfg b/wifi/services/wifi_standard/etc/init/wifi_standard.cfg old mode 100755 new mode 100644 similarity index 36% rename from services/wifi_standard/etc/init/wifi_standard.cfg rename to wifi/services/wifi_standard/etc/init/wifi_standard.cfg index 8f38a71bd4e42bfcec92a6479e08690605ed4506..031a792b79ab55e4c066cf01d799a780dc34f374 --- a/services/wifi_standard/etc/init/wifi_standard.cfg +++ b/wifi/services/wifi_standard/etc/init/wifi_standard.cfg @@ -1,17 +1,21 @@ { "jobs" : [{ - "name" : "post-fs-data", + "name" : "services:wifi_manager_service", "cmds" : [ - "mkdir /data/dhcp", - "start wifi_manager_service" + "mkdir /data/service/el1/public/dhcp 0770 dhcp dhcp" ] } ], "services" : [{ "name" : "wifi_manager_service", "path" : ["/system/bin/sa_main", "/system/profile/wifi_manager_service.xml"], - "uid" : "root", - "gid" : ["root", "shell"] + "uid" : "wifi", + "gid" : ["wifi", "shell", "dhcp"], + "caps" : ["CAP_NET_ADMIN", "CAP_NET_BIND_SERVICE", "CAP_NET_RAW"], + "jobs" : { + "on-start" : "services:wifi_manager_service" + }, + "secon" : "u:r:wifi_manager_service:s0" } ] } diff --git a/wifi/services/wifi_standard/include/wifi_common_def.h b/wifi/services/wifi_standard/include/wifi_common_def.h new file mode 100644 index 0000000000000000000000000000000000000000..5418b32c4fbe348dcfe4ccfb34283e0ed5debbf2 --- /dev/null +++ b/wifi/services/wifi_standard/include/wifi_common_def.h @@ -0,0 +1,29 @@ +/* + * Copyright (C) 2022 Huawei Device Co., Ltd. + * 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 OHOS_WIFI_COMMON_DEF_H +#define OHOS_WIFI_COMMON_DEF_H + +#ifdef __cplusplus +extern "C" { +#endif + +#define CONFIG_ROOR_DIR "/data/service/el1/public/wifi" + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/wifi/services/wifi_standard/ipc_framework/cRPC/BUILD.gn b/wifi/services/wifi_standard/ipc_framework/cRPC/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..3d8c68e4bb00b2ee939a4818f824b2f15f1a3df6 --- /dev/null +++ b/wifi/services/wifi_standard/ipc_framework/cRPC/BUILD.gn @@ -0,0 +1,114 @@ +# Copyright (C) 2021-2022 Huawei Device Co., Ltd. +# 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. + +crpc_server_sources = [ + "./src/context.c", + "./src/evloop.c", + "./src/hash_table.c", + "./src/net.c", + "./src/serial.c", + "./src/server.c", +] + +crpc_client_sources = [ + "./src/client.c", + "./src/context.c", + "./src/net.c", + "./src/serial.c", +] + +if (defined(ohos_lite)) { + import("//build/lite/config/component/lite_component.gni") + import("//foundation/communication/wifi/wifi/wifi_lite.gni") + + static_library("crpc_server") { + sources = crpc_server_sources + + include_dirs = [ + "include", + "//base/hiviewdfx/hilog_lite/interfaces/native/innerkits", + "//third_party/bounds_checking_function/include", + ] + + deps = [ + "//base/hiviewdfx/hilog_lite/frameworks/featured:hilog_shared", + "//third_party/bounds_checking_function:libsec_shared", + ] + cflags_c = [ + "-fPIC", + "-std=c99", + ] + defines = [ "OHOS_ARCH_LITE" ] + } + + static_library("crpc_client") { + sources = crpc_client_sources + include_dirs = [ + "include", + "$WIFI_ROOT_DIR/services/wifi_standard/wifi_framework/wifi_toolkit/log", + "//base/hiviewdfx/hilog_lite/interfaces/native/innerkits", + "//third_party/bounds_checking_function/include", + ] + + deps = [ + "//base/hiviewdfx/hilog_lite/frameworks/featured:hilog_shared", + "//third_party/bounds_checking_function:libsec_shared", + ] + configs -= [ "//build/lite/config:language_c" ] + cflags_c = [ + "-fPIC", + "-std=c99", + ] + defines = [ "OHOS_ARCH_LITE" ] + } +} else { + import("//build/ohos.gni") + import("//foundation/communication/wifi/wifi/wifi.gni") + + ohos_static_library("crpc_server") { + sources = crpc_server_sources + + include_dirs = [ + "include", + "//commonlibrary/c_utils/base/include", + "//base/hiviewdfx/hilog/interfaces/native/innerkits/include", + ] + cflags_cc = [ "-fno-rtti" ] + deps = [ "//base/hiviewdfx/hilog/interfaces/native/innerkits:libhilog" ] + external_deps = [ "c_utils:utils" ] + subsystem_name = "communication" + part_name = "wifi" + } + + ohos_static_library("crpc_client") { + sources = crpc_client_sources + include_dirs = [ + "include", + "//commonlibrary/c_utils/base/include", + "//base/hiviewdfx/hilog/interfaces/native/innerkits/include", + "$WIFI_ROOT_DIR/services/wifi_standard/wifi_framework/wifi_toolkit/log", + ] + cflags_cc = [ "-fno-rtti" ] + deps = [ "//base/hiviewdfx/hilog/interfaces/native/innerkits:libhilog" ] + external_deps = [ "c_utils:utils" ] + subsystem_name = "communication" + part_name = "wifi" + } +} + +group("ipc_framework") { + deps = [ + ":crpc_client", + ":crpc_server", + ] +} diff --git a/services/wifi_standard/ipc_framework/cRPC/include/client.h b/wifi/services/wifi_standard/ipc_framework/cRPC/include/client.h similarity index 97% rename from services/wifi_standard/ipc_framework/cRPC/include/client.h rename to wifi/services/wifi_standard/ipc_framework/cRPC/include/client.h index 0cf65971938a82a0d586d0d165a82ffabff7a7d2..ff7d86c41fc010afbb45bde5b2f630b3d44e841c 100644 --- a/services/wifi_standard/ipc_framework/cRPC/include/client.h +++ b/wifi/services/wifi_standard/ipc_framework/cRPC/include/client.h @@ -1,5 +1,5 @@ /* - * Copyright (C) 2021 Huawei Device Co., Ltd. + * Copyright (C) 2021-2022 Huawei Device Co., Ltd. * 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 @@ -16,8 +16,8 @@ #ifndef CRPC_CLIENT_H #define CRPC_CLIENT_H +#include #include "context.h" -#include "net.h" #ifdef __cplusplus extern "C" { @@ -105,4 +105,4 @@ int OnTransact(Context *context); #ifdef __cplusplus } #endif -#endif \ No newline at end of file +#endif diff --git a/services/wifi_standard/ipc_framework/cRPC/include/common.h b/wifi/services/wifi_standard/ipc_framework/cRPC/include/common.h similarity index 100% rename from services/wifi_standard/ipc_framework/cRPC/include/common.h rename to wifi/services/wifi_standard/ipc_framework/cRPC/include/common.h diff --git a/services/wifi_standard/ipc_framework/cRPC/include/context.h b/wifi/services/wifi_standard/ipc_framework/cRPC/include/context.h similarity index 97% rename from services/wifi_standard/ipc_framework/cRPC/include/context.h rename to wifi/services/wifi_standard/ipc_framework/cRPC/include/context.h index 9e5ec1310ab35f7851aac36fbc25e7f23e507481..1407c06008eb659fb81088dc25971074ef5dbd88 100644 --- a/services/wifi_standard/ipc_framework/cRPC/include/context.h +++ b/wifi/services/wifi_standard/ipc_framework/cRPC/include/context.h @@ -1,5 +1,5 @@ /* - * Copyright (C) 2021 Huawei Device Co., Ltd. + * Copyright (C) 2021-2022 Huawei Device Co., Ltd. * 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 @@ -16,9 +16,6 @@ #ifndef CRPC_CONTEXT_H #define CRPC_CONTEXT_H -#include "common.h" -#include "net.h" - #ifdef __cplusplus extern "C" { #endif @@ -98,4 +95,4 @@ char *ContextGetReadRecord(Context *context); #ifdef __cplusplus } #endif -#endif \ No newline at end of file +#endif diff --git a/services/wifi_standard/ipc_framework/cRPC/include/evloop.h b/wifi/services/wifi_standard/ipc_framework/cRPC/include/evloop.h similarity index 96% rename from services/wifi_standard/ipc_framework/cRPC/include/evloop.h rename to wifi/services/wifi_standard/ipc_framework/cRPC/include/evloop.h index 0e60caba60e1ad0b3ff749e43d76ab8cf28c8f57..a32959683f598e62d3ac22c701d3ae393f9540c5 100644 --- a/services/wifi_standard/ipc_framework/cRPC/include/evloop.h +++ b/wifi/services/wifi_standard/ipc_framework/cRPC/include/evloop.h @@ -1,5 +1,5 @@ /* - * Copyright (C) 2021 Huawei Device Co., Ltd. + * Copyright (C) 2021-2022 Huawei Device Co., Ltd. * 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 @@ -16,8 +16,6 @@ #ifndef CRPC_EVENT_LOOP_H #define CRPC_EVENT_LOOP_H -#include "common.h" - #ifdef __cplusplus extern "C" { #endif @@ -83,4 +81,4 @@ int DelFdEvent(EventLoop *loop, int fd, unsigned int delMask); #ifdef __cplusplus } #endif -#endif \ No newline at end of file +#endif diff --git a/services/wifi_standard/ipc_framework/cRPC/include/hash_table.h b/wifi/services/wifi_standard/ipc_framework/cRPC/include/hash_table.h similarity index 96% rename from services/wifi_standard/ipc_framework/cRPC/include/hash_table.h rename to wifi/services/wifi_standard/ipc_framework/cRPC/include/hash_table.h index e52536534a837f031f40c5d82cdddf9a9f0c29d3..f0a079e38803cae949b17d668afdf5f45d00badf 100644 --- a/services/wifi_standard/ipc_framework/cRPC/include/hash_table.h +++ b/wifi/services/wifi_standard/ipc_framework/cRPC/include/hash_table.h @@ -1,5 +1,5 @@ /* - * Copyright (C) 2021 Huawei Device Co., Ltd. + * Copyright (C) 2021-2022 Huawei Device Co., Ltd. * 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 @@ -16,7 +16,6 @@ #ifndef CRPC_HASH_TABLE_H #define CRPC_HASH_TABLE_H -#include "common.h" #include "context.h" #ifdef __cplusplus @@ -97,4 +96,4 @@ void DeleteHashTable(HashTable *p, const Context *context); #ifdef __cplusplus } #endif -#endif \ No newline at end of file +#endif diff --git a/services/wifi_standard/ipc_framework/cRPC/include/log.h b/wifi/services/wifi_standard/ipc_framework/cRPC/include/log.h similarity index 91% rename from services/wifi_standard/ipc_framework/cRPC/include/log.h rename to wifi/services/wifi_standard/ipc_framework/cRPC/include/log.h index 8d22ad43f9d45558e288933b4350424d2e89ced0..fc0bef5279822fc9b76a41f06fece5799e771ab0 100644 --- a/services/wifi_standard/ipc_framework/cRPC/include/log.h +++ b/wifi/services/wifi_standard/ipc_framework/cRPC/include/log.h @@ -1,5 +1,5 @@ /* - * Copyright (C) 2021 Huawei Device Co., Ltd. + * Copyright (C) 2021-2022 Huawei Device Co., Ltd. * 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 @@ -16,7 +16,11 @@ #ifndef CPRC_WIFI_LOG_H #define CPRC_WIFI_LOG_H +#ifdef OHOS_ARCH_LITE +#include "hilog/log.h" +#else #include "hilog/log_c.h" +#endif #undef LOG_TAG #define LOG_TAG "WifiCrpc" diff --git a/services/wifi_standard/ipc_framework/cRPC/include/net.h b/wifi/services/wifi_standard/ipc_framework/cRPC/include/net.h similarity index 96% rename from services/wifi_standard/ipc_framework/cRPC/include/net.h rename to wifi/services/wifi_standard/ipc_framework/cRPC/include/net.h index 1cf69659a459f4571ddc3acc33aeb3e991513aa0..243ab6b73c49835de4afa9d6cb0cfd1be9c4dabc 100644 --- a/services/wifi_standard/ipc_framework/cRPC/include/net.h +++ b/wifi/services/wifi_standard/ipc_framework/cRPC/include/net.h @@ -1,5 +1,5 @@ /* - * Copyright (C) 2021 Huawei Device Co., Ltd. + * Copyright (C) 2021-2022 Huawei Device Co., Ltd. * 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 @@ -16,8 +16,6 @@ #ifndef CRPC_NET_H #define CRPC_NET_H -#include "common.h" - #ifdef __cplusplus extern "C" { #endif @@ -81,4 +79,4 @@ int WaitFdEvent(int fd, unsigned int mask, int milliseconds); #ifdef __cplusplus } #endif -#endif \ No newline at end of file +#endif diff --git a/services/wifi_standard/ipc_framework/cRPC/include/serial.h b/wifi/services/wifi_standard/ipc_framework/cRPC/include/serial.h similarity index 98% rename from services/wifi_standard/ipc_framework/cRPC/include/serial.h rename to wifi/services/wifi_standard/ipc_framework/cRPC/include/serial.h index 6ae2ce66fd75bfd1e1ef94dc1d1b9e53c9fd80ea..fb725f0c3f570177f01d0bc8f1bb9e734dbc2934 100644 --- a/services/wifi_standard/ipc_framework/cRPC/include/serial.h +++ b/wifi/services/wifi_standard/ipc_framework/cRPC/include/serial.h @@ -1,5 +1,5 @@ /* - * Copyright (C) 2021 Huawei Device Co., Ltd. + * Copyright (C) 2021-2022 Huawei Device Co., Ltd. * 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 @@ -17,7 +17,6 @@ #define CRPC_SERIAL_H #include -#include "common.h" #include "context.h" #ifdef __cplusplus @@ -192,4 +191,4 @@ int ReadUStr(Context *context, unsigned char *uStr, int count); #ifdef __cplusplus } #endif -#endif \ No newline at end of file +#endif diff --git a/services/wifi_standard/ipc_framework/cRPC/include/server.h b/wifi/services/wifi_standard/ipc_framework/cRPC/include/server.h similarity index 96% rename from services/wifi_standard/ipc_framework/cRPC/include/server.h rename to wifi/services/wifi_standard/ipc_framework/cRPC/include/server.h index c47f4dedeb4b6a040c6d509f62645ed7f71421a9..273cbbe20ad46a89779b5ee099c6a0a267b80505 100644 --- a/services/wifi_standard/ipc_framework/cRPC/include/server.h +++ b/wifi/services/wifi_standard/ipc_framework/cRPC/include/server.h @@ -1,5 +1,5 @@ /* - * Copyright (C) 2021 Huawei Device Co., Ltd. + * Copyright (C) 2021-2022 Huawei Device Co., Ltd. * 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 @@ -15,12 +15,10 @@ #ifndef CRPC_SERVER_H #define CRPC_SERVER_H -#include "common.h" +#include #include "context.h" #include "evloop.h" #include "hash_table.h" -#include "net.h" -#include "serial.h" #ifdef __cplusplus extern "C" { @@ -134,4 +132,4 @@ int EndCallbackTransact(const RpcServer *server, int event); #ifdef __cplusplus } #endif -#endif \ No newline at end of file +#endif diff --git a/services/wifi_standard/ipc_framework/cRPC/src/client.c b/wifi/services/wifi_standard/ipc_framework/cRPC/src/client.c similarity index 95% rename from services/wifi_standard/ipc_framework/cRPC/src/client.c rename to wifi/services/wifi_standard/ipc_framework/cRPC/src/client.c index d89b6e3d6b1c75e8bac6ea6edc3b19bdd6748a94..7a7cf62bc646db92c6251159c9b47fe2eacc9367 100644 --- a/services/wifi_standard/ipc_framework/cRPC/src/client.c +++ b/wifi/services/wifi_standard/ipc_framework/cRPC/src/client.c @@ -1,5 +1,5 @@ /* - * Copyright (C) 2021 Huawei Device Co., Ltd. + * Copyright (C) 2021-2022 Huawei Device Co., Ltd. * 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 @@ -12,10 +12,18 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + #include "client.h" +#include +#include #include -#include +#include +#include +#include +#include +#include "common.h" #include "log.h" +#include "net.h" #undef LOG_TAG #define LOG_TAG "WifiRpcClient" @@ -24,7 +32,8 @@ const int FD_CHECK_TIMEOUT = 1000; /* poll wait time, units: ms */ const int CLIENT_STATE_IDLE = 0; const int CLIENT_STATE_DEAL_REPLY = 1; const int CLIENT_STATE_EXIT = 2; -const int TMP_BUFF_SIZE = 16; + +#define TMP_BUFF_SIZE 16 static void *RpcClientThreadDeal(void *arg); @@ -55,6 +64,7 @@ static char *RpcClientReadMsg(RpcClient *client) if (!client->threadRunFlag) { if (buff != NULL) { free(buff); + buff = NULL; } return NULL; } @@ -90,6 +100,7 @@ static void RpcClientDealReadMsg(RpcClient *client, char *buff) client->context->nSize = strlen(buff); OnTransact(client->context); free(buff); + buff = NULL; } return; } @@ -132,6 +143,7 @@ RpcClient *CreateRpcClient(const char *path) if (client->context == NULL) { close(fd); free(client); + client = NULL; return NULL; } client->context->fd = fd; @@ -152,6 +164,7 @@ RpcClient *CreateRpcClient(const char *path) ReleaseContext(client->context); close(fd); free(client); + client = NULL; return NULL; } signal(SIGPIPE, SIG_IGN); @@ -172,6 +185,7 @@ void ReleaseRpcClient(RpcClient *client) close(client->context->fd); ReleaseContext(client->context); free(client); + client = NULL; } return; } diff --git a/services/wifi_standard/ipc_framework/cRPC/src/context.c b/wifi/services/wifi_standard/ipc_framework/cRPC/src/context.c similarity index 94% rename from services/wifi_standard/ipc_framework/cRPC/src/context.c rename to wifi/services/wifi_standard/ipc_framework/cRPC/src/context.c index 35e3b2f62e317b9248511a57c4c2178381db7a62..dcac478544a7a215faf1711ddb44e808923b2083 100644 --- a/services/wifi_standard/ipc_framework/cRPC/src/context.c +++ b/wifi/services/wifi_standard/ipc_framework/cRPC/src/context.c @@ -1,5 +1,5 @@ /* - * Copyright (C) 2021 Huawei Device Co., Ltd. + * Copyright (C) 2021-2022 Huawei Device Co., Ltd. * 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 @@ -14,6 +14,12 @@ */ #include "context.h" +#include +#include +#include +#include +#include "common.h" +#include "net.h" Context *CreateContext(int capacity) { @@ -31,15 +37,17 @@ Context *CreateContext(int capacity) context->szRead = (char *)calloc(capacity, sizeof(char)); if (context->szRead == NULL) { free(context); + context = NULL; return NULL; } context->szWrite = (char *)calloc(capacity, sizeof(char)); if (context->szWrite == NULL) { free(context->szRead); free(context); + context = NULL; return NULL; } - context->cSplit = '|'; + context->cSplit = '\t'; context->cMsgEnd = "$$$$$$"; return context; } @@ -54,6 +62,7 @@ void ReleaseContext(Context *context) free(context->szRead); free(context->szWrite); free(context); + context = NULL; } } @@ -81,11 +90,13 @@ static int ExpandReadCache(Context *context, int len) } if (memmove_s(p, capacity, context->szRead, context->rCapacity) != EOK) { free(p); + p = NULL; return -1; } if (context->rBegin > context->rEnd && memmove_s(p + context->rCapacity, context->rCapacity, p, context->rEnd) != EOK) { free(p); + p = NULL; return -1; } char *pFree = context->szRead; @@ -95,6 +106,7 @@ static int ExpandReadCache(Context *context, int len) } context->rCapacity = capacity; free(pFree); + pFree = NULL; } return 0; } @@ -118,15 +130,19 @@ static int ExpandWriteCache(Context *context, int len) return -1; } if (context->wCapacity < 0) { + free(p); + p = NULL; return -1; } if (memmove_s(p, capacity, context->szWrite, context->wCapacity) != EOK) { free(p); + p = NULL; return -1; } if (context->wBegin > context->wEnd && memmove_s(p + context->wCapacity, context->wCapacity, p, context->wEnd) != EOK) { free(p); + p = NULL; return -1; } char *pFree = context->szWrite; @@ -136,6 +152,7 @@ static int ExpandWriteCache(Context *context, int len) } context->wCapacity = capacity; free(pFree); + pFree = NULL; } return 0; } diff --git a/services/wifi_standard/ipc_framework/cRPC/src/evloop.c b/wifi/services/wifi_standard/ipc_framework/cRPC/src/evloop.c similarity index 95% rename from services/wifi_standard/ipc_framework/cRPC/src/evloop.c rename to wifi/services/wifi_standard/ipc_framework/cRPC/src/evloop.c index b32619484b82234c9b64633bda84748208a51439..6cf12a61803bd69a26175feb25f9f846d9bf1bd2 100644 --- a/services/wifi_standard/ipc_framework/cRPC/src/evloop.c +++ b/wifi/services/wifi_standard/ipc_framework/cRPC/src/evloop.c @@ -1,5 +1,5 @@ /* - * Copyright (C) 2021 Huawei Device Co., Ltd. + * Copyright (C) 2021-2022 Huawei Device Co., Ltd. * 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 @@ -14,6 +14,10 @@ */ #include "evloop.h" +#include +#include +#include +#include "common.h" #include "log.h" #undef LOG_TAG @@ -36,6 +40,7 @@ EventLoop *CreateEventLoop(int size) evLoop->epfd = -1; if (size <= 0) { free(evLoop); + evLoop = NULL; return NULL; } evLoop->fdMasks = (FdMask *)calloc(size, sizeof(FdMask)); @@ -62,6 +67,7 @@ EventLoop *CreateEventLoop(int size) free(evLoop->epEvents); } free(evLoop); + evLoop = NULL; return NULL; } @@ -81,6 +87,7 @@ void DestroyEventLoop(EventLoop *loop) free(loop->epEvents); } free(loop); + loop = NULL; return; } diff --git a/services/wifi_standard/ipc_framework/cRPC/src/hash_table.c b/wifi/services/wifi_standard/ipc_framework/cRPC/src/hash_table.c similarity index 96% rename from services/wifi_standard/ipc_framework/cRPC/src/hash_table.c rename to wifi/services/wifi_standard/ipc_framework/cRPC/src/hash_table.c index 20db5486918574f58ef1de939e91e80350a27cc1..e7014d919c296fca2898d14a2f33c17660c7c9aa 100644 --- a/services/wifi_standard/ipc_framework/cRPC/src/hash_table.c +++ b/wifi/services/wifi_standard/ipc_framework/cRPC/src/hash_table.c @@ -1,5 +1,5 @@ /* - * Copyright (C) 2021 Huawei Device Co., Ltd. + * Copyright (C) 2021-2022 Huawei Device Co., Ltd. * 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 @@ -14,6 +14,8 @@ */ #include "hash_table.h" +#include +#include "common.h" #include "log.h" #undef LOG_TAG @@ -79,6 +81,7 @@ void DestroyHashTable(HashTable *p) } free(p->list); free(p); + p = NULL; } static int RebuildHashTable(HashTable *p) @@ -88,6 +91,9 @@ static int RebuildHashTable(HashTable *p) } int slot = (p->slots << 1); /* double size */ slot = CalcNextPrime(slot); + if (slot <= 0) { + return -1; + } ListNode **new_list = (ListNode **)calloc(slot, sizeof(ListNode *)); if (new_list == NULL) { LOGE("rebuild hash table calloc failed!"); @@ -185,6 +191,7 @@ void DeleteHashTable(HashTable *p, const Context *context) q->next = t->next; } free(t); + t = NULL; p->size -= 1; } return; diff --git a/services/wifi_standard/ipc_framework/cRPC/src/net.c b/wifi/services/wifi_standard/ipc_framework/cRPC/src/net.c similarity index 95% rename from services/wifi_standard/ipc_framework/cRPC/src/net.c rename to wifi/services/wifi_standard/ipc_framework/cRPC/src/net.c index 1e059f69d238052f3e0718fc5aa3d8c0cd1fe6e0..99f86d9f29543297f01891b2f78a75da6eb24935 100644 --- a/services/wifi_standard/ipc_framework/cRPC/src/net.c +++ b/wifi/services/wifi_standard/ipc_framework/cRPC/src/net.c @@ -1,5 +1,5 @@ /* - * Copyright (C) 2021 Huawei Device Co., Ltd. + * Copyright (C) 2021-2022 Huawei Device Co., Ltd. * 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 @@ -12,8 +12,18 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + #include "net.h" +#include +#include +#include +#include +#include +#include +#include "common.h" +#include "errno.h" #include "log.h" + #undef LOG_TAG #define LOG_TAG "WifiRpcNet" @@ -86,6 +96,7 @@ int MyWrite(int fd, const char *buf, int count) LOGD("write: %{private}s", szTmp); } free(szTmp); + szTmp = NULL; } #endif pos += ret; diff --git a/services/wifi_standard/ipc_framework/cRPC/src/serial.c b/wifi/services/wifi_standard/ipc_framework/cRPC/src/serial.c similarity index 95% rename from services/wifi_standard/ipc_framework/cRPC/src/serial.c rename to wifi/services/wifi_standard/ipc_framework/cRPC/src/serial.c index ed45314a921e744610ef2a4a21dd8758e8c30bb3..923b50e67a33225c4974d3bc83656a651e397630 100644 --- a/services/wifi_standard/ipc_framework/cRPC/src/serial.c +++ b/wifi/services/wifi_standard/ipc_framework/cRPC/src/serial.c @@ -1,5 +1,5 @@ /* - * Copyright (C) 2021 Huawei Device Co., Ltd. + * Copyright (C) 2021-2022 Huawei Device Co., Ltd. * 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 @@ -12,10 +12,16 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -#include + #include "serial.h" +#include +#include +#include +#include +#include "common.h" + +#define TMP_CHAR_LEN 64 -const int TMP_CHAR_LEN = 64; const int HIGH_TWO_BIT = 16; const int ALPHA_NUM_MAX = 10; @@ -49,10 +55,12 @@ int WriteFunc(Context *context, const char *funcName) } if (snprintf_s(buf, len + 1, len, "%s%c", funcName, context->cSplit) < 0) { free(buf); + buf = NULL; return -1; } int ret = ContextAppendWrite(context, buf, len); free(buf); + buf = NULL; return ret; } @@ -137,10 +145,12 @@ int WriteStr(Context *context, const char *pStr) } if (snprintf_s(buf, len + 1, len, "%s%c", pStr, context->cSplit) < 0) { free(buf); + buf = NULL; return -1; } int ret = ContextAppendWrite(context, buf, len); free(buf); + buf = NULL; return ret; } @@ -160,6 +170,7 @@ int WriteUStr(Context *context, const unsigned char *uStr, unsigned int len) pos = (i << 1); if (snprintf_s(buf + pos, inLen - pos, inLen - pos - 1, "%02x", uStr[i]) < 0) { free(buf); + buf = NULL; return -1; } } @@ -167,6 +178,7 @@ int WriteUStr(Context *context, const unsigned char *uStr, unsigned int len) buf[inLen] = 0; int ret = ContextAppendWrite(context, buf, inLen); free(buf); + buf = NULL; return ret; } @@ -275,7 +287,7 @@ int ReadInt(Context *context, int *iData) int ReadLong(Context *context, long *pLong) { - if (context == NULL) { + if (context == NULL || pLong == NULL) { return -1; } @@ -307,7 +319,7 @@ int ReadInt64(Context *context, int64_t *pInt64) int ReadDouble(Context *context, double *dData) { - if (context == NULL) { + if (context == NULL || dData == NULL) { return -1; } @@ -361,7 +373,7 @@ int ReadStr(Context *context, char *str, int count) int ReadUStr(Context *context, unsigned char *uStr, int count) { - if (context == NULL) { + if (context == NULL || uStr == NULL) { return -1; } diff --git a/services/wifi_standard/ipc_framework/cRPC/src/server.c b/wifi/services/wifi_standard/ipc_framework/cRPC/src/server.c similarity index 96% rename from services/wifi_standard/ipc_framework/cRPC/src/server.c rename to wifi/services/wifi_standard/ipc_framework/cRPC/src/server.c index c30e29d64471540ff68288e54a359f02a63609cb..f9e3555da8d7d78f5ede5e98b338707cfb5fee09 100644 --- a/services/wifi_standard/ipc_framework/cRPC/src/server.c +++ b/wifi/services/wifi_standard/ipc_framework/cRPC/src/server.c @@ -1,5 +1,5 @@ /* - * Copyright (C) 2021 Huawei Device Co., Ltd. + * Copyright (C) 2021-2022 Huawei Device Co., Ltd. * 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 @@ -12,8 +12,18 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + #include "server.h" +#include +#include +#include +#include +#include +#include +#include +#include "common.h" #include "log.h" +#include "net.h" #undef LOG_TAG #define LOG_TAG "WifiRpcServer" @@ -105,6 +115,7 @@ static int DealReadMessage(RpcServer *server, Context *client) client->nSize = strlen(buf); OnTransact(server, client); free(buf); + buf = NULL; AddFdEvent(server->loop, client->fd, WRIT_EVENT); return 1; } @@ -199,7 +210,7 @@ int RunRpcLoop(RpcServer *server) EventLoop *loop = server->loop; while (!loop->stop) { BeforeLoop(server); - int retval = epoll_wait(loop->epfd, loop->epEvents, loop->setSize, 1); /* wait 1ms */ + int retval = epoll_wait(loop->epfd, loop->epEvents, loop->setSize, 5); for (int i = 0; i < retval; ++i) { struct epoll_event *e = loop->epEvents + i; int fd = e->data.fd; @@ -228,6 +239,7 @@ void ReleaseRpcServer(RpcServer *server) } pthread_mutex_destroy(&server->mutex); free(server); + server = NULL; } } @@ -318,6 +330,7 @@ int UnRegisterCallback(RpcServer *server, int event, const Context *context) q->next = p->next; } free(p); + p = NULL; } return 0; } @@ -346,6 +359,7 @@ static int RemoveCallback(RpcServer *server, const Context *context) q->next = p->next; } free(p); + p = NULL; } } return 0; diff --git a/services/wifi_standard/sa_profile/1125.xml b/wifi/services/wifi_standard/sa_profile/1120.xml similarity index 94% rename from services/wifi_standard/sa_profile/1125.xml rename to wifi/services/wifi_standard/sa_profile/1120.xml index 5f57921eff71a8b38eb371d04860c3342d6352cb..e682deb6f76bf5050d4eda44a348efbd54c7cacb 100644 --- a/services/wifi_standard/sa_profile/1125.xml +++ b/wifi/services/wifi_standard/sa_profile/1120.xml @@ -1,6 +1,6 @@ - 1125 + 1120 libwifi_device_ability.z.so diff --git a/services/wifi_standard/sa_profile/1127.xml b/wifi/services/wifi_standard/sa_profile/1121.xml similarity index 96% rename from services/wifi_standard/sa_profile/1127.xml rename to wifi/services/wifi_standard/sa_profile/1121.xml index 4ab0910319f9d7780ae60299442037526bb99ac3..df798c75a731e65487ac188e0008116209f2bc9c 100644 --- a/services/wifi_standard/sa_profile/1127.xml +++ b/wifi/services/wifi_standard/sa_profile/1121.xml @@ -16,7 +16,7 @@ wifi_manager_service - 1127 + 1121 libwifi_hotspot_ability.z.so diff --git a/services/wifi_standard/sa_profile/1128.xml b/wifi/services/wifi_standard/sa_profile/1123.xml similarity index 96% rename from services/wifi_standard/sa_profile/1128.xml rename to wifi/services/wifi_standard/sa_profile/1123.xml index 1441306fe043199ecff361d6e20322f1d5953735..d73a5b2d2fdea7b72a0bbcb976ae2253b946c9dc 100644 --- a/services/wifi_standard/sa_profile/1128.xml +++ b/wifi/services/wifi_standard/sa_profile/1123.xml @@ -16,7 +16,7 @@ wifi_manager_service - 1128 + 1123 libwifi_p2p_ability.z.so diff --git a/services/wifi_standard/sa_profile/1126.xml b/wifi/services/wifi_standard/sa_profile/1124.xml similarity index 96% rename from services/wifi_standard/sa_profile/1126.xml rename to wifi/services/wifi_standard/sa_profile/1124.xml index b32b6a3d1bc7a68bd520a847cfec09cb7b27d885..eb2f218d0c6d45a6eee34ab37ffdbbbbe659a220 100644 --- a/services/wifi_standard/sa_profile/1126.xml +++ b/wifi/services/wifi_standard/sa_profile/1124.xml @@ -16,7 +16,7 @@ wifi_manager_service - 1126 + 1124 libwifi_scan_ability.z.so diff --git a/services/wifi_standard/sa_profile/BUILD.gn b/wifi/services/wifi_standard/sa_profile/BUILD.gn similarity index 82% rename from services/wifi_standard/sa_profile/BUILD.gn rename to wifi/services/wifi_standard/sa_profile/BUILD.gn index 3fdebc476fcaf23f2d052c4ce053a52e23fb92f0..35c2b0cd6978821565c2a45e85d8676507ea4cb4 100644 --- a/services/wifi_standard/sa_profile/BUILD.gn +++ b/wifi/services/wifi_standard/sa_profile/BUILD.gn @@ -1,4 +1,4 @@ -# Copyright (C) 2021 Huawei Device Co., Ltd. +# Copyright (C) 2021-2022 Huawei Device Co., Ltd. # 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 @@ -15,10 +15,10 @@ import("//build/ohos/sa_profile/sa_profile.gni") ohos_sa_profile("wifi_standard_sa_profile") { sources = [ - "1125.xml", - "1126.xml", - "1127.xml", - "1128.xml", + "1120.xml", + "1121.xml", + "1123.xml", + "1124.xml", ] - part_name = "wifi_standard" + part_name = "wifi" } diff --git a/wifi/services/wifi_standard/wifi_framework/BUILD.gn b/wifi/services/wifi_standard/wifi_framework/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..811308785a250dc939c662bd109c7841c1028e88 --- /dev/null +++ b/wifi/services/wifi_standard/wifi_framework/BUILD.gn @@ -0,0 +1,57 @@ +# Copyright (C) 2021-2022 Huawei Device Co., Ltd. +# 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. + +if (defined(ohos_lite)) { + import("//build/lite/config/component/lite_component.gni") + import("//foundation/communication/wifi/wifi/wifi_lite.gni") +} else { + import("//build/ohos.gni") + import("//foundation/communication/wifi/wifi/wifi.gni") +} + +group("wifi_system_ability") { + if (defined(ohos_lite)) { + deps = [ "$WIFI_ROOT_DIR/services/wifi_standard/wifi_framework/wifi_manage:wifi_service_base" ] + } else { + deps = [ + "$WIFI_ROOT_DIR/services/wifi_standard/sa_profile:wifi_standard_sa_profile", + "$WIFI_ROOT_DIR/services/wifi_standard/wifi_framework/wifi_manage:wifi_device_ability", + "$WIFI_ROOT_DIR/services/wifi_standard/wifi_framework/wifi_manage:wifi_scan_ability", + ] + if (wifi_feature_with_ap_num > 0) { + deps += [ "$WIFI_ROOT_DIR/services/wifi_standard/wifi_framework/wifi_manage:wifi_hotspot_ability" ] + } + if (wifi_feature_with_p2p) { + deps += [ "$WIFI_ROOT_DIR/services/wifi_standard/wifi_framework/wifi_manage:wifi_p2p_ability" ] + } + } +} + +group("wifi_manage") { + deps = [ + "$WIFI_ROOT_DIR/services/wifi_standard/wifi_framework/wifi_manage:wifi_manager_service", + "$WIFI_ROOT_DIR/services/wifi_standard/wifi_framework/wifi_manage/idl_client:wifi_idl_client", + "$WIFI_ROOT_DIR/services/wifi_standard/wifi_framework/wifi_manage/wifi_scan:wifi_scan_service", + "$WIFI_ROOT_DIR/services/wifi_standard/wifi_framework/wifi_manage/wifi_sta:wifi_sta_service", + "$WIFI_ROOT_DIR/services/wifi_standard/wifi_framework/wifi_toolkit:wifi_toolkit", + ] + if (!defined(ohos_lite)) { + deps += [ + "$WIFI_ROOT_DIR/services/wifi_standard/wifi_framework/wifi_manage/wifi_ap:wifi_ap_service", + "$WIFI_ROOT_DIR/services/wifi_standard/wifi_framework/wifi_manage/wifi_common:wifi_common_service", + ] + if (wifi_feature_with_p2p) { + deps += [ "$WIFI_ROOT_DIR/services/wifi_standard/wifi_framework/wifi_manage/wifi_p2p:wifi_p2p_service" ] + } + } +} diff --git a/wifi/services/wifi_standard/wifi_framework/wifi_manage/BUILD.gn b/wifi/services/wifi_standard/wifi_framework/wifi_manage/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..a6288b76cf5349e55993b61494f08efbbf0563c3 --- /dev/null +++ b/wifi/services/wifi_standard/wifi_framework/wifi_manage/BUILD.gn @@ -0,0 +1,429 @@ +# Copyright (C) 2021-2022 Huawei Device Co., Ltd. +# 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. + +if (defined(ohos_lite)) { + import("//build/lite/config/component/lite_component.gni") + import("//foundation/communication/wifi/wifi/wifi_lite.gni") +} else { + import("//build/ohos.gni") + import("//build/ohos/sa_profile/sa_profile.gni") + import("//build/ohos_var.gni") + import("//foundation/communication/wifi/wifi/wifi.gni") +} + +################################################################################ + +if (defined(ohos_lite)) { + shared_library("wifi_service_base") { + sources = [ + "$WIFI_ROOT_DIR/services/wifi_standard/wifi_framework/wifi_manage/common/wifi_permission_helper.cpp", + "$WIFI_ROOT_DIR/services/wifi_standard/wifi_framework/wifi_manage/common/wifi_permission_utils.cpp", + "wifi_auth_center.cpp", + "wifi_config_center.cpp", + "wifi_device_callback_proxy_lite.cpp", + "wifi_device_service_impl.cpp", + "wifi_device_stub_lite.cpp", + "wifi_dumper.cpp", + "wifi_internal_event_dispatcher_lite.cpp", + "wifi_manager.cpp", + "wifi_protect.cpp", + "wifi_protect_manager.cpp", + "wifi_scan_callback_proxy_lite.cpp", + "wifi_scan_service_impl.cpp", + "wifi_scan_stub_lite.cpp", + "wifi_service_manager.cpp", + ] + + include_dirs = [ + "$WIFI_ROOT_DIR/frameworks/native/include", + "$WIFI_ROOT_DIR/frameworks/native/interfaces", + "$WIFI_ROOT_DIR/services/wifi_standard/ipc_framework/cRPC/include", + "$WIFI_ROOT_DIR/services/wifi_standard/wifi_framework/wifi_toolkit/include", + "$WIFI_ROOT_DIR/services/wifi_standard/wifi_framework/wifi_toolkit/log", + "$WIFI_ROOT_DIR/services/wifi_standard/wifi_framework/wifi_toolkit/net_helper", + "$WIFI_ROOT_DIR/services/wifi_standard/wifi_framework/wifi_toolkit/utils", + "$WIFI_ROOT_DIR/services/wifi_standard/wifi_framework/wifi_toolkit/config", + "$WIFI_ROOT_DIR/services/wifi_standard/wifi_framework/wifi_manage", + "$WIFI_ROOT_DIR/services/wifi_standard/wifi_framework/wifi_manage/common", + "$WIFI_ROOT_DIR/services/wifi_standard/wifi_framework/wifi_manage/idl_client", + "$WIFI_ROOT_DIR/services/wifi_standard/wifi_framework/wifi_manage/idl_client/idl_interface", + "$WIFI_ROOT_DIR/services/wifi_standard/wifi_framework/wifi_manage/wifi_sta", + "$WIFI_ROOT_DIR/services/wifi_standard/wifi_framework/wifi_manage/wifi_scan", + "$DHCP_ROOT_DIR/services/mgr_service/include", + "$DHCP_ROOT_DIR/interfaces/inner_api/include", + "$DHCP_ROOT_DIR/interfaces/inner_api/interfaces", + "$WIFI_ROOT_DIR/utils/inc", + "//base/hiviewdfx/hilog_lite/interfaces/native/innerkits", + "//foundation/communication/ipc/interfaces/innerkits/c/ipc/include", + "//foundation/systemabilitymgr/samgr_lite/interfaces/innerkits/registry", + "//foundation/systemabilitymgr/samgr_lite/interfaces/innerkits/samgr", + "//third_party/bounds_checking_function/include", + "$WIFI_ROOT_DIR/services/wifi_standard/include", + ] + + deps = [ + "$WIFI_ROOT_DIR/services/wifi_standard/wifi_framework/wifi_manage/idl_client:wifi_idl_client", + "$WIFI_ROOT_DIR/services/wifi_standard/wifi_framework/wifi_toolkit:wifi_toolkit", + "$WIFI_ROOT_DIR/utils:wifi_utils", + "//base/hiviewdfx/hilog_lite/frameworks/featured:hilog_shared", + "//foundation/communication/ipc/interfaces/innerkits/c/ipc:ipc_single", + "//foundation/systemabilitymgr/samgr_lite/samgr:samgr", + "//third_party/bounds_checking_function:libsec_shared", + ] + + defines = [ + "OHOS_ARCH_LITE", + "AP_INSTANCE_MAX_NUM=$wifi_feature_with_ap_num", + ] + + if (wifi_feature_with_auth_disable) { + defines += [ "PERMISSION_ALWAYS_GRANT" ] + } + + cflags_cc = [ + "-std=c++17", + "-fno-rtti", + ] + } + + executable("wifi_manager_service") { + sources = [ + "wifi_device_feature_lite.cpp", + "wifi_sa_service_lite.c", + "wifi_scan_feature_lite.cpp", + "wifi_service_main_lite.c", + ] + + include_dirs = [ + "$WIFI_ROOT_DIR/frameworks/native/include", + "$WIFI_ROOT_DIR/frameworks/native/interfaces", + "$WIFI_ROOT_DIR/services/wifi_standard/ipc_framework/cRPC/include", + "$WIFI_ROOT_DIR/services/wifi_standard/wifi_framework/wifi_toolkit/include", + "$WIFI_ROOT_DIR/services/wifi_standard/wifi_framework/wifi_toolkit/log", + "$WIFI_ROOT_DIR/services/wifi_standard/wifi_framework/wifi_toolkit/net_helper", + "$WIFI_ROOT_DIR/services/wifi_standard/wifi_framework/wifi_toolkit/utils", + "$WIFI_ROOT_DIR/services/wifi_standard/wifi_framework/wifi_toolkit/config", + "$WIFI_ROOT_DIR/services/wifi_standard/wifi_framework/wifi_manage", + "$WIFI_ROOT_DIR/services/wifi_standard/wifi_framework/wifi_manage/common", + "$WIFI_ROOT_DIR/services/wifi_standard/wifi_framework/wifi_manage/idl_client", + "$WIFI_ROOT_DIR/services/wifi_standard/wifi_framework/wifi_manage/idl_client/idl_interface", + "$WIFI_ROOT_DIR/services/wifi_standard/wifi_framework/wifi_manage/wifi_sta", + "$WIFI_ROOT_DIR/services/wifi_standard/wifi_framework/wifi_manage/wifi_scan", + "$DHCP_ROOT_DIR/services/mgr_service/include", + "$DHCP_ROOT_DIR/interfaces/inner_api/include", + "$DHCP_ROOT_DIR/interfaces/inner_api/interfaces", + "$WIFI_ROOT_DIR/utils/inc", + "//base/hiviewdfx/hilog_lite/interfaces/native/innerkits", + "//foundation/communication/ipc/interfaces/innerkits/c/ipc/include", + "//foundation/systemabilitymgr/samgr_lite/interfaces/innerkits/registry", + "//foundation/systemabilitymgr/samgr_lite/interfaces/innerkits/samgr", + "//third_party/bounds_checking_function/include", + ] + + deps = [ + "$WIFI_ROOT_DIR/services/wifi_standard/wifi_framework/wifi_manage:wifi_service_base", + "$WIFI_ROOT_DIR/services/wifi_standard/wifi_framework/wifi_manage/idl_client:wifi_idl_client", + "$WIFI_ROOT_DIR/utils:wifi_utils", + "//base/hiviewdfx/hilog_lite/frameworks/featured:hilog_shared", + "//foundation/communication/ipc/interfaces/innerkits/c/ipc:ipc_single", + "//foundation/systemabilitymgr/samgr_lite/samgr:samgr", + "//third_party/bounds_checking_function:libsec_shared", + ] + + defines = [ "OHOS_ARCH_LITE" ] + cflags_cc = [ + "-std=c++17", + "-fno-rtti", + ] + } +} else { + config("wifi_manager_service_header") { + include_dirs = [ + "//commonlibrary/c_utils/base/include", + "//base/hiviewdfx/hilog/interfaces/native/innerkits/include", + "//base/security/huks/interfaces/innerkits/huks_standard/main/include", + "//foundation/arkui/ace_engine/frameworks/base/utils", + "//foundation/arkui/ace_engine/frameworks", + "//foundation/systemabilitymgr/safwk/interfaces/innerkits/safwk/", + "$WIFI_ROOT_DIR/frameworks/native/interfaces", + "$WIFI_ROOT_DIR/services/wifi_standard/ipc_framework/cRPC/include", + "$WIFI_ROOT_DIR/services/wifi_standard/wifi_framework/wifi_toolkit/include", + "$WIFI_ROOT_DIR/services/wifi_standard/wifi_framework/wifi_toolkit/log", + "$WIFI_ROOT_DIR/services/wifi_standard/wifi_framework/wifi_toolkit/net_helper", + "$WIFI_ROOT_DIR/services/wifi_standard/wifi_framework/wifi_toolkit/utils", + "$WIFI_ROOT_DIR/services/wifi_standard/wifi_framework/wifi_toolkit/config", + "$WIFI_ROOT_DIR/services/wifi_standard/wifi_framework/wifi_manage", + "$WIFI_ROOT_DIR/services/wifi_standard/wifi_framework/wifi_manage/common", + "$WIFI_ROOT_DIR/services/wifi_standard/wifi_framework/wifi_manage/idl_client", + "$WIFI_ROOT_DIR/services/wifi_standard/wifi_framework/wifi_manage/idl_client/idl_interface", + "$WIFI_ROOT_DIR/services/wifi_standard/wifi_framework/wifi_manage/wifi_sta", + "$WIFI_ROOT_DIR/services/wifi_standard/wifi_framework/wifi_manage/wifi_scan", + "$WIFI_ROOT_DIR/services/wifi_standard/wifi_framework/wifi_manage/wifi_ap", + "$WIFI_ROOT_DIR/services/wifi_standard/wifi_framework/wifi_manage/wifi_p2p", + "$WIFI_ROOT_DIR/services/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/hid2d", + "$DHCP_ROOT_DIR/services/mgr_service/include", + "$DHCP_ROOT_DIR/interfaces/inner_api/include", + "$DHCP_ROOT_DIR/interfaces/inner_api/interfaces", + "$WIFI_ROOT_DIR/utils/inc", + "//foundation/appexecfwk/adapter/interfaces/innerkits/appexecfwk_base/include", + "//base/security/access_token/interfaces/innerkits/accesstoken/include", + "//foundation/communication/netmanager_base/frameworks/native/netmanagernative", + "//foundation/communication/netmanager_base/interfaces/innerkits/netmanagernative/include", + "$WIFI_ROOT_DIR/services/wifi_standard/include", + ] + } + + config("wifi_manager_service_config") { + visibility = [ "//:*" ] + include_dirs = [ ":wifi_fw_common_header" ] + + cflags = [ + "-std=c++17", + "-fno-rtti", + ] + if (target_cpu == "arm") { + cflags += [ "-DBINDER_IPC_32BIT" ] + } + + if (product_name == "rk3568") { + defines = [ "NON_SEPERATE_P2P" ] + } + } + + ohos_source_set("wifi_scan_service_impl") { + part_name = "wifi" + sources = [ + "wifi_scan_callback_proxy.cpp", + "wifi_scan_death_recipient.cpp", + "wifi_scan_service_impl.cpp", + "wifi_scan_stub.cpp", + ] + configs = [ + ":wifi_manager_service_config", + ":wifi_manager_service_header", + ] + + deps = [ + "//base/hiviewdfx/hilog/interfaces/native/innerkits:libhilog", + "//foundation/systemabilitymgr/safwk/interfaces/innerkits/safwk:system_ability_fwk", + ] + + external_deps = [ + "c_utils:utils", + "ipc:ipc_core", + ] + } + ohos_source_set("wifi_device_service_impl") { + part_name = "wifi" + sources = [ + "wifi_device_callback_proxy.cpp", + "wifi_device_death_recipient.cpp", + "wifi_device_service_impl.cpp", + "wifi_device_stub.cpp", + ] + configs = [ + ":wifi_manager_service_config", + ":wifi_manager_service_header", + ] + + defines = [] + if (wifi_feature_with_ap_num > 0) { + defines += [ "FEATURE_AP_SUPPORT" ] + } + + deps = [ + "$WIFI_ROOT_DIR/services/wifi_standard/wifi_framework/wifi_toolkit:wifi_toolkit", + "$WIFI_ROOT_DIR/utils:wifi_utils", + "//base/hiviewdfx/hilog/interfaces/native/innerkits:libhilog", + "//foundation/systemabilitymgr/safwk/interfaces/innerkits/safwk:system_ability_fwk", + ] + + if (wifi_feature_with_p2p) { + defines += [ "FEATURE_P2P_SUPPORT" ] + deps += [ ":wifi_p2p_service_impl" ] + } + + if (wifi_feature_with_encryption) { + defines += [ "FEATURE_ENCRYPTION_SUPPORT" ] + } + + external_deps = [ + "ability_base:want", + "bundle_framework:appexecfwk_base", + "c_utils:utils", + "common_event_service:cesfwk_innerkits", + "ipc:ipc_core", + ] + } + ohos_source_set("wifi_hotspot_service_impl") { + part_name = "wifi" + sources = [ + "wifi_hotspot_callback_proxy.cpp", + "wifi_hotspot_death_recipient.cpp", + "wifi_hotspot_mgr_service_impl.cpp", + "wifi_hotspot_mgr_stub.cpp", + "wifi_hotspot_service_impl.cpp", + "wifi_hotspot_stub.cpp", + ] + configs = [ + ":wifi_manager_service_config", + ":wifi_manager_service_header", + ] + + deps = [ + "$WIFI_ROOT_DIR/services/wifi_standard/wifi_framework/wifi_toolkit:wifi_toolkit", + "$WIFI_ROOT_DIR/utils:wifi_utils", + "//base/hiviewdfx/hilog/interfaces/native/innerkits:libhilog", + "//foundation/systemabilitymgr/safwk/interfaces/innerkits/safwk:system_ability_fwk", + ] + + external_deps = [ + "c_utils:utils", + "ipc:ipc_core", + ] + + defines = [ + "FEATURE_AP_SUPPORT", + "AP_INSTANCE_MAX_NUM=$wifi_feature_with_ap_num", + ] + } + ohos_source_set("wifi_p2p_service_impl") { + part_name = "wifi" + sources = [ + "$WIFI_ROOT_DIR/frameworks/native/src/wifi_hid2d_msg.cpp", + "$WIFI_ROOT_DIR/frameworks/native/src/wifi_p2p_msg.cpp", + "wifi_p2p_callback_proxy.cpp", + "wifi_p2p_death_recipient.cpp", + "wifi_p2p_service_impl.cpp", + "wifi_p2p_stub.cpp", + ] + configs = [ + ":wifi_manager_service_config", + ":wifi_manager_service_header", + ] + + deps = [ + "$WIFI_ROOT_DIR/services/wifi_standard/wifi_framework/wifi_toolkit:wifi_toolkit", + "$WIFI_ROOT_DIR/utils:wifi_utils", + "//base/hiviewdfx/hilog/interfaces/native/innerkits:libhilog", + "//foundation/systemabilitymgr/safwk/interfaces/innerkits/safwk:system_ability_fwk", + ] + + external_deps = [ + "c_utils:utils", + "ipc:ipc_core", + "netmanager_base:net_conn_manager_if", + ] + defines = [ "FEATURE_P2P_SUPPORT" ] + } + + ohos_shared_library("wifi_manager_service") { + install_enable = true + sources = [ + "$WIFI_ROOT_DIR/services/wifi_standard/wifi_framework/wifi_manage/common/wifi_permission_helper.cpp", + "$WIFI_ROOT_DIR/services/wifi_standard/wifi_framework/wifi_manage/common/wifi_permission_utils.cpp", + "wifi_auth_center.cpp", + "wifi_config_center.cpp", + "wifi_dumper.cpp", + "wifi_internal_event_dispatcher.cpp", + "wifi_manager.cpp", + "wifi_net_agent.cpp", + "wifi_service_manager.cpp", + ] + + deps = [ + "$WIFI_ROOT_DIR/services/wifi_standard/etc/init:etc", + "$WIFI_ROOT_DIR/services/wifi_standard/wifi_framework/wifi_toolkit:wifi_toolkit", + "$WIFI_ROOT_DIR/utils:wifi_utils", + "//base/hiviewdfx/hilog/interfaces/native/innerkits:libhilog", + "//foundation/communication/netmanager_base/services/netmanagernative:netsys_native_manager", + "//foundation/systemabilitymgr/safwk/interfaces/innerkits/safwk:system_ability_fwk", + ] + + configs = [ ":wifi_manager_service_header" ] + + external_deps = [ + "access_token:libaccesstoken_sdk", + "c_utils:utils", + "ipc:ipc_core", + "netmanager_base:net_conn_manager_if", + "samgr:samgr_proxy", + ] + if (wifi_feature_with_encryption) { + external_deps += [ "huks:libhukssdk" ] + } + defines = [ + "FEATURE_AP_SUPPORT", + "AP_INSTANCE_MAX_NUM=$wifi_feature_with_ap_num", + ] + + if (wifi_feature_with_auth_disable) { + defines += [ "PERMISSION_ALWAYS_GRANT" ] + } + + if (wifi_feature_with_encryption) { + defines += [ "FEATURE_ENCRYPTION_SUPPORT" ] + } + + if (wifi_feature_with_p2p) { + defines += [ "FEATURE_P2P_SUPPORT" ] + } + + part_name = "wifi" + subsystem_name = "communication" + } + + ohos_shared_library("wifi_device_ability") { + install_enable = true + deps = [ + ":wifi_device_service_impl", + ":wifi_manager_service", + ] + + part_name = "wifi" + subsystem_name = "communication" + } + + ohos_shared_library("wifi_scan_ability") { + install_enable = true + deps = [ + ":wifi_manager_service", + ":wifi_scan_service_impl", + ] + + part_name = "wifi" + subsystem_name = "communication" + } + + ohos_shared_library("wifi_hotspot_ability") { + install_enable = true + deps = [ + ":wifi_hotspot_service_impl", + ":wifi_manager_service", + ] + + part_name = "wifi" + subsystem_name = "communication" + } + + ohos_shared_library("wifi_p2p_ability") { + install_enable = true + deps = [ + ":wifi_manager_service", + ":wifi_p2p_service_impl", + ] + + part_name = "wifi" + subsystem_name = "communication" + } +} diff --git a/services/wifi_standard/wifi_framework/wifi_manage/common/handler.cpp b/wifi/services/wifi_standard/wifi_framework/wifi_manage/common/handler.cpp similarity index 94% rename from services/wifi_standard/wifi_framework/wifi_manage/common/handler.cpp rename to wifi/services/wifi_standard/wifi_framework/wifi_manage/common/handler.cpp index b391be031f97bf1c67005619aabf263ed3784c6f..3cd0100d6368080ac63288bab67ab1cb7d46179a 100644 --- a/services/wifi_standard/wifi_framework/wifi_manage/common/handler.cpp +++ b/wifi/services/wifi_standard/wifi_framework/wifi_manage/common/handler.cpp @@ -46,28 +46,27 @@ bool Handler::InitialHandler() } int ret = pthread_create(&handleThread, nullptr, RunHandleThreadFunc, this); - if (ret < 0) { + if (ret != 0) { LOGE("pthread_create failed.\n"); return false; } - + LOGI("pthread_create ret: %{public}d\n", ret); return true; } void Handler::StopHandlerThread() { - LOGI("Handler::StopHandlerThread"); + LOGI("Enter StopHandlerThread"); if (isRunning) { isRunning = false; if (pMyQueue != nullptr) { pMyQueue->StopQueueLoop(); } - if (handleThread != 0) { pthread_join(handleThread, nullptr); } } - + LOGI("Leave StopHandlerThread"); return; } @@ -78,6 +77,7 @@ void *Handler::RunHandleThreadFunc(void *pInstance) return nullptr; } + LOGI("Run handler func."); Handler *pHandler = (Handler *)pInstance; pHandler->GetAndDistributeMessage(); @@ -94,10 +94,10 @@ void Handler::GetAndDistributeMessage() while (isRunning) { InternalMessage *msg = pMyQueue->GetNextMessage(); if (msg == nullptr) { - LOGE("GetNextMessage failed.\n"); + LOGE("GetNextMessage null.\n"); continue; } - + LOGI("Handler get message: %{public}d\n", msg->GetMessageName()); DistributeMessage(msg); MessageManage::GetInstance().ReclaimMsg(msg); } diff --git a/services/wifi_standard/wifi_framework/wifi_manage/common/handler.h b/wifi/services/wifi_standard/wifi_framework/wifi_manage/common/handler.h similarity index 100% rename from services/wifi_standard/wifi_framework/wifi_manage/common/handler.h rename to wifi/services/wifi_standard/wifi_framework/wifi_manage/common/handler.h diff --git a/services/wifi_standard/wifi_framework/wifi_manage/common/internal_message.cpp b/wifi/services/wifi_standard/wifi_framework/wifi_manage/common/internal_message.cpp similarity index 99% rename from services/wifi_standard/wifi_framework/wifi_manage/common/internal_message.cpp rename to wifi/services/wifi_standard/wifi_framework/wifi_manage/common/internal_message.cpp index 09f4e8362a62740484ba0e09a595b31ab68f0e3d..7d3199fc976079ddc96836eb2f9adb65c1bb85a6 100644 --- a/services/wifi_standard/wifi_framework/wifi_manage/common/internal_message.cpp +++ b/wifi/services/wifi_standard/wifi_framework/wifi_manage/common/internal_message.cpp @@ -311,6 +311,7 @@ void MessageManage::ReclaimMsg(InternalMessage *m) } delete m; + m = nullptr; return; } diff --git a/services/wifi_standard/wifi_framework/wifi_manage/common/internal_message.h b/wifi/services/wifi_standard/wifi_framework/wifi_manage/common/internal_message.h similarity index 99% rename from services/wifi_standard/wifi_framework/wifi_manage/common/internal_message.h rename to wifi/services/wifi_standard/wifi_framework/wifi_manage/common/internal_message.h index ebe7aec1993b62449b59832b628d9201f81f88e4..cacc908fc9426c056d3cd83032ac6b43a56d65db 100644 --- a/services/wifi_standard/wifi_framework/wifi_manage/common/internal_message.h +++ b/wifi/services/wifi_standard/wifi_framework/wifi_manage/common/internal_message.h @@ -119,7 +119,7 @@ public: int GetIntFromMessage(); /** - * @Description : Obtains Sting data from message. + * @Description : Obtains String data from message. * * @return std::string */ diff --git a/services/wifi_standard/wifi_framework/wifi_manage/common/message_queue.cpp b/wifi/services/wifi_standard/wifi_framework/wifi_manage/common/message_queue.cpp old mode 100755 new mode 100644 similarity index 75% rename from services/wifi_standard/wifi_framework/wifi_manage/common/message_queue.cpp rename to wifi/services/wifi_standard/wifi_framework/wifi_manage/common/message_queue.cpp index df87fc310a1b0c27f029479a80933a495adfadd7..2dd4062c460a1e32819b005c7d4f2324323bbc1c --- a/services/wifi_standard/wifi_framework/wifi_manage/common/message_queue.cpp +++ b/wifi/services/wifi_standard/wifi_framework/wifi_manage/common/message_queue.cpp @@ -1,5 +1,5 @@ /* - * Copyright (C) 2021 Huawei Device Co., Ltd. + * Copyright (C) 2021-2022 Huawei Device Co., Ltd. * 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 @@ -12,10 +12,12 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + #include "message_queue.h" +#include #include +#include #include "wifi_log.h" -#include "wifi_errcode.h" #undef LOG_TAG #define LOG_TAG "OHWIFI_MESSAGE_QUEUE" @@ -23,7 +25,9 @@ namespace OHOS { namespace Wifi { MessageQueue::MessageQueue() : pMessageQueue(nullptr), mIsBlocked(false), mNeedQuit(false) -{} +{ + LOGI("MessageQueue::MessageQueue"); +} MessageQueue::~MessageQueue() { @@ -37,25 +41,27 @@ MessageQueue::~MessageQueue() delete current; current = next; } - return; } bool MessageQueue::AddMessageToQueue(InternalMessage *message, int64_t handleTime) { if (message == nullptr) { - LOGE("message is null.\n"); + LOGE("message is null."); return false; } + LOGI("MessageQueue::AddMessageToQueue, msg: %{public}d, timestamp:%" PRIu64 "\n", + message->GetMessageName(), handleTime); + if (mNeedQuit) { MessageManage::GetInstance().ReclaimMsg(message); - LOGE("Already quit the message queue.\n"); + LOGE("Already quit the message queue."); return false; } message->SetHandleTime(handleTime); - bool needWake = false; + bool mNeedWakeup = false; /* * If the queue is empty, the current message needs to be executed * immediately, or the execution time is earlier than the queue header, the @@ -65,14 +71,16 @@ bool MessageQueue::AddMessageToQueue(InternalMessage *message, int64_t handleTim { std::unique_lock lck(mMtxQueue); InternalMessage *pTop = pMessageQueue; - if (pTop == nullptr || handleTime == 0 || handleTime < pTop->GetHandleTime()) { + if (pTop == nullptr || handleTime == 0 || handleTime <= pTop->GetHandleTime()) { + LOGI("Add the message in the head of queue."); message->SetNextMsg(pTop); pMessageQueue = message; - needWake = mIsBlocked; - /* Inserts messages in the middle of the queue based on the execution time. */ + mNeedWakeup = mIsBlocked; } else { + LOGI("Insert the message in the middle of the queue."); InternalMessage *pPrev = nullptr; InternalMessage *pCurrent = pTop; + /* Inserts messages in the middle of the queue based on the execution time. */ while (pCurrent != nullptr) { pPrev = pCurrent; pCurrent = pCurrent->GetNextMsg(); @@ -85,20 +93,20 @@ bool MessageQueue::AddMessageToQueue(InternalMessage *message, int64_t handleTim } } - /* Wake up the process. */ - if (needWake) { + LOGI("Add message needWakeup: %{public}d", static_cast(mNeedWakeup)); + if (mNeedWakeup) { std::unique_lock lck(mMtxBlock); - mCvQueue.notify_all(); mIsBlocked = false; } - + /* Wake up the process. */ + mCvQueue.notify_one(); return true; } bool MessageQueue::DeleteMessageFromQueue(int messageName) { + LOGI("MessageQueue::DeleteMessageFromQueue"); std::unique_lock lck(mMtxQueue); - InternalMessage *pTop = pMessageQueue; if (pTop == nullptr) { return true; @@ -120,7 +128,6 @@ bool MessageQueue::DeleteMessageFromQueue(int messageName) pMessageQueue = pTop->GetNextMsg(); MessageManage::GetInstance().ReclaimMsg(pTop); } - return true; } @@ -133,25 +140,27 @@ InternalMessage *MessageQueue::GetNextMessage() /* Obtains the current time, accurate to milliseconds. */ struct timeval curTime = {0, 0}; if (gettimeofday(&curTime, nullptr) != 0) { - LOGE("gettimeofday failed.\n"); + LOGE("gettimeofday failed."); return nullptr; } - int64_t nowTime = static_cast(curTime.tv_sec) * TIME_USEC_1000 + curTime.tv_usec / TIME_USEC_1000; + int64_t nowTime = static_cast(curTime.tv_sec) * TIME_USEC_1000 + curTime.tv_usec / TIME_USEC_1000; { - std::unique_lock lck(mMtxQueue); + std::unique_lock lck(mMtxQueue); // Data queue lock InternalMessage *curMsg = pMessageQueue; mIsBlocked = true; if (curMsg != nullptr) { + LOGI("Message queue is not empty."); if (nowTime < curMsg->GetHandleTime()) { /* The execution time of the first message is not reached. - The remaining time is blocked here. */ + The remaining time is blocked here. */ nextBlockTime = curMsg->GetHandleTime() - nowTime; } else { - /* Return the first message. */ + /* Get the message of queue header. */ mIsBlocked = false; pMessageQueue = curMsg->GetNextMsg(); curMsg->SetNextMsg(nullptr); + LOGI("Get queue message: %{public}d", curMsg->GetMessageName()); return curMsg; } } else { @@ -160,31 +169,31 @@ InternalMessage *MessageQueue::GetNextMessage() } } - std::unique_lock lck(mMtxBlock); + std::unique_lock lck(mMtxBlock); // mCvQueue lock if (mIsBlocked && (!mNeedQuit)) { + LOGI("mCvQueue wait_for: %{public}d", nextBlockTime); if (mCvQueue.wait_for(lck, std::chrono::milliseconds(nextBlockTime)) == std::cv_status::timeout) { - LOGD("mCvQueue timeout.\n"); + LOGI("mCvQueue wake up, reason: cv_status::timeout: %{public}d", nextBlockTime); } else { - LOGD("Wake up.\n"); + LOGI("mCvQueue is wake up."); } } mIsBlocked = false; } - - LOGE("Already quit the message queue.\n"); + LOGE("Already quit the message queue."); return nullptr; } void MessageQueue::StopQueueLoop() { + LOGI("Start stop queue loop."); mNeedQuit = true; if (mIsBlocked) { std::unique_lock lck(mMtxBlock); - mCvQueue.notify_all(); mIsBlocked = false; } - - return; + mCvQueue.notify_one(); + LOGI("Queue loop has stopped."); } } // namespace Wifi -} // namespace OHOS \ No newline at end of file +} // namespace OHOS diff --git a/services/wifi_standard/wifi_framework/wifi_manage/common/message_queue.h b/wifi/services/wifi_standard/wifi_framework/wifi_manage/common/message_queue.h similarity index 94% rename from services/wifi_standard/wifi_framework/wifi_manage/common/message_queue.h rename to wifi/services/wifi_standard/wifi_framework/wifi_manage/common/message_queue.h index a31371f4b685ea16b6ac10bc5822fba793410266..c95778941f6edb6af14e027b58680341c65e0a72 100644 --- a/services/wifi_standard/wifi_framework/wifi_manage/common/message_queue.h +++ b/wifi/services/wifi_standard/wifi_framework/wifi_manage/common/message_queue.h @@ -1,5 +1,5 @@ /* - * Copyright (C) 2021 Huawei Device Co., Ltd. + * Copyright (C) 2021-2022 Huawei Device Co., Ltd. * 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 @@ -16,6 +16,7 @@ #ifndef OHOS_MESSAGE_QUEUE_H #define OHOS_MESSAGE_QUEUE_H +#include #include #include #include @@ -73,9 +74,9 @@ private: /* Message Queuing */ InternalMessage *pMessageQueue; /* No messages to be executed, blocking */ - bool mIsBlocked; + std::atomic mIsBlocked; /* Exit Loop */ - bool mNeedQuit; + std::atomic mNeedQuit; /* Thread lock of operation queue */ std::mutex mMtxQueue; /* Blocked thread lock */ diff --git a/services/wifi_standard/wifi_framework/wifi_manage/common/state.cpp b/wifi/services/wifi_standard/wifi_framework/wifi_manage/common/state.cpp similarity index 100% rename from services/wifi_standard/wifi_framework/wifi_manage/common/state.cpp rename to wifi/services/wifi_standard/wifi_framework/wifi_manage/common/state.cpp diff --git a/services/wifi_standard/wifi_framework/wifi_manage/common/state.h b/wifi/services/wifi_standard/wifi_framework/wifi_manage/common/state.h similarity index 100% rename from services/wifi_standard/wifi_framework/wifi_manage/common/state.h rename to wifi/services/wifi_standard/wifi_framework/wifi_manage/common/state.h diff --git a/services/wifi_standard/wifi_framework/wifi_manage/common/state_machine.cpp b/wifi/services/wifi_standard/wifi_framework/wifi_manage/common/state_machine.cpp old mode 100755 new mode 100644 similarity index 95% rename from services/wifi_standard/wifi_framework/wifi_manage/common/state_machine.cpp rename to wifi/services/wifi_standard/wifi_framework/wifi_manage/common/state_machine.cpp index 0262b46ebaadd15403b13440e7ef0169320bd588..b67e6b57e1e6b7e47f33b91c190b450bf3efaf2e --- a/services/wifi_standard/wifi_framework/wifi_manage/common/state_machine.cpp +++ b/wifi/services/wifi_standard/wifi_framework/wifi_manage/common/state_machine.cpp @@ -1,5 +1,5 @@ /* - * Copyright (C) 2021 Huawei Device Co., Ltd. + * Copyright (C) 2021-2022 Huawei Device Co., Ltd. * 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 @@ -12,7 +12,8 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -#include + +#include #include "state_machine.h" #include "wifi_log.h" @@ -30,11 +31,13 @@ StateMachine::~StateMachine() LOGD("StateMachine::~StateMachine"); if (pStateMachineHandler != nullptr) { delete pStateMachineHandler; + pStateMachineHandler = nullptr; } } bool StateMachine::InitialStateMachine() { + LOGI("InitialStateMachine\n"); pStateMachineHandler = new (std::nothrow) StateMachineHandler(this); if (pStateMachineHandler == nullptr) { LOGE("pStateMachineHandler alloc failed.\n"); @@ -129,7 +132,6 @@ void StateMachine::StopHandlerThread() LOGE("Start StateMachine failed, pStateMachineHandler is nullptr!"); return; } - pStateMachineHandler->StopHandlerThread(); } @@ -280,7 +282,7 @@ StateMachineHandler::StateMachineHandler(StateMachine *pStateMgr) StateMachineHandler::~StateMachineHandler() { - LOGD("StateMachineHandler::~StateMachineHandler"); + LOGI("StateMachineHandler::~StateMachineHandler"); StopHandlerThread(); ReleaseDelayedMessages(); ClearWhenQuit(); @@ -290,6 +292,7 @@ StateMachineHandler::~StateMachineHandler() bool StateMachineHandler::InitialSmHandler() { if (!InitialHandler()) { + LOGE("InitialHandler failed."); return false; } return true; @@ -473,6 +476,7 @@ void StateMachineHandler::ReleaseDelayedMessages() InternalMessage *curMsg = mDelayedMessages[i]; if (curMsg != nullptr) { delete curMsg; + curMsg = nullptr; } } mDelayedMessages.clear(); @@ -500,6 +504,11 @@ int StateMachineHandler::MoveSequenceToStateVector() void StateMachineHandler::SwitchState(State *targetState) { + if (targetState == nullptr) { + LOGE("targetState is null."); + return; + } + LOGE("SwitchState, Switch to targetState: %{public}s.", targetState->GetStateName().c_str()); pTargetState = static_cast(targetState); } @@ -527,13 +536,15 @@ void StateMachineHandler::ClearWhenQuit() void StateMachineHandler::PerformSwitchState(State *msgProcessedState, InternalMessage *msg) { if (msgProcessedState == nullptr || msg == nullptr) { - LOGE("poniter is null."); + LOGE("pointer is null."); } State *targetState = pTargetState; if (targetState != nullptr) { - LOGD("StateMachineHandler::PerformSwitchState targetState name is: %{public}s", - targetState->GetStateName().c_str()); + if (pFirstState != nullptr) { + LOGI("StateMachineHandler::PerformSwitchState, Switch %{public}s -->> %{public}s", + pFirstState->GetStateName().c_str(), targetState->GetStateName().c_str()); + } while (true) { StateInfo *commonStateInfo = BuildSequenceStateVector(targetState); mSwitchingStateFlag = true; @@ -582,7 +593,7 @@ void StateMachineHandler::ExecuteMessage(InternalMessage *msg) if (pStateMachine != nullptr) { PerformSwitchState(msgProcessedState, msg); } else { - LOGE("poniter is null."); + LOGE("pointer is null."); } if (pStateMachine != nullptr && msg->GetMessageName() != SM_INIT_CMD) { @@ -621,6 +632,11 @@ State *StateMachineHandler::ExecuteTreeStateMsg(InternalMessage *msg) return nullptr; } + if (curStateInfo->state) { + LOGI("State machine: %{public}s execute Cmd:%{public}d", + curStateInfo->state->GetStateName().c_str(), msg->GetMessageName()); + } + while (curStateInfo->state && (!curStateInfo->state->ExecuteStateMsg(msg))) { curStateInfo = curStateInfo->upperStateInfo; @@ -666,4 +682,4 @@ void StateMachineHandler::CallTreeStateEnters(int index) mSwitchingStateFlag = false; } } // namespace Wifi -} // namespace OHOS \ No newline at end of file +} // namespace OHOS diff --git a/services/wifi_standard/wifi_framework/wifi_manage/common/state_machine.h b/wifi/services/wifi_standard/wifi_framework/wifi_manage/common/state_machine.h old mode 100755 new mode 100644 similarity index 99% rename from services/wifi_standard/wifi_framework/wifi_manage/common/state_machine.h rename to wifi/services/wifi_standard/wifi_framework/wifi_manage/common/state_machine.h index 69e90189872a7500a64b1f1df326aa6f3b6635d7..91cbd65779055260afb1acc027f5c76535a44c67 --- a/services/wifi_standard/wifi_framework/wifi_manage/common/state_machine.h +++ b/wifi/services/wifi_standard/wifi_framework/wifi_manage/common/state_machine.h @@ -455,7 +455,7 @@ private: void PerformSwitchState(State *msgProcessedState, InternalMessage *msg); /** - * @Description : Process messages. If the current state doesnot process it, + * @Description : Process messages. If the current state does not process it, * the upper state processing is called, and so on. If all upper states * are not processed, invoke the NotExecutedMessage method of the state machine. * @@ -514,4 +514,4 @@ private: }; } // namespace Wifi } // namespace OHOS -#endif \ No newline at end of file +#endif diff --git a/services/wifi_standard/wifi_framework/wifi_manage/common/wifi_broadcast_helper.cpp b/wifi/services/wifi_standard/wifi_framework/wifi_manage/common/wifi_broadcast_helper.cpp similarity index 88% rename from services/wifi_standard/wifi_framework/wifi_manage/common/wifi_broadcast_helper.cpp rename to wifi/services/wifi_standard/wifi_framework/wifi_manage/common/wifi_broadcast_helper.cpp index 67d87aa714394b774ef0c78ffced141eee861dc7..6250514f32576ff57f2dbf18bcb6ba488fe1e324 100644 --- a/services/wifi_standard/wifi_framework/wifi_manage/common/wifi_broadcast_helper.cpp +++ b/wifi/services/wifi_standard/wifi_framework/wifi_manage/common/wifi_broadcast_helper.cpp @@ -13,7 +13,7 @@ * limitations under the License. */ #include "wifi_broadcast_helper.h" -#include +#include #include #include "wifi_logger.h" @@ -33,7 +33,7 @@ void WifiBroadCastHelper::Show(const std::string &v) return; } -void WifiBroadCastHelper::Show(int v) +void WifiBroadCastHelper::Show(const int v) { WIFI_LOGI(" -i:%{public}d", v); return; @@ -54,9 +54,9 @@ void WifiBroadCastHelper::Show(const WifiP2pDevice &v) return; } -void WifiBroadCastHelper::Show(const WifiP2pInfo &v) +void WifiBroadCastHelper::Show(const WifiP2pLinkedInfo &v) { - WIFI_LOGI(" -WifiP2pInfo:"); + WIFI_LOGI(" -WifiP2pLinkedInfo:"); if (v.GetConnectState() == P2pConnectedState::P2P_CONNECTED) { WIFI_LOGI(" connectState: Connected"); @@ -118,7 +118,7 @@ void WifiBroadCastHelper::Show(const std::vector &v) return; } -void WifiBroadCastHelper::Show(const std::vector &v) +void WifiBroadCastHelper::Show(const std::vector &v) { WIFI_LOGI(" -WifiP2pDevice Vector size[%{public}zu]:", v.size()); for (auto i : v) { @@ -135,5 +135,14 @@ void WifiBroadCastHelper::Show(const std::vector &v) } return; } + +void WifiBroadCastHelper::Show(const std::map &v) +{ + WIFI_LOGI(" -str and str Map size[%{public}zu]:", v.size()); + for (auto i : v) { + WIFI_LOGI(" -key str:%{public}s, -value str:%{public}s", i.first.c_str(), i.second.c_str()); + } + return; +} } // namespace Wifi } // namespace OHOS \ No newline at end of file diff --git a/services/wifi_standard/wifi_framework/wifi_manage/common/wifi_broadcast_helper.h b/wifi/services/wifi_standard/wifi_framework/wifi_manage/common/wifi_broadcast_helper.h similarity index 89% rename from services/wifi_standard/wifi_framework/wifi_manage/common/wifi_broadcast_helper.h rename to wifi/services/wifi_standard/wifi_framework/wifi_manage/common/wifi_broadcast_helper.h index b93e6d9dd02f3b889d018afecfdfd5f3d30ba326..68eea9d5b9c52d43f5e519a3bb13c644e3ec759b 100644 --- a/services/wifi_standard/wifi_framework/wifi_manage/common/wifi_broadcast_helper.h +++ b/wifi/services/wifi_standard/wifi_framework/wifi_manage/common/wifi_broadcast_helper.h @@ -1,5 +1,5 @@ /* - * Copyright (C) 2021 Huawei Device Co., Ltd. + * Copyright (C) 2021-2022 Huawei Device Co., Ltd. * 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 @@ -16,7 +16,8 @@ #define OHOS_WIFI_BROADCAST_HELPER_H #include -#include "wifi_msg.h" +#include +#include "wifi_p2p_msg.h" namespace OHOS { namespace Wifi { @@ -29,9 +30,9 @@ public: static void Show(const std::map &v); static void Show(const int v); static void Show(const WifiP2pDevice &v); - static void Show(const WifiP2pInfo &v); + static void Show(const WifiP2pLinkedInfo &v); static void Show(const std::vector &v); - static void Show(const std::vector &v); + static void Show(const std::vector &v); static void Show(const WifiP2pServiceInfo &v); static void Show(const std::vector &v); diff --git a/services/wifi_standard/wifi_framework/wifi_manage/common/wifi_permission_helper.cpp b/wifi/services/wifi_standard/wifi_framework/wifi_manage/common/wifi_permission_helper.cpp similarity index 74% rename from services/wifi_standard/wifi_framework/wifi_manage/common/wifi_permission_helper.cpp rename to wifi/services/wifi_standard/wifi_framework/wifi_manage/common/wifi_permission_helper.cpp index 8852af29d37268f7e2aadb33f009216c6dd795cf..49d23bbb4c80efbf86b292a9129633bcd74a2bbb 100644 --- a/services/wifi_standard/wifi_framework/wifi_manage/common/wifi_permission_helper.cpp +++ b/wifi/services/wifi_standard/wifi_framework/wifi_manage/common/wifi_permission_helper.cpp @@ -1,5 +1,5 @@ /* - * Copyright (C) 2021 Huawei Device Co., Ltd. + * Copyright (C) 2021-2022 Huawei Device Co., Ltd. * 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 @@ -17,6 +17,10 @@ #include #include #include "wifi_log.h" +#ifndef OHOS_ARCH_LITE +#include "ipc_skeleton.h" +#include "accesstoken_kit.h" +#endif #undef LOG_TAG #define LOG_TAG "OHWIFI_MANAGER_PERMISSION_HELPER" @@ -30,10 +34,9 @@ static PermissionDef g_wifiPermissions[] = { {"ohos.permission.GET_WIFI_CONFIG", USER_GRANT, NOT_RESTRICTED}, {"ohos.permission.MANAGE_WIFI_CONNECTION", USER_GRANT, NOT_RESTRICTED}, {"ohos.permission.MANAGE_WIFI_HOTSPOT", USER_GRANT, NOT_RESTRICTED}, - {"ohos.permission.MANAGE_ENHANCER_WIFI", USER_GRANT, NOT_RESTRICTED}, {"ohos.permission.GET_WIFI_LOCAL_MAC", USER_GRANT, NOT_RESTRICTED}, {"ohos.permission.LOCATION", USER_GRANT, NOT_RESTRICTED}, - {"ohos.permission.GET_P2P_DEVICE_LOCATION", USER_GRANT, NOT_RESTRICTED}, + {"ohos.permission.MANAGE_WIFI_HOTSPOT_EXT", USER_GRANT, NOT_RESTRICTED}, }; static int g_wifiPermissionSize = sizeof(g_wifiPermissions) / sizeof(PermissionDef); @@ -157,7 +160,28 @@ IsGranted WifiPermissionHelper::MockVerifyPermission(const std::string &permissi int WifiPermissionHelper::VerifyPermission(const std::string &permissionName, const int &pid, const int &uid) { - return MockVerifyPermission(permissionName, pid, uid); +#ifdef OHOS_ARCH_LITE + return PERMISSION_GRANTED; +#else + auto callerToken = IPCSkeleton::GetCallingTokenID(); + auto tokenType = Security::AccessToken::AccessTokenKit::GetTokenTypeFlag(callerToken); + if (tokenType == Security::AccessToken::ATokenTypeEnum::TOKEN_NATIVE) { + return PERMISSION_GRANTED; + } + + if (tokenType == Security::AccessToken::ATokenTypeEnum::TOKEN_HAP) { + int result = Security::AccessToken::AccessTokenKit::VerifyAccessToken(callerToken, permissionName); + if (result == Security::AccessToken::PermissionState::PERMISSION_GRANTED) { + return PERMISSION_GRANTED; + } + + LOGI("callerToken=0x%{public}x has no permission_name=%{public}s", pid, permissionName.c_str()); + return PERMISSION_DENIED; + } + + LOGE("callerToken=0x%{public}x has invalid token type=%{public}d", pid, tokenType); + return PERMISSION_DENIED; +#endif } int WifiPermissionHelper::VerifySetWifiInfoPermission(const int &pid, const int &uid) @@ -185,6 +209,14 @@ int WifiPermissionHelper::VerifySetWifiConfigPermission(const int &pid, const in return PERMISSION_GRANTED; } +int WifiPermissionHelper::VerifyGetWifiConfigPermission(const int &pid, const int &uid) +{ + if (VerifyPermission("ohos.permission.GET_WIFI_CONFIG", pid, uid) == PERMISSION_DENIED) { + return PERMISSION_DENIED; + } + return PERMISSION_GRANTED; +} + int WifiPermissionHelper::VerifyGetScanInfosPermission(const int &pid, const int &uid) { if (VerifyPermission("ohos.permission.LOCATION", pid, uid) == PERMISSION_DENIED) { @@ -211,10 +243,42 @@ int WifiPermissionHelper::VerifyWifiConnectionPermission(const int &pid, const i int WifiPermissionHelper::VerifyGetWifiDirectDevicePermission(const int &pid, const int &uid) { - if (VerifyPermission("ohos.permission.GET_P2P_DEVICE_LOCATION", pid, uid) == PERMISSION_DENIED) { + if (VerifyPermission("ohos.permission.LOCATION", pid, uid) == PERMISSION_DENIED) { + return PERMISSION_DENIED; + } + return PERMISSION_GRANTED; +} + +int WifiPermissionHelper::VerifyManageWifiHotspotPermission(const int &pid, const int &uid) +{ + if (VerifyPermission("ohos.permission.MANAGE_WIFI_HOTSPOT", pid, uid) == PERMISSION_DENIED) { + return PERMISSION_DENIED; + } + return PERMISSION_GRANTED; +} + +int WifiPermissionHelper::VerifyGetWifiPeersMacPermission(const int &pid, const int &uid) +{ + if (VerifyPermission("ohos.permission.GET_WIFI_PEERS_MAC", pid, uid) == PERMISSION_DENIED) { + return PERMISSION_DENIED; + } + return PERMISSION_GRANTED; +} + +int WifiPermissionHelper::VerifyGetWifiInfoInternalPermission(const int &pid, const int &uid) +{ + if (VerifyPermission("ohos.permission.GET_WIFI_INFO_INTERNAL", pid, uid) == PERMISSION_DENIED) { + return PERMISSION_DENIED; + } + return PERMISSION_GRANTED; +} + +int WifiPermissionHelper::VerifyManageWifiHotspotExtPermission(const int &pid, const int &uid) +{ + if (VerifyPermission("ohos.permission.MANAGE_WIFI_HOTSPOT_EXT", pid, uid) == PERMISSION_DENIED) { return PERMISSION_DENIED; } return PERMISSION_GRANTED; } } // namespace Wifi -} // namespace OHOS \ No newline at end of file +} // namespace OHOS diff --git a/services/wifi_standard/wifi_framework/wifi_manage/common/wifi_permission_helper.h b/wifi/services/wifi_standard/wifi_framework/wifi_manage/common/wifi_permission_helper.h similarity index 74% rename from services/wifi_standard/wifi_framework/wifi_manage/common/wifi_permission_helper.h rename to wifi/services/wifi_standard/wifi_framework/wifi_manage/common/wifi_permission_helper.h index be4c1162b403eef23dfaba32775801be63c82ea1..bbef84a986751e57e43a43e573ab37338aa0002c 100644 --- a/services/wifi_standard/wifi_framework/wifi_manage/common/wifi_permission_helper.h +++ b/wifi/services/wifi_standard/wifi_framework/wifi_manage/common/wifi_permission_helper.h @@ -1,5 +1,5 @@ /* - * Copyright (C) 2021 Huawei Device Co., Ltd. + * Copyright (C) 2021-2022 Huawei Device Co., Ltd. * 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 @@ -125,6 +125,15 @@ public: */ static int VerifySetWifiConfigPermission(const int &pid, const int &uid); + /** + * @Description : Verify Get Wifi Config Permission. + * + * @param pid - Process ID.[in] + * @param uid - User ID.[in] + * @return int + */ + static int VerifyGetWifiConfigPermission(const int &pid, const int &uid); + /** * @Description : Verify location information about nearby P2P devices Permission. * @@ -133,6 +142,42 @@ public: * @return int */ static int VerifyGetWifiDirectDevicePermission(const int &pid, const int &uid); + + /** + * @Description : Verify manage wifi hotspot Permission. + * + * @param pid - Process ID.[in] + * @param uid - User ID.[in] + * @return int + */ + static int VerifyManageWifiHotspotPermission(const int &pid, const int &uid); + + /** + * @Description : Verify get wifi peers mac Permission. + * + * @param pid - Process ID.[in] + * @param uid - User ID.[in] + * @return int + */ + static int VerifyGetWifiPeersMacPermission(const int &pid, const int &uid); + + /** + * @Description : Verify get internal wifi info Permission. + * + * @param pid - Process ID.[in] + * @param uid - User ID.[in] + * @return int + */ + static int VerifyGetWifiInfoInternalPermission(const int &pid, const int &uid); + + /** + * @Description : Verify manage wifi hotspot extend permission. + * + * @param pid - Process ID.[in] + * @param uid - User ID.[in] + * @return int + */ + static int VerifyManageWifiHotspotExtPermission(const int &pid, const int &uid); }; } // namespace Wifi } // namespace OHOS diff --git a/services/wifi_standard/wifi_framework/wifi_manage/common/wifi_permission_utils.cpp b/wifi/services/wifi_standard/wifi_framework/wifi_manage/common/wifi_permission_utils.cpp similarity index 48% rename from services/wifi_standard/wifi_framework/wifi_manage/common/wifi_permission_utils.cpp rename to wifi/services/wifi_standard/wifi_framework/wifi_manage/common/wifi_permission_utils.cpp index e5e8bf12d3852689b0ba07e1267d579792356fe7..86ebcb30451797b32c7ce65fcdf412051335292a 100644 --- a/services/wifi_standard/wifi_framework/wifi_manage/common/wifi_permission_utils.cpp +++ b/wifi/services/wifi_standard/wifi_framework/wifi_manage/common/wifi_permission_utils.cpp @@ -1,5 +1,5 @@ /* - * Copyright (C) 2021 Huawei Device Co., Ltd. + * Copyright (C) 2021-2022 Huawei Device Co., Ltd. * 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 @@ -13,11 +13,74 @@ * limitations under the License. */ #include "wifi_permission_utils.h" +#ifndef OHOS_ARCH_LITE #include "ipc_skeleton.h" +#endif #include "wifi_auth_center.h" namespace OHOS { namespace Wifi { +#ifdef OHOS_ARCH_LITE +int WifiPermissionUtils::VerifySetWifiInfoPermission() +{ + return PERMISSION_GRANTED; +} + +int WifiPermissionUtils::VerifyGetWifiInfoPermission() +{ + return PERMISSION_GRANTED; +} + +int WifiPermissionUtils::VerifyWifiConnectionPermission() +{ + return PERMISSION_GRANTED; +} + +int WifiPermissionUtils::VerifyGetScanInfosPermission() +{ + return PERMISSION_GRANTED; +} + +int WifiPermissionUtils::VerifyGetWifiLocalMacPermission() +{ + return PERMISSION_GRANTED; +} + +int WifiPermissionUtils::VerifySetWifiConfigPermission() +{ + return PERMISSION_GRANTED; +} + +int WifiPermissionUtils::VerifyGetWifiConfigPermission() +{ + return PERMISSION_GRANTED; +} + +int WifiPermissionUtils::VerifyGetWifiDirectDevicePermission() +{ + return PERMISSION_GRANTED; +} + +int WifiPermissionUtils::VerifyManageWifiHotspotPermission() +{ + return PERMISSION_GRANTED; +} + +int WifiPermissionUtils::VerifyGetWifiPeersMacPermission() +{ + return PERMISSION_GRANTED; +} + +int WifiPermissionUtils::VerifyGetWifiInfoInternalPermission() +{ + return PERMISSION_GRANTED; +} + +int WifiPermissionUtils::VerifyManageWifiHotspotExtPermission() +{ + return PERMISSION_GRANTED; +} +#else int WifiPermissionUtils::VerifySetWifiInfoPermission() { return WifiAuthCenter::GetInstance().VerifySetWifiInfoPermission( @@ -54,10 +117,41 @@ int WifiPermissionUtils::VerifySetWifiConfigPermission() IPCSkeleton::GetCallingPid(), IPCSkeleton::GetCallingUid()); } +int WifiPermissionUtils::VerifyGetWifiConfigPermission() +{ + return WifiAuthCenter::GetInstance().VerifyGetWifiConfigPermission( + IPCSkeleton::GetCallingPid(), IPCSkeleton::GetCallingUid()); +} + int WifiPermissionUtils::VerifyGetWifiDirectDevicePermission() { return WifiAuthCenter::GetInstance().VerifyGetWifiDirectDevicePermission( IPCSkeleton::GetCallingPid(), IPCSkeleton::GetCallingUid()); } + +int WifiPermissionUtils::VerifyManageWifiHotspotPermission() +{ + return WifiAuthCenter::GetInstance().VerifyManageWifiHotspotPermission( + IPCSkeleton::GetCallingPid(), IPCSkeleton::GetCallingUid()); +} + +int WifiPermissionUtils::VerifyGetWifiPeersMacPermission() +{ + return WifiAuthCenter::GetInstance().VerifyGetWifiPeersMacPermission( + IPCSkeleton::GetCallingPid(), IPCSkeleton::GetCallingUid()); +} + +int WifiPermissionUtils::VerifyGetWifiInfoInternalPermission() +{ + return WifiAuthCenter::GetInstance().VerifyGetWifiInfoInternalPermission( + IPCSkeleton::GetCallingPid(), IPCSkeleton::GetCallingUid()); +} + +int WifiPermissionUtils::VerifyManageWifiHotspotExtPermission() +{ + return WifiAuthCenter::GetInstance().VerifyManageWifiHotspotPermission( + IPCSkeleton::GetCallingPid(), IPCSkeleton::GetCallingUid()); +} +#endif } // namespace Wifi } // namespace OHOS \ No newline at end of file diff --git a/services/wifi_standard/wifi_framework/wifi_manage/common/wifi_permission_utils.h b/wifi/services/wifi_standard/wifi_framework/wifi_manage/common/wifi_permission_utils.h similarity index 78% rename from services/wifi_standard/wifi_framework/wifi_manage/common/wifi_permission_utils.h rename to wifi/services/wifi_standard/wifi_framework/wifi_manage/common/wifi_permission_utils.h index ec7de24e03bcd90463d9d496636823e5d814a5cb..2b593acf0ae8cc896484604a9328383ef2e7a367 100644 --- a/services/wifi_standard/wifi_framework/wifi_manage/common/wifi_permission_utils.h +++ b/wifi/services/wifi_standard/wifi_framework/wifi_manage/common/wifi_permission_utils.h @@ -1,5 +1,5 @@ /* - * Copyright (C) 2021 Huawei Device Co., Ltd. + * Copyright (C) 2021-2022 Huawei Device Co., Ltd. * 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 @@ -28,7 +28,12 @@ public: static int VerifyGetScanInfosPermission(); static int VerifyGetWifiLocalMacPermission(); static int VerifySetWifiConfigPermission(); + static int VerifyGetWifiConfigPermission(); static int VerifyGetWifiDirectDevicePermission(); + static int VerifyManageWifiHotspotPermission(); + static int VerifyGetWifiPeersMacPermission(); + static int VerifyGetWifiInfoInternalPermission(); + static int VerifyManageWifiHotspotExtPermission(); }; } // namespace Wifi } // namespace OHOS diff --git a/wifi/services/wifi_standard/wifi_framework/wifi_manage/idl_client/BUILD.gn b/wifi/services/wifi_standard/wifi_framework/wifi_manage/idl_client/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..5dbcea799d45002830465709e4b385f816da95ce --- /dev/null +++ b/wifi/services/wifi_standard/wifi_framework/wifi_manage/idl_client/BUILD.gn @@ -0,0 +1,165 @@ +# Copyright (C) 2021-2022 Huawei Device Co., Ltd. +# 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. + +if (defined(ohos_lite)) { + import("//build/lite/config/component/lite_component.gni") + import("//foundation/communication/wifi/wifi/wifi_lite.gni") +} else { + import("//build/ohos.gni") + import("//foundation/communication/wifi/wifi/wifi.gni") +} + +config("wifi_fw_common_header") { + include_dirs = [ + "idl_interface", + "$WIFI_ROOT_DIR/frameworks/native/interfaces", + "$WIFI_ROOT_DIR/services/wifi_standard/sdk/include", + "$WIFI_ROOT_DIR/services/wifi_standard/ipc_framework/cRPC/include", + "$WIFI_ROOT_DIR/services/wifi_standard/wifi_framework/wifi_toolkit/include", + "$WIFI_ROOT_DIR/services/wifi_standard/wifi_framework/wifi_toolkit/net_helper", + "$WIFI_ROOT_DIR/services/wifi_standard/wifi_framework/wifi_toolkit/log", + "$WIFI_ROOT_DIR/services/wifi_standard/wifi_framework/wifi_toolkit/config", + "$WIFI_ROOT_DIR/services/wifi_standard/wifi_framework/wifi_toolkit/utils", + "$WIFI_ROOT_DIR/services/wifi_standard/ipc_framework/interface", + "$WIFI_ROOT_DIR/services/wifi_standard/wifi_framework/wifi_manage/idl_client", + "$WIFI_ROOT_DIR/services/wifi_standard/include", + ] + if (defined(ohos_lite)) { + include_dirs += [ + "//base/hiviewdfx/hilog_lite/interfaces/native/innerkits", + "//third_party/bounds_checking_function/include", + ] + } else { + include_dirs += [ + "//commonlibrary/c_utils/base/include", + "//base/hiviewdfx/hilog/interfaces/native/innerkits/include", + ] + } +} + +config("wifi_idl_cxx_config") { + visibility = [ "//:*" ] + include_dirs = [ ":wifi_fw_common_header" ] + + cflags = [ + "-std=c++17", + "-fno-rtti", + ] + + if (target_cpu == "arm") { + cflags += [ "-DBINDER_IPC_32BIT" ] + } +} + +idl_client_sources = [ + "$WIFI_ROOT_DIR/frameworks/native/src/wifi_hid2d_msg.cpp", + "$WIFI_ROOT_DIR/frameworks/native/src/wifi_msg.cpp", + "idl_interface/i_wifi.c", + "idl_interface/i_wifi_chip.c", + "idl_interface/i_wifi_hotspot_iface.c", + "idl_interface/i_wifi_iface.c", + "idl_interface/i_wifi_p2p_iface.c", + "idl_interface/i_wifi_public_func.c", + "idl_interface/i_wifi_sta_iface.c", + "idl_interface/i_wifi_supplicant_iface.c", + "wifi_ap_hal_interface.cpp", + "wifi_base_hal_interface.cpp", + "wifi_chip_hal_interface.cpp", + "wifi_idl_client.cpp", + "wifi_idl_inner_interface.cpp", + "wifi_p2p_hal_interface.cpp", + "wifi_sta_hal_interface.cpp", + "wifi_supplicant_hal_interface.cpp", +] + +if (defined(ohos_lite)) { + shared_library("wifi_idl_client") { + sources = idl_client_sources + + configs += [ + ":wifi_idl_cxx_config", + ":wifi_fw_common_header", + ] + + deps = [ + "$WIFI_ROOT_DIR/services/wifi_standard/ipc_framework/cRPC:crpc_client", + "$WIFI_ROOT_DIR/services/wifi_standard/wifi_framework/wifi_toolkit:wifi_toolkit", + "//base/hiviewdfx/hilog_lite/frameworks/featured:hilog_shared", + "//third_party/bounds_checking_function:libsec_shared", + ] + + defines = [ + "OHOS_ARCH_LITE", + "AP_INSTANCE_MAX_NUM=$wifi_feature_with_ap_num", + ] + configs -= [ + "//build/lite/config:language_cpp", + "//build/lite/config:language_c", + ] + cflags_c = [ + "-std=c99", + "-fPIC", + ] + cflags_cc = [ + "-std=c++17", + "-fno-rtti", + "-fPIC", + ] + ldflags = [ + "-fPIC", + "-Wl,-E", + ] + } +} else { + ohos_source_set("wifi_utils") { + part_name = "wifi" + sources = [] + + configs = [ + ":wifi_idl_cxx_config", + ":wifi_fw_common_header", + ] + } + + ohos_shared_library("wifi_idl_client") { + install_enable = true + sources = idl_client_sources + + defines = [ "AP_INSTANCE_MAX_NUM=$wifi_feature_with_ap_num" ] + + configs = [ ":wifi_fw_common_header" ] + + deps = [ + ":wifi_utils", + "$WIFI_ROOT_DIR/services/wifi_standard/ipc_framework/cRPC:crpc_client", + "$WIFI_ROOT_DIR/services/wifi_standard/wifi_framework/wifi_toolkit:wifi_toolkit", + ] + + external_deps = [ + "c_utils:utils", + "hiviewdfx_hilog_native:libhilog", + ] + cflags_cc = [ + "-std=c++17", + "-fno-rtti", + ] + + ldflags = [ + "-fPIC", + "-Wl,-E", + ] + + part_name = "wifi" + subsystem_name = "communication" + } +} diff --git a/services/wifi_standard/wifi_framework/wifi_manage/idl_client/idl_interface/i_wifi.c b/wifi/services/wifi_standard/wifi_framework/wifi_manage/idl_client/idl_interface/i_wifi.c similarity index 89% rename from services/wifi_standard/wifi_framework/wifi_manage/idl_client/idl_interface/i_wifi.c rename to wifi/services/wifi_standard/wifi_framework/wifi_manage/idl_client/idl_interface/i_wifi.c index 6567a789ccd68c9a121f088cf13653c742f54de6..d41cccfbcf5fea9076043ef9088735b74aaf0121 100644 --- a/services/wifi_standard/wifi_framework/wifi_manage/idl_client/idl_interface/i_wifi.c +++ b/wifi/services/wifi_standard/wifi_framework/wifi_manage/idl_client/idl_interface/i_wifi.c @@ -1,5 +1,5 @@ /* - * Copyright (C) 2021 Huawei Device Co., Ltd. + * Copyright (C) 2021-2022 Huawei Device Co., Ltd. * 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 @@ -14,20 +14,23 @@ */ #include "i_wifi.h" -#include "client.h" /* RPC client.h */ -#include "serial.h" -#include "wifi_log.h" -#include "wifi_idl_define.h" -#include "wifi_idl_inner_interface.h" +#include +#include +#include "client.h" +#include "context.h" #include "i_wifi_chip.h" #include "i_wifi_chip_event_callback.h" #include "i_wifi_event_callback.h" -#include "i_wifi_hotspot_iface.h" -#include "i_wifi_sta_iface.h" -#include "i_wifi_supplicant_iface.h" #include "i_wifi_event_p2p_callback.h" +#include "i_wifi_hotspot_iface.h" #include "i_wifi_p2p_iface.h" #include "i_wifi_public_func.h" +#include "i_wifi_sta_iface.h" +#include "i_wifi_supplicant_iface.h" +#include "serial.h" +#include "wifi_idl_define.h" +#include "wifi_idl_inner_interface.h" +#include "wifi_log.h" #undef LOG_TAG #define LOG_TAG "WifiIdlIWifi" @@ -156,6 +159,7 @@ static void IdlCbkAddRemoveIface(Context *context, int event) } if (ReadStr(context, iface, len + 1) < 0) { free(iface); + iface = NULL; return; } IWifiChipEventCallback *callback = GetWifiChipEventCallback(); @@ -167,13 +171,18 @@ static void IdlCbkAddRemoveIface(Context *context, int event) } } free(iface); + iface = NULL; return; } static void IdlCbkStaJoinLeave(Context *context) { + int id; CStationInfo info = {0}; char *reason = NULL; + if (ReadInt(context, &id) < 0) { + return; + } if (ReadInt(context, &info.type) < 0) { return; } @@ -187,17 +196,20 @@ static void IdlCbkStaJoinLeave(Context *context) } if (ReadStr(context, reason, len + 1) < 0) { free(reason); + reason = NULL; return; } if (strncpy_s(info.mac, sizeof(info.mac), reason, sizeof(info.mac) - 1) != EOK) { free(reason); + reason = NULL; return; } - IWifiApEventCallback *callback = GetWifiApEventCallback(); + IWifiApEventCallback *callback = GetWifiApEventCallback(id); if (callback != NULL && callback->onStaJoinOrLeave != NULL) { - callback->onStaJoinOrLeave(&info); + callback->onStaJoinOrLeave(&info, id); } free(reason); + reason = NULL; return; } @@ -230,11 +242,31 @@ static void IdlCbkConnectChanged(Context *context) return; } -static void IdlCbkApStateChange(int event) +static void IdlCbkBssidChanged(Context *context) +{ + char reason[WIFI_REASON_LENGTH] = {0}; + char bssid[WIFI_BSSID_LENGTH] = {0}; + if (ReadStr(context, reason, sizeof(reason)) != 0 || + ReadStr(context, bssid, sizeof(bssid)) != 0) { + LOGE("Read event info error!"); + return; + } + IWifiEventCallback *callback = GetWifiEventCallback(); + if (callback != NULL && callback->onBssidChanged != NULL) { + callback->onBssidChanged(reason, bssid); + } + return; +} + +static void IdlCbkApStateChange(Context *context, int event) { - IWifiApEventCallback *callback = GetWifiApEventCallback(); + int id = 0; + if (ReadInt(context, &id) < 0) { + return; + } + IWifiApEventCallback *callback = GetWifiApEventCallback(id); if (callback != NULL && callback->onApEnableOrDisable != NULL) { - callback->onApEnableOrDisable(event); + callback->onApEnableOrDisable(event, id); } return; } @@ -261,11 +293,18 @@ static void IdlCbkWpaEventDeal(Context *context, int event) if (event == WIFI_IDL_CBK_CMD_WPA_STATE_CHANGEM && callback->onWpaStateChanged != NULL) { callback->onWpaStateChanged(status); } + if (event == WIFI_IDL_CBK_CMD_WPS_CONNECTION_FULL && callback->onWpsConnectionFull != NULL) { + callback->onWpsConnectionFull(status); + } + if (event == WIFI_IDL_CBK_CMD_WPS_CONNECTION_REJECT && callback->onWpsConnectionReject != NULL) { + callback->onWpsConnectionReject(status); + } return; } static int IdlDealStaApEvent(Context *context, int event) { + LOGI("OnTransact deal sta/ap event: %{public}d", event); switch (event) { case WIFI_IDL_CBK_CMD_FAILURE: case WIFI_IDL_CBK_CMD_STARTED: @@ -285,14 +324,19 @@ static int IdlDealStaApEvent(Context *context, int event) case WIFI_IDL_CBK_CMD_CONNECT_CHANGED: IdlCbkConnectChanged(context); break; + case WIFI_IDL_CBK_CMD_BSSID_CHANGED: + IdlCbkBssidChanged(context); + break; case WIFI_IDL_CBK_CMD_AP_ENABLE: case WIFI_IDL_CBK_CMD_AP_DISABLE: - IdlCbkApStateChange(event); + IdlCbkApStateChange(context, event); break; case WIFI_IDL_CBK_CMD_WPA_STATE_CHANGEM: case WIFI_IDL_CBK_CMD_SSID_WRONG_KEY: case WIFI_IDL_CBK_CMD_WPS_OVERLAP: case WIFI_IDL_CBK_CMD_WPS_TIME_OUT: + case WIFI_IDL_CBK_CMD_WPS_CONNECTION_FULL: + case WIFI_IDL_CBK_CMD_WPS_CONNECTION_REJECT: IdlCbkWpaEventDeal(context, event); break; default: @@ -325,7 +369,7 @@ static void IdlCbP2pSupConnFailedEvent() static void IdlCbP2pDeviceFoundEventDeal(Context *context) { - HidlP2pDeviceInfo info; + P2pDeviceInfo info; if (memset_s(&info, sizeof(info), 0, sizeof(info)) != EOK) { return; } @@ -396,7 +440,7 @@ static void IdlCbP2pGoNegotiationFailureEvent(Context *context) static void IdlCbP2pInvitationReceivedEvent(Context *context) { - HidlP2pInvitationInfo info; + P2pInvitationInfo info; if (memset_s(&info, sizeof(info), 0, sizeof(info)) != EOK) { return; } @@ -452,7 +496,7 @@ static void IdlCbP2pGroupFormationFailureEvent(Context *context) static void IdlCbP2pGroupStartedEvent(Context *context) { - HidlP2pGroupInfo info; + P2pGroupInfo info; if (memset_s(&info, sizeof(info), 0, sizeof(info)) != EOK) { return; } @@ -583,11 +627,13 @@ static void IdlCbP2pServDiscRespEvent(Context *context) } if (ReadStr(context, (char *)tlvs, tlvsLength + 1) != 0) { free(tlvs); + tlvs = NULL; return; } if (NumStrToNumArry(tlvs, &tlvsLength) < 0) { LOGE("Failed to convert tlvs hex string to byte list."); free(tlvs); + tlvs = NULL; return; } } @@ -596,6 +642,7 @@ static void IdlCbP2pServDiscRespEvent(Context *context) callback->onServiceDiscoveryResponse(address, updataIndicator, tlvs, tlvsLength); } free(tlvs); + tlvs = NULL; return; } @@ -629,7 +676,7 @@ static void IdlCbP2pApStaConnectEvent(Context *context, int event) static void IdlCbP2pServDiscReqEvent(Context *context) { - HidlP2pServDiscReqInfo info; + P2pServDiscReqInfo info; if (memset_s(&info, sizeof(info), 0, sizeof(info)) != EOK) { return; } @@ -647,6 +694,7 @@ static void IdlCbP2pServDiscReqEvent(Context *context) if (NumStrToNumArry(info.tlvs, &info.tlvsLength) < 0) { LOGE("Failed to convert tlvs hex string to byte list."); free(info.tlvs); + info.tlvs = NULL; return; } } @@ -655,9 +703,26 @@ static void IdlCbP2pServDiscReqEvent(Context *context) callback->onP2pServDiscReq(&info); } free(info.tlvs); + info.tlvs = NULL; return; } +static void IdlCbP2pIfaceCreatedEvent(Context *context) +{ + int id; + int isGo = 0; + char ifName[WIFI_INTERFACE_NAME_SIZE] = {0}; + if (ReadInt(context, &id) < 0 || ReadInt(context, &isGo) < 0 || + ReadStr(context, ifName, sizeof(ifName)) != 0) { + LOGE("Failed to read P2pIfaceCreatedEvent id:%{public}d", id); + return; + } + IWifiEventP2pCallback *callback = GetWifiP2pEventCallback(); + if (callback != NULL && callback->onP2pIfaceCreated != NULL) { + callback->onP2pIfaceCreated(ifName, isGo); + } +} + static int IdlDealP2pEventFirst(Context *context, int event) { switch (event) { @@ -733,6 +798,9 @@ static int IdlDealP2pEventSecond(Context *context, int event) case WIFI_IDL_CBK_CMD_P2P_SERV_DISC_REQ_EVENT: IdlCbP2pServDiscReqEvent(context); break; + case WIFI_IDL_CBK_CMD_P2P_IFACE_CREATED_EVENT: + IdlCbP2pIfaceCreatedEvent(context); + break; default: return -1; } @@ -741,6 +809,7 @@ static int IdlDealP2pEventSecond(Context *context, int event) static int IdlDealP2pEvent(Context *context, int event) { + LOGI("OnTransact deal p2p event: %{public}d", event); if (IdlDealP2pEventFirst(context, event) == 0 || IdlDealP2pEventSecond(context, event) == 0) { return 0; } @@ -751,10 +820,11 @@ int OnTransact(Context *context) { int event = 0; if (ReadInt(context, &event) < 0) { + LOGE("OnTransact read event failed!"); return -1; } if (IdlDealStaApEvent(context, event) < 0 && IdlDealP2pEvent(context, event) < 0) { - LOGI("unsupport call back events: %{public}d", event); + LOGI("unsupported call back events: %{public}d", event); } return 0; } diff --git a/services/wifi_standard/wifi_framework/wifi_manage/idl_client/idl_interface/i_wifi.h b/wifi/services/wifi_standard/wifi_framework/wifi_manage/idl_client/idl_interface/i_wifi.h similarity index 94% rename from services/wifi_standard/wifi_framework/wifi_manage/idl_client/idl_interface/i_wifi.h rename to wifi/services/wifi_standard/wifi_framework/wifi_manage/idl_client/idl_interface/i_wifi.h index 6b501fee51ba1672a06ec73528d88a9054b9ba3e..d7b0ab81c267b32745197c04967ec9bd12d32222 100644 --- a/services/wifi_standard/wifi_framework/wifi_manage/idl_client/idl_interface/i_wifi.h +++ b/wifi/services/wifi_standard/wifi_framework/wifi_manage/idl_client/idl_interface/i_wifi.h @@ -1,5 +1,5 @@ /* - * Copyright (C) 2021 Huawei Device Co., Ltd. + * Copyright (C) 2021-2022 Huawei Device Co., Ltd. * 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 @@ -16,8 +16,9 @@ #ifndef OHOS_IDL_IWIFI_H #define OHOS_IDL_IWIFI_H -#include "wifi_error_no.h" +#include #include "i_wifi_struct.h" +#include "wifi_error_no.h" #ifdef __cplusplus extern "C" { @@ -66,4 +67,4 @@ WifiErrorNo NotifyClear(void); #ifdef __cplusplus } #endif -#endif \ No newline at end of file +#endif diff --git a/services/wifi_standard/wifi_framework/wifi_manage/idl_client/idl_interface/i_wifi_chip.c b/wifi/services/wifi_standard/wifi_framework/wifi_manage/idl_client/idl_interface/i_wifi_chip.c similarity index 75% rename from services/wifi_standard/wifi_framework/wifi_manage/idl_client/idl_interface/i_wifi_chip.c rename to wifi/services/wifi_standard/wifi_framework/wifi_manage/idl_client/idl_interface/i_wifi_chip.c index 38e166da49f3baab83b86bf5fc2d609df8d49dfb..1bb8429226727c2d9088cd9b46af456cc2c7bf5c 100644 --- a/services/wifi_standard/wifi_framework/wifi_manage/idl_client/idl_interface/i_wifi_chip.c +++ b/wifi/services/wifi_standard/wifi_framework/wifi_manage/idl_client/idl_interface/i_wifi_chip.c @@ -1,5 +1,5 @@ /* - * Copyright (C) 2021 Huawei Device Co., Ltd. + * Copyright (C) 2021-2022 Huawei Device Co., Ltd. * 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 @@ -12,13 +12,16 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + #include "i_wifi_chip.h" +#include #include "client.h" +#include "context.h" +#include "i_wifi_public_func.h" #include "serial.h" -#include "wifi_log.h" #include "wifi_idl_define.h" #include "wifi_idl_inner_interface.h" -#include "i_wifi_public_func.h" +#include "wifi_log.h" #undef LOG_TAG #define LOG_TAG "WifiIdlWifiChip" @@ -320,21 +323,117 @@ WifiErrorNo RequestFirmwareDebugDump(unsigned char *bytes, int32_t *size) return result; } -WifiErrorNo SetPowerMode(uint8_t mode) +WifiErrorNo IsChipSupportDbdc(bool *isSupport) { RpcClient *client = GetChipRpcClient(); LockRpcClient(client); Context *context = client->context; WriteBegin(context, 0); - WriteFunc(context, "SetPowerMode"); - WriteInt(context, mode); + WriteFunc(context, "IsChipSupportDbdc"); WriteEnd(context); - if (RpcClientCall(client, "SetPowerMode") != WIFI_IDL_OPT_OK) { - return WIFI_IDL_OPT_FAILED; + if (RpcClientCall(client, "IsChipSupportDbdc") != WIFI_IDL_OPT_OK) { + return false; } int result = WIFI_IDL_OPT_FAILED; ReadInt(context, &result); + int retValue = WIFI_IDL_FALSE; + if (result == WIFI_IDL_OPT_OK) { + ReadInt(context, &retValue); + *isSupport = (retValue == WIFI_IDL_TRUE); + } ReadClientEnd(client); UnlockRpcClient(client); return result; -} \ No newline at end of file +} + +WifiErrorNo IsChipSupportCsa(bool *isSupport) +{ + RpcClient *client = GetChipRpcClient(); + LockRpcClient(client); + Context *context = client->context; + WriteBegin(context, 0); + WriteFunc(context, "IsChipSupportCsa"); + WriteEnd(context); + if (RpcClientCall(client, "IsChipSupportCsa") != WIFI_IDL_OPT_OK) { + return false; + } + int result = WIFI_IDL_OPT_FAILED; + ReadInt(context, &result); + int retValue = WIFI_IDL_FALSE; + if (result == WIFI_IDL_OPT_OK) { + ReadInt(context, &retValue); + *isSupport = (retValue == WIFI_IDL_TRUE); + } + ReadClientEnd(client); + UnlockRpcClient(client); + return result; +} + +WifiErrorNo IsChipSupportRadarDetect(bool *isSupport) +{ + RpcClient *client = GetChipRpcClient(); + LockRpcClient(client); + Context *context = client->context; + WriteBegin(context, 0); + WriteFunc(context, "IsChipSupportRadarDetect"); + WriteEnd(context); + if (RpcClientCall(client, "IsChipSupportRadarDetect") != WIFI_IDL_OPT_OK) { + return false; + } + int result = WIFI_IDL_OPT_FAILED; + ReadInt(context, &result); + int retValue = WIFI_IDL_FALSE; + if (result == WIFI_IDL_OPT_OK) { + ReadInt(context, &retValue); + *isSupport = (retValue == WIFI_IDL_TRUE); + } + ReadClientEnd(client); + UnlockRpcClient(client); + return result; +} + +WifiErrorNo IsChipSupportDfsChannel(bool *isSupport) +{ + RpcClient *client = GetChipRpcClient(); + LockRpcClient(client); + Context *context = client->context; + WriteBegin(context, 0); + WriteFunc(context, "IsChipSupportDfsChannel"); + WriteEnd(context); + if (RpcClientCall(client, "IsChipSupportDfsChannel") != WIFI_IDL_OPT_OK) { + return false; + } + int result = WIFI_IDL_OPT_FAILED; + ReadInt(context, &result); + int retValue = WIFI_IDL_FALSE; + if (result == WIFI_IDL_OPT_OK) { + ReadInt(context, &retValue); + *isSupport = (retValue == WIFI_IDL_TRUE); + } + ReadClientEnd(client); + UnlockRpcClient(client); + return result; +} + +WifiErrorNo IsChipSupportIndoorChannel(bool *isSupport) +{ + RpcClient *client = GetChipRpcClient(); + LockRpcClient(client); + Context *context = client->context; + WriteBegin(context, 0); + WriteFunc(context, "IsChipSupportIndoorChannel"); + WriteEnd(context); + if (RpcClientCall(client, "IsChipSupportIndoorChannel") != WIFI_IDL_OPT_OK) { + return false; + } + int result = WIFI_IDL_OPT_FAILED; + ReadInt(context, &result); + int retValue = WIFI_IDL_FALSE; + if (result == WIFI_IDL_OPT_OK) { + ReadInt(context, &retValue); + *isSupport = (retValue == WIFI_IDL_TRUE); + } + ReadClientEnd(client); + UnlockRpcClient(client); + return result; +} diff --git a/services/wifi_standard/wifi_framework/wifi_manage/idl_client/idl_interface/i_wifi_chip.h b/wifi/services/wifi_standard/wifi_framework/wifi_manage/idl_client/idl_interface/i_wifi_chip.h similarity index 79% rename from services/wifi_standard/wifi_framework/wifi_manage/idl_client/idl_interface/i_wifi_chip.h rename to wifi/services/wifi_standard/wifi_framework/wifi_manage/idl_client/idl_interface/i_wifi_chip.h index c11d95982d167fbb7d559fe6c65e29e17361e08d..70660e2e71eadd47e474789dd30268b07e93aac7 100644 --- a/services/wifi_standard/wifi_framework/wifi_manage/idl_client/idl_interface/i_wifi_chip.h +++ b/wifi/services/wifi_standard/wifi_framework/wifi_manage/idl_client/idl_interface/i_wifi_chip.h @@ -1,5 +1,5 @@ /* - * Copyright (C) 2021 Huawei Device Co., Ltd. + * Copyright (C) 2021-2022 Huawei Device Co., Ltd. * 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 @@ -16,9 +16,11 @@ #ifndef OHOS_IDL_IWIFI_CHIP_H #define OHOS_IDL_IWIFI_CHIP_H -#include "wifi_error_no.h" +#include +#include #include "i_wifi_chip_event_callback.h" #include "i_wifi_struct.h" +#include "wifi_error_no.h" #ifdef __cplusplus extern "C" { @@ -138,14 +140,45 @@ WifiErrorNo RegisterEventCallback(IWifiChipEventCallback callback); WifiErrorNo RequestFirmwareDebugDump(unsigned char *bytes, int32_t *size); /** - * @Description Setting the Low Latency Mode. + * @Description is support DBDC * - * @param mode + * @param isSupport - is support or not + * @return WifiErrorNo + */ +WifiErrorNo IsChipSupportDbdc(bool *isSupport); + +/** + * @Description is support CSA + * + * @param isSupport - is support or not * @return WifiErrorNo */ -WifiErrorNo SetPowerMode(uint8_t mode); +WifiErrorNo IsChipSupportCsa(bool *isSupport); +/** + * @Description is support radar detection + * + * @param isSupport - is support or not + * @return WifiErrorNo + */ +WifiErrorNo IsChipSupportRadarDetect(bool *isSupport); + +/** + * @Description is support DFS channel + * + * @param isSupport - is support or not + * @return WifiErrorNo + */ +WifiErrorNo IsChipSupportDfsChannel(bool *isSupport); + +/** + * @Description is support indoor channel + * + * @param isSupport - is support or not + * @return WifiErrorNo + */ +WifiErrorNo IsChipSupportIndoorChannel(bool *isSupport); #ifdef __cplusplus } #endif -#endif \ No newline at end of file +#endif diff --git a/services/wifi_standard/wifi_framework/wifi_manage/idl_client/idl_interface/i_wifi_chip_event_callback.h b/wifi/services/wifi_standard/wifi_framework/wifi_manage/idl_client/idl_interface/i_wifi_chip_event_callback.h similarity index 100% rename from services/wifi_standard/wifi_framework/wifi_manage/idl_client/idl_interface/i_wifi_chip_event_callback.h rename to wifi/services/wifi_standard/wifi_framework/wifi_manage/idl_client/idl_interface/i_wifi_chip_event_callback.h diff --git a/services/wifi_standard/wifi_framework/wifi_manage/idl_client/idl_interface/i_wifi_event_callback.h b/wifi/services/wifi_standard/wifi_framework/wifi_manage/idl_client/idl_interface/i_wifi_event_callback.h similarity index 88% rename from services/wifi_standard/wifi_framework/wifi_manage/idl_client/idl_interface/i_wifi_event_callback.h rename to wifi/services/wifi_standard/wifi_framework/wifi_manage/idl_client/idl_interface/i_wifi_event_callback.h index 21d6bc123f9ce0d743d469d0a7ac24bf9ce3eb97..4166b1b3820fe206497028087df5a3075de8d639 100644 --- a/services/wifi_standard/wifi_framework/wifi_manage/idl_client/idl_interface/i_wifi_event_callback.h +++ b/wifi/services/wifi_standard/wifi_framework/wifi_manage/idl_client/idl_interface/i_wifi_event_callback.h @@ -27,10 +27,13 @@ typedef struct IWifiEventCallback { void (*onStopped)(void); void (*onFailure)(WifiErrorNo errCode); void (*onConnectChanged)(int status, int networkId, const char *bssid); + void (*onBssidChanged)(const char *reason, const char *bssid); void (*onWpaStateChanged)(int status); void (*onSsidWrongkey)(int status); void (*onWpsOverlap)(int status); void (*onWpsTimeOut)(int status); + void (*onWpsConnectionFull)(int status); + void (*onWpsConnectionReject)(int status); } IWifiEventCallback; #ifdef __cplusplus diff --git a/services/wifi_standard/wifi_framework/wifi_manage/idl_client/idl_interface/i_wifi_event_p2p_callback.h b/wifi/services/wifi_standard/wifi_framework/wifi_manage/idl_client/idl_interface/i_wifi_event_p2p_callback.h similarity index 87% rename from services/wifi_standard/wifi_framework/wifi_manage/idl_client/idl_interface/i_wifi_event_p2p_callback.h rename to wifi/services/wifi_standard/wifi_framework/wifi_manage/idl_client/idl_interface/i_wifi_event_p2p_callback.h index fa4d1a1f8565403e7e319bbd81c2612d5fc90e04..3cd0478bb555135bbfdb23a55cd3fa124f6c6c3d 100644 --- a/services/wifi_standard/wifi_framework/wifi_manage/idl_client/idl_interface/i_wifi_event_p2p_callback.h +++ b/wifi/services/wifi_standard/wifi_framework/wifi_manage/idl_client/idl_interface/i_wifi_event_p2p_callback.h @@ -25,16 +25,16 @@ extern "C" { typedef struct IWifiEventP2pCallback { void (*onP2pSupplicantConnect)(int status); - void (*onDeviceFound)(const HidlP2pDeviceInfo *device); + void (*onDeviceFound)(const P2pDeviceInfo *device); void (*onDeviceLost)(const char *p2pDeviceAddress); void (*onGoNegotiationRequest)(const char *srcAddress, short passwordId); void (*onGoNegotiationSuccess)(void); void (*onGoNegotiationFailure)(int status); - void (*onInvitationReceived)(const HidlP2pInvitationInfo *info); + void (*onInvitationReceived)(const P2pInvitationInfo *info); void (*onInvitationResult)(const char *bssid, int status); void (*onGroupFormationSuccess)(void); void (*onGroupFormationFailure)(const char *failureReason); - void (*onGroupStarted)(const HidlP2pGroupInfo *group); + void (*onGroupStarted)(const P2pGroupInfo *group); void (*onGroupRemoved)(const char *groupIfName, int isGo); void (*onProvisionDiscoveryPbcRequest)(const char *p2pDeviceAddress); void (*onProvisionDiscoveryPbcResponse)(const char *p2pDeviceAddress); @@ -47,10 +47,11 @@ typedef struct IWifiEventP2pCallback { void (*onStaDeauthorized)(const char *p2pDeviceAddress); void (*onStaAuthorized)(const char *p2pDeviceAddress); void (*connectSupplicantFailed)(void); - void (*onP2pServDiscReq)(const HidlP2pServDiscReqInfo *info); + void (*onP2pServDiscReq)(const P2pServDiscReqInfo *info); + void (*onP2pIfaceCreated)(const char *ifName, int isGo); } IWifiEventP2pCallback; #ifdef __cplusplus } #endif -#endif \ No newline at end of file +#endif diff --git a/services/wifi_standard/wifi_framework/wifi_manage/idl_client/idl_interface/i_wifi_hotspot_iface.c b/wifi/services/wifi_standard/wifi_framework/wifi_manage/idl_client/idl_interface/i_wifi_hotspot_iface.c similarity index 76% rename from services/wifi_standard/wifi_framework/wifi_manage/idl_client/idl_interface/i_wifi_hotspot_iface.c rename to wifi/services/wifi_standard/wifi_framework/wifi_manage/idl_client/idl_interface/i_wifi_hotspot_iface.c index a04cdb0b1e81515ab8cd0bc38570d7036fcd89b7..3deb12b296c225c0409655615ecac277ce520a8f 100644 --- a/services/wifi_standard/wifi_framework/wifi_manage/idl_client/idl_interface/i_wifi_hotspot_iface.c +++ b/wifi/services/wifi_standard/wifi_framework/wifi_manage/idl_client/idl_interface/i_wifi_hotspot_iface.c @@ -1,5 +1,5 @@ /* - * Copyright (C) 2021 Huawei Device Co., Ltd. + * Copyright (C) 2021-2022 Huawei Device Co., Ltd. * 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 @@ -12,37 +12,41 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + #include "i_wifi_hotspot_iface.h" +#include #include "client.h" +#include "context.h" +#include "i_wifi_public_func.h" #include "serial.h" -#include "wifi_log.h" #include "wifi_idl_define.h" #include "wifi_idl_inner_interface.h" -#include "i_wifi_public_func.h" +#include "wifi_log.h" #undef LOG_TAG #define LOG_TAG "WifiIdlHotspotIface" #define AP_EVENT_MAX_NUM 8 -static IWifiApEventCallback g_wifiApEventCallback = {0}; -void SetWifiApEventCallback(IWifiApEventCallback callback) +static IWifiApEventCallback g_wifiApEventCallback[AP_INSTANCE_MAX_NUM]; +void SetWifiApEventCallback(IWifiApEventCallback callback, int id) { - g_wifiApEventCallback = callback; + g_wifiApEventCallback[id] = callback; } -IWifiApEventCallback *GetWifiApEventCallback(void) +IWifiApEventCallback *GetWifiApEventCallback(int id) { - return &g_wifiApEventCallback; + return &g_wifiApEventCallback[id]; } -WifiErrorNo StartSoftAp(void) +WifiErrorNo StartSoftAp(int id) { RpcClient *client = GetApRpcClient(); LockRpcClient(client); Context *context = client->context; WriteBegin(context, 0); WriteFunc(context, "StartSoftAp"); + WriteInt(context, id); WriteEnd(context); if (RpcClientCall(client, "StartSoftAp") != WIFI_IDL_OPT_OK) { @@ -56,13 +60,14 @@ WifiErrorNo StartSoftAp(void) return result; } -WifiErrorNo StopSoftAp(void) +WifiErrorNo StopSoftAp(int id) { RpcClient *client = GetApRpcClient(); LockRpcClient(client); Context *context = client->context; WriteBegin(context, 0); WriteFunc(context, "StopSoftAp"); + WriteInt(context, id); WriteEnd(context); if (RpcClientCall(client, "StopSoftAp") != WIFI_IDL_OPT_OK) { @@ -76,7 +81,7 @@ WifiErrorNo StopSoftAp(void) return result; } -WifiErrorNo SetHostapdConfig(HostapdConfig *config) +WifiErrorNo SetHostapdConfig(HostapdConfig *config, int id) { RpcClient *client = GetApRpcClient(); LockRpcClient(client); @@ -91,6 +96,7 @@ WifiErrorNo SetHostapdConfig(HostapdConfig *config) WriteInt(context, config->band); WriteInt(context, config->channel); WriteInt(context, config->maxConn); + WriteInt(context, id); WriteEnd(context); if (RpcClientCall(client, "SetHostapdConfig") != WIFI_IDL_OPT_OK) { return WIFI_IDL_OPT_FAILED; @@ -102,7 +108,7 @@ WifiErrorNo SetHostapdConfig(HostapdConfig *config) return result; } -WifiErrorNo GetStaInfos(char *infos, int32_t *size) +WifiErrorNo GetStaInfos(char *infos, int32_t *size, int id) { RpcClient *client = GetApRpcClient(); LockRpcClient(client); @@ -110,6 +116,7 @@ WifiErrorNo GetStaInfos(char *infos, int32_t *size) WriteBegin(context, 0); WriteFunc(context, "GetStaInfos"); WriteInt(context, *size); + WriteInt(context, id); WriteEnd(context); if (RpcClientCall(client, "GetStaInfos") != WIFI_IDL_OPT_OK) { return WIFI_IDL_OPT_FAILED; @@ -127,7 +134,7 @@ WifiErrorNo GetStaInfos(char *infos, int32_t *size) return result; } -WifiErrorNo SetMacFilter(unsigned char *mac, int lenMac) +WifiErrorNo SetMacFilter(unsigned char *mac, int lenMac, int id) { RpcClient *client = GetApRpcClient(); LockRpcClient(client); @@ -136,6 +143,7 @@ WifiErrorNo SetMacFilter(unsigned char *mac, int lenMac) WriteFunc(context, "SetMacFilter"); WriteInt(context, lenMac); WriteUStr(context, mac, lenMac); + WriteInt(context, id); WriteEnd(context); if (RpcClientCall(client, "SetMacFilter") != WIFI_IDL_OPT_OK) { return WIFI_IDL_OPT_FAILED; @@ -147,7 +155,7 @@ WifiErrorNo SetMacFilter(unsigned char *mac, int lenMac) return result; } -WifiErrorNo DelMacFilter(unsigned char *mac, int lenMac) +WifiErrorNo DelMacFilter(unsigned char *mac, int lenMac, int id) { RpcClient *client = GetApRpcClient(); LockRpcClient(client); @@ -156,6 +164,7 @@ WifiErrorNo DelMacFilter(unsigned char *mac, int lenMac) WriteFunc(context, "DelMacFilter"); WriteInt(context, lenMac); WriteUStr(context, mac, lenMac); + WriteInt(context, id); WriteEnd(context); if (RpcClientCall(client, "DelMacFilter") != WIFI_IDL_OPT_OK) { return WIFI_IDL_OPT_FAILED; @@ -167,7 +176,7 @@ WifiErrorNo DelMacFilter(unsigned char *mac, int lenMac) return result; } -WifiErrorNo DisassociateSta(unsigned char *mac, int lenMac) +WifiErrorNo DisassociateSta(unsigned char *mac, int lenMac, int id) { RpcClient *client = GetApRpcClient(); LockRpcClient(client); @@ -176,6 +185,7 @@ WifiErrorNo DisassociateSta(unsigned char *mac, int lenMac) WriteFunc(context, "DisassociateSta"); WriteInt(context, lenMac); WriteUStr(context, mac, lenMac); + WriteInt(context, id); WriteEnd(context); if (RpcClientCall(client, "DisassociateSta") != WIFI_IDL_OPT_OK) { return WIFI_IDL_OPT_FAILED; @@ -187,7 +197,7 @@ WifiErrorNo DisassociateSta(unsigned char *mac, int lenMac) return result; } -WifiErrorNo GetValidFrequenciesForBand(int32_t band, int *frequencies, int32_t *size) +WifiErrorNo GetValidFrequenciesForBand(int32_t band, int *frequencies, int32_t *size, int id) { RpcClient *client = GetApRpcClient(); LockRpcClient(client); @@ -196,6 +206,7 @@ WifiErrorNo GetValidFrequenciesForBand(int32_t band, int *frequencies, int32_t * WriteFunc(context, "GetValidFrequenciesForBand"); WriteInt(context, band); WriteInt(context, *size); + WriteInt(context, id); WriteEnd(context); if (RpcClientCall(client, "GetValidFrequenciesForBand") != WIFI_IDL_OPT_OK) { return WIFI_IDL_OPT_FAILED; @@ -215,7 +226,7 @@ WifiErrorNo GetValidFrequenciesForBand(int32_t band, int *frequencies, int32_t * return result; } -WifiErrorNo SetCountryCode(const char *code) +WifiErrorNo SetCountryCode(const char *code, int id) { RpcClient *client = GetApRpcClient(); LockRpcClient(client); @@ -223,6 +234,7 @@ WifiErrorNo SetCountryCode(const char *code) WriteBegin(context, 0); WriteFunc(context, "SetCountryCode"); WriteStr(context, code); + WriteInt(context, id); WriteEnd(context); if (RpcClientCall(client, "SetCountryCode") != WIFI_IDL_OPT_OK) { return WIFI_IDL_OPT_FAILED; @@ -250,7 +262,7 @@ static int GetApCallbackEvents(int *events, int size) return num; } -WifiErrorNo RegisterAsscociatedEvent(IWifiApEventCallback callback) +WifiErrorNo RegisterAsscociatedEvent(IWifiApEventCallback callback, int id) { int events[AP_EVENT_MAX_NUM]; int num = GetApCallbackEvents(events, AP_EVENT_MAX_NUM); @@ -270,14 +282,56 @@ WifiErrorNo RegisterAsscociatedEvent(IWifiApEventCallback callback) WriteEnd(context); if (RpcClientCall(client, "RegisterAsscociatedEvent") != WIFI_IDL_OPT_OK) { if (callback.onStaJoinOrLeave == NULL) { - SetWifiApEventCallback(callback); + SetWifiApEventCallback(callback, id); } return WIFI_IDL_OPT_FAILED; } int result = WIFI_IDL_OPT_FAILED; ReadInt(context, &result); if (result == WIFI_IDL_OPT_OK || callback.onStaJoinOrLeave == NULL) { - SetWifiApEventCallback(callback); + SetWifiApEventCallback(callback, id); + } + ReadClientEnd(client); + UnlockRpcClient(client); + return result; +} + +WifiErrorNo WpaSetPowerModel(const int model, int id) +{ + RpcClient *client = GetSupplicantRpcClient(); + LockRpcClient(client); + Context *context = client->context; + WriteBegin(context, 0); + WriteFunc(context, "WpaSetPowerModel"); + WriteInt(context, model); + WriteInt(context, id); + WriteEnd(context); + if (RpcClientCall(client, "WpaSetPowerModel") != WIFI_IDL_OPT_OK) { + return WIFI_IDL_OPT_FAILED; + } + int result = WIFI_IDL_OPT_FAILED; + ReadInt(context, &result); + ReadClientEnd(client); + UnlockRpcClient(client); + return result; +} + +WifiErrorNo WpaGetPowerModel(int* model, int id) +{ + RpcClient *client = GetSupplicantRpcClient(); + LockRpcClient(client); + Context *context = client->context; + WriteBegin(context, 0); + WriteFunc(context, "WpaGetPowerModel"); + WriteInt(context, id); + WriteEnd(context); + if (RpcClientCall(client, "WpaGetPowerModel") != WIFI_IDL_OPT_OK) { + return WIFI_IDL_OPT_FAILED; + } + int result = WIFI_IDL_OPT_FAILED; + ReadInt(context, &result); + if (result == WIFI_IDL_OPT_OK) { + ReadInt(context, model); } ReadClientEnd(client); UnlockRpcClient(client); diff --git a/services/wifi_standard/wifi_framework/wifi_manage/idl_client/idl_interface/i_wifi_hotspot_iface.h b/wifi/services/wifi_standard/wifi_framework/wifi_manage/idl_client/idl_interface/i_wifi_hotspot_iface.h similarity index 70% rename from services/wifi_standard/wifi_framework/wifi_manage/idl_client/idl_interface/i_wifi_hotspot_iface.h rename to wifi/services/wifi_standard/wifi_framework/wifi_manage/idl_client/idl_interface/i_wifi_hotspot_iface.h index ec99f1d692aca635762667f489a856abeca41c4f..20530bb5223042009de350e1ea4f71e1def08224 100644 --- a/services/wifi_standard/wifi_framework/wifi_manage/idl_client/idl_interface/i_wifi_hotspot_iface.h +++ b/wifi/services/wifi_standard/wifi_framework/wifi_manage/idl_client/idl_interface/i_wifi_hotspot_iface.h @@ -28,46 +28,51 @@ extern "C" { * @Description Sets the AP event callback function. * * @param callback + * @param id - ap id */ -void SetWifiApEventCallback(IWifiApEventCallback callback); +void SetWifiApEventCallback(IWifiApEventCallback callback, int id); /** * @Description Obtains the AP event callback structure. * * @return IWifiApEventCallback* */ -IWifiApEventCallback *GetWifiApEventCallback(void); +IWifiApEventCallback *GetWifiApEventCallback(int id); /** * @Description Start Ap. * * @return WifiErrorNo + * @param id - ap id */ -WifiErrorNo StartSoftAp(void); +WifiErrorNo StartSoftAp(int id); /** * @Description Close Ap. * * @return WifiErrorNo + * @param id - ap id */ -WifiErrorNo StopSoftAp(void); +WifiErrorNo StopSoftAp(int id); /** * @Description Setting the startup configuration items of the hostapd. * * @param config - HostapdConfig object's point. + * @param id - ap id * @return WifiErrorNo */ -WifiErrorNo SetHostapdConfig(HostapdConfig *config); +WifiErrorNo SetHostapdConfig(HostapdConfig *config, int id); /** * @Description Obtains information about all connected STAs. * * @param infos * @param size + * @param id - ap id * @return WifiErrorNo */ -WifiErrorNo GetStaInfos(char *infos, int32_t *size); +WifiErrorNo GetStaInfos(char *infos, int32_t *size, int id); /** * @Description To set the blocklist filtering in AP mode to prohibit the MAC @@ -75,9 +80,10 @@ WifiErrorNo GetStaInfos(char *infos, int32_t *size); * * @param mac - Mac address. * @param lenMac - Mac string length. + * @param id - ap id * @return WifiErrorNo */ -WifiErrorNo SetMacFilter(unsigned char *mac, int lenMac); +WifiErrorNo SetMacFilter(unsigned char *mac, int lenMac, int id); /** * @Description This command is used to set blocklist filtering in AP mode and delete @@ -85,18 +91,20 @@ WifiErrorNo SetMacFilter(unsigned char *mac, int lenMac); * * @param mac - Mac address. * @param lenMac - Mac string length. + * @param id - ap id * @return WifiErrorNo */ -WifiErrorNo DelMacFilter(unsigned char *mac, int lenMac); +WifiErrorNo DelMacFilter(unsigned char *mac, int lenMac, int id); /** * @Description Disconnect the STA with a specified MAC address. * * @param mac - Mac address. * @param lenMac - Mac string length. + * @param id - ap id * @return WifiErrorNo */ -WifiErrorNo DisassociateSta(unsigned char *mac, int lenMac); +WifiErrorNo DisassociateSta(unsigned char *mac, int lenMac, int id); /** * @Description Obtains the hotspot frequency supported by a specified frequency band. @@ -105,22 +113,25 @@ WifiErrorNo DisassociateSta(unsigned char *mac, int lenMac); * @param frequencies - Numeric group pointer of the int type. * @param size - Size of the memory to which the frequencies point and the * number of obtained data. + * @param id - ap id * @return WifiErrorNo */ -WifiErrorNo GetValidFrequenciesForBand(int32_t band, int *frequencies, int32_t *size); +WifiErrorNo GetValidFrequenciesForBand(int32_t band, int *frequencies, int32_t *size, int id); /** * @Description Setting the Wi-Fi Country Code. * * @param code + * @param id - ap id * @return WifiErrorNo */ -WifiErrorNo SetCountryCode(const char *code); +WifiErrorNo SetCountryCode(const char *code, int id); /** * @Description Disconnect the STA connection based on the MAC address. * * @param mac - MAC address of the STA to be disconnected. + * @param id - ap id * @return WifiErrorNo */ WifiErrorNo DisconnectStaByMac(const char *mac); @@ -129,10 +140,28 @@ WifiErrorNo DisconnectStaByMac(const char *mac); * @Description Information about the disconnected or connected STA. * * @param callback + * @param id - ap id * @return WifiErrorNo */ -WifiErrorNo RegisterAsscociatedEvent(IWifiApEventCallback callback); +WifiErrorNo RegisterAsscociatedEvent(IWifiApEventCallback callback, int id); +/** + * @Description Get supported power model list + * + * @param model - the model to be set + * @param id - ap id + * @return ErrCode - operation result + */ +WifiErrorNo WpaSetPowerModel(const int model, int id); + +/** + * @Description Get power model + * + * @param model - current power model + * @param id - ap id + * @return ErrCode - operation result + */ +WifiErrorNo WpaGetPowerModel(int* model, int id); #ifdef __cplusplus } #endif diff --git a/services/wifi_standard/wifi_framework/wifi_manage/idl_client/idl_interface/i_wifi_iface.c b/wifi/services/wifi_standard/wifi_framework/wifi_manage/idl_client/idl_interface/i_wifi_iface.c similarity index 96% rename from services/wifi_standard/wifi_framework/wifi_manage/idl_client/idl_interface/i_wifi_iface.c rename to wifi/services/wifi_standard/wifi_framework/wifi_manage/idl_client/idl_interface/i_wifi_iface.c index 5dbd38ed26313313091a8018cbed66dc5fb8e7b7..ac898b786388d421a1f22b5ddfd53c6a0f20fc2a 100644 --- a/services/wifi_standard/wifi_framework/wifi_manage/idl_client/idl_interface/i_wifi_iface.c +++ b/wifi/services/wifi_standard/wifi_framework/wifi_manage/idl_client/idl_interface/i_wifi_iface.c @@ -1,5 +1,5 @@ /* - * Copyright (C) 2021 Huawei Device Co., Ltd. + * Copyright (C) 2021-2022 Huawei Device Co., Ltd. * 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 @@ -12,12 +12,14 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + #include "i_wifi_iface.h" #include "client.h" +#include "context.h" +#include "i_wifi_public_func.h" #include "serial.h" -#include "wifi_log.h" #include "wifi_idl_inner_interface.h" -#include "i_wifi_public_func.h" +#include "wifi_log.h" #undef LOG_TAG #define LOG_TAG "WifiIdlIface" diff --git a/services/wifi_standard/wifi_framework/wifi_manage/idl_client/idl_interface/i_wifi_iface.h b/wifi/services/wifi_standard/wifi_framework/wifi_manage/idl_client/idl_interface/i_wifi_iface.h similarity index 100% rename from services/wifi_standard/wifi_framework/wifi_manage/idl_client/idl_interface/i_wifi_iface.h rename to wifi/services/wifi_standard/wifi_framework/wifi_manage/idl_client/idl_interface/i_wifi_iface.h diff --git a/services/wifi_standard/wifi_framework/wifi_manage/idl_client/idl_interface/i_wifi_p2p_iface.c b/wifi/services/wifi_standard/wifi_framework/wifi_manage/idl_client/idl_interface/i_wifi_p2p_iface.c similarity index 95% rename from services/wifi_standard/wifi_framework/wifi_manage/idl_client/idl_interface/i_wifi_p2p_iface.c rename to wifi/services/wifi_standard/wifi_framework/wifi_manage/idl_client/idl_interface/i_wifi_p2p_iface.c index bf44d425dc9f81ffc4882a6ea7c077df15a328ca..17ca764e205b407c0597473d04d92dba94261c3e 100644 --- a/services/wifi_standard/wifi_framework/wifi_manage/idl_client/idl_interface/i_wifi_p2p_iface.c +++ b/wifi/services/wifi_standard/wifi_framework/wifi_manage/idl_client/idl_interface/i_wifi_p2p_iface.c @@ -1,5 +1,5 @@ /* - * Copyright (C) 2021 Huawei Device Co., Ltd. + * Copyright (C) 2021-2022 Huawei Device Co., Ltd. * 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 @@ -14,14 +14,15 @@ */ #include "i_wifi_p2p_iface.h" +#include +#include #include "client.h" +#include "context.h" +#include "i_wifi_public_func.h" #include "serial.h" - -#include "wifi_log.h" #include "wifi_idl_define.h" #include "wifi_idl_inner_interface.h" -#include "i_wifi_public_func.h" -#include +#include "wifi_log.h" #undef LOG_TAG #define LOG_TAG "WifiIdlP2pIface" @@ -292,7 +293,8 @@ static int GetP2pCallbackEvents(int *events, int size) WIFI_IDL_CBK_CMD_AP_STA_DISCONNECTED_EVENT, WIFI_IDL_CBK_CMD_AP_STA_CONNECTED_EVENT, WIFI_IDL_CBK_CMD_SUP_CONN_FAILED_EVENT, - WIFI_IDL_CBK_CMD_P2P_SERV_DISC_REQ_EVENT + WIFI_IDL_CBK_CMD_P2P_SERV_DISC_REQ_EVENT, + WIFI_IDL_CBK_CMD_P2P_IFACE_CREATED_EVENT }; int max = sizeof(p2pEvents) / sizeof(p2pEvents[0]); int num = 0; @@ -400,7 +402,7 @@ WifiErrorNo P2pRemoveNetwork(int networkId) return result; } -WifiErrorNo P2pListNetworks(HidlP2pNetworkList *infoList) +WifiErrorNo P2pListNetworks(P2pNetworkList *infoList) { RpcClient *client = GetP2pRpcClient(); LockRpcClient(client); @@ -424,7 +426,7 @@ WifiErrorNo P2pListNetworks(HidlP2pNetworkList *infoList) if (infoNum <= 0) { break; } - infoList->infos = (HidlP2pNetworkInfo *)calloc(infoNum, sizeof(HidlP2pNetworkInfo)); + infoList->infos = (P2pNetworkInfo *)calloc(infoNum, sizeof(P2pNetworkInfo)); if (infoList->infos == NULL) { result = WIFI_IDL_OPT_FAILED; break; @@ -597,7 +599,7 @@ WifiErrorNo P2pSetListenChannel(int channel, int regClass) return result; } -WifiErrorNo P2pConnect(HidlP2pConnectInfo *info) +WifiErrorNo P2pConnect(P2pConnectInfo *info) { RpcClient *client = GetP2pRpcClient(); LockRpcClient(client); @@ -773,7 +775,7 @@ WifiErrorNo P2pGetGroupCapability(const char *bssid, int *cap) return result; } -WifiErrorNo P2pAddService(const HidlP2pServiceInfo *info) +WifiErrorNo P2pAddService(const P2pServiceInfo *info) { RpcClient *client = GetP2pRpcClient(); LockRpcClient(client); @@ -799,7 +801,7 @@ WifiErrorNo P2pAddService(const HidlP2pServiceInfo *info) return result; } -WifiErrorNo P2pRemoveService(const HidlP2pServiceInfo *info) +WifiErrorNo P2pRemoveService(const P2pServiceInfo *info) { RpcClient *client = GetP2pRpcClient(); LockRpcClient(client); @@ -946,7 +948,7 @@ WifiErrorNo P2pSetServDiscExternal(int mode) return result; } -WifiErrorNo P2pGetPeer(const char *deviceAddress, HidlP2pDeviceInfo *peerInfo) +WifiErrorNo P2pGetPeer(const char *deviceAddress, P2pDeviceInfo *peerInfo) { RpcClient *client = GetP2pRpcClient(); LockRpcClient(client); @@ -969,6 +971,7 @@ WifiErrorNo P2pGetPeer(const char *deviceAddress, HidlP2pDeviceInfo *peerInfo) ReadInt(context, &peerInfo->configMethods); ReadInt(context, &peerInfo->deviceCapabilities); ReadInt(context, &peerInfo->groupCapabilities); + ReadStr(context, peerInfo->operSsid, sizeof(peerInfo->operSsid)); } ReadClientEnd(client); UnlockRpcClient(client); @@ -1004,7 +1007,7 @@ WifiErrorNo P2pGetFrequencies(int32_t band, int *frequencies, int32_t *size) return result; } -WifiErrorNo P2pSetGroupConfig(int networkId, HidlP2pGroupConfig *pConfig, int size) +WifiErrorNo P2pSetGroupConfig(int networkId, P2pGroupConfig *pConfig, int size) { RpcClient *client = GetP2pRpcClient(); LockRpcClient(client); @@ -1031,7 +1034,7 @@ WifiErrorNo P2pSetGroupConfig(int networkId, HidlP2pGroupConfig *pConfig, int si return result; } -WifiErrorNo P2pGetGroupConfig(int networkId, HidlP2pGroupConfig *pConfig, int size) +WifiErrorNo P2pGetGroupConfig(int networkId, P2pGroupConfig *pConfig, int size) { RpcClient *client = GetP2pRpcClient(); LockRpcClient(client); @@ -1082,4 +1085,26 @@ WifiErrorNo P2pAddNetwork(int *networkId) ReadClientEnd(client); UnlockRpcClient(client); return result; -} \ No newline at end of file +} + +WifiErrorNo Hid2dConnect(Hid2dConnectInfo *info) +{ + RpcClient *client = GetP2pRpcClient(); + LockRpcClient(client); + Context *context = client->context; + WriteBegin(context, 0); + WriteFunc(context, "P2pHid2dConnect"); + WriteStr(context, info->ssid); + WriteStr(context, info->bssid); + WriteStr(context, info->passphrase); + WriteInt(context, info->frequency); + WriteEnd(context); + if (RpcClientCall(client, "P2pHid2dConnect") != WIFI_IDL_OPT_OK) { + return WIFI_IDL_OPT_FAILED; + } + int result = WIFI_IDL_OPT_FAILED; + ReadInt(context, &result); + ReadClientEnd(client); + UnlockRpcClient(client); + return result; +} diff --git a/services/wifi_standard/wifi_framework/wifi_manage/idl_client/idl_interface/i_wifi_p2p_iface.h b/wifi/services/wifi_standard/wifi_framework/wifi_manage/idl_client/idl_interface/i_wifi_p2p_iface.h similarity index 92% rename from services/wifi_standard/wifi_framework/wifi_manage/idl_client/idl_interface/i_wifi_p2p_iface.h rename to wifi/services/wifi_standard/wifi_framework/wifi_manage/idl_client/idl_interface/i_wifi_p2p_iface.h index f2abbef3711b966b6d048d63274fa8f6761ddad8..c47526bcf57a2b2de41b3a22b561a8069de5af50 100644 --- a/services/wifi_standard/wifi_framework/wifi_manage/idl_client/idl_interface/i_wifi_p2p_iface.h +++ b/wifi/services/wifi_standard/wifi_framework/wifi_manage/idl_client/idl_interface/i_wifi_p2p_iface.h @@ -1,5 +1,5 @@ /* - * Copyright (C) 2021 Huawei Device Co., Ltd. + * Copyright (C) 2021-2022 Huawei Device Co., Ltd. * 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 @@ -16,9 +16,10 @@ #ifndef OHOS_IDL_IWIFI_P2P_IFACE_H #define OHOS_IDL_IWIFI_P2P_IFACE_H -#include "wifi_error_no.h" +#include #include "i_wifi_event_p2p_callback.h" #include "i_wifi_struct.h" +#include "wifi_error_no.h" #ifdef __cplusplus extern "C" { @@ -172,7 +173,7 @@ WifiErrorNo P2pRemoveNetwork(int networkId); * * @return WifiErrorNo */ -WifiErrorNo P2pListNetworks(HidlP2pNetworkList *infoList); +WifiErrorNo P2pListNetworks(P2pNetworkList *infoList); /** * @Description Send a request for set group max idle to the P2P @@ -246,7 +247,7 @@ WifiErrorNo P2pSetListenChannel(int channel, int regClass); * @Description Send a request for connect to the P2P * */ -WifiErrorNo P2pConnect(HidlP2pConnectInfo *info); +WifiErrorNo P2pConnect(P2pConnectInfo *info); /** * @Description Send a request for cancel connect to the P2P @@ -316,7 +317,7 @@ WifiErrorNo P2pGetGroupCapability(const char *bssid, int *cap); * @param info * @return WifiErrorNo */ -WifiErrorNo P2pAddService(const HidlP2pServiceInfo *info); +WifiErrorNo P2pAddService(const P2pServiceInfo *info); /** * @Description Send a request for removing a service to the P2P @@ -324,7 +325,7 @@ WifiErrorNo P2pAddService(const HidlP2pServiceInfo *info); * @param info * @return WifiErrorNo */ -WifiErrorNo P2pRemoveService(const HidlP2pServiceInfo *info); +WifiErrorNo P2pRemoveService(const P2pServiceInfo *info); /** * @Description Send a request for request service discovery to the P2P @@ -382,7 +383,7 @@ WifiErrorNo P2pSetServDiscExternal(int mode); * * @return WifiErrorNo */ -WifiErrorNo P2pGetPeer(const char *deviceAddress, HidlP2pDeviceInfo *peerInfo); +WifiErrorNo P2pGetPeer(const char *deviceAddress, P2pDeviceInfo *peerInfo); /** * @Description Obtains the frequencies supported by a specified frequency band. @@ -401,7 +402,7 @@ WifiErrorNo P2pGetFrequencies(int32_t band, int *frequencies, int32_t *size); * @param config * @return WifiErrorNo */ -WifiErrorNo P2pSetGroupConfig(int networkId, HidlP2pGroupConfig *pConfig, int size); +WifiErrorNo P2pSetGroupConfig(int networkId, P2pGroupConfig *pConfig, int size); /** * @Description Getting the P2P group config. @@ -410,7 +411,7 @@ WifiErrorNo P2pSetGroupConfig(int networkId, HidlP2pGroupConfig *pConfig, int si * @param config * @return WifiErrorNo */ -WifiErrorNo P2pGetGroupConfig(int networkId, HidlP2pGroupConfig *pConfig, int size); +WifiErrorNo P2pGetGroupConfig(int networkId, P2pGroupConfig *pConfig, int size); /** * @Description Request to obtain the next network ID. @@ -420,6 +421,14 @@ WifiErrorNo P2pGetGroupConfig(int networkId, HidlP2pGroupConfig *pConfig, int si */ WifiErrorNo P2pAddNetwork(int *networkId); +/** + * @Description Send a request for hid2d connect + * + * @param info - configuration for the connection + * @return WifiErrorNo + */ +WifiErrorNo Hid2dConnect(Hid2dConnectInfo *info); + #ifdef __cplusplus } #endif diff --git a/services/wifi_standard/wifi_framework/wifi_manage/idl_client/idl_interface/i_wifi_public_func.c b/wifi/services/wifi_standard/wifi_framework/wifi_manage/idl_client/idl_interface/i_wifi_public_func.c similarity index 93% rename from services/wifi_standard/wifi_framework/wifi_manage/idl_client/idl_interface/i_wifi_public_func.c rename to wifi/services/wifi_standard/wifi_framework/wifi_manage/idl_client/idl_interface/i_wifi_public_func.c index 3b1b0a8a0b657669947ae3a3456ae9f1fe7ce38f..3b40636a9ed5f6d03504384aaf18797271c57b22 100644 --- a/services/wifi_standard/wifi_framework/wifi_manage/idl_client/idl_interface/i_wifi_public_func.c +++ b/wifi/services/wifi_standard/wifi_framework/wifi_manage/idl_client/idl_interface/i_wifi_public_func.c @@ -1,5 +1,5 @@ /* - * Copyright (C) 2021 Huawei Device Co., Ltd. + * Copyright (C) 2021-2022 Huawei Device Co., Ltd. * 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 @@ -12,8 +12,11 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + #include "i_wifi_public_func.h" +#include #include "wifi_log.h" + #undef LOG_TAG #define LOG_TAG "OHWIFI_IDLCLIENT_I_WIFI_PUBLIC_FUNC" diff --git a/services/wifi_standard/wifi_framework/wifi_manage/idl_client/idl_interface/i_wifi_public_func.h b/wifi/services/wifi_standard/wifi_framework/wifi_manage/idl_client/idl_interface/i_wifi_public_func.h similarity index 100% rename from services/wifi_standard/wifi_framework/wifi_manage/idl_client/idl_interface/i_wifi_public_func.h rename to wifi/services/wifi_standard/wifi_framework/wifi_manage/idl_client/idl_interface/i_wifi_public_func.h diff --git a/services/wifi_standard/wifi_framework/wifi_manage/idl_client/idl_interface/i_wifi_sta_iface.c b/wifi/services/wifi_standard/wifi_framework/wifi_manage/idl_client/idl_interface/i_wifi_sta_iface.c similarity index 90% rename from services/wifi_standard/wifi_framework/wifi_manage/idl_client/idl_interface/i_wifi_sta_iface.c rename to wifi/services/wifi_standard/wifi_framework/wifi_manage/idl_client/idl_interface/i_wifi_sta_iface.c index b6ccac6d9d990ccdc12e34e323444f9c918f1f15..52179259999e5f8ee3b3a42bb683cceaff7ffca8 100644 --- a/services/wifi_standard/wifi_framework/wifi_manage/idl_client/idl_interface/i_wifi_sta_iface.c +++ b/wifi/services/wifi_standard/wifi_framework/wifi_manage/idl_client/idl_interface/i_wifi_sta_iface.c @@ -1,5 +1,5 @@ /* - * Copyright (C) 2021 Huawei Device Co., Ltd. + * Copyright (C) 2021-2022 Huawei Device Co., Ltd. * 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 @@ -12,13 +12,17 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + #include "i_wifi_sta_iface.h" +#include +#include #include "client.h" +#include "context.h" +#include "i_wifi_public_func.h" #include "serial.h" -#include "wifi_log.h" #include "wifi_idl_define.h" #include "wifi_idl_inner_interface.h" -#include "i_wifi_public_func.h" +#include "wifi_log.h" #undef LOG_TAG #define LOG_TAG "WifiIdlStaIface" @@ -319,7 +323,7 @@ WifiErrorNo DisableNetwork(int networkId) return result; } -WifiErrorNo SetNetwork(int networkId, HidlSetNetworkConfig *confs, int size) +WifiErrorNo SetNetwork(int networkId, SetNetworkConfig *confs, int size) { RpcClient *client = GetStaRpcClient(); LockRpcClient(client); @@ -346,7 +350,7 @@ WifiErrorNo SetNetwork(int networkId, HidlSetNetworkConfig *confs, int size) return result; } -WifiErrorNo WpaGetNetwork(HidlGetNetworkConfig *confs) +WifiErrorNo WpaGetNetwork(GetNetworkConfig *confs) { RpcClient *client = GetStaRpcClient(); LockRpcClient(client); @@ -420,7 +424,7 @@ WifiErrorNo StartScan(const ScanSettings *settings) return result; } -WifiErrorNo GetNetworkList(HidlNetworkInfo *infos, int *size) +WifiErrorNo GetNetworkList(WifiNetworkInfo *infos, int *size) { RpcClient *client = GetStaRpcClient(); LockRpcClient(client); @@ -450,6 +454,34 @@ WifiErrorNo GetNetworkList(HidlNetworkInfo *infos, int *size) return result; } +static void GetScanInfoElems(Context *context, ScanInfo* scanInfo) +{ + const int MAX_INFO_ELEMS_SIZE = 256; + ReadInt(context, &scanInfo->ieSize); + if (scanInfo->ieSize <= 0 || scanInfo->ieSize > MAX_INFO_ELEMS_SIZE) { + return; + } + /* This pointer will be released in its client */ + scanInfo->infoElems = (ScanInfoElem *)calloc(scanInfo->ieSize, sizeof(ScanInfoElem)); + if (scanInfo->infoElems == NULL) { + return; + } + for (int i = 0; i < scanInfo->ieSize; ++i) { + ReadInt(context, (int *)&scanInfo->infoElems[i].id); + ReadInt(context, &scanInfo->infoElems[i].size); + if (scanInfo->infoElems[i].size <= 0) { + continue; + } + /* This pointer will be released in its client */ + scanInfo->infoElems[i].content = calloc(scanInfo->infoElems[i].size + 1, sizeof(char)); + if (scanInfo->infoElems[i].content == NULL) { + return; + } + ReadUStr(context, (unsigned char *)scanInfo->infoElems[i].content, + scanInfo->infoElems[i].size + 1); + } +} + ScanInfo* GetScanInfos(int *size) { RpcClient *client = GetStaRpcClient(); @@ -480,6 +512,10 @@ ScanInfo* GetScanInfos(int *size) ReadStr(context, scanInfos[i].capability, WIFI_SCAN_INFO_CAPABILITIES_LENGTH); ReadStr(context, scanInfos[i].ssid, WIFI_SSID_LENGTH); ReadInt64(context, &scanInfos[i].timestamp); + ReadInt(context, &scanInfos[i].channelWidth); + ReadInt(context, &scanInfos[i].centerFrequency0); + ReadInt(context, &scanInfos[i].centerFrequency1); + GetScanInfoElems(context, &scanInfos[i]); } } else { LOGE("GetScanInfos alloc mem failed!"); @@ -554,10 +590,13 @@ static int CheckRegisterEvent(int *events, int size) WIFI_IDL_CBK_CMD_STARTED, WIFI_IDL_CBK_CMD_STOPED, WIFI_IDL_CBK_CMD_CONNECT_CHANGED, + WIFI_IDL_CBK_CMD_BSSID_CHANGED, WIFI_IDL_CBK_CMD_WPA_STATE_CHANGEM, WIFI_IDL_CBK_CMD_SSID_WRONG_KEY, WIFI_IDL_CBK_CMD_WPS_OVERLAP, - WIFI_IDL_CBK_CMD_WPS_TIME_OUT + WIFI_IDL_CBK_CMD_WPS_TIME_OUT, + WIFI_IDL_CBK_CMD_WPS_CONNECTION_FULL, + WIFI_IDL_CBK_CMD_WPS_CONNECTION_REJECT }; int max = sizeof(staEvents) / sizeof(staEvents[0]); int num = 0; @@ -770,7 +809,7 @@ WifiErrorNo WpaBlocklistClear(void) return result; } -WifiErrorNo GetConnectSignalInfo(const char *endBssid, HidlWpaSignalInfo *info) +WifiErrorNo GetConnectSignalInfo(const char *endBssid, WpaSignalInfo *info) { RpcClient *client = GetStaRpcClient(); LockRpcClient(client); @@ -797,3 +836,23 @@ WifiErrorNo GetConnectSignalInfo(const char *endBssid, HidlWpaSignalInfo *info) UnlockRpcClient(client); return result; } + +WifiErrorNo SetSuspendMode(bool mode) +{ + RpcClient *client = GetStaRpcClient(); + LockRpcClient(client); + Context *context = client->context; + WriteBegin(context, 0); + WriteFunc(context, "SetSuspendMode"); + WriteInt(context, mode); + WriteEnd(context); + if (RpcClientCall(client, "SetSuspendMode") != WIFI_IDL_OPT_OK) { + return WIFI_IDL_OPT_FAILED; + } + int result = WIFI_IDL_OPT_FAILED; + ReadInt(context, &result); + ReadClientEnd(client); + UnlockRpcClient(client); + return result; +} + diff --git a/services/wifi_standard/wifi_framework/wifi_manage/idl_client/idl_interface/i_wifi_sta_iface.h b/wifi/services/wifi_standard/wifi_framework/wifi_manage/idl_client/idl_interface/i_wifi_sta_iface.h similarity index 91% rename from services/wifi_standard/wifi_framework/wifi_manage/idl_client/idl_interface/i_wifi_sta_iface.h rename to wifi/services/wifi_standard/wifi_framework/wifi_manage/idl_client/idl_interface/i_wifi_sta_iface.h index 400d68e929e25a7e003a4e1bae2532aa7e961116..bee02f8dd5c200c63f0885d764de14b51c6778d5 100644 --- a/services/wifi_standard/wifi_framework/wifi_manage/idl_client/idl_interface/i_wifi_sta_iface.h +++ b/wifi/services/wifi_standard/wifi_framework/wifi_manage/idl_client/idl_interface/i_wifi_sta_iface.h @@ -1,5 +1,5 @@ /* - * Copyright (C) 2021 Huawei Device Co., Ltd. + * Copyright (C) 2021-2022 Huawei Device Co., Ltd. * 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 @@ -16,9 +16,12 @@ #ifndef OHOS_IDL_IWIFI_STA_IFACE_H #define OHOS_IDL_IWIFI_STA_IFACE_H +#include +#include #include "wifi_error_no.h" #include "i_wifi_event_callback.h" #include "i_wifi_struct.h" +#include "wifi_error_no.h" #ifdef __cplusplus extern "C" { @@ -161,7 +164,7 @@ WifiErrorNo DisableNetwork(int networkId); * @param size * @return WifiErrorNo */ -WifiErrorNo SetNetwork(int networkId, HidlSetNetworkConfig *confs, int size); +WifiErrorNo SetNetwork(int networkId, SetNetworkConfig *confs, int size); /** * @Description WpaGetNetwork Info. @@ -169,7 +172,7 @@ WifiErrorNo SetNetwork(int networkId, HidlSetNetworkConfig *confs, int size); * @param confs * @return WifiErrorNo */ -WifiErrorNo WpaGetNetwork(HidlGetNetworkConfig *confs); +WifiErrorNo WpaGetNetwork(GetNetworkConfig *confs); /** * @Description Save the network. @@ -284,7 +287,7 @@ WifiErrorNo WpaBlocklistClear(void); * @param size * @return WifiErrorNo */ -WifiErrorNo GetNetworkList(HidlNetworkInfo *infos, int *size); +WifiErrorNo GetNetworkList(WifiNetworkInfo *infos, int *size); /** * @Description Get current connect signal info, rssi, linkspeed, noise ... @@ -293,9 +296,16 @@ WifiErrorNo GetNetworkList(HidlNetworkInfo *infos, int *size); * @param info - signal info * @return WifiErrorNo */ -WifiErrorNo GetConnectSignalInfo(const char *endBssid, HidlWpaSignalInfo *info); +WifiErrorNo GetConnectSignalInfo(const char *endBssid, WpaSignalInfo *info); +/** + * @Description send suspend mode for wpa. + * + * @param mode: true for suspend, false for resume. + * @return WifiErrorNo + */ +WifiErrorNo SetSuspendMode(bool mode); #ifdef __cplusplus } #endif -#endif \ No newline at end of file +#endif diff --git a/services/wifi_standard/wifi_framework/wifi_manage/idl_client/idl_interface/i_wifi_struct.h b/wifi/services/wifi_standard/wifi_framework/wifi_manage/idl_client/idl_interface/i_wifi_struct.h similarity index 86% rename from services/wifi_standard/wifi_framework/wifi_manage/idl_client/idl_interface/i_wifi_struct.h rename to wifi/services/wifi_standard/wifi_framework/wifi_manage/idl_client/idl_interface/i_wifi_struct.h index 304e556dfe11a3872a0516466479b4d4e6b030ce..4416f47e5ccd3e199b04ee4f6265324f091342c7 100644 --- a/services/wifi_standard/wifi_framework/wifi_manage/idl_client/idl_interface/i_wifi_struct.h +++ b/wifi/services/wifi_standard/wifi_framework/wifi_manage/idl_client/idl_interface/i_wifi_struct.h @@ -1,5 +1,5 @@ /* - * Copyright (C) 2021 Huawei Device Co., Ltd. + * Copyright (C) 2021-2022 Huawei Device Co., Ltd. * 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 @@ -22,6 +22,7 @@ extern "C" { #endif #define WIFI_SSID_LENGTH 132 #define WIFI_BSSID_LENGTH 18 +#define WIFI_REASON_LENGTH 32 #define WIFI_NETWORK_FLAGS_LENGTH 64 #define WIFI_SCAN_INFO_CAPABILITIES_LENGTH 256 #define WIFI_NETWORK_CONFIG_NAME_LENGTH 64 @@ -107,12 +108,12 @@ typedef struct ScanInfo { int antValue; } ScanInfo; -typedef struct HidlNetworkInfo { +typedef struct WifiNetworkInfo { int id; char ssid[WIFI_SSID_LENGTH]; char bssid[WIFI_BSSID_LENGTH]; char flags[WIFI_NETWORK_FLAGS_LENGTH]; -} HidlNetworkInfo; +} WifiNetworkInfo; typedef struct PnoScanSettings { int scanInterval; @@ -143,19 +144,22 @@ typedef enum DeviceConfigType { DEVICE_CONFIG_WEP_KEY_1 = 12, DEVICE_CONFIG_WEP_KEY_2 = 13, DEVICE_CONFIG_WEP_KEY_3 = 14, + DEVICE_CONFIG_EAP_CLIENT_CERT = 15, + DEVICE_CONFIG_EAP_PRIVATE_KEY = 16, + DEVICE_CONFIG_EAP_PHASE2METHOD = 17, DEVICE_CONFIG_END_POS, /* Number of network configuration parameters, which is used as the last parameter. */ } DeviceConfigType; -typedef struct HidlSetNetworkConfig { +typedef struct SetNetworkConfig { DeviceConfigType cfgParam; /* param */ char cfgValue[WIFI_NETWORK_CONFIG_VALUE_LENGTH]; /* param value */ -} HidlSetNetworkConfig; +} SetNetworkConfig; -typedef struct HidlGetNetworkConfig { +typedef struct GetNetworkConfig { int networkId; char param[WIFI_NETWORK_CONFIG_NAME_LENGTH]; char value[WIFI_NETWORK_CONFIG_VALUE_LENGTH]; -} HidlGetNetworkConfig; +} GetNetworkConfig; typedef struct WifiWpsParam { int anyFlag; @@ -169,13 +173,13 @@ typedef struct WifiRoamCapability { int maxTrustlistSize; } WifiRoamCapability; -typedef struct HidlWpaSignalInfo { +typedef struct WpaSignalInfo { int signal; int txrate; int rxrate; int noise; int frequency; -} HidlWpaSignalInfo; +} WpaSignalInfo; typedef struct HostapdConfig { char ssid[WIFI_SSID_LENGTH]; @@ -194,8 +198,8 @@ typedef struct CStationInfo { } CStationInfo; typedef struct IWifiApEventCallback { - void (*onStaJoinOrLeave)(const CStationInfo *info); - void (*onApEnableOrDisable)(int event); + void (*onStaJoinOrLeave)(const CStationInfo *info, int id); + void (*onApEnableOrDisable)(int event, int id); } IWifiApEventCallback; typedef enum IfaceType { TYPE_STA, TYPE_AP, TYPE_P2P, TYPE_NAN } IfaceType; @@ -211,7 +215,7 @@ typedef enum IfaceType { TYPE_STA, TYPE_AP, TYPE_P2P, TYPE_NAN } IfaceType; #define WIFI_P2P_IDL_SERVER_INFO_LENGTH 256 #define WIFI_P2P_GROUP_CONFIG_VALUE_LENGTH 256 -typedef struct HidlP2pDeviceInfo { +typedef struct P2pDeviceInfo { char srcAddress[WIFI_MAC_ADDR_LENGTH + 1]; char p2pDeviceAddress[WIFI_MAC_ADDR_LENGTH + 1]; char primaryDeviceType[WIFI_P2P_DEVICE_TYPE_LENGTH]; @@ -221,9 +225,10 @@ typedef struct HidlP2pDeviceInfo { int groupCapabilities; char wfdDeviceInfo[WIFI_P2P_WFD_DEVICE_INFO_LENGTH]; unsigned int wfdLength; -} HidlP2pDeviceInfo; + char operSsid[WIFI_P2P_DEVICE_NAME_LENGTH]; +} P2pDeviceInfo; -typedef struct HidlP2pGroupInfo { +typedef struct P2pGroupInfo { int isGo; int isPersistent; int frequency; @@ -232,54 +237,54 @@ typedef struct HidlP2pGroupInfo { char psk[WIFI_P2P_TMP_MSG_LENGTH_128]; char passphrase[WIFI_P2P_TMP_MSG_LENGTH_128]; char goDeviceAddress[WIFI_MAC_ADDR_LENGTH + 1]; -} HidlP2pGroupInfo; +} P2pGroupInfo; -typedef struct HidlP2pInvitationInfo { - int type; /* 0:Recived, 1:Accepted */ +typedef struct P2pInvitationInfo { + int type; /* 0:Received, 1:Accepted */ int persistentNetworkId; int operatingFrequency; char srcAddress[WIFI_MAC_ADDR_LENGTH + 1]; char goDeviceAddress[WIFI_MAC_ADDR_LENGTH + 1]; char bssid[WIFI_MAC_ADDR_LENGTH + 1]; -} HidlP2pInvitationInfo; +} P2pInvitationInfo; -typedef struct HidlP2pServDiscReqInfo { +typedef struct P2pServDiscReqInfo { int freq; int dialogToken; int updateIndic; int tlvsLength; char mac[WIFI_MAC_ADDR_LENGTH + 1]; unsigned char *tlvs; -} HidlP2pServDiscReqInfo; +} P2pServDiscReqInfo; -typedef struct HidlP2pServiceInfo { +typedef struct P2pServiceInfo { int mode; /* 0/1, upnp/bonjour */ int version; char name[WIFI_P2P_IDL_SERVER_NAME_LENGTH]; char query[WIFI_P2P_IDL_SERVER_INFO_LENGTH]; char resp[WIFI_P2P_IDL_SERVER_INFO_LENGTH]; -} HidlP2pServiceInfo; +} P2pServiceInfo; -typedef struct HidlP2pNetworkInfo { +typedef struct P2pNetworkInfo { int id; char ssid[WIFI_SSID_LENGTH]; char bssid[WIFI_MAC_ADDR_LENGTH + 1]; char flags[WIFI_P2P_TMP_MSG_LENGTH_64]; -} HidlP2pNetworkInfo; +} P2pNetworkInfo; -typedef struct HidlP2pNetworkList { +typedef struct P2pNetworkList { int infoNum; - HidlP2pNetworkInfo *infos; -} HidlP2pNetworkList; + P2pNetworkInfo *infos; +} P2pNetworkList; -typedef struct HidlP2pConnectInfo { +typedef struct P2pConnectInfo { int persistent; /* |persistent=] */ int mode; /* [join|auth] */ int goIntent; /* [go_intent=<0..15>] */ int provdisc; /* [provdisc] */ char peerDevAddr[WIFI_MAC_ADDR_LENGTH + 1]; char pin[WIFI_PIN_CODE_LENGTH + 1]; /* */ -} HidlP2pConnectInfo; +} P2pConnectInfo; /* Wifi P2P Group Network configuration parameter flag */ typedef enum P2pGroupConfigType { @@ -295,15 +300,20 @@ typedef enum P2pGroupConfigType { GROUP_CONFIG_END_POS, } P2pGroupConfigType; -typedef struct HidlP2pGroupConfig { +typedef struct P2pGroupConfig { P2pGroupConfigType cfgParam; /* param */ char cfgValue[WIFI_P2P_GROUP_CONFIG_VALUE_LENGTH]; /* param value */ -} HidlP2pGroupConfig; +} P2pGroupConfig; +typedef struct Hid2dConnectInfo { + char ssid[WIFI_SSID_LENGTH]; + char bssid[WIFI_MAC_ADDR_LENGTH + 1]; + char passphrase[WIFI_P2P_TMP_MSG_LENGTH_128]; + int frequency; +} Hid2dConnectInfo; /* ----------------p2p struct defines end--------------------------- */ - #ifdef __cplusplus } #endif -#endif \ No newline at end of file +#endif diff --git a/services/wifi_standard/wifi_framework/wifi_manage/idl_client/idl_interface/i_wifi_supplicant_iface.c b/wifi/services/wifi_standard/wifi_framework/wifi_manage/idl_client/idl_interface/i_wifi_supplicant_iface.c similarity index 98% rename from services/wifi_standard/wifi_framework/wifi_manage/idl_client/idl_interface/i_wifi_supplicant_iface.c rename to wifi/services/wifi_standard/wifi_framework/wifi_manage/idl_client/idl_interface/i_wifi_supplicant_iface.c index b6e96ed201a7126dc96184391775f2c1a58cc987..d09d7b741edeb53bad7f44c0bf8847a793c9fede 100644 --- a/services/wifi_standard/wifi_framework/wifi_manage/idl_client/idl_interface/i_wifi_supplicant_iface.c +++ b/wifi/services/wifi_standard/wifi_framework/wifi_manage/idl_client/idl_interface/i_wifi_supplicant_iface.c @@ -1,5 +1,5 @@ /* - * Copyright (C) 2021 Huawei Device Co., Ltd. + * Copyright (C) 2021-2022 Huawei Device Co., Ltd. * 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 @@ -12,13 +12,17 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + #include "i_wifi_supplicant_iface.h" +#include +#include #include "client.h" +#include "context.h" +#include "i_wifi_public_func.h" #include "serial.h" -#include "wifi_log.h" #include "wifi_idl_define.h" #include "wifi_idl_inner_interface.h" -#include "i_wifi_public_func.h" +#include "wifi_log.h" #undef LOG_TAG #define LOG_TAG "WifiIdlSupplicantIface" @@ -296,4 +300,4 @@ WifiErrorNo WpaGetCountryCode(char *countryCode, int codeSize) return WIFI_IDL_OPT_FAILED; } return result; -} \ No newline at end of file +} diff --git a/services/wifi_standard/wifi_framework/wifi_manage/idl_client/idl_interface/i_wifi_supplicant_iface.h b/wifi/services/wifi_standard/wifi_framework/wifi_manage/idl_client/idl_interface/i_wifi_supplicant_iface.h similarity index 100% rename from services/wifi_standard/wifi_framework/wifi_manage/idl_client/idl_interface/i_wifi_supplicant_iface.h rename to wifi/services/wifi_standard/wifi_framework/wifi_manage/idl_client/idl_interface/i_wifi_supplicant_iface.h diff --git a/services/wifi_standard/wifi_framework/wifi_manage/idl_client/supplicant_event_callback.h b/wifi/services/wifi_standard/wifi_framework/wifi_manage/idl_client/supplicant_event_callback.h similarity index 100% rename from services/wifi_standard/wifi_framework/wifi_manage/idl_client/supplicant_event_callback.h rename to wifi/services/wifi_standard/wifi_framework/wifi_manage/idl_client/supplicant_event_callback.h diff --git a/services/wifi_standard/wifi_framework/wifi_manage/idl_client/wifi_ap_event_callback.h b/wifi/services/wifi_standard/wifi_framework/wifi_manage/idl_client/wifi_ap_event_callback.h similarity index 100% rename from services/wifi_standard/wifi_framework/wifi_manage/idl_client/wifi_ap_event_callback.h rename to wifi/services/wifi_standard/wifi_framework/wifi_manage/idl_client/wifi_ap_event_callback.h diff --git a/services/wifi_standard/wifi_framework/wifi_manage/idl_client/wifi_ap_hal_interface.cpp b/wifi/services/wifi_standard/wifi_framework/wifi_manage/idl_client/wifi_ap_hal_interface.cpp similarity index 47% rename from services/wifi_standard/wifi_framework/wifi_manage/idl_client/wifi_ap_hal_interface.cpp rename to wifi/services/wifi_standard/wifi_framework/wifi_manage/idl_client/wifi_ap_hal_interface.cpp index 95320a250a1be4ca66d13ba7fd37853c14ad90cc..d6681dabbe1463559d838267e0d850163da520c8 100644 --- a/services/wifi_standard/wifi_framework/wifi_manage/idl_client/wifi_ap_hal_interface.cpp +++ b/wifi/services/wifi_standard/wifi_framework/wifi_manage/idl_client/wifi_ap_hal_interface.cpp @@ -1,5 +1,5 @@ /* - * Copyright (C) 2021 Huawei Device Co., Ltd. + * Copyright (C) 2021-2022 Huawei Device Co., Ltd. * 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 @@ -22,6 +22,7 @@ namespace OHOS { namespace Wifi { +static IWifiApMonitorEventCallback g_cb = {nullptr, nullptr}; WifiApHalInterface &WifiApHalInterface::GetInstance(void) { static WifiApHalInterface inst; @@ -38,68 +39,95 @@ WifiApHalInterface &WifiApHalInterface::GetInstance(void) return inst; } -WifiErrorNo WifiApHalInterface::StartAp(void) +WifiErrorNo WifiApHalInterface::StartAp(int id) { - return mIdlClient->StartAp(); + CHECK_NULL_AND_RETURN(mIdlClient, WIFI_IDL_OPT_FAILED); + return mIdlClient->StartAp(id); } -WifiErrorNo WifiApHalInterface::StopAp(void) +WifiErrorNo WifiApHalInterface::StopAp(int id) { - return mIdlClient->StopAp(); + CHECK_NULL_AND_RETURN(mIdlClient, WIFI_IDL_OPT_FAILED); + return mIdlClient->StopAp(id); } -WifiErrorNo WifiApHalInterface::SetSoftApConfig(const HotspotConfig &config) +WifiErrorNo WifiApHalInterface::SetSoftApConfig(const HotspotConfig &config, int id) { - return mIdlClient->SetSoftApConfig(config); + CHECK_NULL_AND_RETURN(mIdlClient, WIFI_IDL_OPT_FAILED); + return mIdlClient->SetSoftApConfig(config, id); } -WifiErrorNo WifiApHalInterface::GetStationList(std::vector &result) +WifiErrorNo WifiApHalInterface::GetStationList(std::vector &result, int id) { - return mIdlClient->GetStationList(result); + CHECK_NULL_AND_RETURN(mIdlClient, WIFI_IDL_OPT_FAILED); + return mIdlClient->GetStationList(result, id); } -WifiErrorNo WifiApHalInterface::AddBlockByMac(const std::string &mac) +WifiErrorNo WifiApHalInterface::AddBlockByMac(const std::string &mac, int id) { - return mIdlClient->AddBlockByMac(mac); + CHECK_NULL_AND_RETURN(mIdlClient, WIFI_IDL_OPT_FAILED); + return mIdlClient->AddBlockByMac(mac, id); } -WifiErrorNo WifiApHalInterface::DelBlockByMac(const std::string &mac) +WifiErrorNo WifiApHalInterface::DelBlockByMac(const std::string &mac, int id) { - return mIdlClient->DelBlockByMac(mac); + CHECK_NULL_AND_RETURN(mIdlClient, WIFI_IDL_OPT_FAILED); + return mIdlClient->DelBlockByMac(mac, id); } -WifiErrorNo WifiApHalInterface::RemoveStation(const std::string &mac) +WifiErrorNo WifiApHalInterface::RemoveStation(const std::string &mac, int id) { - return mIdlClient->RemoveStation(mac); + CHECK_NULL_AND_RETURN(mIdlClient, WIFI_IDL_OPT_FAILED); + return mIdlClient->RemoveStation(mac, id); } -WifiErrorNo WifiApHalInterface::GetFrequenciesByBand(int band, std::vector &frequencies) +WifiErrorNo WifiApHalInterface::GetFrequenciesByBand(int band, std::vector &frequencies, int id) { - return mIdlClient->GetFrequenciesByBand(band, frequencies); + CHECK_NULL_AND_RETURN(mIdlClient, WIFI_IDL_OPT_FAILED); + return mIdlClient->GetFrequenciesByBand(band, frequencies, id); } -WifiErrorNo WifiApHalInterface::RegisterApEvent(IWifiApMonitorEventCallback callback) +WifiErrorNo WifiApHalInterface::RegisterApEvent(IWifiApMonitorEventCallback callback, int id) { - WifiErrorNo err = mIdlClient->RegisterApEvent(callback); + CHECK_NULL_AND_RETURN(mIdlClient, WIFI_IDL_OPT_FAILED); + WifiErrorNo err = mIdlClient->RegisterApEvent(callback, id); if (err == WIFI_IDL_OPT_OK || callback.onStaJoinOrLeave == nullptr) { - mApCallback = callback; + mApCallback[id] = callback; } return err; } -WifiErrorNo WifiApHalInterface::SetWifiCountryCode(const std::string &code) +WifiErrorNo WifiApHalInterface::SetWifiCountryCode(const std::string &code, int id) { - return mIdlClient->SetWifiCountryCode(code); + CHECK_NULL_AND_RETURN(mIdlClient, WIFI_IDL_OPT_FAILED); + return mIdlClient->SetWifiCountryCode(code, id); } -WifiErrorNo WifiApHalInterface::DisconnectStaByMac(const std::string &mac) +WifiErrorNo WifiApHalInterface::DisconnectStaByMac(const std::string &mac, int id) { - return mIdlClient->ReqDisconnectStaByMac(mac); + CHECK_NULL_AND_RETURN(mIdlClient, WIFI_IDL_OPT_FAILED); + return mIdlClient->ReqDisconnectStaByMac(mac, id); } -const IWifiApMonitorEventCallback &WifiApHalInterface::GetApCallbackInst(void) const +const IWifiApMonitorEventCallback &WifiApHalInterface::GetApCallbackInst(int id) const { - return mApCallback; + auto iter = mApCallback.find(id); + if (iter != mApCallback.end()) { + return iter->second; + } + return g_cb; +} + +WifiErrorNo WifiApHalInterface::GetPowerModel(int& model, int id) const +{ + CHECK_NULL_AND_RETURN(mIdlClient, WIFI_IDL_OPT_FAILED); + return mIdlClient->ReqGetPowerModel(model, id); +} + +WifiErrorNo WifiApHalInterface::SetPowerModel(const int& model, int id) const +{ + CHECK_NULL_AND_RETURN(mIdlClient, WIFI_IDL_OPT_FAILED); + return mIdlClient->ReqSetPowerModel(model, id); } } // namespace Wifi } // namespace OHOS \ No newline at end of file diff --git a/services/wifi_standard/wifi_framework/wifi_manage/idl_client/wifi_ap_hal_interface.h b/wifi/services/wifi_standard/wifi_framework/wifi_manage/idl_client/wifi_ap_hal_interface.h similarity index 74% rename from services/wifi_standard/wifi_framework/wifi_manage/idl_client/wifi_ap_hal_interface.h rename to wifi/services/wifi_standard/wifi_framework/wifi_manage/idl_client/wifi_ap_hal_interface.h index b46c6788bd95a6e8bafb06d6eadca30fbd9ac2bb..d31c3724f49042e6a89858149dd28fe37a0be953 100644 --- a/services/wifi_standard/wifi_framework/wifi_manage/idl_client/wifi_ap_hal_interface.h +++ b/wifi/services/wifi_standard/wifi_framework/wifi_manage/idl_client/wifi_ap_hal_interface.h @@ -38,14 +38,14 @@ public: * * @return WifiErrorNo */ - virtual WifiErrorNo StartAp(void); + virtual WifiErrorNo StartAp(int id = 0); /** * @Description Close Ap. * * @return WifiErrorNo */ - virtual WifiErrorNo StopAp(void); + virtual WifiErrorNo StopAp(int id = 0); /** * @Description Setting SoftAP Configurations. @@ -53,7 +53,7 @@ public: * @param config * @return WifiErrorNo */ - WifiErrorNo SetSoftApConfig(const HotspotConfig &config); + WifiErrorNo SetSoftApConfig(const HotspotConfig &config, int id = 0); /** * @Description Obtains information about all connected STAs. @@ -61,7 +61,7 @@ public: * @param result - Returns the obtained STA information list. * @return WifiErrorNo */ - WifiErrorNo GetStationList(std::vector &result); + WifiErrorNo GetStationList(std::vector &result, int id = 0); /** * @Description To set the blocklist filtering in AP mode to prohibit @@ -70,7 +70,7 @@ public: * @param mac - Blocklisted address. * @return WifiErrorNo */ - WifiErrorNo AddBlockByMac(const std::string &mac); + WifiErrorNo AddBlockByMac(const std::string &mac, int id = 0); /** * @Description To set blocklist filtering in AP mode and delete a @@ -79,7 +79,7 @@ public: * @param mac - Blocklisted address. * @return WifiErrorNo */ - WifiErrorNo DelBlockByMac(const std::string &mac); + WifiErrorNo DelBlockByMac(const std::string &mac, int id = 0); /** * @Description Disconnect the STA with a specified MAC address. @@ -87,7 +87,7 @@ public: * @param mac - Address information. * @return WifiErrorNo */ - WifiErrorNo RemoveStation(const std::string &mac); + WifiErrorNo RemoveStation(const std::string &mac, int id = 0); /** * @Description Obtains the hotspot frequency supported by a @@ -97,7 +97,7 @@ public: * @param frequencies - Frequency list. * @return WifiErrorNo */ - WifiErrorNo GetFrequenciesByBand(int band, std::vector &frequencies); + WifiErrorNo GetFrequenciesByBand(int band, std::vector &frequencies, int id = 0); /** * @Description Listening to Wi-Fi disconnection or connection events @@ -107,7 +107,7 @@ public: * registration events. * @return WifiErrorNo */ - WifiErrorNo RegisterApEvent(IWifiApMonitorEventCallback callback); + WifiErrorNo RegisterApEvent(IWifiApMonitorEventCallback callback, int id = 0); /** * @Description Sets the Wi-Fi country code. @@ -115,7 +115,7 @@ public: * @param code * @return WifiErrorNo */ - WifiErrorNo SetWifiCountryCode(const std::string &code); + WifiErrorNo SetWifiCountryCode(const std::string &code, int id = 0); /** * @Description Disconnect STAs based on MAC addresses. @@ -123,17 +123,33 @@ public: * @param mac * @return WifiErrorNo */ - WifiErrorNo DisconnectStaByMac(const std::string &mac); + WifiErrorNo DisconnectStaByMac(const std::string &mac, int id = 0); /** * @Description Get the Ap Callback Inst object * * @return const IWifiApMonitorEventCallback& - register ap callback objects */ - const IWifiApMonitorEventCallback &GetApCallbackInst(void) const; + const IWifiApMonitorEventCallback &GetApCallbackInst(int id = 0) const; + + /** + * @Description Get power mode. + * + * @param model + * @return WifiErrorNo + */ + WifiErrorNo GetPowerModel(int& model, int id = 0) const; + + /** + * @Description Set power mode. + * + * @param model + * @return WifiErrorNo + */ + WifiErrorNo SetPowerModel(const int& model, int id = 0) const; private: - IWifiApMonitorEventCallback mApCallback; + std::map mApCallback; }; } // namespace Wifi } // namespace OHOS diff --git a/services/wifi_standard/wifi_framework/wifi_manage/idl_client/wifi_base_hal_interface.cpp b/wifi/services/wifi_standard/wifi_framework/wifi_manage/idl_client/wifi_base_hal_interface.cpp similarity index 95% rename from services/wifi_standard/wifi_framework/wifi_manage/idl_client/wifi_base_hal_interface.cpp rename to wifi/services/wifi_standard/wifi_framework/wifi_manage/idl_client/wifi_base_hal_interface.cpp index 102f1ea2454e2f78cd086f688a79424277d9cfc9..1f4b5d078fb2e423f102621072259488ce269c63 100644 --- a/services/wifi_standard/wifi_framework/wifi_manage/idl_client/wifi_base_hal_interface.cpp +++ b/wifi/services/wifi_standard/wifi_framework/wifi_manage/idl_client/wifi_base_hal_interface.cpp @@ -30,6 +30,7 @@ WifiBaseHalInterface::~WifiBaseHalInterface() { if (mIdlClient != nullptr) { delete mIdlClient; + mIdlClient = nullptr; } } @@ -51,6 +52,7 @@ bool WifiBaseHalInterface::InitIdlClient(void) void WifiBaseHalInterface::ExitAllIdlClient(void) { + LOGI("Exit all idl client!"); if (mIdlClient != nullptr) { mIdlClient->ExitAllClient(); } diff --git a/services/wifi_standard/wifi_framework/wifi_manage/idl_client/wifi_base_hal_interface.h b/wifi/services/wifi_standard/wifi_framework/wifi_manage/idl_client/wifi_base_hal_interface.h similarity index 100% rename from services/wifi_standard/wifi_framework/wifi_manage/idl_client/wifi_base_hal_interface.h rename to wifi/services/wifi_standard/wifi_framework/wifi_manage/idl_client/wifi_base_hal_interface.h diff --git a/services/wifi_standard/wifi_framework/wifi_manage/idl_client/wifi_chip_event_callback.h b/wifi/services/wifi_standard/wifi_framework/wifi_manage/idl_client/wifi_chip_event_callback.h similarity index 100% rename from services/wifi_standard/wifi_framework/wifi_manage/idl_client/wifi_chip_event_callback.h rename to wifi/services/wifi_standard/wifi_framework/wifi_manage/idl_client/wifi_chip_event_callback.h diff --git a/services/wifi_standard/wifi_framework/wifi_manage/idl_client/wifi_chip_hal_interface.cpp b/wifi/services/wifi_standard/wifi_framework/wifi_manage/idl_client/wifi_chip_hal_interface.cpp similarity index 59% rename from services/wifi_standard/wifi_framework/wifi_manage/idl_client/wifi_chip_hal_interface.cpp rename to wifi/services/wifi_standard/wifi_framework/wifi_manage/idl_client/wifi_chip_hal_interface.cpp index 47a32d9061f9ef99fff1cc516009618d8ec7bb17..bae6284ba482bc382e2c9bc9f8698bace0641702 100644 --- a/services/wifi_standard/wifi_framework/wifi_manage/idl_client/wifi_chip_hal_interface.cpp +++ b/wifi/services/wifi_standard/wifi_framework/wifi_manage/idl_client/wifi_chip_hal_interface.cpp @@ -1,5 +1,5 @@ /* - * Copyright (C) 2021 Huawei Device Co., Ltd. + * Copyright (C) 2021-2022 Huawei Device Co., Ltd. * 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 @@ -39,52 +39,86 @@ WifiChipHalInterface &WifiChipHalInterface::GetInstance(void) WifiErrorNo WifiChipHalInterface::GetWifiChipObject(int id, IWifiChip &chip) { + CHECK_NULL_AND_RETURN(mIdlClient, WIFI_IDL_OPT_FAILED); return mIdlClient->GetWifiChipObject(id, chip); } WifiErrorNo WifiChipHalInterface::GetChipIds(std::vector &ids) { + CHECK_NULL_AND_RETURN(mIdlClient, WIFI_IDL_OPT_FAILED); return mIdlClient->GetChipIds(ids); } WifiErrorNo WifiChipHalInterface::GetUsedChipId(int &id) { + CHECK_NULL_AND_RETURN(mIdlClient, WIFI_IDL_OPT_FAILED); return mIdlClient->GetUsedChipId(id); } WifiErrorNo WifiChipHalInterface::GetChipCapabilities(int &capabilities) { + CHECK_NULL_AND_RETURN(mIdlClient, WIFI_IDL_OPT_FAILED); return mIdlClient->GetChipCapabilities(capabilities); } WifiErrorNo WifiChipHalInterface::GetSupportedModes(std::vector &modes) { + CHECK_NULL_AND_RETURN(mIdlClient, WIFI_IDL_OPT_FAILED); return mIdlClient->GetSupportedModes(modes); } WifiErrorNo WifiChipHalInterface::ConfigRunModes(int mode) { + CHECK_NULL_AND_RETURN(mIdlClient, WIFI_IDL_OPT_FAILED); return mIdlClient->ConfigRunModes(mode); } WifiErrorNo WifiChipHalInterface::GetCurrentMode(int &mode) { + CHECK_NULL_AND_RETURN(mIdlClient, WIFI_IDL_OPT_FAILED); return mIdlClient->GetCurrentMode(mode); } WifiErrorNo WifiChipHalInterface::RegisterChipEventCallback(WifiChipEventCallback &callback) { + CHECK_NULL_AND_RETURN(mIdlClient, WIFI_IDL_OPT_FAILED); return mIdlClient->RegisterChipEventCallback(callback); } WifiErrorNo WifiChipHalInterface::RequestFirmwareDebugInfo(std::string &debugInfo) { + CHECK_NULL_AND_RETURN(mIdlClient, WIFI_IDL_OPT_FAILED); return mIdlClient->RequestFirmwareDebugInfo(debugInfo); } -WifiErrorNo WifiChipHalInterface::SetWifiPowerMode(int mode) +WifiErrorNo WifiChipHalInterface::IsSupportDbdc(bool &isSupport) const { - return mIdlClient->SetWifiPowerMode(mode); + CHECK_NULL_AND_RETURN(mIdlClient, WIFI_IDL_OPT_FAILED); + return mIdlClient->ReqIsSupportDbdc(isSupport); +} + +WifiErrorNo WifiChipHalInterface::IsSupportCsa(bool &isSupport) const +{ + CHECK_NULL_AND_RETURN(mIdlClient, WIFI_IDL_OPT_FAILED); + return mIdlClient->ReqIsSupportCsa(isSupport); +} + +WifiErrorNo WifiChipHalInterface::IsSupportRadarDetect(bool &isSupport) const +{ + CHECK_NULL_AND_RETURN(mIdlClient, WIFI_IDL_OPT_FAILED); + return mIdlClient->ReqIsSupportRadarDetect(isSupport); +} + +WifiErrorNo WifiChipHalInterface::IsSupportDfsChannel(bool &isSupport) const +{ + CHECK_NULL_AND_RETURN(mIdlClient, WIFI_IDL_OPT_FAILED); + return mIdlClient->ReqIsSupportDfsChannel(isSupport); +} + +WifiErrorNo WifiChipHalInterface::IsSupportIndoorChannel(bool &isSupport) const +{ + CHECK_NULL_AND_RETURN(mIdlClient, WIFI_IDL_OPT_FAILED); + return mIdlClient->ReqIsSupportIndoorChannel(isSupport); } } // namespace Wifi } // namespace OHOS \ No newline at end of file diff --git a/services/wifi_standard/wifi_framework/wifi_manage/idl_client/wifi_chip_hal_interface.h b/wifi/services/wifi_standard/wifi_framework/wifi_manage/idl_client/wifi_chip_hal_interface.h similarity index 78% rename from services/wifi_standard/wifi_framework/wifi_manage/idl_client/wifi_chip_hal_interface.h rename to wifi/services/wifi_standard/wifi_framework/wifi_manage/idl_client/wifi_chip_hal_interface.h index 0da3666c66c74eb332e093f778bcc6657925d5fe..a36e0f210c779160377feab5b155e91645cb4e07 100644 --- a/services/wifi_standard/wifi_framework/wifi_manage/idl_client/wifi_chip_hal_interface.h +++ b/wifi/services/wifi_standard/wifi_framework/wifi_manage/idl_client/wifi_chip_hal_interface.h @@ -109,12 +109,44 @@ public: WifiErrorNo RequestFirmwareDebugInfo(std::string &debugInfo); /** - * @Description Setting the Power Mode. + * @Description is support DBDC * - * @param mode + * @param isSupport + * @return WifiErrorNo + */ + WifiErrorNo IsSupportDbdc(bool &isSupport) const; + + /** + * @Description is support CSA + * + * @param isSupport + * @return WifiErrorNo + */ + WifiErrorNo IsSupportCsa(bool &isSupport) const; + + /** + * @Description is support radar detection + * + * @param isSupport + * @return WifiErrorNo + */ + WifiErrorNo IsSupportRadarDetect(bool &isSupport) const; + + /** + * @Description is support DFS channel + * + * @param isSupport + * @return WifiErrorNo + */ + WifiErrorNo IsSupportDfsChannel(bool &isSupport) const; + + /** + * @Description is support indoor channel + * + * @param isSupport * @return WifiErrorNo */ - WifiErrorNo SetWifiPowerMode(int mode); + WifiErrorNo IsSupportIndoorChannel(bool &isSupport) const; }; } // namespace Wifi } // namespace OHOS diff --git a/services/wifi_standard/wifi_framework/wifi_manage/idl_client/wifi_error_no.h b/wifi/services/wifi_standard/wifi_framework/wifi_manage/idl_client/wifi_error_no.h similarity index 100% rename from services/wifi_standard/wifi_framework/wifi_manage/idl_client/wifi_error_no.h rename to wifi/services/wifi_standard/wifi_framework/wifi_manage/idl_client/wifi_error_no.h diff --git a/services/wifi_standard/wifi_framework/wifi_manage/idl_client/wifi_event_callback.h b/wifi/services/wifi_standard/wifi_framework/wifi_manage/idl_client/wifi_event_callback.h similarity index 85% rename from services/wifi_standard/wifi_framework/wifi_manage/idl_client/wifi_event_callback.h rename to wifi/services/wifi_standard/wifi_framework/wifi_manage/idl_client/wifi_event_callback.h index 6a5c9be85114f401812645dae1c899d1df490717..935dadf8d6b24768c55243b0ccc1085eecfb9012 100644 --- a/services/wifi_standard/wifi_framework/wifi_manage/idl_client/wifi_event_callback.h +++ b/wifi/services/wifi_standard/wifi_framework/wifi_manage/idl_client/wifi_event_callback.h @@ -22,10 +22,13 @@ namespace OHOS { namespace Wifi { struct WifiEventCallback { std::function onConnectChanged; + std::function onBssidChanged; std::function onWpaStateChanged; std::function onWpaSsidWrongKey; std::function onWpsOverlap; std::function onWpsTimeOut; + std::function onWpaConnectionFull; + std::function onWpaConnectionReject; }; } // namespace Wifi } // namespace OHOS diff --git a/services/wifi_standard/wifi_framework/wifi_manage/idl_client/wifi_idl_client.cpp b/wifi/services/wifi_standard/wifi_framework/wifi_manage/idl_client/wifi_idl_client.cpp similarity index 86% rename from services/wifi_standard/wifi_framework/wifi_manage/idl_client/wifi_idl_client.cpp rename to wifi/services/wifi_standard/wifi_framework/wifi_manage/idl_client/wifi_idl_client.cpp index e1dfabd96a2f17606d2c3aa10ba64eba9e6186cf..54b9805f556684e2e24e1e654abc5fced435aa6f 100644 --- a/services/wifi_standard/wifi_framework/wifi_manage/idl_client/wifi_idl_client.cpp +++ b/wifi/services/wifi_standard/wifi_framework/wifi_manage/idl_client/wifi_idl_client.cpp @@ -1,5 +1,5 @@ /* - * Copyright (C) 2021 Huawei Device Co., Ltd. + * Copyright (C) 2021-2022 Huawei Device Co., Ltd. * 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 @@ -12,6 +12,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + #include "wifi_idl_client.h" #include #include "wifi_global_func.h" @@ -55,7 +56,7 @@ WifiIdlClient::~WifiIdlClient() int WifiIdlClient::InitClient(void) { - const std::string idlSockPath = "/data/misc/wifi/unix_sock.sock"; + const std::string idlSockPath = CONFIG_ROOR_DIR"/unix_sock.sock"; pRpcClient = CreateRpcClient(idlSockPath.c_str()); if (pRpcClient == nullptr) { LOGE("init rpc client failed!"); @@ -66,6 +67,7 @@ int WifiIdlClient::InitClient(void) void WifiIdlClient::ExitAllClient(void) { + LOGI("Exit all client!"); if (pRpcClient == nullptr) { return; } @@ -233,12 +235,15 @@ WifiErrorNo WifiIdlClient::Scan(const WifiScanParam &scanParam) } if (settings.freqs != nullptr) { free(settings.freqs); + settings.freqs = nullptr; } if (settings.hiddenSsid != nullptr) { for (int i = 0; i < settings.hiddenSsidSize; ++i) { free(settings.hiddenSsid[i]); + settings.hiddenSsid[i] = nullptr; } free(settings.hiddenSsid); + settings.hiddenSsid = nullptr; } return err; } @@ -246,7 +251,7 @@ WifiErrorNo WifiIdlClient::Scan(const WifiScanParam &scanParam) WifiErrorNo WifiIdlClient::ReqGetNetworkList(std::vector &networkList) { CHECK_CLIENT_NOT_NULL; - HidlNetworkInfo infos[WIFI_IDL_GET_MAX_NETWORK_LIST]; + WifiNetworkInfo infos[WIFI_IDL_GET_MAX_NETWORK_LIST]; if (memset_s(infos, sizeof(infos), 0, sizeof(infos)) != EOK) { return WIFI_IDL_OPT_FAILED; } @@ -282,10 +287,28 @@ WifiErrorNo WifiIdlClient::QueryScanInfos(std::vector &scanInfos) tmp.rssi = results[i].signalLevel; tmp.timestamp = results[i].timestamp; tmp.capabilities = results[i].capability; + tmp.channelWidth = (WifiChannelWidth)results[i].channelWidth; + tmp.centerFrequency0 = results[i].centerFrequency0; + tmp.centerFrequency1 = results[i].centerFrequency1; + for (int j = 0; j < results[i].ieSize; ++j) { + WifiInfoElem infoElemTmp; + int infoElemSize = results[i].infoElems[j].size; + infoElemTmp.id = results[i].infoElems[j].id; + for (int k = 0; k < infoElemSize; ++k) { + infoElemTmp.content.emplace_back(results[i].infoElems[j].content[k]); + } + if (results[i].infoElems[j].content) { + free(results[i].infoElems[j].content); + } + tmp.infoElems.emplace_back(infoElemTmp); + } + if (results[i].infoElems) { + free(results[i].infoElems); + } scanInfos.emplace_back(tmp); } free(results); - results = NULL; + results = nullptr; return WIFI_IDL_OPT_OK; } @@ -336,18 +359,23 @@ WifiErrorNo WifiIdlClient::ReqStartPnoScan(const WifiPnoScanParam &scanParam) } if (settings.freqs != nullptr) { free(settings.freqs); + settings.freqs = nullptr; } if (settings.hiddenSsid != nullptr) { for (int i = 0; i < settings.hiddenSsidSize; ++i) { free(settings.hiddenSsid[i]); + settings.hiddenSsid[i] = nullptr; } free(settings.hiddenSsid); + settings.hiddenSsid = nullptr; } if (settings.savedSsid != nullptr) { for (int i = 0; i < settings.savedSsidSize; ++i) { free(settings.savedSsid[i]); + settings.savedSsid[i] = nullptr; } free(settings.savedSsid); + settings.savedSsid = nullptr; } return err; } @@ -394,7 +422,7 @@ WifiErrorNo WifiIdlClient::ReqDisableNetwork(int networkId) WifiErrorNo WifiIdlClient::GetDeviceConfig(WifiIdlGetDeviceConfig &config) { CHECK_CLIENT_NOT_NULL; - HidlGetNetworkConfig conf; + GetNetworkConfig conf; if (memset_s(&conf, sizeof(conf), 0, sizeof(conf)) != EOK) { return WIFI_IDL_OPT_FAILED; } @@ -411,7 +439,7 @@ WifiErrorNo WifiIdlClient::GetDeviceConfig(WifiIdlGetDeviceConfig &config) } int WifiIdlClient::PushDeviceConfigString( - HidlSetNetworkConfig *pConfig, DeviceConfigType type, const std::string &msg) const + SetNetworkConfig *pConfig, DeviceConfigType type, const std::string &msg) const { if (msg.length() > 0) { pConfig->cfgParam = type; @@ -424,7 +452,7 @@ int WifiIdlClient::PushDeviceConfigString( } } -int WifiIdlClient::PushDeviceConfigInt(HidlSetNetworkConfig *pConfig, DeviceConfigType type, int i) const +int WifiIdlClient::PushDeviceConfigInt(SetNetworkConfig *pConfig, DeviceConfigType type, int i) const { pConfig->cfgParam = type; if (snprintf_s(pConfig->cfgValue, sizeof(pConfig->cfgValue), sizeof(pConfig->cfgValue) - 1, "%d", i) < 0) { @@ -434,7 +462,7 @@ int WifiIdlClient::PushDeviceConfigInt(HidlSetNetworkConfig *pConfig, DeviceConf } int WifiIdlClient::PushDeviceConfigAuthAlgorithm( - HidlSetNetworkConfig *pConfig, DeviceConfigType type, unsigned int alg) const + SetNetworkConfig *pConfig, DeviceConfigType type, unsigned int alg) const { pConfig->cfgParam = type; if (alg & 0x1) { @@ -443,7 +471,7 @@ int WifiIdlClient::PushDeviceConfigAuthAlgorithm( } } if (alg & 0x2) { - if (strcat_s(pConfig->cfgValue, sizeof(pConfig->cfgValue), "SHARED ") != EOK) { + if (strcat_s(pConfig->cfgValue, sizeof(pConfig->cfgValue), "OPEN SHARED ") != EOK) { return 0; } } @@ -472,19 +500,27 @@ WifiErrorNo WifiIdlClient::SetDeviceConfig(int networkId, const WifiIdlDeviceCon { CHECK_CLIENT_NOT_NULL; if (CheckValidDeviceConfig(config) != WIFI_IDL_OPT_OK) { + LOGE("SetDeviceConfig, CheckValidDeviceConfig return error!"); return WIFI_IDL_OPT_FAILED; } - HidlSetNetworkConfig conf[DEVICE_CONFIG_END_POS]; + SetNetworkConfig conf[DEVICE_CONFIG_END_POS]; if (memset_s(conf, sizeof(conf), 0, sizeof(conf)) != EOK) { + LOGE("SetDeviceConfig, memset_s return error!"); return WIFI_IDL_OPT_FAILED; } int num = 0; num += PushDeviceConfigString(conf + num, DEVICE_CONFIG_SSID, config.ssid); num += PushDeviceConfigString(conf + num, DEVICE_CONFIG_PSK, config.psk); - num += PushDeviceConfigString(conf + num, DEVICE_CONFIG_KEYMGMT, config.keyMgmt); + if (config.keyMgmt == KEY_MGMT_NONE || config.keyMgmt == KEY_MGMT_WEP) { + num += PushDeviceConfigString(conf + num, DEVICE_CONFIG_KEYMGMT, KEY_MGMT_NONE); + } else { + num += PushDeviceConfigString(conf + num, DEVICE_CONFIG_KEYMGMT, config.keyMgmt); + } num += PushDeviceConfigString(conf + num, DEVICE_CONFIG_EAP, config.eap); num += PushDeviceConfigString(conf + num, DEVICE_CONFIG_IDENTITY, config.identity); num += PushDeviceConfigString(conf + num, DEVICE_CONFIG_PASSWORD, config.password); + num += PushDeviceConfigString(conf + num, DEVICE_CONFIG_EAP_CLIENT_CERT, config.clientCert); + num += PushDeviceConfigString(conf + num, DEVICE_CONFIG_EAP_PRIVATE_KEY, config.privateKey); num += PushDeviceConfigString(conf + num, DEVICE_CONFIG_BSSID, config.bssid); int i = 0; num += PushDeviceConfigString(conf + num, DEVICE_CONFIG_WEP_KEY_0, config.wepKeys[i++]); @@ -503,12 +539,29 @@ WifiErrorNo WifiIdlClient::SetDeviceConfig(int networkId, const WifiIdlDeviceCon if (config.authAlgorithms > 0) { num += PushDeviceConfigAuthAlgorithm(conf + num, DEVICE_CONFIG_AUTH_ALGORITHMS, config.authAlgorithms); } + if (config.phase2Method != static_cast(Phase2Method::NONE)) { + std::string strPhase2Method = WifiEapConfig::Phase2MethodToStr(config.eap, config.phase2Method); + num += PushDeviceConfigString(conf + num, DEVICE_CONFIG_EAP_PHASE2METHOD, strPhase2Method); + } if (num == 0) { return WIFI_IDL_OPT_OK; } return SetNetwork(networkId, conf, num); } +WifiErrorNo WifiIdlClient::SetWpsBssid(int networkId, const std::string &bssid) +{ + CHECK_CLIENT_NOT_NULL; + SetNetworkConfig conf; + int num = PushDeviceConfigString(&conf, DEVICE_CONFIG_BSSID, bssid); + if (num == 0) { + LOGE("SetWpsBssid, PushDeviceConfigString return error!"); + return WIFI_IDL_OPT_OK; + } + + return SetNetwork(networkId, &conf, num); +} + WifiErrorNo WifiIdlClient::SaveDeviceConfig(void) { CHECK_CLIENT_NOT_NULL; @@ -524,10 +577,13 @@ WifiErrorNo WifiIdlClient::ReqRegisterStaEventCallback(const WifiEventCallback & } if (callback.onConnectChanged != nullptr) { cEventCallback.onConnectChanged = OnConnectChanged; + cEventCallback.onBssidChanged = OnBssidChanged; cEventCallback.onWpaStateChanged = OnWpaStateChanged; cEventCallback.onSsidWrongkey = OnWpaSsidWrongKey; cEventCallback.onWpsOverlap = OnWpsOverlap; cEventCallback.onWpsTimeOut = OnWpsTimeOut; + cEventCallback.onWpsConnectionFull = OnWpaConnectionFull; + cEventCallback.onWpsConnectionReject = OnWpaConnectionReject; } return RegisterStaEventCallback(cEventCallback); } @@ -614,6 +670,7 @@ char **WifiIdlClient::ConVectorToCArrayString(const std::vector &ve free(list[j]); } free(list); + list = nullptr; return nullptr; } else { return list; @@ -649,14 +706,18 @@ WifiErrorNo WifiIdlClient::ReqSetRoamConfig(const WifiIdlRoamConfig &config) if (blocklist != nullptr) { for (int i = 0; i < blocksize; ++i) { free(blocklist[i]); + blocklist[i] = nullptr; } free(blocklist); + blocklist = nullptr; } if (trustlist != nullptr) { for (int i = 0; i < trustsize; ++i) { free(trustlist[i]); + trustlist[i] = nullptr; } free(trustlist); + trustlist = nullptr; } return err; } @@ -664,7 +725,7 @@ WifiErrorNo WifiIdlClient::ReqSetRoamConfig(const WifiIdlRoamConfig &config) WifiErrorNo WifiIdlClient::ReqGetConnectSignalInfo(const std::string &endBssid, WifiWpaSignalInfo &info) const { CHECK_CLIENT_NOT_NULL; - HidlWpaSignalInfo req = {0}; + WpaSignalInfo req = {0}; WifiErrorNo err = GetConnectSignalInfo(endBssid.c_str(), &req); if (err == WIFI_IDL_OPT_OK) { info.signal = req.signal; @@ -676,19 +737,19 @@ WifiErrorNo WifiIdlClient::ReqGetConnectSignalInfo(const std::string &endBssid, return err; } -WifiErrorNo WifiIdlClient::StartAp(void) +WifiErrorNo WifiIdlClient::StartAp(int id) { CHECK_CLIENT_NOT_NULL; - return StartSoftAp(); + return StartSoftAp(id); } -WifiErrorNo WifiIdlClient::StopAp(void) +WifiErrorNo WifiIdlClient::StopAp(int id) { CHECK_CLIENT_NOT_NULL; - return StopSoftAp(); + return StopSoftAp(id); } -WifiErrorNo WifiIdlClient::SetSoftApConfig(const HotspotConfig &config) +WifiErrorNo WifiIdlClient::SetSoftApConfig(const HotspotConfig &config, int id) { CHECK_CLIENT_NOT_NULL; HostapdConfig tmp; @@ -708,10 +769,10 @@ WifiErrorNo WifiIdlClient::SetSoftApConfig(const HotspotConfig &config) tmp.band = static_cast(config.GetBand()); tmp.channel = config.GetChannel(); tmp.maxConn = config.GetMaxConn(); - return SetHostapdConfig(&tmp); + return SetHostapdConfig(&tmp, id); } -WifiErrorNo WifiIdlClient::GetStationList(std::vector &result) +WifiErrorNo WifiIdlClient::GetStationList(std::vector &result, int id) { CHECK_CLIENT_NOT_NULL; @@ -720,7 +781,7 @@ WifiErrorNo WifiIdlClient::GetStationList(std::vector &result) return WIFI_IDL_OPT_FAILED; } int32_t size = BUFFER_SIZE; - WifiErrorNo err = GetStaInfos(staInfos, &size); + WifiErrorNo err = GetStaInfos(staInfos, &size, id); if (err != WIFI_IDL_OPT_OK) { delete[] staInfos; return WIFI_IDL_OPT_FAILED; @@ -731,43 +792,43 @@ WifiErrorNo WifiIdlClient::GetStationList(std::vector &result) return WIFI_IDL_OPT_OK; } -WifiErrorNo WifiIdlClient::AddBlockByMac(const std::string &mac) +WifiErrorNo WifiIdlClient::AddBlockByMac(const std::string &mac, int id) { CHECK_CLIENT_NOT_NULL; if (CheckMacIsValid(mac) != 0) { return WIFI_IDL_OPT_INPUT_MAC_INVALID; } int len = mac.length(); - return SetMacFilter((unsigned char *)mac.c_str(), len); + return SetMacFilter((unsigned char *)mac.c_str(), len, id); } -WifiErrorNo WifiIdlClient::DelBlockByMac(const std::string &mac) +WifiErrorNo WifiIdlClient::DelBlockByMac(const std::string &mac, int id) { CHECK_CLIENT_NOT_NULL; if (CheckMacIsValid(mac) != 0) { return WIFI_IDL_OPT_INPUT_MAC_INVALID; } int len = mac.length(); - return DelMacFilter((unsigned char *)mac.c_str(), len); + return DelMacFilter((unsigned char *)mac.c_str(), len, id); } -WifiErrorNo WifiIdlClient::RemoveStation(const std::string &mac) +WifiErrorNo WifiIdlClient::RemoveStation(const std::string &mac, int id) { CHECK_CLIENT_NOT_NULL; if (CheckMacIsValid(mac) != 0) { return WIFI_IDL_OPT_INPUT_MAC_INVALID; } int len = mac.length(); - return DisassociateSta((unsigned char *)mac.c_str(), len); + return DisassociateSta((unsigned char *)mac.c_str(), len, id); } -WifiErrorNo WifiIdlClient::GetFrequenciesByBand(int32_t band, std::vector &frequencies) +WifiErrorNo WifiIdlClient::GetFrequenciesByBand(int32_t band, std::vector &frequencies, int id) { CHECK_CLIENT_NOT_NULL; int values[WIFI_IDL_GET_MAX_BANDS] = {0}; int size = WIFI_IDL_GET_MAX_BANDS; - if (GetValidFrequenciesForBand(band, values, &size) != 0) { + if (GetValidFrequenciesForBand(band, values, &size, id) != 0) { return WIFI_IDL_OPT_FAILED; } @@ -778,7 +839,7 @@ WifiErrorNo WifiIdlClient::GetFrequenciesByBand(int32_t band, std::vector & return WIFI_IDL_OPT_OK; } -WifiErrorNo WifiIdlClient::RegisterApEvent(IWifiApMonitorEventCallback callback) const +WifiErrorNo WifiIdlClient::RegisterApEvent(IWifiApMonitorEventCallback callback, int id) const { CHECK_CLIENT_NOT_NULL; IWifiApEventCallback cEventCallback; @@ -790,25 +851,37 @@ WifiErrorNo WifiIdlClient::RegisterApEvent(IWifiApMonitorEventCallback callback) cEventCallback.onApEnableOrDisable = OnApEnableOrDisable; } - return RegisterAsscociatedEvent(cEventCallback); + return RegisterAsscociatedEvent(cEventCallback, id); } -WifiErrorNo WifiIdlClient::SetWifiCountryCode(const std::string &code) +WifiErrorNo WifiIdlClient::SetWifiCountryCode(const std::string &code, int id) { CHECK_CLIENT_NOT_NULL; if (code.length() != WIFI_IDL_COUNTRY_CODE_LENGTH) { return WIFI_IDL_OPT_INVALID_PARAM; } - return SetCountryCode(code.c_str()); + return SetCountryCode(code.c_str(), id); } -WifiErrorNo WifiIdlClient::ReqDisconnectStaByMac(const std::string &mac) +WifiErrorNo WifiIdlClient::ReqDisconnectStaByMac(const std::string &mac, int id) { CHECK_CLIENT_NOT_NULL; if (CheckMacIsValid(mac) != 0) { return WIFI_IDL_OPT_INPUT_MAC_INVALID; } - return DisassociateSta((unsigned char *)mac.c_str(), strlen(mac.c_str())); + return DisassociateSta((unsigned char *)mac.c_str(), strlen(mac.c_str()), id); +} + +WifiErrorNo WifiIdlClient::ReqGetPowerModel(int& model, int id) +{ + CHECK_CLIENT_NOT_NULL; + return WpaGetPowerModel(&model, id); +} + +WifiErrorNo WifiIdlClient::ReqSetPowerModel(const int& model, int id) +{ + CHECK_CLIENT_NOT_NULL; + return WpaSetPowerModel(model, id); } WifiErrorNo WifiIdlClient::GetWifiChipObject(int id, IWifiChip &chip) @@ -886,11 +959,34 @@ WifiErrorNo WifiIdlClient::RequestFirmwareDebugInfo(std::string &debugInfo) return WIFI_IDL_OPT_OK; } -WifiErrorNo WifiIdlClient::SetWifiPowerMode(int mode) +WifiErrorNo WifiIdlClient::ReqIsSupportDbdc(bool &isSupport) const { CHECK_CLIENT_NOT_NULL; - LOGD("start SetWifiPowerMode mode %{public}d", mode); - return WIFI_IDL_OPT_OK; + return IsChipSupportDbdc(&isSupport); +} + +WifiErrorNo WifiIdlClient::ReqIsSupportCsa(bool &isSupport) const +{ + CHECK_CLIENT_NOT_NULL; + return IsChipSupportCsa(&isSupport); +} + +WifiErrorNo WifiIdlClient::ReqIsSupportRadarDetect(bool &isSupport) const +{ + CHECK_CLIENT_NOT_NULL; + return IsChipSupportRadarDetect(&isSupport); +} + +WifiErrorNo WifiIdlClient::ReqIsSupportDfsChannel(bool &isSupport) const +{ + CHECK_CLIENT_NOT_NULL; + return IsChipSupportDfsChannel(&isSupport); +} + +WifiErrorNo WifiIdlClient::ReqIsSupportIndoorChannel(bool &isSupport) const +{ + CHECK_CLIENT_NOT_NULL; + return IsChipSupportIndoorChannel(&isSupport); } WifiErrorNo WifiIdlClient::ReqStartSupplicant(void) @@ -1094,6 +1190,7 @@ WifiErrorNo WifiIdlClient::ReqP2pRegisterCallback(const P2pHalCallback &callback cEventCallback.onStaAuthorized = OnP2pStaAuthorized; cEventCallback.connectSupplicantFailed = OnP2pConnectSupplicantFailed; cEventCallback.onP2pServDiscReq = OnP2pServDiscReq; + cEventCallback.onP2pIfaceCreated = OnP2pIfaceCreated; } return RegisterP2pEventCallback(cEventCallback); @@ -1130,7 +1227,7 @@ WifiErrorNo WifiIdlClient::ReqP2pRemoveNetwork(int networkId) const WifiErrorNo WifiIdlClient::ReqP2pListNetworks(std::map &mapGroups) const { CHECK_CLIENT_NOT_NULL; - HidlP2pNetworkList infoList = {0}; + P2pNetworkList infoList = {0}; WifiErrorNo ret = P2pListNetworks(&infoList); if (ret != WIFI_IDL_OPT_OK) { return ret; @@ -1151,6 +1248,7 @@ WifiErrorNo WifiIdlClient::ReqP2pListNetworks(std::map &m mapGroups.insert(std::pair(infoList.infos[i].id, groupInfo)); } free(infoList.infos); + infoList.infos = nullptr; return ret; } @@ -1211,10 +1309,11 @@ WifiErrorNo WifiIdlClient::ReqP2pSetListenChannel(size_t channel, unsigned char return P2pSetListenChannel(channel, regClass); } -WifiErrorNo WifiIdlClient::ReqP2pConnect(const WifiP2pConfig &config, bool isJoinExistingGroup, std::string &pin) const +WifiErrorNo WifiIdlClient::ReqP2pConnect(const WifiP2pConfigInternal &config, bool isJoinExistingGroup, + std::string &pin) const { CHECK_CLIENT_NOT_NULL; - HidlP2pConnectInfo info = {0}; + P2pConnectInfo info = {0}; info.mode = isJoinExistingGroup; info.persistent = config.GetNetId(); if (isJoinExistingGroup) { @@ -1257,7 +1356,7 @@ WifiErrorNo WifiIdlClient::ReqP2pCancelConnect() const return P2pCancelConnect(); } -WifiErrorNo WifiIdlClient::ReqP2pProvisionDiscovery(const WifiP2pConfig &config) const +WifiErrorNo WifiIdlClient::ReqP2pProvisionDiscovery(const WifiP2pConfigInternal &config) const { CHECK_CLIENT_NOT_NULL; WpsMethod mode = config.GetWpsInfo().GetWpsMethod(); @@ -1316,7 +1415,7 @@ WifiErrorNo WifiIdlClient::ReqP2pAddService(const WifiP2pServiceInfo &info) cons { CHECK_CLIENT_NOT_NULL; WifiErrorNo ret = WIFI_IDL_OPT_OK; - HidlP2pServiceInfo servInfo = {0}; + P2pServiceInfo servInfo = {0}; std::vector queryList = info.GetQueryList(); for (auto iter = queryList.begin(); iter != queryList.end(); iter++) { std::vector vec; @@ -1356,7 +1455,7 @@ WifiErrorNo WifiIdlClient::ReqP2pRemoveService(const WifiP2pServiceInfo &info) c { CHECK_CLIENT_NOT_NULL; WifiErrorNo ret = WIFI_IDL_OPT_OK; - HidlP2pServiceInfo servInfo = {0}; + P2pServiceInfo servInfo = {0}; std::vector queryList = info.GetQueryList(); for (auto iter = queryList.begin(); iter != queryList.end(); iter++) { std::vector vec; @@ -1402,6 +1501,7 @@ WifiErrorNo WifiIdlClient::ReqP2pReqServiceDiscovery( char *pTlvs = (char *)calloc(size, sizeof(char)); if (pTlvs == nullptr || Val2HexChar(tlvs, pTlvs, size) < 0) { free(pTlvs); + pTlvs = nullptr; return WIFI_IDL_OPT_FAILED; } char retBuf[WIFI_IDL_P2P_TMP_BUFFER_SIZE_128] = {0}; @@ -1410,6 +1510,7 @@ WifiErrorNo WifiIdlClient::ReqP2pReqServiceDiscovery( reqID = retBuf; } free(pTlvs); + pTlvs = nullptr; return ret; } @@ -1448,11 +1549,15 @@ WifiErrorNo WifiIdlClient::ReqRespServiceDiscovery( unsigned size = (tlvs.size() << 1) + 1; char *pTlvs = (char *)calloc(size, sizeof(char)); if (pTlvs == nullptr || Val2HexChar(tlvs, pTlvs, size) < 0) { - free(pTlvs); + if (pTlvs != nullptr) { + free(pTlvs); + pTlvs = nullptr; + } return WIFI_IDL_OPT_FAILED; } WifiErrorNo ret = P2pRespServerDiscovery(device.GetDeviceAddress().c_str(), frequency, dialogToken, pTlvs); free(pTlvs); + pTlvs = nullptr; return ret; } @@ -1465,7 +1570,7 @@ WifiErrorNo WifiIdlClient::ReqSetServiceDiscoveryExternal(bool isExternalProcess WifiErrorNo WifiIdlClient::ReqGetP2pPeer(const std::string &deviceAddress, WifiP2pDevice &device) const { CHECK_CLIENT_NOT_NULL; - HidlP2pDeviceInfo peerInfo; + P2pDeviceInfo peerInfo; if (memset_s(&peerInfo, sizeof(peerInfo), 0, sizeof(peerInfo)) != EOK) { return WIFI_IDL_OPT_FAILED; } @@ -1477,6 +1582,7 @@ WifiErrorNo WifiIdlClient::ReqGetP2pPeer(const std::string &deviceAddress, WifiP device.SetWpsConfigMethod(peerInfo.configMethods); device.SetDeviceCapabilitys(peerInfo.deviceCapabilities); device.SetGroupCapabilitys(peerInfo.groupCapabilities); + device.SetNetworkName(peerInfo.operSsid); } return ret; } @@ -1499,7 +1605,7 @@ WifiErrorNo WifiIdlClient::ReqP2pGetSupportFrequencies(int band, std::vector 0) { pConfig->cfgParam = type; @@ -1512,7 +1618,7 @@ int WifiIdlClient::PushP2pGroupConfigString( } } -int WifiIdlClient::PushP2pGroupConfigInt(HidlP2pGroupConfig *pConfig, P2pGroupConfigType type, int i) const +int WifiIdlClient::PushP2pGroupConfigInt(P2pGroupConfig *pConfig, P2pGroupConfigType type, int i) const { pConfig->cfgParam = type; if (snprintf_s(pConfig->cfgValue, sizeof(pConfig->cfgValue), sizeof(pConfig->cfgValue) - 1, "%d", i) < 0) { @@ -1524,7 +1630,7 @@ int WifiIdlClient::PushP2pGroupConfigInt(HidlP2pGroupConfig *pConfig, P2pGroupCo WifiErrorNo WifiIdlClient::ReqP2pSetGroupConfig(int networkId, const IdlP2pGroupConfig &config) const { CHECK_CLIENT_NOT_NULL; - HidlP2pGroupConfig conf[GROUP_CONFIG_END_POS]; + P2pGroupConfig conf[GROUP_CONFIG_END_POS]; if (memset_s(conf, sizeof(conf), 0, sizeof(conf)) != EOK) { return WIFI_IDL_OPT_FAILED; } @@ -1554,7 +1660,7 @@ WifiErrorNo WifiIdlClient::ReqP2pSetGroupConfig(int networkId, const IdlP2pGroup WifiErrorNo WifiIdlClient::ReqP2pGetGroupConfig(int networkId, IdlP2pGroupConfig &config) const { CHECK_CLIENT_NOT_NULL; - HidlP2pGroupConfig confs[GROUP_CONFIG_END_POS]; + P2pGroupConfig confs[GROUP_CONFIG_END_POS]; if (memset_s(confs, sizeof(confs), 0, sizeof(confs)) != EOK) { return WIFI_IDL_OPT_FAILED; } @@ -1582,5 +1688,33 @@ WifiErrorNo WifiIdlClient::ReqP2pAddNetwork(int &networkId) const CHECK_CLIENT_NOT_NULL; return P2pAddNetwork(&networkId); } + +WifiErrorNo WifiIdlClient::ReqP2pHid2dConnect(const Hid2dConnectConfig &config) const +{ + CHECK_CLIENT_NOT_NULL; + Hid2dConnectInfo info; + if (memset_s(&info, sizeof(info), 0, sizeof(info)) != EOK) { + return WIFI_IDL_OPT_FAILED; + } + if (strncpy_s(info.ssid, sizeof(info.ssid), config.GetSsid().c_str(), config.GetSsid().length()) != EOK) { + return WIFI_IDL_OPT_FAILED; + } + if (strncpy_s(info.bssid, sizeof(info.bssid), config.GetBssid().c_str(), config.GetBssid().length()) != EOK) { + return WIFI_IDL_OPT_FAILED; + } + if (strncpy_s(info.passphrase, sizeof(info.passphrase), + config.GetPreSharedKey().c_str(), config.GetPreSharedKey().length()) != EOK) { + return WIFI_IDL_OPT_FAILED; + } + info.frequency = config.GetFrequency(); + WifiErrorNo ret = Hid2dConnect(&info); + return ret; +} + +WifiErrorNo WifiIdlClient::ReqWpaSetSuspendMode(bool mode) const +{ + CHECK_CLIENT_NOT_NULL; + return SetSuspendMode(mode); +} } // namespace Wifi -} // namespace OHOS \ No newline at end of file +} // namespace OHOS diff --git a/services/wifi_standard/wifi_framework/wifi_manage/idl_client/wifi_idl_client.h b/wifi/services/wifi_standard/wifi_framework/wifi_manage/idl_client/wifi_idl_client.h similarity index 87% rename from services/wifi_standard/wifi_framework/wifi_manage/idl_client/wifi_idl_client.h rename to wifi/services/wifi_standard/wifi_framework/wifi_manage/idl_client/wifi_idl_client.h index 5568a688b5ac4aa5be454b74bf2ac607839f9a25..4520eb05be89801f9897c4cb5ff993e42016e99b 100644 --- a/services/wifi_standard/wifi_framework/wifi_manage/idl_client/wifi_idl_client.h +++ b/wifi/services/wifi_standard/wifi_framework/wifi_manage/idl_client/wifi_idl_client.h @@ -1,5 +1,5 @@ /* - * Copyright (C) 2021 Huawei Device Co., Ltd. + * Copyright (C) 2021-2022 Huawei Device Co., Ltd. * 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 @@ -33,6 +33,7 @@ #include "i_wifi_hotspot_iface.h" #include "i_wifi_struct.h" #include "wifi_global_func.h" +#include "wifi_hid2d_msg.h" namespace OHOS { namespace Wifi { @@ -267,6 +268,15 @@ public: */ WifiErrorNo SetDeviceConfig(int networkId, const WifiIdlDeviceConfig &config); + /** + * @Description Set bssid to supplicant. + * + * @param networkId + * @param bssid + * @return WifiErrorNo + */ + WifiErrorNo SetWpsBssid(int networkId, const std::string &bssid); + /** * @Description Save the network. * @@ -338,14 +348,14 @@ public: * * @return WifiErrorNo */ - WifiErrorNo StartAp(void); + WifiErrorNo StartAp(int id = 0); /** * @Description Close Ap. * * @return WifiErrorNo */ - WifiErrorNo StopAp(void); + WifiErrorNo StopAp(int id = 0); /** * @Description Setting SoftAP Configurations. @@ -353,7 +363,7 @@ public: * @param config * @return WifiErrorNo */ - WifiErrorNo SetSoftApConfig(const HotspotConfig &config); + WifiErrorNo SetSoftApConfig(const HotspotConfig &config, int id = 0); /** * @Description Obtains information about all connected STAs. @@ -361,7 +371,7 @@ public: * @param result * @return WifiErrorNo */ - WifiErrorNo GetStationList(std::vector &result); + WifiErrorNo GetStationList(std::vector &result, int id = 0); /** * @Description To set the blocklist filtering in AP mode to prohibit the MAC @@ -370,7 +380,7 @@ public: * @param mac - Blocklisted address. * @return WifiErrorNo */ - WifiErrorNo AddBlockByMac(const std::string &mac); + WifiErrorNo AddBlockByMac(const std::string &mac, int id = 0); /** * @Description To set blocklist filtering in AP mode and delete a specified MAC @@ -379,7 +389,7 @@ public: * @param mac - Blocklisted address. * @return WifiErrorNo */ - WifiErrorNo DelBlockByMac(const std::string &mac); + WifiErrorNo DelBlockByMac(const std::string &mac, int id = 0); /** * @Description Disconnect the STA with a specified MAC address. @@ -387,7 +397,7 @@ public: * @param mac * @return WifiErrorNo */ - WifiErrorNo RemoveStation(const std::string &mac); + WifiErrorNo RemoveStation(const std::string &mac, int id = 0); /** * @Description Obtains the hotspot frequency supported by a specified frequency band. @@ -396,7 +406,7 @@ public: * @param frequencies * @return WifiErrorNo */ - WifiErrorNo GetFrequenciesByBand(int band, std::vector &frequencies); + WifiErrorNo GetFrequenciesByBand(int band, std::vector &frequencies, int id = 0); /** * @Description Listening to Wi-Fi disconnection or connection events @@ -405,7 +415,7 @@ public: * @param callback * @return WifiErrorNo */ - WifiErrorNo RegisterApEvent(IWifiApMonitorEventCallback callback) const; + WifiErrorNo RegisterApEvent(IWifiApMonitorEventCallback callback, int id = 0) const; /** * @Description Sets the Wi-Fi country code. @@ -413,7 +423,7 @@ public: * @param code * @return WifiErrorNo */ - WifiErrorNo SetWifiCountryCode(const std::string &code); + WifiErrorNo SetWifiCountryCode(const std::string &code, int id = 0); /** * @Description Disconnect the STA connection based on the MAC address. @@ -421,7 +431,23 @@ public: * @param mac * @return WifiErrorNo */ - WifiErrorNo ReqDisconnectStaByMac(const std::string &mac); + WifiErrorNo ReqDisconnectStaByMac(const std::string &mac, int id = 0); + + /** + * @Description Request get the power mode. + * + * @param mode - The mode of power. + * @return WifiErrorNo + */ + WifiErrorNo ReqGetPowerModel(int& model, int id = 0); + + /** + * @Description Request set the power mode. + * + * @param mode - The mode to set. + * @return WifiErrorNo + */ + WifiErrorNo ReqSetPowerModel(const int& model, int id = 0); /* ************************** ChipMode interface **************************** */ @@ -500,12 +526,44 @@ public: WifiErrorNo RequestFirmwareDebugInfo(std::string &debugInfo); /** - * @Description Setting the Power Mode. + * @Description is support DBDC * - * @param mode + * @param isSupport + * @return WifiErrorNo + */ + WifiErrorNo ReqIsSupportDbdc(bool &isSupport) const; + + /** + * @Description is support CSA + * + * @param isSupport * @return WifiErrorNo */ - WifiErrorNo SetWifiPowerMode(int mode); + WifiErrorNo ReqIsSupportCsa(bool &isSupport) const; + + /** + * @Description is support radar detection + * + * @param isSupport + * @return WifiErrorNo + */ + WifiErrorNo ReqIsSupportRadarDetect(bool &isSupport) const; + + /** + * @Description is support DFS channel + * + * @param isSupport + * @return WifiErrorNo + */ + WifiErrorNo ReqIsSupportDfsChannel(bool &isSupport) const; + + /** + * @Description is support indoor channel + * + * @param isSupport + * @return WifiErrorNo + */ + WifiErrorNo ReqIsSupportIndoorChannel(bool &isSupport) const; /* ******************************* Supplicant interface********************** */ @@ -574,7 +632,7 @@ public: * @param countCode * @return WifiErrorNo */ - WifiErrorNo ReqWpaSetCountryCode(const std::string &countCode); + WifiErrorNo ReqWpaSetCountryCode(const std::string &countryCode); /** * @Description Obtains the country code. @@ -582,7 +640,7 @@ public: * @param countCode * @return WifiErrorNo */ - WifiErrorNo ReqWpaGetCountryCode(std::string &countCode); + WifiErrorNo ReqWpaGetCountryCode(std::string &countryCode); /** * @Description Wpa_s disable/enable(0/1) automatic reconnection. @@ -791,7 +849,7 @@ public: * @param pin * @return WifiErrorNo */ - WifiErrorNo ReqP2pConnect(const WifiP2pConfig &config, bool isJoinExistingGroup, std::string &pin) const; + WifiErrorNo ReqP2pConnect(const WifiP2pConfigInternal &config, bool isJoinExistingGroup, std::string &pin) const; /** * @Description Send a request for cancel connect to the P2P @@ -804,7 +862,7 @@ public: * @Description Send a request for Provision Discovery to the P2P * */ - WifiErrorNo ReqP2pProvisionDiscovery(const WifiP2pConfig &config) const; + WifiErrorNo ReqP2pProvisionDiscovery(const WifiP2pConfigInternal &config) const; /** * @Description Send a request for add a P2P group to the P2P @@ -993,18 +1051,34 @@ public: * @return WifiErrorNo */ WifiErrorNo ReqP2pAddNetwork(int &networkId) const; + + /** + * @Description Send a request for hid2d connect + * + * @param config + * @return WifiErrorNo + */ + WifiErrorNo ReqP2pHid2dConnect(const Hid2dConnectConfig &config) const; + + /** + * @Description Send suspend mode to wpa + * + * @param mode: true for suspend, false for resume + * @return WifiErrorNo + */ + WifiErrorNo ReqWpaSetSuspendMode(bool mode) const; public: RpcClient *pRpcClient; private: char **ConVectorToCArrayString(const std::vector &vec) const; WifiErrorNo ConvertPnoScanParam(const WifiPnoScanParam ¶m, PnoScanSettings *pSettings) const; - int PushDeviceConfigString(HidlSetNetworkConfig *pConfig, DeviceConfigType type, const std::string &msg) const; - int PushDeviceConfigInt(HidlSetNetworkConfig *pConfig, DeviceConfigType type, int i) const; - int PushDeviceConfigAuthAlgorithm(HidlSetNetworkConfig *pConfig, DeviceConfigType type, unsigned int alg) const; + int PushDeviceConfigString(SetNetworkConfig *pConfig, DeviceConfigType type, const std::string &msg) const; + int PushDeviceConfigInt(SetNetworkConfig *pConfig, DeviceConfigType type, int i) const; + int PushDeviceConfigAuthAlgorithm(SetNetworkConfig *pConfig, DeviceConfigType type, unsigned int alg) const; WifiErrorNo CheckValidDeviceConfig(const WifiIdlDeviceConfig &config) const; - int PushP2pGroupConfigString(HidlP2pGroupConfig *pConfig, P2pGroupConfigType type, const std::string &str) const; - int PushP2pGroupConfigInt(HidlP2pGroupConfig *pConfig, P2pGroupConfigType type, int i) const; + int PushP2pGroupConfigString(P2pGroupConfig *pConfig, P2pGroupConfigType type, const std::string &str) const; + int PushP2pGroupConfigInt(P2pGroupConfig *pConfig, P2pGroupConfigType type, int i) const; }; } // namespace Wifi } // namespace OHOS diff --git a/services/wifi_standard/wifi_framework/wifi_manage/idl_client/wifi_idl_define.h b/wifi/services/wifi_standard/wifi_framework/wifi_manage/idl_client/wifi_idl_define.h similarity index 93% rename from services/wifi_standard/wifi_framework/wifi_manage/idl_client/wifi_idl_define.h rename to wifi/services/wifi_standard/wifi_framework/wifi_manage/idl_client/wifi_idl_define.h index a4b727f731370000b5f05c5b85080e86b4783bf8..86933987daf6ea866a8f5153005dc9e9a22e5ebb 100644 --- a/services/wifi_standard/wifi_framework/wifi_manage/idl_client/wifi_idl_define.h +++ b/wifi/services/wifi_standard/wifi_framework/wifi_manage/idl_client/wifi_idl_define.h @@ -30,12 +30,15 @@ typedef enum WifiIdlEvent { /* SupplicantEventCallback */ WIFI_IDL_CBK_CMD_SCAN_INFO_NOTIFY, /* SCAN Scan Result Notification */ WIFI_IDL_CBK_CMD_CONNECT_CHANGED, /* Connection status change notification */ + WIFI_IDL_CBK_CMD_BSSID_CHANGED, /* bssid change notification */ WIFI_IDL_CBK_CMD_AP_ENABLE, /* AP enabling notification */ WIFI_IDL_CBK_CMD_AP_DISABLE, /* AP closure notification */ WIFI_IDL_CBK_CMD_WPA_STATE_CHANGEM, /* WPA status change notification */ WIFI_IDL_CBK_CMD_SSID_WRONG_KEY, /* Password error status notification */ WIFI_IDL_CBK_CMD_WPS_OVERLAP, /* wps PBC overlap */ WIFI_IDL_CBK_CMD_WPS_TIME_OUT, /* wps connect time out */ + WIFI_IDL_CBK_CMD_WPS_CONNECTION_FULL, /* network connection full */ + WIFI_IDL_CBK_CMD_WPS_CONNECTION_REJECT, /* network connection reject */ /* P2p callback */ WIFI_IDL_CBK_CMD_P2P_SUPPLICANT_CONNECT, /* p2p connect supplicant */ WIFI_IDL_CBK_CMD_SUP_CONN_FAILED_EVENT, /* Wpa_supplicant client connection failure event */ @@ -60,8 +63,11 @@ typedef enum WifiIdlEvent { WIFI_IDL_CBK_CMD_AP_STA_DISCONNECTED_EVENT, /* STA Disconnected from AP */ WIFI_IDL_CBK_CMD_AP_STA_CONNECTED_EVENT, /* STA and AP connected event */ WIFI_IDL_CBK_CMD_P2P_SERV_DISC_REQ_EVENT, /* Service discovery request event */ + WIFI_IDL_CBK_CMD_P2P_IFACE_CREATED_EVENT, /* P2P interface created event */ } WifiIdlEvent; +#define WIFI_IDL_FALSE 0 +#define WIFI_IDL_TRUE 1 #define SINGLE_SCAN_FAILED 1 /* Scan failure notification */ #define SINGLE_SCAN_OVER_OK 2 /* Scan success notification */ #define PNO_SCAN_OVER_OK 3 /* PNO Scan success notification */ @@ -85,5 +91,4 @@ typedef enum WifiIdlEvent { #define WIFI_IDL_P2P_TMP_BUFFER_SIZE_128 128 #define WIFI_IDL_P2P_SERVICE_TYPE_MIN_SIZE 3 #define WIFI_IDL_P2P_SERVICE_TYPE_2_POS 2 - -#endif \ No newline at end of file +#endif diff --git a/services/wifi_standard/wifi_framework/wifi_manage/idl_client/wifi_idl_inner_interface.cpp b/wifi/services/wifi_standard/wifi_framework/wifi_manage/idl_client/wifi_idl_inner_interface.cpp similarity index 89% rename from services/wifi_standard/wifi_framework/wifi_manage/idl_client/wifi_idl_inner_interface.cpp rename to wifi/services/wifi_standard/wifi_framework/wifi_manage/idl_client/wifi_idl_inner_interface.cpp index 3b7213aa96fd2619b366b248ee72d354b8738ee1..b03cf34333d5ef665951113373414f420a35874a 100644 --- a/services/wifi_standard/wifi_framework/wifi_manage/idl_client/wifi_idl_inner_interface.cpp +++ b/wifi/services/wifi_standard/wifi_framework/wifi_manage/idl_client/wifi_idl_inner_interface.cpp @@ -30,13 +30,13 @@ RpcClient *GetApRpcClient(void) return OHOS::Wifi::WifiApHalInterface::GetInstance().mIdlClient->pRpcClient; } -void OnApStaJoinOrLeave(const CStationInfo *info) +void OnApStaJoinOrLeave(const CStationInfo *info, int id) { if (info == nullptr) { return; } const OHOS::Wifi::IWifiApMonitorEventCallback &cbk = - OHOS::Wifi::WifiApHalInterface::GetInstance().GetApCallbackInst(); + OHOS::Wifi::WifiApHalInterface::GetInstance().GetApCallbackInst(id); if (cbk.onStaJoinOrLeave) { OHOS::Wifi::WifiApConnectionNofify cbInfo; cbInfo.type = info->type; @@ -45,12 +45,12 @@ void OnApStaJoinOrLeave(const CStationInfo *info) } } -void OnApEnableOrDisable(int satus) +void OnApEnableOrDisable(int status, int id) { const OHOS::Wifi::IWifiApMonitorEventCallback &cbk = - OHOS::Wifi::WifiApHalInterface::GetInstance().GetApCallbackInst(); + OHOS::Wifi::WifiApHalInterface::GetInstance().GetApCallbackInst(id); if (cbk.onApEnableOrDisable) { - cbk.onApEnableOrDisable(satus); + cbk.onApEnableOrDisable(status); } } @@ -70,6 +70,17 @@ void OnConnectChanged(int status, int networkId, const char *mac) } } +void OnBssidChanged(const char *reason, const char *bssid) +{ + if (reason == nullptr || bssid == nullptr) { + return; + } + const OHOS::Wifi::WifiEventCallback &cbk = OHOS::Wifi::WifiStaHalInterface::GetInstance().GetCallbackInst(); + if (cbk.onBssidChanged) { + cbk.onBssidChanged(reason, bssid); + } +} + void OnWpaStateChanged(int status) { const OHOS::Wifi::WifiEventCallback &cbk = OHOS::Wifi::WifiStaHalInterface::GetInstance().GetCallbackInst(); @@ -86,6 +97,22 @@ void OnWpaSsidWrongKey(int status) } } +void OnWpaConnectionFull(int status) +{ + const OHOS::Wifi::WifiEventCallback &cbk = OHOS::Wifi::WifiStaHalInterface::GetInstance().GetCallbackInst(); + if (cbk.onWpaConnectionFull) { + cbk.onWpaConnectionFull(status); + } +} + +void OnWpaConnectionReject(int status) +{ + const OHOS::Wifi::WifiEventCallback &cbk = OHOS::Wifi::WifiStaHalInterface::GetInstance().GetCallbackInst(); + if (cbk.onWpaConnectionReject) { + cbk.onWpaConnectionReject(status); + } +} + void OnWpsOverlap(int status) { const OHOS::Wifi::WifiEventCallback &cbk = OHOS::Wifi::WifiStaHalInterface::GetInstance().GetCallbackInst(); @@ -129,7 +156,7 @@ void OnP2pConnectSupplicant(int state) } } -void OnP2pDeviceFound(const HidlP2pDeviceInfo *info) +void OnP2pDeviceFound(const P2pDeviceInfo *info) { if (info == nullptr) { return; @@ -202,7 +229,7 @@ void OnP2pInvitationResult(const char *bssid, int status) } } -void OnP2pInvitationReceived(const HidlP2pInvitationInfo *info) +void OnP2pInvitationReceived(const P2pInvitationInfo *info) { if (info == nullptr) { return; @@ -239,7 +266,7 @@ void OnP2pGroupFormationFailure(const char *failureReason) } } -void OnP2pGroupStarted(const HidlP2pGroupInfo *group) +void OnP2pGroupStarted(const P2pGroupInfo *group) { if (group == nullptr) { return; @@ -376,7 +403,7 @@ void OnP2pConnectSupplicantFailed(void) } } -void OnP2pServDiscReq(const HidlP2pServDiscReqInfo *info) +void OnP2pServDiscReq(const P2pServDiscReqInfo *info) { if (info == nullptr) { return; @@ -394,3 +421,14 @@ void OnP2pServDiscReq(const HidlP2pServDiscReqInfo *info) cbk.onP2pServDiscReq(cbInfo); } } + +void OnP2pIfaceCreated(const char *ifName, int isGo) +{ + if (ifName == nullptr) { + return; + } + const OHOS::Wifi::P2pHalCallback &cbk = OHOS::Wifi::WifiP2PHalInterface::GetInstance().GetP2pCallbackInst(); + if (cbk.onP2pIfaceCreated) { + cbk.onP2pIfaceCreated(ifName, isGo); + } +} diff --git a/services/wifi_standard/wifi_framework/wifi_manage/idl_client/wifi_idl_inner_interface.h b/wifi/services/wifi_standard/wifi_framework/wifi_manage/idl_client/wifi_idl_inner_interface.h similarity index 84% rename from services/wifi_standard/wifi_framework/wifi_manage/idl_client/wifi_idl_inner_interface.h rename to wifi/services/wifi_standard/wifi_framework/wifi_manage/idl_client/wifi_idl_inner_interface.h index 43e1a28007d4065ba0bb99c2b9ab59c82adabf13..153d917d5a526ab149567e724e69f5c7461922a6 100644 --- a/services/wifi_standard/wifi_framework/wifi_manage/idl_client/wifi_idl_inner_interface.h +++ b/wifi/services/wifi_standard/wifi_framework/wifi_manage/idl_client/wifi_idl_inner_interface.h @@ -30,8 +30,8 @@ extern "C" { */ RpcClient *GetApRpcClient(void); -void OnApStaJoinOrLeave(const CStationInfo *info); -void OnApEnableOrDisable(int satus); +void OnApStaJoinOrLeave(const CStationInfo *info, int id); +void OnApEnableOrDisable(int status, int id); /** * @Description Get the Chip Rpc Client object. @@ -48,10 +48,13 @@ RpcClient *GetChipRpcClient(void); RpcClient *GetStaRpcClient(void); void OnConnectChanged(int status, int networkId, const char *mac); +void OnBssidChanged(const char *reason, const char *bssid); void OnWpaStateChanged(int status); void OnWpaSsidWrongKey(int status); void OnWpsOverlap(int status); void OnWpsTimeOut(int status); +void OnWpaConnectionFull(int status); +void OnWpaConnectionReject(int status); /** * @Description Get the Supplicant Rpc Client object. @@ -70,16 +73,16 @@ void OnScanNotify(int status); RpcClient *GetP2pRpcClient(void); void OnP2pConnectSupplicant(int state); -void OnP2pDeviceFound(const HidlP2pDeviceInfo *info); +void OnP2pDeviceFound(const P2pDeviceInfo *info); void OnP2pDeviceLost(const char *p2pDeviceAddress); void OnP2pGoNegotiationRequest(const char *srcAddress, short passwordId); void OnP2pGoNegotiationSuccess(void); void OnP2pGoNegotiationFailure(int status); void OnP2pInvitationResult(const char *bssid, int status); -void OnP2pInvitationReceived(const HidlP2pInvitationInfo *info); +void OnP2pInvitationReceived(const P2pInvitationInfo *info); void OnP2pGroupFormationSuccess(void); void OnP2pGroupFormationFailure(const char *failureReason); -void OnP2pGroupStarted(const HidlP2pGroupInfo *group); +void OnP2pGroupStarted(const P2pGroupInfo *group); void OnP2pGroupRemoved(const char *groupIfName, int isGo); void OnP2pProvisionDiscoveryPbcRequest(const char *p2pDeviceAddress); void OnP2pProvisionDiscoveryPbcResponse(const char *p2pDeviceAddress); @@ -92,8 +95,9 @@ void OnP2pServiceDiscoveryResponse( void OnP2pStaDeauthorized(const char *p2pDeviceAddress); void OnP2pStaAuthorized(const char *p2pDeviceAddress); void OnP2pConnectSupplicantFailed(void); -void OnP2pServDiscReq(const HidlP2pServDiscReqInfo *info); +void OnP2pServDiscReq(const P2pServDiscReqInfo *info); +void OnP2pIfaceCreated(const char *ifName, int isGo); #ifdef __cplusplus } #endif -#endif \ No newline at end of file +#endif diff --git a/services/wifi_standard/wifi_framework/wifi_manage/idl_client/wifi_idl_struct.h b/wifi/services/wifi_standard/wifi_framework/wifi_manage/idl_client/wifi_idl_struct.h similarity index 95% rename from services/wifi_standard/wifi_framework/wifi_manage/idl_client/wifi_idl_struct.h rename to wifi/services/wifi_standard/wifi_framework/wifi_manage/idl_client/wifi_idl_struct.h index fa562c51e3c805f3af6efba7f475237b0250dff5..13ea086f67911abcbfe3c5f61254965eb333936c 100644 --- a/services/wifi_standard/wifi_framework/wifi_manage/idl_client/wifi_idl_struct.h +++ b/wifi/services/wifi_standard/wifi_framework/wifi_manage/idl_client/wifi_idl_struct.h @@ -47,9 +47,13 @@ struct WifiIdlDeviceConfig { std::string eap; std::string identity; std::string password; + std::string clientCert; + std::string privateKey; std::string bssid; + int phase2Method; - WifiIdlDeviceConfig() : networkId(-1), priority(-1), scanSsid(-1), authAlgorithms(-1), wepKeyIdx(-1) + WifiIdlDeviceConfig() : networkId(-1), priority(-1), scanSsid(-1), authAlgorithms(-1), wepKeyIdx(-1), + phase2Method(0) {} ~WifiIdlDeviceConfig() @@ -142,7 +146,7 @@ struct IdlP2pDeviceFound { }; struct IdlP2pInvitationInfo { - int type; /* 0:Recived, 1:Accepted */ + int type; /* 0:Received, 1:Accepted */ int persistentNetworkId; int operatingFrequency; std::string srcAddress; @@ -213,4 +217,4 @@ struct IdlP2pGroupConfig { }; } // namespace Wifi } // namespace OHOS -#endif \ No newline at end of file +#endif diff --git a/services/wifi_standard/wifi_framework/wifi_manage/idl_client/wifi_p2p_event_callback.h b/wifi/services/wifi_standard/wifi_framework/wifi_manage/idl_client/wifi_p2p_event_callback.h similarity index 96% rename from services/wifi_standard/wifi_framework/wifi_manage/idl_client/wifi_p2p_event_callback.h rename to wifi/services/wifi_standard/wifi_framework/wifi_manage/idl_client/wifi_p2p_event_callback.h index 4893f59e6c10b6abe53e57c284d0323bb64f5d38..2229fac251ac38cc89bc5d8f602f061c4d5174f8 100644 --- a/services/wifi_standard/wifi_framework/wifi_manage/idl_client/wifi_p2p_event_callback.h +++ b/wifi/services/wifi_standard/wifi_framework/wifi_manage/idl_client/wifi_p2p_event_callback.h @@ -46,8 +46,9 @@ struct P2pHalCallback { std::function onStaAuthorized; std::function connectSupplicantFailed; std::function onP2pServDiscReq; + std::function onP2pIfaceCreated; }; } // namespace Wifi } // namespace OHOS -#endif \ No newline at end of file +#endif diff --git a/services/wifi_standard/wifi_framework/wifi_manage/idl_client/wifi_p2p_hal_interface.cpp b/wifi/services/wifi_standard/wifi_framework/wifi_manage/idl_client/wifi_p2p_hal_interface.cpp similarity index 72% rename from services/wifi_standard/wifi_framework/wifi_manage/idl_client/wifi_p2p_hal_interface.cpp rename to wifi/services/wifi_standard/wifi_framework/wifi_manage/idl_client/wifi_p2p_hal_interface.cpp index 92aea54a0989f508487e11f76d9142a8c4c572bb..c613d59913587093bcc4bf6c4d958af770dc120f 100644 --- a/services/wifi_standard/wifi_framework/wifi_manage/idl_client/wifi_p2p_hal_interface.cpp +++ b/wifi/services/wifi_standard/wifi_framework/wifi_manage/idl_client/wifi_p2p_hal_interface.cpp @@ -1,5 +1,5 @@ /* - * Copyright (C) 2021 Huawei Device Co., Ltd. + * Copyright (C) 2021-2022 Huawei Device Co., Ltd. * 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 @@ -40,16 +40,19 @@ WifiP2PHalInterface &WifiP2PHalInterface::GetInstance(void) WifiErrorNo WifiP2PHalInterface::StartP2p(void) const { + CHECK_NULL_AND_RETURN(mIdlClient, WIFI_IDL_OPT_FAILED); return mIdlClient->ReqP2pStart(); } WifiErrorNo WifiP2PHalInterface::StopP2p(void) const { + CHECK_NULL_AND_RETURN(mIdlClient, WIFI_IDL_OPT_FAILED); return mIdlClient->ReqP2pStop(); } WifiErrorNo WifiP2PHalInterface::RegisterP2pCallback(const P2pHalCallback &callbacks) { + CHECK_NULL_AND_RETURN(mIdlClient, WIFI_IDL_OPT_FAILED); WifiErrorNo err = mIdlClient->ReqP2pRegisterCallback(callbacks); if (err == WIFI_IDL_OPT_OK || callbacks.onConnectSupplicant == nullptr) { mP2pCallback = callbacks; @@ -59,219 +62,263 @@ WifiErrorNo WifiP2PHalInterface::RegisterP2pCallback(const P2pHalCallback &callb WifiErrorNo WifiP2PHalInterface::StartWpsPbc(const std::string &groupInterface, const std::string &bssid) const { + CHECK_NULL_AND_RETURN(mIdlClient, WIFI_IDL_OPT_FAILED); return mIdlClient->ReqP2pSetupWpsPbc(groupInterface, bssid); } WifiErrorNo WifiP2PHalInterface::StartWpsPin( const std::string &groupInterface, const std::string &address, const std::string &pin, std::string &result) const { + CHECK_NULL_AND_RETURN(mIdlClient, WIFI_IDL_OPT_FAILED); return mIdlClient->ReqP2pSetupWpsPin(groupInterface, address, pin, result); } WifiErrorNo WifiP2PHalInterface::RemoveNetwork(int networkId) const { + CHECK_NULL_AND_RETURN(mIdlClient, WIFI_IDL_OPT_FAILED); return mIdlClient->ReqP2pRemoveNetwork(networkId); } WifiErrorNo WifiP2PHalInterface::ListNetworks(std::map &mapGroups) const { + CHECK_NULL_AND_RETURN(mIdlClient, WIFI_IDL_OPT_FAILED); return mIdlClient->ReqP2pListNetworks(mapGroups); } WifiErrorNo WifiP2PHalInterface::SetP2pDeviceName(const std::string &name) const { + CHECK_NULL_AND_RETURN(mIdlClient, WIFI_IDL_OPT_FAILED); return mIdlClient->ReqP2pSetDeviceName(name); } WifiErrorNo WifiP2PHalInterface::SetP2pDeviceType(const std::string &type) const { + CHECK_NULL_AND_RETURN(mIdlClient, WIFI_IDL_OPT_FAILED); return mIdlClient->ReqP2pSetWpsDeviceType(type); } WifiErrorNo WifiP2PHalInterface::SetP2pSecondaryDeviceType(const std::string &type) { + CHECK_NULL_AND_RETURN(mIdlClient, WIFI_IDL_OPT_FAILED); return mIdlClient->ReqP2pSetWpsSecondaryDeviceType(type); } WifiErrorNo WifiP2PHalInterface::SetP2pConfigMethods(const std::string &methods) const { + CHECK_NULL_AND_RETURN(mIdlClient, WIFI_IDL_OPT_FAILED); return mIdlClient->ReqP2pSetWpsConfigMethods(methods); } WifiErrorNo WifiP2PHalInterface::SetP2pSsidPostfix(const std::string &postfixName) const { + CHECK_NULL_AND_RETURN(mIdlClient, WIFI_IDL_OPT_FAILED); return mIdlClient->ReqP2pSetSsidPostfixName(postfixName); } WifiErrorNo WifiP2PHalInterface::SetP2pGroupIdle(const std::string &groupInterface, size_t time) const { + CHECK_NULL_AND_RETURN(mIdlClient, WIFI_IDL_OPT_FAILED); return mIdlClient->ReqP2pSetGroupMaxIdle(groupInterface, time); } WifiErrorNo WifiP2PHalInterface::SetP2pPowerSave(const std::string &groupInterface, bool enable) const { + CHECK_NULL_AND_RETURN(mIdlClient, WIFI_IDL_OPT_FAILED); return mIdlClient->ReqP2pSetPowerSave(groupInterface, enable); } WifiErrorNo WifiP2PHalInterface::SetWfdEnable(bool enable) const { + CHECK_NULL_AND_RETURN(mIdlClient, WIFI_IDL_OPT_FAILED); return mIdlClient->ReqP2pSetWfdEnable(enable); } WifiErrorNo WifiP2PHalInterface::SetWfdDeviceConfig(const std::string &config) const { + CHECK_NULL_AND_RETURN(mIdlClient, WIFI_IDL_OPT_FAILED); return mIdlClient->ReqP2pSetWfdDeviceConfig(config); } WifiErrorNo WifiP2PHalInterface::P2pFind(size_t timeout) const { + CHECK_NULL_AND_RETURN(mIdlClient, WIFI_IDL_OPT_FAILED); return mIdlClient->ReqP2pStartFind(timeout); } WifiErrorNo WifiP2PHalInterface::P2pStopFind() const { + CHECK_NULL_AND_RETURN(mIdlClient, WIFI_IDL_OPT_FAILED); return mIdlClient->ReqP2pStopFind(); } WifiErrorNo WifiP2PHalInterface::P2pConfigureListen(bool enable, size_t period, size_t interval) const { + CHECK_NULL_AND_RETURN(mIdlClient, WIFI_IDL_OPT_FAILED); return mIdlClient->ReqP2pSetExtListen(enable, period, interval); } WifiErrorNo WifiP2PHalInterface::SetListenChannel(size_t channel, unsigned char regClass) const { + CHECK_NULL_AND_RETURN(mIdlClient, WIFI_IDL_OPT_FAILED); return mIdlClient->ReqP2pSetListenChannel(channel, regClass); } WifiErrorNo WifiP2PHalInterface::P2pFlush() const { + CHECK_NULL_AND_RETURN(mIdlClient, WIFI_IDL_OPT_FAILED); return mIdlClient->ReqP2pFlush(); } -WifiErrorNo WifiP2PHalInterface::Connect(const WifiP2pConfig &config, bool isJoinExistingGroup, std::string &pin) const +WifiErrorNo WifiP2PHalInterface::Connect(const WifiP2pConfigInternal &config, bool isJoinExistingGroup, + std::string &pin) const { + CHECK_NULL_AND_RETURN(mIdlClient, WIFI_IDL_OPT_FAILED); return mIdlClient->ReqP2pConnect(config, isJoinExistingGroup, pin); } WifiErrorNo WifiP2PHalInterface::CancelConnect() const { + CHECK_NULL_AND_RETURN(mIdlClient, WIFI_IDL_OPT_FAILED); return mIdlClient->ReqP2pCancelConnect(); } -WifiErrorNo WifiP2PHalInterface::ProvisionDiscovery(const WifiP2pConfig &config) const +WifiErrorNo WifiP2PHalInterface::ProvisionDiscovery(const WifiP2pConfigInternal &config) const { + CHECK_NULL_AND_RETURN(mIdlClient, WIFI_IDL_OPT_FAILED); return mIdlClient->ReqP2pProvisionDiscovery(config); } WifiErrorNo WifiP2PHalInterface::GroupAdd(bool isPersistent, int networkId, int freq) const { + CHECK_NULL_AND_RETURN(mIdlClient, WIFI_IDL_OPT_FAILED); return mIdlClient->ReqP2pAddGroup(isPersistent, networkId, freq); } WifiErrorNo WifiP2PHalInterface::GroupRemove(const std::string &groupInterface) const { + CHECK_NULL_AND_RETURN(mIdlClient, WIFI_IDL_OPT_FAILED); return mIdlClient->ReqP2pRemoveGroup(groupInterface); } WifiErrorNo WifiP2PHalInterface::Invite(const WifiP2pGroupInfo &group, const std::string &deviceAddr) const { + CHECK_NULL_AND_RETURN(mIdlClient, WIFI_IDL_OPT_FAILED); return mIdlClient->ReqP2pInvite(group, deviceAddr); } WifiErrorNo WifiP2PHalInterface::Reinvoke(int networkId, const std::string &deviceAddr) const { + CHECK_NULL_AND_RETURN(mIdlClient, WIFI_IDL_OPT_FAILED); return mIdlClient->ReqP2pReinvoke(networkId, deviceAddr); } WifiErrorNo WifiP2PHalInterface::GetDeviceAddress(std::string &deviceAddress) const { + CHECK_NULL_AND_RETURN(mIdlClient, WIFI_IDL_OPT_FAILED); return mIdlClient->ReqP2pGetDeviceAddress(deviceAddress); } WifiErrorNo WifiP2PHalInterface::GetGroupCapability(const std::string &deviceAddress, uint32_t &cap) const { + CHECK_NULL_AND_RETURN(mIdlClient, WIFI_IDL_OPT_FAILED); return mIdlClient->ReqP2pGetGroupCapability(deviceAddress, cap); } WifiErrorNo WifiP2PHalInterface::P2pServiceAdd(const WifiP2pServiceInfo &info) const { + CHECK_NULL_AND_RETURN(mIdlClient, WIFI_IDL_OPT_FAILED); return mIdlClient->ReqP2pAddService(info); } WifiErrorNo WifiP2PHalInterface::P2pServiceRemove(const WifiP2pServiceInfo &info) const { + CHECK_NULL_AND_RETURN(mIdlClient, WIFI_IDL_OPT_FAILED); return mIdlClient->ReqP2pRemoveService(info); } WifiErrorNo WifiP2PHalInterface::FlushService() const { + CHECK_NULL_AND_RETURN(mIdlClient, WIFI_IDL_OPT_FAILED); return mIdlClient->ReqP2pFlushService(); } WifiErrorNo WifiP2PHalInterface::SaveConfig() const { + CHECK_NULL_AND_RETURN(mIdlClient, WIFI_IDL_OPT_FAILED); return mIdlClient->ReqP2pSaveConfig(); } WifiErrorNo WifiP2PHalInterface::ReqServiceDiscovery( const std::string &deviceAddress, const std::vector &tlvs, std::string &reqID) const { + CHECK_NULL_AND_RETURN(mIdlClient, WIFI_IDL_OPT_FAILED); return mIdlClient->ReqP2pReqServiceDiscovery(deviceAddress, tlvs, reqID); } WifiErrorNo WifiP2PHalInterface::CancelReqServiceDiscovery(const std::string &id) const { + CHECK_NULL_AND_RETURN(mIdlClient, WIFI_IDL_OPT_FAILED); return mIdlClient->ReqP2pCancelServiceDiscovery(id); } WifiErrorNo WifiP2PHalInterface::SetRandomMacAddr(bool enable) const { + CHECK_NULL_AND_RETURN(mIdlClient, WIFI_IDL_OPT_FAILED); return mIdlClient->ReqP2pSetRandomMac(enable); } WifiErrorNo WifiP2PHalInterface::SetMiracastMode(int type) const { + CHECK_NULL_AND_RETURN(mIdlClient, WIFI_IDL_OPT_FAILED); return mIdlClient->ReqP2pSetMiracastType(type); } WifiErrorNo WifiP2PHalInterface::SetPersistentReconnect(int mode) const { + CHECK_NULL_AND_RETURN(mIdlClient, WIFI_IDL_OPT_FAILED); return mIdlClient->ReqSetPersistentReconnect(mode); } WifiErrorNo WifiP2PHalInterface::RespServiceDiscovery( const WifiP2pDevice &device, int frequency, int dialogToken, const std::vector &tlvs) const { + CHECK_NULL_AND_RETURN(mIdlClient, WIFI_IDL_OPT_FAILED); return mIdlClient->ReqRespServiceDiscovery(device, frequency, dialogToken, tlvs); } WifiErrorNo WifiP2PHalInterface::SetServiceDiscoveryExternal(bool isExternalProcess) const { + CHECK_NULL_AND_RETURN(mIdlClient, WIFI_IDL_OPT_FAILED); return mIdlClient->ReqSetServiceDiscoveryExternal(isExternalProcess); } WifiErrorNo WifiP2PHalInterface::GetP2pPeer(const std::string &deviceAddress, WifiP2pDevice &device) const { + CHECK_NULL_AND_RETURN(mIdlClient, WIFI_IDL_OPT_FAILED); return mIdlClient->ReqGetP2pPeer(deviceAddress, device); } WifiErrorNo WifiP2PHalInterface::P2pGetSupportFrequenciesByBand(int band, std::vector &frequencies) const { + CHECK_NULL_AND_RETURN(mIdlClient, WIFI_IDL_OPT_FAILED); return mIdlClient->ReqP2pGetSupportFrequencies(band, frequencies); } WifiErrorNo WifiP2PHalInterface::P2pSetGroupConfig(int networkId, const IdlP2pGroupConfig &config) const { + CHECK_NULL_AND_RETURN(mIdlClient, WIFI_IDL_OPT_FAILED); return mIdlClient->ReqP2pSetGroupConfig(networkId, config); } WifiErrorNo WifiP2PHalInterface::P2pGetGroupConfig(int networkId, IdlP2pGroupConfig &config) const { + CHECK_NULL_AND_RETURN(mIdlClient, WIFI_IDL_OPT_FAILED); return mIdlClient->ReqP2pGetGroupConfig(networkId, config); } WifiErrorNo WifiP2PHalInterface::P2pAddNetwork(int &networkId) const { + CHECK_NULL_AND_RETURN(mIdlClient, WIFI_IDL_OPT_FAILED); return mIdlClient->ReqP2pAddNetwork(networkId); } @@ -279,5 +326,11 @@ const P2pHalCallback &WifiP2PHalInterface::GetP2pCallbackInst(void) const { return mP2pCallback; } + +WifiErrorNo WifiP2PHalInterface::Hid2dConnect(const Hid2dConnectConfig &config) const +{ + CHECK_NULL_AND_RETURN(mIdlClient, WIFI_IDL_OPT_FAILED); + return mIdlClient->ReqP2pHid2dConnect(config); +} } // namespace Wifi } // namespace OHOS \ No newline at end of file diff --git a/services/wifi_standard/wifi_framework/wifi_manage/idl_client/wifi_p2p_hal_interface.h b/wifi/services/wifi_standard/wifi_framework/wifi_manage/idl_client/wifi_p2p_hal_interface.h similarity index 96% rename from services/wifi_standard/wifi_framework/wifi_manage/idl_client/wifi_p2p_hal_interface.h rename to wifi/services/wifi_standard/wifi_framework/wifi_manage/idl_client/wifi_p2p_hal_interface.h index 174e40539c70a320b89b61e3906d690beb53caf7..6e0a9921d9db74d8dc39dfae296c04015a734ddf 100644 --- a/services/wifi_standard/wifi_framework/wifi_manage/idl_client/wifi_p2p_hal_interface.h +++ b/wifi/services/wifi_standard/wifi_framework/wifi_manage/idl_client/wifi_p2p_hal_interface.h @@ -1,5 +1,5 @@ /* - * Copyright (C) 2021 Huawei Device Co., Ltd. + * Copyright (C) 2021-2022 Huawei Device Co., Ltd. * 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 @@ -12,6 +12,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + #ifndef OHOS_WIFI_P2P_HAL_INTERFACE_H #define OHOS_WIFI_P2P_HAL_INTERFACE_H @@ -212,7 +213,7 @@ public: * @param pin - if using pin mode, return pin code * @return WifiErrorNo */ - WifiErrorNo Connect(const WifiP2pConfig &config, bool isJoinExistingGroup, std::string &pin) const; + WifiErrorNo Connect(const WifiP2pConfigInternal &config, bool isJoinExistingGroup, std::string &pin) const; /** * @Description Sends a request for cancel connect to the P2P @@ -227,7 +228,7 @@ public: * @param config * @return WifiErrorNo */ - WifiErrorNo ProvisionDiscovery(const WifiP2pConfig &config) const; + WifiErrorNo ProvisionDiscovery(const WifiP2pConfigInternal &config) const; /** * @Description Add Group @@ -427,6 +428,14 @@ public: */ const P2pHalCallback &GetP2pCallbackInst(void) const; + /** + * @Description Sends a request for hid2d connect to the P2P + * + * @param config hid2d config + * @return WifiErrorNo + */ + WifiErrorNo Hid2dConnect(const Hid2dConnectConfig &config) const; + private: P2pHalCallback mP2pCallback; }; diff --git a/services/wifi_standard/wifi_framework/wifi_manage/idl_client/wifi_scan_param.h b/wifi/services/wifi_standard/wifi_framework/wifi_manage/idl_client/wifi_scan_param.h similarity index 100% rename from services/wifi_standard/wifi_framework/wifi_manage/idl_client/wifi_scan_param.h rename to wifi/services/wifi_standard/wifi_framework/wifi_manage/idl_client/wifi_scan_param.h diff --git a/services/wifi_standard/wifi_framework/wifi_manage/idl_client/wifi_sta_hal_interface.cpp b/wifi/services/wifi_standard/wifi_framework/wifi_manage/idl_client/wifi_sta_hal_interface.cpp similarity index 71% rename from services/wifi_standard/wifi_framework/wifi_manage/idl_client/wifi_sta_hal_interface.cpp rename to wifi/services/wifi_standard/wifi_framework/wifi_manage/idl_client/wifi_sta_hal_interface.cpp index 523e59322def3a08a38622e4f1aef46366e8fdd2..0a82f06a331690df104a15209a718d582c198f39 100644 --- a/services/wifi_standard/wifi_framework/wifi_manage/idl_client/wifi_sta_hal_interface.cpp +++ b/wifi/services/wifi_standard/wifi_framework/wifi_manage/idl_client/wifi_sta_hal_interface.cpp @@ -1,5 +1,5 @@ /* - * Copyright (C) 2021 Huawei Device Co., Ltd. + * Copyright (C) 2021-2022 Huawei Device Co., Ltd. * 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 @@ -39,146 +39,175 @@ WifiStaHalInterface &WifiStaHalInterface::GetInstance(void) WifiErrorNo WifiStaHalInterface::StartWifi(void) { + CHECK_NULL_AND_RETURN(mIdlClient, WIFI_IDL_OPT_FAILED); return mIdlClient->StartWifi(); } WifiErrorNo WifiStaHalInterface::StopWifi(void) { + CHECK_NULL_AND_RETURN(mIdlClient, WIFI_IDL_OPT_FAILED); return mIdlClient->StopWifi(); } WifiErrorNo WifiStaHalInterface::Connect(int networkId) { + CHECK_NULL_AND_RETURN(mIdlClient, WIFI_IDL_OPT_FAILED); return mIdlClient->ReqConnect(networkId); } WifiErrorNo WifiStaHalInterface::Reconnect(void) { + CHECK_NULL_AND_RETURN(mIdlClient, WIFI_IDL_OPT_FAILED); return mIdlClient->ReqReconnect(); } WifiErrorNo WifiStaHalInterface::Reassociate(void) { + CHECK_NULL_AND_RETURN(mIdlClient, WIFI_IDL_OPT_FAILED); return mIdlClient->ReqReassociate(); } WifiErrorNo WifiStaHalInterface::Disconnect(void) { + CHECK_NULL_AND_RETURN(mIdlClient, WIFI_IDL_OPT_FAILED); return mIdlClient->ReqDisconnect(); } WifiErrorNo WifiStaHalInterface::GetStaCapabilities(unsigned int &capabilities) { + CHECK_NULL_AND_RETURN(mIdlClient, WIFI_IDL_OPT_FAILED); return mIdlClient->GetStaCapabilities(capabilities); } WifiErrorNo WifiStaHalInterface::GetStaDeviceMacAddress(std::string &mac) { + CHECK_NULL_AND_RETURN(mIdlClient, WIFI_IDL_OPT_FAILED); return mIdlClient->GetStaDeviceMacAddress(mac); } WifiErrorNo WifiStaHalInterface::GetSupportFrequencies(int band, std::vector &frequencies) { + CHECK_NULL_AND_RETURN(mIdlClient, WIFI_IDL_OPT_FAILED); return mIdlClient->GetSupportFrequencies(band, frequencies); } WifiErrorNo WifiStaHalInterface::SetConnectMacAddr(const std::string &mac) { + CHECK_NULL_AND_RETURN(mIdlClient, WIFI_IDL_OPT_FAILED); return mIdlClient->SetConnectMacAddr(mac); } WifiErrorNo WifiStaHalInterface::SetScanMacAddress(const std::string &mac) { + CHECK_NULL_AND_RETURN(mIdlClient, WIFI_IDL_OPT_FAILED); return mIdlClient->SetScanMacAddress(mac); } WifiErrorNo WifiStaHalInterface::DisconnectLastRoamingBssid(const std::string &mac) { + CHECK_NULL_AND_RETURN(mIdlClient, WIFI_IDL_OPT_FAILED); return mIdlClient->DisconnectLastRoamingBssid(mac); } WifiErrorNo WifiStaHalInterface::GetSupportFeature(long &feature) { + CHECK_NULL_AND_RETURN(mIdlClient, WIFI_IDL_OPT_FAILED); return mIdlClient->ReqGetSupportFeature(feature); } WifiErrorNo WifiStaHalInterface::SendRequest(const WifiStaRequest &request) { + CHECK_NULL_AND_RETURN(mIdlClient, WIFI_IDL_OPT_FAILED); return mIdlClient->SendRequest(request); } WifiErrorNo WifiStaHalInterface::SetTxPower(int power) { + CHECK_NULL_AND_RETURN(mIdlClient, WIFI_IDL_OPT_FAILED); return mIdlClient->SetTxPower(power); } WifiErrorNo WifiStaHalInterface::Scan(const WifiScanParam &scanParam) { + CHECK_NULL_AND_RETURN(mIdlClient, WIFI_IDL_OPT_FAILED); return mIdlClient->Scan(scanParam); } WifiErrorNo WifiStaHalInterface::QueryScanInfos(std::vector &scanInfos) { + CHECK_NULL_AND_RETURN(mIdlClient, WIFI_IDL_OPT_FAILED); return mIdlClient->QueryScanInfos(scanInfos); } WifiErrorNo WifiStaHalInterface::GetNetworkList(std::vector &networkList) { + CHECK_NULL_AND_RETURN(mIdlClient, WIFI_IDL_OPT_FAILED); return mIdlClient->ReqGetNetworkList(networkList); } WifiErrorNo WifiStaHalInterface::StartPnoScan(const WifiPnoScanParam &scanParam) { + CHECK_NULL_AND_RETURN(mIdlClient, WIFI_IDL_OPT_FAILED); return mIdlClient->ReqStartPnoScan(scanParam); } WifiErrorNo WifiStaHalInterface::StopPnoScan(void) { + CHECK_NULL_AND_RETURN(mIdlClient, WIFI_IDL_OPT_FAILED); return mIdlClient->ReqStopPnoScan(); } WifiErrorNo WifiStaHalInterface::RemoveDevice(int networkId) { + CHECK_NULL_AND_RETURN(mIdlClient, WIFI_IDL_OPT_FAILED); return mIdlClient->RemoveDevice(networkId); } WifiErrorNo WifiStaHalInterface::ClearDeviceConfig(void) const { + CHECK_NULL_AND_RETURN(mIdlClient, WIFI_IDL_OPT_FAILED); return mIdlClient->ClearDeviceConfig(); } WifiErrorNo WifiStaHalInterface::GetNextNetworkId(int &networkId) { + CHECK_NULL_AND_RETURN(mIdlClient, WIFI_IDL_OPT_FAILED); return mIdlClient->GetNextNetworkId(networkId); } WifiErrorNo WifiStaHalInterface::EnableNetwork(int networkId) { + CHECK_NULL_AND_RETURN(mIdlClient, WIFI_IDL_OPT_FAILED); return mIdlClient->ReqEnableNetwork(networkId); } WifiErrorNo WifiStaHalInterface::DisableNetwork(int networkId) { + CHECK_NULL_AND_RETURN(mIdlClient, WIFI_IDL_OPT_FAILED); return mIdlClient->ReqDisableNetwork(networkId); } WifiErrorNo WifiStaHalInterface::SetDeviceConfig(int networkId, const WifiIdlDeviceConfig &config) { + CHECK_NULL_AND_RETURN(mIdlClient, WIFI_IDL_OPT_FAILED); return mIdlClient->SetDeviceConfig(networkId, config); } WifiErrorNo WifiStaHalInterface::GetDeviceConfig(WifiIdlGetDeviceConfig &config) { + CHECK_NULL_AND_RETURN(mIdlClient, WIFI_IDL_OPT_FAILED); return mIdlClient->GetDeviceConfig(config); } WifiErrorNo WifiStaHalInterface::SaveDeviceConfig(void) { + CHECK_NULL_AND_RETURN(mIdlClient, WIFI_IDL_OPT_FAILED); return mIdlClient->SaveDeviceConfig(); } WifiErrorNo WifiStaHalInterface::RegisterStaEventCallback(const WifiEventCallback &callback) { + CHECK_NULL_AND_RETURN(mIdlClient, WIFI_IDL_OPT_FAILED); WifiErrorNo err = mIdlClient->ReqRegisterStaEventCallback(callback); if (err == WIFI_IDL_OPT_OK || callback.onConnectChanged == nullptr) { mStaCallback = callback; @@ -188,6 +217,7 @@ WifiErrorNo WifiStaHalInterface::RegisterStaEventCallback(const WifiEventCallbac WifiErrorNo WifiStaHalInterface::StartWpsPbcMode(const WifiIdlWpsConfig &config) { + CHECK_NULL_AND_RETURN(mIdlClient, WIFI_IDL_OPT_FAILED); return mIdlClient->ReqStartWpsPbcMode(config); } @@ -196,31 +226,43 @@ WifiErrorNo WifiStaHalInterface::StartWpsPinMode(const WifiIdlWpsConfig &config, if (!config.pinCode.empty() && config.pinCode.length() != WIFI_IDL_PIN_CODE_LENGTH) { return WIFI_IDL_OPT_INVALID_PARAM; } + CHECK_NULL_AND_RETURN(mIdlClient, WIFI_IDL_OPT_FAILED); return mIdlClient->ReqStartWpsPinMode(config, pinCode); } WifiErrorNo WifiStaHalInterface::StopWps(void) { + CHECK_NULL_AND_RETURN(mIdlClient, WIFI_IDL_OPT_FAILED); return mIdlClient->ReqStopWps(); } WifiErrorNo WifiStaHalInterface::GetRoamingCapabilities(WifiIdlRoamCapability &capability) { + CHECK_NULL_AND_RETURN(mIdlClient, WIFI_IDL_OPT_FAILED); return mIdlClient->ReqGetRoamingCapabilities(capability); } +WifiErrorNo WifiStaHalInterface::SetWpsBssid(int networkId, const std::string &bssid) +{ + CHECK_NULL_AND_RETURN(mIdlClient, WIFI_IDL_OPT_FAILED); + return mIdlClient->SetWpsBssid(networkId, bssid); +} + WifiErrorNo WifiStaHalInterface::SetRoamConfig(const WifiIdlRoamConfig &config) { + CHECK_NULL_AND_RETURN(mIdlClient, WIFI_IDL_OPT_FAILED); return mIdlClient->ReqSetRoamConfig(config); } WifiErrorNo WifiStaHalInterface::WpaAutoConnect(int enable) { + CHECK_NULL_AND_RETURN(mIdlClient, WIFI_IDL_OPT_FAILED); return mIdlClient->ReqWpaAutoConnect(enable); } WifiErrorNo WifiStaHalInterface::WpaBlocklistClear() { + CHECK_NULL_AND_RETURN(mIdlClient, WIFI_IDL_OPT_FAILED); return mIdlClient->ReqWpaBlocklistClear(); } @@ -229,6 +271,7 @@ WifiErrorNo WifiStaHalInterface::GetConnectSignalInfo(const std::string &endBssi if (endBssid.length() != WIFI_IDL_BSSID_LENGTH) { return WIFI_IDL_OPT_INPUT_MAC_INVALID; } + CHECK_NULL_AND_RETURN(mIdlClient, WIFI_IDL_OPT_FAILED); return mIdlClient->ReqGetConnectSignalInfo(endBssid, info); } diff --git a/services/wifi_standard/wifi_framework/wifi_manage/idl_client/wifi_sta_hal_interface.h b/wifi/services/wifi_standard/wifi_framework/wifi_manage/idl_client/wifi_sta_hal_interface.h similarity index 97% rename from services/wifi_standard/wifi_framework/wifi_manage/idl_client/wifi_sta_hal_interface.h rename to wifi/services/wifi_standard/wifi_framework/wifi_manage/idl_client/wifi_sta_hal_interface.h index 9d035d35efc7f10a16a70d1e27e3e18d758bc85d..e66cc9aa51aca61c4e86abcd320ddbe17e7963e3 100644 --- a/services/wifi_standard/wifi_framework/wifi_manage/idl_client/wifi_sta_hal_interface.h +++ b/wifi/services/wifi_standard/wifi_framework/wifi_manage/idl_client/wifi_sta_hal_interface.h @@ -286,6 +286,15 @@ public: */ WifiErrorNo GetRoamingCapabilities(WifiIdlRoamCapability &capability); + /** + * @Description Set bssid to supplicant. + * + * @param networkId + * @param bssid + * @return WifiErrorNo + */ + WifiErrorNo SetWpsBssid(int networkId, const std::string &bssid); + /** * @Description Setting Roaming Configurations. * diff --git a/services/wifi_standard/wifi_framework/wifi_manage/idl_client/wifi_sta_request.h b/wifi/services/wifi_standard/wifi_framework/wifi_manage/idl_client/wifi_sta_request.h similarity index 100% rename from services/wifi_standard/wifi_framework/wifi_manage/idl_client/wifi_sta_request.h rename to wifi/services/wifi_standard/wifi_framework/wifi_manage/idl_client/wifi_sta_request.h diff --git a/services/wifi_standard/wifi_framework/wifi_manage/idl_client/wifi_supplicant_hal_interface.cpp b/wifi/services/wifi_standard/wifi_framework/wifi_manage/idl_client/wifi_supplicant_hal_interface.cpp similarity index 76% rename from services/wifi_standard/wifi_framework/wifi_manage/idl_client/wifi_supplicant_hal_interface.cpp rename to wifi/services/wifi_standard/wifi_framework/wifi_manage/idl_client/wifi_supplicant_hal_interface.cpp index 04f641677869ce63e3f2e17e78d8c8df0e736f9d..03ff718ac2ae3ff81eb09b6f2c5022c9395b543a 100644 --- a/services/wifi_standard/wifi_framework/wifi_manage/idl_client/wifi_supplicant_hal_interface.cpp +++ b/wifi/services/wifi_standard/wifi_framework/wifi_manage/idl_client/wifi_supplicant_hal_interface.cpp @@ -1,5 +1,5 @@ /* - * Copyright (C) 2021 Huawei Device Co., Ltd. + * Copyright (C) 2021-2022 Huawei Device Co., Ltd. * 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 @@ -39,31 +39,37 @@ WifiSupplicantHalInterface &WifiSupplicantHalInterface::GetInstance(void) WifiErrorNo WifiSupplicantHalInterface::StartSupplicant(void) const { + CHECK_NULL_AND_RETURN(mIdlClient, WIFI_IDL_OPT_FAILED); return mIdlClient->ReqStartSupplicant(); } WifiErrorNo WifiSupplicantHalInterface::StopSupplicant(void) const { + CHECK_NULL_AND_RETURN(mIdlClient, WIFI_IDL_OPT_FAILED); return mIdlClient->ReqStopSupplicant(); } WifiErrorNo WifiSupplicantHalInterface::ConnectSupplicant(void) const { + CHECK_NULL_AND_RETURN(mIdlClient, WIFI_IDL_OPT_FAILED); return mIdlClient->ReqConnectSupplicant(); } WifiErrorNo WifiSupplicantHalInterface::DisconnectSupplicant(void) const { + CHECK_NULL_AND_RETURN(mIdlClient, WIFI_IDL_OPT_FAILED); return mIdlClient->ReqDisconnectSupplicant(); } WifiErrorNo WifiSupplicantHalInterface::RequestToSupplicant(const std::string &request) const { + CHECK_NULL_AND_RETURN(mIdlClient, WIFI_IDL_OPT_FAILED); return mIdlClient->ReqRequestToSupplicant(request); } WifiErrorNo WifiSupplicantHalInterface::RegisterSupplicantEventCallback(SupplicantEventCallback &callback) { + CHECK_NULL_AND_RETURN(mIdlClient, WIFI_IDL_OPT_FAILED); WifiErrorNo err = mIdlClient->ReqRegisterSupplicantEventCallback(callback); if (err == WIFI_IDL_OPT_OK) { mCallback = callback; @@ -73,6 +79,7 @@ WifiErrorNo WifiSupplicantHalInterface::RegisterSupplicantEventCallback(Supplica WifiErrorNo WifiSupplicantHalInterface::UnRegisterSupplicantEventCallback(void) { + CHECK_NULL_AND_RETURN(mIdlClient, WIFI_IDL_OPT_FAILED); WifiErrorNo err = mIdlClient->ReqUnRegisterSupplicantEventCallback(); mCallback.onScanNotify = nullptr; return err; @@ -80,16 +87,19 @@ WifiErrorNo WifiSupplicantHalInterface::UnRegisterSupplicantEventCallback(void) WifiErrorNo WifiSupplicantHalInterface::SetPowerSave(bool enable) const { + CHECK_NULL_AND_RETURN(mIdlClient, WIFI_IDL_OPT_FAILED); return mIdlClient->ReqSetPowerSave(enable); } WifiErrorNo WifiSupplicantHalInterface::WpaSetCountryCode(const std::string &countryCode) const { + CHECK_NULL_AND_RETURN(mIdlClient, WIFI_IDL_OPT_FAILED); return mIdlClient->ReqWpaSetCountryCode(countryCode); } WifiErrorNo WifiSupplicantHalInterface::WpaGetCountryCode(std::string &countryCode) const { + CHECK_NULL_AND_RETURN(mIdlClient, WIFI_IDL_OPT_FAILED); return mIdlClient->ReqWpaGetCountryCode(countryCode); } @@ -97,5 +107,11 @@ const SupplicantEventCallback &WifiSupplicantHalInterface::GetCallbackInst(void) { return mCallback; } + +WifiErrorNo WifiSupplicantHalInterface::WpaSetSuspendMode(bool mode) const +{ + CHECK_NULL_AND_RETURN(mIdlClient, WIFI_IDL_OPT_FAILED); + return mIdlClient->ReqWpaSetSuspendMode(mode); +} } // namespace Wifi -} // namespace OHOS \ No newline at end of file +} // namespace OHOS diff --git a/services/wifi_standard/wifi_framework/wifi_manage/idl_client/wifi_supplicant_hal_interface.h b/wifi/services/wifi_standard/wifi_framework/wifi_manage/idl_client/wifi_supplicant_hal_interface.h similarity index 92% rename from services/wifi_standard/wifi_framework/wifi_manage/idl_client/wifi_supplicant_hal_interface.h rename to wifi/services/wifi_standard/wifi_framework/wifi_manage/idl_client/wifi_supplicant_hal_interface.h index f5d13cbbb72cfbce6c86d504004f645dbf75bbb6..c3909b979cf12a4617a99f0d15f90f273fb7682d 100644 --- a/services/wifi_standard/wifi_framework/wifi_manage/idl_client/wifi_supplicant_hal_interface.h +++ b/wifi/services/wifi_standard/wifi_framework/wifi_manage/idl_client/wifi_supplicant_hal_interface.h @@ -115,6 +115,14 @@ public: */ const SupplicantEventCallback &GetCallbackInst(void) const; + /** + * @Description Set suspend mode to wpa + * + * @param mode - true for suspend mode, false for resume mode + * + * @Return success: WIFI_OPT_SUCCESS, fail: WIFI_OPT_FAILED + */ + WifiErrorNo WpaSetSuspendMode(bool mode) const; private: SupplicantEventCallback mCallback; }; diff --git a/services/wifi_standard/wifi_framework/wifi_manage/wifi_ap/BUILD.gn b/wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_ap/BUILD.gn similarity index 37% rename from services/wifi_standard/wifi_framework/wifi_manage/wifi_ap/BUILD.gn rename to wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_ap/BUILD.gn index 5006bc005be4eb6edf54c4f3856f9e048f5d0669..422dc8d5977ba4623e8a88fd736a14d7ce2ed1a2 100644 --- a/services/wifi_standard/wifi_framework/wifi_manage/wifi_ap/BUILD.gn +++ b/wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_ap/BUILD.gn @@ -1,4 +1,4 @@ -# Copyright (C) 2021 Huawei Device Co., Ltd. +# Copyright (C) 2021-2022 Huawei Device Co., Ltd. # 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 @@ -12,6 +12,7 @@ # limitations under the License. import("//build/ohos.gni") +import("//foundation/communication/wifi/wifi/wifi.gni") ohos_shared_library("wifi_ap_service") { install_enable = true @@ -21,7 +22,6 @@ ohos_shared_library("wifi_ap_service") { "../common/message_queue.cpp", "../common/state.cpp", "../common/state_machine.cpp", - "//foundation/communication/wifi/services/wifi_standard/wifi_framework/common/net_helper/dhcpd_interface.cpp", "ap_config_use.cpp", "ap_idle_state.cpp", "ap_interface.cpp", @@ -35,24 +35,28 @@ ohos_shared_library("wifi_ap_service") { ] include_dirs = [ - "//foundation/communication/wifi/services/wifi_standard/ipc_framework/interface", - "//utils/native/base/include", + "$WIFI_ROOT_DIR/services/wifi_standard/ipc_framework/interface", + "//commonlibrary/c_utils/base/include", "//base/hiviewdfx/hilog/interfaces/native/innerkits/include", - "//foundation/communication/wifi/interfaces/innerkits/native_cpp/wifi_standard/interfaces", - "//foundation/communication/wifi/services/wifi_standard/ipc_framework/cRPC/include", - "//foundation/communication/wifi/services/wifi_standard/wifi_framework/common/include", - "//foundation/communication/wifi/services/wifi_standard/wifi_framework/common/net_helper", - "//foundation/communication/wifi/services/wifi_standard/wifi_framework/common/config", - "//foundation/communication/wifi/services/wifi_standard/wifi_framework/common/log", - "//foundation/communication/wifi/services/wifi_standard/wifi_framework/common/utils", - "//foundation/communication/wifi/services/wifi_standard/wifi_framework/wifi_manage/common/include", - "//foundation/communication/wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_ap", - "//foundation/communication/wifi/services/wifi_standard/wifi_framework/wifi_manage", - "//foundation/communication/wifi/services/wifi_standard/wifi_framework/wifi_manage/common", - "//foundation/communication/wifi/services/wifi_standard/wifi_framework/wifi_manage/idl_client", - "//foundation/communication/wifi/services/wifi_standard/wifi_framework/wifi_manage/idl_client/idl_interface", - "//foundation/communication/wifi/services/wifi_standard/wifi_framework/dhcp_manage/mgr_service/include", - "//foundation/communication/wifi/services/wifi_standard/wifi_framework/dhcp_manage/mgr_service/interfaces", + "$WIFI_ROOT_DIR/frameworks/native/interfaces", + "$WIFI_ROOT_DIR/services/wifi_standard/ipc_framework/cRPC/include", + "$WIFI_ROOT_DIR/services/wifi_standard/wifi_framework/wifi_toolkit/include", + "$WIFI_ROOT_DIR/services/wifi_standard/wifi_framework/wifi_toolkit/net_helper", + "$WIFI_ROOT_DIR/services/wifi_standard/wifi_framework/wifi_toolkit/config", + "$WIFI_ROOT_DIR/services/wifi_standard/wifi_framework/wifi_toolkit/log", + "$WIFI_ROOT_DIR/services/wifi_standard/wifi_framework/wifi_toolkit/utils", + "$WIFI_ROOT_DIR/services/wifi_standard/wifi_framework/wifi_manage/common/include", + "$WIFI_ROOT_DIR/services/wifi_standard/wifi_framework/wifi_manage/wifi_ap", + "$WIFI_ROOT_DIR/services/wifi_standard/wifi_framework/wifi_manage", + "$WIFI_ROOT_DIR/services/wifi_standard/wifi_framework/wifi_manage/common", + "$WIFI_ROOT_DIR/services/wifi_standard/wifi_framework/wifi_manage/idl_client", + "$WIFI_ROOT_DIR/services/wifi_standard/wifi_framework/wifi_manage/idl_client/idl_interface", + "$DHCP_ROOT_DIR/services/mgr_service/include", + "$DHCP_ROOT_DIR/interfaces/inner_api/include", + "$DHCP_ROOT_DIR/interfaces/inner_api/interfaces", + "$WIFI_ROOT_DIR/utils/inc", + "$WIFI_ROOT_DIR/services/wifi_standard/wifi_framework/wifi_manage/wifi_common", + "$WIFI_ROOT_DIR/services/wifi_standard/include", ] cflags_cc = [ @@ -65,15 +69,24 @@ ohos_shared_library("wifi_ap_service") { "-Wl,-E", ] - external_deps = [ "hiviewdfx_hilog_native:libhilog" ] + external_deps = [ + "c_utils:utils", + "hiviewdfx_hilog_native:libhilog", + ] deps = [ - "//foundation/communication/wifi/services/wifi_standard/wifi_framework/dhcp_manage/mgr_service:dhcp_manager_service", - "//foundation/communication/wifi/services/wifi_standard/wifi_framework/wifi_manage:wifi_manager_service", - "//foundation/communication/wifi/services/wifi_standard/wifi_framework/wifi_manage/idl_client:wifi_idl_client", - "//utils/native/base:utils", + "$WIFI_ROOT_DIR/services/wifi_standard/wifi_framework/wifi_manage/idl_client:wifi_idl_client", + "$WIFI_ROOT_DIR/services/wifi_standard/wifi_framework/wifi_manage/wifi_common:wifi_common_service", + "$WIFI_ROOT_DIR/services/wifi_standard/wifi_framework/wifi_toolkit:wifi_toolkit", + "$WIFI_ROOT_DIR/utils:wifi_utils", ] - part_name = "wifi_standard" + defines = [ "AP_INTF=\"$wifi_feature_with_ap_intf\"" ] + + if (wifi_feature_with_dhcp_disable) { + defines += [ "WIFI_DHCP_DISABLED" ] + } + + part_name = "wifi" subsystem_name = "communication" } diff --git a/services/wifi_standard/wifi_framework/wifi_manage/wifi_ap/ap_config_use.cpp b/wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_ap/ap_config_use.cpp similarity index 70% rename from services/wifi_standard/wifi_framework/wifi_manage/wifi_ap/ap_config_use.cpp rename to wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_ap/ap_config_use.cpp index b8f418b8ac735904252dbf600b02e23e06e7f574..8e380a2f975582c5b46dde5e65a60f03cc9eff76 100644 --- a/services/wifi_standard/wifi_framework/wifi_manage/wifi_ap/ap_config_use.cpp +++ b/wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_ap/ap_config_use.cpp @@ -25,7 +25,7 @@ DEFINE_WIFILOG_HOTSPOT_LABEL("WifiApConfigUse"); namespace OHOS { namespace Wifi { -ApConfigUse::ApConfigUse() +ApConfigUse::ApConfigUse(int id) : m_id(id) {} ApConfigUse::~ApConfigUse() @@ -61,7 +61,7 @@ void ApConfigUse::TransformFrequencyIntoChannel(const std::vector &freqVect printList += std::to_string(chanVector[i]); printList += " "; } - WIFI_LOGD("TransformFrequencyIntoChannel:size:(%{public}zu) to (%{public}zu).list: %{public}s", + WIFI_LOGD("TransformFrequencyIntoChannel:size:(%{public}zu) to (%{public}zu).list: %{public}s.", freqVector.size(), chanVector.size(), printList.c_str()); @@ -69,8 +69,9 @@ void ApConfigUse::TransformFrequencyIntoChannel(const std::vector &freqVect void ApConfigUse::LogConfig(HotspotConfig &apConfig) const { - WIFI_LOGI("HotspotConfig::SSID = %s", apConfig.GetSsid().c_str()); - WIFI_LOGI("HotspotConfig::preSharedKey = %s", apConfig.GetPreSharedKey().c_str()); + WIFI_LOGI("current instance is %{public}d", m_id); + WIFI_LOGI("HotspotConfig::SSID = %{private}s", apConfig.GetSsid().c_str()); + WIFI_LOGI("HotspotConfig::preSharedKey = %{private}s", apConfig.GetPreSharedKey().c_str()); WIFI_LOGI("HotspotConfig::securityType = %{public}d", static_cast(apConfig.GetSecurityType())); WIFI_LOGI("HotspotConfig::band = %{public}d", static_cast(apConfig.GetBand())); WIFI_LOGI("HotspotConfig::channel = %{public}d", apConfig.GetChannel()); @@ -79,20 +80,41 @@ void ApConfigUse::LogConfig(HotspotConfig &apConfig) const bool ApConfigUse::IsValid24GHz(int freq) const { - return (freq > FREP_2G_MIN) && (freq < FREP_2G_MAX); + return (freq >= FREP_2G_MIN) && (freq <= CHANNEL_14_FREP); } bool ApConfigUse::IsValid5GHz(int freq) const { - return (freq > FREP_5G_MIN) && (freq < FREP_5G_MAX); + return (freq >= FREP_5G_MIN) && (freq <= FREP_5G_MAX); } +void ApConfigUse::ApplyDefaultConfig(HotspotConfig &apConfig, std::vector &vecChannels) const +{ + if (!vecChannels.empty()) { + apConfig.SetChannel(vecChannels.front()); + return; + } + + if (apConfig.GetBand() == BandType::BAND_2GHZ) { + apConfig.SetChannel(AP_CHANNEL_DEFAULT); + return; + } + if (apConfig.GetBand() == BandType::BAND_5GHZ) { + apConfig.SetChannel(AP_CHANNEL_5G_DEFAULT); + return; + } + apConfig.SetBand(BandType::BAND_2GHZ); + apConfig.SetChannel(AP_CHANNEL_DEFAULT); + return; +} void ApConfigUse::CheckBandChannel(HotspotConfig &apConfig, const ChannelsTable &validChanTable) const { bool cfgValid = false; + std::vector vecChannels; auto it = validChanTable.find(apConfig.GetBand()); if (it != validChanTable.end() && it->second.size() != 0) { + vecChannels = it->second; for (auto vecIt = it->second.begin(); vecIt != it->second.end(); ++vecIt) { if (*vecIt == apConfig.GetChannel()) { cfgValid = true; @@ -101,9 +123,11 @@ void ApConfigUse::CheckBandChannel(HotspotConfig &apConfig, const ChannelsTable } } if (!cfgValid) { - WIFI_LOGW("Error band or error channels in band, use 2.4G band default channel."); - apConfig.SetBand(BandType::BAND_2GHZ); - apConfig.SetChannel(AP_CHANNEL_DEFAULT); + WIFI_LOGE("Error band or error channels in band: %{public}d, %{public}d", + static_cast(apConfig.GetBand()), apConfig.GetChannel()); + ApplyDefaultConfig(apConfig, vecChannels); + WIFI_LOGI("Use default config: %{public}d, %{public}d", + static_cast(apConfig.GetBand()), apConfig.GetChannel()); } } } // namespace Wifi diff --git a/services/wifi_standard/wifi_framework/wifi_manage/wifi_ap/ap_config_use.h b/wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_ap/ap_config_use.h similarity index 85% rename from services/wifi_standard/wifi_framework/wifi_manage/wifi_ap/ap_config_use.h rename to wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_ap/ap_config_use.h index 2bc98a1aebffeab042f3c4b185072ddc929dee3e..e7d1a908a81a98efabf3221189eeae4862234ebc 100644 --- a/services/wifi_standard/wifi_framework/wifi_manage/wifi_ap/ap_config_use.h +++ b/wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_ap/ap_config_use.h @@ -1,5 +1,5 @@ /* - * Copyright (C) 2021 Huawei Device Co., Ltd. + * Copyright (C) 2021-2022 Huawei Device Co., Ltd. * 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 @@ -16,9 +16,10 @@ #define OHOS_AP_CONFIG_UTIL_H #include +#include #include "ap_define.h" #include "ap_macro.h" -#include "wifi_msg.h" +#include "wifi_ap_msg.h" namespace OHOS { namespace Wifi { @@ -69,14 +70,14 @@ public: * @param validChanTable - Valid channel tables. * @return None */ - virtual void CheckBandChannel(HotspotConfig &apConfig, const ChannelsTable &validChanTable) const; + virtual void CheckBandChannel(HotspotConfig &apConfig, const ChannelsTable &validChanTable) const;; /** * @Description construction method * @param None * @return None */ - ApConfigUse(); + explicit ApConfigUse(int id = 0); /** * @Description destructor method * @param None @@ -84,13 +85,22 @@ public: */ virtual ~ApConfigUse(); /** - * @Description Convert frequency to channel number + * @Description Convert frequency to channel number. * @param freq - frequency to convert * @return success: channel num failed: -1 */ virtual int TransformFrequencyIntoChannel(const int freq) const; private: + /** + * @Description apply default configuration. + * @param apConfig + * @param vecChannels + * @return None + */ + void ApplyDefaultConfig(HotspotConfig &apConfig, std::vector &vecChannels) const;; + int m_id; + DISALLOW_COPY_AND_ASSIGN(ApConfigUse) }; } // namespace Wifi diff --git a/services/wifi_standard/wifi_framework/wifi_manage/wifi_ap/ap_define.h b/wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_ap/ap_define.h similarity index 89% rename from services/wifi_standard/wifi_framework/wifi_manage/wifi_ap/ap_define.h rename to wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_ap/ap_define.h index d871e25eb6cc975f099f5c8e2ba5dfd0e0203ede..8fc2b5066dcc79e43d3e08ed15561e901ea8fc50 100644 --- a/services/wifi_standard/wifi_framework/wifi_manage/wifi_ap/ap_define.h +++ b/wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_ap/ap_define.h @@ -1,5 +1,5 @@ /* - * Copyright (C) 2021 Huawei Device Co., Ltd. + * Copyright (C) 2021-2022 Huawei Device Co., Ltd. * 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 @@ -15,11 +15,10 @@ #ifndef OHOS_AP_DEFINE_H #define OHOS_AP_DEFINE_H -#include #include +#include #include "ap_macro.h" -#include "wifi_msg.h" namespace OHOS { namespace Wifi { @@ -37,9 +36,9 @@ const std::string GETTING_INFO = "Obtaining..."; /* *********************************StateMachine*************************** */ -/* Internal communication message of the state machine */ +/* Internal communication message of the state machine. */ enum class ApStatemachineEvent { - CMD_START_HOTSPOT, /* start */ + CMD_START_HOTSPOT, /* start */ CMD_STOP_HOTSPOT, /* stop */ CMD_FAIL, /* failed */ CMD_STATION_JOIN, /* new station */ @@ -55,4 +54,4 @@ enum class ApStatemachineEvent { using HandlerMethod = void(ApStatemachineEvent, int, int, const std::any &); } } // namespace OHOS -#endif /* OHOS_AP_DEFINE_H */ \ No newline at end of file +#endif /* OHOS_AP_DEFINE_H */ diff --git a/services/wifi_standard/wifi_framework/wifi_manage/wifi_ap/ap_idle_state.cpp b/wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_ap/ap_idle_state.cpp similarity index 82% rename from services/wifi_standard/wifi_framework/wifi_manage/wifi_ap/ap_idle_state.cpp rename to wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_ap/ap_idle_state.cpp index efe2adec39808f6e3ce0160b814dec3c3dfcb41d..c09884e1450c13e949fc89354d63c28c48e46f1a 100644 --- a/services/wifi_standard/wifi_framework/wifi_manage/wifi_ap/ap_idle_state.cpp +++ b/wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_ap/ap_idle_state.cpp @@ -21,8 +21,8 @@ DEFINE_WIFILOG_HOTSPOT_LABEL("WifiApIdleState"); namespace OHOS { namespace Wifi { -ApIdleState::ApIdleState(ApStateMachine &apStateMachine) - : State("ApIdleState"), m_ApStateMachine(apStateMachine) +ApIdleState::ApIdleState(ApStateMachine &apStateMachine, int id) + : State("ApIdleState"), m_ApStateMachine(apStateMachine), m_id(id) {} ApIdleState::~ApIdleState() @@ -30,12 +30,12 @@ ApIdleState::~ApIdleState() void ApIdleState::GoInState() { - WIFI_LOGI("%{public}s GoInState.", GetStateName().c_str()); + WIFI_LOGI("Instance %{public}d %{public}s GoInState.", m_id, GetStateName().c_str()); } void ApIdleState::GoOutState() { - WIFI_LOGI("%{public}s GoOutState.", GetStateName().c_str()); + WIFI_LOGI("Instance %{public}d %{public}s GoOutState.", m_id, GetStateName().c_str()); } bool ApIdleState::ExecuteStateMsg(InternalMessage *msg) @@ -57,7 +57,6 @@ bool ApIdleState::ExecuteStateMsg(InternalMessage *msg) } default: return NOT_EXECUTED; - break; } return EXECUTED; diff --git a/services/wifi_standard/wifi_framework/wifi_manage/wifi_ap/ap_idle_state.h b/wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_ap/ap_idle_state.h similarity index 91% rename from services/wifi_standard/wifi_framework/wifi_manage/wifi_ap/ap_idle_state.h rename to wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_ap/ap_idle_state.h index 53fc04533fe6327898803c0fbe5a8bf4bc2e5fd7..30a26633165de03ea3f3131c23607ed0aa1e3759 100644 --- a/services/wifi_standard/wifi_framework/wifi_manage/wifi_ap/ap_idle_state.h +++ b/wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_ap/ap_idle_state.h @@ -27,13 +27,13 @@ class ApIdleState : public State { public: /** - * @Description construction method + * @Description construction method. * @param None * @return None */ - explicit ApIdleState(ApStateMachine &); + explicit ApIdleState(ApStateMachine &, int id = 0); /** - * @Description destructor method + * @Description destructor method. * @param None * @return None */ @@ -60,6 +60,7 @@ public: virtual bool ExecuteStateMsg(InternalMessage *msg) override; private: ApStateMachine &m_ApStateMachine; + int m_id; }; } // namespace Wifi } // namespace OHOS diff --git a/services/wifi_standard/wifi_framework/wifi_manage/wifi_ap/ap_interface.cpp b/wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_ap/ap_interface.cpp similarity index 71% rename from services/wifi_standard/wifi_framework/wifi_manage/wifi_ap/ap_interface.cpp rename to wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_ap/ap_interface.cpp index 3a7f173dcb435eaed98c6fae6f6d7ed2e74149f6..5c9d7f2e30e90524826dc6c44d746fe203caaa4b 100644 --- a/services/wifi_standard/wifi_framework/wifi_manage/wifi_ap/ap_interface.cpp +++ b/wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_ap/ap_interface.cpp @@ -17,28 +17,29 @@ namespace OHOS { namespace Wifi { -ApInterface::ApInterface() - : m_ApRootState(), - m_ApStartedState(m_ApStateMachine, m_ApConfigUse, m_ApMonitor), - m_ApIdleState(m_ApStateMachine), - m_ApMonitor(), - m_ApStateMachine(m_ApStationsManager, m_ApRootState, m_ApIdleState, m_ApStartedState, m_ApMonitor), - m_ApService(m_ApStateMachine), - m_ApStationsManager(), - m_ApConfigUse() +ApInterface::ApInterface(int id) + : m_ApRootState(id), + m_ApStartedState(m_ApStateMachine, m_ApConfigUse, m_ApMonitor, id), + m_ApIdleState(m_ApStateMachine, id), + m_ApMonitor(id), + m_ApStateMachine(m_ApStationsManager, m_ApRootState, m_ApIdleState, m_ApStartedState, m_ApMonitor, id), + m_ApService(m_ApStateMachine, id), + m_ApStationsManager(id), + m_ApConfigUse(id) {} ApInterface::~ApInterface() {} -extern "C" IApService *Create(void) +extern "C" IApService *Create(int id = 0) { - return new ApInterface(); + return new ApInterface(id); } extern "C" void Destroy(IApService *pservice) { delete pservice; + pservice = nullptr; } ErrCode ApInterface::EnableHotspot() { @@ -80,14 +81,29 @@ ErrCode ApInterface::GetValidBands(std::vector &bands) return m_ApService.GetValidBands(bands); } -ErrCode ApInterface::GetValidChannels(BandType band, std::vector &validchannel) +ErrCode ApInterface::GetValidChannels(BandType band, std::vector &validChannel) { - return m_ApService.GetValidChannels(band, validchannel); + return m_ApService.GetValidChannels(band, validChannel); } ErrCode ApInterface::RegisterApServiceCallbacks(const IApServiceCallbacks &callbacks) { return m_ApService.RegisterApServiceCallbacks(callbacks); } + +ErrCode ApInterface::GetSupportedPowerModel(std::set& setPowerModelList) +{ + return m_ApService.GetSupportedPowerModel(setPowerModelList); +} + +ErrCode ApInterface::GetPowerModel(PowerModel& model) +{ + return m_ApService.GetPowerModel(model); +} + +ErrCode ApInterface::SetPowerModel(const PowerModel& model) +{ + return m_ApService.SetPowerModel(model); +} } // namespace Wifi } // namespace OHOS \ No newline at end of file diff --git a/services/wifi_standard/wifi_framework/wifi_manage/wifi_ap/ap_interface.h b/wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_ap/ap_interface.h similarity index 80% rename from services/wifi_standard/wifi_framework/wifi_manage/wifi_ap/ap_interface.h rename to wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_ap/ap_interface.h index 73357a48fd66ff7bc76af79790d13da480fa2ff7..526a0a5795c1a8deb0b7ed3557b871ea9d7ea2dc 100644 --- a/services/wifi_standard/wifi_framework/wifi_manage/wifi_ap/ap_interface.h +++ b/wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_ap/ap_interface.h @@ -25,13 +25,13 @@ namespace Wifi { class ApInterface : public IApService { public: /** - * @Description construction method + * @Description construction method. * @param None * @return None */ - ApInterface(); + explicit ApInterface(int id = 0); /** - * @Description destructor method + * @Description destructor method. * @param None * @return None */ @@ -74,7 +74,7 @@ public: virtual ErrCode SetHotspotConfig(const HotspotConfig &hotspotConfig) override; /** - * @Description Disconnet Station connect from station information. + * @Description Disconnect Station connect from station information. * @param stationInfo - station information. * @return ErrCode - success: WIFI_OPT_SUCCESS failed: ERROR_CODE */ @@ -110,7 +110,31 @@ public: * @param validchannel - band's valid channel * @return ErrCode - success: WIFI_OPT_SUCCESS failed: ERROR_CODE */ - virtual ErrCode GetValidChannels(BandType band, std::vector &validchannel) override; + virtual ErrCode GetValidChannels(BandType band, std::vector &validChannel) override; + + /** + * @Description Get supported power model list + * + * @param setPowerModelList - supported power model list + * @return ErrCode - operation result + */ + virtual ErrCode GetSupportedPowerModel(std::set& setPowerModelList) override; + + /** + * @Description Get power model + * + * @param model - current power model + * @return ErrCode - operation result + */ + virtual ErrCode GetPowerModel(PowerModel& model) override; + + /** + * @Description Get supported power model list + * + * @param model - the model to be set + * @return ErrCode - operation result + */ + virtual ErrCode SetPowerModel(const PowerModel& model) override; private: ApRootState m_ApRootState; diff --git a/services/wifi_standard/wifi_framework/wifi_manage/wifi_ap/ap_macro.h b/wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_ap/ap_macro.h similarity index 94% rename from services/wifi_standard/wifi_framework/wifi_manage/wifi_ap/ap_macro.h rename to wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_ap/ap_macro.h index 5764b742cb8975cb7c1bb8d22a6e65cdc8914f67..e7d7ad3b6cca31d5bb94fe292194c2cdaf889017 100644 --- a/services/wifi_standard/wifi_framework/wifi_manage/wifi_ap/ap_macro.h +++ b/wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_ap/ap_macro.h @@ -21,7 +21,7 @@ */ #define DISALLOW_COPY_AND_ASSIGN(TypeName) \ TypeName(const TypeName &) = delete; \ - TypeName &operator=(const TypeName &) = delete; + TypeName (&operator=(const TypeName &)) = delete; #define FRIEND_GTEST(test_typename) friend class test_typename##_test #endif \ No newline at end of file diff --git a/services/wifi_standard/wifi_framework/wifi_manage/wifi_ap/ap_monitor.cpp b/wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_ap/ap_monitor.cpp similarity index 92% rename from services/wifi_standard/wifi_framework/wifi_manage/wifi_ap/ap_monitor.cpp rename to wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_ap/ap_monitor.cpp index eea3b37b82d0861b7f86eaa4bc1df23926bd836c..e9a5c74813555735b256d9861cf37967993f8b9f 100644 --- a/services/wifi_standard/wifi_framework/wifi_manage/wifi_ap/ap_monitor.cpp +++ b/wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_ap/ap_monitor.cpp @@ -1,5 +1,5 @@ /* - * Copyright (C) 2021 Huawei Device Co., Ltd. + * Copyright (C) 2021-2022 Huawei Device Co., Ltd. * 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 @@ -24,12 +24,13 @@ #include "wifi_ap_hal_interface.h" #include "wifi_logger.h" #include "dhcpd_interface.h" +#include "wifi_common_util.h" DEFINE_WIFILOG_HOTSPOT_LABEL("WifiApMonitor"); namespace OHOS { namespace Wifi { -ApMonitor::ApMonitor() +ApMonitor::ApMonitor(int id) : m_id(id) {} ApMonitor::~ApMonitor() @@ -43,8 +44,8 @@ void ApMonitor::DealStaJoinOrLeave(const StationInfo &info, ApStatemachineEvent WIFI_LOGI("StationChangeEvent event: [%{public}d(join=3,leave=4)] %{public}s . %{private}s . %{private}s.,", event, info.deviceName.c_str(), - info.bssid.c_str(), - info.ipAddr.c_str()); + MacAnonymize(info.bssid).c_str(), + IpAnonymize(info.ipAddr).c_str()); SendMessage(m_selectIfacName, event, 0, 0, anySta); } @@ -82,9 +83,9 @@ void ApMonitor::StartMonitor() std::bind(&ApMonitor::OnStaJoinOrLeave, this, _1), std::bind(&ApMonitor::OnHotspotStateEvent, this, _1), }; - WifiApHalInterface::GetInstance().RegisterApEvent(wifiApEventCallback); + WifiApHalInterface::GetInstance().RegisterApEvent(wifiApEventCallback, m_id); - std::string iface = "wlan0"; + std::string iface = std::string(AP_INTF) + std::to_string(m_id); m_selectIfacName = iface; m_setMonitorIface.insert(iface); } @@ -111,7 +112,7 @@ void ApMonitor::SendMessage( void ApMonitor::StopMonitor() { IWifiApMonitorEventCallback wifiApEventCallback = {}; - WifiApHalInterface::GetInstance().RegisterApEvent(wifiApEventCallback); + WifiApHalInterface::GetInstance().RegisterApEvent(wifiApEventCallback, m_id); } void ApMonitor::RegisterHandler(const std::string &iface, const std::function &handler) @@ -132,4 +133,4 @@ void ApMonitor::UnregisterHandler(const std::string &iface) } } } // namespace Wifi -} // namespace OHOS \ No newline at end of file +} // namespace OHOS diff --git a/services/wifi_standard/wifi_framework/wifi_manage/wifi_ap/ap_monitor.h b/wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_ap/ap_monitor.h similarity index 95% rename from services/wifi_standard/wifi_framework/wifi_manage/wifi_ap/ap_monitor.h rename to wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_ap/ap_monitor.h index 6afb5c1c02e5c1069f7d3ec546b66353e38c7bc3..1622bdf0f5375e0cdd006689cc00c22ed6fb8b8c 100644 --- a/services/wifi_standard/wifi_framework/wifi_manage/wifi_ap/ap_monitor.h +++ b/wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_ap/ap_monitor.h @@ -1,5 +1,5 @@ /* - * Copyright (C) 2021 Huawei Device Co., Ltd. + * Copyright (C) 2021-2022 Huawei Device Co., Ltd. * 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 @@ -12,11 +12,14 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + #ifndef OHOS_AP_MONITOR_H #define OHOS_AP_MONITOR_H #include +#include +#include "wifi_ap_msg.h" #include "ap_define.h" #include "wifi_idl_struct.h" @@ -26,7 +29,7 @@ class ApMonitor { FRIEND_GTEST(ApMonitor); public: - ApMonitor(); + explicit ApMonitor(int id = 0); virtual ~ApMonitor(); /** * @Description IDL called this interface when STA connected or @@ -96,6 +99,7 @@ private: std::map> m_mapHandler; std::string m_selectIfacName; std::set m_setMonitorIface; + int m_id; }; } // namespace Wifi } // namespace OHOS diff --git a/services/wifi_standard/wifi_framework/wifi_manage/wifi_ap/ap_root_state.cpp b/wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_ap/ap_root_state.cpp similarity index 83% rename from services/wifi_standard/wifi_framework/wifi_manage/wifi_ap/ap_root_state.cpp rename to wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_ap/ap_root_state.cpp index 8ae76e83edf5619894d9d88321a861eca0a9c78c..0e40c0b547a08d2743d574655bcca5c1c5763c32 100644 --- a/services/wifi_standard/wifi_framework/wifi_manage/wifi_ap/ap_root_state.cpp +++ b/wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_ap/ap_root_state.cpp @@ -21,7 +21,7 @@ DEFINE_WIFILOG_HOTSPOT_LABEL("WifiApRootState"); namespace OHOS { namespace Wifi { -ApRootState::ApRootState() : State("ApRootState") +ApRootState::ApRootState(int id) : State("ApRootState"), m_id(id) {} ApRootState::~ApRootState() @@ -29,12 +29,12 @@ ApRootState::~ApRootState() void ApRootState::GoInState() { - WIFI_LOGI("%{public}s GoInState.", GetStateName().c_str()); + WIFI_LOGI("Instance %{public}d %{public}s GoInState.", m_id, GetStateName().c_str()); } void ApRootState::GoOutState() { - WIFI_LOGI("%{public}s GoOutState.", GetStateName().c_str()); + WIFI_LOGI("Instance %{public}d %{public}s GoOutState.", m_id, GetStateName().c_str()); } bool ApRootState::ExecuteStateMsg(InternalMessage *msg) diff --git a/services/wifi_standard/wifi_framework/wifi_manage/wifi_ap/ap_root_state.h b/wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_ap/ap_root_state.h similarity index 92% rename from services/wifi_standard/wifi_framework/wifi_manage/wifi_ap/ap_root_state.h rename to wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_ap/ap_root_state.h index 55e71d292d96500499e0d475ee303b0ebfee4a0e..b87ae33a32866e907ffac82c3a3dd25b4509ea32 100644 --- a/services/wifi_standard/wifi_framework/wifi_manage/wifi_ap/ap_root_state.h +++ b/wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_ap/ap_root_state.h @@ -24,13 +24,13 @@ class ApRootState : public State { FRIEND_GTEST(ApRootState); public: /** - * @Description construction method + * @Description construction method. * @param None * @return None */ - ApRootState(); + explicit ApRootState(int id = 0); /** - * @Description destructor method + * @Description destructor method. * @param None * @return None */ @@ -56,6 +56,9 @@ public: * @return HANDLED:Processed successfully */ virtual bool ExecuteStateMsg(InternalMessage *msg) override; + +private: + int m_id; }; } // namespace Wifi } // namespace OHOS diff --git a/services/wifi_standard/wifi_framework/wifi_manage/wifi_ap/ap_service.cpp b/wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_ap/ap_service.cpp similarity index 48% rename from services/wifi_standard/wifi_framework/wifi_manage/wifi_ap/ap_service.cpp rename to wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_ap/ap_service.cpp index ba41b200cb621b1d388a5d1961944f43c172ab6a..ca3bee67c922c3f9f40f5487b8616f5bd1ade2df 100644 --- a/services/wifi_standard/wifi_framework/wifi_manage/wifi_ap/ap_service.cpp +++ b/wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_ap/ap_service.cpp @@ -1,5 +1,5 @@ /* - * Copyright (C) 2021 Huawei Device Co., Ltd. + * Copyright (C) 2021-2022 Huawei Device Co., Ltd. * 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 @@ -12,18 +12,19 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + #include "ap_service.h" #include #include "ap_state_machine.h" -#include "wifi_log.h" -#include "wifi_settings.h" - #include "wifi_logger.h" +#include "wifi_settings.h" +#include "wifi_ap_hal_interface.h" DEFINE_WIFILOG_HOTSPOT_LABEL("WifiApService"); namespace OHOS { namespace Wifi { -ApService::ApService(ApStateMachine &apStateMachine) : m_ApStateMachine(apStateMachine) +ApService::ApService(ApStateMachine &apStateMachine, int id) + : m_ApStateMachine(apStateMachine), m_id(id) {} ApService::~ApService() @@ -31,18 +32,21 @@ ApService::~ApService() ErrCode ApService::EnableHotspot() const { + WIFI_LOGI("Instance %{public}d %{public}s", m_id, __func__); m_ApStateMachine.SendMessage(static_cast(ApStatemachineEvent::CMD_START_HOTSPOT)); return ErrCode::WIFI_OPT_SUCCESS; } ErrCode ApService::DisableHotspot() const { + WIFI_LOGI("Instance %{public}d %{public}s", m_id, __func__); m_ApStateMachine.SendMessage(static_cast(ApStatemachineEvent::CMD_STOP_HOTSPOT)); return ErrCode::WIFI_OPT_SUCCESS; } ErrCode ApService::SetHotspotConfig(const HotspotConfig &cfg) const { + WIFI_LOGI("Instance %{public}d %{public}s", m_id, __func__); InternalMessage *msg = m_ApStateMachine.CreateMessage(); if (msg == nullptr) { return ErrCode::WIFI_OPT_FAILED; @@ -60,6 +64,7 @@ ErrCode ApService::SetHotspotConfig(const HotspotConfig &cfg) const ErrCode ApService::AddBlockList(const StationInfo &stationInfo) const { + WIFI_LOGI("Instance %{public}d %{public}s", m_id, __func__); InternalMessage *msg = m_ApStateMachine.CreateMessage(); if (msg == nullptr) { return ErrCode::WIFI_OPT_FAILED; @@ -74,6 +79,7 @@ ErrCode ApService::AddBlockList(const StationInfo &stationInfo) const ErrCode ApService::DelBlockList(const StationInfo &stationInfo) const { + WIFI_LOGI("Instance %{public}d %{public}s", m_id, __func__); InternalMessage *msg = m_ApStateMachine.CreateMessage(); if (msg == nullptr) { return ErrCode::WIFI_OPT_FAILED; @@ -88,6 +94,7 @@ ErrCode ApService::DelBlockList(const StationInfo &stationInfo) const ErrCode ApService::DisconnetStation(const StationInfo &stationInfo) const { + WIFI_LOGI("Instance %{public}d %{public}s", m_id, __func__); InternalMessage *msg = m_ApStateMachine.CreateMessage(); if (msg == nullptr) { return ErrCode::WIFI_OPT_FAILED; @@ -102,15 +109,16 @@ ErrCode ApService::DisconnetStation(const StationInfo &stationInfo) const ErrCode ApService::GetStationList(std::vector &result) const { + WIFI_LOGI("Instance %{public}d %{public}s", m_id, __func__); WifiSettings::GetInstance().GetStationList(result); if (result.empty()) { - WIFI_LOGD("GetStationList is empty."); + WIFI_LOGW("GetStationList is empty."); return ErrCode::WIFI_OPT_SUCCESS; } // get dhcp lease info, return full connected station info std::map tmp; if (!m_ApStateMachine.GetConnectedStationInfo(tmp)) { - WIFI_LOGD("Get connected station info failed!"); + WIFI_LOGW("Get connected station info failed!"); return ErrCode::WIFI_OPT_FAILED; } for (auto iter = result.begin(); iter != result.end(); ++iter) { @@ -126,35 +134,125 @@ ErrCode ApService::GetStationList(std::vector &result) const ErrCode ApService::GetValidBands(std::vector &bands) { - if (WifiSettings::GetInstance().GetValidBands(bands) < 0) { - WIFI_LOGE("Delete block list failed!"); + WIFI_LOGI("Instance %{public}d %{public}s", m_id, __func__); + std::vector allowed5GFreq; + std::vector allowed2GFreq; + if (WifiSettings::GetInstance().GetValidBands(bands) != 0) { + WIFI_LOGE("%{public}s, GetValidBands failed!", __func__); + return ErrCode::WIFI_OPT_FAILED; + } + if (bands.size() > 0) { + return ErrCode::WIFI_OPT_SUCCESS; + } + + /* Get freqs from hal */ + if (WifiApHalInterface::GetInstance().GetFrequenciesByBand(static_cast(BandType::BAND_2GHZ), allowed2GFreq)) { + WIFI_LOGW("%{public}s, fail to get 2.4G channel", __func__); + } + if (WifiApHalInterface::GetInstance().GetFrequenciesByBand(static_cast(BandType::BAND_5GHZ), allowed5GFreq)) { + WIFI_LOGW("%{public}s, fail to get 5G channel", __func__); + } + if (allowed2GFreq.size() > 0) { + bands.push_back(BandType::BAND_2GHZ); + } + if (allowed5GFreq.size() > 0) { + bands.push_back(BandType::BAND_5GHZ); + } + if (bands.size() <= 0) { + WIFI_LOGW("%{public}s, GetValidBands failed!", __func__); return ErrCode::WIFI_OPT_FAILED; } return ErrCode::WIFI_OPT_SUCCESS; } -ErrCode ApService::GetValidChannels(BandType band, std::vector &validchannel) +ErrCode ApService::GetValidChannels(BandType band, std::vector &validChannel) { + WIFI_LOGI("Instance %{public}d %{public}s", m_id, __func__); ChannelsTable channelsInfo; - if (WifiSettings::GetInstance().GetValidChannels(channelsInfo)) { - WIFI_LOGE("Failed to obtain data from the WifiSettings."); + if (WifiSettings::GetInstance().GetValidChannels(channelsInfo) != 0) { + WIFI_LOGE("Failed to obtain channels from the WifiSettings."); return ErrCode::WIFI_OPT_FAILED; } - auto it = channelsInfo.find(band); - if (it == channelsInfo.end()) { - WIFI_LOGE("The value of band is invalid."); + + if (channelsInfo.size() > 0) { + auto it = channelsInfo.find(band); + if (it != channelsInfo.end()) { + validChannel = channelsInfo[band]; + WIFI_LOGI("%{public}s, get valid channel size:%{public}d, band:%{public}d from WifiSettings.", + __func__, (int)validChannel.size(), band); + return ErrCode::WIFI_OPT_SUCCESS; + } + } + + /* get freqs from hal service */ + std::vector allowed5GFreq, allowed2GFreq; + std::vector allowed5GChan, allowed2GChan; + if (WifiApHalInterface::GetInstance().GetFrequenciesByBand(static_cast(BandType::BAND_2GHZ), allowed2GFreq)) { + WIFI_LOGW("%{public}s, fail to get 2.4G channel", __func__); + } + if (WifiApHalInterface::GetInstance().GetFrequenciesByBand(static_cast(BandType::BAND_5GHZ), allowed5GFreq)) { + WIFI_LOGW("%{public}s, fail to get 5G channel", __func__); + } + if (allowed2GFreq.size() == 0) { + WifiSettings::GetInstance().SetDefaultFrequenciesByCountryBand(BandType::BAND_2GHZ, allowed2GFreq); + } + TransformFrequencyIntoChannel(allowed2GFreq, allowed2GChan); + TransformFrequencyIntoChannel(allowed5GFreq, allowed5GChan); + + ChannelsTable ChanTbs; + ChanTbs[BandType::BAND_2GHZ] = allowed2GChan; + ChanTbs[BandType::BAND_5GHZ] = allowed5GChan; + if (WifiSettings::GetInstance().SetValidChannels(ChanTbs)) { + WIFI_LOGE("%{public}s, fail to SetValidChannels", __func__); + } + if (band == BandType::BAND_2GHZ || band == BandType::BAND_5GHZ) { + validChannel = ChanTbs[band]; + } else { + WIFI_LOGE("%{public}s, invalid band: %{public}d", __func__, band); return ErrCode::WIFI_OPT_INVALID_PARAM; } - validchannel = channelsInfo[band]; + WIFI_LOGI("%{public}s, get valid channel size:%{public}d, band:%{public}d from hal service.", + __func__, (int)validChannel.size(), band); return ErrCode::WIFI_OPT_SUCCESS; } ErrCode ApService::RegisterApServiceCallbacks(const IApServiceCallbacks &callbacks) { + WIFI_LOGI("Instance %{public}d %{public}s", m_id, __func__); WIFI_LOGI("RegisterApServiceCallbacks."); m_ApStateMachine.RegisterApServiceCallbacks(callbacks); return ErrCode::WIFI_OPT_SUCCESS; } +ErrCode ApService::GetSupportedPowerModel(std::set& setPowerModelList) +{ + WIFI_LOGI("Instance %{public}d %{public}s", m_id, __func__); + /* All modes are currently supported */ + setPowerModelList.insert(PowerModel::SLEEPING); + setPowerModelList.insert(PowerModel::GENERAL); + setPowerModelList.insert(PowerModel::THROUGH_WALL); + return ErrCode::WIFI_OPT_SUCCESS; +} + +ErrCode ApService::GetPowerModel(PowerModel& model) +{ + WIFI_LOGI("Instance %{public}d %{public}s", m_id, __func__); + WifiSettings::GetInstance().GetPowerModel(model, m_id); + LOGI("ApService::GetPowerModel, model=[%{public}d]", static_cast(model)); + return ErrCode::WIFI_OPT_SUCCESS; +} + +ErrCode ApService::SetPowerModel(const PowerModel& model) +{ + WIFI_LOGI("Instance %{public}d %{public}s", m_id, __func__); + LOGI("Enter ApService::SetPowerModel, model=[%d]", static_cast(model)); + if (WifiApHalInterface::GetInstance().SetPowerModel(static_cast(model), m_id) != WIFI_IDL_OPT_OK) { + LOGE("SetPowerModel() failed!"); + return WIFI_OPT_FAILED; + } + LOGI("SetPowerModel() succeed!"); + WifiSettings::GetInstance().SetPowerModel(model); + return ErrCode::WIFI_OPT_SUCCESS; +} } // namespace Wifi } // namespace OHOS \ No newline at end of file diff --git a/services/wifi_standard/wifi_framework/wifi_manage/wifi_ap/ap_service.h b/wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_ap/ap_service.h similarity index 78% rename from services/wifi_standard/wifi_framework/wifi_manage/wifi_ap/ap_service.h rename to wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_ap/ap_service.h index 00cd91100838ea751d051e4016748f89dc92c6a1..d04045ee11683ff164afa7b2843b5d8efbfda7cc 100644 --- a/services/wifi_standard/wifi_framework/wifi_manage/wifi_ap/ap_service.h +++ b/wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_ap/ap_service.h @@ -32,7 +32,7 @@ public: * @param None * @return None */ - ApService(ApStateMachine &); + explicit ApService(ApStateMachine &apStateMachine, int id = 0); /** * @Description destructor method. @@ -43,21 +43,21 @@ public: DISALLOW_COPY_AND_ASSIGN(ApService) /** - * @Description open hotspot + * @Description open hotspot. * @param None * @return ErrCode - success: WIFI_OPT_SUCCESS failed: ERROR_CODE */ ErrCode EnableHotspot() const; /** - * @Description close hotspot + * @Description close hotspot. * @param None * @return ErrCode - success: WIFI_OPT_SUCCESS failed: ERROR_CODE */ ErrCode DisableHotspot() const; /** - * @Description set ap config + * @Description set ap config. * @param cfg - ap config * @return ErrCode - success: WIFI_OPT_SUCCESS failed: ERROR_CODE */ @@ -71,14 +71,14 @@ public: ErrCode AddBlockList(const StationInfo &stationInfo) const; /** - * @Description delete block list + * @Description delete block list. * @param stationInfo - sta infos * @return ErrCode - success: WIFI_OPT_SUCCESS failed: ERROR_CODE */ ErrCode DelBlockList(const StationInfo &stationInfo) const; /** - * @Description Disconnect a specified STA + * @Description Disconnect a specified STA. * @param stationInfo - sta infos * @return ErrCode - success: WIFI_OPT_SUCCESS failed: ERROR_CODE */ @@ -107,7 +107,7 @@ public: * @param validchannel - band's valid channel * @return ErrCode - success: WIFI_OPT_SUCCESS failed: ERROR_CODE */ - ErrCode GetValidChannels(BandType band, std::vector &validchannel); + ErrCode GetValidChannels(BandType band, std::vector &validChannel); /** * @Description Sets the callback function for the state machine. @@ -117,8 +117,33 @@ public: */ ErrCode RegisterApServiceCallbacks(const IApServiceCallbacks &callbacks); + /** + * @Description Get supported power model list + * + * @param setPowerModelList - supported power model list + * @return ErrCode - operation result + */ + ErrCode GetSupportedPowerModel(std::set& setPowerModelList); + + /** + * @Description Get power model + * + * @param model - current power model + * @return ErrCode - operation result + */ + ErrCode GetPowerModel(PowerModel& model); + + /** + * @Description Get supported power model list + * + * @param model - the model to be set + * @return ErrCode - operation result + */ + ErrCode SetPowerModel(const PowerModel& model); + private: ApStateMachine &m_ApStateMachine; + int m_id; }; } // namespace Wifi } // namespace OHOS diff --git a/services/wifi_standard/wifi_framework/wifi_manage/wifi_ap/ap_started_state.cpp b/wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_ap/ap_started_state.cpp similarity index 75% rename from services/wifi_standard/wifi_framework/wifi_manage/wifi_ap/ap_started_state.cpp rename to wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_ap/ap_started_state.cpp index 42876b6aeff4bc9e58d841ca68140bd05fb213cf..c083f74b6c1fb5ce21bd809a163741b3e74dcab2 100644 --- a/services/wifi_standard/wifi_framework/wifi_manage/wifi_ap/ap_started_state.cpp +++ b/wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_ap/ap_started_state.cpp @@ -1,5 +1,5 @@ /* - * Copyright (C) 2021 Huawei Device Co., Ltd. + * Copyright (C) 2021-2022 Huawei Device Co., Ltd. * 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 @@ -12,6 +12,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + #include "ap_started_state.h" #include #include @@ -23,22 +24,25 @@ #include "ap_monitor.h" #include "ap_service.h" #include "ap_state_machine.h" +#include "ap_stations_manager.h" #include "dhcpd_interface.h" #include "wifi_ap_hal_interface.h" #include "wifi_ap_nat_manager.h" -#include "ap_stations_manager.h" +#include "wifi_chip_capability.h" #include "wifi_settings.h" #include "wifi_logger.h" +#include "wifi_common_util.h" DEFINE_WIFILOG_HOTSPOT_LABEL("WifiApStartedState"); namespace OHOS { namespace Wifi { -ApStartedState::ApStartedState(ApStateMachine &apStateMachine, ApConfigUse &apConfigUse, ApMonitor &apMonitor) +ApStartedState::ApStartedState(ApStateMachine &apStateMachine, ApConfigUse &apConfigUse, ApMonitor &apMonitor, int id) : State("ApStartedState"), m_hotspotConfig(HotspotConfig()), m_ApStateMachine(apStateMachine), m_ApConfigUse(apConfigUse), - m_ApMonitor(apMonitor) + m_ApMonitor(apMonitor), + m_id(id) { Init(); } @@ -48,8 +52,9 @@ ApStartedState::~ApStartedState() void ApStartedState::GoInState() { + WIFI_LOGI("Instance %{public}d %{public}s", m_id, __func__); m_ApStateMachine.OnApStateChange(ApState::AP_STATE_STARTING); - WIFI_LOGI("%{public}s GoInState", GetStateName().c_str()); + WIFI_LOGI("Instance %{public}d %{public}s GoInState", m_id, GetStateName().c_str()); m_ApStateMachine.RegisterEventHandler(); StartMonitor(); @@ -70,19 +75,20 @@ void ApStartedState::GoInState() WIFI_LOGE("Set Blocklist failed."); } - WIFI_LOGE("Singleton version has not nat and use wlan0."); - if (0) { - if (EnableInterfaceNat() == false) { - m_ApStateMachine.SwitchState(&m_ApStateMachine.m_ApIdleState); - return; - } + WIFI_LOGE("Singleton version has not nat and use %{public}s.", AP_INTF); + + if (EnableInterfaceNat() == false) { + m_ApStateMachine.SwitchState(&m_ApStateMachine.m_ApIdleState); + return; } + UpdatePowerMode(); m_ApStateMachine.OnApStateChange(ApState::AP_STATE_STARTED); + ChipCapability::GetInstance().InitializeChipCapability(); } void ApStartedState::GoOutState() { - WIFI_LOGI("%{public}s GoOutState.", GetStateName().c_str()); + WIFI_LOGI("Instance %{public}d %{public}s", m_id, __func__); m_ApStateMachine.OnApStateChange(ApState::AP_STATE_CLOSING); DisableInterfaceNat(); m_ApStateMachine.StopDhcpServer(); @@ -122,7 +128,7 @@ bool ApStartedState::ExecuteStateMsg(InternalMessage *msg) return false; } int msgName = msg->GetMessageName(); - WIFI_LOGI("ApStartedState Process msgName:%{public}d.", msgName); + WIFI_LOGI("Instance %{public}d ApStartedState Process msgName:%{public}d.", m_id, msgName); auto iter = mProcessFunMap.find(static_cast(msgName)); if (iter == mProcessFunMap.end()) { @@ -135,13 +141,16 @@ bool ApStartedState::ExecuteStateMsg(InternalMessage *msg) bool ApStartedState::SetConfig(HotspotConfig &apConfig) { + WIFI_LOGI("Instance %{public}d %{public}s", m_id, __func__); std::vector allowed5GFreq, allowed2GFreq; std::vector allowed5GChan, allowed2GChan; if (WifiApHalInterface::GetInstance().GetFrequenciesByBand(static_cast(BandType::BAND_2GHZ), allowed2GFreq)) { WIFI_LOGW("failed to get 2.4G channel."); + WifiSettings::GetInstance().SetDefaultFrequenciesByCountryBand(BandType::BAND_2GHZ, allowed2GFreq); } if (WifiApHalInterface::GetInstance().GetFrequenciesByBand(static_cast(BandType::BAND_5GHZ), allowed5GFreq)) { WIFI_LOGW("failed to get 5G channel."); + WifiSettings::GetInstance().SetDefaultFrequenciesByCountryBand(BandType::BAND_5GHZ, allowed5GFreq); } m_ApConfigUse.TransformFrequencyIntoChannel(allowed5GFreq, allowed5GChan); @@ -158,11 +167,13 @@ bool ApStartedState::SetConfig(HotspotConfig &apConfig) m_ApConfigUse.CheckBandChannel(apConfig, channelTbs); - if (WifiApHalInterface::GetInstance().SetSoftApConfig(apConfig) != WifiErrorNo::WIFI_IDL_OPT_OK) { + if (WifiApHalInterface::GetInstance().SetSoftApConfig(apConfig, m_id) != WifiErrorNo::WIFI_IDL_OPT_OK) { WIFI_LOGE("set hostapd config failed."); return false; } + WifiSettings::GetInstance().SetHotspotConfig(apConfig, m_id); + WifiSettings::GetInstance().SyncHotspotConfig(); m_ApConfigUse.LogConfig(apConfig); WIFI_LOGI("SetConfig OK!."); return true; @@ -170,18 +181,19 @@ bool ApStartedState::SetConfig(HotspotConfig &apConfig) bool ApStartedState::SetConfig() { + WIFI_LOGI("Instance %{public}d %{public}s", m_id, __func__); std::string countryCode; if (WifiSettings::GetInstance().GetCountryCode(countryCode)) { WIFI_LOGE("get countryCode failed."); return false; } - if (WifiApHalInterface::GetInstance().SetWifiCountryCode(countryCode) != WifiErrorNo::WIFI_IDL_OPT_OK) { + if (WifiApHalInterface::GetInstance().SetWifiCountryCode(countryCode, m_id) != WifiErrorNo::WIFI_IDL_OPT_OK) { WIFI_LOGE("set countryCode:%{public}s failed.", countryCode.c_str()); return false; } WIFI_LOGI("HotspotConfig CountryCode = %{public}s.", countryCode.c_str()); - if (WifiSettings::GetInstance().GetHotspotConfig(m_hotspotConfig)) { + if (WifiSettings::GetInstance().GetHotspotConfig(m_hotspotConfig, m_id)) { WIFI_LOGE("GetConfig failed!!!."); return false; } @@ -191,8 +203,8 @@ bool ApStartedState::SetConfig() bool ApStartedState::StartAp() const { - WIFI_LOGI("enter startAp."); - WifiErrorNo retCode = WifiApHalInterface::GetInstance().StartAp(); + WIFI_LOGI("Instance %{public}d %{public}s", m_id, __func__); + WifiErrorNo retCode = WifiApHalInterface::GetInstance().StartAp(m_id); if (retCode != WifiErrorNo::WIFI_IDL_OPT_OK) { WIFI_LOGE("startAp is failed!"); return false; @@ -202,7 +214,8 @@ bool ApStartedState::StartAp() const bool ApStartedState::StopAp() const { - WifiErrorNo retCode = WifiApHalInterface::GetInstance().StopAp(); + WIFI_LOGI("Instance %{public}d %{public}s", m_id, __func__); + WifiErrorNo retCode = WifiApHalInterface::GetInstance().StopAp(m_id); if (retCode != WifiErrorNo::WIFI_IDL_OPT_OK) { return false; } @@ -211,40 +224,46 @@ bool ApStartedState::StopAp() const void ApStartedState::StartMonitor() const { + WIFI_LOGI("Instance %{public}d %{public}s", m_id, __func__); m_ApMonitor.StartMonitor(); } void ApStartedState::StopMonitor() const { + WIFI_LOGI("Instance %{public}d %{public}s", m_id, __func__); m_ApMonitor.StopMonitor(); } bool ApStartedState::EnableInterfaceNat() const { +#ifdef SUPPORT_NAT if (!mApNatManager.EnableInterfaceNat(true, IN_INTERFACE, OUT_INTERFACE)) { WIFI_LOGE("set nat failed."); return false; } +#endif return true; } bool ApStartedState::DisableInterfaceNat() const { +#ifdef SUPPORT_NAT if (!mApNatManager.EnableInterfaceNat(false, IN_INTERFACE, OUT_INTERFACE)) { WIFI_LOGE("remove NAT config failed."); } +#endif return true; } void ApStartedState::ProcessCmdFail(InternalMessage &msg) const { - WIFI_LOGI("State Machine message: %{public}d.", msg.GetMessageName()); + WIFI_LOGI("Instance %{public}d State Machine message: %{public}d.", m_id, msg.GetMessageName()); m_ApStateMachine.SwitchState(&m_ApStateMachine.m_ApIdleState); } void ApStartedState::ProcessCmdStationJoin(InternalMessage &msg) const { - WIFI_LOGI("New station join."); + WIFI_LOGI("Instance %{public}d %{public}s", m_id, __func__); StationInfo staInfo; if (msg.GetMessageObj(staInfo)) { m_ApStateMachine.m_ApStationsManager.StationJoin(staInfo); @@ -255,7 +274,7 @@ void ApStartedState::ProcessCmdStationJoin(InternalMessage &msg) const void ApStartedState::ProcessCmdStationLeave(InternalMessage &msg) const { - WIFI_LOGI("Old station leave."); + WIFI_LOGI("Instance %{public}d %{public}s", m_id, __func__); StationInfo staInfo; if (msg.GetMessageObj(staInfo)) { m_ApStateMachine.m_ApStationsManager.StationLeave(staInfo.bssid); @@ -266,8 +285,7 @@ void ApStartedState::ProcessCmdStationLeave(InternalMessage &msg) const void ApStartedState::ProcessCmdSetHotspotConfig(InternalMessage &msg) { - WIFI_LOGI("Set HotspotConfig."); - + WIFI_LOGI("Instance %{public}d %{public}s", m_id, __func__); m_hotspotConfig.SetSsid(msg.GetStringFromMessage()); m_hotspotConfig.SetPreSharedKey(msg.GetStringFromMessage()); m_hotspotConfig.SetSecurityType(static_cast(msg.GetIntFromMessage())); @@ -284,13 +302,16 @@ void ApStartedState::ProcessCmdSetHotspotConfig(InternalMessage &msg) void ApStartedState::ProcessCmdUpdateConfigResult(InternalMessage &msg) const { + WIFI_LOGI("Instance %{public}d %{public}s", m_id, __func__); if (msg.GetParam1() == 1) { WIFI_LOGI("Hot update HotspotConfig succeeded."); - if (WifiSettings::GetInstance().SetHotspotConfig(m_hotspotConfig)) { + if (WifiSettings::GetInstance().SetHotspotConfig(m_hotspotConfig, m_id)) { WIFI_LOGE("set apConfig to settings failed."); } +#ifndef WIFI_DHCP_DISABLED m_ApStateMachine.StopDhcpServer(); m_ApStateMachine.StartDhcpServer(); +#endif } else { m_ApStateMachine.SwitchState(&m_ApStateMachine.m_ApIdleState); } @@ -298,40 +319,54 @@ void ApStartedState::ProcessCmdUpdateConfigResult(InternalMessage &msg) const void ApStartedState::ProcessCmdAddBlockList(InternalMessage &msg) const { - WIFI_LOGI("Add block list."); + WIFI_LOGI("Instance %{public}d %{public}s", m_id, __func__); StationInfo staInfo; staInfo.deviceName = msg.GetStringFromMessage(); staInfo.bssid = msg.GetStringFromMessage(); staInfo.ipAddr = msg.GetStringFromMessage(); - WIFI_LOGI("staInfo:%s, %s, %s.", staInfo.deviceName.c_str(), staInfo.bssid.c_str(), staInfo.ipAddr.c_str()); + WIFI_LOGI("staInfo:%{private}s, %{public}s, %{public}s.", + staInfo.deviceName.c_str(), MacAnonymize(staInfo.bssid).c_str(), IpAnonymize(staInfo.ipAddr).c_str()); m_ApStateMachine.m_ApStationsManager.AddBlockList(staInfo); } void ApStartedState::ProcessCmdDelBlockList(InternalMessage &msg) const { - WIFI_LOGI("Delete block list."); + WIFI_LOGI("Instance %{public}d %{public}s", m_id, __func__); StationInfo staInfo; staInfo.deviceName = msg.GetStringFromMessage(); staInfo.bssid = msg.GetStringFromMessage(); staInfo.ipAddr = msg.GetStringFromMessage(); - WIFI_LOGI("staInfo:%s, %s, %s.", staInfo.deviceName.c_str(), staInfo.bssid.c_str(), staInfo.ipAddr.c_str()); + WIFI_LOGI("staInfo:%{private}s, %{public}s, %{public}s.", staInfo.deviceName.c_str(), + MacAnonymize(staInfo.bssid).c_str(), IpAnonymize(staInfo.ipAddr).c_str()); m_ApStateMachine.m_ApStationsManager.DelBlockList(staInfo); } void ApStartedState::ProcessCmdStopHotspot(InternalMessage &msg) const { - WIFI_LOGI("Disable hotspot: %{public}d.", msg.GetMessageName()); + WIFI_LOGI("Instance %{public}d Disable hotspot: %{public}d.", m_id, msg.GetMessageName()); m_ApStateMachine.SwitchState(&m_ApStateMachine.m_ApIdleState); } void ApStartedState::ProcessCmdDisconnectStation(InternalMessage &msg) const { - WIFI_LOGI("Disconnect station."); + WIFI_LOGI("Instance %{public}d %{public}s", m_id, __func__); StationInfo staInfo; staInfo.deviceName = msg.GetStringFromMessage(); staInfo.bssid = msg.GetStringFromMessage(); staInfo.ipAddr = msg.GetStringFromMessage(); m_ApStateMachine.m_ApStationsManager.DisConnectStation(staInfo); } + +void ApStartedState::UpdatePowerMode() const +{ + WIFI_LOGI("UpdatePowerMode."); + int model = -1; + if (WifiApHalInterface::GetInstance().GetPowerModel(model) != WIFI_IDL_OPT_OK) { + LOGE("GetPowerModel() failed!"); + return; + } + LOGI("SetPowerModel(): %{public}d.", model); + WifiSettings::GetInstance().SetPowerModel(PowerModel(model)); +} } // namespace Wifi -} // namespace OHOS \ No newline at end of file +} // namespace OHOS diff --git a/services/wifi_standard/wifi_framework/wifi_manage/wifi_ap/ap_started_state.h b/wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_ap/ap_started_state.h similarity index 85% rename from services/wifi_standard/wifi_framework/wifi_manage/wifi_ap/ap_started_state.h rename to wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_ap/ap_started_state.h index 36506f6091bb0e22d42e60a56316801a68e6b372..7037bafcadcb236572db0df3e2c3c9bc4fb42a07 100644 --- a/services/wifi_standard/wifi_framework/wifi_manage/wifi_ap/ap_started_state.h +++ b/wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_ap/ap_started_state.h @@ -1,5 +1,5 @@ /* - * Copyright (C) 2021 Huawei Device Co., Ltd. + * Copyright (C) 2021-2022 Huawei Device Co., Ltd. * 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 @@ -15,9 +15,11 @@ #ifndef OHOS_AP_STARTEND_STATE_H #define OHOS_AP_STARTEND_STATE_H +#include #include "ap_define.h" #include "state.h" #include "wifi_ap_nat_manager.h" +#include "wifi_ap_msg.h" namespace OHOS { namespace Wifi { @@ -28,13 +30,13 @@ class ApStartedState : public State { FRIEND_GTEST(ApStartedState); public: /** - * @Description construction method + * @Description construction method. * @param None * @return None */ - ApStartedState(ApStateMachine &, ApConfigUse &, ApMonitor &); + ApStartedState(ApStateMachine &apStateMachine, ApConfigUse &apConfigUse, ApMonitor &apMonitor, int id = 0); /** - * @Description destructor method + * @Description destructor method. * @param None * @return None */ @@ -63,7 +65,7 @@ public: /** * @Description Implement pure base class methods:The CMD processed when the AP is in the running state (such as updating - the blocklist to hostapd) + the blocklist to hostapd.) * @param msg - processed message * @return HANDLED:Processed successfully NOT_EXECUTED: Processed failed */ @@ -72,7 +74,7 @@ public: private: /** * @Description Called inside the state,The processing function of - the HAL layer when the AP is turned on + the HAL layer when the AP is turned on. * @param None * @return true: Successfully opened false: Failed to open */ @@ -80,7 +82,7 @@ private: /** * @Description Called inside the state,The processing function of - the HAL layer when the AP is turned off + the HAL layer when the AP is turned off. * @param None * @return true: Closed successfully false: Close failed */ @@ -103,21 +105,21 @@ private: bool SetConfig(); /** - * @Description Status update notification APSERVICE + * @Description Status update notification APSERVICE. * @param state - New state * @return None */ void OnApStateChange(const ApState &state) const; /** - * @Description Start ap monitor + * @Description Start ap monitor. * @param None * @return None */ void StartMonitor() const; /** - * @Description Stop ap monitor + * @Description Stop ap monitor. * @param None * @return None */ @@ -131,7 +133,7 @@ private: bool EnableInterfaceNat() const; /** - * @Description stop NAT + * @Description stop NAT. * @param None * @return true: success false: failed */ @@ -139,21 +141,21 @@ private: private: /** - * @Description Handle hostapd failure events received by the state machine + * @Description Handle hostapd failure events received by the state machine. * @param msg - Message body sent by the state machine * @return None */ void ProcessCmdFail(InternalMessage &msg) const; /** - * @Description Process the STA connection message received by the state machine + * @Description Process the STA connection message received by the state machine. * @param msg - Message body sent by the state machine * @return None */ void ProcessCmdStationJoin(InternalMessage &msg) const; /** - * @Description Process the STA disconnect message received by the state machine + * @Description Process the STA disconnect message received by the state machine. * @param msg - Message body sent by the state machine * @return None */ @@ -161,7 +163,7 @@ private: /** * @Description Process the hotspot configuration message of the APP - received by the state machine + received by the state machine. * @param msg - Message body sent by the state machine * @return None */ @@ -169,7 +171,7 @@ private: /** * @Description Process the hotspot configuration update result - received by the state machine + received by the state machine. * @param msg - Message body sent by the state machine * @return None */ @@ -177,7 +179,7 @@ private: /** * @Description Process the add blocklist message received by the - state machine + state machine. * @param msg - Message body sent by the state machine * @return None */ @@ -185,7 +187,7 @@ private: /** * @Description Process the delete blocklist message received by the - state machine + state machine. * @param msg - Message body sent by the state machine * @return None */ @@ -193,7 +195,7 @@ private: /** * @Description Process the close hotspot message received by the - state machine + state machine. * @param msg - Message body sent by the state machine * @return None */ @@ -201,14 +203,20 @@ private: /** * @Description Process the disconnected STA message received by the - state machine + state machine. * @param msg - Message body sent by the state machine * @return None */ void ProcessCmdDisconnectStation(InternalMessage &msg) const; /** - * @Description Initialization + * @Description update the power mode. + * @return None + */ + void UpdatePowerMode() const; + + /** + * @Description Initialization. * @param None * @return None */ @@ -229,6 +237,7 @@ private: ApStateMachine &m_ApStateMachine; ApConfigUse &m_ApConfigUse; ApMonitor &m_ApMonitor; + int m_id; }; } // namespace Wifi } // namespace OHOS diff --git a/services/wifi_standard/wifi_framework/wifi_manage/wifi_ap/ap_state_machine.cpp b/wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_ap/ap_state_machine.cpp similarity index 88% rename from services/wifi_standard/wifi_framework/wifi_manage/wifi_ap/ap_state_machine.cpp rename to wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_ap/ap_state_machine.cpp index d87e0da7e45a5e120c5a2b5ba6be24828943642f..72f54d512b3bc234b0ef1ae61c1e466a74483a31 100644 --- a/services/wifi_standard/wifi_framework/wifi_manage/wifi_ap/ap_state_machine.cpp +++ b/wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_ap/ap_state_machine.cpp @@ -22,27 +22,31 @@ #include "wifi_logger.h" DEFINE_WIFILOG_HOTSPOT_LABEL("WifiApStateMachine"); + namespace OHOS { namespace Wifi { ApStateMachine::ApStateMachine(ApStationsManager &apStationsManager, ApRootState &apRootState, ApIdleState &apIdleState, - ApStartedState &apStartedState, ApMonitor &apMonitor) + ApStartedState &apStartedState, ApMonitor &apMonitor, int id) : StateMachine("ApStateMachine"), m_ApStationsManager(apStationsManager), m_ApRootState(apRootState), m_ApIdleState(apIdleState), m_ApStartedState(apStartedState), - m_ApMonitor(apMonitor) + m_ApMonitor(apMonitor), + m_id(id) { Init(); } ApStateMachine::~ApStateMachine() { +#ifndef WIFI_DHCP_DISABLED StopDhcpServer(); if (pDhcpNotify.get() != nullptr) { pDhcpNotify.reset(nullptr); } StopHandlerThread(); +#endif } ApStateMachine::DhcpNotify::DhcpNotify(ApStateMachine &apStateMachine) : m_apStateMachine(apStateMachine) @@ -80,20 +84,20 @@ void ApStateMachine::Init() StatePlus(&m_ApIdleState, &m_ApRootState); StatePlus(&m_ApStartedState, &m_ApRootState); SetFirstState(&m_ApIdleState); - m_iface = "wlan0"; + m_iface = std::string(AP_INTF) + std::to_string(m_id); StartStateMachine(); } void ApStateMachine::OnApStateChange(ApState state) { - if (WifiSettings::GetInstance().SetHotspotState(static_cast(state))) { + if (WifiSettings::GetInstance().SetHotspotState(static_cast(state), m_id)) { WIFI_LOGE("WifiSetting change state fail."); } if (m_Callbacks.OnApStateChangedEvent != nullptr && (state == ApState::AP_STATE_IDLE || state == ApState::AP_STATE_STARTED || state == ApState::AP_STATE_STARTING || state == ApState::AP_STATE_CLOSING)) { - m_Callbacks.OnApStateChangedEvent(state); + m_Callbacks.OnApStateChangedEvent(state, m_id); } return; } @@ -109,12 +113,12 @@ void ApStateMachine::BroadCastStationChange(const StationInfo &staInfo, ApStatem switch (act) { case ApStatemachineEvent::CMD_STATION_JOIN: if (m_Callbacks.OnHotspotStaJoinEvent) { - m_Callbacks.OnHotspotStaJoinEvent(staInfo); + m_Callbacks.OnHotspotStaJoinEvent(staInfo, m_id); } break; case ApStatemachineEvent::CMD_STATION_LEAVE: if (m_Callbacks.OnHotspotStaLeaveEvent) { - m_Callbacks.OnHotspotStaLeaveEvent(staInfo); + m_Callbacks.OnHotspotStaLeaveEvent(staInfo, m_id); } break; default: @@ -126,6 +130,7 @@ void ApStateMachine::BroadCastStationChange(const StationInfo &staInfo, ApStatem bool ApStateMachine::StartDhcpServer() { WIFI_LOGI("Enter:StartDhcpServer"); +#ifndef WIFI_DHCP_DISABLED Ipv4Address ipv4(Ipv4Address::INVALID_INET_ADDRESS); Ipv6Address ipv6(Ipv6Address::INVALID_INET6_ADDRESS); if (!m_DhcpdInterface.StartDhcpServer(IN_INTERFACE, ipv4, ipv6, true)) { @@ -135,22 +140,34 @@ bool ApStateMachine::StartDhcpServer() if (!m_DhcpdInterface.SetDhcpEventFunc(IN_INTERFACE, pDhcpNotify.get())) { WIFI_LOGW("Set dhcp notify failed."); } + WIFI_LOGI("Start dhcp server for AP finished."); + return true; +#else return true; +#endif } bool ApStateMachine::StopDhcpServer() { +#ifndef WIFI_DHCP_DISABLED WIFI_LOGI("Enter:StopDhcpServer"); if (!m_DhcpdInterface.StopDhcpServer(IN_INTERFACE)) { WIFI_LOGE("Close dhcpd fail."); return false; } return true; +#else + return true; +#endif } bool ApStateMachine::GetConnectedStationInfo(std::map &result) { +#ifndef WIFI_DHCP_DISABLED return m_DhcpdInterface.GetConnectedStationInfo(IN_INTERFACE, result); +#else + return true; +#endif } void ApStateMachine::RegisterEventHandler() @@ -168,4 +185,4 @@ void ApStateMachine::RegisterEventHandler() m_ApStationsManager.RegisterEventHandler(std::bind(&ApStateMachine::BroadCastStationChange, this, _1, _2)); } } // namespace Wifi -} // namespace OHOS \ No newline at end of file +} // namespace OHOS diff --git a/services/wifi_standard/wifi_framework/wifi_manage/wifi_ap/ap_state_machine.h b/wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_ap/ap_state_machine.h similarity index 96% rename from services/wifi_standard/wifi_framework/wifi_manage/wifi_ap/ap_state_machine.h rename to wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_ap/ap_state_machine.h index 12ae60b8b5951d49a8cf5823f4b68d8ae1a052c2..27b97bdee773bf7735b1ccfaf03377ec90e06cce 100644 --- a/services/wifi_standard/wifi_framework/wifi_manage/wifi_ap/ap_state_machine.h +++ b/wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_ap/ap_state_machine.h @@ -80,7 +80,8 @@ public: * @param None * @return None */ - ApStateMachine(ApStationsManager &, ApRootState &, ApIdleState &, ApStartedState &, ApMonitor &); + ApStateMachine(ApStationsManager &apStationsManager, ApRootState &apRootState, ApIdleState &apIdleState, + ApStartedState &apStartedState, ApMonitor &apMonitor, int id = 0); /** * @Description destructor method. @@ -167,7 +168,7 @@ private: DhcpdInterface m_DhcpdInterface; std::unique_ptr pDhcpNotify; - + int m_id; }; /* ApStateMachine */ } // namespace Wifi } // namespace OHOS diff --git a/services/wifi_standard/wifi_framework/wifi_manage/wifi_ap/ap_stations_manager.cpp b/wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_ap/ap_stations_manager.cpp similarity index 70% rename from services/wifi_standard/wifi_framework/wifi_manage/wifi_ap/ap_stations_manager.cpp rename to wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_ap/ap_stations_manager.cpp index 9a99fa226714adb560132f07895cd8176e3a99e7..29b2cc42b4b7b51ddd47a27fc8317777a552c473 100644 --- a/services/wifi_standard/wifi_framework/wifi_manage/wifi_ap/ap_stations_manager.cpp +++ b/wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_ap/ap_stations_manager.cpp @@ -20,12 +20,13 @@ #include "wifi_ap_hal_interface.h" #include "ap_state_machine.h" #include "wifi_logger.h" +#include "wifi_common_util.h" DEFINE_WIFILOG_HOTSPOT_LABEL("WifiApStationsManager"); namespace OHOS { namespace Wifi { -ApStationsManager::ApStationsManager() +ApStationsManager::ApStationsManager(int id) : m_id(id) {} ApStationsManager::~ApStationsManager() @@ -33,7 +34,8 @@ ApStationsManager::~ApStationsManager() bool ApStationsManager::AddBlockList(const StationInfo &staInfo) const { - if (WifiApHalInterface::GetInstance().AddBlockByMac(staInfo.bssid) != WifiErrorNo::WIFI_IDL_OPT_OK) { + if (WifiApHalInterface::GetInstance().AddBlockByMac(staInfo.bssid, m_id) != WifiErrorNo::WIFI_IDL_OPT_OK) { + WIFI_LOGE("Instance is %{public}d failed to add block.", m_id); return false; } return true; @@ -41,7 +43,8 @@ bool ApStationsManager::AddBlockList(const StationInfo &staInfo) const bool ApStationsManager::DelBlockList(const StationInfo &staInfo) const { - if (WifiApHalInterface::GetInstance().DelBlockByMac(staInfo.bssid) != WifiErrorNo::WIFI_IDL_OPT_OK) { + if (WifiApHalInterface::GetInstance().DelBlockByMac(staInfo.bssid, m_id) != WifiErrorNo::WIFI_IDL_OPT_OK) { + WIFI_LOGE("Instance is %{public}d failed to del block.", m_id); return false; } return true; @@ -49,7 +52,8 @@ bool ApStationsManager::DelBlockList(const StationInfo &staInfo) const bool ApStationsManager::AddAssociationStation(const StationInfo &staInfo) const { - if (WifiSettings::GetInstance().ManageStation(staInfo, MODE_ADD)) { + if (WifiSettings::GetInstance().ManageStation(staInfo, MODE_ADD, m_id)) { + WIFI_LOGE("Instance is %{public}d failed add station.", m_id); return false; } return true; @@ -57,7 +61,8 @@ bool ApStationsManager::AddAssociationStation(const StationInfo &staInfo) const bool ApStationsManager::DelAssociationStation(const StationInfo &staInfo) const { - if (WifiSettings::GetInstance().ManageStation(staInfo, MODE_DEL)) { + if (WifiSettings::GetInstance().ManageStation(staInfo, MODE_DEL, m_id)) { + WIFI_LOGE("Instance is %{public}d failed to del station.", m_id); return false; } return true; @@ -66,15 +71,16 @@ bool ApStationsManager::DelAssociationStation(const StationInfo &staInfo) const bool ApStationsManager::EnableAllBlockList() const { std::vector results; - if (WifiSettings::GetInstance().GetBlockList(results)) { - WIFI_LOGE("failed to get blocklist."); + if (WifiSettings::GetInstance().GetBlockList(results, m_id)) { + WIFI_LOGE("Instance is %{public}d failed to get blocklist.", m_id); return false; } std::string mac; bool ret = true; for (std::vector::iterator iter = results.begin(); iter != results.end(); iter++) { - if (WifiApHalInterface::GetInstance().AddBlockByMac(iter->bssid) != WifiErrorNo::WIFI_IDL_OPT_OK) { - WIFI_LOGE("error:Failed to add block bssid is:%{private}s.", iter->bssid.c_str()); + if (WifiApHalInterface::GetInstance().AddBlockByMac(iter->bssid, m_id) != WifiErrorNo::WIFI_IDL_OPT_OK) { + WIFI_LOGE("Instance is %{public}d failed to add block bssid is:%{public}s.", m_id, + MacAnonymize(iter->bssid).c_str()); ret = false; } } @@ -85,8 +91,8 @@ void ApStationsManager::StationLeave(const std::string &mac) const { StationInfo staInfo; std::vector results; - if (WifiSettings::GetInstance().GetStationList(results)) { - WIFI_LOGE("failed to GetStationList."); + if (WifiSettings::GetInstance().GetStationList(results, m_id)) { + WIFI_LOGE("Instance is %{public}d failed to GetStationList.", m_id); return; } auto it = results.begin(); @@ -94,7 +100,7 @@ void ApStationsManager::StationLeave(const std::string &mac) const if (it->bssid == mac) { staInfo = *it; if (!DelAssociationStation(staInfo)) { - WIFI_LOGE("DelAssociationStation failed."); + WIFI_LOGE("Instance is %{public}d del AssociationStation failed.", m_id); return; } break; @@ -110,8 +116,8 @@ void ApStationsManager::StationJoin(const StationInfo &staInfo) const { StationInfo staInfoTemp = staInfo; std::vector results; - if (WifiSettings::GetInstance().GetStationList(results)) { - WIFI_LOGE("failed to GetStationList."); + if (WifiSettings::GetInstance().GetStationList(results, m_id)) { + WIFI_LOGE("Instance is %{public}d failed to GetStationList.", m_id); return; } auto it = results.begin(); @@ -125,7 +131,7 @@ void ApStationsManager::StationJoin(const StationInfo &staInfo) const } if (!AddAssociationStation(staInfoTemp)) { - WIFI_LOGE("AddAssociationStation failed."); + WIFI_LOGE("Instance is %{public}d addAssociationStation failed.", m_id); return; } @@ -140,11 +146,12 @@ void ApStationsManager::StationJoin(const StationInfo &staInfo) const bool ApStationsManager::DisConnectStation(const StationInfo &staInfo) const { std::string mac = staInfo.bssid; - int ret = static_cast(WifiApHalInterface::GetInstance().DisconnectStaByMac(mac)); + int ret = static_cast(WifiApHalInterface::GetInstance().DisconnectStaByMac(mac, m_id)); if (ret != WifiErrorNo::WIFI_IDL_OPT_OK) { - WIFI_LOGE("failed to DisConnectStation staInfo bssid:%{private}s, address:%{private}s, name:%{private}s.", - staInfo.bssid.c_str(), - staInfo.ipAddr.c_str(), + WIFI_LOGE("Instance is %{public}d failed to DisConnectStation staInfo bssid:%{public}s,address:%{public}s, name:%{private}s.", + m_id, + MacAnonymize(staInfo.bssid).c_str(), + IpAnonymize(staInfo.ipAddr).c_str(), staInfo.deviceName.c_str()); return false; } @@ -154,9 +161,9 @@ bool ApStationsManager::DisConnectStation(const StationInfo &staInfo) const std::vector ApStationsManager::GetAllConnectedStations() const { std::vector staMacList; - if (WifiApHalInterface::GetInstance().GetStationList(staMacList) == WifiErrorNo::WIFI_IDL_OPT_OK) { + if (WifiApHalInterface::GetInstance().GetStationList(staMacList, m_id) == WifiErrorNo::WIFI_IDL_OPT_OK) { for (size_t i = 0; i < staMacList.size(); ++i) { - WIFI_LOGD("staMacList[%{public}zu]:%{private}s.", i, staMacList[i].c_str()); + WIFI_LOGD("Instance is %{public}d staMacList[%{public}zu]:%{private}s.", m_id, i, staMacList[i].c_str()); } } return staMacList; diff --git a/services/wifi_standard/wifi_framework/wifi_manage/wifi_ap/ap_stations_manager.h b/wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_ap/ap_stations_manager.h similarity index 91% rename from services/wifi_standard/wifi_framework/wifi_manage/wifi_ap/ap_stations_manager.h rename to wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_ap/ap_stations_manager.h index 3154a516a86022ad99279418cd6efe061d735554..58d8e9a8c72e477914318370dca2c33814b276d0 100644 --- a/services/wifi_standard/wifi_framework/wifi_manage/wifi_ap/ap_stations_manager.h +++ b/wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_ap/ap_stations_manager.h @@ -1,5 +1,5 @@ /* - * Copyright (C) 2021 Huawei Device Co., Ltd. + * Copyright (C) 2021-2022 Huawei Device Co., Ltd. * 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 @@ -16,6 +16,7 @@ #define OHOS_STATIONS_MANAGER_H #include "ap_define.h" +#include "wifi_ap_msg.h" #include "wifi_error_no.h" namespace OHOS { @@ -25,14 +26,14 @@ class ApStationsManager { public: FRIEND_GTEST(ApStationsManager); /** - * @Description construction + * @Description construction. * @param None * @return None */ - ApStationsManager(); + explicit ApStationsManager(int id = 0); /** - * @Description destructor + * @Description destructor. * @param None * @return None */ @@ -40,20 +41,20 @@ public: /** * @Description Add a blocklist - * @param staInfo - Information about station to be added to the blocklist + * @param staInfo - Information about station to be added to the blocklist. * @return true: Adding succeeded. false: Failed to add. */ bool AddBlockList(const StationInfo &staInfo) const; /** * @Description Deleting a blocklist - * @param staInfo - Deleting the station information from the blocklist + * @param staInfo - Deleting the station information from the blocklist. * @return true: Deleted successfully false: Deletion failed */ bool DelBlockList(const StationInfo &staInfo) const; /** - * @Description Add all blocklists to the hostapd + * @Description Add all blocklists to the hostapd. * @param None * @return true: Set successful false: Set failed(Obtaining failed,Failed to set one or more blocklists.) @@ -74,7 +75,7 @@ public: */ void StationJoin(const StationInfo &staInfo) const; /** - * @Description Disconnect a specified station. + * @Description Disconnect a specified station.. * @param mac - address of the newly connected station * @return true: Disconnected successfully false: Disconnected failed */ @@ -113,6 +114,7 @@ private: bool DelAssociationStation(const StationInfo &staInfo) const; std::function m_stationChangeCallback; + int m_id; }; } // namespace Wifi } // namespace OHOS diff --git a/services/wifi_standard/wifi_framework/wifi_manage/wifi_ap/i_ap_service.h b/wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_ap/i_ap_service.h similarity index 85% rename from services/wifi_standard/wifi_framework/wifi_manage/wifi_ap/i_ap_service.h rename to wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_ap/i_ap_service.h index db88d4db9354306541620a400026400f78cfe833..aaa39b13d1527312ca4df3dbe621a44c6e97d5fe 100644 --- a/services/wifi_standard/wifi_framework/wifi_manage/wifi_ap/i_ap_service.h +++ b/wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_ap/i_ap_service.h @@ -1,5 +1,5 @@ /* - * Copyright (C) 2021 Huawei Device Co., Ltd. + * Copyright (C) 2021-2022 Huawei Device Co., Ltd. * 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 @@ -36,7 +36,10 @@ public: virtual ErrCode DisconnetStation(const StationInfo &stationInfo) = 0; virtual ErrCode GetStationList(std::vector &result) = 0; virtual ErrCode GetValidBands(std::vector &bands) = 0; - virtual ErrCode GetValidChannels(BandType band, std::vector &validchannel) = 0; + virtual ErrCode GetValidChannels(BandType band, std::vector &validChannel) = 0; + virtual ErrCode GetSupportedPowerModel(std::set& setPowerModelList) = 0; + virtual ErrCode GetPowerModel(PowerModel& model) = 0; + virtual ErrCode SetPowerModel(const PowerModel& model) = 0; /** * @Description - Registers all callbacks provided by the P2P service. diff --git a/services/wifi_standard/wifi_framework/wifi_manage/wifi_ap/i_ap_service_callbacks.h b/wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_ap/i_ap_service_callbacks.h similarity index 77% rename from services/wifi_standard/wifi_framework/wifi_manage/wifi_ap/i_ap_service_callbacks.h rename to wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_ap/i_ap_service_callbacks.h index 38b0ebdbb0eb1f0aecb8fdb3a9734c3b32ab926d..1823a8f88aaf04ef76046b5dcccd74378d60eee6 100644 --- a/services/wifi_standard/wifi_framework/wifi_manage/wifi_ap/i_ap_service_callbacks.h +++ b/wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_ap/i_ap_service_callbacks.h @@ -24,9 +24,9 @@ namespace OHOS { namespace Wifi { /* All callbacks provided by the AP service */ struct IApServiceCallbacks { - std::function OnApStateChangedEvent; - std::function OnHotspotStaJoinEvent; // STA device join event. - std::function OnHotspotStaLeaveEvent; // STA device leaving event. + std::function OnApStateChangedEvent; + std::function OnHotspotStaJoinEvent; // STA device join event. + std::function OnHotspotStaLeaveEvent; // STA device leaving event. }; } // namespace Wifi } // namespace OHOS diff --git a/services/wifi_standard/wifi_framework/wifi_manage/wifi_ap/wifi_ap_nat_manager.cpp b/wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_ap/wifi_ap_nat_manager.cpp similarity index 83% rename from services/wifi_standard/wifi_framework/wifi_manage/wifi_ap/wifi_ap_nat_manager.cpp rename to wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_ap/wifi_ap_nat_manager.cpp index 99081e7124448ff6b41d43ed7facb2f1fa67d778..decb63f64e5af75629e4101704964c14745ed298 100644 --- a/services/wifi_standard/wifi_framework/wifi_manage/wifi_ap/wifi_ap_nat_manager.cpp +++ b/wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_ap/wifi_ap_nat_manager.cpp @@ -1,5 +1,5 @@ /* - * Copyright (C) 2021 Huawei Device Co., Ltd. + * Copyright (C) 2021-2022 Huawei Device Co., Ltd. * 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 @@ -22,6 +22,7 @@ #include #include #include "network_interface.h" +#include "if_config.h" #include "wifi_logger.h" DEFINE_WIFILOG_HOTSPOT_LABEL("WifiApNatManager"); @@ -34,12 +35,11 @@ const std::string SYSTEM_COMMAND_IPTABLES = "/system/bin/iptables"; const std::string SYSTEM_COMMAND_IP6TABLES = "/system/bin/ip6tables"; const std::string IP_V4_FORWARDING_CONFIG_FILE = "/proc/sys/net/ipv4/ip_forward"; const std::string IP_V6_FORWARDING_CONFIG_FILE = "/proc/sys/net/ipv6/conf/all/forwarding"; -const int SYSTEM_NOT_EXECUTED = 127; bool WifiApNatManager::EnableInterfaceNat(bool enable, std::string inInterfaceName, std::string outInterfaceName) const { - WIFI_LOGI("EnableInterfaceNat enable [%{public}s], inInterfaceName [%s] outInterfaceName " - "[%s].", + WIFI_LOGI("EnableInterfaceNat enable [%{public}s], inInterfaceName [%{private}s] outInterfaceName " + "[%{private}s].", enable ? "true" : "false", inInterfaceName.c_str(), outInterfaceName.c_str()); @@ -51,7 +51,7 @@ bool WifiApNatManager::EnableInterfaceNat(bool enable, std::string inInterfaceNa } if (inInterfaceName == outInterfaceName) { - WIFI_LOGE("Duplicate interface name."); + WIFI_LOGI("Duplicate interface no need NAT."); return false; } @@ -98,7 +98,7 @@ bool WifiApNatManager::SetInterfaceRoute(bool enable) const ipRouteCmd.push_back("254"); ipRouteCmd.push_back("prio"); ipRouteCmd.push_back("18000"); - ExecCommand(ipRouteCmd); + IfConfig::GetInstance().ExecCommand(ipRouteCmd); /* Refresh the cache */ ipRouteCmd.clear(); @@ -106,7 +106,7 @@ bool WifiApNatManager::SetInterfaceRoute(bool enable) const ipRouteCmd.push_back("route"); ipRouteCmd.push_back("flush"); ipRouteCmd.push_back("cache"); - ExecCommand(ipRouteCmd); + IfConfig::GetInstance().ExecCommand(ipRouteCmd); return true; } @@ -118,7 +118,7 @@ bool WifiApNatManager::SetInterfaceNat(bool enable, const std::string &outInterf /* Clearing the Firewalls */ iptablesCmd.push_back(SYSTEM_COMMAND_IPTABLES); iptablesCmd.push_back("-F"); - ExecCommand(iptablesCmd); + IfConfig::GetInstance().ExecCommand(iptablesCmd); /* iptable forward ACCEPT */ iptablesCmd.clear(); @@ -126,7 +126,7 @@ bool WifiApNatManager::SetInterfaceNat(bool enable, const std::string &outInterf iptablesCmd.push_back("-P"); iptablesCmd.push_back("FORWARD"); iptablesCmd.push_back(enable ? "ACCEPT" : "DROP"); - ExecCommand(iptablesCmd); + IfConfig::GetInstance().ExecCommand(iptablesCmd); /* Setting NAT Rules */ iptablesCmd.clear(); @@ -139,7 +139,7 @@ bool WifiApNatManager::SetInterfaceNat(bool enable, const std::string &outInterf iptablesCmd.push_back(outInterfaceName); iptablesCmd.push_back("-j"); iptablesCmd.push_back("MASQUERADE"); - ExecCommand(iptablesCmd); + IfConfig::GetInstance().ExecCommand(iptablesCmd); return true; } @@ -148,7 +148,7 @@ bool WifiApNatManager::WriteDataToFile(const std::string &fileName, const std::s { std::ofstream outf(fileName, std::ios::out); if (!outf) { - WIFI_LOGE("write content [%s] to file [%s] failed. error: %{public}d.", + WIFI_LOGE("write content [%publics] to file [%publics] failed. error: %{public}d.", content.c_str(), fileName.c_str(), errno); return false; } @@ -156,24 +156,5 @@ bool WifiApNatManager::WriteDataToFile(const std::string &fileName, const std::s outf.close(); return true; } - -bool WifiApNatManager::ExecCommand(const std::vector &vecCommandArg) const -{ - std::string command; - for (auto iter : vecCommandArg) { - command += iter; - command += " "; - } - - WIFI_LOGE("exec cmd: [%s]", command.c_str()); - - int ret = system(command.c_str()); - if (ret == -1 || ret == SYSTEM_NOT_EXECUTED) { - WIFI_LOGE("exec failed. cmd: %s, error:%{public}d.", command.c_str(), errno); - return false; - } - - return true; -} } // namespace Wifi } // namespace OHOS \ No newline at end of file diff --git a/services/wifi_standard/wifi_framework/wifi_manage/wifi_ap/wifi_ap_nat_manager.h b/wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_ap/wifi_ap_nat_manager.h similarity index 86% rename from services/wifi_standard/wifi_framework/wifi_manage/wifi_ap/wifi_ap_nat_manager.h rename to wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_ap/wifi_ap_nat_manager.h index eb4557ec5b4fdd82d0640d958cc9df83fb785953..9b438f21a8e88aaba8ea4a9c955aa3d4dfca39a3 100644 --- a/services/wifi_standard/wifi_framework/wifi_manage/wifi_ap/wifi_ap_nat_manager.h +++ b/wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_ap/wifi_ap_nat_manager.h @@ -1,5 +1,5 @@ /* - * Copyright (C) 2021 Huawei Device Co., Ltd. + * Copyright (C) 2021-2022 Huawei Device Co., Ltd. * 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 @@ -63,14 +63,6 @@ private: * @return true: success false: failed */ bool WriteDataToFile(const std::string &fileName, const std::string &content) const; - - /** - * @Description Running System Commands. - * @param vecCommandArg - Related Items in Commands, - vecCommandArg[0] is file path. - * @return true: success false: failed - */ - bool ExecCommand(const std::vector &vecCommandArg) const; }; } // namespace Wifi } // namespace OHOS diff --git a/services/wifi_standard/wifi_framework/wifi_manage/wifi_auth_center.cpp b/wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_auth_center.cpp similarity index 71% rename from services/wifi_standard/wifi_framework/wifi_manage/wifi_auth_center.cpp rename to wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_auth_center.cpp index 9da26944c2fa6f664f4c0e76d2c18a36fe030280..e0311f1bc3f36feaa90e55d6c24f8b15be97ef61 100644 --- a/services/wifi_standard/wifi_framework/wifi_manage/wifi_auth_center.cpp +++ b/wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_auth_center.cpp @@ -1,5 +1,5 @@ /* - * Copyright (C) 2021 Huawei Device Co., Ltd. + * Copyright (C) 2021-2022 Huawei Device Co., Ltd. * 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 @@ -97,6 +97,14 @@ int WifiAuthCenter::VerifySetWifiConfigPermission(const int &pid, const int &uid return WifiPermissionHelper::VerifySetWifiConfigPermission(pid, uid); } +int WifiAuthCenter::VerifyGetWifiConfigPermission(const int &pid, const int &uid) +{ + if (g_permissinAlwaysGrant) { + return PERMISSION_GRANTED; + } + return WifiPermissionHelper::VerifyGetWifiConfigPermission(pid, uid); +} + int WifiAuthCenter::VerifyGetWifiDirectDevicePermission(const int &pid, const int &uid) { if (g_permissinAlwaysGrant) { @@ -104,5 +112,37 @@ int WifiAuthCenter::VerifyGetWifiDirectDevicePermission(const int &pid, const in } return WifiPermissionHelper::VerifyGetWifiDirectDevicePermission(pid, uid); } + +int WifiAuthCenter::VerifyManageWifiHotspotPermission(const int &pid, const int &uid) +{ + if (g_permissinAlwaysGrant) { + return PERMISSION_GRANTED; + } + return WifiPermissionHelper::VerifyManageWifiHotspotPermission(pid, uid); +} + +int WifiAuthCenter::VerifyGetWifiPeersMacPermission(const int &pid, const int &uid) +{ + if (g_permissinAlwaysGrant) { + return PERMISSION_GRANTED; + } + return WifiPermissionHelper::VerifyGetWifiPeersMacPermission(pid, uid); +} + +int WifiAuthCenter::VerifyGetWifiInfoInternalPermission(const int &pid, const int &uid) +{ + if (g_permissinAlwaysGrant) { + return PERMISSION_GRANTED; + } + return WifiPermissionHelper::VerifyGetWifiInfoInternalPermission(pid, uid); +} + +int WifiAuthCenter::VerifyManageWifiHotspotExtPermission(const int &pid, const int &uid) +{ + if (g_permissinAlwaysGrant) { + return PERMISSION_GRANTED; + } + return WifiPermissionHelper::VerifyManageWifiHotspotExtPermission(pid, uid); +} } // namespace Wifi } // namespace OHOS \ No newline at end of file diff --git a/services/wifi_standard/wifi_framework/wifi_manage/wifi_auth_center.h b/wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_auth_center.h similarity index 71% rename from services/wifi_standard/wifi_framework/wifi_manage/wifi_auth_center.h rename to wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_auth_center.h index b3c85f9f4870f4c452f5bd37ca45517183f359b5..962117e875bceffa7d23a3756c38bc1bde93c659 100644 --- a/services/wifi_standard/wifi_framework/wifi_manage/wifi_auth_center.h +++ b/wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_auth_center.h @@ -1,5 +1,5 @@ /* - * Copyright (C) 2021 Huawei Device Co., Ltd. + * Copyright (C) 2021-2022 Huawei Device Co., Ltd. * 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 @@ -104,6 +104,15 @@ public: */ int VerifySetWifiConfigPermission(const int &pid, const int &uid); + /** + * @Description Verify whether the app has the permission to get hotspot config, hotspot blocklist config + * + * @param pid - the app's process id + * @param uid - the app id + * @return int - PERMISSION_DENIED or PERMISSION_GRANTED + */ + int VerifyGetWifiConfigPermission(const int &pid, const int &uid); + /** * @Description : Verify location information about nearby P2P devices Permission. * @@ -113,6 +122,42 @@ public: */ int VerifyGetWifiDirectDevicePermission(const int &pid, const int &uid); + /** + * @Description : Verify manage wifi hotspot Permission. + * + * @param pid - Process ID.[in] + * @param uid - User ID.[in] + * @return int - PERMISSION_DENIED or PERMISSION_GRANTED + */ + int VerifyManageWifiHotspotPermission(const int &pid, const int &uid); + + /** + * @Description : Get wifi peers mac Permission. + * + * @param pid - Process ID.[in] + * @param uid - User ID.[in] + * @return int - PERMISSION_DENIED or PERMISSION_GRANTED + */ + int VerifyGetWifiPeersMacPermission(const int &pid, const int &uid); + + /** + * @Description : Get wifi internal wifi info Permission. + * + * @param pid - Process ID.[in] + * @param uid - User ID.[in] + * @return int - PERMISSION_DENIED or PERMISSION_GRANTED + */ + int VerifyGetWifiInfoInternalPermission(const int &pid, const int &uid); + + /** + * @Description : Verify manage wifi hotspot extend permission. + * + * @param pid - Process ID.[in] + * @param uid - User ID.[in] + * @return int - PERMISSION_DENIED or PERMISSION_GRANTED + */ + int VerifyManageWifiHotspotExtPermission(const int &pid, const int &uid); + private: /* system auth service client */ }; diff --git a/services/wifi_standard/ipc_framework/cRPC/BUILD.gn b/wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_common/BUILD.gn similarity index 33% rename from services/wifi_standard/ipc_framework/cRPC/BUILD.gn rename to wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_common/BUILD.gn index c5315d76b80a7ac30fd82bb6f78d69067ac398f1..a00d9f536309e19c2800bae4558c4a32a3a0e4bf 100644 --- a/services/wifi_standard/ipc_framework/cRPC/BUILD.gn +++ b/wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_common/BUILD.gn @@ -1,4 +1,4 @@ -# Copyright (C) 2021 Huawei Device Co., Ltd. +# Copyright (C) 2022 Huawei Device Co., Ltd. # 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 @@ -12,52 +12,32 @@ # limitations under the License. import("//build/ohos.gni") +import("//foundation/communication/wifi/wifi/wifi.gni") -ohos_static_library("crpc_server") { - sources = [ - "./src/context.c", - "./src/evloop.c", - "./src/hash_table.c", - "./src/net.c", - "./src/serial.c", - "./src/server.c", - ] - +ohos_shared_library("wifi_common_service") { + install_enable = true include_dirs = [ - "include", - "//utils/native/base/include", - "//base/hiviewdfx/hilog/interfaces/native/innerkits/include", - ] - cflags_cc = [ "-fno-rtti" ] - deps = [ - "//base/hiviewdfx/hilog/interfaces/native/innerkits:libhilog", - "//utils/native/base:utils", + "$WIFI_ROOT_DIR/services/wifi_standard/wifi_framework/wifi_manage/idl_client", + "$WIFI_ROOT_DIR/services/wifi_standard/wifi_framework/wifi_manage/idl_client/idl_interface", + "$WIFI_ROOT_DIR/frameworks/native/interfaces", + "$WIFI_ROOT_DIR/services/wifi_standard/wifi_framework/wifi_toolkit/net_helper", + "$WIFI_ROOT_DIR/services/wifi_standard/wifi_framework/wifi_toolkit/include", + "$WIFI_ROOT_DIR/services/wifi_standard/wifi_framework/wifi_toolkit/utils", + "$WIFI_ROOT_DIR/services/wifi_standard/wifi_framework/wifi_toolkit/config", + "$WIFI_ROOT_DIR/services/wifi_standard/wifi_framework/wifi_toolkit/log", + "$WIFI_ROOT_DIR/services/wifi_standard/ipc_framework/cRPC/include", + "$WIFI_ROOT_DIR/services/wifi_standard/include", ] -} -ohos_static_library("crpc_client") { - sources = [ - "./src/client.c", - "./src/context.c", - "./src/net.c", - "./src/serial.c", - ] - include_dirs = [ - "include", - "//utils/native/base/include", - "//base/hiviewdfx/hilog/interfaces/native/innerkits/include", - "//foundation/communication/wifi/services/wifi_standard/wifi_framework/common/log", - ] - cflags_cc = [ "-fno-rtti" ] - deps = [ - "//base/hiviewdfx/hilog/interfaces/native/innerkits:libhilog", - "//utils/native/base:utils", - ] -} + sources = [ "wifi_chip_capability.cpp" ] -group("ipc_framework") { - deps = [ - ":crpc_client", - ":crpc_server", + deps = [ "$WIFI_ROOT_DIR/services/wifi_standard/wifi_framework/wifi_manage/idl_client:wifi_idl_client" ] + + external_deps = [ + "c_utils:utils", + "hiviewdfx_hilog_native:libhilog", ] + + part_name = "wifi" + subsystem_name = "communication" } diff --git a/wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_common/wifi_chip_capability.cpp b/wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_common/wifi_chip_capability.cpp new file mode 100644 index 0000000000000000000000000000000000000000..cb2db7562586a3e784e4c627e69756db4d79ebdc --- /dev/null +++ b/wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_common/wifi_chip_capability.cpp @@ -0,0 +1,121 @@ +/* + * Copyright (C) 2022 Huawei Device Co., Ltd. + * 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 "wifi_chip_capability.h" +#include +#include "wifi_chip_hal_interface.h" +#include "wifi_logger.h" + +namespace OHOS { +namespace Wifi { +DEFINE_WIFILOG_LABEL("ChipCapability"); +ChipCapability& ChipCapability::GetInstance() +{ + static ChipCapability inst; + return inst; +} + +ChipCapability::ChipCapability() +{ + m_isInitialized = false; + m_isSupportDbdc = false; + m_isSupportCsa = false; + m_isSupportRadarDetect = false; + m_isSupportDfsChannel = false; + m_isSupportIndoorChannel = false; +} + +ChipCapability::~ChipCapability() +{ +} + +bool ChipCapability::InitializeChipCapability() +{ + WIFI_LOGI("Enter InitializeChipCapability"); + if (m_isInitialized) { + WIFI_LOGI("ChipCapability has been initialized"); + return true; + } + + m_isInitialized = true; + WifiErrorNo ret = WIFI_IDL_OPT_FAILED; + ret = WifiChipHalInterface::GetInstance().IsSupportDbdc(m_isSupportDbdc); + if (ret != WIFI_IDL_OPT_OK) { + m_isInitialized = false; + WIFI_LOGE("Get IsSupportDbdc failed"); + } + ret = WifiChipHalInterface::GetInstance().IsSupportCsa(m_isSupportCsa); + if (ret != WIFI_IDL_OPT_OK) { + m_isInitialized = false; + WIFI_LOGE("Get IsSupportCsa failed"); + } + ret = WifiChipHalInterface::GetInstance().IsSupportRadarDetect(m_isSupportRadarDetect); + if (ret != WIFI_IDL_OPT_OK) { + m_isInitialized = false; + WIFI_LOGE("Get IsP2pSupportRadarDetect failed"); + } + ret = WifiChipHalInterface::GetInstance().IsSupportDfsChannel(m_isSupportDfsChannel); + if (ret != WIFI_IDL_OPT_OK) { + m_isInitialized = false; + WIFI_LOGE("Get IsP2pSupportDfsChannel failed"); + } + ret = WifiChipHalInterface::GetInstance().IsSupportIndoorChannel(m_isSupportIndoorChannel); + if (ret != WIFI_IDL_OPT_OK) { + m_isInitialized = false; + WIFI_LOGE("Get IsP2pSupportIndoorChannel failed"); + } + ToString(); + return m_isInitialized; +} + +bool ChipCapability::IsSupportDbdc(void) +{ + return m_isSupportDbdc; +} + +bool ChipCapability::IsSupportCsa(void) +{ + return m_isSupportCsa; +} + +bool ChipCapability::IsSupportRadarDetect(void) +{ + return m_isSupportRadarDetect; +} + +bool ChipCapability::IsSupportDfsChannel(void) +{ + return m_isSupportDfsChannel; +} + +bool ChipCapability::IsSupportIndoorChannel(void) +{ + return m_isSupportIndoorChannel; +} + +std::string ChipCapability::ToString(void) +{ + std::stringstream ss; + ss << "[WifiChipCap]:" << "\n"; + ss << "Dbdc = " << m_isSupportDbdc << "\n"; + ss << "Csa = " << m_isSupportCsa << "\n"; + ss << "RadarDetect = " << m_isSupportRadarDetect << "\n"; + ss << "DfsChannel = " << m_isSupportDfsChannel << "\n"; + ss << "IndoorChannel = " << m_isSupportIndoorChannel << "\n"; + WIFI_LOGI("%{public}s", ss.str().c_str()); + return ss.str(); +} +} // namespace Wifi +} // namespace OHOS \ No newline at end of file diff --git a/wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_common/wifi_chip_capability.h b/wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_common/wifi_chip_capability.h new file mode 100644 index 0000000000000000000000000000000000000000..1635be55ed21c984c5c9b0e46ead554b2beaa33e --- /dev/null +++ b/wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_common/wifi_chip_capability.h @@ -0,0 +1,49 @@ +/* + * Copyright (C) 2022 Huawei Device Co., Ltd. + * 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 OHOS_WIFI_CHIP_CAPABILITY_H +#define OHOS_WIFI_CHIP_CAPABILITY_H + +#include + +namespace OHOS { +namespace Wifi { +class ChipCapability { +public: + ChipCapability(); + virtual ~ChipCapability(); + bool InitializeChipCapability(); + static ChipCapability& GetInstance(); + + bool IsSupportDbdc(void); + bool IsSupportCsa(void); + bool IsSupportRadarDetect(void); + bool IsSupportDfsChannel(void); + bool IsSupportIndoorChannel(void); + +private: + std::string ToString(void); + +private: + bool m_isInitialized; + bool m_isSupportDbdc; + bool m_isSupportCsa; + bool m_isSupportRadarDetect; + bool m_isSupportDfsChannel; + bool m_isSupportIndoorChannel; +}; +} // namespace Wifi +} // namespace OHOS +#endif \ No newline at end of file diff --git a/services/wifi_standard/wifi_framework/wifi_manage/wifi_config_center.cpp b/wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_config_center.cpp similarity index 70% rename from services/wifi_standard/wifi_framework/wifi_manage/wifi_config_center.cpp rename to wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_config_center.cpp index dabbd675c2f5af26d440126b9e7dd8057f30729b..ea5cb46f9ca2faa32a49610d29c39775c3a75ef6 100644 --- a/services/wifi_standard/wifi_framework/wifi_manage/wifi_config_center.cpp +++ b/wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_config_center.cpp @@ -30,7 +30,7 @@ WifiConfigCenter &WifiConfigCenter::GetInstance() WifiConfigCenter::WifiConfigCenter() { mStaMidState = WifiOprMidState::CLOSED; - mApMidState = WifiOprMidState::CLOSED; + mApMidState.emplace(0, WifiOprMidState::CLOSED); mP2pMidState = WifiOprMidState::CLOSED; mScanMidState = WifiOprMidState::CLOSED; mWifiOpenedWhenAirplane = false; @@ -115,6 +115,11 @@ int WifiConfigCenter::GetDeviceConfig(std::vector &results) return WifiSettings::GetInstance().GetDeviceConfig(results); } +int WifiConfigCenter::GetCandidateConfigs(const int uid, std::vector &results) +{ + return WifiSettings::GetInstance().GetAllCandidateConfig(uid, results); +} + int WifiConfigCenter::SetDeviceState(int networkId, int state, bool bSetOther) { return WifiSettings::GetInstance().SetDeviceState(networkId, state, bSetOther); @@ -145,59 +150,80 @@ int WifiConfigCenter::GetCountryCode(std::string &countryCode) return WifiSettings::GetInstance().GetCountryCode(countryCode); } -WifiOprMidState WifiConfigCenter::GetApMidState() +bool WifiConfigCenter::IsLoadStabak() { - return mApMidState.load(); + return WifiSettings::GetInstance().IsLoadStabak(); } -bool WifiConfigCenter::SetApMidState(WifiOprMidState expState, WifiOprMidState state) +WifiOprMidState WifiConfigCenter::GetApMidState(int id) { - return mApMidState.compare_exchange_strong(expState, state); + auto iter = mApMidState.find(id); + if (iter != mApMidState.end()) { + return iter->second.load(); + } else { + mApMidState.emplace(id, WifiOprMidState::CLOSED); + return mApMidState[id].load(); + } } -void WifiConfigCenter::SetApMidState(WifiOprMidState state) +bool WifiConfigCenter::SetApMidState(WifiOprMidState expState, WifiOprMidState state, int id) { - mApMidState = state; + auto iter = mApMidState.find(id); + if (iter != mApMidState.end()) { + return iter->second.compare_exchange_strong(expState, state); + } else { + mApMidState.emplace(id, state); + return true; + } + return false; +} + +void WifiConfigCenter::SetApMidState(WifiOprMidState state, int id) +{ + auto ret = mApMidState.emplace(id, state); + if (!ret.second) { + mApMidState[id] = state; + } } -int WifiConfigCenter::GetHotspotState() +int WifiConfigCenter::GetHotspotState(int id) { - return WifiSettings::GetInstance().GetHotspotState(); + return WifiSettings::GetInstance().GetHotspotState(id); } -int WifiConfigCenter::SetHotspotConfig(const HotspotConfig &config) +int WifiConfigCenter::SetHotspotConfig(const HotspotConfig &config, int id) { - return WifiSettings::GetInstance().SetHotspotConfig(config); + return WifiSettings::GetInstance().SetHotspotConfig(config, id); } -int WifiConfigCenter::GetHotspotConfig(HotspotConfig &config) +int WifiConfigCenter::GetHotspotConfig(HotspotConfig &config, int id) { - return WifiSettings::GetInstance().GetHotspotConfig(config); + return WifiSettings::GetInstance().GetHotspotConfig(config, id); } -int WifiConfigCenter::GetStationList(std::vector &results) +int WifiConfigCenter::GetStationList(std::vector &results, int id) { - return WifiSettings::GetInstance().GetStationList(results); + return WifiSettings::GetInstance().GetStationList(results, id); } -int WifiConfigCenter::FindConnStation(const StationInfo &info) +int WifiConfigCenter::FindConnStation(const StationInfo &info, int id) { - return WifiSettings::GetInstance().FindConnStation(info); + return WifiSettings::GetInstance().FindConnStation(info, id); } -int WifiConfigCenter::GetBlockLists(std::vector &infos) +int WifiConfigCenter::GetBlockLists(std::vector &infos, int id) { - return WifiSettings::GetInstance().GetBlockList(infos); + return WifiSettings::GetInstance().GetBlockList(infos, id); } -int WifiConfigCenter::AddBlockList(const StationInfo &info) +int WifiConfigCenter::AddBlockList(const StationInfo &info, int id) { - return WifiSettings::GetInstance().ManageBlockList(info, MODE_ADD); + return WifiSettings::GetInstance().ManageBlockList(info, MODE_ADD, id); } -int WifiConfigCenter::DelBlockList(const StationInfo &info) +int WifiConfigCenter::DelBlockList(const StationInfo &info, int id) { - return WifiSettings::GetInstance().ManageBlockList(info, MODE_DEL); + return WifiSettings::GetInstance().ManageBlockList(info, MODE_DEL, id); } int WifiConfigCenter::GetValidBands(std::vector &bands) @@ -210,31 +236,6 @@ int WifiConfigCenter::GetValidChannels(ChannelsTable &channelsInfo) return WifiSettings::GetInstance().GetValidChannels(channelsInfo); } -bool WifiConfigCenter::GetSupportedBandChannel() -{ - std::vector allowed5GFreq, allowed2GFreq; - std::vector allowed5GChan, allowed2GChan; - if (WifiApHalInterface::GetInstance().GetFrequenciesByBand(static_cast(BandType::BAND_2GHZ), allowed2GFreq)) { - WIFI_LOGW("fail to get 2.4G channel"); - } - if (WifiApHalInterface::GetInstance().GetFrequenciesByBand(static_cast(BandType::BAND_5GHZ), allowed5GFreq)) { - WIFI_LOGW("fail to get 5G channel"); - } - - TransformFrequencyIntoChannel(allowed5GFreq, allowed5GChan); - TransformFrequencyIntoChannel(allowed2GFreq, allowed2GChan); - - ChannelsTable ChanTbs; - ChanTbs[BandType::BAND_2GHZ] = allowed2GChan; - ChanTbs[BandType::BAND_5GHZ] = allowed5GChan; - - if (WifiSettings::GetInstance().SetValidChannels(ChanTbs)) { - WIFI_LOGE("fail to SetValidChannels"); - return false; - } - return true; -} - WifiOprMidState WifiConfigCenter::GetScanMidState() { return mScanMidState.load(); @@ -310,7 +311,7 @@ void WifiConfigCenter::SetScreenState(const int &state) WifiSettings::GetInstance().SetScreenState(state); } -int WifiConfigCenter::GetScreenState() +int WifiConfigCenter::GetScreenState() const { return WifiSettings::GetInstance().GetScreenState(); } @@ -320,17 +321,17 @@ void WifiConfigCenter::SetAirplaneModeState(const int &state) WifiSettings::GetInstance().SetAirplaneModeState(state); } -int WifiConfigCenter::GetAirplaneModeState() +int WifiConfigCenter::GetAirplaneModeState() const { return WifiSettings::GetInstance().GetAirplaneModeState(); } -void WifiConfigCenter::SetAppRunningState(const int &state) +void WifiConfigCenter::SetAppRunningState(ScanMode appRunMode) { - WifiSettings::GetInstance().SetAppRunningState(state); + WifiSettings::GetInstance().SetAppRunningState(appRunMode); } -int WifiConfigCenter::GetAppRunningState() +ScanMode WifiConfigCenter::GetAppRunningState() const { return WifiSettings::GetInstance().GetAppRunningState(); } @@ -340,11 +341,41 @@ void WifiConfigCenter::SetPowerSavingModeState(const int &state) WifiSettings::GetInstance().SetPowerSavingModeState(state); } -int WifiConfigCenter::GetPowerSavingModeState() +int WifiConfigCenter::GetPowerSavingModeState() const { return WifiSettings::GetInstance().GetPowerSavingModeState(); } +void WifiConfigCenter::SetAppPackageName(const std::string &appPackageName) +{ + WifiSettings::GetInstance().SetAppPackageName(appPackageName); +} + +const std::string WifiConfigCenter::GetAppPackageName() const +{ + return WifiSettings::GetInstance().GetAppPackageName(); +} + +void WifiConfigCenter::SetFreezeModeState(int state) +{ + WifiSettings::GetInstance().SetFreezeModeState(state); +} + +int WifiConfigCenter::GetFreezeModeState() const +{ + return WifiSettings::GetInstance().GetFreezeModeState(); +} + +void WifiConfigCenter::SetNoChargerPlugModeState(int state) +{ + WifiSettings::GetInstance().SetNoChargerPlugModeState(state); +} + +int WifiConfigCenter::GetNoChargerPlugModeState() const +{ + return WifiSettings::GetInstance().GetNoChargerPlugModeState(); +} + int WifiConfigCenter::SetP2pDeviceName(const std::string &deviceName) { return WifiSettings::GetInstance().SetP2pDeviceName(deviceName); diff --git a/services/wifi_standard/wifi_framework/wifi_manage/wifi_config_center.h b/wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_config_center.h similarity index 81% rename from services/wifi_standard/wifi_framework/wifi_manage/wifi_config_center.h rename to wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_config_center.h index e6c69503e54216428dfc9eaa723999d03be12f06..4affcf4c5f1ba922bae5cd76d07872bac4a2ed47 100644 --- a/services/wifi_standard/wifi_framework/wifi_manage/wifi_config_center.h +++ b/wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_config_center.h @@ -55,7 +55,7 @@ public: * @param expState - expect the original state * @param state - want to set state * @return true - set the state success - * @return false - set state failed, current mid sate is not equal to the expState + * @return false - set state failed, current mid state is not equal to the expState */ bool SetWifiMidState(WifiOprMidState expState, WifiOprMidState state); @@ -142,12 +142,20 @@ public: */ int GetDeviceConfig(std::vector &results); + /** + * @Description Get all candidate wifi device config + * + * @param results - output wifi device config results + * @return int - 0 success + */ + int GetCandidateConfigs(const int uid, std::vector &results); + /** * @Description Set a wifi device's state who's networkId equals input networkId; * when the param bSetOther is true and the state is ENABLED, that means we need * to set other wifi device DISABLED * @param networkId - the wifi device's id - * @param state - WifiDeviceConfigStatus INVALID/CURRENT/DISABLED/ENABLED/UNKNOWN + * @param state - WifiDeviceConfigStatus DISABLED/ENABLED/UNKNOWN * @param bSetOther - whether set other device config disabled * @return int - when 0 means success, other means some fails happened, * Input state invalid or not find the wifi device config @@ -194,12 +202,19 @@ public: */ int GetCountryCode(std::string &countryCode); + /** + * @Description Obtaining Whether to Load the Configuration of the Standby STA. + * + * @return bool - Indicates whether to load the configuration of the standby STA. + */ + bool IsLoadStabak(); + /** * @Description Get current hotspot middle state * * @return WifiOprMidState - which can be a CLOSED/CLOSING/OPENING/RUNNING/UNKNOWN */ - WifiOprMidState GetApMidState(); + WifiOprMidState GetApMidState(int id = 0); /** * @Description Set current hotspot middle state @@ -207,23 +222,23 @@ public: * @param expState - expect the original state * @param state - want to set state * @return true - set the state success - * @return false - set state failed, current mid sate is not equal to the expState + * @return false - set state failed, current mid state is not equal to the expState */ - bool SetApMidState(WifiOprMidState expState, WifiOprMidState state); + bool SetApMidState(WifiOprMidState expState, WifiOprMidState state, int id = 0); /** * @Description Force to set current hotspot middle state * * @param state - want to set state */ - void SetApMidState(WifiOprMidState state); + void SetApMidState(WifiOprMidState state, int id = 0); /** * @Description Get current hotspot state * * @return int - the hotspot state, IDLE/STARTING/STARTED/CLOSING/CLOSED */ - int GetHotspotState(); + int GetHotspotState(int id = 0); /** * @Description Set the hotspot config @@ -231,7 +246,7 @@ public: * @param config - input HotspotConfig struct * @return int - 0 success */ - int SetHotspotConfig(const HotspotConfig &config); + int SetHotspotConfig(const HotspotConfig &config, int id = 0); /** * @Description Get the hotspot config @@ -239,7 +254,7 @@ public: * @param config - output HotspotConfig struct * @return int - 0 success */ - int GetHotspotConfig(HotspotConfig &config); + int GetHotspotConfig(HotspotConfig &config, int id = 0); /** * @Description Get current hotspot accept linked stations @@ -247,7 +262,7 @@ public: * @param results - output StationInfo results * @return int - 0 success */ - int GetStationList(std::vector &results); + int GetStationList(std::vector &results, int id = 0); /** * @Description Judge whether the station is in current linked station list @@ -255,7 +270,7 @@ public: * @param info - input StationInfo struct * @return int - 0 find the station, exist; -1 not find, not exist */ - int FindConnStation(const StationInfo &info); + int FindConnStation(const StationInfo &info, int id = 0); /** * @Description Get the block list @@ -263,7 +278,7 @@ public: * @param infos - output StationInfo results * @return int - 0 success */ - int GetBlockLists(std::vector &infos); + int GetBlockLists(std::vector &infos, int id = 0); /** * @Description Add the station info into the block list @@ -271,7 +286,7 @@ public: * @param info - input StationInfo struct * @return int - 0 success */ - int AddBlockList(const StationInfo &info); + int AddBlockList(const StationInfo &info, int id = 0); /** * @Description Remove the station info from the block list @@ -279,7 +294,7 @@ public: * @param info - input StationInfo struct * @return int - 0 success */ - int DelBlockList(const StationInfo &info); + int DelBlockList(const StationInfo &info, int id = 0); /** * @Description Get the valid bands info @@ -297,11 +312,6 @@ public: */ int GetValidChannels(ChannelsTable &channelsInfo); - /** - * @Description request to chip for initation current vaild bands and channels - */ - bool GetSupportedBandChannel(); - /** * @Description Get current scan service middle state * @@ -315,7 +325,7 @@ public: * @param expState - expect the original state * @param state - want to set state * @return true - set the state success - * @return false - set state failed, current mid sate is not equal to the expState + * @return false - set state failed, current mid state is not equal to the expState */ bool SetScanMidState(WifiOprMidState expState, WifiOprMidState state); @@ -348,7 +358,7 @@ public: * @param expState - expect the original state * @param state - want to set state * @return true - set the state success - * @return false - set state failed, current mid sate is not equal to the expState + * @return false - set state failed, current mid state is not equal to the expState */ bool SetP2pMidState(WifiOprMidState expState, WifiOprMidState state); @@ -433,7 +443,7 @@ public: * * @return int - 1 open; 2 close */ - int GetScreenState(); + int GetScreenState() const; /** * @Description Set current airplane mode state @@ -447,21 +457,21 @@ public: * * @return int - 1 open; 2 close */ - int GetAirplaneModeState(); + int GetAirplaneModeState() const; /** * @Description Set current app running mode * - * @param state - 1 front; 2 backend + * @param appRunMode - app run mode */ - void SetAppRunningState(const int &state); + void SetAppRunningState(ScanMode appRunMode); /** * @Description Get current app running mode * - * @return int - 1 front; 2 backend + * @param ScanMode */ - int GetAppRunningState(); + ScanMode GetAppRunningState() const; /** * @Description Set current power saving mode @@ -475,7 +485,49 @@ public: * * @return int - 1 saving mode; 2 not saving mode */ - int GetPowerSavingModeState(); + int GetPowerSavingModeState() const; + + /** + * @Description Set app package name. + * + * @param appPackageName - app package name + */ + void SetAppPackageName(const std::string &appPackageName); + + /** + * @Description Get app package name. + * + * @return const std::string& - app package name. + */ + const std::string GetAppPackageName() const; + + /** + * @Description Set freeze mode state. + * + * @param state - 1 freeze mode; 2 moving mode + */ + void SetFreezeModeState(int state); + + /** + * @Description Get freeze mode state. + * + * @return freeze mode. + */ + int GetFreezeModeState() const; + + /** + * @Description Set no charger plugged in mode. + * + * @param state - 1 no charger plugged in mode; 2 charger plugged in mode + */ + void SetNoChargerPlugModeState(int state); + + /** + * @Description Get no charger plugged in mode. + * + * @return no charger plugged in mode. + */ + int GetNoChargerPlugModeState() const; /** * @Description set the device name @@ -487,7 +539,7 @@ public: private: std::atomic mStaMidState; - std::atomic mApMidState; + std::map> mApMidState; std::atomic mP2pMidState; std::atomic mScanMidState; /* Time interval for disabling and re-enabling the STA */ diff --git a/services/wifi_standard/wifi_framework/wifi_manage/wifi_device_callback_proxy.cpp b/wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_device_callback_proxy.cpp similarity index 72% rename from services/wifi_standard/wifi_framework/wifi_manage/wifi_device_callback_proxy.cpp rename to wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_device_callback_proxy.cpp index 59ce431dce4b57ac3a1f91d93de43e65a3695d3e..e7baf7eaeab0b0079634ca2faf03c4a2e3f4e141 100644 --- a/services/wifi_standard/wifi_framework/wifi_manage/wifi_device_callback_proxy.cpp +++ b/wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_device_callback_proxy.cpp @@ -1,5 +1,5 @@ /* - * Copyright (C) 2021 Huawei Device Co., Ltd. + * Copyright (C) 2021-2022 Huawei Device Co., Ltd. * 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 @@ -31,9 +31,12 @@ void WifiDeviceCallBackProxy::OnWifiStateChanged(int state) MessageOption option; MessageParcel data; MessageParcel reply; + if (!data.WriteInterfaceToken(GetDescriptor())) { + WIFI_LOGE("Write interface token error: %{public}s", __func__); + return; + } data.WriteInt32(0); data.WriteInt32(state); - int error = Remote()->SendRequest(WIFI_CBK_CMD_STATE_CHANGE, data, reply, option); if (error != ERR_NONE) { WIFI_LOGE("Set Attr(%{public}d) failed,error code is %{public}d", WIFI_CBK_CMD_STATE_CHANGE, error); @@ -53,6 +56,10 @@ void WifiDeviceCallBackProxy::OnWifiConnectionChanged(int state, const WifiLinke MessageOption option; MessageParcel data; MessageParcel reply; + if (!data.WriteInterfaceToken(GetDescriptor())) { + WIFI_LOGE("Write interface token error: %{public}s", __func__); + return; + } data.WriteInt32(0); data.WriteInt32(state); data.WriteInt32(info.networkId); @@ -66,13 +73,14 @@ void WifiDeviceCallBackProxy::OnWifiConnectionChanged(int state, const WifiLinke data.WriteInt32(info.ipAddress); data.WriteInt32((int)info.connState); data.WriteBool(info.ifHiddenSSID); - data.WriteCString(info.rxLinkSpeed.c_str()); - data.WriteCString(info.txLinkSpeed.c_str()); + data.WriteInt32(info.rxLinkSpeed); + data.WriteInt32(info.txLinkSpeed); data.WriteInt32(info.chload); data.WriteInt32(info.snr); + data.WriteInt32(info.isDataRestricted); + data.WriteCString(info.portalUrl.c_str()); data.WriteInt32((int)info.supplicantState); data.WriteInt32((int)info.detailedState); - int error = Remote()->SendRequest(WIFI_CBK_CMD_CONNECTION_CHANGE, data, reply, option); if (error != ERR_NONE) { WIFI_LOGE("Set Attr(%{public}d) failed,error code is %{public}d", WIFI_CBK_CMD_CONNECTION_CHANGE, error); @@ -91,6 +99,10 @@ void WifiDeviceCallBackProxy::OnWifiRssiChanged(int rssi) MessageOption option; MessageParcel data; MessageParcel reply; + if (!data.WriteInterfaceToken(GetDescriptor())) { + WIFI_LOGE("Write interface token error: %{public}s", __func__); + return; + } data.WriteInt32(0); data.WriteInt32(rssi); int error = Remote()->SendRequest(WIFI_CBK_CMD_RSSI_CHANGE, data, reply, option); @@ -111,6 +123,10 @@ void WifiDeviceCallBackProxy::OnWifiWpsStateChanged(int state, const std::string MessageOption option; MessageParcel data; MessageParcel reply; + if (!data.WriteInterfaceToken(GetDescriptor())) { + WIFI_LOGE("Write interface token error: %{public}s", __func__); + return; + } data.WriteInt32(0); data.WriteInt32(state); data.WriteCString(pinCode.c_str()); @@ -132,6 +148,10 @@ void WifiDeviceCallBackProxy::OnStreamChanged(int direction) MessageOption option; MessageParcel data; MessageParcel reply; + if (!data.WriteInterfaceToken(GetDescriptor())) { + WIFI_LOGE("Write interface token error: %{public}s", __func__); + return; + } data.WriteInt32(0); data.WriteInt32(direction); int error = Remote()->SendRequest(WIFI_CBK_CMD_STREAM_DIRECTION, data, reply, option); @@ -145,5 +165,29 @@ void WifiDeviceCallBackProxy::OnStreamChanged(int direction) } return; } + +void WifiDeviceCallBackProxy::OnDeviceConfigChanged(ConfigChange value) +{ + WIFI_LOGD("WifiDeviceCallBackProxy::OnDeviceConfigChanged"); + MessageOption option; + MessageParcel data; + MessageParcel reply; + if (!data.WriteInterfaceToken(GetDescriptor())) { + WIFI_LOGE("Write interface token error: %{public}s", __func__); + return; + } + data.WriteInt32(0); + data.WriteInt32((int)value); + int error = Remote()->SendRequest(WIFI_CBK_CMD_DEVICE_CONFIG_CHANGE, data, reply, option); + if (error != ERR_NONE) { + WIFI_LOGE("Set Attr(%{public}d) failed,error code is %{public}d", WIFI_CBK_CMD_DEVICE_CONFIG_CHANGE, error); + return; + } + int exception = reply.ReadInt32(); + if (exception) { + WIFI_LOGE("notify wifi device config changed failed!"); + } + return; +} } // namespace Wifi } // namespace OHOS \ No newline at end of file diff --git a/services/wifi_standard/wifi_framework/wifi_manage/wifi_device_callback_proxy.h b/wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_device_callback_proxy.h similarity index 79% rename from services/wifi_standard/wifi_framework/wifi_manage/wifi_device_callback_proxy.h rename to wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_device_callback_proxy.h index 6f16006be88f643a0d9115c61030fd0e9a3adcb9..094967236ce8e5289dfa8c7a0c3497c758f72623 100644 --- a/services/wifi_standard/wifi_framework/wifi_manage/wifi_device_callback_proxy.h +++ b/wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_device_callback_proxy.h @@ -16,16 +16,27 @@ #define OHOS_WIFI_DEVICE_CALLBACK_PROXY_H #include "i_wifi_device_callback.h" +#ifdef OHOS_ARCH_LITE +#include "serializer.h" +#else #include "iremote_proxy.h" +#endif #include "wifi_msg.h" namespace OHOS { namespace Wifi { +#ifdef OHOS_ARCH_LITE +class WifiDeviceCallBackProxy : public IWifiDeviceCallBack { +public: + explicit WifiDeviceCallBackProxy(SvcIdentity *sid); + virtual ~WifiDeviceCallBackProxy(); +#else class WifiDeviceCallBackProxy : public IRemoteProxy { public: explicit WifiDeviceCallBackProxy(const sptr &remote); virtual ~WifiDeviceCallBackProxy() {} +#endif /** * @Description Deal wifi state change message @@ -64,9 +75,21 @@ public: */ void OnStreamChanged(int direction) override; + /** + * @Description Deal device config change message + * + * @param ConfigChange - change type of config + */ + void OnDeviceConfigChanged(ConfigChange value) override; + private: +#ifdef OHOS_ARCH_LITE + SvcIdentity sid_; + static const int DEFAULT_IPC_SIZE = 256; +#else static inline BrokerDelegator g_delegator; +#endif }; } // namespace Wifi } // namespace OHOS -#endif \ No newline at end of file +#endif diff --git a/wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_device_callback_proxy_lite.cpp b/wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_device_callback_proxy_lite.cpp new file mode 100644 index 0000000000000000000000000000000000000000..113afa3b27ffdbd656cddb3bd41407e54ddc1f31 --- /dev/null +++ b/wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_device_callback_proxy_lite.cpp @@ -0,0 +1,169 @@ +/* + * Copyright (C) 2022 Huawei Device Co., Ltd. + * 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 "wifi_device_callback_proxy.h" +#include "define.h" +#include "ipc_skeleton.h" +#include "rpc_errno.h" +#include "wifi_logger.h" + +DEFINE_WIFILOG_LABEL("WifiDeviceCallBackProxy"); + +namespace OHOS { +namespace Wifi { +WifiDeviceCallBackProxy::WifiDeviceCallBackProxy(SvcIdentity *sid) : sid_(*sid) +{} + +WifiDeviceCallBackProxy::~WifiDeviceCallBackProxy() +{ + ReleaseSvc(sid_); +} + +void WifiDeviceCallBackProxy::OnWifiStateChanged(int state) +{ + WIFI_LOGD("WifiDeviceCallBackProxy::OnWifiStateChanged"); + IpcIo data; + uint8_t buff[DEFAULT_IPC_SIZE]; + IpcIoInit(&data, buff, DEFAULT_IPC_SIZE, 0); + (void)WriteInt32(&data, 0); + (void)WriteInt32(&data, state); + + IpcIo reply; + MessageOption option; + MessageOptionInit(&option); + option.flags = TF_OP_ASYNC; + int ret = SendRequest(sid_, WIFI_CBK_CMD_STATE_CHANGE, &data, &reply, option, nullptr); + if (ret != ERR_NONE) { + WIFI_LOGE("Set Attr(%{public}d) failed,error code is %{public}d", WIFI_CBK_CMD_STATE_CHANGE, ret); + } +} + +void WifiDeviceCallBackProxy::OnWifiConnectionChanged(int state, const WifiLinkedInfo &info) +{ + WIFI_LOGD("WifiDeviceCallBackProxy::OnWifiConnectionChanged"); + IpcIo data; + constexpr int IPC_DATA_SIZE = 1024; + uint8_t buff[IPC_DATA_SIZE]; + IpcIoInit(&data, buff, IPC_DATA_SIZE, 0); + (void)WriteInt32(&data, 0); + (void)WriteInt32(&data, state); + (void)WriteInt32(&data, info.networkId); + (void)WriteString(&data, info.ssid.c_str()); + (void)WriteString(&data, info.bssid.c_str()); + (void)WriteInt32(&data, info.rssi); + (void)WriteInt32(&data, info.band); + (void)WriteInt32(&data, info.frequency); + (void)WriteInt32(&data, info.linkSpeed); + (void)WriteString(&data, info.macAddress.c_str()); + (void)WriteUint32(&data, info.ipAddress); + (void)WriteInt32(&data, (int)info.connState); + (void)WriteBool(&data, info.ifHiddenSSID); + (void)WriteInt32(&data, info.rxLinkSpeed); + (void)WriteInt32(&data, info.txLinkSpeed); + (void)WriteInt32(&data, info.chload); + (void)WriteInt32(&data, info.snr); + (void)WriteInt32(&data, info.isDataRestricted); + (void)WriteString(&data, info.portalUrl.c_str()); + (void)WriteInt32(&data, (int)info.supplicantState); + (void)WriteInt32(&data, (int)info.detailedState); + + IpcIo reply; + MessageOption option; + MessageOptionInit(&option); + option.flags = TF_OP_ASYNC; + int ret = SendRequest(sid_, WIFI_CBK_CMD_CONNECTION_CHANGE, &data, &reply, option, nullptr); + if (ret != ERR_NONE) { + WIFI_LOGE("Set Attr(%{public}d) failed,error code is %{public}d", WIFI_CBK_CMD_CONNECTION_CHANGE, ret); + } +} + +void WifiDeviceCallBackProxy::OnWifiRssiChanged(int rssi) +{ + WIFI_LOGD("WifiDeviceCallBackProxy::OnWifiRssiChanged"); + IpcIo data; + uint8_t buff[DEFAULT_IPC_SIZE]; + IpcIoInit(&data, buff, DEFAULT_IPC_SIZE, 0); + (void)WriteInt32(&data, 0); + (void)WriteInt32(&data, rssi); + + IpcIo reply; + MessageOption option; + MessageOptionInit(&option); + option.flags = TF_OP_ASYNC; + int ret = SendRequest(sid_, WIFI_CBK_CMD_RSSI_CHANGE, &data, &reply, option, nullptr); + if (ret != ERR_NONE) { + WIFI_LOGE("Set Attr(%{public}d) failed,error code is %{public}d", WIFI_CBK_CMD_RSSI_CHANGE, ret); + } +} + +void WifiDeviceCallBackProxy::OnWifiWpsStateChanged(int state, const std::string &pinCode) +{ + WIFI_LOGD("WifiDeviceCallBackProxy::OnWifiWpsStateChanged"); + IpcIo data; + uint8_t buff[DEFAULT_IPC_SIZE]; + IpcIoInit(&data, buff, DEFAULT_IPC_SIZE, 0); + (void)WriteInt32(&data, 0); + (void)WriteInt32(&data, state); + (void)WriteString(&data, pinCode.c_str()); + + IpcIo reply; + MessageOption option; + MessageOptionInit(&option); + option.flags = TF_OP_ASYNC; + int ret = SendRequest(sid_, WIFI_CBK_CMD_WPS_STATE_CHANGE, &data, &reply, option, nullptr); + if (ret != ERR_NONE) { + WIFI_LOGE("Set Attr(%{public}d) failed,error code is %{public}d", WIFI_CBK_CMD_WPS_STATE_CHANGE, ret); + } +} + +void WifiDeviceCallBackProxy::OnStreamChanged(int direction) +{ + WIFI_LOGD("WifiDeviceCallBackProxy::OnStreamChanged"); + IpcIo data; + uint8_t buff[DEFAULT_IPC_SIZE]; + IpcIoInit(&data, buff, DEFAULT_IPC_SIZE, 0); + (void)WriteInt32(&data, 0); + (void)WriteInt32(&data, direction); + + IpcIo reply; + MessageOption option; + MessageOptionInit(&option); + option.flags = TF_OP_ASYNC; + int ret = SendRequest(sid_, WIFI_CBK_CMD_STREAM_DIRECTION, &data, &reply, option, nullptr); + if (ret != ERR_NONE) { + WIFI_LOGE("Set Attr(%{public}d) failed,error code is %{public}d", WIFI_CBK_CMD_STREAM_DIRECTION, ret); + } +} + +void WifiDeviceCallBackProxy::OnDeviceConfigChanged(ConfigChange state) +{ + WIFI_LOGD("WifiDeviceCallBackProxy::OnDeviceConfigChanged"); + IpcIo data; + uint8_t buff[DEFAULT_IPC_SIZE]; + IpcIoInit(&data, buff, DEFAULT_IPC_SIZE, 0); + (void)WriteInt32(&data, 0); + (void)WriteInt32(&data, static_cast(state)); + + IpcIo reply; + MessageOption option; + MessageOptionInit(&option); + option.flags = TF_OP_ASYNC; + int ret = SendRequest(sid_, WIFI_CBK_CMD_DEVICE_CONFIG_CHANGE, &data, &reply, option, nullptr); + if (ret != ERR_NONE) { + WIFI_LOGE("Set Attr(%{public}d) failed,error code is %{public}d", WIFI_CBK_CMD_DEVICE_CONFIG_CHANGE, ret); + } +} +} // namespace Wifi +} // namespace OHOS diff --git a/services/wifi_standard/wifi_framework/wifi_manage/wifi_device_death_recipient.cpp b/wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_device_death_recipient.cpp similarity index 94% rename from services/wifi_standard/wifi_framework/wifi_manage/wifi_device_death_recipient.cpp rename to wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_device_death_recipient.cpp index 15400dcb1342dd25483aa4874bc606b3b6b61859..d013552970b24d85d3095e5a99b79bddc7c87c86 100644 --- a/services/wifi_standard/wifi_framework/wifi_manage/wifi_device_death_recipient.cpp +++ b/wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_device_death_recipient.cpp @@ -21,7 +21,7 @@ namespace OHOS { namespace Wifi { void WifiDeviceDeathRecipient::OnRemoteDied(const wptr& remoteObject) { - WIFI_LOGD("WifiDeviceDeathRecipient::OnRemoteDied!"); + WIFI_LOGW("WifiDeviceDeathRecipient::OnRemoteDied!"); WifiInternalEventDispatcher::GetInstance().RemoveStaCallback(remoteObject.promote()); } } // namespace Wifi diff --git a/services/wifi_standard/wifi_framework/wifi_manage/wifi_device_death_recipient.h b/wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_device_death_recipient.h similarity index 100% rename from services/wifi_standard/wifi_framework/wifi_manage/wifi_device_death_recipient.h rename to wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_device_death_recipient.h diff --git a/wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_device_feature_lite.cpp b/wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_device_feature_lite.cpp new file mode 100644 index 0000000000000000000000000000000000000000..1086030bac7e8ca76ad83a8414f5d15199697897 --- /dev/null +++ b/wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_device_feature_lite.cpp @@ -0,0 +1,112 @@ +/* + * Copyright (C) 2022 Huawei Device Co., Ltd. + * 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 "iproxy_server.h" +#include "ohos_errno.h" +#include "ohos_init.h" +#include "samgr_lite.h" +#include "service.h" +#include "wifi_device_service_impl.h" +#include "wifi_log.h" +#include "wifi_ipc_lite_adapter.h" + +using namespace OHOS::Wifi; + +static std::shared_ptr g_devServiceImpl = WifiDeviceServiceImpl::GetInstance(); + +typedef struct WifiDeviceApi { + INHERIT_SERVER_IPROXY; +} WifiDeviceApi; + +typedef struct WifiDeviceFeature { + INHERIT_FEATURE; + INHERIT_IUNKNOWNENTRY(WifiDeviceApi); + Identity identity; + Service *parent; +} WifiDeviceFeature; + +static const char *GetName(Feature *feature) +{ + return WIFI_FEATURE_DEVICE; +} + +static void OnInitialize(Feature *feature, Service *parent, Identity identity) +{ + if (feature != NULL) { + WifiDeviceFeature *deviceFeature = (WifiDeviceFeature *)feature; + deviceFeature->identity = identity; + deviceFeature->parent = parent; + } + if (g_devServiceImpl != NULL) { + g_devServiceImpl->OnStart(); + } +} + +static void OnStop(Feature *feature, Identity identity) +{ + if (g_devServiceImpl != NULL) { + g_devServiceImpl->OnStop(); + } + if (feature != NULL) { + WifiDeviceFeature *deviceFeature = (WifiDeviceFeature *)feature; + deviceFeature->identity.queueId = NULL; + deviceFeature->identity.featureId = -1; + deviceFeature->identity.serviceId = -1; + } +} + +static BOOL OnMessage(Feature *feature, Request *request) +{ + return TRUE; +} + +static int Invoke(IServerProxy *proxy, int funcId, void *origin, IpcIo *req, IpcIo *reply) +{ + LOGI("[WifiDeviceFeature] begin to call Invoke, funcId is %{public}d", funcId); + if (g_devServiceImpl != NULL) { + return g_devServiceImpl->OnRemoteRequest(funcId, req, reply); + } + return EC_FAILURE; +} + +static WifiDeviceFeature g_devFeature = { + .GetName = GetName, + .OnInitialize = OnInitialize, + .OnStop = OnStop, + .OnMessage = OnMessage, + SERVER_IPROXY_IMPL_BEGIN, + .Invoke = Invoke, + IPROXY_END, + .identity = {-1, -1, NULL}, +}; + +static void Init(void) +{ + LOGI("[WifiDeviceFeature] Init start."); + BOOL ret = SAMGR_GetInstance()->RegisterFeature(WIFI_SERVICE_LITE, (Feature *)&g_devFeature); + if (ret == FALSE) { + LOGE("[WifiDeviceFeature] register feature fail."); + return; + } + ret = SAMGR_GetInstance()->RegisterFeatureApi(WIFI_SERVICE_LITE, + WIFI_FEATURE_DEVICE, GET_IUNKNOWN(g_devFeature)); + if (ret == FALSE) { + LOGE("[WifiDeviceFeature] register feature api fail."); + } +} +SYSEX_FEATURE_INIT(Init); diff --git a/services/wifi_standard/wifi_framework/wifi_manage/wifi_device_service_impl.cpp b/wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_device_service_impl.cpp similarity index 40% rename from services/wifi_standard/wifi_framework/wifi_manage/wifi_device_service_impl.cpp rename to wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_device_service_impl.cpp index f6c8b526049a8ba472c7a486a2aa1d23ed614d52..d40a1cf1f490e10216170be8f263d86ed96402c1 100644 --- a/services/wifi_standard/wifi_framework/wifi_manage/wifi_device_service_impl.cpp +++ b/wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_device_service_impl.cpp @@ -1,5 +1,5 @@ /* - * Copyright (C) 2021 Huawei Device Co., Ltd. + * Copyright (C) 2021-2022 Huawei Device Co., Ltd. * 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 @@ -14,30 +14,56 @@ */ #include "wifi_device_service_impl.h" +#include +#include #include +#ifndef OHOS_ARCH_LITE +#include +#endif #include "wifi_permission_utils.h" #include "wifi_internal_msg.h" #include "wifi_auth_center.h" #include "wifi_config_center.h" +#ifdef OHOS_ARCH_LITE +#include "wifi_internal_event_dispatcher_lite.h" +#else #include "wifi_internal_event_dispatcher.h" +#endif #include "wifi_manager.h" #include "wifi_service_manager.h" +#include "wifi_protect_manager.h" #include "wifi_logger.h" #include "define.h" +#include "wifi_dumper.h" +#include "wifi_common_util.h" +#include "wifi_protect_manager.h" DEFINE_WIFILOG_LABEL("WifiDeviceServiceImpl"); namespace OHOS { namespace Wifi { std::mutex WifiDeviceServiceImpl::g_instanceLock; +#ifdef OHOS_ARCH_LITE +std::shared_ptr WifiDeviceServiceImpl::g_instance; +std::shared_ptr WifiDeviceServiceImpl::GetInstance() +#else +const uint32_t TIMEOUT_APP_EVENT = 3000; +const uint32_t TIMEOUT_SCREEN_EVENT = 3000; +const uint32_t TIMEOUT_THERMAL_EVENT = 3000; +using TimeOutCallback = std::function; sptr WifiDeviceServiceImpl::g_instance; const bool REGISTER_RESULT = SystemAbility::MakeAndRegisterAbility(WifiDeviceServiceImpl::GetInstance().GetRefPtr()); sptr WifiDeviceServiceImpl::GetInstance() +#endif { if (g_instance == nullptr) { std::lock_guard autoLock(g_instanceLock); if (g_instance == nullptr) { +#ifdef OHOS_ARCH_LITE + auto service = std::make_shared(); +#else auto service = new (std::nothrow) WifiDeviceServiceImpl; +#endif g_instance = service; } } @@ -45,18 +71,49 @@ sptr WifiDeviceServiceImpl::GetInstance() } WifiDeviceServiceImpl::WifiDeviceServiceImpl() +#ifdef OHOS_ARCH_LITE + : mPublishFlag(false), mState(ServiceRunningState::STATE_NOT_START) + +#else : SystemAbility(WIFI_DEVICE_ABILITY_ID, true), mPublishFlag(false), mState(ServiceRunningState::STATE_NOT_START) +#endif {} WifiDeviceServiceImpl::~WifiDeviceServiceImpl() {} +bool WifiDeviceServiceImpl::IsProcessNeedToRestart() +{ + return (WifiConfigCenter::GetInstance().GetWifiMidState() == WifiOprMidState::RUNNING); +} + +void WifiDeviceServiceImpl::SigHandler(int sig) +{ + WIFI_LOGI("[Sta] Recv SIG: %{public}d\n", sig); + switch (sig) { + case SIGUSR1: + if (IsProcessNeedToRestart()) { + StaServiceCallback cb = WifiManager::GetInstance().GetStaCallback(); + if (cb.OnStaCloseRes != nullptr) { + cb.OnStaCloseRes(OperateResState::CLOSE_WIFI_SUCCEED); + } + WIFI_LOGE("[Sta] --------------Abort process to restart!!!--------------\n"); + abort(); + } + break; + + default: + break; + } +} + void WifiDeviceServiceImpl::OnStart() { if (mState == ServiceRunningState::STATE_RUNNING) { - WIFI_LOGD("Service has already started."); + WIFI_LOGW("Service has already started."); return; } + (void)signal(SIGUSR1, SigHandler); if (!Init()) { WIFI_LOGE("Failed to init service"); OnStop(); @@ -65,19 +122,76 @@ void WifiDeviceServiceImpl::OnStart() mState = ServiceRunningState::STATE_RUNNING; WIFI_LOGI("Start sta service!"); WifiManager::GetInstance(); +#ifndef OHOS_ARCH_LITE + if (eventSubscriber_ == nullptr) { + lpTimer_ = std::make_unique("WifiDeviceServiceImpl"); + TimeOutCallback timeoutCallback = std::bind(&WifiDeviceServiceImpl::RegisterAppRemoved, this); + if (lpTimer_ != nullptr) { + lpTimer_->Setup(); + lpTimer_->Register(timeoutCallback, TIMEOUT_APP_EVENT, true); + } else { + WIFI_LOGE("lpTimer_ is nullptr!"); + } + } + + if (screenEventSubscriber_ == nullptr) { + lpScreenTimer_ = std::make_unique("WifiDeviceServiceImpl"); + TimeOutCallback timeoutCallback = std::bind(&WifiDeviceServiceImpl::RegisterScreenEvent, this); + if (lpScreenTimer_ != nullptr) { + lpScreenTimer_->Setup(); + lpScreenTimer_->Register(timeoutCallback, TIMEOUT_SCREEN_EVENT, true); + } else { + WIFI_LOGE("lpScreenTimer_ is nullptr"); + } + } + + if (thermalLevelSubscriber_ == nullptr) { + lpThermalTimer_ = std::make_unique("WifiDeviceServiceImpl"); + TimeOutCallback timeoutCallback = std::bind(&WifiDeviceServiceImpl::RegisterThermalLevel, this); + lpThermalTimer_->Setup(); + lpThermalTimer_->Register(timeoutCallback, TIMEOUT_THERMAL_EVENT, true); + } +#endif } void WifiDeviceServiceImpl::OnStop() { mState = ServiceRunningState::STATE_NOT_START; mPublishFlag = false; +#ifndef OHOS_ARCH_LITE + if (eventSubscriber_ != nullptr) { + UnRegisterAppRemoved(); + } + if (lpTimer_ != nullptr) { + lpTimer_->Shutdown(false); + lpTimer_ = nullptr; + } + if (screenEventSubscriber_ != nullptr) { + UnRegisterScreenEvent(); + } + if (lpScreenTimer_ != nullptr) { + lpScreenTimer_->Shutdown(false); + lpScreenTimer_ = nullptr; + } + if (thermalLevelSubscriber_ != nullptr) { + UnRegisterThermalLevel(); + } + if (lpThermalTimer_ != nullptr) { + lpThermalTimer_->Shutdown(false); + lpThermalTimer_ = nullptr; + } +#endif WIFI_LOGI("Stop sta service!"); } bool WifiDeviceServiceImpl::Init() { if (!mPublishFlag) { +#ifdef OHOS_ARCH_LITE + bool ret = true; +#else bool ret = Publish(WifiDeviceServiceImpl::GetInstance()); +#endif if (!ret) { WIFI_LOGE("Failed to publish sta service!"); return false; @@ -104,15 +218,23 @@ ErrCode WifiDeviceServiceImpl::EnableWifi() } } +#ifdef FEATURE_AP_SUPPORT + curState = WifiConfigCenter::GetInstance().GetApMidState(0); + if (curState != WifiOprMidState::CLOSED) { + WIFI_LOGW("current ap state is %{public}d, please close SoftAp first!", + static_cast(curState)); + return WIFI_OPT_NOT_SUPPORTED; + } +#endif + if (!WifiConfigCenter::GetInstance().SetWifiMidState(curState, WifiOprMidState::OPENING)) { - WIFI_LOGI("set wifi mid state opening failed! may be other activity has been operated"); + WIFI_LOGI("set wifi mid state opening failed!"); return WIFI_OPT_OPEN_SUCC_WHEN_OPENED; } errCode = WIFI_OPT_FAILED; do { if (WifiServiceManager::GetInstance().CheckAndEnforceService(WIFI_SERVICE_STA) < 0) { - WIFI_LOGE("Load %{public}s service failed!", WIFI_SERVICE_STA); break; } IStaService *pService = WifiServiceManager::GetInstance().GetStaServiceInst(); @@ -138,7 +260,15 @@ ErrCode WifiDeviceServiceImpl::EnableWifi() WifiServiceManager::GetInstance().UnloadService(WIFI_SERVICE_STA); return errCode; } +#ifdef FEATURE_P2P_SUPPORT + sptr p2pService = WifiP2pServiceImpl::GetInstance(); + if (p2pService != nullptr && p2pService->EnableP2p() != WIFI_OPT_SUCCESS) { + // only record to log + WIFI_LOGE("Enable P2p failed!"); + } +#endif + WifiSettings::GetInstance().SyncWifiConfig(); return WIFI_OPT_SUCCESS; } @@ -149,6 +279,11 @@ ErrCode WifiDeviceServiceImpl::DisableWifi() return WIFI_OPT_PERMISSION_DENIED; } + if (WifiPermissionUtils::VerifyWifiConnectionPermission() == PERMISSION_DENIED) { + WIFI_LOGE("DisableWifi:VerifyWifiConnectionPermission PERMISSION_DENIED!"); + return WIFI_OPT_PERMISSION_DENIED; + } + WifiOprMidState curState = WifiConfigCenter::GetInstance().GetWifiMidState(); if (curState != WifiOprMidState::RUNNING) { WIFI_LOGI("current wifi state is %{public}d", static_cast(curState)); @@ -158,6 +293,15 @@ ErrCode WifiDeviceServiceImpl::DisableWifi() return WIFI_OPT_CLOSE_SUCC_WHEN_CLOSED; } } + +#ifdef FEATURE_P2P_SUPPORT + sptr p2pService = WifiP2pServiceImpl::GetInstance(); + if (p2pService != nullptr && p2pService->DisableP2p() != WIFI_OPT_SUCCESS) { + WIFI_LOGE("Disable P2p failed!"); + return WIFI_OPT_FAILED; + } +#endif + if (!WifiConfigCenter::GetInstance().SetWifiMidState(curState, WifiOprMidState::CLOSING)) { WIFI_LOGI("set wifi mid state opening failed! may be other activity has been operated"); return WIFI_OPT_CLOSE_SUCC_WHEN_CLOSED; @@ -177,13 +321,212 @@ ErrCode WifiDeviceServiceImpl::DisableWifi() return ret; } -ErrCode WifiDeviceServiceImpl::AddDeviceConfig(const WifiDeviceConfig &config, int &result) +ErrCode WifiDeviceServiceImpl::InitWifiProtect(const WifiProtectType &protectType, const std::string &protectName) +{ + /* refer to WifiProtectManager::GetInstance().InitWifiProtect, DO NOT support now! */ + return WIFI_OPT_SUCCESS; +} + +ErrCode WifiDeviceServiceImpl::GetWifiProtectRef(const WifiProtectMode &protectMode, const std::string &protectName) +{ + /* refer to WifiProtectManager::GetInstance().GetWifiProtect, DO NOT support now! */ + return WIFI_OPT_SUCCESS; +} + +ErrCode WifiDeviceServiceImpl::PutWifiProtectRef(const std::string &protectName) +{ + /* refer to WifiProtectManager::GetInstance().PutWifiProtect, DO NOT support now! */ + return WIFI_OPT_SUCCESS; +} + +bool WifiDeviceServiceImpl::CheckConfigEap(const WifiDeviceConfig &config) +{ + if (config.keyMgmt != KEY_MGMT_EAP) { + WIFI_LOGE("CheckConfigEap: keyMgmt is not EAP!"); + return false; + } + if (config.wifiEapConfig.eap == EAP_METHOD_TLS) { + if (config.wifiEapConfig.identity.empty() || + config.wifiEapConfig.clientCert.empty() || + config.wifiEapConfig.privateKey.empty()) { + WIFI_LOGE("CheckConfigEap: with invalid TLS params!"); + return false; + } + return true; + } else if (config.wifiEapConfig.eap == EAP_METHOD_PEAP) { + if (config.wifiEapConfig.identity.empty() || config.wifiEapConfig.password.empty()) { + WIFI_LOGE("CheckConfigEap: with invalid PEAP params!"); + return false; + } + return true; + } else { + WIFI_LOGE("EAP:%{public}s unsupported!", config.wifiEapConfig.eap.c_str()); + } + return false; +} + +bool WifiDeviceServiceImpl::CheckConfigPwd(const WifiDeviceConfig &config) +{ + if ((config.ssid.length() <= 0) || (config.keyMgmt.length()) <= 0) { + WIFI_LOGE("CheckConfigPwd: invalid ssid or keyMgmt!"); + return false; + } + + WIFI_LOGI("CheckConfigPwd: keyMgmt = %{public}s!", config.keyMgmt.c_str()); + if (config.keyMgmt == KEY_MGMT_EAP) { + return CheckConfigEap(config); + } + + if ((config.keyMgmt != KEY_MGMT_NONE && config.keyMgmt != KEY_MGMT_WEP) && + config.preSharedKey.empty()) { + WIFI_LOGE("CheckConfigPwd: preSharedKey is empty!"); + return false; + } + + int len = config.preSharedKey.length(); + bool isAllHex = std::all_of(config.preSharedKey.begin(), config.preSharedKey.end(), isxdigit); + WIFI_LOGI("CheckConfigPwd, ssid: %{public}s, psk len: %{public}d", SsidAnonymize(config.ssid).c_str(), len); + if (config.keyMgmt == KEY_MGMT_WEP) { + for (int i = 0; i != WEPKEYS_SIZE; ++i) { + if (!config.wepKeys[i].empty()) { // wep + int wepLen = config.wepKeys[i].size(); + if (wepLen == WEP_KEY_LEN1 || wepLen == WEP_KEY_LEN2 || wepLen == WEP_KEY_LEN3) { + return true; + } + constexpr int MULTIPLE_HEXT_TO_ASCII = 2; + if (wepLen == (WEP_KEY_LEN1 * MULTIPLE_HEXT_TO_ASCII) || + wepLen == (WEP_KEY_LEN2 * MULTIPLE_HEXT_TO_ASCII) || + wepLen == (WEP_KEY_LEN3 * MULTIPLE_HEXT_TO_ASCII)) { + return isAllHex; + } + WIFI_LOGE("CheckConfigPwd: invalid wepLen: %{public}d!", wepLen); + return false; + } + } + return true; + } + if (config.keyMgmt == KEY_MGMT_NONE) { + return config.preSharedKey.empty(); + } + int minLen = config.keyMgmt == KEY_MGMT_SAE ? MIN_SAE_LEN : MIN_PSK_LEN; + int maxLen = isAllHex ? MAX_HEX_LEN : MAX_PRESHAREDKEY_LEN; + if (len < minLen || len > maxLen) { + WIFI_LOGE("CheckConfigPwd: preSharedKey length error: %{public}d", len); + return false; + } + return true; +} + +ErrCode WifiDeviceServiceImpl::CheckCallingUid(int &uid) +{ +#ifndef OHOS_ARCH_LITE + uid = GetCallingUid(); + if (!IsForegroundApp(uid)) { + return WIFI_OPT_INVALID_PARAM; + } + return WIFI_OPT_SUCCESS; +#else + return WIFI_OPT_NOT_SUPPORTED; +#endif +} + +ErrCode WifiDeviceServiceImpl::CheckRemoveCandidateConfig(void) +{ + if (WifiPermissionUtils::VerifySetWifiInfoPermission() == PERMISSION_DENIED) { + WIFI_LOGE("CheckRemoveCandidateConfig:VerifySetWifiInfoPermission PERMISSION_DENIED!"); + return WIFI_OPT_PERMISSION_DENIED; + } + + if (!IsStaServiceRunning()) { + WIFI_LOGE("CheckRemoveCandidateConfig:IsStaServiceRunning not running!"); + return WIFI_OPT_STA_NOT_OPENED; + } + + return WIFI_OPT_SUCCESS; +} + +ErrCode WifiDeviceServiceImpl::RemoveCandidateConfig(const WifiDeviceConfig &config) +{ + ErrCode ret = CheckRemoveCandidateConfig(); + if (ret != WIFI_OPT_SUCCESS) { + return ret; + } + /* check the caller's uid */ + int uid = 0; + if (CheckCallingUid(uid) != WIFI_OPT_SUCCESS) { + WIFI_LOGE("CheckCallingUid failed!"); + return WIFI_OPT_INVALID_PARAM; + } + IStaService *pService = WifiServiceManager::GetInstance().GetStaServiceInst(); + if (pService == nullptr) { + WIFI_LOGE("pService is nullptr!"); + return WIFI_OPT_STA_NOT_OPENED; + } + /* get all candidate configs */ + std::vector configs; + if (WifiConfigCenter::GetInstance().GetCandidateConfigs(uid, configs) != 0) { + WIFI_LOGE("NOT find the caller's configs!"); + return WIFI_OPT_INVALID_CONFIG; + } + /* find the networkId of the removed config */ + int networkId = INVALID_NETWORK_ID; + size_t size = configs.size(); + for (size_t i = 0; i < size; i++) { + if (configs[i].ssid == config.ssid) { + networkId = configs[i].networkId; + WIFI_LOGI("find the removed config, networkId:%{public}d!", networkId); + break; + } + } + /* removed the config */ + if (networkId != INVALID_NETWORK_ID) { + return pService->RemoveCandidateConfig(uid, networkId); + } + return WIFI_OPT_INVALID_CONFIG; +} + +ErrCode WifiDeviceServiceImpl::RemoveCandidateConfig(int networkId) +{ + ErrCode ret = CheckRemoveCandidateConfig(); + if (ret != WIFI_OPT_SUCCESS) { + return ret; + } + int uid = 0; + if (CheckCallingUid(uid) != WIFI_OPT_SUCCESS) { + WIFI_LOGE("CheckCallingUid failed!"); + return WIFI_OPT_INVALID_PARAM; + } + IStaService *pService = WifiServiceManager::GetInstance().GetStaServiceInst(); + if (pService == nullptr) { + WIFI_LOGE("pService is nullptr!"); + return WIFI_OPT_STA_NOT_OPENED; + } + if (networkId == INVALID_NETWORK_ID) { + return pService->RemoveAllCandidateConfig(uid); + } else { + return pService->RemoveCandidateConfig(uid, networkId); + } +} + +ErrCode WifiDeviceServiceImpl::AddDeviceConfig(const WifiDeviceConfig &config, int &result, bool isCandidate) { if (WifiPermissionUtils::VerifySetWifiInfoPermission() == PERMISSION_DENIED) { WIFI_LOGE("AddDeviceConfig:VerifySetWifiInfoPermission PERMISSION_DENIED!"); return WIFI_OPT_PERMISSION_DENIED; } + if (!isCandidate) { + if (WifiPermissionUtils::VerifySetWifiConfigPermission() == PERMISSION_DENIED) { + WIFI_LOGE("AddDeviceConfig:VerifySetWifiConfigPermission PERMISSION_DENIED!"); + return WIFI_OPT_PERMISSION_DENIED; + } + } + + if (!CheckConfigPwd(config)) { + WIFI_LOGE("CheckConfigPwd failed!"); + return WIFI_OPT_INVALID_PARAM; + } + if (!IsStaServiceRunning()) { return WIFI_OPT_STA_NOT_OPENED; } @@ -192,6 +535,16 @@ ErrCode WifiDeviceServiceImpl::AddDeviceConfig(const WifiDeviceConfig &config, i if (pService == nullptr) { return WIFI_OPT_STA_NOT_OPENED; } + + if (isCandidate) { + int uid = 0; + if (CheckCallingUid(uid) != WIFI_OPT_SUCCESS) { + WIFI_LOGE("CheckCallingUid failed!"); + return WIFI_OPT_INVALID_PARAM; + } + return pService->AddCandidateConfig(uid, config, result); + } + int retNetworkId = pService->AddDeviceConfig(config); if (retNetworkId < 0) { return WIFI_OPT_FAILED; @@ -200,6 +553,35 @@ ErrCode WifiDeviceServiceImpl::AddDeviceConfig(const WifiDeviceConfig &config, i return WIFI_OPT_SUCCESS; } +ErrCode WifiDeviceServiceImpl::UpdateDeviceConfig(const WifiDeviceConfig &config, int &result) +{ + if (WifiPermissionUtils::VerifySetWifiInfoPermission() == PERMISSION_DENIED) { + WIFI_LOGE("UpdateDeviceConfig:VerifySetWifiInfoPermission PERMISSION_DENIED!"); + return WIFI_OPT_PERMISSION_DENIED; + } + + if (WifiPermissionUtils::VerifySetWifiConfigPermission() == PERMISSION_DENIED) { + WIFI_LOGE("UpdateDeviceConfig:VerifySetWifiConfigPermission PERMISSION_DENIED!"); + return WIFI_OPT_PERMISSION_DENIED; + } + + if (!IsStaServiceRunning()) { + return WIFI_OPT_STA_NOT_OPENED; + } + + IStaService *pService = WifiServiceManager::GetInstance().GetStaServiceInst(); + if (pService == nullptr) { + return WIFI_OPT_STA_NOT_OPENED; + } + + int retNetworkId = pService->UpdateDeviceConfig(config); + if (retNetworkId <= INVALID_NETWORK_ID) { + return WIFI_OPT_FAILED; + } + result = retNetworkId; + return WIFI_OPT_SUCCESS; +} + ErrCode WifiDeviceServiceImpl::RemoveDevice(int networkId) { if (WifiPermissionUtils::VerifySetWifiInfoPermission() == PERMISSION_DENIED) { @@ -207,10 +589,19 @@ ErrCode WifiDeviceServiceImpl::RemoveDevice(int networkId) return WIFI_OPT_PERMISSION_DENIED; } + if (WifiPermissionUtils::VerifyWifiConnectionPermission() == PERMISSION_DENIED) { + WIFI_LOGE("RemoveDevice:VerifyWifiConnectionPermission PERMISSION_DENIED!"); + return WIFI_OPT_PERMISSION_DENIED; + } + if (!IsStaServiceRunning()) { return WIFI_OPT_STA_NOT_OPENED; } + if (networkId < 0) { + return WIFI_OPT_INVALID_PARAM; + } + IStaService *pService = WifiServiceManager::GetInstance().GetStaServiceInst(); if (pService == nullptr) { return WIFI_OPT_STA_NOT_OPENED; @@ -225,6 +616,11 @@ ErrCode WifiDeviceServiceImpl::RemoveAllDevice() return WIFI_OPT_PERMISSION_DENIED; } + if (WifiPermissionUtils::VerifyWifiConnectionPermission() == PERMISSION_DENIED) { + WIFI_LOGE("RemoveAllDevice:VerifyWifiConnectionPermission PERMISSION_DENIED!"); + return WIFI_OPT_PERMISSION_DENIED; + } + if (!IsStaServiceRunning()) { return WIFI_OPT_STA_NOT_OPENED; } @@ -236,14 +632,39 @@ ErrCode WifiDeviceServiceImpl::RemoveAllDevice() return pService->RemoveAllDevice(); } -ErrCode WifiDeviceServiceImpl::GetDeviceConfigs(std::vector &result) +ErrCode WifiDeviceServiceImpl::GetDeviceConfigs(std::vector &result, bool isCandidate) { - if (WifiPermissionUtils::VerifyGetWifiInfoPermission() == PERMISSION_DENIED) { + if (WifiPermissionUtils::VerifyGetWifiInfoInternalPermission() == PERMISSION_DENIED) { WIFI_LOGE("GetDeviceConfigs:VerifyGetWifiInfoPermission() PERMISSION_DENIED!"); - return WIFI_OPT_PERMISSION_DENIED; + + if (WifiPermissionUtils::VerifyGetWifiInfoPermission() == PERMISSION_DENIED) { + WIFI_LOGE("GetDeviceConfigs:VerifyGetWifiInfoPermission() PERMISSION_DENIED!"); + return WIFI_OPT_PERMISSION_DENIED; + } + + if (WifiPermissionUtils::VerifyGetScanInfosPermission() == PERMISSION_DENIED) { + WIFI_LOGE("GetDeviceConfigs:VerifyGetWifiInfoPermission() PERMISSION_DENIED!"); + return WIFI_OPT_PERMISSION_DENIED; + } + + if (!isCandidate) { + if (WifiPermissionUtils::VerifyGetWifiConfigPermission() == PERMISSION_DENIED) { + WIFI_LOGE("GetDeviceConfigs:VerifyGetWifiInfoPermission() PERMISSION_DENIED!"); + return WIFI_OPT_PERMISSION_DENIED; + } + } } - WifiConfigCenter::GetInstance().GetDeviceConfig(result); + if (isCandidate) { + int uid = 0; + if (CheckCallingUid(uid) != WIFI_OPT_SUCCESS) { + WIFI_LOGE("CheckCallingUid failed!"); + return WIFI_OPT_INVALID_PARAM; + } + WifiConfigCenter::GetInstance().GetCandidateConfigs(uid, result); + } else { + WifiConfigCenter::GetInstance().GetDeviceConfig(result); + } return WIFI_OPT_SUCCESS; } @@ -258,6 +679,10 @@ ErrCode WifiDeviceServiceImpl::EnableDeviceConfig(int networkId, bool attemptEna return WIFI_OPT_STA_NOT_OPENED; } + if (networkId < 0) { + return WIFI_OPT_INVALID_PARAM; + } + IStaService *pService = WifiServiceManager::GetInstance().GetStaServiceInst(); if (pService == nullptr) { return WIFI_OPT_STA_NOT_OPENED; @@ -272,10 +697,19 @@ ErrCode WifiDeviceServiceImpl::DisableDeviceConfig(int networkId) return WIFI_OPT_PERMISSION_DENIED; } + if (WifiPermissionUtils::VerifyWifiConnectionPermission() == PERMISSION_DENIED) { + WIFI_LOGE("DisableDeviceConfig:VerifySetWifiInfoPermission PERMISSION_DENIED!"); + return WIFI_OPT_PERMISSION_DENIED; + } + if (!IsStaServiceRunning()) { return WIFI_OPT_STA_NOT_OPENED; } + if (networkId < 0) { + return WIFI_OPT_INVALID_PARAM; + } + IStaService *pService = WifiServiceManager::GetInstance().GetStaServiceInst(); if (pService == nullptr) { return WIFI_OPT_STA_NOT_OPENED; @@ -283,42 +717,93 @@ ErrCode WifiDeviceServiceImpl::DisableDeviceConfig(int networkId) return pService->DisableDeviceConfig(networkId); } -ErrCode WifiDeviceServiceImpl::ConnectToNetwork(int networkId) +ErrCode WifiDeviceServiceImpl::ConnectToNetwork(int networkId, bool isCandidate) { - if (WifiPermissionUtils::VerifySetWifiInfoPermission() == PERMISSION_DENIED) { - WIFI_LOGE("ConnectToNetwork:VerifySetWifiInfoPermission PERMISSION_DENIED!"); - return WIFI_OPT_PERMISSION_DENIED; + if (isCandidate) { + if (WifiPermissionUtils::VerifySetWifiInfoPermission() == PERMISSION_DENIED) { + WIFI_LOGE("ConnectToCandidateConfig:VerifySetWifiInfoPermission PERMISSION_DENIED!"); + return WIFI_OPT_PERMISSION_DENIED; + } + } else { + if (WifiPermissionUtils::VerifyWifiConnectionPermission() == PERMISSION_DENIED) { + WIFI_LOGE("ConnectToNetwork:VerifyWifiConnectionPermission PERMISSION_DENIED!"); + return WIFI_OPT_PERMISSION_DENIED; + } } if (!IsStaServiceRunning()) { + WIFI_LOGE("ConnectToNetwork: sta service is not running!"); return WIFI_OPT_STA_NOT_OPENED; } + if (networkId < 0) { + WIFI_LOGE("ConnectToNetwork: invalid networkId = %{public}d!", networkId); + return WIFI_OPT_INVALID_PARAM; + } + IStaService *pService = WifiServiceManager::GetInstance().GetStaServiceInst(); if (pService == nullptr) { + WIFI_LOGE("ConnectToNetwork: pService is nullptr!"); return WIFI_OPT_STA_NOT_OPENED; } + + if (isCandidate) { + int uid = 0; + if (CheckCallingUid(uid) != WIFI_OPT_SUCCESS) { + WIFI_LOGE("CheckCallingUid failed!"); + return WIFI_OPT_INVALID_PARAM; + } + return pService->ConnectToCandidateConfig(uid, networkId); + } return pService->ConnectToNetwork(networkId); } ErrCode WifiDeviceServiceImpl::ConnectToDevice(const WifiDeviceConfig &config) { if (WifiPermissionUtils::VerifySetWifiInfoPermission() == PERMISSION_DENIED) { - WIFI_LOGE("ConnectToDevice with config:VerifySetWifiInfoPermission PERMISSION_DENIED!"); + WIFI_LOGE("ConnectToDevice:VerifySetWifiInfoPermission PERMISSION_DENIED!"); + return WIFI_OPT_PERMISSION_DENIED; + } + + if (WifiPermissionUtils::VerifyWifiConnectionPermission() == PERMISSION_DENIED) { + WIFI_LOGE("ConnectToDevice:VerifyWifiConnectionPermission PERMISSION_DENIED!"); + return WIFI_OPT_PERMISSION_DENIED; + } + + if (WifiPermissionUtils::VerifySetWifiConfigPermission() == PERMISSION_DENIED) { + WIFI_LOGE("ConnectToDevice:VerifySetWifiConfigPermission PERMISSION_DENIED!"); return WIFI_OPT_PERMISSION_DENIED; } + if (!CheckConfigPwd(config)) { + WIFI_LOGE("CheckConfigPwd failed!"); + return WIFI_OPT_INVALID_PARAM; + } if (!IsStaServiceRunning()) { + WIFI_LOGE("ConnectToDevice: sta service is not running!"); return WIFI_OPT_STA_NOT_OPENED; } - IStaService *pService = WifiServiceManager::GetInstance().GetStaServiceInst(); if (pService == nullptr) { + WIFI_LOGE("ConnectToNetwork: pService is nullptr!"); return WIFI_OPT_STA_NOT_OPENED; } return pService->ConnectToDevice(config); } +bool WifiDeviceServiceImpl::IsConnected() +{ + WifiLinkedInfo linkedInfo; + + if (WifiPermissionUtils::VerifyGetWifiInfoPermission() == PERMISSION_DENIED) { + WIFI_LOGE("IsConnected:VerifyGetWifiInfoPermission() PERMISSION_DENIED!"); + return WIFI_OPT_PERMISSION_DENIED; + } + + WifiConfigCenter::GetInstance().GetLinkedInfo(linkedInfo); + return linkedInfo.connState == ConnState::CONNECTED; +} + ErrCode WifiDeviceServiceImpl::ReConnect() { if (WifiPermissionUtils::VerifySetWifiInfoPermission() == PERMISSION_DENIED) { @@ -326,25 +811,26 @@ ErrCode WifiDeviceServiceImpl::ReConnect() return WIFI_OPT_PERMISSION_DENIED; } - if (!IsStaServiceRunning()) { - return WIFI_OPT_STA_NOT_OPENED; + if (WifiPermissionUtils::VerifyWifiConnectionPermission() == PERMISSION_DENIED) { + WIFI_LOGE("ReConnect:VerifyWifiConnectionPermission() PERMISSION_DENIED!"); + return WIFI_OPT_PERMISSION_DENIED; } - if (!IsScanServiceRunning()) { - return WIFI_OPT_SCAN_NOT_OPENED; + if (!IsStaServiceRunning()) { + return WIFI_OPT_STA_NOT_OPENED; } - IScanService *pService = WifiServiceManager::GetInstance().GetScanServiceInst(); + IStaService *pService = WifiServiceManager::GetInstance().GetStaServiceInst(); if (pService == nullptr) { - return WIFI_OPT_SCAN_NOT_OPENED; + return WIFI_OPT_STA_NOT_OPENED; } - return pService->Scan(false); + return pService->ReConnect(); } ErrCode WifiDeviceServiceImpl::ReAssociate(void) { - if (WifiPermissionUtils::VerifySetWifiInfoPermission() == PERMISSION_DENIED) { - WIFI_LOGE("ReAssociate:VerifySetWifiInfoPermission() PERMISSION_DENIED!"); + if (WifiPermissionUtils::VerifyWifiConnectionPermission() == PERMISSION_DENIED) { + WIFI_LOGE("ReAssociate:VerifyWifiConnectionPermission() PERMISSION_DENIED!"); return WIFI_OPT_PERMISSION_DENIED; } @@ -366,6 +852,11 @@ ErrCode WifiDeviceServiceImpl::Disconnect(void) return WIFI_OPT_PERMISSION_DENIED; } + if (WifiPermissionUtils::VerifyWifiConnectionPermission() == PERMISSION_DENIED) { + WIFI_LOGE("Disconnect:VerifyWifiConnectionPermission() PERMISSION_DENIED!"); + return WIFI_OPT_PERMISSION_DENIED; + } + if (!IsStaServiceRunning()) { return WIFI_OPT_STA_NOT_OPENED; } @@ -415,6 +906,11 @@ ErrCode WifiDeviceServiceImpl::CancelWps(void) ErrCode WifiDeviceServiceImpl::IsWifiActive(bool &bActive) { + if (WifiPermissionUtils::VerifyGetWifiInfoPermission() == PERMISSION_DENIED) { + WIFI_LOGE("IsWifiActive:VerifyGetWifiInfoPermission() PERMISSION_DENIED!"); + return WIFI_OPT_PERMISSION_DENIED; + } + bActive = IsStaServiceRunning(); return WIFI_OPT_SUCCESS; } @@ -437,17 +933,17 @@ ErrCode WifiDeviceServiceImpl::GetLinkedInfo(WifiLinkedInfo &info) return WIFI_OPT_PERMISSION_DENIED; } + WifiConfigCenter::GetInstance().GetLinkedInfo(info); if (WifiPermissionUtils::VerifyGetWifiLocalMacPermission() == PERMISSION_DENIED) { WIFI_LOGE("GetLinkedInfo:VerifyGetWifiLocalMacPermission() PERMISSION_DENIED!"); - return WIFI_OPT_PERMISSION_DENIED; + /* Clear mac addr */ + info.macAddress = ""; } - if (WifiPermissionUtils::VerifyGetScanInfosPermission() == PERMISSION_DENIED) { - WIFI_LOGE("GetLinkedInfo:VerifyGetScanInfosPermission() PERMISSION_DENIED!"); - return WIFI_OPT_PERMISSION_DENIED; - } - - WifiConfigCenter::GetInstance().GetLinkedInfo(info); + WIFI_LOGI("GetLinkedInfo, networkId=%{public}d, ssid=%{public}s, rssi=%{public}d, frequency=%{public}d", + info.networkId, SsidAnonymize(info.ssid).c_str(), info.rssi, info.frequency); + WIFI_LOGI("GetLinkedInfo, connState=%{public}d, supplicantState=%{public}d, detailedState=%{public}d", + info.connState, info.supplicantState, info.detailedState); return WIFI_OPT_SUCCESS; } @@ -485,8 +981,8 @@ ErrCode WifiDeviceServiceImpl::SetCountryCode(const std::string &countryCode) ErrCode WifiDeviceServiceImpl::GetCountryCode(std::string &countryCode) { - if (WifiPermissionUtils::VerifyWifiConnectionPermission() == PERMISSION_DENIED) { - WIFI_LOGE("GetCountryCode:VerifyWifiConnectionPermission() PERMISSION_DENIED!"); + if (WifiPermissionUtils::VerifyGetWifiInfoPermission() == PERMISSION_DENIED) { + WIFI_LOGE("GetCountryCode:VerifyGetWifiInfoPermission() PERMISSION_DENIED!"); return WIFI_OPT_PERMISSION_DENIED; } @@ -495,7 +991,11 @@ ErrCode WifiDeviceServiceImpl::GetCountryCode(std::string &countryCode) return WIFI_OPT_SUCCESS; } +#ifdef OHOS_ARCH_LITE +ErrCode WifiDeviceServiceImpl::RegisterCallBack(const std::shared_ptr &callback) +#else ErrCode WifiDeviceServiceImpl::RegisterCallBack(const sptr &callback) +#endif { WIFI_LOGI("RegisterCallBack"); if (callback == nullptr) { @@ -554,12 +1054,25 @@ ErrCode WifiDeviceServiceImpl::GetDeviceMacAddress(std::string &result) return WIFI_OPT_SUCCESS; } +bool WifiDeviceServiceImpl::SetLowLatencyMode(bool enabled) +{ + WIFI_LOGI("SetLowLatencyMode"); + /* refer to WifiProtectManager::GetInstance().SetLowLatencyMode, DO NOT support now! */ + return true; +} + ErrCode WifiDeviceServiceImpl::CheckCanEnableWifi(void) { if (WifiPermissionUtils::VerifySetWifiInfoPermission() == PERMISSION_DENIED) { WIFI_LOGE("EnableWifi:VerifySetWifiInfoPermission PERMISSION_DENIED!"); return WIFI_OPT_PERMISSION_DENIED; } + + if (WifiPermissionUtils::VerifyWifiConnectionPermission() == PERMISSION_DENIED) { + WIFI_LOGE("EnableWifi:VerifyWifiConnectionPermission PERMISSION_DENIED!"); + return WIFI_OPT_PERMISSION_DENIED; + } + /** * when airplane mode opened, if the config "can_use_sta_when_airplanemode" * opened, then can open sta; other, return forbid. @@ -594,7 +1107,7 @@ bool WifiDeviceServiceImpl::IsStaServiceRunning() { WifiOprMidState curState = WifiConfigCenter::GetInstance().GetWifiMidState(); if (curState != WifiOprMidState::RUNNING) { - WIFI_LOGD("current wifi state is %{public}d", static_cast(curState)); + WIFI_LOGW("current wifi state is %{public}d", static_cast(curState)); return false; } return true; @@ -604,10 +1117,228 @@ bool WifiDeviceServiceImpl::IsScanServiceRunning() { WifiOprMidState curState = WifiConfigCenter::GetInstance().GetScanMidState(); if (curState != WifiOprMidState::RUNNING) { - WIFI_LOGD("scan service does not started!"); + WIFI_LOGW("scan service does not started!"); return false; } return true; } + +void WifiDeviceServiceImpl::SaBasicDump(std::string& result) +{ + WifiDeviceServiceImpl impl; + bool isActive = impl.IsStaServiceRunning(); + result.append("WiFi active state: "); + std::string strActive = isActive ? "activated" : "inactive"; + result += strActive + "\n\n"; + + WifiLinkedInfo linkedInfo; + WifiConfigCenter::GetInstance().GetLinkedInfo(linkedInfo); + bool isConnected = linkedInfo.connState == ConnState::CONNECTED; + result.append("WiFi connection status: "); + std::string strIsConnected = isConnected ? "connected" : "not connected"; + result += strIsConnected + "\n"; + if (isConnected) { + std::stringstream ss; + ss << " Connection.ssid: " << linkedInfo.ssid << "\n"; + ss << " Connection.bssid: " << MacAnonymize(linkedInfo.bssid) << "\n"; + ss << " Connection.rssi: " << linkedInfo.rssi << "\n"; + + enum {BAND_2GHZ = 1, BAND_5GHZ = 2, BAND_ANY = 3}; + auto funcStrBand = [](int band) { + std::string retStr; + switch (band) { + case BAND_2GHZ: + retStr = "2.4GHz"; + break; + case BAND_5GHZ: + retStr = "5GHz"; + break; + case BAND_ANY: + retStr = "dual-mode frequency band"; + break; + default: + retStr = "unknown band"; + } + return retStr; + }; + ss << " Connection.band: " << funcStrBand(linkedInfo.band) << "\n"; + ss << " Connection.frequency: " << linkedInfo.frequency << "\n"; + ss << " Connection.linkSpeed: " << linkedInfo.linkSpeed << "\n"; + ss << " Connection.macAddress: " << MacAnonymize(linkedInfo.macAddress) << "\n"; + ss << " Connection.isHiddenSSID: " << (linkedInfo.ifHiddenSSID ? "true" : "false") << "\n"; + + int level = WifiConfigCenter::GetInstance().GetSignalLevel(linkedInfo.rssi, linkedInfo.band); + ss << " Connection.signalLevel: " << level << "\n"; + result += ss.str(); + } + result += "\n"; + + std::string cc; + WifiConfigCenter::GetInstance().GetCountryCode(cc); + result.append("Country Code: ").append(cc); + result += "\n"; +} + +#ifndef OHOS_ARCH_LITE +int32_t WifiDeviceServiceImpl::Dump(int32_t fd, const std::vector& args) +{ + WIFI_LOGI("Enter sta dump func."); + std::vector vecArgs; + std::transform(args.begin(), args.end(), std::back_inserter(vecArgs), [](const std::u16string &arg) { + return Str16ToStr8(arg); + }); + + WifiDumper dumper; + std::string result; + dumper.DeviceDump(SaBasicDump, vecArgs, result); + if (!SaveStringToFd(fd, result)) { + WIFI_LOGE("WiFi device save string to fd failed."); + return ERR_OK; + } + return ERR_OK; +} + +void WifiDeviceServiceImpl::RegisterAppRemoved() +{ + OHOS::EventFwk::MatchingSkills matchingSkills; + matchingSkills.AddEvent(OHOS::EventFwk::CommonEventSupport::COMMON_EVENT_PACKAGE_REMOVED); + EventFwk::CommonEventSubscribeInfo subscriberInfo(matchingSkills); + eventSubscriber_ = std::make_shared(subscriberInfo); + if (!EventFwk::CommonEventManager::SubscribeCommonEvent(eventSubscriber_)) { + WIFI_LOGE("AppEvent SubscribeCommonEvent() failed"); + } else { + WIFI_LOGI("AppEvent SubscribeCommonEvent() OK"); + } +} + +void WifiDeviceServiceImpl::UnRegisterAppRemoved() +{ + if (!EventFwk::CommonEventManager::UnSubscribeCommonEvent(eventSubscriber_)) { + WIFI_LOGE("AppEvent UnSubscribeCommonEvent() failed"); + } else { + WIFI_LOGI("AppEvent UnSubscribeCommonEvent() OK"); + } + eventSubscriber_ = nullptr; +} + +void WifiDeviceServiceImpl::RegisterScreenEvent() +{ + OHOS::EventFwk::MatchingSkills matchingSkills; + matchingSkills.AddEvent(OHOS::EventFwk::CommonEventSupport::COMMON_EVENT_SCREEN_ON); + matchingSkills.AddEvent(OHOS::EventFwk::CommonEventSupport::COMMON_EVENT_SCREEN_OFF); + EventFwk::CommonEventSubscribeInfo subscriberInfo(matchingSkills); + screenEventSubscriber_ = std::make_shared(subscriberInfo); + if (!EventFwk::CommonEventManager::SubscribeCommonEvent(screenEventSubscriber_)) { + WIFI_LOGE("ScreenEvent SubscribeCommonEvent() failed"); + } else { + WIFI_LOGI("ScreenEvent SubscribeCommonEvent() OK"); + } +} + +void WifiDeviceServiceImpl::UnRegisterScreenEvent() +{ + if (!EventFwk::CommonEventManager::UnSubscribeCommonEvent(screenEventSubscriber_)) { + WIFI_LOGE("ScreenEvent UnSubscribeCommonEvent() failed"); + } else { + WIFI_LOGI("ScreenEvent UnSubscribeCommonEvent() OK"); + } + screenEventSubscriber_ = nullptr; +} + +void WifiDeviceServiceImpl::RegisterThermalLevel() +{ + OHOS::EventFwk::MatchingSkills matchingSkills; + matchingSkills.AddEvent(OHOS::EventFwk::CommonEventSupport::COMMON_EVENT_THERMAL_LEVEL_CHANGED); + EventFwk::CommonEventSubscribeInfo subscriberInfo(matchingSkills); + thermalLevelSubscriber_ = std::make_shared(subscriberInfo); + if (!EventFwk::CommonEventManager::SubscribeCommonEvent(thermalLevelSubscriber_)) { + WIFI_LOGE("THERMAL_LEVEL_CHANGED SubscribeCommonEvent() failed"); + } else { + WIFI_LOGI("THERMAL_LEVEL_CHANGED SubscribeCommonEvent() OK"); + } +} + +void WifiDeviceServiceImpl::UnRegisterThermalLevel() +{ + if (!EventFwk::CommonEventManager::UnSubscribeCommonEvent(thermalLevelSubscriber_)) { + WIFI_LOGE("THERMAL_LEVEL_CHANGED UnSubscribeCommonEvent() failed"); + } else { + WIFI_LOGI("THERMAL_LEVEL_CHANGED UnSubscribeCommonEvent() OK"); + } + thermalLevelSubscriber_ = nullptr; +} + +void AppEventSubscriber::OnReceiveEvent(const OHOS::EventFwk::CommonEventData &data) +{ + std::string action = data.GetWant().GetAction(); + WIFI_LOGI("AppEventSubscriber::OnReceiveEvent : %{public}s.", action.c_str()); + if (action == OHOS::EventFwk::CommonEventSupport::COMMON_EVENT_PACKAGE_REMOVED) { + auto wantTemp = data.GetWant(); + auto uid = wantTemp.GetIntParam(AppExecFwk::Constants::UID, -1); + WIFI_LOGI("Package removed of uid %{public}d.", uid); + IStaService *pService = WifiServiceManager::GetInstance().GetStaServiceInst(); + if (pService == nullptr) { + WIFI_LOGI("Sta service not opend!"); + std::vector tempConfigs; + WifiSettings::GetInstance().GetAllCandidateConfig(uid, tempConfigs); + for (const auto &config : tempConfigs) { + if (WifiSettings::GetInstance().RemoveDevice(config.networkId) != WIFI_OPT_SUCCESS) { + WIFI_LOGE("RemoveAllCandidateConfig-RemoveDevice() failed!"); + } + } + WifiSettings::GetInstance().SyncDeviceConfig(); + return; + } + if (pService->RemoveAllCandidateConfig(uid) != WIFI_OPT_SUCCESS) { + WIFI_LOGE("RemoveAllCandidateConfig failed"); + } + } +} + +void ScreenEventSubscriber::OnReceiveEvent(const OHOS::EventFwk::CommonEventData &data) +{ + std::string action = data.GetWant().GetAction(); + WIFI_LOGI("ScreenEventSubscriber::OnReceiveEvent: %{public}s.", action.c_str()); + IStaService *pService = WifiServiceManager::GetInstance().GetStaServiceInst(); + if (pService == nullptr) { + WIFI_LOGE("sta service is NOT start!"); + return; + } + + int screenState = WifiSettings::GetInstance().GetScreenState(); + if (action == OHOS::EventFwk::CommonEventSupport::COMMON_EVENT_SCREEN_OFF && + screenState == MODE_STATE_OPEN) { + WifiSettings::GetInstance().SetScreenState(MODE_STATE_CLOSE); + /* Send suspend to wpa */ + if (pService->SetSuspendMode(true) != WIFI_OPT_SUCCESS) { + WIFI_LOGE("SetSuspendMode failed"); + } + return; + } + + if (action == OHOS::EventFwk::CommonEventSupport::COMMON_EVENT_SCREEN_ON && + screenState == MODE_STATE_CLOSE) { + WifiSettings::GetInstance().SetScreenState(MODE_STATE_OPEN); + /* Send resume to wpa */ + if (pService->SetSuspendMode(false) != WIFI_OPT_SUCCESS) { + WIFI_LOGE("SetSuspendMode failed"); + } + return; + } + WIFI_LOGW("ScreenEventSubscriber::OnReceiveEvent, screen state: %{public}d.", screenState); +} + +void ThermalLevelSubscriber::OnReceiveEvent(const OHOS::EventFwk::CommonEventData &data) +{ + std::string action = data.GetWant().GetAction(); + WIFI_LOGI("ThermalLevelSubscriber::OnReceiveEvent: %{public}s.", action.c_str()); + if (action == OHOS::EventFwk::CommonEventSupport::COMMON_EVENT_THERMAL_LEVEL_CHANGED) { + static const std::string THERMAL_EVENT_ID = "0"; + int level = data.GetWant().GetIntParam(THERMAL_EVENT_ID, 0); + WifiSettings::GetInstance().SetThermalLevel(level); + WIFI_LOGI("ThermalLevelSubscriber SetThermalLevel: %{public}d.", level); + } +} +#endif } // namespace Wifi -} // namespace OHOS \ No newline at end of file +} // namespace OHOS diff --git a/services/wifi_standard/wifi_framework/wifi_manage/wifi_device_service_impl.h b/wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_device_service_impl.h similarity index 42% rename from services/wifi_standard/wifi_framework/wifi_manage/wifi_device_service_impl.h rename to wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_device_service_impl.h index 1d519c9f8f07409f8eef64d1df68ce301bca0c26..55fc00d4e922aed6e939172ed0abf64ea0cecb47 100644 --- a/services/wifi_standard/wifi_framework/wifi_manage/wifi_device_service_impl.h +++ b/wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_device_service_impl.h @@ -1,5 +1,5 @@ /* - * Copyright (C) 2021 Huawei Device Co., Ltd. + * Copyright (C) 2021-2022 Huawei Device Co., Ltd. * 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 @@ -19,47 +19,104 @@ #include "wifi_errcode.h" #include "wifi_msg.h" #include "i_wifi_device_callback.h" +#ifdef OHOS_ARCH_LITE +#include "wifi_device_stub_lite.h" +#else #include "system_ability.h" #include "wifi_device_stub.h" #include "iremote_object.h" +#include "wifi_p2p_service_impl.h" +#include "common_event_manager.h" +#include "common_event_support.h" +#include "bundle_constants.h" +#include "timer.h" +#endif namespace OHOS { namespace Wifi { +#ifndef OHOS_ARCH_LITE +class AppEventSubscriber : public OHOS::EventFwk::CommonEventSubscriber { +public: + explicit AppEventSubscriber(const OHOS::EventFwk::CommonEventSubscribeInfo &subscriberInfo) + : CommonEventSubscriber(subscriberInfo) {} + virtual ~AppEventSubscriber() {}; + virtual void OnReceiveEvent(const OHOS::EventFwk::CommonEventData &data) override; +}; + +class ScreenEventSubscriber : public OHOS::EventFwk::CommonEventSubscriber { +public: + explicit ScreenEventSubscriber(const OHOS::EventFwk::CommonEventSubscribeInfo &subscriberInfo) + : CommonEventSubscriber(subscriberInfo) {} + virtual ~ScreenEventSubscriber() {}; + virtual void OnReceiveEvent(const OHOS::EventFwk::CommonEventData &data) override; +}; + +class ThermalLevelSubscriber : public OHOS::EventFwk::CommonEventSubscriber { +public: + explicit ThermalLevelSubscriber(const OHOS::EventFwk::CommonEventSubscribeInfo &subscriberInfo) + : CommonEventSubscriber(subscriberInfo) {} + virtual ~ThermalLevelSubscriber() {}; + virtual void OnReceiveEvent(const OHOS::EventFwk::CommonEventData &data) override; +}; +#endif +#ifdef OHOS_ARCH_LITE enum ServiceRunningState { STATE_NOT_START, STATE_RUNNING }; + +class WifiDeviceServiceImpl : public WifiDeviceStub { +#else + class WifiDeviceServiceImpl : public SystemAbility, public WifiDeviceStub { DECLARE_SYSTEM_ABILITY(WifiDeviceServiceImpl); +#endif public: WifiDeviceServiceImpl(); virtual ~WifiDeviceServiceImpl(); +#ifdef OHOS_ARCH_LITE + static std::shared_ptr GetInstance(); + + void OnStart(); + void OnStop(); +#else static sptr GetInstance(); void OnStart() override; void OnStop() override; +#endif ErrCode EnableWifi() override; ErrCode DisableWifi() override; - ErrCode AddDeviceConfig(const WifiDeviceConfig &config, int &result) override; + ErrCode InitWifiProtect(const WifiProtectType &protectType, const std::string &protectName) override; + + ErrCode GetWifiProtectRef(const WifiProtectMode &protectMode, const std::string &protectName) override; + + ErrCode PutWifiProtectRef(const std::string &protectName) override; + + ErrCode AddDeviceConfig(const WifiDeviceConfig &config, int &result, bool isCandidate) override; + + ErrCode UpdateDeviceConfig(const WifiDeviceConfig &config, int &result) override; ErrCode RemoveDevice(int networkId) override; ErrCode RemoveAllDevice() override; - ErrCode GetDeviceConfigs(std::vector &result) override; + ErrCode GetDeviceConfigs(std::vector &result, bool isCandidate) override; ErrCode EnableDeviceConfig(int networkId, bool attemptEnable) override; ErrCode DisableDeviceConfig(int networkId) override; - ErrCode ConnectToNetwork(int networkId) override; + ErrCode ConnectToNetwork(int networkId, bool isCandidate) override; ErrCode ConnectToDevice(const WifiDeviceConfig &config) override; + bool IsConnected() override; + ErrCode ReConnect() override; ErrCode ReAssociate(void) override; @@ -82,7 +139,11 @@ public: ErrCode GetCountryCode(std::string &countryCode) override; +#ifdef OHOS_ARCH_LITE + ErrCode RegisterCallBack(const std::shared_ptr &callback) override; +#else ErrCode RegisterCallBack(const sptr &callback) override; +#endif ErrCode GetSignalLevel(const int &rssi, const int &band, int &level) override; @@ -90,18 +151,61 @@ public: ErrCode GetDeviceMacAddress(std::string &result) override; + bool SetLowLatencyMode(bool enabled) override; + + ErrCode RemoveCandidateConfig(int networkId) override; + + ErrCode RemoveCandidateConfig(const WifiDeviceConfig &config) override; + +#ifndef OHOS_ARCH_LITE + int32_t Dump(int32_t fd, const std::vector& args) override; +#endif + private: bool Init(); ErrCode CheckCanEnableWifi(void); bool IsStaServiceRunning(); bool IsScanServiceRunning(); + bool CheckConfigEap(const WifiDeviceConfig &config); + bool CheckConfigPwd(const WifiDeviceConfig &config); + ErrCode CheckCallingUid(int &uid); + static void SaBasicDump(std::string& result); + static void SigHandler(int sig); + static bool IsProcessNeedToRestart(); + ErrCode CheckRemoveCandidateConfig(void); +#ifndef OHOS_ARCH_LITE + void RegisterAppRemoved(); + void UnRegisterAppRemoved(); + void RegisterScreenEvent(); + void UnRegisterScreenEvent(); + void RegisterThermalLevel(); + void UnRegisterThermalLevel(); +#endif private: + static constexpr int MAX_PRESHAREDKEY_LEN = 63; + static constexpr int MAX_HEX_LEN = 64; + static constexpr int MIN_PSK_LEN = 8; + static constexpr int MIN_SAE_LEN = 1; + static constexpr int WEP_KEY_LEN1 = 5; + static constexpr int WEP_KEY_LEN2 = 13; + static constexpr int WEP_KEY_LEN3 = 16; + +#ifdef OHOS_ARCH_LITE + static std::shared_ptr g_instance; +#else static sptr g_instance; + std::shared_ptr eventSubscriber_ = nullptr; + std::shared_ptr screenEventSubscriber_ = nullptr; + std::shared_ptr thermalLevelSubscriber_ = nullptr; + std::unique_ptr lpTimer_ = nullptr; + std::unique_ptr lpScreenTimer_ = nullptr; + std::unique_ptr lpThermalTimer_ = nullptr; +#endif static std::mutex g_instanceLock; bool mPublishFlag; ServiceRunningState mState; }; } // namespace Wifi } // namespace OHOS -#endif \ No newline at end of file +#endif diff --git a/services/wifi_standard/wifi_framework/wifi_manage/wifi_device_stub.cpp b/wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_device_stub.cpp similarity index 78% rename from services/wifi_standard/wifi_framework/wifi_manage/wifi_device_stub.cpp rename to wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_device_stub.cpp index 2afaed4b854a3da0ce3173290b9c8c44d436a4bd..a9070b46260bfc7578f6ea60e6c36525aedcb5f8 100644 --- a/services/wifi_standard/wifi_framework/wifi_manage/wifi_device_stub.cpp +++ b/wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_device_stub.cpp @@ -1,5 +1,5 @@ /* - * Copyright (C) 2021 Huawei Device Co., Ltd. + * Copyright (C) 2021-2022 Huawei Device Co., Ltd. * 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 @@ -20,6 +20,7 @@ #include "wifi_device_callback_proxy.h" #include "wifi_internal_event_dispatcher.h" #include "wifi_device_death_recipient.h" +#include "wifi_common_util.h" DEFINE_WIFILOG_LABEL("WifiDeviceStub"); @@ -37,7 +38,11 @@ void WifiDeviceStub::InitHandleMap() { handleFuncMap[WIFI_SVR_CMD_ENABLE_WIFI] = &WifiDeviceStub::OnEnableWifi; handleFuncMap[WIFI_SVR_CMD_DISABLE_WIFI] = &WifiDeviceStub::OnDisableWifi; + handleFuncMap[WIFI_SVR_CMD_INIT_WIFI_PROTECT] = &WifiDeviceStub::OnInitWifiProtect; + handleFuncMap[WIFI_SVR_CMD_GET_WIFI_PROTECT] = &WifiDeviceStub::OnGetWifiProtectRef; + handleFuncMap[WIFI_SVR_CMD_PUT_WIFI_PROTECT] = &WifiDeviceStub::OnPutWifiProtectRef; handleFuncMap[WIFI_SVR_CMD_ADD_DEVICE_CONFIG] = &WifiDeviceStub::OnAddDeviceConfig; + handleFuncMap[WIFI_SVR_CMD_UPDATE_DEVICE_CONFIG] = &WifiDeviceStub::OnUpdateDeviceConfig; handleFuncMap[WIFI_SVR_CMD_REMOVE_DEVICE_CONFIG] = &WifiDeviceStub::OnRemoveDevice; handleFuncMap[WIFI_SVR_CMD_REMOVE_ALL_DEVICE_CONFIG] = &WifiDeviceStub::OnRemoveAllDevice; handleFuncMap[WIFI_SVR_CMD_GET_DEVICE_CONFIGS] = &WifiDeviceStub::OnGetDeviceConfigs; @@ -60,11 +65,19 @@ void WifiDeviceStub::InitHandleMap() handleFuncMap[WIFI_SVR_CMD_GET_SIGNAL_LEVEL] = &WifiDeviceStub::OnGetSignalLevel; handleFuncMap[WIFI_SVR_CMD_GET_SUPPORTED_FEATURES] = &WifiDeviceStub::OnGetSupportedFeatures; handleFuncMap[WIFI_SVR_CMD_GET_DERVICE_MAC_ADD] = &WifiDeviceStub::OnGetDeviceMacAdd; + handleFuncMap[WIFI_SVR_CMD_IS_WIFI_CONNECTED] = &WifiDeviceStub::OnIsWifiConnected; + handleFuncMap[WIFI_SVR_CMD_SET_LOW_LATENCY_MODE] = &WifiDeviceStub::OnSetLowLatencyMode; + handleFuncMap[WIFI_SVR_CMD_REMOVE_CANDIDATE_CONFIG] = &WifiDeviceStub::OnRemoveCandidateConfig; return; } int WifiDeviceStub::OnRemoteRequest(uint32_t code, MessageParcel &data, MessageParcel &reply, MessageOption &option) { + if (data.ReadInterfaceToken() != GetDescriptor()) { + WIFI_LOGE("Sta stub token verification error: %{public}d", code); + return WIFI_OPT_FAILED; + } + int exception = data.ReadInt32(); if (exception) { return WIFI_OPT_FAILED; @@ -101,14 +114,47 @@ void WifiDeviceStub::OnDisableWifi(uint32_t code, MessageParcel &data, MessagePa return; } +void WifiDeviceStub::OnInitWifiProtect(uint32_t code, MessageParcel &data, MessageParcel &reply) +{ + WIFI_LOGD("run %{public}s code %{public}u, datasize %{public}zu", __func__, code, data.GetRawDataSize()); + WifiProtectType protectType = (WifiProtectType)data.ReadInt32(); + std::string protectName = data.ReadCString(); + ErrCode ret = InitWifiProtect(protectType, protectName); + reply.WriteInt32(0); + reply.WriteInt32(ret); + return; +} + +void WifiDeviceStub::OnGetWifiProtectRef(uint32_t code, MessageParcel &data, MessageParcel &reply) +{ + WIFI_LOGD("run %{public}s code %{public}u, datasize %{public}zu", __func__, code, data.GetRawDataSize()); + WifiProtectMode protectMode = (WifiProtectMode)data.ReadInt32(); + std::string protectName = data.ReadCString(); + ErrCode ret = GetWifiProtectRef(protectMode, protectName); + reply.WriteInt32(0); + reply.WriteInt32(ret); + return; +} + +void WifiDeviceStub::OnPutWifiProtectRef(uint32_t code, MessageParcel &data, MessageParcel &reply) +{ + WIFI_LOGD("run %{public}s code %{public}u, datasize %{public}zu", __func__, code, data.GetRawDataSize()); + std::string protectName = data.ReadCString(); + ErrCode ret = PutWifiProtectRef(protectName); + reply.WriteInt32(0); + reply.WriteInt32(ret); + return; +} + void WifiDeviceStub::OnAddDeviceConfig(uint32_t code, MessageParcel &data, MessageParcel &reply) { WIFI_LOGD("run %{public}s code %{public}u, datasize %{public}zu", __func__, code, data.GetRawDataSize()); + bool isCandidate = data.ReadBool(); WifiDeviceConfig config; ReadWifiDeviceConfig(data, config); - int result = 0; - ErrCode ret = AddDeviceConfig(config, result); + int result = INVALID_NETWORK_ID; + ErrCode ret = AddDeviceConfig(config, result, isCandidate); reply.WriteInt32(0); reply.WriteInt32(ret); @@ -119,6 +165,21 @@ void WifiDeviceStub::OnAddDeviceConfig(uint32_t code, MessageParcel &data, Messa return; } +void WifiDeviceStub::OnUpdateDeviceConfig(uint32_t code, MessageParcel &data, MessageParcel &reply) +{ + WIFI_LOGD("run %{public}s code %{public}u, datasize %{public}zu", __func__, code, data.GetRawDataSize()); + WifiDeviceConfig config; + ReadWifiDeviceConfig(data, config); + int result = INVALID_NETWORK_ID; + ErrCode ret = UpdateDeviceConfig(config, result); + reply.WriteInt32(0); + reply.WriteInt32(ret); + if (ret == WIFI_OPT_SUCCESS) { + reply.WriteInt32(result); + } + return; +} + void WifiDeviceStub::ReadWifiDeviceConfig(MessageParcel &data, WifiDeviceConfig &config) { config.networkId = data.ReadInt32(); @@ -151,6 +212,9 @@ void WifiDeviceStub::ReadWifiDeviceConfig(MessageParcel &data, WifiDeviceConfig config.wifiEapConfig.eap = data.ReadCString(); config.wifiEapConfig.identity = data.ReadCString(); config.wifiEapConfig.password = data.ReadCString(); + config.wifiEapConfig.clientCert = data.ReadCString(); + config.wifiEapConfig.privateKey = data.ReadCString(); + config.wifiEapConfig.phase2Method = Phase2Method(data.ReadInt32()); config.wifiProxyconfig.configureMethod = ConfigureProxyMethod(data.ReadInt32()); config.wifiProxyconfig.autoProxyConfig.pacWebAddress = data.ReadCString(); config.wifiProxyconfig.manualProxyConfig.serverHostName = data.ReadCString(); @@ -162,13 +226,17 @@ void WifiDeviceStub::ReadWifiDeviceConfig(MessageParcel &data, WifiDeviceConfig void WifiDeviceStub::ReadIpAddress(MessageParcel &data, WifiIpAddress &address) { + constexpr int MAX_LIMIT_SIZE = 1024; address.family = data.ReadInt32(); address.addressIpv4 = data.ReadInt32(); int size = data.ReadInt32(); + if (size > MAX_LIMIT_SIZE) { + WIFI_LOGE("Read ip address parameter error: %{public}d", size); + return; + } for (int i = 0; i < size; i++) { address.addressIpv6.push_back(data.ReadInt8()); } - return; } @@ -204,12 +272,16 @@ void WifiDeviceStub::WriteWifiDeviceConfig(MessageParcel &reply, const WifiDevic reply.WriteCString(config.wifiEapConfig.eap.c_str()); reply.WriteCString(config.wifiEapConfig.identity.c_str()); reply.WriteCString(config.wifiEapConfig.password.c_str()); + reply.WriteCString(config.wifiEapConfig.clientCert.c_str()); + reply.WriteCString(config.wifiEapConfig.privateKey.c_str()); + reply.WriteInt32(static_cast(config.wifiEapConfig.phase2Method)); reply.WriteInt32((int)config.wifiProxyconfig.configureMethod); reply.WriteCString(config.wifiProxyconfig.autoProxyConfig.pacWebAddress.c_str()); reply.WriteCString(config.wifiProxyconfig.manualProxyConfig.serverHostName.c_str()); reply.WriteInt32(config.wifiProxyconfig.manualProxyConfig.serverPort); reply.WriteCString(config.wifiProxyconfig.manualProxyConfig.exclusionObjectList.c_str()); reply.WriteInt32((int)config.wifiPrivacySetting); + reply.WriteInt32(config.uid); return; } @@ -250,8 +322,9 @@ void WifiDeviceStub::OnRemoveAllDevice(uint32_t code, MessageParcel &data, Messa void WifiDeviceStub::OnGetDeviceConfigs(uint32_t code, MessageParcel &data, MessageParcel &reply) { WIFI_LOGD("run %{public}s code %{public}u, datasize %{public}zu", __func__, code, data.GetRawDataSize()); + bool isCandidate = data.ReadBool(); std::vector result; - ErrCode ret = GetDeviceConfigs(result); + ErrCode ret = GetDeviceConfigs(result, isCandidate); reply.WriteInt32(0); reply.WriteInt32(ret); @@ -291,8 +364,9 @@ void WifiDeviceStub::OnDisableDeviceConfig(uint32_t code, MessageParcel &data, M void WifiDeviceStub::OnConnectTo(uint32_t code, MessageParcel &data, MessageParcel &reply) { WIFI_LOGD("run %{public}s code %{public}u, datasize %{public}zu", __func__, code, data.GetRawDataSize()); + bool isCandidate = data.ReadBool(); int networkId = data.ReadInt32(); - ErrCode ret = ConnectToNetwork(networkId); + ErrCode ret = ConnectToNetwork(networkId, isCandidate); reply.WriteInt32(0); reply.WriteInt32(ret); @@ -311,6 +385,14 @@ void WifiDeviceStub::OnConnect2To(uint32_t code, MessageParcel &data, MessagePar return; } +void WifiDeviceStub::OnIsWifiConnected(uint32_t code, MessageParcel &data, MessageParcel &reply) +{ + WIFI_LOGD("run %{public}s code %{public}u, datasize %{public}zu", __func__, code, data.GetRawDataSize()); + reply.WriteInt32(0); + reply.WriteBool(IsConnected()); + return; +} + void WifiDeviceStub::OnReConnect(uint32_t code, MessageParcel &data, MessageParcel &reply) { WIFI_LOGD("run %{public}s code %{public}u, datasize %{public}zu", __func__, code, data.GetRawDataSize()); @@ -409,13 +491,16 @@ void WifiDeviceStub::OnGetLinkedInfo(uint32_t code, MessageParcel &data, Message reply.WriteInt32(wifiInfo.frequency); reply.WriteInt32(wifiInfo.linkSpeed); reply.WriteCString(wifiInfo.macAddress.c_str()); + reply.WriteInt32(wifiInfo.macType); reply.WriteInt32(wifiInfo.ipAddress); reply.WriteInt32((int)wifiInfo.connState); reply.WriteBool(wifiInfo.ifHiddenSSID); - reply.WriteCString(wifiInfo.rxLinkSpeed.c_str()); - reply.WriteCString(wifiInfo.txLinkSpeed.c_str()); + reply.WriteInt32(wifiInfo.rxLinkSpeed); + reply.WriteInt32(wifiInfo.txLinkSpeed); reply.WriteInt32(wifiInfo.chload); reply.WriteInt32(wifiInfo.snr); + reply.WriteInt32(wifiInfo.isDataRestricted); + reply.WriteCString(wifiInfo.portalUrl.c_str()); reply.WriteInt32((int)wifiInfo.supplicantState); reply.WriteInt32((int)wifiInfo.detailedState); } @@ -472,18 +557,18 @@ void WifiDeviceStub::OnGetCountryCode(uint32_t code, MessageParcel &data, Messag void WifiDeviceStub::OnRegisterCallBack(uint32_t code, MessageParcel &data, MessageParcel &reply) { - WIFI_LOGD("run %{public}s code %{public}u, datasize %zu", __func__, code, data.GetRawDataSize()); + WIFI_LOGD("run %{public}s code %{public}u, datasize %{public}zu", __func__, code, data.GetRawDataSize()); ErrCode ret = WIFI_OPT_FAILED; do { sptr remote = data.ReadRemoteObject(); if (remote == nullptr) { - WIFI_LOGD("Failed to ReadRemoteObject!"); + WIFI_LOGW("Failed to ReadRemoteObject!"); break; } callback_ = iface_cast(remote); if (callback_ == nullptr) { callback_ = new (std::nothrow) WifiDeviceCallBackProxy(remote); - WIFI_LOGD("create new WifiDeviceCallBackProxy!"); + WIFI_LOGI("create new WifiDeviceCallBackProxy!"); } if (mSingleCallback) { @@ -508,7 +593,6 @@ void WifiDeviceStub::OnRegisterCallBack(uint32_t code, MessageParcel &data, Mess void WifiDeviceStub::OnGetSignalLevel(uint32_t code, MessageParcel &data, MessageParcel &reply) { - WIFI_LOGD("run %{public}s code %{public}u, datasize %{public}zu", __func__, code, data.GetRawDataSize()); int rssi = data.ReadInt32(); int band = data.ReadInt32(); int level = 0; @@ -549,5 +633,35 @@ void WifiDeviceStub::OnGetDeviceMacAdd(uint32_t code, MessageParcel &data, Messa return; } + +void WifiDeviceStub::OnSetLowLatencyMode(uint32_t code, MessageParcel &data, MessageParcel &reply) +{ + WIFI_LOGD("run %{public}s code %{public}u, datasize %{public}zu", __func__, code, data.GetRawDataSize()); + + bool enabled = data.ReadBool(); + reply.WriteInt32(0); + reply.WriteBool(SetLowLatencyMode(enabled)); +} + +void WifiDeviceStub::OnRemoveCandidateConfig(uint32_t code, MessageParcel &data, MessageParcel &reply) +{ + WIFI_LOGD("run %{public}s code %{public}u, datasize %{public}zu", __func__, code, data.GetRawDataSize()); + ErrCode ret = WIFI_OPT_FAILED; + int flag = data.ReadInt32(); + /* Read a flag: 1-remove config by networkId, 2-remove config by WifiDeviceConfig */ + if (flag == 1) { + int networkId = data.ReadInt32(); + WIFI_LOGI("Remove candidate config by networkId: %{public}d", networkId); + ret = RemoveCandidateConfig(networkId); + } else { + WifiDeviceConfig config; + ReadWifiDeviceConfig(data, config); + WIFI_LOGD("Remove candidate config by config: %{public}s", SsidAnonymize(config.ssid).c_str()); + ret = RemoveCandidateConfig(config); + } + reply.WriteInt32(0); + reply.WriteInt32(ret); + return; +} } // namespace Wifi -} // namespace OHOS \ No newline at end of file +} // namespace OHOS diff --git a/services/wifi_standard/wifi_framework/wifi_manage/wifi_device_stub.h b/wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_device_stub.h similarity index 85% rename from services/wifi_standard/wifi_framework/wifi_manage/wifi_device_stub.h rename to wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_device_stub.h index 0f2e9e24064c043fc7f97910b2aac8c4938cb3d2..9b0e2bf6d1d584140a007f304d9b9ec110a3a96c 100644 --- a/services/wifi_standard/wifi_framework/wifi_manage/wifi_device_stub.h +++ b/wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_device_stub.h @@ -1,5 +1,5 @@ /* - * Copyright (C) 2021 Huawei Device Co., Ltd. + * Copyright (C) 2021-2022 Huawei Device Co., Ltd. * 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 @@ -12,6 +12,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + #ifndef OHOS_WIFI_DEVICE_STUB_H #define OHOS_WIFI_DEVICE_STUB_H @@ -37,7 +38,11 @@ private: void InitHandleMap(); void OnEnableWifi(uint32_t code, MessageParcel &data, MessageParcel &reply); void OnDisableWifi(uint32_t code, MessageParcel &data, MessageParcel &reply); + void OnInitWifiProtect(uint32_t code, MessageParcel &data, MessageParcel &reply); + void OnGetWifiProtectRef(uint32_t code, MessageParcel &data, MessageParcel &reply); + void OnPutWifiProtectRef(uint32_t code, MessageParcel &data, MessageParcel &reply); void OnAddDeviceConfig(uint32_t code, MessageParcel &data, MessageParcel &reply); + void OnUpdateDeviceConfig(uint32_t code, MessageParcel &data, MessageParcel &reply); void OnRemoveDevice(uint32_t code, MessageParcel &data, MessageParcel &reply); void OnRemoveAllDevice(uint32_t code, MessageParcel &data, MessageParcel &reply); void OnGetDeviceConfigs(uint32_t code, MessageParcel &data, MessageParcel &reply); @@ -60,6 +65,9 @@ private: void OnGetSignalLevel(uint32_t code, MessageParcel &data, MessageParcel &reply); void OnGetSupportedFeatures(uint32_t code, MessageParcel &data, MessageParcel &reply); void OnGetDeviceMacAdd(uint32_t code, MessageParcel &data, MessageParcel &reply); + void OnIsWifiConnected(uint32_t code, MessageParcel &data, MessageParcel &reply); + void OnSetLowLatencyMode(uint32_t code, MessageParcel &data, MessageParcel &reply); + void OnRemoveCandidateConfig(uint32_t code, MessageParcel &data, MessageParcel &reply); private: void ReadWifiDeviceConfig(MessageParcel &data, WifiDeviceConfig &config); diff --git a/wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_device_stub_lite.cpp b/wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_device_stub_lite.cpp new file mode 100644 index 0000000000000000000000000000000000000000..3837fc20472cc40f1df21314f47af1b367380bd6 --- /dev/null +++ b/wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_device_stub_lite.cpp @@ -0,0 +1,604 @@ +/* + * Copyright (C) 2022 Huawei Device Co., Ltd. + * 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 "wifi_device_stub_lite.h" +#include "define.h" +#include "ipc_skeleton.h" +#include "rpc_errno.h" +#include "wifi_device_callback_proxy.h" +#include "wifi_errcode.h" +#include "wifi_logger.h" +#include "wifi_msg.h" + +DEFINE_WIFILOG_LABEL("WifiDeviceStubLite"); + +namespace OHOS { +namespace Wifi { +WifiDeviceStub::WifiDeviceStub() +{ + InitHandleMap(); +} + +WifiDeviceStub::~WifiDeviceStub() +{} + +void WifiDeviceStub::ReadIpAddress(IpcIo *req, WifiIpAddress &address) +{ + constexpr int MAX_LIMIT_SIZE = 1024; + (void)ReadInt32(req, &address.family); + (void)ReadUint32(req, &address.addressIpv4); + int size = 0; + (void)ReadInt32(req, &size); + if (size > MAX_LIMIT_SIZE) { + WIFI_LOGE("Read ip address parameter error: %{public}d", size); + return; + } + int8_t tmpInt8; + for (int i = 0; i < size; i++) { + (void)ReadInt8(req, &tmpInt8); + address.addressIpv6.push_back(tmpInt8); + } +} + +void WifiDeviceStub::ReadWifiDeviceConfig(IpcIo *req, WifiDeviceConfig &config) +{ + int tmpInt; + size_t size; + (void)ReadInt32(req, &config.networkId); + (void)ReadInt32(req, &config.status); + config.bssid = (char *)ReadString(req, &size); + config.ssid = (char *)ReadString(req, &size); + (void)ReadInt32(req, &config.band); + (void)ReadInt32(req, &config.channel); + (void)ReadInt32(req, &config.frequency); + (void)ReadInt32(req, &config.level); + (void)ReadBool(req, &config.isPasspoint); + (void)ReadBool(req, &config.isEphemeral); + config.preSharedKey = (char *)ReadString(req, &size); + config.keyMgmt = (char *)ReadString(req, &size); + for (int i = 0; i < WEPKEYS_SIZE; i++) { + config.wepKeys[i] = (char *)ReadString(req, &size); + } + (void)ReadInt32(req, &config.wepTxKeyIndex); + (void)ReadInt32(req, &config.priority); + (void)ReadBool(req, &config.hiddenSSID); + (void)ReadInt32(req, &tmpInt); + config.wifiIpConfig.assignMethod = AssignIpMethod(tmpInt); + ReadIpAddress(req, config.wifiIpConfig.staticIpAddress.ipAddress.address); + (void)ReadInt32(req, &config.wifiIpConfig.staticIpAddress.ipAddress.prefixLength); + (void)ReadInt32(req, &config.wifiIpConfig.staticIpAddress.ipAddress.flags); + (void)ReadInt32(req, &config.wifiIpConfig.staticIpAddress.ipAddress.scope); + ReadIpAddress(req, config.wifiIpConfig.staticIpAddress.gateway); + ReadIpAddress(req, config.wifiIpConfig.staticIpAddress.dnsServer1); + ReadIpAddress(req, config.wifiIpConfig.staticIpAddress.dnsServer2); + config.wifiIpConfig.staticIpAddress.domains = (char *)ReadString(req, &size); + config.wifiEapConfig.eap = (char *)ReadString(req, &size); + config.wifiEapConfig.identity = (char *)ReadString(req, &size); + config.wifiEapConfig.password = (char *)ReadString(req, &size); + (void)ReadInt32(req, &tmpInt); + config.wifiProxyconfig.configureMethod = ConfigureProxyMethod(tmpInt); + config.wifiProxyconfig.autoProxyConfig.pacWebAddress = (char *)ReadString(req, &size); + config.wifiProxyconfig.manualProxyConfig.serverHostName = (char *)ReadString(req, &size); + (void)ReadInt32(req, &config.wifiProxyconfig.manualProxyConfig.serverPort); + config.wifiProxyconfig.manualProxyConfig.exclusionObjectList = (char *)ReadString(req, &size); + (void)ReadInt32(req, &tmpInt); + config.wifiPrivacySetting = WifiPrivacyConfig(tmpInt); +} + +void WifiDeviceStub::WriteIpAddress(IpcIo *reply, const WifiIpAddress &address) +{ + (void)WriteInt32(reply, address.family); + (void)WriteUint32(reply, address.addressIpv4); + int size = address.addressIpv6.size(); + (void)WriteInt32(reply, size); + for (int i = 0; i < size; i++) { + (void)WriteInt8(reply, address.addressIpv6[i]); + } +} + +void WifiDeviceStub::WriteWifiDeviceConfig(IpcIo *reply, const WifiDeviceConfig &config) +{ + (void)WriteInt32(reply, config.networkId); + (void)WriteInt32(reply, config.status); + (void)WriteString(reply, config.bssid.c_str()); + (void)WriteString(reply, config.ssid.c_str()); + (void)WriteInt32(reply, config.band); + (void)WriteInt32(reply, config.channel); + (void)WriteInt32(reply, config.frequency); + (void)WriteInt32(reply, config.level); + (void)WriteBool(reply, config.isPasspoint); + (void)WriteBool(reply, config.isEphemeral); + (void)WriteString(reply, config.preSharedKey.c_str()); + (void)WriteString(reply, config.keyMgmt.c_str()); + for (int j = 0; j < WEPKEYS_SIZE; j++) { + (void)WriteString(reply, config.wepKeys[j].c_str()); + } + (void)WriteInt32(reply, config.wepTxKeyIndex); + (void)WriteInt32(reply, config.priority); + (void)WriteBool(reply, config.hiddenSSID); + (void)WriteInt32(reply, (int)config.wifiIpConfig.assignMethod); + WriteIpAddress(reply, config.wifiIpConfig.staticIpAddress.ipAddress.address); + (void)WriteInt32(reply, config.wifiIpConfig.staticIpAddress.ipAddress.prefixLength); + (void)WriteInt32(reply, config.wifiIpConfig.staticIpAddress.ipAddress.flags); + (void)WriteInt32(reply, config.wifiIpConfig.staticIpAddress.ipAddress.scope); + WriteIpAddress(reply, config.wifiIpConfig.staticIpAddress.gateway); + WriteIpAddress(reply, config.wifiIpConfig.staticIpAddress.dnsServer1); + WriteIpAddress(reply, config.wifiIpConfig.staticIpAddress.dnsServer2); + (void)WriteString(reply, config.wifiIpConfig.staticIpAddress.domains.c_str()); + (void)WriteString(reply, config.wifiEapConfig.eap.c_str()); + (void)WriteString(reply, config.wifiEapConfig.identity.c_str()); + (void)WriteString(reply, config.wifiEapConfig.password.c_str()); + (void)WriteInt32(reply, (int)config.wifiProxyconfig.configureMethod); + (void)WriteString(reply, config.wifiProxyconfig.autoProxyConfig.pacWebAddress.c_str()); + (void)WriteString(reply, config.wifiProxyconfig.manualProxyConfig.serverHostName.c_str()); + (void)WriteInt32(reply, config.wifiProxyconfig.manualProxyConfig.serverPort); + (void)WriteString(reply, config.wifiProxyconfig.manualProxyConfig.exclusionObjectList.c_str()); + (void)WriteInt32(reply, (int)config.wifiPrivacySetting); +} + +void WifiDeviceStub::OnEnableWifi(uint32_t code, IpcIo *req, IpcIo *reply) +{ + WIFI_LOGD("run %{public}s code %{public}u", __func__, code); + ErrCode ret = EnableWifi(); + (void)WriteInt32(reply, 0); + (void)WriteInt32(reply, ret); +} + +void WifiDeviceStub::OnDisableWifi(uint32_t code, IpcIo *req, IpcIo *reply) +{ + WIFI_LOGD("run %{public}s code %{public}u", __func__, code); + ErrCode ret = DisableWifi(); + (void)WriteInt32(reply, 0); + (void)WriteInt32(reply, ret); +} + +void WifiDeviceStub::OnInitWifiProtect(uint32_t code, IpcIo *req, IpcIo *reply) +{ + WIFI_LOGD("run %{public}s code %{public}u", __func__, code); + size_t size; + int type = 0; + (void)ReadInt32(req, &type); + WifiProtectType protectType = (WifiProtectType)type; + std::string protectName = (char *)ReadString(req, &size); + ErrCode ret = InitWifiProtect(protectType, protectName); + (void)WriteInt32(reply, 0); + (void)WriteInt32(reply, ret); +} + +void WifiDeviceStub::OnGetWifiProtectRef(uint32_t code, IpcIo *req, IpcIo *reply) +{ + WIFI_LOGD("run %{public}s code %{public}u", __func__, code); + size_t size; + int mode = 0; + (void)ReadInt32(req, &mode); + WifiProtectMode protectMode = (WifiProtectMode)mode; + std::string protectName = (char *)ReadString(req, &size); + ErrCode ret = GetWifiProtectRef(protectMode, protectName); + (void)WriteInt32(reply, 0); + (void)WriteInt32(reply, ret); +} + +void WifiDeviceStub::OnPutWifiProtectRef(uint32_t code, IpcIo *req, IpcIo *reply) +{ + WIFI_LOGD("run %{public}s code %{public}u", __func__, code); + size_t size; + std::string protectName = (char *)ReadString(req, &size); + ErrCode ret = PutWifiProtectRef(protectName); + (void)WriteInt32(reply, 0); + (void)WriteInt32(reply, ret); +} + +void WifiDeviceStub::OnAddDeviceConfig(uint32_t code, IpcIo *req, IpcIo *reply) +{ + WIFI_LOGD("run %{public}s code %{public}u", __func__, code); + bool isCandidate = false; + WifiDeviceConfig config; + (void)ReadBool(req, &isCandidate); + ReadWifiDeviceConfig(req, config); + + int result = INVALID_NETWORK_ID; + ErrCode ret = AddDeviceConfig(config, result, isCandidate); + + (void)WriteInt32(reply, 0); + (void)WriteInt32(reply, ret); + if (ret == WIFI_OPT_SUCCESS) { + (void)WriteInt32(reply, result); + } +} + +void WifiDeviceStub::OnUpdateDeviceConfig(uint32_t code, IpcIo *req, IpcIo *reply) +{ + WIFI_LOGD("run %{public}s code %{public}u", __func__, code); + WifiDeviceConfig config; + ReadWifiDeviceConfig(req, config); + int result = INVALID_NETWORK_ID; + ErrCode ret = UpdateDeviceConfig(config, result); + (void)WriteInt32(reply, 0); + (void)WriteInt32(reply, ret); + if (ret == WIFI_OPT_SUCCESS) { + (void)WriteInt32(reply, result); + } +} + +void WifiDeviceStub::OnRemoveDevice(uint32_t code, IpcIo *req, IpcIo *reply) +{ + WIFI_LOGD("run %{public}s code %{public}u", __func__, code); + int networkId = 0; + (void)ReadInt32(req, &networkId); + ErrCode ret = RemoveDevice(networkId); + (void)WriteInt32(reply, 0); + (void)WriteInt32(reply, ret); +} + +void WifiDeviceStub::OnRemoveAllDevice(uint32_t code, IpcIo *req, IpcIo *reply) +{ + WIFI_LOGD("run %{public}s code %{public}u", __func__, code); + ErrCode ret = RemoveAllDevice(); + (void)WriteInt32(reply, 0); + (void)WriteInt32(reply, ret); +} + +void WifiDeviceStub::OnGetDeviceConfigs(uint32_t code, IpcIo *req, IpcIo *reply) +{ + WIFI_LOGD("run %{public}s code %{public}u", __func__, code); + bool isCandidate = false; + std::vector result; + (void)ReadBool(req, &isCandidate); + ErrCode ret = GetDeviceConfigs(result, isCandidate); + (void)WriteInt32(reply, 0); + (void)WriteInt32(reply, ret); + + if (ret == WIFI_OPT_SUCCESS) { + unsigned int size = result.size(); + (void)WriteInt32(reply, size); + for (unsigned int i = 0; i < size; ++i) { + WriteWifiDeviceConfig(reply, result[i]); + } + } +} + +void WifiDeviceStub::OnEnableDeviceConfig(uint32_t code, IpcIo *req, IpcIo *reply) +{ + WIFI_LOGD("run %{public}s code %{public}u", __func__, code); + int networkId = 0; + (void)ReadInt32(req, &networkId); + bool attemptEnable; + (void)ReadBool(req, &attemptEnable); + ErrCode ret = EnableDeviceConfig(networkId, attemptEnable); + (void)WriteInt32(reply, 0); + (void)WriteInt32(reply, ret); +} + +void WifiDeviceStub::OnDisableDeviceConfig(uint32_t code, IpcIo *req, IpcIo *reply) +{ + WIFI_LOGD("run %{public}s code %{public}u", __func__, code); + int networkId = 0; + (void)ReadInt32(req, &networkId); + ErrCode ret = DisableDeviceConfig(networkId); + (void)WriteInt32(reply, 0); + (void)WriteInt32(reply, ret); +} + +void WifiDeviceStub::OnConnectTo(uint32_t code, IpcIo *req, IpcIo *reply) +{ + WIFI_LOGD("run %{public}s code %{public}u", __func__, code); + int networkId = 0; + bool isCandidate = false; + (void)ReadBool(req, &isCandidate); + (void)ReadInt32(req, &networkId); + ErrCode ret = ConnectToNetwork(networkId, isCandidate); + (void)WriteInt32(reply, 0); + (void)WriteInt32(reply, ret); +} + +void WifiDeviceStub::OnConnect2To(uint32_t code, IpcIo *req, IpcIo *reply) +{ + WIFI_LOGD("run %{public}s code %{public}u", __func__, code); + WifiDeviceConfig config; + ReadWifiDeviceConfig(req, config); + ErrCode ret = ConnectToDevice(config); + (void)WriteInt32(reply, 0); + (void)WriteInt32(reply, ret); +} + +void WifiDeviceStub::OnIsWifiConnected(uint32_t code, IpcIo *req, IpcIo *reply) +{ + WIFI_LOGD("run %{public}s code %{public}u", __func__, code); + (void)WriteInt32(reply, 0); + (void)WriteInt32(reply, WIFI_OPT_SUCCESS); + (void)WriteBool(reply, IsConnected()); +} + +void WifiDeviceStub::OnReConnect(uint32_t code, IpcIo *req, IpcIo *reply) +{ + WIFI_LOGD("run %{public}s code %{public}u", __func__, code); + ErrCode ret = ReConnect(); + (void)WriteInt32(reply, 0); + (void)WriteInt32(reply, ret); +} + +void WifiDeviceStub::OnReAssociate(uint32_t code, IpcIo *req, IpcIo *reply) +{ + WIFI_LOGD("run %{public}s code %{public}u", __func__, code); + ErrCode ret = ReAssociate(); + (void)WriteInt32(reply, 0); + (void)WriteInt32(reply, ret); +} + +void WifiDeviceStub::OnDisconnect(uint32_t code, IpcIo *req, IpcIo *reply) +{ + WIFI_LOGD("run %{public}s code %{public}u", __func__, code); + ErrCode ret = Disconnect(); + (void)WriteInt32(reply, 0); + (void)WriteInt32(reply, ret); +} + +void WifiDeviceStub::OnStartWps(uint32_t code, IpcIo *req, IpcIo *reply) +{ + WIFI_LOGD("run %{public}s code %{public}u", __func__, code); + size_t size; + WpsConfig config; + int setup; + (void)ReadInt32(req, &setup); + config.setup = SetupMethod(setup); + config.pin = (char *)ReadString(req, &size); + config.bssid = (char *)ReadString(req, &size); + + ErrCode ret = StartWps(config); + (void)WriteInt32(reply, 0); + (void)WriteInt32(reply, ret); +} + +void WifiDeviceStub::OnCancelWps(uint32_t code, IpcIo *req, IpcIo *reply) +{ + WIFI_LOGD("run %{public}s code %{public}u", __func__, code); + ErrCode ret = CancelWps(); + (void)WriteInt32(reply, 0); + (void)WriteInt32(reply, ret); +} + +void WifiDeviceStub::OnIsWifiActive(uint32_t code, IpcIo *req, IpcIo *reply) +{ + WIFI_LOGD("run %{public}s code %{public}u", __func__, code); + bool bActive = false; + ErrCode ret = IsWifiActive(bActive); + (void)WriteInt32(reply, 0); + (void)WriteInt32(reply, ret); + if (ret == WIFI_OPT_SUCCESS) { + (void)WriteBool(reply, bActive); + } +} + +void WifiDeviceStub::OnGetWifiState(uint32_t code, IpcIo *req, IpcIo *reply) +{ + WIFI_LOGD("run %{public}s code %{public}u", __func__, code); + int state = 0; + ErrCode ret = GetWifiState(state); + (void)WriteInt32(reply, 0); + (void)WriteInt32(reply, ret); + if (ret == WIFI_OPT_SUCCESS) { + (void)WriteInt32(reply, state); + } +} + +void WifiDeviceStub::OnGetLinkedInfo(uint32_t code, IpcIo *req, IpcIo *reply) +{ + WIFI_LOGD("run %{public}s code %{public}u", __func__, code); + WifiLinkedInfo wifiInfo; + ErrCode ret = GetLinkedInfo(wifiInfo); + (void)WriteInt32(reply, 0); + (void)WriteInt32(reply, ret); + + if (ret == WIFI_OPT_SUCCESS) { + (void)WriteInt32(reply, wifiInfo.networkId); + (void)WriteString(reply, wifiInfo.ssid.c_str()); + (void)WriteString(reply, wifiInfo.bssid.c_str()); + (void)WriteInt32(reply, wifiInfo.rssi); + (void)WriteInt32(reply, wifiInfo.band); + (void)WriteInt32(reply, wifiInfo.frequency); + (void)WriteInt32(reply, wifiInfo.linkSpeed); + (void)WriteString(reply, wifiInfo.macAddress.c_str()); + (void)WriteUint32(reply, wifiInfo.ipAddress); + (void)WriteInt32(reply, (int)wifiInfo.connState); + (void)WriteBool(reply, wifiInfo.ifHiddenSSID); + (void)WriteInt32(reply, wifiInfo.rxLinkSpeed); + (void)WriteInt32(reply, wifiInfo.txLinkSpeed); + (void)WriteInt32(reply, wifiInfo.chload); + (void)WriteInt32(reply, wifiInfo.snr); + (void)WriteInt32(reply, wifiInfo.isDataRestricted); + (void)WriteString(reply, wifiInfo.portalUrl.c_str()); + (void)WriteInt32(reply, (int)wifiInfo.supplicantState); + (void)WriteInt32(reply, (int)wifiInfo.detailedState); + } +} + +void WifiDeviceStub::OnGetIpInfo(uint32_t code, IpcIo *req, IpcIo *reply) +{ + WIFI_LOGD("run %{public}s code %{public}u", __func__, code); + IpInfo info; + ErrCode ret = GetIpInfo(info); + (void)WriteInt32(reply, 0); + (void)WriteInt32(reply, ret); + + if (ret == WIFI_OPT_SUCCESS) { + (void)WriteUint32(reply, info.ipAddress); + (void)WriteUint32(reply, info.gateway); + (void)WriteUint32(reply, info.netmask); + (void)WriteUint32(reply, info.primaryDns); + (void)WriteUint32(reply, info.secondDns); + (void)WriteUint32(reply, info.serverIp); + (void)WriteUint32(reply, info.leaseDuration); + } +} + +void WifiDeviceStub::OnSetCountryCode(uint32_t code, IpcIo *req, IpcIo *reply) +{ + WIFI_LOGD("run %{public}s code %{public}u", __func__, code); + size_t size; + std::string countrycode = (char *)ReadString(req, &size); + ErrCode ret = SetCountryCode(countrycode); + (void)WriteInt32(reply, 0); + (void)WriteInt32(reply, ret); +} + +void WifiDeviceStub::OnGetCountryCode(uint32_t code, IpcIo *req, IpcIo *reply) +{ + WIFI_LOGD("run %{public}s code %{public}u", __func__, code); + std::string countryCode; + ErrCode ret = GetCountryCode(countryCode); + (void)WriteInt32(reply, 0); + (void)WriteInt32(reply, ret); + + if (ret == WIFI_OPT_SUCCESS) { + (void)WriteString(reply, countryCode.c_str()); + } +} + +void WifiDeviceStub::OnRegisterCallBack(uint32_t code, IpcIo *req, IpcIo *reply) +{ + WIFI_LOGD("run %{public}s code %{public}u", __func__, code); + ErrCode ret = WIFI_OPT_FAILED; + SvcIdentity sid; + bool readSid = ReadRemoteObject(req, &sid); + if (!readSid) { + WIFI_LOGE("read SvcIdentity failed"); + (void)WriteInt32(reply, 0); + (void)WriteInt32(reply, ret); + return; + } + + callback_ = std::make_shared(&sid); + WIFI_LOGD("create new WifiDeviceCallbackProxy!"); + ret = RegisterCallBack(callback_); + + (void)WriteInt32(reply, 0); + (void)WriteInt32(reply, ret); +} + +void WifiDeviceStub::OnGetSignalLevel(uint32_t code, IpcIo *req, IpcIo *reply) +{ + WIFI_LOGD("run %{public}s code %{public}u", __func__, code); + int rssi = 0; + int band = 0; + int level = 0; + (void)ReadInt32(req, &rssi); + (void)ReadInt32(req, &band); + ErrCode ret = GetSignalLevel(rssi, band, level); + (void)WriteInt32(reply, 0); + (void)WriteInt32(reply, ret); + if (ret == WIFI_OPT_SUCCESS) { + (void)WriteInt32(reply, level); + } +} + +void WifiDeviceStub::OnGetSupportedFeatures(uint32_t code, IpcIo *req, IpcIo *reply) +{ + WIFI_LOGD("run %{public}s code %{public}u", __func__, code); + long features = 0; + int ret = GetSupportedFeatures(features); + (void)WriteInt32(reply, 0); + (void)WriteInt32(reply, ret); + + if (ret == WIFI_OPT_SUCCESS) { + (void)WriteUint64(reply, features); + } +} + +void WifiDeviceStub::OnGetDeviceMacAdd(uint32_t code, IpcIo *req, IpcIo *reply) +{ + WIFI_LOGD("run %{public}s code %{public}u", __func__, code); + std::string strMacAddr; + ErrCode ret = GetDeviceMacAddress(strMacAddr); + (void)WriteInt32(reply, 0); + (void)WriteInt32(reply, ret); + if (ret == WIFI_OPT_SUCCESS) { + (void)WriteString(reply, strMacAddr.c_str()); + } +} + +void WifiDeviceStub::OnSetLowLatencyMode(uint32_t code, IpcIo *req, IpcIo *reply) +{ + WIFI_LOGD("run %{public}s code %{public}u", __func__, code); + + bool enabled; + (void)ReadBool(req, &enabled); + (void)WriteInt32(reply, 0); + (void)WriteInt32(reply, WIFI_OPT_SUCCESS); + (void)WriteBool(reply, SetLowLatencyMode(enabled)); +} + +void WifiDeviceStub::InitHandleMap() +{ + handleFuncMap_[WIFI_SVR_CMD_ENABLE_WIFI] = &WifiDeviceStub::OnEnableWifi; + handleFuncMap_[WIFI_SVR_CMD_DISABLE_WIFI] = &WifiDeviceStub::OnDisableWifi; + handleFuncMap_[WIFI_SVR_CMD_INIT_WIFI_PROTECT] = &WifiDeviceStub::OnInitWifiProtect; + handleFuncMap_[WIFI_SVR_CMD_GET_WIFI_PROTECT] = &WifiDeviceStub::OnGetWifiProtectRef; + handleFuncMap_[WIFI_SVR_CMD_PUT_WIFI_PROTECT] = &WifiDeviceStub::OnPutWifiProtectRef; + handleFuncMap_[WIFI_SVR_CMD_ADD_DEVICE_CONFIG] = &WifiDeviceStub::OnAddDeviceConfig; + handleFuncMap_[WIFI_SVR_CMD_UPDATE_DEVICE_CONFIG] = &WifiDeviceStub::OnUpdateDeviceConfig; + handleFuncMap_[WIFI_SVR_CMD_REMOVE_DEVICE_CONFIG] = &WifiDeviceStub::OnRemoveDevice; + handleFuncMap_[WIFI_SVR_CMD_REMOVE_ALL_DEVICE_CONFIG] = &WifiDeviceStub::OnRemoveAllDevice; + handleFuncMap_[WIFI_SVR_CMD_GET_DEVICE_CONFIGS] = &WifiDeviceStub::OnGetDeviceConfigs; + handleFuncMap_[WIFI_SVR_CMD_ENABLE_DEVICE] = &WifiDeviceStub::OnEnableDeviceConfig; + handleFuncMap_[WIFI_SVR_CMD_DISABLE_DEVICE] = &WifiDeviceStub::OnDisableDeviceConfig; + handleFuncMap_[WIFI_SVR_CMD_CONNECT_TO] = &WifiDeviceStub::OnConnectTo; + handleFuncMap_[WIFI_SVR_CMD_CONNECT2_TO] = &WifiDeviceStub::OnConnect2To; + handleFuncMap_[WIFI_SVR_CMD_RECONNECT] = &WifiDeviceStub::OnReConnect; + handleFuncMap_[WIFI_SVR_CMD_REASSOCIATE] = &WifiDeviceStub::OnReAssociate; + handleFuncMap_[WIFI_SVR_CMD_DISCONNECT] = &WifiDeviceStub::OnDisconnect; + handleFuncMap_[WIFI_SVR_CMD_START_WPS] = &WifiDeviceStub::OnStartWps; + handleFuncMap_[WIFI_SVR_CMD_CANCEL_WPS] = &WifiDeviceStub::OnCancelWps; + handleFuncMap_[WIFI_SVR_CMD_IS_WIFI_ACTIVE] = &WifiDeviceStub::OnIsWifiActive; + handleFuncMap_[WIFI_SVR_CMD_GET_WIFI_STATE] = &WifiDeviceStub::OnGetWifiState; + handleFuncMap_[WIFI_SVR_CMD_GET_LINKED_INFO] = &WifiDeviceStub::OnGetLinkedInfo; + handleFuncMap_[WIFI_SVR_CMD_GET_DHCP_INFO] = &WifiDeviceStub::OnGetIpInfo; + handleFuncMap_[WIFI_SVR_CMD_SET_COUNTRY_CODE] = &WifiDeviceStub::OnSetCountryCode; + handleFuncMap_[WIFI_SVR_CMD_GET_COUNTRY_CODE] = &WifiDeviceStub::OnGetCountryCode; + handleFuncMap_[WIFI_SVR_CMD_REGISTER_CALLBACK_CLIENT] = &WifiDeviceStub::OnRegisterCallBack; + handleFuncMap_[WIFI_SVR_CMD_GET_SIGNAL_LEVEL] = &WifiDeviceStub::OnGetSignalLevel; + handleFuncMap_[WIFI_SVR_CMD_GET_SUPPORTED_FEATURES] = &WifiDeviceStub::OnGetSupportedFeatures; + handleFuncMap_[WIFI_SVR_CMD_GET_DERVICE_MAC_ADD] = &WifiDeviceStub::OnGetDeviceMacAdd; + handleFuncMap_[WIFI_SVR_CMD_IS_WIFI_CONNECTED] = &WifiDeviceStub::OnIsWifiConnected; + handleFuncMap_[WIFI_SVR_CMD_SET_LOW_LATENCY_MODE] = &WifiDeviceStub::OnSetLowLatencyMode; +} + +int WifiDeviceStub::OnRemoteRequest(uint32_t code, IpcIo *req, IpcIo *reply) +{ + WIFI_LOGD("run: %{public}s code: %{public}u", __func__, code); + if (req == nullptr || reply == nullptr) { + WIFI_LOGD("req:%{public}d, reply:%{public}d", req == nullptr, reply == nullptr); + return ERR_FAILED; + } + int exception = 0; + (void)ReadInt32(req, &exception); + if (exception) { + (void)WriteInt32(reply, 0); + (void)WriteInt32(reply, WIFI_OPT_NOT_SUPPORTED); + return WIFI_OPT_FAILED; + } + + HandleFuncMap::iterator iter = handleFuncMap_.find(code); + if (iter == handleFuncMap_.end()) { + WIFI_LOGI("not find function to deal, code %{public}u", code); + (void)WriteInt32(reply, 0); + (void)WriteInt32(reply, WIFI_OPT_NOT_SUPPORTED); + } else { + (this->*(iter->second))(code, req, reply); + } + + return 0; +} +} // namespace Wifi +} // namespace OHOS diff --git a/wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_device_stub_lite.h b/wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_device_stub_lite.h new file mode 100644 index 0000000000000000000000000000000000000000..9372ef087a1e5e0b7c132a9f2c016d0aa982859d --- /dev/null +++ b/wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_device_stub_lite.h @@ -0,0 +1,82 @@ +/* + * Copyright (C) 2021-2022 Huawei Device Co., Ltd. + * 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 OHOS_WIFI_DEVICE_STUB_LITE_H +#define OHOS_WIFI_DEVICE_STUB_LITE_H + +#include +#include "i_wifi_device.h" +#include "i_wifi_device_callback.h" +#include "serializer.h" + +namespace OHOS { +namespace Wifi { +class WifiDeviceStub : public IWifiDevice { +public: + WifiDeviceStub(); + virtual ~WifiDeviceStub(); + + using HandleFunc = void (WifiDeviceStub::*)(uint32_t code, IpcIo *req, IpcIo *reply); + using HandleFuncMap = std::map; + + virtual int OnRemoteRequest(uint32_t code, IpcIo *req, IpcIo *reply); + +private: + void InitHandleMap(); + void OnEnableWifi(uint32_t code, IpcIo *req, IpcIo *reply); + void OnDisableWifi(uint32_t code, IpcIo *req, IpcIo *reply); + void OnInitWifiProtect(uint32_t code, IpcIo *req, IpcIo *reply); + void OnGetWifiProtectRef(uint32_t code, IpcIo *req, IpcIo *reply); + void OnPutWifiProtectRef(uint32_t code, IpcIo *req, IpcIo *reply); + void OnAddDeviceConfig(uint32_t code, IpcIo *req, IpcIo *reply); + void OnUpdateDeviceConfig(uint32_t code, IpcIo *req, IpcIo *reply); + void OnRemoveDevice(uint32_t code, IpcIo *req, IpcIo *reply); + void OnRemoveAllDevice(uint32_t code, IpcIo *req, IpcIo *reply); + void OnGetDeviceConfigs(uint32_t code, IpcIo *req, IpcIo *reply); + void OnEnableDeviceConfig(uint32_t code, IpcIo *req, IpcIo *reply); + void OnDisableDeviceConfig(uint32_t code, IpcIo *req, IpcIo *reply); + void OnConnectTo(uint32_t code, IpcIo *req, IpcIo *reply); + void OnConnect2To(uint32_t code, IpcIo *req, IpcIo *reply); + void OnReConnect(uint32_t code, IpcIo *req, IpcIo *reply); + void OnReAssociate(uint32_t code, IpcIo *req, IpcIo *reply); + void OnDisconnect(uint32_t code, IpcIo *req, IpcIo *reply); + void OnStartWps(uint32_t code, IpcIo *req, IpcIo *reply); + void OnCancelWps(uint32_t code, IpcIo *req, IpcIo *reply); + void OnIsWifiActive(uint32_t code, IpcIo *req, IpcIo *reply); + void OnGetWifiState(uint32_t code, IpcIo *req, IpcIo *reply); + void OnGetLinkedInfo(uint32_t code, IpcIo *req, IpcIo *reply); + void OnGetIpInfo(uint32_t code, IpcIo *req, IpcIo *reply); + void OnSetCountryCode(uint32_t code, IpcIo *req, IpcIo *reply); + void OnGetCountryCode(uint32_t code, IpcIo *req, IpcIo *reply); + void OnRegisterCallBack(uint32_t code, IpcIo *req, IpcIo *reply); + void OnGetSignalLevel(uint32_t code, IpcIo *req, IpcIo *reply); + void OnGetSupportedFeatures(uint32_t code, IpcIo *req, IpcIo *reply); + void OnGetDeviceMacAdd(uint32_t code, IpcIo *req, IpcIo *reply); + void OnIsWifiConnected(uint32_t code, IpcIo *req, IpcIo *reply); + void OnSetLowLatencyMode(uint32_t code, IpcIo *req, IpcIo *reply); + +private: + void ReadWifiDeviceConfig(IpcIo *req, WifiDeviceConfig &config); + void ReadIpAddress(IpcIo *req, WifiIpAddress &address); + void WriteWifiDeviceConfig(IpcIo *reply, const WifiDeviceConfig &config); + void WriteIpAddress(IpcIo *reply, const WifiIpAddress &address); + +private: + HandleFuncMap handleFuncMap_; + std::shared_ptr callback_; +}; +} // namespace Wifi +} // namespace OHOS +#endif \ No newline at end of file diff --git a/wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_dumper.cpp b/wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_dumper.cpp new file mode 100644 index 0000000000000000000000000000000000000000..e82262473484cdb137153b1f56a00effc4ee6acb --- /dev/null +++ b/wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_dumper.cpp @@ -0,0 +1,126 @@ +/* + * Copyright (C) 2021 Huawei Device Co., Ltd. + * 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 "wifi_dumper.h" +#include +#include "wifi_logger.h" + +DEFINE_WIFILOG_LABEL("WifiDumper"); +namespace OHOS { +namespace Wifi { +const std::string ARGS_HELP = "-h"; + +void WifiDumper::PrintArgs(const std::vector& vecArgs) +{ + std::string strArgs; + for (auto& each: vecArgs) { + strArgs += each + "|"; + } + WIFI_LOGD("Dumper[%{public}zu] args: %{public}s", vecArgs.size(), strArgs.c_str()); +} + +std::string WifiDumper::ShowDeviceDumpUsage() const +{ + std::string help; + return help.append("WiFi device dump options:\n") + .append(" [-h]\n") + .append(" description of the cmd option:\n") + .append(" -h: show help.\n"); +} + +bool WifiDumper::DeviceDump(std::function saBasicDumpFunc, + const std::vector& vecArgs, std::string& result) +{ + PrintArgs(vecArgs); + result.clear(); + if (!vecArgs.empty() && vecArgs[0] == ARGS_HELP) { + result = ShowDeviceDumpUsage(); + return true; + } + + saBasicDumpFunc(result); + return true; +} + +std::string WifiDumper::ShowScanDumpUsage() const +{ + std::string help; + return help.append("WiFi scan dump options:\n") + .append(" [-h]\n") + .append(" description of the cmd option:\n") + .append(" -h: show help.\n"); +} + +bool WifiDumper::ScanDump(std::function saBasicDumpFunc, + const std::vector& vecArgs, std::string& result) +{ + PrintArgs(vecArgs); + result.clear(); + if (!vecArgs.empty() && vecArgs[0] == ARGS_HELP) { + result = ShowScanDumpUsage(); + return true; + } + + saBasicDumpFunc(result); + return true; +} + +std::string WifiDumper::ShowP2pDumpUsage() const +{ + std::string help; + return help.append("WiFi P2P dump options:\n") + .append(" [-h]\n") + .append(" description of the cmd option:\n") + .append(" -h: show help.\n"); +} + +bool WifiDumper::P2pDump(std::function saBasicDumpFunc, + const std::vector& vecArgs, std::string& result) +{ + PrintArgs(vecArgs); + result.clear(); + if (!vecArgs.empty() && vecArgs[0] == ARGS_HELP) { + result = ShowP2pDumpUsage(); + return true; + } + + saBasicDumpFunc(result); + return true; +} + +std::string WifiDumper::ShowHotspotDumpUsage() const +{ + std::string help; + return help.append("WiFi hotspot dump options:\n") + .append(" [-h]\n") + .append(" description of the cmd option:\n") + .append(" -h: show help.\n"); +} + +bool WifiDumper::HotspotDump(std::function saBasicDumpFunc, + const std::vector& vecArgs, std::string& result) +{ + PrintArgs(vecArgs); + result.clear(); + if (!vecArgs.empty() && vecArgs[0] == ARGS_HELP) { + result = ShowHotspotDumpUsage(); + return true; + } + + saBasicDumpFunc(result); + return true; +} +} // namespace Wifi +} // namespace OHOS diff --git a/wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_dumper.h b/wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_dumper.h new file mode 100644 index 0000000000000000000000000000000000000000..f960281cf9cf74fc89f2f3847e3aa166090d70db --- /dev/null +++ b/wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_dumper.h @@ -0,0 +1,47 @@ +/* + * Copyright (C) 2021 Huawei Device Co., Ltd. + * 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 OHOS_WIFI_DUMPER_H +#define OHOS_WIFI_DUMPER_H + +#include +#include + +namespace OHOS { +namespace Wifi { +class WifiDumper { +public: + bool DeviceDump(std::function saBasicDumpFunc, + const std::vector &vecArgs, std::string &result); + + bool ScanDump(std::function saBasicDumpFunc, + const std::vector &vecArgs, std::string &result); + + bool P2pDump(std::function saBasicDumpFunc, + const std::vector &vecArgs, std::string &result); + + bool HotspotDump(std::function saBasicDumpFunc, + const std::vector &vecArgs, std::string &result); + +private: + std::string ShowDeviceDumpUsage() const; + std::string ShowScanDumpUsage() const; + std::string ShowP2pDumpUsage() const; + std::string ShowHotspotDumpUsage() const; + void PrintArgs(const std::vector& vecArgs); +}; +} // namespace Wifi +} // namespace OHOS +#endif \ No newline at end of file diff --git a/services/wifi_standard/wifi_framework/wifi_manage/wifi_hotspot_callback_proxy.cpp b/wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_hotspot_callback_proxy.cpp similarity index 86% rename from services/wifi_standard/wifi_framework/wifi_manage/wifi_hotspot_callback_proxy.cpp rename to wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_hotspot_callback_proxy.cpp index 74a18808fae158de574fe8a16734d79f99a046a9..d75ca9399b066060b0e712b4c4696a66829668b2 100644 --- a/services/wifi_standard/wifi_framework/wifi_manage/wifi_hotspot_callback_proxy.cpp +++ b/wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_hotspot_callback_proxy.cpp @@ -1,5 +1,5 @@ /* - * Copyright (C) 2021 Huawei Device Co., Ltd. + * Copyright (C) 2021-2022 Huawei Device Co., Ltd. * 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 @@ -30,9 +30,12 @@ void WifiHotspotCallbackProxy::OnHotspotStateChanged(int state) MessageOption option; MessageParcel data; MessageParcel reply; + if (!data.WriteInterfaceToken(GetDescriptor())) { + WIFI_LOGE("Write interface token error: %{public}s", __func__); + return; + } data.WriteInt32(0); data.WriteInt32(state); - int error = Remote()->SendRequest(WIFI_CBK_CMD_HOTSPOT_STATE_CHANGE, data, reply, option); if (error != ERR_NONE) { WIFI_LOGE("Set Attr(%{public}d) failed,error code is %{public}d", WIFI_CBK_CMD_HOTSPOT_STATE_CHANGE, error); @@ -52,6 +55,10 @@ void WifiHotspotCallbackProxy::OnHotspotStaJoin(const StationInfo &info) MessageOption option; MessageParcel data; MessageParcel reply; + if (!data.WriteInterfaceToken(GetDescriptor())) { + WIFI_LOGE("Write interface token error: %{public}s", __func__); + return; + } data.WriteInt32(0); data.WriteCString(info.deviceName.c_str()); data.WriteCString(info.bssid.c_str()); @@ -65,7 +72,6 @@ void WifiHotspotCallbackProxy::OnHotspotStaJoin(const StationInfo &info) if (exception) { WIFI_LOGE("notify wifi hotspot join failed!"); } - return; } @@ -75,6 +81,10 @@ void WifiHotspotCallbackProxy::OnHotspotStaLeave(const StationInfo &info) MessageOption option; MessageParcel data; MessageParcel reply; + if (!data.WriteInterfaceToken(GetDescriptor())) { + WIFI_LOGE("Write interface token error: %{public}s", __func__); + return; + } data.WriteInt32(0); data.WriteCString(info.deviceName.c_str()); data.WriteCString(info.bssid.c_str()); diff --git a/services/wifi_standard/wifi_framework/wifi_manage/wifi_hotspot_callback_proxy.h b/wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_hotspot_callback_proxy.h similarity index 100% rename from services/wifi_standard/wifi_framework/wifi_manage/wifi_hotspot_callback_proxy.h rename to wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_hotspot_callback_proxy.h diff --git a/services/wifi_standard/wifi_framework/wifi_manage/wifi_hotspot_death_recipient.cpp b/wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_hotspot_death_recipient.cpp similarity index 94% rename from services/wifi_standard/wifi_framework/wifi_manage/wifi_hotspot_death_recipient.cpp rename to wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_hotspot_death_recipient.cpp index f8de93325094c46a9fed09a9ceb1c02249fedadd..e24ef8f3a17f42d1aee653ecbf7264807b622708 100644 --- a/services/wifi_standard/wifi_framework/wifi_manage/wifi_hotspot_death_recipient.cpp +++ b/wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_hotspot_death_recipient.cpp @@ -21,7 +21,7 @@ namespace OHOS { namespace Wifi { void WifiHotspotDeathRecipient::OnRemoteDied(const wptr& remoteObject) { - WIFI_LOGD("WifiHotspotDeathRecipient::OnRemoteDied!"); + WIFI_LOGI("WifiHotspotDeathRecipient::OnRemoteDied!"); WifiInternalEventDispatcher::GetInstance().RemoveHotspotCallback(remoteObject.promote()); } } // namespace Wifi diff --git a/services/wifi_standard/wifi_framework/wifi_manage/wifi_hotspot_death_recipient.h b/wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_hotspot_death_recipient.h similarity index 100% rename from services/wifi_standard/wifi_framework/wifi_manage/wifi_hotspot_death_recipient.h rename to wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_hotspot_death_recipient.h diff --git a/wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_hotspot_mgr_service_impl.cpp b/wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_hotspot_mgr_service_impl.cpp new file mode 100644 index 0000000000000000000000000000000000000000..dffd84e74a258234ac712355fb21a53d71bdeb24 --- /dev/null +++ b/wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_hotspot_mgr_service_impl.cpp @@ -0,0 +1,164 @@ +/* + * Copyright (C) 2022 Huawei Device Co., Ltd. + * 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 "wifi_logger.h" +#include "wifi_config_center.h" +#include "wifi_dumper.h" +#include "wifi_manager.h" +#include "wifi_hotspot_mgr_service_impl.h" +#include "wifi_hotspot_service_impl.h" + +DEFINE_WIFILOG_HOTSPOT_LABEL("WifiHotspotMgrServiceImpl"); + +namespace OHOS { +namespace Wifi { +std::mutex WifiHotspotMgrServiceImpl::g_instanceLock; +sptr WifiHotspotMgrServiceImpl::g_instance; +const bool REGISTER_RESULT = SystemAbility::MakeAndRegisterAbility( + WifiHotspotMgrServiceImpl::GetInstance().GetRefPtr()); + +sptr WifiHotspotMgrServiceImpl::GetInstance() +{ + if (g_instance == nullptr) { + std::lock_guard autoLock(g_instanceLock); + if (g_instance == nullptr) { + auto service = new (std::nothrow) WifiHotspotMgrServiceImpl; + g_instance = service; + } + } + return g_instance; +} + +WifiHotspotMgrServiceImpl::WifiHotspotMgrServiceImpl() + : SystemAbility(WIFI_HOTSPOT_ABILITY_ID, true), mPublishFlag(false), mState(ServiceRunningState::STATE_NOT_START) +{} + +WifiHotspotMgrServiceImpl::~WifiHotspotMgrServiceImpl() +{} + +bool IsProcessNeedToRestart() +{ + sptr instancePtr = WifiHotspotMgrServiceImpl::GetInstance(); + if (instancePtr == nullptr) { + return false; + } + for (auto it = instancePtr->mWifiService.begin(); it != instancePtr->mWifiService.end(); it++) { + int id = it->first; + if (WifiConfigCenter::GetInstance().GetApMidState(id) == WifiOprMidState::RUNNING) { + return true; + } + } + return false; +} + +void SigHandler(int sig) +{ + WIFI_LOGI("[Ap] Recv SIG: %{public}d\n", sig); + switch (sig) { + case SIGUSR2: + if (IsProcessNeedToRestart()) { + IApServiceCallbacks cb = WifiManager::GetInstance().GetApCallback(); + sptr instancePtr = WifiHotspotMgrServiceImpl::GetInstance(); + if (cb.OnApStateChangedEvent != nullptr && instancePtr != nullptr) { + for (auto it = instancePtr->mWifiService.begin(); it != instancePtr->mWifiService.end(); it++) { + int id = it->first; + cb.OnApStateChangedEvent(ApState::AP_STATE_IDLE, id); + } + } + WIFI_LOGE("[AP] --------------Abort process to restart!!!--------------\n"); + abort(); + } + break; + + default: + break; + } +} + +void WifiHotspotMgrServiceImpl::OnStart() +{ + if (mState == ServiceRunningState::STATE_RUNNING) { + WIFI_LOGW("Service has already started."); + return; + } + if (!Init()) { + WIFI_LOGE("Failed to init service"); + OnStop(); + return; + } + (void)signal(SIGUSR2, SigHandler); + mState = ServiceRunningState::STATE_RUNNING; + WIFI_LOGI("Start ap service!"); + WifiManager::GetInstance().AddSupportedFeatures(WifiFeatures::WIFI_FEATURE_MOBILE_HOTSPOT); +} + +void WifiHotspotMgrServiceImpl::OnStop() +{ + mState = ServiceRunningState::STATE_NOT_START; + mPublishFlag = false; + WIFI_LOGI("Stop ap service!"); +} + +bool WifiHotspotMgrServiceImpl::Init() +{ + if (!mPublishFlag) { + for (int i = 0; i < AP_INSTANCE_MAX_NUM; i++) { + sptr wifi = new WifiHotspotServiceImpl(i); + if (wifi == nullptr) { + WIFI_LOGE("create ap hotspot service id %{public}d failed!", i); + return false; + } + mWifiService[i] = wifi->AsObject(); + } + + bool ret = Publish(WifiHotspotMgrServiceImpl::GetInstance()); + if (!ret) { + WIFI_LOGE("Failed to publish hotspot service!"); + return false; + } + mPublishFlag = true; + } + return true; +} + +sptr WifiHotspotMgrServiceImpl::GetWifiRemote(int id) +{ + auto iter = mWifiService.find(id); + if (iter != mWifiService.end()) { + return mWifiService[id]; + } + return nullptr; +} + +int32_t WifiHotspotMgrServiceImpl::Dump(int32_t fd, const std::vector& args) +{ + WIFI_LOGI("Enter hotspot dump func."); + std::vector vecArgs; + std::transform(args.begin(), args.end(), std::back_inserter(vecArgs), [](const std::u16string &arg) { + return Str16ToStr8(arg); + }); + + WifiDumper dumper; + std::string result; + dumper.HotspotDump(WifiHotspotServiceImpl::SaBasicDump, vecArgs, result); + if (!SaveStringToFd(fd, result)) { + WIFI_LOGE("WiFi hotspot save string to fd failed."); + return ERR_OK; + } + return ERR_OK; +} +} // namespace Wifi +} // namespace OHOS diff --git a/services/wifi_standard/wifi_framework/wifi_manage/wifi_sta/sta_network_speed.h b/wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_hotspot_mgr_service_impl.h similarity index 34% rename from services/wifi_standard/wifi_framework/wifi_manage/wifi_sta/sta_network_speed.h rename to wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_hotspot_mgr_service_impl.h index d19abdaf92b158e897086e80bee066d9d95922ab..5c180a0f3b5fca7ec909ae94d9a041ca8e57dac0 100644 --- a/services/wifi_standard/wifi_framework/wifi_manage/wifi_sta/sta_network_speed.h +++ b/wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_hotspot_mgr_service_impl.h @@ -1,5 +1,5 @@ /* - * Copyright (C) 2021 Huawei Device Co., Ltd. + * Copyright (C) 2022 Huawei Device Co., Ltd. * 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 @@ -13,57 +13,51 @@ * limitations under the License. */ -#ifndef OHOS_WIFI_NET_SPEED_H -#define OHOS_WIFI_NET_SPEED_H +#ifndef OHOS_WIFI_HOTSPOT_MGR_SERVICE_IMPL_H +#define OHOS_WIFI_HOTSPOT_MGR_SERVICE_IMPL_H -#include -#include -#include -#include -#include "wifi_log.h" -#include "sta_define.h" +#include +#include "iremote_object.h" +#include "system_ability.h" #include "wifi_errcode.h" - -static const std::string IF_NAME = "wlan0"; -static const std::string WLAN0_NETSPEED_FILE = "/proc/net/dev"; - -static const int MAXIMUM_BYTE = 1024; -static const int MAXIMUM_KILOBYTE = 1048576; - -static const int UP_TRAFFIC_INDEX = 1; -static const int REV_TRAFFIC_INDEX = 9; +#include "wifi_hotspot_mgr_stub.h" +#include "wifi_hotspot_stub.h" namespace OHOS { namespace Wifi { -class StaNetWorkSpeed { +enum ServiceRunningState { + STATE_NOT_START, + STATE_RUNNING +}; + +class WifiHotspotMgrServiceImpl : public SystemAbility, public WifiHotspotMgrStub { + DECLARE_SYSTEM_ABILITY(WifiHotspotMgrServiceImpl); public: - StaNetWorkSpeed(); - ~StaNetWorkSpeed(); + WifiHotspotMgrServiceImpl(); + virtual ~WifiHotspotMgrServiceImpl(); + static sptr GetInstance(); + void OnStart() override; + void OnStop() override; + sptr GetWifiRemote(int id) override; + /** - * @Description : Get internet speed + * @Description dump hotspot information * - * @param strRx - download speed string[out] - * @param strTx - Upload speed string [out] + * @param fd - file descriptor + * @param args - dump arguments + * @return ErrCode - operation result */ - void GetNetSpeed(std::string &strRx, std::string &strTx); + int32_t Dump(int32_t fd, const std::vector& args) override; private: - /** - * @Description : Get upload and download speed. - * - * @param rxBytes - download speed long[out] - * @param txBytes - Upload speed long [out] - * @Return success:WIFI_OPT_SUCCESS failed: WIFI_OPT_FAILED - */ - ErrCode GetTxAndRxBytes(long &rxBytes, long &txBytes); - /** - * @Description : Split string according to delimiter. - * - * @param source - Source string[in] - * @param delim - Delimiter string [in] - * @Return : Separated string vector - */ - std::vector SplitString(std::string source, const std::string delim); + bool Init(); + friend void SigHandler(int sig); + friend bool IsProcessNeedToRestart(); + static sptr g_instance; + std::map> mWifiService; + static std::mutex g_instanceLock; + bool mPublishFlag; + ServiceRunningState mState; }; } // namespace Wifi } // namespace OHOS diff --git a/wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_hotspot_mgr_stub.cpp b/wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_hotspot_mgr_stub.cpp new file mode 100644 index 0000000000000000000000000000000000000000..250f5e0c9c18aaffd3681eea64fce5f86a2b4066 --- /dev/null +++ b/wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_hotspot_mgr_stub.cpp @@ -0,0 +1,59 @@ +/* + * Copyright (C) 2022 Huawei Device Co., Ltd. + * 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 "wifi_hotspot_mgr_stub.h" +#include "wifi_logger.h" +#include "wifi_errcode.h" +DEFINE_WIFILOG_HOTSPOT_LABEL("WifiHotspotMgrStub"); + +namespace OHOS { +namespace Wifi { +WifiHotspotMgrStub::FuncHandleMap WifiHotspotMgrStub::funcHandleMap_ = { + {WIFI_MGR_GET_HOTSPOT_SERVICE, &WifiHotspotMgrStub::GetWifiRemoteInner}, +}; + +WifiHotspotMgrStub::WifiHotspotMgrStub() +{} + +WifiHotspotMgrStub::~WifiHotspotMgrStub() +{} + +int WifiHotspotMgrStub::GetWifiRemoteInner( + uint32_t code, MessageParcel &data, MessageParcel &reply, MessageOption &option) +{ + int id = data.ReadInt32(); + sptr obj = GetWifiRemote(id); + int ret = reply.WriteRemoteObject(obj); + return ret; +} + +int WifiHotspotMgrStub::OnRemoteRequest( + uint32_t code, MessageParcel &data, MessageParcel &reply, MessageOption &option) +{ + if (data.ReadInterfaceToken() != GetDescriptor()) { + WIFI_LOGE("Hotspot stub token verification error: %{public}d", code); + return WIFI_OPT_FAILED; + } + FuncHandleMap::iterator iter = funcHandleMap_.find(code); + if (iter == funcHandleMap_.end()) { + WIFI_LOGE("not find function to deal, code %{public}u", code); + return WIFI_OPT_NOT_SUPPORTED; + } else { + return (this->*(iter->second))(code, data, reply, option); + } + return 0; +} +} // namespace Wifi +} // namespace OHOS diff --git a/wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_hotspot_mgr_stub.h b/wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_hotspot_mgr_stub.h new file mode 100644 index 0000000000000000000000000000000000000000..bc0929a562d3f264fc97010a7856f27e6694df78 --- /dev/null +++ b/wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_hotspot_mgr_stub.h @@ -0,0 +1,43 @@ +/* + * Copyright (C) 2022 Huawei Device Co., Ltd. + * 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 OHOS_WIFI_HOTSPOT_MGR_SERVICE_H +#define OHOS_WIFI_HOTSPOT_MGR_SERVICE_H + +#include +#include "iremote_stub.h" +#include "message_parcel.h" +#include "message_option.h" +#include "i_wifi_hotspot_mgr.h" + +namespace OHOS { +namespace Wifi { +class WifiHotspotMgrStub : public IRemoteStub { +public: + using FuncHandle = int (WifiHotspotMgrStub::*)( + uint32_t code, MessageParcel &data, MessageParcel &reply, MessageOption &option); + using FuncHandleMap = std::map; + + WifiHotspotMgrStub(); + virtual ~WifiHotspotMgrStub(); + virtual int OnRemoteRequest(uint32_t code, MessageParcel &data, + MessageParcel &reply, MessageOption &option) override; + int GetWifiRemoteInner(uint32_t code, MessageParcel &data, + MessageParcel &reply, MessageOption &option); + static FuncHandleMap funcHandleMap_; +}; +} // namespace Wifi +} // namespace OHOS +#endif \ No newline at end of file diff --git a/services/wifi_standard/wifi_framework/wifi_manage/wifi_hotspot_service_impl.cpp b/wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_hotspot_service_impl.cpp similarity index 48% rename from services/wifi_standard/wifi_framework/wifi_manage/wifi_hotspot_service_impl.cpp rename to wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_hotspot_service_impl.cpp index fdc93ba149bb0971ec163cd95147afeeaf2ab88b..ff23be4f158f259f65d3b3cc400517a0346ed757 100644 --- a/services/wifi_standard/wifi_framework/wifi_manage/wifi_hotspot_service_impl.cpp +++ b/wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_hotspot_service_impl.cpp @@ -1,5 +1,5 @@ /* - * Copyright (C) 2021 Huawei Device Co., Ltd. + * Copyright (C) 2021-2022 Huawei Device Co., Ltd. * 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 @@ -14,6 +14,7 @@ */ #include "wifi_hotspot_service_impl.h" +#include #include "wifi_permission_utils.h" #include "wifi_global_func.h" #include "wifi_auth_center.h" @@ -24,80 +25,74 @@ #include "wifi_logger.h" #include "define.h" #include "wifi_logger.h" +#include "wifi_common_util.h" DEFINE_WIFILOG_HOTSPOT_LABEL("WifiHotspotServiceImpl"); namespace OHOS { namespace Wifi { -std::mutex WifiHotspotServiceImpl::g_instanceLock; -sptr WifiHotspotServiceImpl::g_instance; -const bool REGISTER_RESULT = SystemAbility::MakeAndRegisterAbility(WifiHotspotServiceImpl::GetInstance().GetRefPtr()); - -sptr WifiHotspotServiceImpl::GetInstance() -{ - if (g_instance == nullptr) { - std::lock_guard autoLock(g_instanceLock); - if (g_instance == nullptr) { - auto service = new (std::nothrow) WifiHotspotServiceImpl; - g_instance = service; - } - } - return g_instance; -} - WifiHotspotServiceImpl::WifiHotspotServiceImpl() - : SystemAbility(WIFI_HOTSPOT_ABILITY_ID, true), mPublishFlag(false), mState(ServiceRunningState::STATE_NOT_START) +{} + +WifiHotspotServiceImpl::WifiHotspotServiceImpl(int id) : WifiHotspotStub(id) {} WifiHotspotServiceImpl::~WifiHotspotServiceImpl() {} -void WifiHotspotServiceImpl::OnStart() +ErrCode WifiHotspotServiceImpl::IsHotspotActive(bool &bActive) { - if (mState == ServiceRunningState::STATE_RUNNING) { - WIFI_LOGD("Service has already started."); - return; - } - if (!Init()) { - WIFI_LOGE("Failed to init service"); - OnStop(); - return; - } - mState = ServiceRunningState::STATE_RUNNING; - WIFI_LOGI("Start ap service!"); - WifiManager::GetInstance().AddSupportedFeatures(WifiFeatures::WIFI_FEATURE_MOBILE_HOTSPOT); -} + WIFI_LOGI("Instance %{public}d %{public}s!", m_id, __func__); + if (WifiPermissionUtils::VerifyManageWifiHotspotPermission() == PERMISSION_DENIED) { + WIFI_LOGE("IsHotspotActive:VerifyManageWifiHotspotPermission PERMISSION_DENIED!"); + return WIFI_OPT_PERMISSION_DENIED; + } -void WifiHotspotServiceImpl::OnStop() -{ - mState = ServiceRunningState::STATE_NOT_START; - mPublishFlag = false; - WIFI_LOGI("Stop ap service!"); + bActive = IsApServiceRunning(); + return WIFI_OPT_SUCCESS; } -bool WifiHotspotServiceImpl::Init() +ErrCode WifiHotspotServiceImpl::IsHotspotDualBandSupported(bool &isSupported) { - if (!mPublishFlag) { - bool ret = Publish(WifiHotspotServiceImpl::GetInstance()); - if (!ret) { - WIFI_LOGE("Failed to publish hotspot service!"); - return false; + WIFI_LOGI("IsHotspotDualBandSupported"); + if (WifiPermissionUtils::VerifyGetWifiInfoInternalPermission() == PERMISSION_DENIED) { + WIFI_LOGE("IsHotspotDualBandSupported:VerifyGetWifiInfoInternalPermission PERMISSION_DENIED!"); + return WIFI_OPT_PERMISSION_DENIED; + } + + if (WifiPermissionUtils::VerifyManageWifiHotspotPermission() == PERMISSION_DENIED) { + WIFI_LOGE("IsHotspotDualBandSupported:VerifyManageWifiHotspotPermission PERMISSION_DENIED!"); + return WIFI_OPT_PERMISSION_DENIED; + } + + std::vector bands; + if (WifiConfigCenter::GetInstance().GetValidBands(bands) < 0) { + WIFI_LOGE("IsHotspotDualBandSupported:GetValidBands return failed!"); + return WIFI_OPT_FAILED; + } + + bool is2GSupported = false; + bool is5GSupported = false; + isSupported = false; + for (size_t i = 0; i < bands.size(); i++) { + if (bands[i] == BandType::BAND_2GHZ) { + is2GSupported = true; + } else if (bands[i] == BandType::BAND_5GHZ) { + is5GSupported = true; + } + if (is2GSupported && is5GSupported) { + isSupported = true; + break; } - mPublishFlag = true; } - return true; -} -ErrCode WifiHotspotServiceImpl::IsHotspotActive(bool &bActive) -{ - WIFI_LOGI("IsHotspotActive"); - bActive = IsApServiceRunning(); + WIFI_LOGI("2.4G band supported: %{public}d, 5G band supported: %{public}d", is2GSupported, is5GSupported); return WIFI_OPT_SUCCESS; } ErrCode WifiHotspotServiceImpl::GetHotspotState(int &state) { - WIFI_LOGI("GetHotspotState"); + WIFI_LOGI("Instance %{public}d %{public}s!", m_id, __func__); if (WifiPermissionUtils::VerifyGetWifiInfoPermission() == PERMISSION_DENIED) { WIFI_LOGE("GetHotspotState:VerifyGetWifiInfoPermission PERMISSION_DENIED!"); return WIFI_OPT_PERMISSION_DENIED; @@ -108,63 +103,87 @@ ErrCode WifiHotspotServiceImpl::GetHotspotState(int &state) return WIFI_OPT_PERMISSION_DENIED; } - state = WifiConfigCenter::GetInstance().GetHotspotState(); + state = WifiConfigCenter::GetInstance().GetHotspotState(m_id); return WIFI_OPT_SUCCESS; } ErrCode WifiHotspotServiceImpl::GetHotspotConfig(HotspotConfig &result) { - WIFI_LOGI("GetHotspotConfig"); + WIFI_LOGI("Instance %{public}d %{public}s!", m_id, __func__); if (WifiPermissionUtils::VerifyGetWifiInfoPermission() == PERMISSION_DENIED) { WIFI_LOGE("GetHotspotConfig:VerifyGetWifiInfoPermission PERMISSION_DENIED!"); return WIFI_OPT_PERMISSION_DENIED; } - WifiConfigCenter::GetInstance().GetHotspotConfig(result); + if (WifiPermissionUtils::VerifyGetWifiConfigPermission() == PERMISSION_DENIED) { + WIFI_LOGE("GetHotspotConfig:VerifyGetWifiConfigPermission PERMISSION_DENIED!"); + return WIFI_OPT_PERMISSION_DENIED; + } + + WifiConfigCenter::GetInstance().GetHotspotConfig(result, m_id); return WIFI_OPT_SUCCESS; } ErrCode WifiHotspotServiceImpl::SetHotspotConfig(const HotspotConfig &config) { - WIFI_LOGI("SetHotspotConfig band %{public}d", static_cast(config.GetBand())); + WIFI_LOGI("Instance %{public}d %{public}s band %{public}d", m_id, __func__, + static_cast(config.GetBand())); if (WifiPermissionUtils::VerifySetWifiInfoPermission() == PERMISSION_DENIED) { WIFI_LOGE("SetHotspotConfig:VerifySetWifiInfoPermission PERMISSION_DENIED!"); return WIFI_OPT_PERMISSION_DENIED; } - if (WifiPermissionUtils::VerifyWifiConnectionPermission() == PERMISSION_DENIED) { - WIFI_LOGE("SetHotspotConfig:VerifyWifiConnectionPermission PERMISSION_DENIED!"); + if (WifiPermissionUtils::VerifyGetWifiConfigPermission() == PERMISSION_DENIED) { + WIFI_LOGE("SetHotspotConfig:VerifyGetWifiConfigPermission PERMISSION_DENIED!"); return WIFI_OPT_PERMISSION_DENIED; } - if (WifiPermissionUtils::WifiPermissionUtils::VerifySetWifiConfigPermission() == PERMISSION_DENIED) { - WIFI_LOGE("SetHotspotConfig:VerifySetWifiConfigPermission PERMISSION_DENIED!"); - return WIFI_OPT_PERMISSION_DENIED; + if (!mGetChannels) { + if (!IsApServiceRunning()) { + return WIFI_OPT_AP_NOT_OPENED; + } + IApService *pService = WifiServiceManager::GetInstance().GetApServiceInst(m_id); + if (pService == nullptr) { + WIFI_LOGE("Instance %{public}d get hotspot service is null!", m_id); + return WIFI_OPT_AP_NOT_OPENED; + } + std::vector valid2GChannel; + std::vector valid5GChannel; + (void)pService->GetValidChannels(BandType::BAND_2GHZ, valid2GChannel); + (void)pService->GetValidChannels(BandType::BAND_5GHZ, valid5GChannel); + if (valid2GChannel.size() + valid5GChannel.size() == 0) { + WIFI_LOGE("Failed to get supported band and channel!"); + } else { + mGetChannels = true; + } } - std::vector bandsFromCenter; WifiConfigCenter::GetInstance().GetValidBands(bandsFromCenter); ChannelsTable channInfoFromCenter; WifiConfigCenter::GetInstance().GetValidChannels(channInfoFromCenter); HotspotConfig configFromCenter; - WifiConfigCenter::GetInstance().GetHotspotConfig(configFromCenter); + WifiConfigCenter::GetInstance().GetHotspotConfig(configFromCenter, m_id); ErrCode validRetval = IsValidHotspotConfig(config, configFromCenter, bandsFromCenter, channInfoFromCenter); if (validRetval != ErrCode::WIFI_OPT_SUCCESS) { + WIFI_LOGE("Instance %{public}d Hotspot config is invalid!", m_id); return validRetval; } WifiLinkedInfo linkInfo; WifiConfigCenter::GetInstance().GetLinkedInfo(linkInfo); + if (!linkInfo.ssid.empty() && linkInfo.ssid == config.GetSsid()) { - WIFI_LOGD("set ssid equal current linked ap ssid, no premission!"); + WIFI_LOGE("set ssid equal current linked ap ssid, no permission!"); return WIFI_OPT_INVALID_PARAM; } if (!IsApServiceRunning()) { - WifiConfigCenter::GetInstance().SetHotspotConfig(config); + WifiConfigCenter::GetInstance().SetHotspotConfig(config, m_id); + WifiSettings::GetInstance().SyncHotspotConfig(); } else { - IApService *pService = WifiServiceManager::GetInstance().GetApServiceInst(); + IApService *pService = WifiServiceManager::GetInstance().GetApServiceInst(m_id); if (pService == nullptr) { + WIFI_LOGE("Instance %{public}d get hotspot service is null!", m_id); return WIFI_OPT_AP_NOT_OPENED; } return pService->SetHotspotConfig(config); @@ -174,28 +193,39 @@ ErrCode WifiHotspotServiceImpl::SetHotspotConfig(const HotspotConfig &config) ErrCode WifiHotspotServiceImpl::GetStationList(std::vector &result) { - WIFI_LOGI("GetStationList"); - if (WifiPermissionUtils::VerifyGetWifiInfoPermission() == PERMISSION_DENIED) { - WIFI_LOGE("GetStationList:VerifyGetWifiInfoPermission PERMISSION_DENIED!"); - return WIFI_OPT_PERMISSION_DENIED; - } + WIFI_LOGI("Instance %{public}d %{public}s!", m_id, __func__); + if (WifiPermissionUtils::VerifyGetWifiInfoInternalPermission() == PERMISSION_DENIED) { + WIFI_LOGE("GetStationList:VerifyGetWifiInfoInternalPermission PERMISSION_DENIED!"); - if (WifiPermissionUtils::VerifyGetWifiLocalMacPermission() == PERMISSION_DENIED) { - WIFI_LOGE("GetStationList:VerifyGetWifiLocalMacPermission PERMISSION_DENIED!"); - return WIFI_OPT_PERMISSION_DENIED; - } + if (WifiPermissionUtils::VerifyGetWifiInfoPermission() == PERMISSION_DENIED) { + WIFI_LOGE("GetStationList:VerifyGetWifiInfoPermission PERMISSION_DENIED!"); + return WIFI_OPT_PERMISSION_DENIED; + } - if (WifiPermissionUtils::VerifyGetScanInfosPermission() == PERMISSION_DENIED) { - WIFI_LOGE("GetStationList:VerifyGetScanInfosPermission PERMISSION_DENIED!"); - return WIFI_OPT_PERMISSION_DENIED; + if (WifiPermissionUtils::VerifyGetWifiLocalMacPermission() == PERMISSION_DENIED) { + WIFI_LOGE("GetStationList:VerifyGetWifiLocalMacPermission PERMISSION_DENIED!"); + return WIFI_OPT_PERMISSION_DENIED; + } + + if (WifiPermissionUtils::VerifyGetScanInfosPermission() == PERMISSION_DENIED) { + WIFI_LOGE("GetStationList:VerifyGetScanInfosPermission PERMISSION_DENIED!"); + return WIFI_OPT_PERMISSION_DENIED; + } + + if (WifiPermissionUtils::VerifyManageWifiHotspotPermission() == PERMISSION_DENIED) { + WIFI_LOGE("GetStationList:VerifyManageWifiHotspotPermission PERMISSION_DENIED!"); + return WIFI_OPT_PERMISSION_DENIED; + } } if (!IsApServiceRunning()) { + WIFI_LOGE("Instance %{public}d hotspot service is not running!", m_id); return WIFI_OPT_AP_NOT_OPENED; } - IApService *pService = WifiServiceManager::GetInstance().GetApServiceInst(); + IApService *pService = WifiServiceManager::GetInstance().GetApServiceInst(m_id); if (pService == nullptr) { + WIFI_LOGE("Instance %{public}d get hotspot service is null!", m_id); return WIFI_OPT_AP_NOT_OPENED; } return pService->GetStationList(result); @@ -203,7 +233,8 @@ ErrCode WifiHotspotServiceImpl::GetStationList(std::vector &result) ErrCode WifiHotspotServiceImpl::DisassociateSta(const StationInfo &info) { - WIFI_LOGI("DisassociateSta device name [%{private}s]", info.deviceName.c_str()); + WIFI_LOGI("Instance %{public}d %{public}s device name [%{private}s]", m_id, __func__, + info.deviceName.c_str()); if (WifiPermissionUtils::VerifySetWifiInfoPermission() == PERMISSION_DENIED) { WIFI_LOGE("DisassociateSta:VerifySetWifiInfoPermission PERMISSION_DENIED!"); return WIFI_OPT_PERMISSION_DENIED; @@ -215,17 +246,24 @@ ErrCode WifiHotspotServiceImpl::DisassociateSta(const StationInfo &info) return WIFI_OPT_AP_NOT_OPENED; } - IApService *pService = WifiServiceManager::GetInstance().GetApServiceInst(); + IApService *pService = WifiServiceManager::GetInstance().GetApServiceInst(m_id); if (pService == nullptr) { + WIFI_LOGE("Instance %{public}d get hotspot service is null!", m_id); return WIFI_OPT_AP_NOT_OPENED; } return pService->DisconnetStation(info); } -ErrCode WifiHotspotServiceImpl::CheckCanEnableHotspot(void) +int WifiHotspotServiceImpl::CheckOperHotspotSwitchPermission(const ServiceType type) { - if (WifiPermissionUtils::VerifyWifiConnectionPermission() == PERMISSION_DENIED) { - WIFI_LOGE("EnableHotspot:VerifyWifiConnectionPermission PERMISSION_DENIED!"); + return (type == ServiceType::WIFI_EXT) ? PERMISSION_GRANTED : + WifiPermissionUtils::VerifyManageWifiHotspotPermission(); +} + +ErrCode WifiHotspotServiceImpl::CheckCanEnableHotspot(const ServiceType type) +{ + if (CheckOperHotspotSwitchPermission(type) == PERMISSION_DENIED) { + WIFI_LOGE("EnableHotspot:VerifyManageWifiHotspotPermission PERMISSION_DENIED!"); return WIFI_OPT_PERMISSION_DENIED; } @@ -237,28 +275,36 @@ ErrCode WifiHotspotServiceImpl::CheckCanEnableHotspot(void) WIFI_LOGI("current power saving mode and can not use ap, open failed!"); return WIFI_OPT_FORBID_POWSAVING; } + + WifiOprMidState curState = WifiConfigCenter::GetInstance().GetWifiMidState(); + if (curState != WifiOprMidState::CLOSED) { + WIFI_LOGI("current wifi state is %{public}d, please close sta first!", + static_cast(curState)); + return WIFI_OPT_NOT_SUPPORTED; + } return WIFI_OPT_SUCCESS; } -ErrCode WifiHotspotServiceImpl::EnableHotspot(void) +ErrCode WifiHotspotServiceImpl::EnableHotspot(const ServiceType type) { - WIFI_LOGI("EnableHotspot"); - ErrCode errCode = CheckCanEnableHotspot(); + WIFI_LOGI("current ap service is %{public}d %{public}s", m_id, __func__); + ErrCode errCode = CheckCanEnableHotspot(type); if (errCode != WIFI_OPT_SUCCESS) { return errCode; } - WifiOprMidState curState = WifiConfigCenter::GetInstance().GetApMidState(); + WifiOprMidState curState = WifiConfigCenter::GetInstance().GetApMidState(m_id); if (curState != WifiOprMidState::CLOSED) { - WIFI_LOGI("current ap state is %{public}d", static_cast(curState)); + WIFI_LOGI("current ap is %{public}d, state is %{public}d", m_id, static_cast(curState)); if (curState == WifiOprMidState::CLOSING) { /* when ap is closing, return */ return WIFI_OPT_OPEN_FAIL_WHEN_CLOSING; } else { return WIFI_OPT_OPEN_SUCC_WHEN_OPENED; } } - if (!WifiConfigCenter::GetInstance().SetApMidState(curState, WifiOprMidState::OPENING)) { - WIFI_LOGI("set ap mid state opening failed! may be other activity has been operated"); + if (!WifiConfigCenter::GetInstance().SetApMidState(curState, WifiOprMidState::OPENING, m_id)) { + WIFI_LOGI("current ap is %{public}d, set ap mid state opening failed!" + "may be other activity has been operated", m_id); return WIFI_OPT_OPEN_SUCC_WHEN_OPENED; } errCode = WIFI_OPT_FAILED; @@ -267,9 +313,9 @@ ErrCode WifiHotspotServiceImpl::EnableHotspot(void) WIFI_LOGE("Load %{public}s service failed!", WIFI_SERVICE_AP); break; } - IApService *pService = WifiServiceManager::GetInstance().GetApServiceInst(); + IApService *pService = WifiServiceManager::GetInstance().GetApServiceInst(m_id); if (pService == nullptr) { - WIFI_LOGE("Create %{public}s service failed!", WIFI_SERVICE_AP); + WIFI_LOGE("Instance %{public}d get hotspot service is null!", m_id); break; } errCode = pService->RegisterApServiceCallbacks(WifiManager::GetInstance().GetApCallback()); @@ -284,21 +330,21 @@ ErrCode WifiHotspotServiceImpl::EnableHotspot(void) } } while (false); if (errCode != WIFI_OPT_SUCCESS) { - WifiConfigCenter::GetInstance().SetApMidState(WifiOprMidState::OPENING, WifiOprMidState::CLOSED); - WifiServiceManager::GetInstance().UnloadService(WIFI_SERVICE_AP); + WifiConfigCenter::GetInstance().SetApMidState(WifiOprMidState::OPENING, WifiOprMidState::CLOSED, m_id); + WifiServiceManager::GetInstance().UnloadService(WIFI_SERVICE_AP, m_id); } return errCode; } -ErrCode WifiHotspotServiceImpl::DisableHotspot(void) +ErrCode WifiHotspotServiceImpl::DisableHotspot(const ServiceType type) { - WIFI_LOGI("DisableHotspot"); - if (WifiPermissionUtils::VerifyWifiConnectionPermission() == PERMISSION_DENIED) { - WIFI_LOGE("DisableHotspot:VerifyWifiConnectionPermission PERMISSION_DENIED!"); + WIFI_LOGI("current ap service is %{public}d %{public}s", m_id, __func__); + if (CheckOperHotspotSwitchPermission(type) == PERMISSION_DENIED) { + WIFI_LOGE("EnableHotspot:VerifyManageWifiHotspotPermission PERMISSION_DENIED!"); return WIFI_OPT_PERMISSION_DENIED; } - WifiOprMidState curState = WifiConfigCenter::GetInstance().GetApMidState(); + WifiOprMidState curState = WifiConfigCenter::GetInstance().GetApMidState(m_id); if (curState != WifiOprMidState::RUNNING) { WIFI_LOGI("current ap state is %{public}d", static_cast(curState)); if (curState == WifiOprMidState::OPENING) { /* when ap is opening, return */ @@ -307,26 +353,28 @@ ErrCode WifiHotspotServiceImpl::DisableHotspot(void) return WIFI_OPT_CLOSE_SUCC_WHEN_CLOSED; } } - if (!WifiConfigCenter::GetInstance().SetApMidState(curState, WifiOprMidState::CLOSING)) { + if (!WifiConfigCenter::GetInstance().SetApMidState(curState, WifiOprMidState::CLOSING, m_id)) { WIFI_LOGI("set ap mid state closing failed! may be other activity has been operated"); return WIFI_OPT_CLOSE_SUCC_WHEN_CLOSED; } - IApService *pService = WifiServiceManager::GetInstance().GetApServiceInst(); + IApService *pService = WifiServiceManager::GetInstance().GetApServiceInst(m_id); if (pService == nullptr) { - WifiConfigCenter::GetInstance().SetApMidState(WifiOprMidState::CLOSED); - WifiServiceManager::GetInstance().UnloadService(WIFI_SERVICE_AP); + WIFI_LOGE("Instance %{public}d get hotspot service is null!", m_id); + WifiConfigCenter::GetInstance().SetApMidState(WifiOprMidState::CLOSED, m_id); + WifiServiceManager::GetInstance().UnloadService(WIFI_SERVICE_AP, m_id); return WIFI_OPT_SUCCESS; } ErrCode ret = pService->DisableHotspot(); if (ret != WIFI_OPT_SUCCESS) { - WifiConfigCenter::GetInstance().SetApMidState(WifiOprMidState::CLOSING, WifiOprMidState::RUNNING); + WifiConfigCenter::GetInstance().SetApMidState(WifiOprMidState::CLOSING, WifiOprMidState::RUNNING, m_id); } return ret; } ErrCode WifiHotspotServiceImpl::AddBlockList(const StationInfo &info) { - WIFI_LOGI("AddBlockList, device name [%{private}s]", info.deviceName.c_str()); + WIFI_LOGI("current ap service is %{public}d %{public}s" + " device name [%{private}s]", m_id, __func__, info.deviceName.c_str()); if (WifiPermissionUtils::VerifyGetWifiInfoPermission() == PERMISSION_DENIED) { WIFI_LOGE("AddBlockList:VerifyGetWifiInfoPermission PERMISSION_DENIED!"); return WIFI_OPT_PERMISSION_DENIED; @@ -344,12 +392,13 @@ ErrCode WifiHotspotServiceImpl::AddBlockList(const StationInfo &info) return WIFI_OPT_AP_NOT_OPENED; } - if (WifiConfigCenter::GetInstance().AddBlockList(info) < 0) { + if (WifiConfigCenter::GetInstance().AddBlockList(info, m_id) < 0) { WIFI_LOGE("Add block list failed!"); return WIFI_OPT_FAILED; } - IApService *pService = WifiServiceManager::GetInstance().GetApServiceInst(); + IApService *pService = WifiServiceManager::GetInstance().GetApServiceInst(m_id); if (pService == nullptr) { + WIFI_LOGE("Instance %{public}d get hotspot service is null!", m_id); return WIFI_OPT_AP_NOT_OPENED; } return pService->AddBlockList(info); @@ -357,7 +406,8 @@ ErrCode WifiHotspotServiceImpl::AddBlockList(const StationInfo &info) ErrCode WifiHotspotServiceImpl::DelBlockList(const StationInfo &info) { - WIFI_LOGI("DelBlockList, device name [%{private}s]", info.deviceName.c_str()); + WIFI_LOGI("current ap service is %{public}d %{public}s device name [%{private}s]", + m_id, __func__, info.deviceName.c_str()); if (WifiPermissionUtils::VerifyGetWifiInfoPermission() == PERMISSION_DENIED) { WIFI_LOGE("DelBlockList:VerifyGetWifiInfoPermission PERMISSION_DENIED!"); return WIFI_OPT_PERMISSION_DENIED; @@ -373,8 +423,9 @@ ErrCode WifiHotspotServiceImpl::DelBlockList(const StationInfo &info) } if (IsApServiceRunning()) { - IApService *pService = WifiServiceManager::GetInstance().GetApServiceInst(); + IApService *pService = WifiServiceManager::GetInstance().GetApServiceInst(m_id); if (pService == nullptr) { + WIFI_LOGE("Instance %{public}d get hotspot service is null!", m_id); return WIFI_OPT_AP_NOT_OPENED; } if (pService->DelBlockList(info) != WIFI_OPT_SUCCESS) { @@ -383,7 +434,7 @@ ErrCode WifiHotspotServiceImpl::DelBlockList(const StationInfo &info) } } - if (WifiConfigCenter::GetInstance().DelBlockList(info) < 0) { + if (WifiConfigCenter::GetInstance().DelBlockList(info, m_id) < 0) { WIFI_LOGE("Delete block list failed!"); return WIFI_OPT_FAILED; } @@ -392,6 +443,7 @@ ErrCode WifiHotspotServiceImpl::DelBlockList(const StationInfo &info) ErrCode WifiHotspotServiceImpl::GetValidBands(std::vector &bands) { + WIFI_LOGI("current ap service is %{public}d %{public}s", m_id, __func__); if (WifiPermissionUtils::VerifyGetWifiInfoPermission() == PERMISSION_DENIED) { WIFI_LOGE("GetValidBands:VerifyGetWifiInfoPermission PERMISSION_DENIED!"); return WIFI_OPT_PERMISSION_DENIED; @@ -405,7 +457,8 @@ ErrCode WifiHotspotServiceImpl::GetValidBands(std::vector &bands) ErrCode WifiHotspotServiceImpl::GetValidChannels(BandType band, std::vector &validchannels) { - WIFI_LOGI("GetValidChannels band %{public}d", static_cast(band)); + WIFI_LOGI("current ap service is %{public}d %{public}s band %{public}d", + m_id, __func__, static_cast(band)); if (WifiPermissionUtils::VerifyGetWifiInfoPermission() == PERMISSION_DENIED) { WIFI_LOGE("GetValidChannels:VerifyGetWifiInfoPermission PERMISSION_DENIED!"); return WIFI_OPT_PERMISSION_DENIED; @@ -425,14 +478,14 @@ ErrCode WifiHotspotServiceImpl::GetValidChannels(BandType band, std::vector &infos) { - WIFI_LOGI("GetBlockLists"); + WIFI_LOGI("current ap service is %{public}d %{public}s", m_id, __func__); if (WifiPermissionUtils::VerifyGetWifiInfoPermission() == PERMISSION_DENIED) { WIFI_LOGE("GetBlockLists:VerifyGetWifiInfoPermission PERMISSION_DENIED!"); return WIFI_OPT_PERMISSION_DENIED; } - if (WifiConfigCenter::GetInstance().GetBlockLists(infos) < 0) { - WIFI_LOGE("Delete block list failed!"); + if (WifiConfigCenter::GetInstance().GetBlockLists(infos, m_id) < 0) { + WIFI_LOGE("Get block list failed!"); return WIFI_OPT_FAILED; } return WIFI_OPT_SUCCESS; @@ -440,7 +493,8 @@ ErrCode WifiHotspotServiceImpl::GetBlockLists(std::vector &infos) bool WifiHotspotServiceImpl::IsApServiceRunning() { - WifiOprMidState curState = WifiConfigCenter::GetInstance().GetApMidState(); + WIFI_LOGI("current ap service is %{public}d %{public}s", m_id, __func__); + WifiOprMidState curState = WifiConfigCenter::GetInstance().GetApMidState(m_id); if (curState != WifiOprMidState::RUNNING) { WIFI_LOGI("current ap state is %{public}d", static_cast(curState)); return false; @@ -450,17 +504,18 @@ bool WifiHotspotServiceImpl::IsApServiceRunning() ErrCode WifiHotspotServiceImpl::RegisterCallBack(const sptr &callback) { - WIFI_LOGI("RegisterCallBack"); + WIFI_LOGI("current ap service is %{public}d %{public}s", m_id, __func__); if (WifiPermissionUtils::VerifyWifiConnectionPermission() == PERMISSION_DENIED) { WIFI_LOGE("RegisterCallBack:VerifyWifiConnectionPermission() PERMISSION_DENIED!"); return WIFI_OPT_PERMISSION_DENIED; } - WifiInternalEventDispatcher::GetInstance().SetSingleHotspotCallback(callback); + WifiInternalEventDispatcher::GetInstance().SetSingleHotspotCallback(callback, m_id); return WIFI_OPT_SUCCESS; } ErrCode WifiHotspotServiceImpl::GetSupportedFeatures(long &features) { + WIFI_LOGI("current ap service is %{public}d %{public}s", m_id, __func__); if (WifiPermissionUtils::VerifyGetWifiInfoPermission() == PERMISSION_DENIED) { WIFI_LOGE("GetSupportedFeatures:VerifyGetWifiInfoPermission() PERMISSION_DENIED!"); return WIFI_OPT_PERMISSION_DENIED; @@ -472,5 +527,157 @@ ErrCode WifiHotspotServiceImpl::GetSupportedFeatures(long &features) } return WIFI_OPT_SUCCESS; } + +ErrCode WifiHotspotServiceImpl::GetSupportedPowerModel(std::set& setPowerModelList) +{ + WIFI_LOGI("current ap service is %{public}d %{public}s", m_id, __func__); + if (WifiPermissionUtils::VerifyGetWifiInfoPermission() == PERMISSION_DENIED) { + WIFI_LOGE("GetSupportedPowerModel:VerifyGetWifiInfoPermission() PERMISSION_DENIED!"); + return WIFI_OPT_PERMISSION_DENIED; + } + + if (!IsApServiceRunning()) { + return WIFI_OPT_AP_NOT_OPENED; + } + IApService *pService = WifiServiceManager::GetInstance().GetApServiceInst(m_id); + if (pService == nullptr) { + WIFI_LOGE("Instance %{public}d get hotspot service is null!", m_id); + return WIFI_OPT_AP_NOT_OPENED; + } + pService->GetSupportedPowerModel(setPowerModelList); + return WIFI_OPT_SUCCESS; +} + +ErrCode WifiHotspotServiceImpl::GetPowerModel(PowerModel& model) +{ + WIFI_LOGI("current ap service is %{public}d %{public}s", m_id, __func__); + if (WifiPermissionUtils::VerifyGetWifiInfoPermission() == PERMISSION_DENIED) { + WIFI_LOGE("GetPowerModel:VerifyGetWifiInfoPermission() PERMISSION_DENIED!"); + return WIFI_OPT_PERMISSION_DENIED; + } + + if (!IsApServiceRunning()) { + return WIFI_OPT_AP_NOT_OPENED; + } + IApService *pService = WifiServiceManager::GetInstance().GetApServiceInst(m_id); + if (pService == nullptr) { + WIFI_LOGE("Instance %{public}d get hotspot service is null!", m_id); + return WIFI_OPT_AP_NOT_OPENED; + } + pService->GetPowerModel(model); + return WIFI_OPT_SUCCESS; +} + +ErrCode WifiHotspotServiceImpl::SetPowerModel(const PowerModel& model) +{ + WIFI_LOGI("current ap service is %{public}d %{public}s", m_id, __func__); + if (!IsApServiceRunning()) { + return WIFI_OPT_AP_NOT_OPENED; + } + IApService *pService = WifiServiceManager::GetInstance().GetApServiceInst(m_id); + if (pService == nullptr) { + WIFI_LOGE("Instance %{public}d get hotspot service is null!", m_id); + return WIFI_OPT_AP_NOT_OPENED; + } + pService->SetPowerModel(model); + return WIFI_OPT_SUCCESS; +} + +void WifiHotspotServiceImpl::ConfigInfoDump(std::string& result) +{ + HotspotConfig config; + WifiConfigCenter::GetInstance().GetHotspotConfig(config); + std::stringstream ss; + ss << "Hotspot config: " << "\n"; + ss << " Config.ssid: " << config.GetSsid() << "\n"; + + std::map mapKeyMgmtToStr = { + {KeyMgmt::NONE, "Open"}, {KeyMgmt::WPA_PSK, "WPA_PSK"}, {KeyMgmt::WPA_EAP, "WPA_EAP"}, + {KeyMgmt::IEEE8021X, "IEEE8021X"}, {KeyMgmt::WPA2_PSK, "WPA2_PSK"}, {KeyMgmt::OSEN, "OSEN"}, + {KeyMgmt::FT_PSK, "FT_PSK"}, {KeyMgmt::FT_EAP, "FT_EAP"} + }; + + auto funcStrKeyMgmt = [&mapKeyMgmtToStr](KeyMgmt secType) { + std::map::iterator iter = mapKeyMgmtToStr.find(secType); + return (iter != mapKeyMgmtToStr.end()) ? iter->second : "Unknown"; + }; + ss << " Config.security_type: " << funcStrKeyMgmt(config.GetSecurityType()) << "\n"; + + auto funcStrBand = [](BandType band) { + std::string retStr; + switch (band) { + case BandType::BAND_2GHZ: + retStr = "2.4GHz"; + break; + case BandType::BAND_5GHZ: + retStr = "5GHz"; + break; + case BandType::BAND_ANY: + retStr = "dual-mode frequency band"; + break; + default: + retStr = "unknown band"; + } + return retStr; + }; + ss << " Config.band: " << funcStrBand(config.GetBand()) << "\n"; + ss << " Config.channel: " << config.GetChannel() << "\n"; + ss << " Config.max_conn: " << config.GetMaxConn() << "\n"; + result += "\n"; + result += ss.str(); + result += "\n"; +} + +void WifiHotspotServiceImpl::StationsInfoDump(std::string& result) +{ + IApService *pService = WifiServiceManager::GetInstance().GetApServiceInst(); + if (pService != nullptr) { + std::stringstream ss; + std::vector vecStations; + pService->GetStationList(vecStations); + ss << "Station list size: " << vecStations.size() << "\n"; + int idx = 0; + for (auto& each : vecStations) { + ++idx; + ss << " Station[" << idx << "].deviceName: " << each.deviceName << "\n"; + ss << " Station[" << idx << "].bssid: " << MacAnonymize(each.bssid) << "\n"; + ss << " Station[" << idx << "].ipAddr: " << IpAnonymize(each.ipAddr) << "\n"; + ss << "\n"; + } + result += ss.str(); + result += "\n"; + } + + std::vector vecBlockStations; + WifiConfigCenter::GetInstance().GetBlockLists(vecBlockStations); + if (!vecBlockStations.empty()) { + std::stringstream ss; + ss << "Block station list size: " << vecBlockStations.size() << "\n"; + int idx = 0; + for (auto& each : vecBlockStations) { + ++idx; + ss << " BlockStation[" << idx << "].deviceName: " << each.deviceName << "\n"; + ss << " BlockStation[" << idx << "].bssid: " << MacAnonymize(each.bssid) << "\n"; + ss << " BlockStation[" << idx << "].ipAddr: " << IpAnonymize(each.ipAddr) << "\n"; + ss << "\n"; + } + result += ss.str(); + result += "\n"; + } +} + +void WifiHotspotServiceImpl::SaBasicDump(std::string& result) +{ + WifiHotspotServiceImpl impl; + bool isActive = impl.IsApServiceRunning(); + result.append("WiFi hotspot active state: "); + std::string strActive = isActive ? "activated" : "inactive"; + result += strActive + "\n"; + + if (isActive) { + ConfigInfoDump(result); + StationsInfoDump(result); + } +} } // namespace Wifi } // namespace OHOS diff --git a/services/wifi_standard/wifi_framework/wifi_manage/wifi_hotspot_service_impl.h b/wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_hotspot_service_impl.h similarity index 71% rename from services/wifi_standard/wifi_framework/wifi_manage/wifi_hotspot_service_impl.h rename to wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_hotspot_service_impl.h index ac6379b0d9066bddb63765105b903c29c462ba3d..55050ffe2ce69262d662cead29e3fdf947f9409a 100644 --- a/services/wifi_standard/wifi_framework/wifi_manage/wifi_hotspot_service_impl.h +++ b/wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_hotspot_service_impl.h @@ -18,27 +18,15 @@ #include "wifi_ap_msg.h" #include "wifi_errcode.h" -#include "system_ability.h" #include "wifi_hotspot_stub.h" -#include "iremote_object.h" namespace OHOS { namespace Wifi { -enum ServiceRunningState { - STATE_NOT_START, - STATE_RUNNING -}; -class WifiHotspotServiceImpl : public SystemAbility, public WifiHotspotStub { -DECLARE_SYSTEM_ABILITY(WifiHotspotServiceImpl); +class WifiHotspotServiceImpl : public WifiHotspotStub { public: WifiHotspotServiceImpl(); + explicit WifiHotspotServiceImpl(int id); virtual ~WifiHotspotServiceImpl(); - - static sptr GetInstance(); - - void OnStart() override; - void OnStop() override; - /** * @Description Check whether the hotspot is active. * @@ -47,6 +35,14 @@ public: */ ErrCode IsHotspotActive(bool &bActive) override; + /** + * @Description Check whether the hotspot supports dual band. + * + * @param isSpuported - Supported / NOT supported + * @return ErrCode - operation result + */ + ErrCode IsHotspotDualBandSupported(bool &isSpuported) override; + /** * @Description Get the Hotspot Config object * @@ -92,14 +88,14 @@ public: * * @return ErrCode - operation result */ - ErrCode EnableHotspot(void) override; + ErrCode EnableHotspot(const ServiceType type = ServiceType::DEFAULT) override; /** * @Description Disable Hotspot * * @return ErrCode - operation result */ - ErrCode DisableHotspot(void) override; + ErrCode DisableHotspot(const ServiceType type = ServiceType::DEFAULT) override; /** * @Description Get the Block Lists object @@ -158,16 +154,48 @@ public: */ ErrCode GetSupportedFeatures(long &features) override; + /** + * @Description Get supported power model list + * + * @param setPowerModelList - supported power model list + * @return ErrCode - operation result + */ + ErrCode GetSupportedPowerModel(std::set& setPowerModelList) override; + + /** + * @Description Get power model + * + * @param model - current power model + * @return ErrCode - operation result + */ + ErrCode GetPowerModel(PowerModel& model) override; + + /** + * @Description Get supported power model list + * + * @param model - the model to be set + * @return ErrCode - operation result + */ + ErrCode SetPowerModel(const PowerModel& model) override; + + /** + * @Description Dump sa basic information + * + * @param result[out] - dump result + */ + static void SaBasicDump(std::string& result); + private: - bool Init(); - ErrCode CheckCanEnableHotspot(void); + ErrCode CheckCanEnableHotspot(const ServiceType type); + int CheckOperHotspotSwitchPermission(const ServiceType type); bool IsApServiceRunning(); + static void ConfigInfoDump(std::string& result); + static void StationsInfoDump(std::string& result); + static void SigHandler(int sig); + static bool IsProcessNeedToRestart(); private: - static sptr g_instance; - static std::mutex g_instanceLock; - bool mPublishFlag; - ServiceRunningState mState; + bool mGetChannels = false; }; } // namespace Wifi } // namespace OHOS diff --git a/services/wifi_standard/wifi_framework/wifi_manage/wifi_hotspot_stub.cpp b/wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_hotspot_stub.cpp similarity index 68% rename from services/wifi_standard/wifi_framework/wifi_manage/wifi_hotspot_stub.cpp rename to wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_hotspot_stub.cpp index f1453995773a821a682dfbd3552b08101339d0e4..74f0b643f8a99696d957e9bd8ea3a0075d1353a0 100644 --- a/services/wifi_standard/wifi_framework/wifi_manage/wifi_hotspot_stub.cpp +++ b/wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_hotspot_stub.cpp @@ -1,5 +1,5 @@ /* - * Copyright (C) 2021 Huawei Device Co., Ltd. + * Copyright (C) 2021-2022 Huawei Device Co., Ltd. * 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 @@ -29,6 +29,11 @@ WifiHotspotStub::WifiHotspotStub():mSingleCallback(false) InitHandleMap(); } +WifiHotspotStub::WifiHotspotStub(int id):mSingleCallback(false), m_id(id) +{ + InitHandleMap(); +} + WifiHotspotStub::~WifiHotspotStub() {} @@ -49,11 +54,20 @@ void WifiHotspotStub::InitHandleMap() handleFuncMap[WIFI_SVR_CMD_GET_VALID_CHANNELS] = &WifiHotspotStub::OnGetValidChannels; handleFuncMap[WIFI_SVR_CMD_REGISTER_HOTSPOT_CALLBACK] = &WifiHotspotStub::OnRegisterCallBack; handleFuncMap[WIFI_SVR_CMD_GET_SUPPORTED_FEATURES] = &WifiHotspotStub::OnGetSupportedFeatures; + handleFuncMap[WIFI_SVR_CMD_GET_SUPPORTED_POWER_MODEL] = &WifiHotspotStub::OnGetSupportedPowerModel; + handleFuncMap[WIFI_SVR_CMD_GET_POWER_MODEL] = &WifiHotspotStub::OnGetPowerModel; + handleFuncMap[WIFI_SVR_CMD_SET_POWER_MODEL] = &WifiHotspotStub::OnSetPowerModel; + handleFuncMap[WIFI_SVR_CMD_IS_HOTSPOT_DUAL_BAND_SUPPORTED] = &WifiHotspotStub::OnIsHotspotDualBandSupported; return; } int WifiHotspotStub::OnRemoteRequest(uint32_t code, MessageParcel &data, MessageParcel &reply, MessageOption &option) { + if (data.ReadInterfaceToken() != GetDescriptor()) { + WIFI_LOGE("Hotspot stub token verification error: %{public}d", code); + return WIFI_OPT_FAILED; + } + int exception = data.ReadInt32(); if (exception) { return WIFI_OPT_FAILED; @@ -61,7 +75,7 @@ int WifiHotspotStub::OnRemoteRequest(uint32_t code, MessageParcel &data, Message HandleFuncMap::iterator iter = handleFuncMap.find(code); if (iter == handleFuncMap.end()) { - WIFI_LOGD("not find function to deal, code %{public}u", code); + WIFI_LOGW("not find function to deal, code %{public}u", code); reply.WriteInt32(0); reply.WriteInt32(WIFI_OPT_NOT_SUPPORTED); } else { @@ -72,7 +86,7 @@ int WifiHotspotStub::OnRemoteRequest(uint32_t code, MessageParcel &data, Message void WifiHotspotStub::OnIsHotspotActive(uint32_t code, MessageParcel &data, MessageParcel &reply, MessageOption &option) { - WIFI_LOGD("run %{public}s code %{public}u, datasize %zu", __func__, code, data.GetRawDataSize()); + WIFI_LOGI("run %{public}s code %{public}u, datasize %{public}zu", __func__, code, data.GetRawDataSize()); bool bActive = false; ErrCode ret = IsHotspotActive(bActive); reply.WriteInt32(0); @@ -83,9 +97,23 @@ void WifiHotspotStub::OnIsHotspotActive(uint32_t code, MessageParcel &data, Mess return; } +void WifiHotspotStub::OnIsHotspotDualBandSupported(uint32_t code, MessageParcel &data, + MessageParcel &reply, MessageOption &option) +{ + WIFI_LOGI("run %{public}s code %{public}u, datasize %{public}zu", __func__, code, data.GetRawDataSize()); + bool isSupported = false; + ErrCode ret = IsHotspotDualBandSupported(isSupported); + reply.WriteInt32(0); + reply.WriteInt32(ret); + if (ret == WIFI_OPT_SUCCESS) { + reply.WriteInt32(isSupported ? 1 : 0); + } + return; +} + void WifiHotspotStub::OnGetApStateWifi(uint32_t code, MessageParcel &data, MessageParcel &reply, MessageOption &option) { - WIFI_LOGD("run %{public}s code %{public}u, datasize %zu", __func__, code, data.GetRawDataSize()); + WIFI_LOGD("run %{public}s code %{public}u, datasize %{public}zu", __func__, code, data.GetRawDataSize()); int state = 0; ErrCode ret = GetHotspotState(state); reply.WriteInt32(0); @@ -99,7 +127,7 @@ void WifiHotspotStub::OnGetApStateWifi(uint32_t code, MessageParcel &data, Messa void WifiHotspotStub::OnGetHotspotConfig( uint32_t code, MessageParcel &data, MessageParcel &reply, MessageOption &option) { - WIFI_LOGD("run %{public}s code %{public}u, datasize %zu", __func__, code, data.GetRawDataSize()); + WIFI_LOGD("run %{public}s code %{public}u, datasize %{public}zu", __func__, code, data.GetRawDataSize()); HotspotConfig hotspotConfig; ErrCode ret = GetHotspotConfig(hotspotConfig); @@ -119,7 +147,7 @@ void WifiHotspotStub::OnGetHotspotConfig( void WifiHotspotStub::OnSetApConfigWifi(uint32_t code, MessageParcel &data, MessageParcel &reply, MessageOption &option) { - WIFI_LOGD("run %{public}s code %{public}u, datasize %zu", __func__, code, data.GetRawDataSize()); + WIFI_LOGD("run %{public}s code %{public}u, datasize %{public}zu", __func__, code, data.GetRawDataSize()); HotspotConfig config; config.SetSsid(data.ReadCString()); config.SetSecurityType(static_cast(data.ReadInt32())); @@ -136,7 +164,7 @@ void WifiHotspotStub::OnSetApConfigWifi(uint32_t code, MessageParcel &data, Mess void WifiHotspotStub::OnGetStationList(uint32_t code, MessageParcel &data, MessageParcel &reply, MessageOption &option) { - WIFI_LOGD("run %{public}s code %{public}u, datasize %zu", __func__, code, data.GetRawDataSize()); + WIFI_LOGD("run %{public}s code %{public}u, datasize %{public}zu", __func__, code, data.GetRawDataSize()); std::vector result; ErrCode ret = GetStationList(result); @@ -157,7 +185,7 @@ void WifiHotspotStub::OnGetStationList(uint32_t code, MessageParcel &data, Messa void WifiHotspotStub::OnDisassociateSta(uint32_t code, MessageParcel &data, MessageParcel &reply, MessageOption &option) { - WIFI_LOGD("run %{public}s code %{public}u, datasize %zu", __func__, code, data.GetRawDataSize()); + WIFI_LOGD("run %{public}s code %{public}u, datasize %{public}zu", __func__, code, data.GetRawDataSize()); StationInfo info; info.deviceName = data.ReadCString(); info.bssid = data.ReadCString(); @@ -170,7 +198,7 @@ void WifiHotspotStub::OnDisassociateSta(uint32_t code, MessageParcel &data, Mess void WifiHotspotStub::OnGetValidBands(uint32_t code, MessageParcel &data, MessageParcel &reply, MessageOption &option) { - WIFI_LOGD("run %{public}s code %{public}u, datasize %zu", __func__, code, data.GetRawDataSize()); + WIFI_LOGD("run %{public}s code %{public}u, datasize %{public}zu", __func__, code, data.GetRawDataSize()); std::vector bands; ErrCode ret = GetValidBands(bands); @@ -189,7 +217,7 @@ void WifiHotspotStub::OnGetValidBands(uint32_t code, MessageParcel &data, Messag void WifiHotspotStub::OnGetValidChannels( uint32_t code, MessageParcel &data, MessageParcel &reply, MessageOption &option) { - WIFI_LOGD("run %{public}s code %{public}u, datasize %zu", __func__, code, data.GetRawDataSize()); + WIFI_LOGD("run %{public}s code %{public}u, datasize %{public}zu", __func__, code, data.GetRawDataSize()); std::vector channels; int32_t band = data.ReadInt32(); ErrCode ret = GetValidChannels(static_cast(band), channels); @@ -208,8 +236,9 @@ void WifiHotspotStub::OnGetValidChannels( void WifiHotspotStub::OnEnableWifiAp(uint32_t code, MessageParcel &data, MessageParcel &reply, MessageOption &option) { - WIFI_LOGD("run %{public}s code %{public}u, datasize %zu", __func__, code, data.GetRawDataSize()); - ErrCode ret = EnableHotspot(); + WIFI_LOGD("run %{public}s code %{public}u, datasize %{public}zu", __func__, code, data.GetRawDataSize()); + int32_t serviceType = data.ReadInt32(); + ErrCode ret = EnableHotspot(ServiceType(serviceType)); reply.WriteInt32(0); reply.WriteInt32(ret); @@ -218,8 +247,9 @@ void WifiHotspotStub::OnEnableWifiAp(uint32_t code, MessageParcel &data, Message void WifiHotspotStub::OnDisableWifiAp(uint32_t code, MessageParcel &data, MessageParcel &reply, MessageOption &option) { - WIFI_LOGD("run %{public}s code %{public}u, datasize %zu", __func__, code, data.GetRawDataSize()); - ErrCode ret = DisableHotspot(); + WIFI_LOGD("run %{public}s code %{public}u, datasize %{public}zu", __func__, code, data.GetRawDataSize()); + int32_t serviceType = data.ReadInt32(); + ErrCode ret = DisableHotspot(ServiceType(serviceType)); reply.WriteInt32(0); reply.WriteInt32(ret); @@ -228,7 +258,7 @@ void WifiHotspotStub::OnDisableWifiAp(uint32_t code, MessageParcel &data, Messag void WifiHotspotStub::OnAddBlockList(uint32_t code, MessageParcel &data, MessageParcel &reply, MessageOption &option) { - WIFI_LOGD("run %{public}s code %{public}u, datasize %zu", __func__, code, data.GetRawDataSize()); + WIFI_LOGD("run %{public}s code %{public}u, datasize %{public}zu", __func__, code, data.GetRawDataSize()); StationInfo info; info.deviceName = data.ReadCString(); info.bssid = data.ReadCString(); @@ -242,7 +272,7 @@ void WifiHotspotStub::OnAddBlockList(uint32_t code, MessageParcel &data, Message void WifiHotspotStub::OnDelBlockList(uint32_t code, MessageParcel &data, MessageParcel &reply, MessageOption &option) { - WIFI_LOGD("run %{public}s code %{public}u, datasize %zu", __func__, code, data.GetRawDataSize()); + WIFI_LOGD("run %{public}s code %{public}u, datasize %{public}zu", __func__, code, data.GetRawDataSize()); StationInfo info; info.deviceName = data.ReadCString(); info.bssid = data.ReadCString(); @@ -256,7 +286,7 @@ void WifiHotspotStub::OnDelBlockList(uint32_t code, MessageParcel &data, Message void WifiHotspotStub::OnGetBlockLists(uint32_t code, MessageParcel &data, MessageParcel &reply, MessageOption &option) { - WIFI_LOGD("run %{public}s code %{public}u, datasize %zu", __func__, code, data.GetRawDataSize()); + WIFI_LOGD("run %{public}s code %{public}u, datasize %{public}zu", __func__, code, data.GetRawDataSize()); std::vector infos; ErrCode ret = GetBlockLists(infos); reply.WriteInt32(0); @@ -277,18 +307,18 @@ void WifiHotspotStub::OnGetBlockLists(uint32_t code, MessageParcel &data, Messag void WifiHotspotStub::OnRegisterCallBack( uint32_t code, MessageParcel &data, MessageParcel &reply, MessageOption &option) { - WIFI_LOGD("run %{public}s code %{public}u, datasize %zu", __func__, code, data.GetRawDataSize()); + WIFI_LOGD("run %{public}s code %{public}u, datasize %{public}zu", __func__, code, data.GetRawDataSize()); ErrCode ret = WIFI_OPT_FAILED; do { sptr remote = data.ReadRemoteObject(); if (remote == nullptr) { - WIFI_LOGD("Failed to ReadRemoteObject!"); + WIFI_LOGE("Failed to ReadRemoteObject!"); break; } sptr callback_ = iface_cast(remote); if (callback_ == nullptr) { callback_ = new (std::nothrow) WifiHotspotCallbackProxy(remote); - WIFI_LOGD("create new WifiHotspotCallbackProxy!"); + WIFI_LOGI("create new WifiHotspotCallbackProxy!"); } if (mSingleCallback) { @@ -301,7 +331,7 @@ void WifiHotspotStub::OnRegisterCallBack( WIFI_LOGD("AddDeathRecipient!"); } if (callback_ != nullptr) { - WifiInternalEventDispatcher::GetInstance().AddHotspotCallback(remote, callback_); + WifiInternalEventDispatcher::GetInstance().AddHotspotCallback(remote, callback_, m_id); } } } while (0); @@ -325,5 +355,44 @@ void WifiHotspotStub::OnGetSupportedFeatures( return; } + +void WifiHotspotStub::OnGetSupportedPowerModel(uint32_t code, MessageParcel &data, + MessageParcel &reply, MessageOption &option) +{ + WIFI_LOGD("run %{public}s code %{public}u, datasize %{public}zu", __func__, code, data.GetRawDataSize()); + std::set setPowerModelList; + ErrCode ret = GetSupportedPowerModel(setPowerModelList); + reply.WriteInt32(0); + reply.WriteInt32(ret); + if (ret == WIFI_OPT_SUCCESS) { + int size = (int)setPowerModelList.size(); + reply.WriteInt32(size); + for (auto &powerModel : setPowerModelList) { + reply.WriteInt32(static_cast(powerModel)); + } + } + return; +} + +void WifiHotspotStub::OnGetPowerModel(uint32_t code, MessageParcel &data, MessageParcel &reply, MessageOption &option) +{ + WIFI_LOGD("run %{public}s code %{public}u, datasize %{public}zu", __func__, code, data.GetRawDataSize()); + PowerModel model; + ErrCode ret = GetPowerModel(model); + reply.WriteInt32(0); + reply.WriteInt32(ret); + reply.WriteInt32(static_cast(model)); + return; +} + +void WifiHotspotStub::OnSetPowerModel(uint32_t code, MessageParcel &data, MessageParcel &reply, MessageOption &option) +{ + WIFI_LOGD("run %{public}s code %{public}u, datasize %{public}zu", __func__, code, data.GetRawDataSize()); + PowerModel model = PowerModel(data.ReadInt32()); + ErrCode ret = SetPowerModel(model); + reply.WriteInt32(0); + reply.WriteInt32(ret); + return; +} } // namespace Wifi } // namespace OHOS diff --git a/services/wifi_standard/wifi_framework/wifi_manage/wifi_hotspot_stub.h b/wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_hotspot_stub.h similarity index 84% rename from services/wifi_standard/wifi_framework/wifi_manage/wifi_hotspot_stub.h rename to wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_hotspot_stub.h index c963af1d07dc6e2cb72e1cbbef8a99c05037db29..10d8ef623737c47ca15cd1e6e8a135c458d46884 100644 --- a/services/wifi_standard/wifi_framework/wifi_manage/wifi_hotspot_stub.h +++ b/wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_hotspot_stub.h @@ -1,5 +1,5 @@ /* - * Copyright (C) 2021 Huawei Device Co., Ltd. + * Copyright (C) 2021-2022 Huawei Device Co., Ltd. * 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 @@ -31,6 +31,7 @@ public: using HandleFuncMap = std::map; WifiHotspotStub(); + explicit WifiHotspotStub(int id); virtual ~WifiHotspotStub(); @@ -54,11 +55,17 @@ private: void OnGetValidChannels(uint32_t code, MessageParcel &data, MessageParcel &reply, MessageOption &option); void OnRegisterCallBack(uint32_t code, MessageParcel &data, MessageParcel &reply, MessageOption &option); void OnGetSupportedFeatures(uint32_t code, MessageParcel &data, MessageParcel &reply, MessageOption &option); + void OnGetSupportedPowerModel(uint32_t code, MessageParcel &data, MessageParcel &reply, MessageOption &option); + void OnGetPowerModel(uint32_t code, MessageParcel &data, MessageParcel &reply, MessageOption &option); + void OnSetPowerModel(uint32_t code, MessageParcel &data, MessageParcel &reply, MessageOption &option); + void OnIsHotspotDualBandSupported(uint32_t code, MessageParcel &data, MessageParcel &reply, MessageOption &option); private: HandleFuncMap handleFuncMap; sptr deathRecipient_; bool mSingleCallback; +protected: + int m_id; }; } // namespace Wifi } // namespace OHOS diff --git a/services/wifi_standard/wifi_framework/wifi_manage/wifi_internal_event_dispatcher.cpp b/wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_internal_event_dispatcher.cpp similarity index 78% rename from services/wifi_standard/wifi_framework/wifi_manage/wifi_internal_event_dispatcher.cpp rename to wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_internal_event_dispatcher.cpp index b69efdce718d0094469222ced5def9dbc8b55020..eeb08c4a464ba7de1b7d64c0be4e95657baf68b4 100644 --- a/services/wifi_standard/wifi_framework/wifi_manage/wifi_internal_event_dispatcher.cpp +++ b/wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_internal_event_dispatcher.cpp @@ -1,5 +1,5 @@ /* - * Copyright (C) 2021 Huawei Device Co., Ltd. + * Copyright (C) 2021-2022 Huawei Device Co., Ltd. * 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 @@ -145,48 +145,65 @@ bool WifiInternalEventDispatcher::HasScanRemote(const sptr &remot } int WifiInternalEventDispatcher::AddHotspotCallback( - const sptr &remote, const sptr &callback) + const sptr &remote, const sptr &callback, int id) { - WIFI_LOGD("WifiInternalEventDispatcher::AddHotspotCallback!"); + WIFI_LOGD("WifiInternalEventDispatcher::AddHotspotCallback, id:%{public}d", id); if (remote == nullptr || callback == nullptr) { WIFI_LOGE("remote object is null!"); return 1; } std::unique_lock lock(mHotspotCallbackMutex); - mHotspotCallbacks[remote] = callback; + auto iter = mHotspotCallbacks.find(id); + if (iter != mHotspotCallbacks.end()) { + (iter->second)[remote] = callback; + return 0; + } + HotspotCallbackMapType hotspotCallback; + hotspotCallback[remote] = callback; + mHotspotCallbacks[id] = hotspotCallback; return 0; } -int WifiInternalEventDispatcher::RemoveHotspotCallback(const sptr &remote) +int WifiInternalEventDispatcher::RemoveHotspotCallback(const sptr &remote, int id) { if (remote != nullptr) { - std::unique_lock lock(mHotspotCallbackMutex); - auto iter = mHotspotCallbacks.find(remote); + auto iter = mHotspotCallbacks.find(id); if (iter != mHotspotCallbacks.end()) { - mHotspotCallbacks.erase(iter); - WIFI_LOGD("WifiInternalEventDispatcher::RemoveHotspotCallback!"); + std::unique_lock lock(mHotspotCallbackMutex); + auto item = iter->second.find(remote); + if (item != iter->second.end()) { + iter->second.erase(item); + WIFI_LOGD("hotspot is is %{public}d WifiInternalEventDispatcher::RemoveHotspotCallback!", id); + } } } return 0; } -int WifiInternalEventDispatcher::SetSingleHotspotCallback(const sptr &callback) +int WifiInternalEventDispatcher::SetSingleHotspotCallback(const sptr &callback, int id) { - mHotspotSingleCallback = callback; + mHotspotSingleCallback[id] = callback; return 0; } -sptr WifiInternalEventDispatcher::GetSingleHotspotCallback() const +sptr WifiInternalEventDispatcher::GetSingleHotspotCallback(int id) const { - return mHotspotSingleCallback; + auto iter = mHotspotSingleCallback.find(id); + if (iter != mHotspotSingleCallback.end()) { + return iter->second; + } + return nullptr; } -bool WifiInternalEventDispatcher::HasHotspotRemote(const sptr &remote) +bool WifiInternalEventDispatcher::HasHotspotRemote(const sptr &remote, int id) { - std::unique_lock lock(mHotspotCallbackMutex); if (remote != nullptr) { - if (mHotspotCallbacks.find(remote) != mHotspotCallbacks.end()) { - return true; + auto iter = mHotspotCallbacks.find(id); + if (iter != mHotspotCallbacks.end()) { + std::unique_lock lock(mHotspotCallbackMutex); + if (iter->second.find(remote) != iter->second.end()) { + return true; + } } } return false; @@ -266,12 +283,14 @@ void WifiInternalEventDispatcher::Exit() void WifiInternalEventDispatcher::DealStaCallbackMsg( WifiInternalEventDispatcher &instance, const WifiEventCallbackMsg &msg) { + WIFI_LOGI("WifiInternalEventDispatcher:: Deal Sta Event Callback Msg: %{public}d", msg.msgCode); + switch (msg.msgCode) { case WIFI_CBK_MSG_STATE_CHANGE: WifiInternalEventDispatcher::PublishWifiStateChangedEvent(msg.msgData); break; case WIFI_CBK_MSG_CONNECTION_CHANGE: - WifiInternalEventDispatcher::PublishConnectionStateChangedEvent(msg.msgData, msg.linkInfo); + WifiInternalEventDispatcher::PublishConnStateChangedEvent(msg.msgData, msg.linkInfo); break; case WIFI_CBK_MSG_RSSI_CHANGE: WifiInternalEventDispatcher::PublishRssiValueChangedEvent(msg.msgData); @@ -302,6 +321,9 @@ void WifiInternalEventDispatcher::DealStaCallbackMsg( case WIFI_CBK_MSG_WPS_STATE_CHANGE: callback->OnWifiWpsStateChanged(msg.msgData, msg.pinCode); break; + case WIFI_CBK_MSG_DEVICE_CONFIG_CHANGE: + callback->OnDeviceConfigChanged(ConfigChange(msg.msgData)); + break; default: WIFI_LOGI("UnKnown msgcode %{public}d", msg.msgCode); break; @@ -314,6 +336,8 @@ void WifiInternalEventDispatcher::DealStaCallbackMsg( void WifiInternalEventDispatcher::DealScanCallbackMsg( WifiInternalEventDispatcher &instance, const WifiEventCallbackMsg &msg) { + WIFI_LOGI("WifiInternalEventDispatcher:: Deal Scan Event Callback Msg: %{public}d", msg.msgCode); + switch (msg.msgCode) { case WIFI_CBK_MSG_SCAN_STATE_CHANGE: WifiCommonEventHelper::PublishScanStateChangedEvent(msg.msgData, "OnScanStateChanged"); @@ -382,6 +406,9 @@ void WifiInternalEventDispatcher::InvokeDeviceCallbacks(const WifiEventCallbackM case WIFI_CBK_MSG_WPS_STATE_CHANGE: callback->OnWifiWpsStateChanged(msg.msgData, msg.pinCode); break; + case WIFI_CBK_MSG_DEVICE_CONFIG_CHANGE: + callback->OnDeviceConfigChanged(ConfigChange(msg.msgData)); + break; default: WIFI_LOGI("UnKnown msgcode %{public}d", msg.msgCode); break; @@ -391,26 +418,29 @@ void WifiInternalEventDispatcher::InvokeDeviceCallbacks(const WifiEventCallbackM void WifiInternalEventDispatcher::InvokeHotspotCallbacks(const WifiEventCallbackMsg &msg) { - HotspotCallbackMapType callbacks = mHotspotCallbacks; - HotspotCallbackMapType::iterator itr; - for (itr = callbacks.begin(); itr != callbacks.end(); itr++) { - auto callback = itr->second; - if (callback == nullptr) { - continue; - } - switch (msg.msgCode) { - case WIFI_CBK_MSG_HOTSPOT_STATE_CHANGE: - callback->OnHotspotStateChanged(msg.msgData); - break; - case WIFI_CBK_MSG_HOTSPOT_STATE_JOIN: - callback->OnHotspotStaJoin(msg.staInfo); - break; - case WIFI_CBK_MSG_HOTSPOT_STATE_LEAVE: - callback->OnHotspotStaLeave(msg.staInfo); - break; - default: - WIFI_LOGI("UnKnown msgcode %{public}d", msg.msgCode); - break; + auto iter = mHotspotCallbacks.find(msg.id); + if (iter != mHotspotCallbacks.end()) { + HotspotCallbackMapType callbacks = iter->second; + HotspotCallbackMapType::iterator itr; + for (itr = callbacks.begin(); itr != callbacks.end(); itr++) { + auto callback = itr->second; + if (callback == nullptr) { + continue; + } + switch (msg.msgCode) { + case WIFI_CBK_MSG_HOTSPOT_STATE_CHANGE: + callback->OnHotspotStateChanged(msg.msgData); + break; + case WIFI_CBK_MSG_HOTSPOT_STATE_JOIN: + callback->OnHotspotStaJoin(msg.staInfo); + break; + case WIFI_CBK_MSG_HOTSPOT_STATE_LEAVE: + callback->OnHotspotStaLeave(msg.staInfo); + break; + default: + WIFI_LOGI("UnKnown msgcode %{public}d", msg.msgCode); + break; + } } } } @@ -418,7 +448,8 @@ void WifiInternalEventDispatcher::InvokeHotspotCallbacks(const WifiEventCallback void WifiInternalEventDispatcher::DealHotspotCallbackMsg( WifiInternalEventDispatcher &instance, const WifiEventCallbackMsg &msg) { - auto callback = instance.GetSingleHotspotCallback(); + WIFI_LOGI("WifiInternalEventDispatcher:: Deal Hotspot Event Callback Msg: %{public}d", msg.msgCode); + auto callback = instance.GetSingleHotspotCallback(msg.id); if (callback != nullptr) { switch (msg.msgCode) { case WIFI_CBK_MSG_HOTSPOT_STATE_CHANGE: @@ -451,11 +482,27 @@ void WifiInternalEventDispatcher::InvokeP2pCallbacks(const WifiEventCallbackMsg } } +void WifiInternalEventDispatcher::SendConfigChangeEvent(sptr &callback, CfgInfo* cfgInfo) +{ + if (cfgInfo == nullptr) { + WIFI_LOGE("cfgInfo is nullptr"); + return; + } + callback->OnConfigChanged(cfgInfo->type, cfgInfo->data, cfgInfo->dataLen); + if (cfgInfo->data != nullptr) { + delete[] cfgInfo->data; + cfgInfo->data = nullptr; + } + delete cfgInfo; + cfgInfo = nullptr; +} + void WifiInternalEventDispatcher::SendP2pCallbackMsg(sptr &callback, const WifiEventCallbackMsg &msg) { if (callback == nullptr) { return; } + switch (msg.msgCode) { case WIFI_CBK_MSG_P2P_STATE_CHANGE: callback->OnP2pStateChanged(msg.msgData); @@ -481,6 +528,9 @@ void WifiInternalEventDispatcher::SendP2pCallbackMsg(sptr &cal case WIFI_CBK_MSG_P2P_ACTION_RESULT: callback->OnP2pActionResult(msg.p2pAction, static_cast(msg.msgData)); break; + case WIFI_CBK_MSG_CFG_CHANGE: + SendConfigChangeEvent(callback, msg.cfgInfo); + break; default: WIFI_LOGI("UnKnown msgcode %{public}d", msg.msgCode); break; @@ -491,6 +541,8 @@ void WifiInternalEventDispatcher::SendP2pCallbackMsg(sptr &cal void WifiInternalEventDispatcher::DealP2pCallbackMsg( WifiInternalEventDispatcher &instance, const WifiEventCallbackMsg &msg) { + WIFI_LOGI("WifiInternalEventDispatcher:: Deal P2P Event Callback Msg: %{public}d", msg.msgCode); + auto callback = instance.GetSingleP2pCallback(); if (callback != nullptr) { SendP2pCallbackMsg(callback, msg); @@ -499,46 +551,28 @@ void WifiInternalEventDispatcher::DealP2pCallbackMsg( return; } -void WifiInternalEventDispatcher::PublishConnectionStateChangedEvent(int state, const WifiLinkedInfo &info) +void WifiInternalEventDispatcher::PublishConnStateChangedEvent(int state, const WifiLinkedInfo &info) { std::string eventData = "Other"; switch (state) { - case int(OHOS::Wifi::ConnectionState::CONNECT_CONNECTING): - eventData = "Connecting"; - break; - case int(OHOS::Wifi::ConnectionState::CONNECT_OBTAINING_IP_FAILED): - eventData = "OBtaingIpFail"; - break; - case int(OHOS::Wifi::ConnectionState::CONNECT_AP_CONNECTED): - eventData = "ApConnecting"; - break; - case int(OHOS::Wifi::ConnectionState::CONNECT_CHECK_PORTAL): + case int(OHOS::Wifi::ConnState::CONNECTING): eventData = "Connecting"; break; - case int(OHOS::Wifi::ConnectionState::CONNECT_NETWORK_ENABLED): - eventData = "NetworkEnabled"; - break; - case int(OHOS::Wifi::ConnectionState::CONNECT_NETWORK_DISABLED): - eventData = "NetworkDisabled"; + case int(OHOS::Wifi::ConnState::CONNECTED): + eventData = "ApConnected"; break; - case int(OHOS::Wifi::ConnectionState::DISCONNECT_DISCONNECTING): - eventData = "DisconnectDisconnecting"; + case int(OHOS::Wifi::ConnState::DISCONNECTING): + eventData = "Disconnecting"; break; - case int(OHOS::Wifi::ConnectionState::DISCONNECT_DISCONNECTED): + case int(OHOS::Wifi::ConnState::DISCONNECTED): eventData = "Disconnected"; break; - case int(OHOS::Wifi::ConnectionState::CONNECT_PASSWORD_WRONG): - eventData = "ConnectPasswordWrong"; - break; - case int(OHOS::Wifi::ConnectionState::CONNECT_CONNECTING_TIMEOUT): - eventData = "ConnectingTimeout"; - break; default: { eventData = "UnknownState"; break; } } - if (!WifiCommonEventHelper::PublishConnectionStateChangedEvent(state, eventData)) { + if (!WifiCommonEventHelper::PublishConnStateChangedEvent(state, eventData)) { WIFI_LOGE("failed to publish connection state changed event!"); return; } @@ -577,14 +611,14 @@ void WifiInternalEventDispatcher::Run(WifiInternalEventDispatcher &instance) instance.mEventQue.pop_front(); lock.unlock(); WIFI_LOGD("WifiInternalEventDispatcher::Run broad cast a msg %{public}d", msg.msgCode); - if (msg.msgCode >= WIFI_CBK_MSG_STATE_CHANGE && msg.msgCode <= WIFI_CBK_MSG_WPS_STATE_CHANGE) { + if (msg.msgCode >= WIFI_CBK_MSG_STATE_CHANGE && msg.msgCode <= WIFI_CBK_MSG_MAX_INVALID_STA) { DealStaCallbackMsg(instance, msg); } else if (msg.msgCode == WIFI_CBK_MSG_SCAN_STATE_CHANGE) { DealScanCallbackMsg(instance, msg); } else if (msg.msgCode >= WIFI_CBK_MSG_HOTSPOT_STATE_CHANGE && - msg.msgCode <= WIFI_CBK_MSG_HOTSPOT_STATE_LEAVE) { + msg.msgCode <= WIFI_CBK_MSG_MAX_INVALID_HOTSPOT) { DealHotspotCallbackMsg(instance, msg); - } else if (msg.msgCode >= WIFI_CBK_MSG_P2P_STATE_CHANGE && msg.msgCode <= WIFI_CBK_MSG_P2P_ACTION_RESULT) { + } else if (msg.msgCode >= WIFI_CBK_MSG_P2P_STATE_CHANGE && msg.msgCode <= WIFI_CBK_MSG_MAX_INVALID_P2P) { DealP2pCallbackMsg(instance, msg); } else { WIFI_LOGI("UnKnown msgcode %{public}d", msg.msgCode); diff --git a/services/wifi_standard/wifi_framework/wifi_manage/wifi_internal_event_dispatcher.h b/wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_internal_event_dispatcher.h old mode 100755 new mode 100644 similarity index 89% rename from services/wifi_standard/wifi_framework/wifi_manage/wifi_internal_event_dispatcher.h rename to wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_internal_event_dispatcher.h index db3ecec93d6adb09542db26d37128a05cbd6e075..8990014eacf3b140faf50baadf94982919042d16 --- a/services/wifi_standard/wifi_framework/wifi_manage/wifi_internal_event_dispatcher.h +++ b/wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_internal_event_dispatcher.h @@ -27,8 +27,10 @@ #include #include "wifi_internal_msg.h" +#ifndef OHOS_ARCH_LITE #include "parcel.h" #include "iremote_object.h" +#endif #include "i_wifi_device_callback.h" #include "i_wifi_scan_callback.h" #include "i_wifi_hotspot_callback.h" @@ -97,11 +99,11 @@ public: sptr GetSingleScanCallback() const; int RemoveScanCallback(const sptr &remote); bool HasScanRemote(const sptr &remote); - int AddHotspotCallback(const sptr &remote, const sptr &callback); - int SetSingleHotspotCallback(const sptr &callback); - sptr GetSingleHotspotCallback() const; - int RemoveHotspotCallback(const sptr &remote); - bool HasHotspotRemote(const sptr &remote); + int AddHotspotCallback(const sptr &remote, const sptr &callback, int id = 0); + int SetSingleHotspotCallback(const sptr &callback, int id = 0); + sptr GetSingleHotspotCallback(int id) const; + int RemoveHotspotCallback(const sptr &remote, int id = 0); + bool HasHotspotRemote(const sptr &remote, int id = 0); int AddP2pCallback(const sptr &remote, const sptr &callback); int SetSingleP2pCallback(const sptr &callback); sptr GetSingleP2pCallback() const; @@ -118,9 +120,10 @@ private: static void DealHotspotCallbackMsg(WifiInternalEventDispatcher &pInstance, const WifiEventCallbackMsg &msg); static void DealP2pCallbackMsg(WifiInternalEventDispatcher &pInstance, const WifiEventCallbackMsg &msg); static void SendP2pCallbackMsg(sptr &callback, const WifiEventCallbackMsg &msg); - static void PublishConnectionStateChangedEvent(int state, const WifiLinkedInfo &info); + static void PublishConnStateChangedEvent(int state, const WifiLinkedInfo &info); static void PublishWifiStateChangedEvent(int state); static void PublishRssiValueChangedEvent(int state); + static void SendConfigChangeEvent(sptr &callback, CfgInfo* cfgInfo); private: std::thread mBroadcastThread; std::atomic mRunFlag; @@ -134,8 +137,8 @@ private: ScanCallbackMapType mScanCallbacks; sptr mScanSingleCallback; std::mutex mHotspotCallbackMutex; - HotspotCallbackMapType mHotspotCallbacks; - sptr mHotspotSingleCallback; + std::map mHotspotCallbacks; + std::map> mHotspotSingleCallback; std::mutex mP2pCallbackMutex; P2pCallbackMapType mP2pCallbacks; sptr mP2pSingleCallback; diff --git a/wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_internal_event_dispatcher_lite.cpp b/wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_internal_event_dispatcher_lite.cpp new file mode 100644 index 0000000000000000000000000000000000000000..e48de3013f94018a95fa2b4595724fc19880fa6e --- /dev/null +++ b/wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_internal_event_dispatcher_lite.cpp @@ -0,0 +1,243 @@ +/* + * Copyright (C) 2021-2022 Huawei Device Co., Ltd. + * 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 "wifi_internal_event_dispatcher_lite.h" +#include "wifi_logger.h" +#include "wifi_permission_helper.h" +#include "wifi_errcode.h" +#include "wifi_common_event_helper.h" + +DEFINE_WIFILOG_LABEL("WifiInternalEventDispatcher"); + +namespace OHOS { +namespace Wifi { +WifiInternalEventDispatcher &WifiInternalEventDispatcher::GetInstance() +{ + static WifiInternalEventDispatcher gWifiEventBroadcast; + return gWifiEventBroadcast; +} + +WifiInternalEventDispatcher::WifiInternalEventDispatcher() : mRunFlag(true) +{} + +WifiInternalEventDispatcher::~WifiInternalEventDispatcher() +{} + +int WifiInternalEventDispatcher::Init() +{ + /* first init system notify service client here ! */ + + mBroadcastThread = std::thread(WifiInternalEventDispatcher::Run, std::ref(*this)); + return 0; +} + +int WifiInternalEventDispatcher::SendSystemNotifyMsg() /* parameters */ +{ + return 0; +} + +int WifiInternalEventDispatcher::SetSingleStaCallback(const std::shared_ptr &callback) +{ + mStaSingleCallback = callback; + return 0; +} + +std::shared_ptr WifiInternalEventDispatcher::GetSingleStaCallback() const +{ + return mStaSingleCallback; +} + +int WifiInternalEventDispatcher::SetSingleScanCallback(const std::shared_ptr &callback) +{ + mScanSingleCallback = callback; + return 0; +} + +std::shared_ptr WifiInternalEventDispatcher::GetSingleScanCallback() const +{ + return mScanSingleCallback; +} + +int WifiInternalEventDispatcher::AddBroadCastMsg(const WifiEventCallbackMsg &msg) +{ + WIFI_LOGD("WifiInternalEventDispatcher::AddBroadCastMsg, msgcode %{public}d", msg.msgCode); + { + std::unique_lock lock(mMutex); + mEventQue.push_back(msg); + } + mCondition.notify_one(); + return 0; +} + +void WifiInternalEventDispatcher::Exit() +{ + if (!mRunFlag) { + return; + } + mRunFlag = false; + mCondition.notify_one(); + if (mBroadcastThread.joinable()) { + mBroadcastThread.join(); + } +} + +void WifiInternalEventDispatcher::DealStaCallbackMsg( + WifiInternalEventDispatcher &instance, const WifiEventCallbackMsg &msg) +{ + WIFI_LOGI("WifiInternalEventDispatcher:: Deal Sta Event Callback Msg: %{public}d", msg.msgCode); + + switch (msg.msgCode) { + case WIFI_CBK_MSG_STATE_CHANGE: + WifiInternalEventDispatcher::PublishWifiStateChangedEvent(msg.msgData); + break; + case WIFI_CBK_MSG_CONNECTION_CHANGE: + WifiInternalEventDispatcher::PublishConnStateChangedEvent(msg.msgData, msg.linkInfo); + break; + case WIFI_CBK_MSG_RSSI_CHANGE: + WifiInternalEventDispatcher::PublishRssiValueChangedEvent(msg.msgData); + break; + case WIFI_CBK_MSG_STREAM_DIRECTION: + break; + case WIFI_CBK_MSG_WPS_STATE_CHANGE: + break; + default: + break; + } + + auto callback = instance.GetSingleStaCallback(); + if (callback != nullptr) { + switch (msg.msgCode) { + case WIFI_CBK_MSG_STATE_CHANGE: + callback->OnWifiStateChanged(msg.msgData); + break; + case WIFI_CBK_MSG_CONNECTION_CHANGE: + callback->OnWifiConnectionChanged(msg.msgData, msg.linkInfo); + break; + case WIFI_CBK_MSG_RSSI_CHANGE: + callback->OnWifiRssiChanged(msg.msgData); + break; + case WIFI_CBK_MSG_STREAM_DIRECTION: + callback->OnStreamChanged(msg.msgData); + break; + case WIFI_CBK_MSG_WPS_STATE_CHANGE: + callback->OnWifiWpsStateChanged(msg.msgData, msg.pinCode); + break; + default: + WIFI_LOGI("UnKnown msgcode %{public}d", msg.msgCode); + break; + } + } + return; +} + +void WifiInternalEventDispatcher::DealScanCallbackMsg( + WifiInternalEventDispatcher &instance, const WifiEventCallbackMsg &msg) +{ + WIFI_LOGI("WifiInternalEventDispatcher:: Deal Scan Event Callback Msg: %{public}d", msg.msgCode); + + switch (msg.msgCode) { + case WIFI_CBK_MSG_SCAN_STATE_CHANGE: + WifiCommonEventHelper::PublishScanStateChangedEvent(msg.msgData, "OnScanStateChanged"); + break; + default: + WIFI_LOGI("UnKnown msgcode %{public}d", msg.msgCode); + break; + } + + auto callback = instance.GetSingleScanCallback(); + if (callback != nullptr) { + switch (msg.msgCode) { + case WIFI_CBK_MSG_SCAN_STATE_CHANGE: + callback->OnWifiScanStateChanged(msg.msgData); + break; + default: + break; + } + } + return; +} + +void WifiInternalEventDispatcher::PublishConnStateChangedEvent(int state, const WifiLinkedInfo &info) +{ + std::string eventData = "Other"; + switch (state) { + case int(OHOS::Wifi::ConnState::CONNECTING): + eventData = "Connecting"; + break; + case int(OHOS::Wifi::ConnState::CONNECTED): + eventData = "ApConnected"; + break; + case int(OHOS::Wifi::ConnState::DISCONNECTING): + eventData = "Disconnecting"; + break; + case int(OHOS::Wifi::ConnState::DISCONNECTED): + eventData = "Disconnected"; + break; + default: { + eventData = "UnknownState"; + break; + } + } + if (!WifiCommonEventHelper::PublishConnStateChangedEvent(state, eventData)) { + WIFI_LOGE("failed to publish connection state changed event!"); + return; + } + WIFI_LOGD("publish connection state changed event."); +} + +void WifiInternalEventDispatcher::PublishRssiValueChangedEvent(int state) +{ + if (!WifiCommonEventHelper::PublishRssiValueChangedEvent(state, "OnRssiValueChanged")) { + WIFI_LOGE("failed to publish rssi value changed event!"); + return; + } + WIFI_LOGD("publish rssi value changed event."); +} + +void WifiInternalEventDispatcher::PublishWifiStateChangedEvent(int state) +{ + if (!WifiCommonEventHelper::PublishPowerStateChangeEvent(state, "OnWifiPowerStateChanged")) { + WIFI_LOGE("failed to publish wifi state changed event!"); + return; + } + WIFI_LOGD("publish wifi state changed event."); +} + +void WifiInternalEventDispatcher::Run(WifiInternalEventDispatcher &instance) +{ + while (instance.mRunFlag) { + std::unique_lock lock(instance.mMutex); + while (instance.mEventQue.empty() && instance.mRunFlag) { + instance.mCondition.wait(lock); + } + if (!instance.mRunFlag) { + break; + } + WifiEventCallbackMsg msg = instance.mEventQue.front(); + instance.mEventQue.pop_front(); + lock.unlock(); + WIFI_LOGD("WifiInternalEventDispatcher::Run broad cast a msg %{public}d", msg.msgCode); + if (msg.msgCode >= WIFI_CBK_MSG_STATE_CHANGE && msg.msgCode <= WIFI_CBK_MSG_WPS_STATE_CHANGE) { + DealStaCallbackMsg(instance, msg); + } else if (msg.msgCode == WIFI_CBK_MSG_SCAN_STATE_CHANGE) { + DealScanCallbackMsg(instance, msg); + } else { + WIFI_LOGI("UnKnown msgcode %{public}d", msg.msgCode); + } + } + return; +} +} // namespace Wifi +} // namespace OHOS \ No newline at end of file diff --git a/wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_internal_event_dispatcher_lite.h b/wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_internal_event_dispatcher_lite.h new file mode 100644 index 0000000000000000000000000000000000000000..bcb16724616f46c17842e0d14c6e4b144afb2b03 --- /dev/null +++ b/wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_internal_event_dispatcher_lite.h @@ -0,0 +1,103 @@ +/* + * Copyright (C) 2022 Huawei Device Co., Ltd. + * 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 OHOS_WIFI_INTERNAL_EVENT_DISPATCHER_LITE_H +#define OHOS_WIFI_INTERNAL_EVENT_DISPATCHER_LITE_H + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "wifi_internal_msg.h" +#include "i_wifi_device_callback.h" +#include "i_wifi_scan_callback.h" + +namespace OHOS { +namespace Wifi { +class WifiInternalEventDispatcher { +public: + WifiInternalEventDispatcher(); + ~WifiInternalEventDispatcher(); + + /** + * @Description Init WifiInternalEventDispatcher object + * + * @return int - init result, when 0 means success, other means some fails happened + */ + int Init(); + + /** + * @Description Send system motify message + * + * @return int - init result, when 0 means success, other means some fails happened + */ + int SendSystemNotifyMsg(void); + + /** + * @Description Add broadcast events to the internal event broadcast queue + * + * @param msg - callback msg + * @return int - 0 success + */ + int AddBroadCastMsg(const WifiEventCallbackMsg &msg); + + /** + * @Description Exit event broadcast thread + * + */ + void Exit(); + + /** + * @Description Event broadcast thread processing function + * 1. Obtain broadcast events from the internal event queue + * mEventQue + * 2. Send broadcast events to handles in the application + * registration list one by one. The BpWifiCallbackService + * method will eventually be called + * + * @param p WifiInternalEventDispatcher this Object + * @return void* - nullptr, not care this now + */ + static void Run(WifiInternalEventDispatcher &instance); + + static WifiInternalEventDispatcher &GetInstance(); + int SetSingleStaCallback(const std::shared_ptr &callback); + std::shared_ptr GetSingleStaCallback() const; + int SetSingleScanCallback(const std::shared_ptr &callback); + std::shared_ptr GetSingleScanCallback() const; +private: + static void DealStaCallbackMsg(WifiInternalEventDispatcher &pInstance, const WifiEventCallbackMsg &msg); + static void DealScanCallbackMsg(WifiInternalEventDispatcher &pInstance, const WifiEventCallbackMsg &msg); + static void PublishConnStateChangedEvent(int state, const WifiLinkedInfo &info); + static void PublishWifiStateChangedEvent(int state); + static void PublishRssiValueChangedEvent(int state); +private: + std::thread mBroadcastThread; + std::atomic mRunFlag; + std::mutex mMutex; + std::condition_variable mCondition; + std::deque mEventQue; + std::shared_ptr mStaSingleCallback; + std::shared_ptr mScanSingleCallback; +}; +} // namespace Wifi +} // namespace OHOS +#endif diff --git a/services/wifi_standard/wifi_framework/wifi_manage/wifi_manager.cpp b/wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_manager.cpp old mode 100755 new mode 100644 similarity index 61% rename from services/wifi_standard/wifi_framework/wifi_manage/wifi_manager.cpp rename to wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_manager.cpp index d2dd430aa2b74ad7b936778590b8c54318dc3947..dbc5178923e234936662a993e180e487e70528b2 --- a/services/wifi_standard/wifi_framework/wifi_manage/wifi_manager.cpp +++ b/wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_manager.cpp @@ -1,5 +1,5 @@ /* - * Copyright (C) 2021 Huawei Device Co., Ltd. + * Copyright (C) 2021-2022 Huawei Device Co., Ltd. * 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 @@ -14,21 +14,26 @@ */ #include "wifi_manager.h" -#include "wifi_global_func.h" -#include "wifi_logger.h" -#include "wifi_sta_hal_interface.h" -#include "wifi_chip_hal_interface.h" +#include #include "wifi_auth_center.h" +#include "wifi_chip_hal_interface.h" +#include "wifi_common_event_helper.h" #include "wifi_config_center.h" +#include "wifi_global_func.h" +#include "wifi_logger.h" +#ifdef OHOS_ARCH_LITE +#include "wifi_internal_event_dispatcher_lite.h" +#else #include "wifi_internal_event_dispatcher.h" +#endif +#include "wifi_sta_hal_interface.h" #include "wifi_service_manager.h" #include "wifi_settings.h" -#include "wifi_common_event_helper.h" - -DEFINE_WIFILOG_LABEL("WifiManager"); namespace OHOS { namespace Wifi { +DEFINE_WIFILOG_LABEL("WifiManager"); +int WifiManager::mCloseApIndex = 0; WifiManager &WifiManager::GetInstance() { static WifiManager gWifiManager; @@ -51,6 +56,162 @@ WifiManager::WifiManager() : mInitStatus(INIT_UNKNOWN), mSupportedFeatures(0) WifiManager::~WifiManager() {} +void WifiManager::AutoStartStaService(void) +{ + WIFI_LOGI("AutoStartStaService"); + WifiOprMidState staState = WifiConfigCenter::GetInstance().GetWifiMidState(); + if (staState == WifiOprMidState::CLOSED) { + if (!WifiConfigCenter::GetInstance().SetWifiMidState(staState, WifiOprMidState::OPENING)) { + WIFI_LOGW("set sta mid state opening failed! may be other activity has been operated"); + return; + } + ErrCode errCode = WIFI_OPT_FAILED; + do { + if (WifiServiceManager::GetInstance().CheckAndEnforceService(WIFI_SERVICE_STA) < 0) { + WIFI_LOGE("Load %{public}s service failed!", WIFI_SERVICE_STA); + break; + } + IStaService *pService = WifiServiceManager::GetInstance().GetStaServiceInst(); + if (pService == nullptr) { + WIFI_LOGE("Create %{public}s service failed!", WIFI_SERVICE_STA); + break; + } + errCode = pService->RegisterStaServiceCallback(WifiManager::GetInstance().GetStaCallback()); + if (errCode != WIFI_OPT_SUCCESS) { + WIFI_LOGE("Register sta service callback failed!"); + break; + } + errCode = pService->EnableWifi(); + if (errCode != WIFI_OPT_SUCCESS) { + WIFI_LOGE("service enable sta failed, ret %{public}d!", static_cast(errCode)); + break; + } + } while (0); + if (errCode != WIFI_OPT_SUCCESS) { + WifiConfigCenter::GetInstance().SetWifiMidState(WifiOprMidState::OPENING, WifiOprMidState::CLOSED); + WifiServiceManager::GetInstance().UnloadService(WIFI_SERVICE_STA); + } + } + return; +} + +void WifiManager::ForceStopWifi(void) +{ + WIFI_LOGI("Enter ForceStopWifi"); + IStaService *pService = WifiServiceManager::GetInstance().GetStaServiceInst(); + if (pService == nullptr || (pService->DisableWifi() != WIFI_OPT_SUCCESS)) { + WIFI_LOGE("service is null or disable wifi failed."); + WifiConfigCenter::GetInstance().SetWifiMidState(WifiOprMidState::CLOSED); + WifiServiceManager::GetInstance().UnloadService(WIFI_SERVICE_STA); + return; + } + WifiOprMidState curState = WifiConfigCenter::GetInstance().GetWifiMidState(); + WIFI_LOGI("In force stop wifi, state: %{public}d", static_cast(curState)); + WifiConfigCenter::GetInstance().SetWifiMidState(curState, WifiOprMidState::CLOSED); +} + +void WifiManager::CheckAndStartSta(void) +{ + DIR *dir = nullptr; + struct dirent *dent = nullptr; + int currentWaitTime = 0; + const int sleepTime = 1; + const int maxWaitTimes = 30; + + while (currentWaitTime < maxWaitTimes) { + dir = opendir("/sys/class/net"); + if (dir == nullptr) { + AutoStartStaService(); + return; + } + while ((dent = readdir(dir)) != nullptr) { + if (dent->d_name[0] == '.') { + continue; + } + if (strncmp(dent->d_name, "wlan", strlen("wlan")) == 0) { + closedir(dir); + AutoStartStaService(); + return; + } + } + closedir(dir); + sleep(sleepTime); + currentWaitTime++; + } + AutoStartStaService(); +} + +void WifiManager::AutoStartServiceThread(void) +{ + WIFI_LOGI("Auto start service..."); + CheckAndStartSta(); +#ifdef FEATURE_P2P_SUPPORT + AutoStartP2pService(); +#endif +} + +#ifdef FEATURE_P2P_SUPPORT +WifiCfgMonitorEventCallback WifiManager::cfgMonitorCallback = { + nullptr, +}; + +void WifiManager::AutoStartP2pService(void) +{ + WIFI_LOGI("AutoStartP2pService"); + WifiOprMidState p2pState = WifiConfigCenter::GetInstance().GetP2pMidState(); + if (p2pState == WifiOprMidState::CLOSED) { + if (!WifiConfigCenter::GetInstance().SetP2pMidState(p2pState, WifiOprMidState::OPENING)) { + WIFI_LOGW("set p2p mid state opening failed!"); + return; + } + } + ErrCode ret = WIFI_OPT_FAILED; + do { + if (WifiServiceManager::GetInstance().CheckAndEnforceService(WIFI_SERVICE_P2P) < 0) { + WIFI_LOGE("Load %{public}s service failed!", WIFI_SERVICE_P2P); + break; + } + IP2pService *pService = WifiServiceManager::GetInstance().GetP2pServiceInst(); + if (pService == nullptr) { + WIFI_LOGE("Create %{public}s service failed!", WIFI_SERVICE_P2P); + break; + } + ret = pService->RegisterP2pServiceCallbacks(WifiManager::GetInstance().GetP2pCallback()); + if (ret != WIFI_OPT_SUCCESS) { + WIFI_LOGE("Register p2p service callback failed!"); + break; + } + ret = pService->EnableP2p(); + if (ret != WIFI_OPT_SUCCESS) { + WIFI_LOGE("service EnableP2p failed, ret %{public}d!", static_cast(ret)); + break; + } + } while (false); + if (ret != WIFI_OPT_SUCCESS) { + WifiConfigCenter::GetInstance().SetP2pMidState(WifiOprMidState::OPENING, WifiOprMidState::CLOSED); + WifiServiceManager::GetInstance().UnloadService(WIFI_SERVICE_P2P); + } + return; +} +#endif + +void WifiManager::AutoStartScanService(void) +{ + WIFI_LOGI("AutoStartScanService"); + if (!WifiConfigCenter::GetInstance().IsScanAlwaysActive()) { + WIFI_LOGW("Scan always is not open, not open scan service."); + return; + } + ScanControlInfo info; + WifiConfigCenter::GetInstance().GetScanControlInfo(info); + if (!IsAllowScanAnyTime(info)) { + WIFI_LOGW("Scan control does not support scan always, not open scan service here."); + return; + } + CheckAndStartScanService(); + return; +} + int WifiManager::Init() { if (WifiConfigCenter::GetInstance().Init() < 0) { @@ -78,18 +239,37 @@ int WifiManager::Init() mInitStatus = INIT_OK; InitStaCallback(); InitScanCallback(); +#ifdef FEATURE_AP_SUPPORT InitApCallback(); +#endif +#ifdef FEATURE_P2P_SUPPORT InitP2pCallback(); - if (!WifiConfigCenter::GetInstance().GetSupportedBandChannel()) { - WIFI_LOGE("Failed to get current chip supported band and channel!"); +#endif + if (WifiServiceManager::GetInstance().CheckPreLoadService() < 0) { + WIFI_LOGE("WifiServiceManager check preload feature service failed!"); + WifiManager::GetInstance().Exit(); + return -1; + } + if (WifiConfigCenter::GetInstance().GetStaLastRunState()) { /* Automatic startup upon startup */ + WIFI_LOGI("AutoStartServiceThread"); + std::thread startStaSrvThread(WifiManager::AutoStartServiceThread); + startStaSrvThread.detach(); + } else { + /** + * The sta service automatically starts upon startup. After the sta + * service is started, the scanning is directly started. + */ + AutoStartScanService(); } return 0; } void WifiManager::Exit() { + WIFI_LOGI("[WifiManager] Exit."); WifiServiceManager::GetInstance().UninstallAllService(); - WifiStaHalInterface::GetInstance().ExitAllIdlClient(); + /* NOTE:: DO NOT allow call hal interface function, delete at 2022.10.16 */ + /* Refer to WifiStaHalInterface::GetInstance().ExitAllIdlClient(); */ WifiInternalEventDispatcher::GetInstance().Exit(); if (mCloseServiceThread.joinable()) { PushServiceCloseMsg(WifiCloseServiceCode::SERVICE_THREAD_EXIT); @@ -113,11 +293,6 @@ void WifiManager::AddSupportedFeatures(WifiFeatures feature) int WifiManager::GetSupportedFeatures(long &features) { - int capability = 0; - if (WifiChipHalInterface::GetInstance().GetChipCapabilities(capability) != WIFI_IDL_OPT_OK) { - WIFI_LOGE("Failed to get chip capability!"); - return -1; - } long supportedFeatures = mSupportedFeatures; supportedFeatures |= static_cast(WifiFeatures::WIFI_FEATURE_INFRA); supportedFeatures |= static_cast(WifiFeatures::WIFI_FEATURE_INFRA_5G); @@ -126,7 +301,9 @@ int WifiManager::GetSupportedFeatures(long &features) supportedFeatures |= static_cast(WifiFeatures::WIFI_FEATURE_WPA3_SAE); supportedFeatures |= static_cast(WifiFeatures::WIFI_FEATURE_WPA3_SUITE_B); supportedFeatures |= static_cast(WifiFeatures::WIFI_FEATURE_OWE); - features = (supportedFeatures & capability); + /* NOTE: features = supportedFeatures & WifiChipHalInterface::GetInstance().GetChipCapabilities */ + /* It does NOT allow call HalInterface from wifi_manager */ + features = supportedFeatures; return 0; } @@ -137,34 +314,38 @@ InitStatus WifiManager::GetInitStatus() void WifiManager::CloseStaService(void) { - WIFI_LOGD("close sta service"); + WIFI_LOGI("close sta service"); WifiServiceManager::GetInstance().UnloadService(WIFI_SERVICE_STA); WifiConfigCenter::GetInstance().SetWifiMidState(WifiOprMidState::CLOSED); WifiConfigCenter::GetInstance().SetWifiStaCloseTime(); return; } -void WifiManager::CloseApService(void) +#ifdef FEATURE_AP_SUPPORT +void WifiManager::CloseApService(int id) { - WIFI_LOGD("close ap service"); - WifiServiceManager::GetInstance().UnloadService(WIFI_SERVICE_AP); - WifiConfigCenter::GetInstance().SetApMidState(WifiOprMidState::CLOSED); - WifiSettings::GetInstance().SetHotspotState(static_cast(ApState::AP_STATE_CLOSED)); + WIFI_LOGI("close %{public}d ap service", id); + WifiServiceManager::GetInstance().UnloadService(WIFI_SERVICE_AP, id); + WifiConfigCenter::GetInstance().SetApMidState(WifiOprMidState::CLOSED, id); + WifiSettings::GetInstance().SetHotspotState(static_cast(ApState::AP_STATE_CLOSED), id); WifiEventCallbackMsg cbMsg; cbMsg.msgCode = WIFI_CBK_MSG_HOTSPOT_STATE_CHANGE; cbMsg.msgData = static_cast(ApState::AP_STATE_CLOSED); + cbMsg.id = id; WifiInternalEventDispatcher::GetInstance().AddBroadCastMsg(cbMsg); return; } +#endif void WifiManager::CloseScanService(void) { - WIFI_LOGD("close scan service"); + WIFI_LOGI("close scan service"); WifiServiceManager::GetInstance().UnloadService(WIFI_SERVICE_SCAN); WifiConfigCenter::GetInstance().SetScanMidState(WifiOprMidState::CLOSED); return; } +#ifdef FEATURE_P2P_SUPPORT void WifiManager::CloseP2pService(void) { WIFI_LOGD("close p2p service"); @@ -177,6 +358,7 @@ void WifiManager::CloseP2pService(void) WifiInternalEventDispatcher::GetInstance().AddBroadCastMsg(cbMsg); return; } +#endif void WifiManager::DealCloseServiceMsg(WifiManager &manager) { @@ -197,17 +379,21 @@ void WifiManager::DealCloseServiceMsg(WifiManager &manager) case WifiCloseServiceCode::SCAN_SERVICE_CLOSE: CloseScanService(); break; +#ifdef FEATURE_AP_SUPPORT case WifiCloseServiceCode::AP_SERVICE_CLOSE: - CloseApService(); + CloseApService(mCloseApIndex); break; +#endif +#ifdef FEATURE_P2P_SUPPORT case WifiCloseServiceCode::P2P_SERVICE_CLOSE: CloseP2pService(); break; +#endif case WifiCloseServiceCode::SERVICE_THREAD_EXIT: - WIFI_LOGD("DealCloseServiceMsg thread exit!"); + WIFI_LOGI("DealCloseServiceMsg thread exit!"); return; default: - WIFI_LOGD("Unknown message code, %{public}d", static_cast(msg)); + WIFI_LOGW("Unknown message code, %{public}d", static_cast(msg)); break; } } @@ -233,37 +419,35 @@ StaServiceCallback WifiManager::GetStaCallback() void WifiManager::DealStaOpenRes(OperateResState state) { + WIFI_LOGI("Enter DealStaOpenRes: %{public}d", static_cast(state)); WifiEventCallbackMsg cbMsg; cbMsg.msgCode = WIFI_CBK_MSG_STATE_CHANGE; - if (state == OperateResState::OPEN_WIFI_FAILED) { - WIFI_LOGD("DealStaOpenRes:upload wifi open failed event!"); - cbMsg.msgData = static_cast(WifiState::UNKNOWN); - WifiInternalEventDispatcher::GetInstance().AddBroadCastMsg(cbMsg); - } else if (state == OperateResState::OPEN_WIFI_OPENING) { + if (state == OperateResState::OPEN_WIFI_OPENING) { cbMsg.msgData = static_cast(WifiState::ENABLING); WifiInternalEventDispatcher::GetInstance().AddBroadCastMsg(cbMsg); - } else if (state == OperateResState::OPEN_WIFI_DISABLED) { - WIFI_LOGD("DealStaOpenRes:wifi open failed,close wifi sta service!"); + return; + } + if ((state == OperateResState::OPEN_WIFI_FAILED) || (state == OperateResState::OPEN_WIFI_DISABLED)) { + WIFI_LOGE("DealStaOpenRes:wifi open failed!"); + WifiConfigCenter::GetInstance().SetWifiMidState(WifiOprMidState::OPENING, WifiOprMidState::CLOSED); DealStaCloseRes(state); - } else { - WIFI_LOGD("DealStaOpenRes:wifi open successfully!"); - WifiConfigCenter::GetInstance().SetWifiMidState(WifiOprMidState::OPENING, WifiOprMidState::RUNNING); - WifiConfigCenter::GetInstance().SetStaLastRunState(true); - if (WifiConfigCenter::GetInstance().GetAirplaneModeState() == 1) { - WifiConfigCenter::GetInstance().SetWifiStateWhenAirplaneMode(true); - } - - cbMsg.msgData = static_cast(WifiState::ENABLED); - WifiInternalEventDispatcher::GetInstance().AddBroadCastMsg(cbMsg); - - CheckAndStartScanService(); + return; } - return; + WIFI_LOGI("DealStaOpenRes:wifi open successfully!"); + WifiConfigCenter::GetInstance().SetWifiMidState(WifiOprMidState::OPENING, WifiOprMidState::RUNNING); + WifiConfigCenter::GetInstance().SetStaLastRunState(true); + if (WifiConfigCenter::GetInstance().GetAirplaneModeState() == 1) { + WifiConfigCenter::GetInstance().SetWifiStateWhenAirplaneMode(true); + } + cbMsg.msgData = static_cast(WifiState::ENABLED); + WifiInternalEventDispatcher::GetInstance().AddBroadCastMsg(cbMsg); + CheckAndStartScanService(); } void WifiManager::DealStaCloseRes(OperateResState state) { + WIFI_LOGI("Enter DealStaCloseRes: %{public}d", static_cast(state)); WifiEventCallbackMsg cbMsg; cbMsg.msgCode = WIFI_CBK_MSG_STATE_CHANGE; if (state == OperateResState::CLOSE_WIFI_CLOSING) { @@ -272,18 +456,16 @@ void WifiManager::DealStaCloseRes(OperateResState state) return; } if (state == OperateResState::CLOSE_WIFI_FAILED) { - WIFI_LOGD("DealStaCloseRes:upload wifi close failed event!"); + WIFI_LOGI("DealStaCloseRes: broadcast wifi close failed event!"); cbMsg.msgData = static_cast(WifiState::UNKNOWN); WifiInternalEventDispatcher::GetInstance().AddBroadCastMsg(cbMsg); + ForceStopWifi(); } - if (WifiConfigCenter::GetInstance().GetAirplaneModeState() == 1) { WifiConfigCenter::GetInstance().SetWifiStateWhenAirplaneMode(false); } - cbMsg.msgData = static_cast(WifiState::DISABLED); WifiInternalEventDispatcher::GetInstance().AddBroadCastMsg(cbMsg); - CheckAndStopScanService(); WifiManager::GetInstance().PushServiceCloseMsg(WifiCloseServiceCode::STA_SERVICE_CLOSE); return; @@ -291,11 +473,16 @@ void WifiManager::DealStaCloseRes(OperateResState state) void WifiManager::DealStaConnChanged(OperateResState state, const WifiLinkedInfo &info) { - WifiEventCallbackMsg cbMsg; - cbMsg.msgCode = WIFI_CBK_MSG_CONNECTION_CHANGE; - cbMsg.msgData = static_cast(ConvertConnStateInternal(state)); - cbMsg.linkInfo = info; - WifiInternalEventDispatcher::GetInstance().AddBroadCastMsg(cbMsg); + WIFI_LOGI("Enter, DealStaConnChanged, state: %{public}d!\n", static_cast(state)); + bool isReport = true; + int reportStateNum = static_cast(ConvertConnStateInternal(state, isReport)); + if (isReport) { + WifiEventCallbackMsg cbMsg; + cbMsg.msgCode = WIFI_CBK_MSG_CONNECTION_CHANGE; + cbMsg.msgData = reportStateNum; + cbMsg.linkInfo = info; + WifiInternalEventDispatcher::GetInstance().AddBroadCastMsg(cbMsg); + } if (state == OperateResState::CONNECT_CONNECTING || state == OperateResState::CONNECT_AP_CONNECTED || state == OperateResState::DISCONNECT_DISCONNECTING || state == OperateResState::DISCONNECT_DISCONNECTED || @@ -308,6 +495,11 @@ void WifiManager::DealStaConnChanged(OperateResState state, const WifiLinkedInfo } } } +#ifdef FEATURE_P2P_SUPPORT + if (cfgMonitorCallback.onStaConnectionChange != nullptr) { + cfgMonitorCallback.onStaConnectionChange(static_cast(state)); + } +#endif return; } @@ -346,6 +538,7 @@ void WifiManager::DealRssiChanged(int rssi) void WifiManager::CheckAndStartScanService(void) { WifiOprMidState scanState = WifiConfigCenter::GetInstance().GetScanMidState(); + WIFI_LOGI("CheckAndStartScanService scanState: %{public}d", static_cast(scanState)); if (scanState != WifiOprMidState::CLOSED) { /* If the scanning function is enabled when the STA is not enabled, you need to start the scheduled scanning function immediately when the STA is enabled. */ @@ -356,7 +549,7 @@ void WifiManager::CheckAndStartScanService(void) return; } if (!WifiConfigCenter::GetInstance().SetScanMidState(scanState, WifiOprMidState::OPENING)) { - WIFI_LOGD("Failed to set scan mid state opening! may be other activity has been operated"); + WIFI_LOGW("Failed to set scan mid state opening! may be other activity has been operated"); return; } ErrCode errCode = WIFI_OPT_FAILED; @@ -397,6 +590,7 @@ void WifiManager::CheckAndStopScanService(void) * service. Otherwise, disable the SCAN service. */ WifiOprMidState scanState = WifiConfigCenter::GetInstance().GetScanMidState(); + WIFI_LOGI("[CheckAndStopScanService] scanState %{public}d!", static_cast(scanState)); if (scanState != WifiOprMidState::OPENING && scanState != WifiOprMidState::RUNNING) { return; } @@ -411,13 +605,16 @@ void WifiManager::CheckAndStopScanService(void) if (WifiConfigCenter::GetInstance().SetScanMidState(scanState, WifiOprMidState::CLOSING)) { IScanService *pService = WifiServiceManager::GetInstance().GetScanServiceInst(); if (pService == nullptr) { + WIFI_LOGE("[CheckAndStopScanService] scan service is null."); WifiManager::GetInstance().PushServiceCloseMsg(WifiCloseServiceCode::SCAN_SERVICE_CLOSE); + WifiConfigCenter::GetInstance().SetScanMidState(scanState, WifiOprMidState::CLOSED); return; } ErrCode ret = pService->UnInit(); - if (ret != WIFI_OPT_SUCCESS) { - WifiConfigCenter::GetInstance().SetScanMidState(WifiOprMidState::CLOSING, scanState); + if (ret != WIFI_OPT_SUCCESS) { // scan service is not exist + WIFI_LOGE("[CheckAndStopScanService] UnInit service failed!"); } + WifiConfigCenter::GetInstance().SetScanMidState(scanState, WifiOprMidState::CLOSED); } } @@ -427,6 +624,7 @@ void WifiManager::InitScanCallback(void) mScanCallback.OnScanStopEvent = DealScanCloseRes; mScanCallback.OnScanFinishEvent = DealScanFinished; mScanCallback.OnScanInfoEvent = DealScanInfoNotify; + mScanCallback.OnStoreScanInfoEvent = DealStoreScanInfoEvent; } IScanSerivceCallbacks WifiManager::GetScanCallback() @@ -463,6 +661,11 @@ void WifiManager::DealScanInfoNotify(std::vector &results) } } +void WifiManager::DealStoreScanInfoEvent(std::vector &results) +{ +} + +#ifdef FEATURE_AP_SUPPORT void WifiManager::InitApCallback(void) { mApCallback.OnApStateChangedEvent = DealApStateChanged; @@ -476,42 +679,52 @@ IApServiceCallbacks WifiManager::GetApCallback() return mApCallback; } -void WifiManager::DealApStateChanged(ApState state) +void WifiManager::DealApStateChanged(ApState state, int id) { WifiEventCallbackMsg cbMsg; cbMsg.msgCode = WIFI_CBK_MSG_HOTSPOT_STATE_CHANGE; cbMsg.msgData = static_cast(state); + cbMsg.id = id; WifiInternalEventDispatcher::GetInstance().AddBroadCastMsg(cbMsg); if (state == ApState::AP_STATE_IDLE) { + mCloseApIndex = id; WifiManager::GetInstance().PushServiceCloseMsg(WifiCloseServiceCode::AP_SERVICE_CLOSE); } if (state == ApState::AP_STATE_STARTED) { - WifiConfigCenter::GetInstance().SetApMidState(WifiOprMidState::OPENING, WifiOprMidState::RUNNING); + WifiConfigCenter::GetInstance().SetApMidState(WifiOprMidState::OPENING, WifiOprMidState::RUNNING, id); } - WifiCommonEventHelper::PublishHotspotStateChangedEvent((int)state, "OnHotspotStateChanged"); + + std::string msg = std::string("OnHotspotStateChanged") + std::string("id = ") + std::to_string(id); + WifiCommonEventHelper::PublishHotspotStateChangedEvent((int)state, msg); return; } -void WifiManager::DealApGetStaJoin(const StationInfo &info) +void WifiManager::DealApGetStaJoin(const StationInfo &info, int id) { WifiEventCallbackMsg cbMsg; cbMsg.msgCode = WIFI_CBK_MSG_HOTSPOT_STATE_JOIN; cbMsg.staInfo = info; + cbMsg.id = id; WifiInternalEventDispatcher::GetInstance().AddBroadCastMsg(cbMsg); - WifiCommonEventHelper::PublishApStaJoinEvent(0, "ApStaJoined"); + std::string msg = std::string("ApStaJoined") + std::string("id = ") + std::to_string(id); + WifiCommonEventHelper::PublishApStaJoinEvent(0, msg); return; } -void WifiManager::DealApGetStaLeave(const StationInfo &info) +void WifiManager::DealApGetStaLeave(const StationInfo &info, int id) { WifiEventCallbackMsg cbMsg; cbMsg.msgCode = WIFI_CBK_MSG_HOTSPOT_STATE_LEAVE; cbMsg.staInfo = info; + cbMsg.id = id; WifiInternalEventDispatcher::GetInstance().AddBroadCastMsg(cbMsg); - WifiCommonEventHelper::PublishApStaLeaveEvent(0, "ApStaLeaved"); + std::string msg = std::string("ApStaLeaved") + std::string("id = ") + std::to_string(id); + WifiCommonEventHelper::PublishApStaLeaveEvent(0, msg); return; } +#endif +#ifdef FEATURE_P2P_SUPPORT void WifiManager::InitP2pCallback(void) { mP2pCallback.OnP2pStateChangedEvent = DealP2pStateChanged; @@ -522,6 +735,7 @@ void WifiManager::InitP2pCallback(void) mP2pCallback.OnP2pDiscoveryChangedEvent = DealP2pDiscoveryChanged; mP2pCallback.OnP2pGroupsChangedEvent = DealP2pGroupsChanged; mP2pCallback.OnP2pActionResultEvent = DealP2pActionResult; + mP2pCallback.OnConfigChangedEvent = DealConfigChanged; return; } @@ -532,6 +746,7 @@ IP2pServiceCallbacks WifiManager::GetP2pCallback(void) void WifiManager::DealP2pStateChanged(P2pState state) { + WIFI_LOGI("DealP2pStateChanged, state: %{public}d", static_cast(state)); WifiEventCallbackMsg cbMsg; cbMsg.msgCode = WIFI_CBK_MSG_P2P_STATE_CHANGE; cbMsg.msgData = static_cast(state); @@ -542,6 +757,16 @@ void WifiManager::DealP2pStateChanged(P2pState state) if (state == P2pState::P2P_STATE_STARTED) { WifiConfigCenter::GetInstance().SetP2pMidState(WifiOprMidState::OPENING, WifiOprMidState::RUNNING); } + if (state == P2pState::P2P_STATE_CLOSED) { + bool ret = WifiConfigCenter::GetInstance().SetP2pMidState(WifiOprMidState::OPENING, WifiOprMidState::CLOSED); + if (ret) { + WIFI_LOGE("P2p start failed, stop wifi!"); + ForceStopWifi(); + cbMsg.msgCode = WIFI_CBK_MSG_STATE_CHANGE; + cbMsg.msgData = static_cast(WifiState::DISABLED); + WifiInternalEventDispatcher::GetInstance().AddBroadCastMsg(cbMsg); + } + } WifiCommonEventHelper::PublishP2pStateChangedEvent((int)state, "OnP2pStateChanged"); return; } @@ -565,7 +790,7 @@ void WifiManager::DealP2pServiceChanged(const std::vector &v return; } -void WifiManager::DealP2pConnectionChanged(const WifiP2pInfo &info) +void WifiManager::DealP2pConnectionChanged(const WifiP2pLinkedInfo &info) { WifiEventCallbackMsg cbMsg; cbMsg.msgCode = WIFI_CBK_MSG_CONNECT_CHANGE; @@ -614,5 +839,42 @@ void WifiManager::DealP2pActionResult(P2pActionCallback action, ErrCode code) return; } +void WifiManager::DealConfigChanged(CfgType type, char* data, int dataLen) +{ + if (data == nullptr || dataLen <= 0) { + return; + } + WifiEventCallbackMsg cbMsg; + cbMsg.msgCode = WIFI_CBK_MSG_CFG_CHANGE; + CfgInfo* cfgInfoPtr = new (std::nothrow) CfgInfo(); + if (cfgInfoPtr == nullptr) { + WIFI_LOGE("DealConfigChanged: new CfgInfo failed"); + return; + } + cfgInfoPtr->type = type; + char* cfgData = new (std::nothrow) char[dataLen]; + if (cfgData == nullptr) { + WIFI_LOGE("DealConfigChanged: new data failed"); + delete cfgInfoPtr; + return; + } + if (memcpy_s(cfgData, dataLen, data, dataLen) != EOK) { + WIFI_LOGE("DealConfigChanged: memcpy_s failed"); + delete cfgInfoPtr; + delete[] cfgData; + return; + } + cfgInfoPtr->data = cfgData; + cfgInfoPtr->dataLen = dataLen; + cbMsg.cfgInfo = cfgInfoPtr; + WifiInternalEventDispatcher::GetInstance().AddBroadCastMsg(cbMsg); + return; +} + +void WifiManager::RegisterCfgMonitorCallback(WifiCfgMonitorEventCallback callback) +{ + cfgMonitorCallback = callback; +} +#endif } // namespace Wifi -} // namespace OHOS \ No newline at end of file +} // namespace OHOS diff --git a/services/wifi_standard/wifi_framework/wifi_manage/wifi_manager.h b/wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_manager.h similarity index 78% rename from services/wifi_standard/wifi_framework/wifi_manage/wifi_manager.h rename to wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_manager.h index 8b7ce5760b82a5294df5bf1e007e41c0afc9d8a4..3eb7b348a6add307081cb558d5a04a4769259632 100644 --- a/services/wifi_standard/wifi_framework/wifi_manage/wifi_manager.h +++ b/wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_manager.h @@ -21,13 +21,18 @@ #include #include #include +#include #include "define.h" #include "wifi_internal_msg.h" #include "sta_service_callback.h" #include "iscan_service_callbacks.h" +#ifdef FEATURE_AP_SUPPORT #include "i_ap_service_callbacks.h" +#endif +#ifdef FEATURE_P2P_SUPPORT #include "ip2p_service_callbacks.h" +#endif namespace OHOS { namespace Wifi { @@ -50,6 +55,10 @@ enum class WifiCloseServiceCode { SERVICE_THREAD_EXIT, }; +struct WifiCfgMonitorEventCallback { + std::function onStaConnectionChange = nullptr; +}; + class WifiManager { public: WifiManager(); @@ -90,25 +99,29 @@ public: */ IScanSerivceCallbacks GetScanCallback(void); +#ifdef FEATURE_AP_SUPPORT /** * @Description Get the ap callback object. * * @return IApServiceCallbacks - return mApCallback */ IApServiceCallbacks GetApCallback(void); +#endif +#ifdef FEATURE_P2P_SUPPORT /** * @Description Get the p2p callback object. * * @return IP2pServiceCallbacks - return mP2pCallback */ IP2pServiceCallbacks GetP2pCallback(void); +#endif /** * @Description Get supported features * * @param features - output supported features - * @return int - operate result + * @return int - operation result */ int GetSupportedFeatures(long &features); @@ -121,18 +134,28 @@ public: static WifiManager &GetInstance(); + void RegisterCfgMonitorCallback(WifiCfgMonitorEventCallback callback); + private: void PushServiceCloseMsg(WifiCloseServiceCode code); void InitStaCallback(void); void InitScanCallback(void); +#ifdef FEATURE_AP_SUPPORT void InitApCallback(void); +#endif +#ifdef FEATURE_P2P_SUPPORT void InitP2pCallback(void); +#endif InitStatus GetInitStatus(); static void DealCloseServiceMsg(WifiManager &manager); static void CloseStaService(void); - static void CloseApService(void); +#ifdef FEATURE_AP_SUPPORT + static void CloseApService(int id = 0); +#endif static void CloseScanService(void); +#ifdef FEATURE_P2P_SUPPORT static void CloseP2pService(void); +#endif static void DealStaOpenRes(OperateResState state); static void DealStaCloseRes(OperateResState state); static void DealStaConnChanged(OperateResState state, const WifiLinkedInfo &info); @@ -145,17 +168,31 @@ private: static void DealScanCloseRes(void); static void DealScanFinished(int state); static void DealScanInfoNotify(std::vector &results); - static void DealApStateChanged(ApState bState); - static void DealApGetStaJoin(const StationInfo &info); - static void DealApGetStaLeave(const StationInfo &info); + static void DealStoreScanInfoEvent(std::vector &results); +#ifdef FEATURE_AP_SUPPORT + static void DealApStateChanged(ApState bState, int id = 0); + static void DealApGetStaJoin(const StationInfo &info, int id = 0); + static void DealApGetStaLeave(const StationInfo &info, int id = 0); +#endif +#ifdef FEATURE_P2P_SUPPORT static void DealP2pStateChanged(P2pState bState); static void DealP2pPeersChanged(const std::vector &vPeers); static void DealP2pServiceChanged(const std::vector &vServices); - static void DealP2pConnectionChanged(const WifiP2pInfo &info); + static void DealP2pConnectionChanged(const WifiP2pLinkedInfo &info); static void DealP2pThisDeviceChanged(const WifiP2pDevice &info); static void DealP2pDiscoveryChanged(bool bState); static void DealP2pGroupsChanged(void); static void DealP2pActionResult(P2pActionCallback action, ErrCode code); + static void DealConfigChanged(CfgType type, char* data, int dataLen); +#endif + static void AutoStartStaService(void); + static void ForceStopWifi(void); +#ifdef FEATURE_P2P_SUPPORT + static void AutoStartP2pService(void); +#endif + static void AutoStartScanService(void); + static void CheckAndStartSta(void); + static void AutoStartServiceThread(void); private: std::thread mCloseServiceThread; @@ -164,10 +201,16 @@ private: std::deque mEventQue; StaServiceCallback mStaCallback; IScanSerivceCallbacks mScanCallback; +#ifdef FEATURE_AP_SUPPORT IApServiceCallbacks mApCallback; +#endif +#ifdef FEATURE_P2P_SUPPORT IP2pServiceCallbacks mP2pCallback; + static WifiCfgMonitorEventCallback cfgMonitorCallback; +#endif InitStatus mInitStatus; long mSupportedFeatures; + static int mCloseApIndex; }; } // namespace Wifi } // namespace OHOS diff --git a/wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_net_agent.cpp b/wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_net_agent.cpp new file mode 100644 index 0000000000000000000000000000000000000000..4d37788cc6d72ac199a71203790411de9901642f --- /dev/null +++ b/wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_net_agent.cpp @@ -0,0 +1,232 @@ +/* + * Copyright (C) 2022 Huawei Device Co., Ltd. + * 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 "wifi_net_agent.h" +#include +#include "inet_addr.h" +#include "ip_tools.h" +#include "iservice_registry.h" +#include "netsys_native_service_proxy.h" +#include "net_conn_client.h" +#include "system_ability_definition.h" +#include "wifi_common_util.h" +#include "wifi_logger.h" + +DEFINE_WIFILOG_LABEL("WifiNetAgent"); + +namespace OHOS { +namespace Wifi { +using namespace NetManagerStandard; + +WifiNetAgent::WifiNetAgent() = default; +WifiNetAgent::~WifiNetAgent() = default; + +bool WifiNetAgent::RegisterNetSupplier() +{ + TimeStats timeStats(__func__); + WIFI_LOGI("Enter RegisterNetSupplier."); + auto netManager = DelayedSingleton::GetInstance(); + if (netManager == nullptr) { + WIFI_LOGE("NetConnClient is null"); + return false; + } + std::string ident = "wifi"; + using NetManagerStandard::NetBearType; + using NetManagerStandard::NetCap; + std::set netCaps {NetCap::NET_CAPABILITY_INTERNET}; + int32_t result = netManager->RegisterNetSupplier(NetBearType::BEARER_WIFI, ident, netCaps, supplierId); + if (result == ERR_NONE) { + WIFI_LOGI("Register NetSupplier successful"); + return true; + } + WIFI_LOGI("Register NetSupplier failed"); + return false; +} + +bool WifiNetAgent::RegisterNetSupplierCallback(const StaServiceCallback &callback) +{ + TimeStats timeStats(__func__); + WIFI_LOGI("Enter RegisterNetSupplierCallback."); + auto netManager = DelayedSingleton::GetInstance(); + if (netManager == nullptr) { + WIFI_LOGE("NetConnClient is null"); + return false; + } + + sptr pNetConnCallback = (std::make_unique(callback)).release(); + if (pNetConnCallback == nullptr) { + WIFI_LOGE("pNetConnCallback is null\n"); + return false; + } + + int32_t result = netManager->RegisterNetSupplierCallback(supplierId, pNetConnCallback); + if (result == ERR_NONE) { + WIFI_LOGI("Register NetSupplierCallback successful"); + return true; + } + WIFI_LOGE("Register NetSupplierCallback failed [%{public}d]", result); + return false; +} + +void WifiNetAgent::UnregisterNetSupplier() +{ + TimeStats timeStats(__func__); + WIFI_LOGI("Enter UnregisterNetSupplier."); + auto netManager = DelayedSingleton::GetInstance(); + if (netManager == nullptr) { + WIFI_LOGE("NetConnClient is null"); + return; + } + int32_t result = netManager->UnregisterNetSupplier(supplierId); + WIFI_LOGI("Unregister network result:%{public}d", result); +} + +void WifiNetAgent::UpdateNetSupplierInfo(const sptr &netSupplierInfo) +{ + TimeStats timeStats(__func__); + WIFI_LOGI("Enter UpdateNetSupplierInfo."); + auto netManager = DelayedSingleton::GetInstance(); + if (netManager == nullptr) { + WIFI_LOGE("NetConnClient is null"); + return; + } + + int32_t result = netManager->UpdateNetSupplierInfo(supplierId, netSupplierInfo); + WIFI_LOGI("Update network result:%{public}d", result); +} + +void WifiNetAgent::UpdateNetLinkInfo(const std::string &ip, const std::string &mask, const std::string &gateWay, + const std::string &strDns, const std::string &strBakDns) +{ + TimeStats timeStats(__func__); + WIFI_LOGI("Enter UpdateNetLinkInfo."); + auto netManager = DelayedSingleton::GetInstance(); + if (netManager == nullptr) { + WIFI_LOGE("NetConnClient is null"); + return; + } + + sptr netLinkInfo = (std::make_unique()).release(); + netLinkInfo->ifaceName_ = "wlan0"; + + unsigned int prefixLength = IpTools::GetMaskLength(mask); + sptr netAddr = (std::make_unique()).release(); + netAddr->type_ = NetManagerStandard::INetAddr::IPV4; + netAddr->address_ = ip; + netAddr->netMask_ = mask; + netAddr->prefixlen_ = prefixLength; + netLinkInfo->netAddrList_.push_back(*netAddr); + + sptr dns = (std::make_unique()).release(); + dns->type_ = NetManagerStandard::INetAddr::IPV4; + dns->address_ = strDns; + netLinkInfo->dnsList_.push_back(*dns); + dns->address_ = strBakDns; + netLinkInfo->dnsList_.push_back(*dns); + + sptr route = (std::make_unique()).release(); + route->iface_ = "wlan0"; + route->destination_.type_ = NetManagerStandard::INetAddr::IPV4; + route->destination_.address_ = "0.0.0.0"; + route->gateway_.address_ = gateWay; + netLinkInfo->routeList_.push_back(*route); + + sptr localRoute = (std::make_unique()).release(); + unsigned int ipInt = IpTools::ConvertIpv4Address(ip); + unsigned int maskInt = IpTools::ConvertIpv4Address(mask); + std::string strLocalRoute = IpTools::ConvertIpv4Address(ipInt & maskInt); + localRoute->iface_ = route->iface_; + localRoute->destination_.type_ = NetManagerStandard::INetAddr::IPV4; + localRoute->destination_.address_ = strLocalRoute; + localRoute->destination_.prefixlen_ = prefixLength; + localRoute->gateway_.address_ = "0.0.0.0"; + netLinkInfo->routeList_.push_back(*localRoute); + + int32_t result = netManager->UpdateNetLinkInfo(supplierId, netLinkInfo); + WIFI_LOGI("UpdateNetLinkInfo result:%{public}d", result); +} + +bool WifiNetAgent::AddRoute(const std::string interface, const std::string ipAddress, int prefixLength) +{ + TimeStats timeStats(__func__); + LOGI("NetAgent add route"); + unsigned int ipInt = IpTools::ConvertIpv4Address(ipAddress); + std::string mask = IpTools::ConvertIpv4Mask(prefixLength); + unsigned int maskInt = IpTools::ConvertIpv4Address(mask); + std::string strLocalRoute = IpTools::ConvertIpv4Address(ipInt & maskInt); + std::string destAddress = strLocalRoute + "/" + std::to_string(prefixLength); + + auto samgr = SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager(); + if (samgr == nullptr) { + LOGE("GetSystemAbilityManager failed!"); + return false; + } + auto remote = samgr->GetSystemAbility(COMM_NETSYS_NATIVE_SYS_ABILITY_ID); + if (remote == nullptr) { + LOGE("GetSystemAbility failed!"); + return false; + } + OHOS::sptr netsysService = iface_cast(remote); + if (netsysService == nullptr) { + LOGE("NetdService is nullptr!"); + return false; + } + LOGI("Add route, interface: %{public}s, destAddress: %{public}s, ipAddress: %{public}s, prefixLength: %{public}d", + interface.c_str(), IpAnonymize(destAddress).c_str(), IpAnonymize(ipAddress).c_str(), prefixLength); + netsysService->NetworkAddRoute(OHOS::nmd::LOCAL_NETWORK_NETID, interface, destAddress, ipAddress); + LOGI("NetAgent add route finish"); + return true; +} + +WifiNetAgent::NetConnCallback::NetConnCallback(const StaServiceCallback &callback) +{ + staCallback = callback; +} + +WifiNetAgent::NetConnCallback::~NetConnCallback() +{} + +int32_t WifiNetAgent::NetConnCallback::RequestNetwork( + const std::string &ident, const std::set &netCaps) +{ + WIFI_LOGD("Enter NetConnCallback::RequestNetwork"); + LogNetCaps(ident, netCaps); + return 0; +} + +int32_t WifiNetAgent::NetConnCallback::ReleaseNetwork( + const std::string &ident, const std::set &netCaps) +{ + WIFI_LOGD("Enter NetConnCallback::ReleaseNetwork"); + LogNetCaps(ident, netCaps); + return 0; +} + +void WifiNetAgent::NetConnCallback::LogNetCaps( + const std::string &ident, const std::set &netCaps) const +{ + WIFI_LOGD("ident=[%s]", ident.c_str()); + std::string logStr; + const std::string logStrEnd("]"); + logStr = "netCaps["; + for (auto netCap : netCaps) { + logStr += std::to_string(static_cast(netCap)); + logStr += " "; + } + logStr += logStrEnd; + WIFI_LOGD("%{public}s", logStr.c_str()); +} +} +} diff --git a/wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_net_agent.h b/wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_net_agent.h new file mode 100644 index 0000000000000000000000000000000000000000..00b6b7714c0801b39ec4b4cbfa1bdc30475fcf82 --- /dev/null +++ b/wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_net_agent.h @@ -0,0 +1,123 @@ +/* + * Copyright (C) 2022 Huawei Device Co., Ltd. + * 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 WIFI_NET_AGENT_H +#define WIFI_NET_AGENT_H + +#include +#include +#include +#include +#include + +#include "i_net_conn_service.h" +#include "net_all_capabilities.h" +#include "net_supplier_callback_base.h" + +#include "wifi_internal_msg.h" +#include "sta_service_callback.h" +#include "wifi_log.h" + +namespace OHOS { +namespace Wifi { +class WifiNetAgent : public DelayedRefSingleton { + DECLARE_DELAYED_REF_SINGLETON(WifiNetAgent); + +public: + /** + * Register the network information with the network management module + * + * @return true if register success else return false; + */ + bool RegisterNetSupplier(); + /** + * Register the network callback with the network management module + * + * @return true if register success else return false; + */ + bool RegisterNetSupplierCallback(const StaServiceCallback &callback); + + /** + * Cancel the registration information to the network management + */ + void UnregisterNetSupplier(); + + /** + * Update network information + * + * @param supplierId network unique identity id returned after network registration + * @param netSupplierInfo network data information + */ + void UpdateNetSupplierInfo(const sptr &netSupplierInfo); + + /** + * Update link information + * + * @param supplierId network unique identity id returned after network registration + * @param netLinkInfo network link data information + */ + void UpdateNetLinkInfo(const std::string &ip, const std::string &mask, const std::string &gateWay, + const std::string &strDns, const std::string &strBakDns); + + /** + * Add route + * + * @param interface interface name + * @param ipAddress IP address + * @param prefixLength prefix length + */ + bool AddRoute(const std::string interface, const std::string ipAddress, int prefixLength); + +public: + class NetConnCallback : public NetManagerStandard::NetSupplierCallbackBase { + public: + /** + * @Description : Construct a new NetConn object + * + */ + explicit NetConnCallback(const StaServiceCallback &callback); + + /** + * @Description : Destroy the NetConn object + * + */ + ~NetConnCallback() override; + + /** + * @Description : Connection Management triggers the open automatic connection feature. + * + * @param ident - identity + * @param netCaps - Net capability to request a network + */ + int32_t RequestNetwork(const std::string &ident, const std::set &netCaps) override; + /** + * @Description : Connection Management triggers the close automatic connection feature. + * + * @param ident - identity + * @param netCaps - Net capability to request a network + */ + int32_t ReleaseNetwork(const std::string &ident, const std::set &netCaps) override; + private: + void LogNetCaps(const std::string &ident, const std::set &netCaps) const; + private: + StaServiceCallback staCallback; + }; + +private: + uint32_t supplierId; +}; +} // namespace Wifi +} // namespace OHOS +#endif // CELLULAR_DATA_NET_AGENT_H diff --git a/services/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/BUILD.gn b/wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/BUILD.gn similarity index 41% rename from services/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/BUILD.gn rename to wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/BUILD.gn index be2669745fe5bdd15fb8a371353bd020b4f5c000..36a54d16b7fb3690b295b2f8f0ba6e9143e04d54 100644 --- a/services/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/BUILD.gn +++ b/wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/BUILD.gn @@ -1,4 +1,4 @@ -# Copyright (C) 2021 Huawei Device Co., Ltd. +# Copyright (C) 2021-2022 Huawei Device Co., Ltd. # 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 @@ -12,18 +12,18 @@ # limitations under the License. import("//build/ohos.gni") +import("//foundation/communication/wifi/wifi/wifi.gni") ohos_shared_library("wifi_p2p_service") { install_enable = true sources = [ - "//foundation/communication/wifi/services/wifi_standard/wifi_framework/common/net_helper/dhcpd_interface.cpp", - "//foundation/communication/wifi/services/wifi_standard/wifi_framework/common/net_helper/mac_address.cpp", - "//foundation/communication/wifi/services/wifi_standard/wifi_framework/wifi_manage/common/handler.cpp", - "//foundation/communication/wifi/services/wifi_standard/wifi_framework/wifi_manage/common/internal_message.cpp", - "//foundation/communication/wifi/services/wifi_standard/wifi_framework/wifi_manage/common/message_queue.cpp", - "//foundation/communication/wifi/services/wifi_standard/wifi_framework/wifi_manage/common/state.cpp", - "//foundation/communication/wifi/services/wifi_standard/wifi_framework/wifi_manage/common/state_machine.cpp", - "//foundation/communication/wifi/services/wifi_standard/wifi_framework/wifi_manage/common/wifi_broadcast_helper.cpp", + "$WIFI_ROOT_DIR/services/wifi_standard/wifi_framework/wifi_manage/common/handler.cpp", + "$WIFI_ROOT_DIR/services/wifi_standard/wifi_framework/wifi_manage/common/internal_message.cpp", + "$WIFI_ROOT_DIR/services/wifi_standard/wifi_framework/wifi_manage/common/message_queue.cpp", + "$WIFI_ROOT_DIR/services/wifi_standard/wifi_framework/wifi_manage/common/state.cpp", + "$WIFI_ROOT_DIR/services/wifi_standard/wifi_framework/wifi_manage/common/state_machine.cpp", + "$WIFI_ROOT_DIR/services/wifi_standard/wifi_framework/wifi_manage/common/wifi_broadcast_helper.cpp", + "$WIFI_ROOT_DIR/services/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/hid2d/wifi_hid2d_service_utils.cpp", "authorizing_negotiation_request_state.cpp", "group_formed_state.cpp", "group_negotiation_state.cpp", @@ -62,23 +62,30 @@ ohos_shared_library("wifi_p2p_service") { include_dirs = [ "./", - "//utils/native/base/include", + "//commonlibrary/c_utils/base/include", "//base/hiviewdfx/hilog/interfaces/native/innerkits/include", - "//foundation/communication/wifi/interfaces/innerkits/native_cpp/wifi_standard/interfaces", - "//foundation/communication/wifi/services/wifi_standard/ipc_framework/cRPC/include", - "//foundation/communication/wifi/services/wifi_standard/wifi_framework/common/include", - "//foundation/communication/wifi/services/wifi_standard/wifi_framework/common/net_helper", - "//foundation/communication/wifi/services/wifi_standard/wifi_framework/common/config", - "//foundation/communication/wifi/services/wifi_standard/wifi_framework/common/log", - "//foundation/communication/wifi/services/wifi_standard/wifi_framework/common/utils", - "//foundation/communication/wifi/services/wifi_standard/wifi_framework/wifi_manage/common/include", - "//foundation/communication/wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_ap", - "//foundation/communication/wifi/services/wifi_standard/wifi_framework/wifi_manage", - "//foundation/communication/wifi/services/wifi_standard/wifi_framework/wifi_manage/common", - "//foundation/communication/wifi/services/wifi_standard/wifi_framework/wifi_manage/idl_client", - "//foundation/communication/wifi/services/wifi_standard/wifi_framework/wifi_manage/idl_client/idl_interface", - "//foundation/communication/wifi/services/wifi_standard/wifi_framework/dhcp_manage/mgr_service/include", - "//foundation/communication/wifi/services/wifi_standard/wifi_framework/dhcp_manage/mgr_service/interfaces", + "$WIFI_ROOT_DIR/frameworks/native/interfaces", + "$WIFI_ROOT_DIR/services/wifi_standard/ipc_framework/cRPC/include", + "$WIFI_ROOT_DIR/services/wifi_standard/wifi_framework/wifi_toolkit/include", + "$WIFI_ROOT_DIR/services/wifi_standard/wifi_framework/wifi_toolkit/net_helper", + "$WIFI_ROOT_DIR/services/wifi_standard/wifi_framework/wifi_toolkit/config", + "$WIFI_ROOT_DIR/services/wifi_standard/wifi_framework/wifi_toolkit/log", + "$WIFI_ROOT_DIR/services/wifi_standard/wifi_framework/wifi_toolkit/utils", + "$WIFI_ROOT_DIR/services/wifi_standard/wifi_framework/wifi_manage/common/include", + "$WIFI_ROOT_DIR/services/wifi_standard/wifi_framework/wifi_manage/wifi_ap", + "$WIFI_ROOT_DIR/services/wifi_standard/wifi_framework/wifi_manage", + "$WIFI_ROOT_DIR/services/wifi_standard/wifi_framework/wifi_manage/common", + "$WIFI_ROOT_DIR/services/wifi_standard/wifi_framework/wifi_manage/idl_client", + "$WIFI_ROOT_DIR/services/wifi_standard/wifi_framework/wifi_manage/idl_client/idl_interface", + "$DHCP_ROOT_DIR/services/mgr_service/include", + "$DHCP_ROOT_DIR/interfaces/inner_api/include", + "$DHCP_ROOT_DIR/interfaces/inner_api/interfaces", + "$WIFI_ROOT_DIR/services/wifi_standard/wifi_framework/wifi_manage/wifi_sta", + "$WIFI_ROOT_DIR/services/wifi_standard/wifi_framework/wifi_manage/wifi_scan", + "$WIFI_ROOT_DIR/utils/inc", + "$WIFI_ROOT_DIR/services/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/hid2d", + "$WIFI_ROOT_DIR/services/wifi_standard/wifi_framework/wifi_manage/wifi_common", + "$WIFI_ROOT_DIR/services/wifi_standard/include", ] cflags_cc = [ @@ -92,16 +99,24 @@ ohos_shared_library("wifi_p2p_service") { ] defines = [ "AP_NOT_DIRECT_USE_DHCP" ] + if (product_name == "rk3568") { + defines += [ "NON_SEPERATE_P2P" ] + } - external_deps = [ "hiviewdfx_hilog_native:libhilog" ] + external_deps = [ + "c_utils:utils", + "hiviewdfx_hilog_native:libhilog", + "netmanager_base:net_conn_manager_if", + ] deps = [ - "//foundation/communication/wifi/services/wifi_standard/wifi_framework/dhcp_manage/mgr_service:dhcp_manager_service", - "//foundation/communication/wifi/services/wifi_standard/wifi_framework/wifi_manage:wifi_manager_service", - "//foundation/communication/wifi/services/wifi_standard/wifi_framework/wifi_manage/idl_client:wifi_idl_client", - "//utils/native/base:utils", + "$DHCP_ROOT_DIR/services/mgr_service:dhcp_manager_service", + "$WIFI_ROOT_DIR/services/wifi_standard/wifi_framework/wifi_manage:wifi_manager_service", + "$WIFI_ROOT_DIR/services/wifi_standard/wifi_framework/wifi_manage/idl_client:wifi_idl_client", + "$WIFI_ROOT_DIR/services/wifi_standard/wifi_framework/wifi_toolkit:wifi_toolkit", + "$WIFI_ROOT_DIR/utils:wifi_utils", ] - part_name = "wifi_standard" + part_name = "wifi" subsystem_name = "communication" } diff --git a/services/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/abstract_ui.h b/wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/abstract_ui.h similarity index 100% rename from services/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/abstract_ui.h rename to wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/abstract_ui.h diff --git a/services/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/authorizing_negotiation_request_state.cpp b/wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/authorizing_negotiation_request_state.cpp similarity index 98% rename from services/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/authorizing_negotiation_request_state.cpp rename to wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/authorizing_negotiation_request_state.cpp index a94094962ffc924d90c6866e094f989e487404da..a38288687ec66ae90066d31fd4ca9463b3a3d826 100644 --- a/services/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/authorizing_negotiation_request_state.cpp +++ b/wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/authorizing_negotiation_request_state.cpp @@ -51,7 +51,7 @@ bool AuthorizingNegotiationRequestState::ExecuteStateMsg(InternalMessage *msg) if (wps.GetWpsMethod() == WpsMethod::WPS_METHOD_KEYPAD) { std::string inputPin; if (!msg->GetMessageObj(inputPin)) { - WIFI_LOGD("Failed to obtain the pin code."); + WIFI_LOGW("Failed to obtain the pin code."); break; } WpsInfo wpsPin = wps; diff --git a/services/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/authorizing_negotiation_request_state.h b/wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/authorizing_negotiation_request_state.h similarity index 93% rename from services/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/authorizing_negotiation_request_state.h rename to wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/authorizing_negotiation_request_state.h index 2e5437cde054db9914805276c2bdd4c7d9b76df3..7f127d13a2ea695e033977396321698b581f5ba8 100644 --- a/services/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/authorizing_negotiation_request_state.h +++ b/wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/authorizing_negotiation_request_state.h @@ -32,7 +32,8 @@ public: * @param None * @return None */ - AuthorizingNegotiationRequestState(P2pStateMachine &, WifiP2pGroupManager &, WifiP2pDeviceManager &); + AuthorizingNegotiationRequestState(P2pStateMachine &stateMachine, WifiP2pGroupManager &groupMgr, + WifiP2pDeviceManager &deviceMgr); /** * @Description Destroy the Authorizing Negotlation Request State object diff --git a/services/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/group_formed_state.cpp b/wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/group_formed_state.cpp similarity index 68% rename from services/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/group_formed_state.cpp rename to wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/group_formed_state.cpp index 122b91bee0e5b8346442296a9040cf2f12c7b59a..a7eb003e9cbb1b10853266a2b376cc82ecd63cd7 100644 --- a/services/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/group_formed_state.cpp +++ b/wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/group_formed_state.cpp @@ -1,5 +1,5 @@ /* - * Copyright (C) 2021 Huawei Device Co., Ltd. + * Copyright (C) 2021-2022 Huawei Device Co., Ltd. * 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 @@ -12,6 +12,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + #include "group_formed_state.h" #include "wifi_p2p_hal_interface.h" #include "p2p_state_machine.h" @@ -65,13 +66,19 @@ void GroupFormedState::Init() std::make_pair(P2P_STATE_MACHINE_CMD::P2P_EVENT_GROUP_STARTED, &GroupFormedState::ProcessGroupStartedEvt)); mProcessFunMap.insert( std::make_pair(P2P_STATE_MACHINE_CMD::CMD_DEVICE_DISCOVERS, &GroupFormedState::ProcessCmdDiscoverPeer)); + mProcessFunMap.insert( + std::make_pair(P2P_STATE_MACHINE_CMD::CMD_DISCOVER_SERVICES, &GroupFormedState::ProcessCmdDiscServices)); + mProcessFunMap.insert( + std::make_pair(P2P_STATE_MACHINE_CMD::CMD_START_LISTEN, &GroupFormedState::ProcessCmdStartListen)); mProcessFunMap.insert( std::make_pair(P2P_STATE_MACHINE_CMD::CMD_P2P_DISABLE, &GroupFormedState::ProcessCmdDisable)); + mProcessFunMap.insert( + std::make_pair(P2P_STATE_MACHINE_CMD::CMD_CANCEL_CONNECT, &GroupFormedState::ProcessCmdCancelConnect)); } bool GroupFormedState::ProcessCmdConnect(const InternalMessage &msg) const { - WifiP2pConfig config; + WifiP2pConfigInternal config; if (!msg.GetMessageObj(config)) { WIFI_LOGE("Connect:Failed to obtain config info."); return EXECUTED; @@ -94,6 +101,7 @@ bool GroupFormedState::ProcessCmdConnect(const InternalMessage &msg) const p2pStateMachine.SwitchState(&p2pStateMachine.p2pInvitationRequestState); return EXECUTED; } + bool GroupFormedState::ProcessProvDiscEvt(const InternalMessage &msg) const { WifiP2pTempDiscEvent procDisc; @@ -102,7 +110,7 @@ bool GroupFormedState::ProcessProvDiscEvt(const InternalMessage &msg) const return EXECUTED; } - p2pStateMachine.savedP2pConfig = WifiP2pConfig(); + p2pStateMachine.savedP2pConfig = WifiP2pConfigInternal(); p2pStateMachine.savedP2pConfig.SetDeviceAddress(procDisc.GetDevice().GetDeviceAddress()); WpsInfo wps; @@ -136,6 +144,7 @@ bool GroupFormedState::ProcessGroupStartedEvt(const InternalMessage &msg) const WIFI_LOGI("recv CMD: %{public}d", msg.GetMessageName()); return EXECUTED; } + bool GroupFormedState::ProcessCmdDiscoverPeer(const InternalMessage &msg) const { WIFI_LOGI("recv CMD: %{public}d", msg.GetMessageName()); @@ -197,13 +206,18 @@ bool GroupFormedState::ProcessDisconnectEvt(const InternalMessage &msg) const return EXECUTED; } + IpPool::ReleaseIp(device.GetDeviceAddress()); device.SetP2pDeviceStatus(P2pDeviceStatus::PDS_AVAILABLE); - - deviceManager.UpdateDeviceStatus(device); - groupManager.UpdateCurrGroupClient(device); - + deviceManager.UpdateDeviceStatus(device); // used for peers change event querying device infos + groupManager.RemoveCurrGroupClient(device); p2pStateMachine.BroadcastP2pPeersChanged(); p2pStateMachine.BroadcastP2pConnectionChanged(); + deviceManager.RemoveDevice(device); + if (groupManager.IsCurrGroupClientEmpty() && !groupManager.GetCurrentGroup().IsExplicitGroup()) { + WIFI_LOGE("Clients empty, remove p2p group."); + p2pStateMachine.SwitchState(&p2pStateMachine.p2pGroupOperatingState); + p2pStateMachine.SendMessage(static_cast(P2P_STATE_MACHINE_CMD::CMD_REMOVE_GROUP)); + } return EXECUTED; } @@ -234,6 +248,75 @@ bool GroupFormedState::ProcessConnectEvt(const InternalMessage &msg) const return EXECUTED; } +bool GroupFormedState::ProcessCmdCancelConnect(const InternalMessage &msg) const +{ + WIFI_LOGI("recv CMD: %{public}d", msg.GetMessageName()); + p2pStateMachine.BroadcastActionResult(P2pActionCallback::P2pCancelConnect, ErrCode::WIFI_OPT_FAILED); + return EXECUTED; +} + +bool GroupFormedState::ProcessCmdDiscServices(const InternalMessage &msg) const +{ + WIFI_LOGI("recv CMD: %{public}d", msg.GetMessageName()); + WIFI_LOGD("p2p_enabled_state recv CMD_DISCOVER_SERVICES"); + + p2pStateMachine.CancelSupplicantSrvDiscReq(); + std::string reqId; + WifiP2pServiceRequest request; + WifiP2pDevice device; + device.SetDeviceAddress(std::string("00:00:00:00:00:00")); + request.SetProtocolType(P2pServicerProtocolType::SERVICE_TYPE_ALL); + request.SetTransactionId(p2pStateMachine.serviceManager.GetTransId()); + + WifiErrorNo retCode = + WifiP2PHalInterface::GetInstance().ReqServiceDiscovery(device.GetDeviceAddress(), request.GetTlv(), reqId); + if (WifiErrorNo::WIFI_IDL_OPT_OK != retCode) { + WIFI_LOGI("Failed to schedule the P2P service discovery request."); + p2pStateMachine.BroadcastActionResult(P2pActionCallback::DiscoverServices, ErrCode::WIFI_OPT_FAILED); + return EXECUTED; + } + p2pStateMachine.serviceManager.SetQueryId(reqId); + + retCode = WifiP2PHalInterface::GetInstance().P2pFind(DISC_TIMEOUT_S); + if (retCode != WifiErrorNo::WIFI_IDL_OPT_OK) { + WIFI_LOGE("call P2pFind failed, ErrorCode: %{public}d", static_cast(retCode)); + p2pStateMachine.BroadcastActionResult(P2pActionCallback::DiscoverServices, ErrCode::WIFI_OPT_FAILED); + return EXECUTED; + } + + WIFI_LOGI("CMD_DISCOVER_SERVICES successful."); + p2pStateMachine.BroadcastActionResult(P2pActionCallback::DiscoverServices, ErrCode::WIFI_OPT_SUCCESS); + p2pStateMachine.BroadcastP2pDiscoveryChanged(true); + return EXECUTED; +} + +bool GroupFormedState::ProcessCmdStartListen(const InternalMessage &msg) const +{ + if (WifiP2PHalInterface::GetInstance().P2pFlush()) { + WIFI_LOGW("Unexpected results in p2p flush."); + } + + constexpr int defaultOpClass = 81; + constexpr int defaultChannel = 6; + if (WifiP2PHalInterface::GetInstance().SetListenChannel(defaultChannel, defaultOpClass)) { + WIFI_LOGI("p2p set listen channel failed. channel:%{public}d, opclass:%{public}d", defaultChannel, + defaultOpClass); + p2pStateMachine.BroadcastActionResult(P2pActionCallback::StartP2pListen, WIFI_OPT_FAILED); + return EXECUTED; + } + + size_t period = msg.GetParam1(); + size_t interval = msg.GetParam2(); + if (WifiP2PHalInterface::GetInstance().P2pConfigureListen(true, period, interval)) { + WIFI_LOGE("p2p configure to start listen failed."); + p2pStateMachine.BroadcastActionResult(P2pActionCallback::StartP2pListen, WIFI_OPT_FAILED); + } else { + WIFI_LOGI("p2p configure to start listen successful."); + p2pStateMachine.BroadcastActionResult(P2pActionCallback::StartP2pListen, WIFI_OPT_SUCCESS); + } + return EXECUTED; +} + bool GroupFormedState::ExecuteStateMsg(InternalMessage *msg) { if (msg == nullptr) { diff --git a/services/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/group_formed_state.h b/wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/group_formed_state.h similarity index 83% rename from services/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/group_formed_state.h rename to wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/group_formed_state.h index f0a6bbc1b5331d15f018d980c0a3cd2506082004..e88daecb31bda8eb6c9f254df58dad2789b769cd 100644 --- a/services/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/group_formed_state.h +++ b/wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/group_formed_state.h @@ -1,5 +1,5 @@ /* - * Copyright (C) 2021 Huawei Device Co., Ltd. + * Copyright (C) 2021-2022 Huawei Device Co., Ltd. * 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 @@ -12,6 +12,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + #ifndef OHOS_P2P_GROUP_FORMED_STATE_H #define OHOS_P2P_GROUP_FORMED_STATE_H @@ -33,7 +34,7 @@ public: * @param None * @return None */ - GroupFormedState(P2pStateMachine &, WifiP2pGroupManager &, WifiP2pDeviceManager &); + GroupFormedState(P2pStateMachine &stateMachine, WifiP2pGroupManager &groupMgr, WifiP2pDeviceManager &deviceMgr); /** * @Description Destroy the Group Formed State object @@ -141,6 +142,13 @@ private: */ virtual bool ProcessCmdDiscoverPeer(const InternalMessage &msg) const; + /** + * @Description Process the discover services command received by the state machine + * @param msg - Message body sent by the state machine + * @return - bool true:handle false:not handle + */ + virtual bool ProcessCmdDiscServices(const InternalMessage &msg) const; + /** * @Description Process the disable command received by the state machine * @param msg - Message body sent by the state machine @@ -148,6 +156,20 @@ private: */ virtual bool ProcessCmdDisable(const InternalMessage &msg) const; + /** + * @Description Process the cancel connect command received by the state machine + * @param msg - Message body sent by the state machine + * @return - bool true:handle false:not handle + */ + virtual bool ProcessCmdCancelConnect(const InternalMessage &msg) const; + + /** + * @Description Process the start listen command received by the state machine + * @param msg - Message body sent by the state machine + * @return - bool true:handle false:not handle + */ + virtual bool ProcessCmdStartListen(const InternalMessage &msg) const; + private: P2pStateMachine &p2pStateMachine; WifiP2pGroupManager &groupManager; diff --git a/services/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/group_negotiation_state.cpp b/wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/group_negotiation_state.cpp similarity index 81% rename from services/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/group_negotiation_state.cpp rename to wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/group_negotiation_state.cpp index b9b3c5ef90d9c41f378932ad998573463601ba4a..c6b658883220edd4d2064e92d8fbd602ae1d8676 100644 --- a/services/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/group_negotiation_state.cpp +++ b/wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/group_negotiation_state.cpp @@ -1,5 +1,5 @@ /* - * Copyright (C) 2021 Huawei Device Co., Ltd. + * Copyright (C) 2021-2022 Huawei Device Co., Ltd. * 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 @@ -53,11 +53,13 @@ void GroupNegotiationState::Init() P2P_STATE_MACHINE_CMD::P2P_EVENT_INVITATION_RESULT, &GroupNegotiationState::ProcessInvitationResultEvt)); mProcessFunMap.insert( std::make_pair(P2P_STATE_MACHINE_CMD::P2P_EVENT_GROUP_REMOVED, &GroupNegotiationState::ProcessGroupRemovedEvt)); + mProcessFunMap.insert( + std::make_pair(P2P_STATE_MACHINE_CMD::CMD_REMOVE_GROUP, &GroupNegotiationState::ProcessCmdRemoveGroup)); } bool GroupNegotiationState::ProcessNegotSucessEvt(InternalMessage &msg) const { - WIFI_LOGI("Negotation success: %{public}d", msg.GetMessageName()); + WIFI_LOGI("Negotiation success: %{public}d", msg.GetMessageName()); return EXECUTED; } @@ -79,16 +81,19 @@ bool GroupNegotiationState::ProcessGroupStartedEvt(InternalMessage &msg) const if (groupManager.GetCurrentGroup().IsGroupOwner() && MacAddress::IsValidMac(groupManager.GetCurrentGroup().GetOwner().GetDeviceAddress().c_str())) { + deviceManager.GetThisDevice().SetP2pDeviceStatus(P2pDeviceStatus::PDS_CONNECTED); group.SetOwner(deviceManager.GetThisDevice()); groupManager.SetCurrentGroup(group); } if (groupManager.GetCurrentGroup().IsPersistent()) { - p2pStateMachine.UpdatePersistentGroups(); + p2pStateMachine.UpdateGroupManager(); const WifiP2pDevice &owner = groupManager.GetCurrentGroup().GetOwner(); WifiP2pGroupInfo copy = groupManager.GetCurrentGroup(); copy.SetNetworkId(groupManager.GetGroupNetworkId(owner, groupManager.GetCurrentGroup().GetGroupName())); groupManager.SetCurrentGroup(copy); + groupManager.AddOrUpdateGroup(groupManager.GetCurrentGroup()); + p2pStateMachine.UpdatePersistentGroups(); } else { WifiP2pGroupInfo copy = groupManager.GetCurrentGroup(); copy.SetNetworkId(TEMPORARY_NET_ID); @@ -116,7 +121,7 @@ bool GroupNegotiationState::ProcessGroupStartedEvt(InternalMessage &msg) const const WifiP2pDevice &owner = groupManager.GetCurrentGroup().GetOwner(); WifiP2pDevice device = deviceManager.GetDevices(owner.GetDeviceAddress()); if (device.IsValid()) { - device.SetP2pDeviceStatus(owner.GetP2pDeviceStatus()); + device.SetP2pDeviceStatus(P2pDeviceStatus::PDS_CONNECTED); WifiP2pGroupInfo copy = groupManager.GetCurrentGroup(); copy.SetOwner(device); groupManager.SetCurrentGroup(copy); @@ -125,9 +130,10 @@ bool GroupNegotiationState::ProcessGroupStartedEvt(InternalMessage &msg) const p2pStateMachine.BroadcastP2pPeersChanged(); } else { - WIFI_LOGD("fail:No GO device information is found."); + WIFI_LOGE("fail:No GO device information is found."); } } + SharedLinkManager::SetSharedLinkCount(SHARED_LINKE_COUNT_ON_CONNECTED); p2pStateMachine.ChangeConnectedStatus(P2pConnectedState::P2P_CONNECTED); p2pStateMachine.SwitchState(&p2pStateMachine.p2pGroupFormedState); return EXECUTED; @@ -136,14 +142,14 @@ bool GroupNegotiationState::ProcessGroupStartedEvt(InternalMessage &msg) const bool GroupNegotiationState::ProcessGroupFormationFailEvt(InternalMessage &msg) const { int status = msg.GetParam1(); - WIFI_LOGD("Group formation failure. Error code: %{public}d", status); + WIFI_LOGW("Group formation failure. Error code: %{public}d", status); return EXECUTED; } bool GroupNegotiationState::ProcessNegotFailEvt(InternalMessage &msg) const { int status = msg.GetParam1(); - WIFI_LOGD("Negotation failure. Error code: %{public}d", status); + WIFI_LOGE("Negotiation failure. Error code: %{public}d", status); p2pStateMachine.SwitchState(&p2pStateMachine.p2pIdleState); return EXECUTED; } @@ -186,6 +192,28 @@ bool GroupNegotiationState::ProcessGroupRemovedEvt(InternalMessage &msg) const return EXECUTED; } +bool GroupNegotiationState::ProcessCmdRemoveGroup(InternalMessage &msg) const +{ + std::string ifName = p2pStateMachine.p2pDevIface; + if (ifName.empty()) { + WIFI_LOGE("invalid ifname on ProcessCmdRemoveGroup"); + return EXECUTED; + } + p2pStateMachine.p2pDevIface = ""; + WifiErrorNo ret = WifiP2PHalInterface::GetInstance().GroupRemove(ifName); + if (ret) { + WIFI_LOGE("P2P group (%{public}s) removal failed.", ifName.c_str()); + p2pStateMachine.ChangeConnectedStatus(P2pConnectedState::P2P_DISCONNECTED); + p2pStateMachine.BroadcastActionResult(P2pActionCallback::RemoveGroup, WIFI_OPT_FAILED); + } else { + WIFI_LOGI("The P2P group (%{public}s) is successfully removed.", ifName.c_str()); + p2pStateMachine.ChangeConnectedStatus(P2pConnectedState::P2P_DISCONNECTED); + p2pStateMachine.BroadcastActionResult(P2pActionCallback::RemoveGroup, WIFI_OPT_SUCCESS); + } + p2pStateMachine.SwitchState(&p2pStateMachine.p2pIdleState); + return EXECUTED; +} + bool GroupNegotiationState::ExecuteStateMsg(InternalMessage *msg) { if (msg == nullptr) { diff --git a/services/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/group_negotiation_state.h b/wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/group_negotiation_state.h similarity index 87% rename from services/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/group_negotiation_state.h rename to wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/group_negotiation_state.h index a3c86f1b2bdc3f3ff2776cbfeb86ee95e548f2b1..f90326aec8f5bf0c41218787f31499925e55996d 100644 --- a/services/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/group_negotiation_state.h +++ b/wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/group_negotiation_state.h @@ -33,7 +33,8 @@ public: * @param None * @return None */ - GroupNegotiationState(P2pStateMachine &, WifiP2pGroupManager &, WifiP2pDeviceManager &); + GroupNegotiationState(P2pStateMachine &stateMachine, WifiP2pGroupManager &groupMgr, + WifiP2pDeviceManager &deviceMgr); /** * @Description Destroy the Group Negotiation State object @@ -65,7 +66,7 @@ public: private: /** - * @Description Process the negotation success message received by the state machine + * @Description Process the negotiation success message received by the state machine * @param msg - Message body sent by the state machine * @return - bool true:handle false:not handle */ @@ -93,7 +94,7 @@ private: virtual bool ProcessGroupFormationFailEvt(InternalMessage &msg) const; /** - * @Description Process the negotation fail message received by the state machine + * @Description Process the negotiation fail message received by the state machine * @param msg - Message body sent by the state machine * @return - bool true:handle false:not handle */ @@ -113,6 +114,13 @@ private: */ virtual bool ProcessGroupRemovedEvt(InternalMessage &msg) const; + /** + * @Description Process remvoe group message received by the state machine + * @param msg - Message body sent by the state machine + * @return - bool true:handle false:not handle + */ + virtual bool ProcessCmdRemoveGroup(InternalMessage &msg) const; + /** * @Description Initialization * @param None diff --git a/wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/hid2d/wifi_hid2d_service_utils.cpp b/wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/hid2d/wifi_hid2d_service_utils.cpp new file mode 100644 index 0000000000000000000000000000000000000000..f1fa46ebeaf13b45f9db315c9fdaa26a5eed2adf --- /dev/null +++ b/wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/hid2d/wifi_hid2d_service_utils.cpp @@ -0,0 +1,135 @@ +/* + * Copyright (C) 2022 Huawei Device Co., Ltd. + * 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 "wifi_hid2d_service_utils.h" +#include +#include +#include "dhcp_define.h" +#include "wifi_logger.h" + +namespace OHOS { +namespace Wifi { +DEFINE_WIFILOG_P2P_LABEL("Hid2dIpPool"); +std::list IpPool::ipList; +std::map IpPool::mapGcMacToAllocIp; +const std::string PATTERN_IP = "^(([01]?\\d\\d?|2[0-4]\\d|25[0-5])\\.){3}([01]?\\d\\d?|2[0-4]\\d|25[0-5])$"; +std::shared_mutex g_ipPoolMutex; + +std::atomic_int SharedLinkManager::sharedLinkCount(0); + +bool IpPool::InitIpPool(const std::string& serverIp) +{ + WIFI_LOGI("Init ip pool"); + + std::unique_lock guard(g_ipPoolMutex); + if (!ipList.empty()) { + return true; + } + + std::string hostIp = serverIp.empty() ? IP_V4_DEFAULT : serverIp; + if (!IsValidIp(hostIp)) { + return false; + } + + std::string serverIpHead = hostIp.substr(0, hostIp.find_last_of("\\.")); + ipList.clear(); + mapGcMacToAllocIp.clear(); + for (int i = HID2D_IPPOOL_START; i <= HID2D_IPPOOL_END; ++i) { + ipList.emplace_back(serverIpHead + "." + std::to_string(i)); + } + return true; +} + +std::string IpPool::GetIp(const std::string& gcMac) +{ + WIFI_LOGI("Get ip, gcMac: %{private}s", gcMac.c_str()); + + std::unique_lock guard(g_ipPoolMutex); + std::string ip = ""; + if (ipList.empty()) { + WIFI_LOGE("Alloc ip failed!"); + return ip; + } + ip = ipList.front(); + ipList.pop_front(); + mapGcMacToAllocIp[gcMac] = ip; + return ip; +} + +void IpPool::ReleaseIp(const std::string& gcMac) +{ + WIFI_LOGI("Release ip, gcMac: %{private}s", gcMac.c_str()); + + std::unique_lock guard(g_ipPoolMutex); + auto iter = mapGcMacToAllocIp.find(gcMac); + if (iter == mapGcMacToAllocIp.end()) { + return; + } + + if (std::find(ipList.begin(), ipList.end(), iter->second) != ipList.end()) { + return; + } + if (IsValidIp(iter->second)) { + ipList.emplace_back(iter->second); + mapGcMacToAllocIp.erase(iter); + } +} + +void IpPool::ReleaseIpPool() +{ + WIFI_LOGI("Release ip pool"); + + std::unique_lock guard(g_ipPoolMutex); + mapGcMacToAllocIp.clear(); + ipList.clear(); +} + +bool IpPool::IsValidIp(const std::string& ip) +{ + if (ip.empty()) { + return false; + } + return std::regex_match(ip, std::regex(PATTERN_IP)); +} + +void SharedLinkManager::IncreaseSharedLink() +{ + WIFI_LOGI("Increase shared link %{public}d -> %{public}d", sharedLinkCount.load(), sharedLinkCount.load() + 1); + ++sharedLinkCount; +} + +void SharedLinkManager::DecreaseSharedLink() +{ + if (sharedLinkCount == 0) { + WIFI_LOGE("Decrease error for sharedLinkCount == 0!"); + return; + } + WIFI_LOGI("Decrease shared link %{public}d -> %{public}d", sharedLinkCount.load(), sharedLinkCount.load() - 1); + --sharedLinkCount; +} + +void SharedLinkManager::SetSharedLinkCount(int count) +{ + WIFI_LOGI("Set sharedLinkCount: %{public}d", count); + sharedLinkCount = count; +} + +int SharedLinkManager::GetSharedLinkCount() +{ + WIFI_LOGI("Get sharedLinkCount: %{public}d", sharedLinkCount.load()); + return sharedLinkCount; +} +} // namespace Wifi +} // namespace OHOS \ No newline at end of file diff --git a/wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/hid2d/wifi_hid2d_service_utils.h b/wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/hid2d/wifi_hid2d_service_utils.h new file mode 100644 index 0000000000000000000000000000000000000000..b364fe6cc9829d3019f3c6a2e271c63e0a577706 --- /dev/null +++ b/wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/hid2d/wifi_hid2d_service_utils.h @@ -0,0 +1,56 @@ +/* + * Copyright (C) 2022 Huawei Device Co., Ltd. + * 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 OHOS_WIFI_HID2D_SERVICE_UTILS_H +#define OHOS_WIFI_HID2D_SERVICE_UTILS_H + +#include +#include +#include +#include + +namespace OHOS { +namespace Wifi { +class IpPool { +public: + static bool InitIpPool(const std::string& serverIp); + static std::string GetIp(const std::string& gcMac); + static void ReleaseIp(const std::string& gcMac); + static void ReleaseIpPool(); + +private: + static bool IsValidIp(const std::string& ip); + + static std::list ipList; + static std::map mapGcMacToAllocIp; + static constexpr int HID2D_IPPOOL_START = 3; + static constexpr int HID2D_IPPOOL_END = 75; +}; + +const int SHARED_LINKE_COUNT_ON_DISCONNECTED = 0; +const int SHARED_LINKE_COUNT_ON_CONNECTED = 1; +class SharedLinkManager { +public: + static void IncreaseSharedLink(); + static void DecreaseSharedLink(); + static void SetSharedLinkCount(int count); + static int GetSharedLinkCount(); + +private: + static std::atomic_int sharedLinkCount; +}; +} // namespace Wifi +} // namespace OHOS +#endif \ No newline at end of file diff --git a/services/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/invitation_received_state.cpp b/wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/invitation_received_state.cpp similarity index 97% rename from services/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/invitation_received_state.cpp rename to wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/invitation_received_state.cpp index 3c3169a9406f9f380cc8049836be7cca29379767..30b7a221c65fcd2e949bda39c667ffe8dcabeb80 100644 --- a/services/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/invitation_received_state.cpp +++ b/wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/invitation_received_state.cpp @@ -47,7 +47,7 @@ bool InvitationReceivedState::ExecuteStateMsg(InternalMessage *msg) if (wps.GetWpsMethod() == WpsMethod::WPS_METHOD_KEYPAD) { std::string inputPin; if (!msg->GetMessageObj(inputPin)) { - WIFI_LOGD("Failed to obtain the pin code."); + WIFI_LOGW("Failed to obtain the pin code."); break; } WpsInfo wpsPin = wps; diff --git a/services/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/invitation_received_state.h b/wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/invitation_received_state.h similarity index 100% rename from services/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/invitation_received_state.h rename to wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/invitation_received_state.h diff --git a/services/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/invitation_request_state.cpp b/wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/invitation_request_state.cpp similarity index 96% rename from services/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/invitation_request_state.cpp rename to wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/invitation_request_state.cpp index 6fd74cb9835334b597a24119cc974c5a49fc98a0..1745fbc40114e972c2cedb17016daf0fac311a0f 100644 --- a/services/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/invitation_request_state.cpp +++ b/wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/invitation_request_state.cpp @@ -56,7 +56,7 @@ bool InvitationRequestState::ExecuteStateMsg(InternalMessage *msg) if (status == P2pStatus::UNKNOWN_P2P_GROUP) { int netId = groupManager.GetCurrentGroup().GetNetworkId(); if (netId >= 0) { - WIFI_LOGD("Remove unknown client from currentGroup"); + WIFI_LOGW("Remove unknown client from currentGroup"); p2pStateMachine.groupManager.RemoveClientFromGroup( netId, p2pStateMachine.savedP2pConfig.GetDeviceAddress()); p2pStateMachine.SwitchState(&p2pStateMachine.p2pGroupFormedState); @@ -68,7 +68,7 @@ bool InvitationRequestState::ExecuteStateMsg(InternalMessage *msg) if (status == P2pStatus::SUCCESS) { WIFI_LOGI("Invitation succeeded."); } else { - WIFI_LOGD("Invitation failed."); + WIFI_LOGW("Invitation failed."); } p2pStateMachine.SwitchState(&p2pStateMachine.p2pGroupFormedState); break; diff --git a/services/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/invitation_request_state.h b/wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/invitation_request_state.h similarity index 100% rename from services/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/invitation_request_state.h rename to wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/invitation_request_state.h diff --git a/services/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/ip2p_service.h b/wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/ip2p_service.h similarity index 55% rename from services/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/ip2p_service.h rename to wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/ip2p_service.h index 1914e9af3071766e6dffb4a5a44737a2da60435e..1c9f254771a6d9a46d5b6ef3d212a2a3ee8f24dd 100644 --- a/services/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/ip2p_service.h +++ b/wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/ip2p_service.h @@ -1,5 +1,5 @@ /* - * Copyright (C) 2021 Huawei Device Co., Ltd. + * Copyright (C) 2021-2022 Huawei Device Co., Ltd. * 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 @@ -12,12 +12,14 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + #ifndef OHOS_IP2P_SERVICE_H #define OHOS_IP2P_SERVICE_H #include "wifi_errcode.h" #include "wifi_msg.h" #include "ip2p_service_callbacks.h" +#include "wifi_hid2d_msg.h" namespace OHOS { namespace Wifi { @@ -30,51 +32,51 @@ public: /** * @Description - The interface of enable p2p. - * @return - ErrCode + * @return ErrCode - operation result */ virtual ErrCode EnableP2p() = 0; /** * @Description - The interface of disable p2p. - * @return - ErrCode + * @return ErrCode - operation result */ virtual ErrCode DisableP2p() = 0; /** * @Description - The interface of start discover peers. - * @return - ErrCode + * @return ErrCode - operation result */ virtual ErrCode DiscoverDevices() = 0; /** * @Description - The interface of stop discover peers. - * @return - ErrCode + * @return ErrCode - operation result */ virtual ErrCode StopDiscoverDevices() = 0; /** * @Description - The interface of start discover services. - * @return - ErrCode + * @return ErrCode - operation result */ virtual ErrCode DiscoverServices() = 0; /** * @Description - The interface of stop discover services. - * @return - ErrCode + * @return ErrCode - operation result */ virtual ErrCode StopDiscoverServices() = 0; /** * @Description - The interface of add local p2p service. * @param srvInfo - information of service. - * @return - ErrCode + * @return ErrCode - operation result */ virtual ErrCode PutLocalP2pService(const WifiP2pServiceInfo &srvInfo) = 0; /** * @Description - The interface of delete local p2p service. * @param srvInfo - information of service. - * @return - ErrCode + * @return ErrCode - operation result */ virtual ErrCode DeleteLocalP2pService(const WifiP2pServiceInfo &srvInfo) = 0; @@ -82,7 +84,7 @@ public: * @Description - The interface of add service request. * @param device - target device information. * @param request - request information. - * @return - ErrCode + * @return ErrCode - operation result */ virtual ErrCode RequestService(const WifiP2pDevice &device, const WifiP2pServiceRequest &request) = 0; @@ -90,48 +92,48 @@ public: * @Description - The interface of start p2p listen(milliseconds). * @param period - time of period. * @param interval - time of interval. - * @return - ErrCode + * @return ErrCode - operation result */ virtual ErrCode StartP2pListen(int period, int interval) = 0; /** * @Description - The interface of stop p2p listen. - * @return - ErrCode + * @return ErrCode - operation result */ virtual ErrCode StopP2pListen() = 0; /** * @DescriptionCreate - The interface of create group. * @param config - configure of group. - * @return - ErrCode + * @return ErrCode - operation result */ - virtual ErrCode FormGroup(const WifiP2pConfig &config) = 0; + virtual ErrCode CreateGroup(const WifiP2pConfig &config) = 0; /** * @Description - The interface of remove current group. - * @return - ErrCode + * @return ErrCode - operation result */ virtual ErrCode RemoveGroup() = 0; /** * @Description - The interface of delete a saved group. * @param group - information of group. - * @return - ErrCode + * @return ErrCode - operation result */ virtual ErrCode DeleteGroup(const WifiP2pGroupInfo &group) = 0; /** * @Description - The interface of p2p connect. * @param config - configure of connect. - * @return - ErrCode + * @return ErrCode - operation result */ virtual ErrCode P2pConnect(const WifiP2pConfig &config) = 0; /** - * @Description - The interface of p2p disconnect. - * @return - ErrCode + * @Description - The interface of canceling a p2p connection. + * @return ErrCode - operation result */ - virtual ErrCode P2pDisConnect() = 0; + virtual ErrCode P2pCancelConnect() = 0; /** * @Description - Set this device name. * @@ -141,64 +143,71 @@ public: virtual ErrCode SetP2pDeviceName(const std::string &devName) = 0; /** * @Description - The interface of query p2p information like the group state,device information and ip address. - * @param connInfo - struct WifiP2pInfo. - * @return - ErrCode + * @param linkedInfo - struct WifiP2pLinkedInfo. + * @return ErrCode - operation result */ - virtual ErrCode QueryP2pInfo(WifiP2pInfo &connInfo) = 0; + virtual ErrCode QueryP2pLinkedInfo(WifiP2pLinkedInfo &linkedInfo) = 0; /** * @DescriptionGet - The interface of get current group information. * @param group - struct WifiP2pGroupInfo. - * @return - ErrCode + * @return ErrCode - operation result */ virtual ErrCode GetCurrentGroup(WifiP2pGroupInfo &group) = 0; /** * @Description - The interface of get p2p running status. * @param status - information of status. - * @return - ErrCode + * @return ErrCode - operation result */ virtual ErrCode GetP2pEnableStatus(int &status) = 0; /** * @Description - The interface of get p2p discover status. * @param status - information of status. - * @return - ErrCode + * @return ErrCode - operation result */ virtual ErrCode GetP2pDiscoverStatus(int &status) = 0; /** * @Description - The interface of get p2p connected status. * @param status - information of status. - * @return - ErrCode + * @return ErrCode - operation result */ virtual ErrCode GetP2pConnectedStatus(int &status) = 0; /** * @Description - The interface of query p2p devices information. - * @param devives - information of devices. - * @return - ErrCode + * @param devices - information of devices. + * @return ErrCode - operation result + */ + virtual ErrCode QueryP2pDevices(std::vector &devices) = 0; + + /** + * @Description - Query the information about own device. + * @param device - own device + * @return ErrCode - operation result */ - virtual ErrCode QueryP2pDevices(std::vector &devives) = 0; + virtual ErrCode QueryP2pLocalDevice(WifiP2pDevice &device) = 0; /** * @Description - The interface of query p2p group information. * @param groups - information of groups. - * @return - ErrCode + * @return ErrCode - operation result */ virtual ErrCode QueryP2pGroups(std::vector &groups) = 0; /** * @Description - The interface of query p2p services information. * @param services - information of services. - * @return - ErrCode + * @return ErrCode - operation result */ virtual ErrCode QueryP2pServices(std::vector &services) = 0; /** * @Description - The interface of register p2p service callbacks, * @param callbacks - information of callbacks. - * @return - ErrCode + * @return ErrCode - operation result */ virtual ErrCode RegisterP2pServiceCallbacks(const IP2pServiceCallbacks &callbacks) = 0; @@ -206,9 +215,99 @@ public: * @Description set p2p wifi display info * * @param wfdInfo - wifi display info - * @return ErrCode - operate result + * @return ErrCode - operation result */ virtual ErrCode SetP2pWfdInfo(const WifiP2pWfdInfo &wfdInfo) = 0; + + /** + * @Description Create hid2d group, used on the GO side. + * + * @param frequency - frequency + * @param type - frequency type + * @return ErrCode - operation result + */ + virtual ErrCode Hid2dCreateGroup(const int frequency, FreqType type) = 0; + + /** + * @Description Connect to a specified group using hid2d, used on the GC side. + * + * @param config - connection parameters + * @return ErrCode - operation result + */ + virtual ErrCode Hid2dConnect(const Hid2dConnectConfig& config) = 0; + + /** + * @Description Get self config info + * + * @param cfgType - config type + * @param cfgData - config data + * @param getDatValidLen - data length + * @return ErrCode - operate result + */ + virtual ErrCode Hid2dGetSelfWifiCfgInfo(SelfCfgType cfgType, + char cfgData[CFG_DATA_MAX_BYTES], int* getDatValidLen) = 0; + + /** + * @Description Set self config info + * + * @param cfgType - config type + * @param cfgData - config data + * @param setDataValidLen - data length + * @return ErrCode - operate result + */ + virtual ErrCode Hid2dSetPeerWifiCfgInfo(PeerCfgType cfgType, + char cfgData[CFG_DATA_MAX_BYTES], int setDataValidLen) = 0; + + /** + * @Description Set self config info + * + * @param gcMac - gc mac address + * @param ipAddr - allocated ip address + * @return ErrCode - operate result + */ + virtual ErrCode Hid2dRequestGcIp(const std::string& gcMac, std::string& ipAddr) = 0; + + /** + * @Description Increase the reference count of the hid2d service. + * + */ + virtual void IncreaseSharedLink(void) = 0; + + /** + * @Description Decrease the reference count of the hid2d service. + * + */ + virtual void DecreaseSharedLink(void) = 0; + + /** + * @Description Get the reference count of the hid2d service. + * + * @return int - reference count + */ + virtual int GetSharedLinkCount(void) = 0; + + /** + * @Description - Get P2P recommended channel. + * + * @return - int - Recommended channel + */ + virtual int GetP2pRecommendChannel(void) = 0; + + /** + * @Description Set the scene of upper layer + * + * @param ifName - interface name + * @param scene - scene + * @return ErrCode - operate result + */ + virtual ErrCode Hid2dSetUpperScene(const std::string& ifName, const Hid2dUpperScene& scene) = 0; + + /** + * @Description Monitor the wifi configuration change + * + * @return ErrCode - operate result + */ + virtual ErrCode MonitorCfgChange(void) = 0; }; } // namespace Wifi } // namespace OHOS diff --git a/services/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/ip2p_service_callbacks.h b/wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/ip2p_service_callbacks.h similarity index 71% rename from services/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/ip2p_service_callbacks.h rename to wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/ip2p_service_callbacks.h index 2d742d727435b3aac72b0c276b122a21b316056d..cbdb53eab3935f0670ae992c8a94b8e5b488e115 100644 --- a/services/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/ip2p_service_callbacks.h +++ b/wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/ip2p_service_callbacks.h @@ -18,6 +18,7 @@ #include #include "wifi_errcode.h" #include "wifi_p2p_msg.h" +#include "wifi_hid2d_msg.h" namespace OHOS { namespace Wifi { @@ -30,7 +31,7 @@ struct IP2pServiceCallbacks { /* Report the latest services discovery information. */ std::function &)> OnP2pServicesChangedEvent; /* The event of connection status change. */ - std::function OnP2pConnectionChangedEvent; + std::function OnP2pConnectionChangedEvent; /* The event of this device configure has change */ std::function OnP2pThisDeviceChangedEvent; /* The event of discovery status change */ @@ -39,6 +40,14 @@ struct IP2pServiceCallbacks { std::function OnP2pGroupsChangedEvent; /* The result returned by the asynchronous interface */ std::function OnP2pActionResultEvent; + /* The event of config change */ + std::function OnConfigChangedEvent; + std::function &, const WifiP2pDevice &)> + OnP2pServiceAvailable; + std::function OnP2pDnsSdServiceAvailable; + std::function &, const WifiP2pDevice &)> + OnP2pDnsSdTxtRecordAvailable; + std::function &, const WifiP2pDevice &)> OnP2pUpnpServiceAvailable; }; } // namespace Wifi } // namespace OHOS diff --git a/services/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/p2p_default_state.cpp b/wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/p2p_default_state.cpp similarity index 100% rename from services/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/p2p_default_state.cpp rename to wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/p2p_default_state.cpp diff --git a/services/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/p2p_default_state.h b/wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/p2p_default_state.h similarity index 100% rename from services/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/p2p_default_state.h rename to wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/p2p_default_state.h diff --git a/services/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/p2p_define.h b/wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/p2p_define.h similarity index 91% rename from services/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/p2p_define.h rename to wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/p2p_define.h index 6ad61b11bad3106c0ae65dfb88435206a1a59afc..cbce583524157b7017b0a77fbf1158d97d739d35 100644 --- a/services/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/p2p_define.h +++ b/wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/p2p_define.h @@ -1,5 +1,5 @@ /* - * Copyright (C) 2021 Huawei Device Co., Ltd. + * Copyright (C) 2021-2022 Huawei Device Co., Ltd. * 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 @@ -12,6 +12,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + #ifndef OHOS_WIFI_P2P_DEFINE_H #define OHOS_WIFI_P2P_DEFINE_H @@ -21,9 +22,13 @@ namespace OHOS { namespace Wifi { +#ifdef NON_SEPERATE_P2P +const std::string P2P_INTERFACE("p2p-dev-wlan0"); +#else const std::string P2P_INTERFACE("p2p0"); +#endif /* The timeout interval of enable p2p */ -constexpr long ENABLE_P2P_TIMED_OUT__INTERVAL = 5000; +constexpr long ENABLE_P2P_TIMED_OUT__INTERVAL = 15000; /* The time of clears service requests processed in records. */ constexpr long REMOVE_SERVICE_REQUEST_RECORD = 3000; @@ -106,6 +111,9 @@ enum class P2P_STATE_MACHINE_CMD { CMD_DISCONNECT, CMD_SET_DEVICE_NAME, /* set device name */ CMD_SET_WFD_INFO, /* set wifi-display info */ + CMD_CANCEL_CONNECT, /* cancel connect */ + CMD_HID2D_CREATE_GROUP, /* hid2d create group */ + CMD_HID2D_CONNECT, /* monitor to state machine */ WPA_CONNECTED_EVENT = 100, // result of connect @@ -131,12 +139,14 @@ enum class P2P_STATE_MACHINE_CMD { P2P_EVENT_PROV_DISC_FAILURE, AP_STA_DISCONNECTED, AP_STA_CONNECTED, + P2P_EVENT_IFACE_CREATED, /* if the requests to WPA is not synchronization need protected by a timeout mechanism */ ENABLE_P2P_TIMED_OUT = 200, INTERNAL_CONN_USER_CONFIRM, // the user confirmed INTERNAL_CONN_USER_ACCEPT, // the user chooses to agree PEER_CONNECTION_USER_REJECT, // the user chooses to reject + INTERNAL_CONN_USER_TIME_OUT, CREATE_GROUP_TIMED_OUT, EXCEPTION_TIMED_OUT, /* P2P exception timeout */ DISABLE_P2P_TIMED_OUT, @@ -144,7 +154,7 @@ enum class P2P_STATE_MACHINE_CMD { }; using HandlerMethod = void(P2P_STATE_MACHINE_CMD, int, int, const std::any &); -}; // namespace Wifi +} // namespace Wifi } // namespace OHOS -#endif \ No newline at end of file +#endif diff --git a/services/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/p2p_disabled_state.cpp b/wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/p2p_disabled_state.cpp similarity index 100% rename from services/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/p2p_disabled_state.cpp rename to wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/p2p_disabled_state.cpp diff --git a/services/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/p2p_disabled_state.h b/wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/p2p_disabled_state.h similarity index 100% rename from services/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/p2p_disabled_state.h rename to wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/p2p_disabled_state.h diff --git a/services/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/p2p_disabling_state.cpp b/wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/p2p_disabling_state.cpp similarity index 100% rename from services/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/p2p_disabling_state.cpp rename to wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/p2p_disabling_state.cpp diff --git a/services/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/p2p_disabling_state.h b/wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/p2p_disabling_state.h similarity index 100% rename from services/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/p2p_disabling_state.h rename to wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/p2p_disabling_state.h diff --git a/services/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/p2p_enabled_state.cpp b/wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/p2p_enabled_state.cpp similarity index 86% rename from services/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/p2p_enabled_state.cpp rename to wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/p2p_enabled_state.cpp index bf58a4bfa1b409d707ae90a876969a34c122839d..95d4124fdbe1c83ee01e6498d042d88a57934cf3 100644 --- a/services/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/p2p_enabled_state.cpp +++ b/wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/p2p_enabled_state.cpp @@ -1,5 +1,5 @@ /* - * Copyright (C) 2021 Huawei Device Co., Ltd. + * Copyright (C) 2021-2022 Huawei Device Co., Ltd. * 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 @@ -12,6 +12,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + #include "p2p_enabled_state.h" #include #include "wifi_logger.h" @@ -24,25 +25,32 @@ DEFINE_WIFILOG_P2P_LABEL("P2pEnabledState"); namespace OHOS { namespace Wifi { -P2pEnabledState::P2pEnabledState( - P2pStateMachine &stateMachine, WifiP2pGroupManager &groupMgr, WifiP2pDeviceManager &deviceMgr) - : State("P2pEnabledState"), mProcessFunMap(), p2pStateMachine(stateMachine), groupManager(groupMgr), deviceManager(deviceMgr) +P2pEnabledState::P2pEnabledState(P2pStateMachine &stateMachine, WifiP2pGroupManager &groupMgr, + WifiP2pDeviceManager &deviceMgr) + : State("P2pEnabledState"), + mProcessFunMap(), + p2pStateMachine(stateMachine), + groupManager(groupMgr), + deviceManager(deviceMgr) {} void P2pEnabledState::GoInState() { WIFI_LOGI(" GoInState"); Init(); - constexpr int defaultListenTime = 500; + constexpr int defaultPeriodTime = 500; + constexpr int defaultIntervalTime = 1000; p2pStateMachine.BroadcastP2pConnectionChanged(); if (P2pSettingsInitialization()) { p2pStateMachine.BroadcastP2pStatusChanged(P2pState::P2P_STATE_STARTED); P2pVendorConfig config; WifiSettings::GetInstance().GetP2pVendorConfig(config); if (config.GetIsAutoListen()) { + WIFI_LOGI("Auto start P2P listen!"); p2pStateMachine.SendMessage( - static_cast(P2P_STATE_MACHINE_CMD::CMD_START_LISTEN), defaultListenTime, defaultListenTime); + static_cast(P2P_STATE_MACHINE_CMD::CMD_START_LISTEN), defaultPeriodTime, defaultIntervalTime); } } else { + WIFI_LOGE("P2pSettingsInitialization Failed, Start Disable P2P!"); p2pStateMachine.SendMessage(static_cast(P2P_STATE_MACHINE_CMD::CMD_P2P_DISABLE)); } } @@ -91,10 +99,12 @@ void P2pEnabledState::Init() std::make_pair(P2P_STATE_MACHINE_CMD::CMD_SET_DEVICE_NAME, &P2pEnabledState::ProcessCmdSetDeviceName)); mProcessFunMap.insert( std::make_pair(P2P_STATE_MACHINE_CMD::CMD_SET_WFD_INFO, &P2pEnabledState::ProcessCmdSetWfdInfo)); + mProcessFunMap.insert( + std::make_pair(P2P_STATE_MACHINE_CMD::CMD_CANCEL_CONNECT, &P2pEnabledState::ProcessCmdCancelConnect)); } bool P2pEnabledState::ProcessCmdDisable(InternalMessage &msg) const { - WIFI_LOGI("recv CMD: %{public}d", msg.GetMessageName()); + WIFI_LOGI("P2P ProcessCmdDisable recv CMD: %{public}d", msg.GetMessageName()); p2pStateMachine.BroadcastP2pStatusChanged(P2pState::P2P_STATE_CLOSING); WifiP2PHalInterface::GetInstance().P2pStopFind(); p2pStateMachine.BroadcastP2pDiscoveryChanged(false); @@ -130,7 +140,7 @@ bool P2pEnabledState::ProcessCmdStartListen(InternalMessage &msg) const } bool P2pEnabledState::ProcessCmdStopListen(InternalMessage &msg) const { - WIFI_LOGI("recv CMD: %{public}d", msg.GetMessageName()); + WIFI_LOGI("P2P ProcessCmdStopListen recv CMD: %{public}d", msg.GetMessageName()); if (WifiP2PHalInterface::GetInstance().P2pConfigureListen(false, 0, 0)) { WIFI_LOGE("p2p configure to stop listen failed."); p2pStateMachine.BroadcastActionResult(P2pActionCallback::StopP2pListen, WIFI_OPT_FAILED); @@ -146,13 +156,13 @@ bool P2pEnabledState::ProcessCmdStopListen(InternalMessage &msg) const } bool P2pEnabledState::ProcessCmdDiscPeer(InternalMessage &msg) const { - WIFI_LOGI("recv CMD: %{public}d", msg.GetMessageName()); + WIFI_LOGI("P2P ProcessCmdDiscPeer recv CMD: %{public}d", msg.GetMessageName()); p2pStateMachine.HandlerDiscoverPeers(); return EXECUTED; } bool P2pEnabledState::ProcessCmdStopDiscPeer(InternalMessage &msg) const { - WIFI_LOGI("recv CMD: %{public}d", msg.GetMessageName()); + WIFI_LOGI("P2P ProcessCmdStopDiscPeer recv CMD: %{public}d", msg.GetMessageName()); WifiErrorNo retCode = WifiP2PHalInterface::GetInstance().P2pStopFind(); if (retCode == WifiErrorNo::WIFI_IDL_OPT_OK) { p2pStateMachine.BroadcastActionResult(P2pActionCallback::StopDiscoverDevices, ErrCode::WIFI_OPT_SUCCESS); @@ -163,7 +173,7 @@ bool P2pEnabledState::ProcessCmdStopDiscPeer(InternalMessage &msg) const } bool P2pEnabledState::ProcessDeviceFoundEvt(InternalMessage &msg) const { - WIFI_LOGD("p2p_enabled_state recv P2P_EVENT_DEVICE_FOUND"); + WIFI_LOGI("p2p_enabled_state recv P2P_EVENT_DEVICE_FOUND"); WifiP2pDevice device; if (!msg.GetMessageObj(device)) { WIFI_LOGE("Failed to obtain device information."); @@ -179,7 +189,7 @@ bool P2pEnabledState::ProcessDeviceFoundEvt(InternalMessage &msg) const } bool P2pEnabledState::ProcessDeviceLostEvt(InternalMessage &msg) const { - WIFI_LOGD("p2p_enabled_state recv P2P_EVENT_DEVICE_LOST"); + WIFI_LOGI("p2p_enabled_state recv P2P_EVENT_DEVICE_LOST"); WifiP2pDevice device; if (!msg.GetMessageObj(device)) { WIFI_LOGE("Failed to obtain device information."); @@ -200,7 +210,7 @@ bool P2pEnabledState::ProcessDeviceLostEvt(InternalMessage &msg) const } bool P2pEnabledState::ProcessFindStoppedEvt(InternalMessage &msg) const { - WIFI_LOGI("recv event: %{public}d", msg.GetMessageName()); + WIFI_LOGI("P2P ProcessFindStoppedEvt recv event: %{public}d", msg.GetMessageName()); p2pStateMachine.BroadcastP2pDiscoveryChanged(false); return EXECUTED; } @@ -246,13 +256,17 @@ bool P2pEnabledState::P2pConfigInitialization() retCode = WifiP2PHalInterface::GetInstance().SetP2pSsidPostfix(ssidPostfixName); if (retCode == WifiErrorNo::WIFI_IDL_OPT_FAILED) { WIFI_LOGE("Failed to set the SSID prefix"); - result = false; } - retCode = WifiP2PHalInterface::GetInstance().SetP2pDeviceType(deviceManager.GetThisDevice().GetPrimaryDeviceType()); - if (retCode == WifiErrorNo::WIFI_IDL_OPT_FAILED) { - WIFI_LOGE("Failed to set the device type."); - result = false; + std::string primaryDeviceType = deviceManager.GetThisDevice().GetPrimaryDeviceType(); + if (!primaryDeviceType.empty()) { + retCode = WifiP2PHalInterface::GetInstance().SetP2pDeviceType(primaryDeviceType); + if (retCode == WifiErrorNo::WIFI_IDL_OPT_FAILED) { + WIFI_LOGE("Failed to set the device type."); + result = false; + } + } else { + WIFI_LOGE("Primary device type is empty!!!"); } std::string secDeviceType = deviceManager.GetThisDevice().GetSecondaryDeviceType(); @@ -260,7 +274,6 @@ bool P2pEnabledState::P2pConfigInitialization() retCode = WifiP2PHalInterface::GetInstance().SetP2pSecondaryDeviceType(secDeviceType); if (retCode == WifiErrorNo::WIFI_IDL_OPT_FAILED) { WIFI_LOGE("Failed to set the secondary device type."); - result = false; } } @@ -273,7 +286,7 @@ bool P2pEnabledState::P2pConfigInitialization() retCode = WifiP2PHalInterface::GetInstance().SetPersistentReconnect(1); if (retCode == WifiErrorNo::WIFI_IDL_OPT_FAILED) { - LOGE("Failed to set persistent reconnect."); + WIFI_LOGE("Failed to set persistent reconnect."); result = false; } @@ -285,15 +298,15 @@ bool P2pEnabledState::P2pConfigInitialization() } deviceManager.GetThisDevice().SetDeviceAddress(deviceAddr); - p2pStateMachine.UpdateGroupInfoToWpa(); return result; } bool P2pEnabledState::P2pSettingsInitialization() { - bool result = P2pConfigInitialization(); + WIFI_LOGI("Start P2pSettingsInitialization"); + bool result = P2pConfigInitialization(); p2pStateMachine.UpdateOwnDevice(P2pDeviceStatus::PDS_AVAILABLE); WifiErrorNo retCode = WifiP2PHalInterface::GetInstance().P2pFlush(); @@ -315,22 +328,14 @@ bool P2pEnabledState::P2pSettingsInitialization() result = false; } - std::map wpaGroups; - retCode = WifiP2PHalInterface::GetInstance().ListNetworks(wpaGroups); - if (retCode == WifiErrorNo::WIFI_IDL_OPT_FAILED) { - WIFI_LOGE("Failed to get listNetworks."); - result = false; - } - groupManager.UpdateGroupsNetwork(wpaGroups); - + p2pStateMachine.UpdateGroupManager(); p2pStateMachine.UpdatePersistentGroups(); - return result; } bool P2pEnabledState::ProcessCmdAddLocalService(InternalMessage &msg) const { - WIFI_LOGD("p2p_enabled_state recv CMD_PUT_LOCAL_SERVICE"); + WIFI_LOGI("p2p_enabled_state recv CMD_PUT_LOCAL_SERVICE"); WifiP2pServiceInfo service; if (!msg.GetMessageObj(service)) { WIFI_LOGE("Failed to obtain WifiP2pServiceInfo information."); @@ -370,7 +375,7 @@ bool P2pEnabledState::ProcessCmdDelLocalService(InternalMessage &msg) const bool P2pEnabledState::ProcessCmdDiscServices(InternalMessage &msg) const { - WIFI_LOGI("recv CMD: %{public}d", msg.GetMessageName()); + WIFI_LOGI("P2P ProcessCmdDiscServices recv CMD: %{public}d", msg.GetMessageName()); p2pStateMachine.CancelSupplicantSrvDiscReq(); std::string reqId; WifiP2pServiceRequest request; @@ -395,7 +400,7 @@ bool P2pEnabledState::ProcessCmdDiscServices(InternalMessage &msg) const return EXECUTED; } - WIFI_LOGD("CMD_DISCOVER_SERVICES successful."); + WIFI_LOGI("CMD_DISCOVER_SERVICES successful."); p2pStateMachine.BroadcastActionResult(P2pActionCallback::DiscoverServices, ErrCode::WIFI_OPT_SUCCESS); p2pStateMachine.BroadcastP2pDiscoveryChanged(true); return EXECUTED; @@ -403,7 +408,7 @@ bool P2pEnabledState::ProcessCmdDiscServices(InternalMessage &msg) const bool P2pEnabledState::ProcessCmdStopDiscServices(InternalMessage &msg) const { - WIFI_LOGI("recv CMD: %{public}d", msg.GetMessageName()); + WIFI_LOGI("P2P ProcessCmdStopDiscServices recv CMD: %{public}d", msg.GetMessageName()); WifiErrorNo retCode = WifiP2PHalInterface::GetInstance().P2pStopFind(); if (retCode == WifiErrorNo::WIFI_IDL_OPT_OK) { p2pStateMachine.BroadcastActionResult(P2pActionCallback::StopDiscoverServices, ErrCode::WIFI_OPT_SUCCESS); @@ -448,7 +453,7 @@ bool P2pEnabledState::ProcessCmdRequestService(InternalMessage &msg) const bool P2pEnabledState::ProcessServiceDiscReqEvt(InternalMessage &msg) const { - WIFI_LOGD("p2p_enabled_state recv P2P_EVENT_SERV_DISC_REQ"); + WIFI_LOGI("p2p_enabled_state recv P2P_EVENT_SERV_DISC_REQ"); WifiP2pServiceRequestList reqList; if (!msg.GetMessageObj(reqList)) { WIFI_LOGE("Failed to obtain WifiP2pServiceRequestList information."); @@ -487,7 +492,7 @@ bool P2pEnabledState::ProcessServiceDiscReqEvt(InternalMessage &msg) const bool P2pEnabledState::ProcessServiceDiscRspEvt(InternalMessage &msg) const { - WIFI_LOGD("p2p_enabled_state recv P2P_EVENT_SERV_DISC_RESP"); + WIFI_LOGI("p2p_enabled_state recv P2P_EVENT_SERV_DISC_RESP"); WifiP2pServiceResponseList respList; if (!msg.GetMessageObj(respList)) { WIFI_LOGE("Failed to obtain WifiP2pServiceResponseList information."); @@ -504,14 +509,14 @@ bool P2pEnabledState::ProcessServiceDiscRspEvt(InternalMessage &msg) const } bool P2pEnabledState::ProcessExceptionTimeOut(InternalMessage &msg) const { - WIFI_LOGI("recv exception timeout event: %d", msg.GetMessageName()); + WIFI_LOGI("recv exception timeout event: %{public}d", msg.GetMessageName()); p2pStateMachine.SwitchState(&p2pStateMachine.p2pIdleState); return EXECUTED; } bool P2pEnabledState::ProcessCmdSetDeviceName(InternalMessage &msg) const { - LOGD("p2p_enabled_state CMD: set device name."); + WIFI_LOGI("p2p_enabled_state CMD: set device name."); std::string deviceName; if (!msg.GetMessageObj(deviceName)) { LOGE("Failed to obtain string information."); @@ -520,28 +525,29 @@ bool P2pEnabledState::ProcessCmdSetDeviceName(InternalMessage &msg) const WifiErrorNo retCode = WifiP2PHalInterface::GetInstance().SetP2pDeviceName(deviceName); if (retCode == WifiErrorNo::WIFI_IDL_OPT_FAILED) { - LOGE("Failed to set the device name."); + WIFI_LOGE("Failed to set the device name."); p2pStateMachine.BroadcastActionResult(P2pActionCallback::P2pSetDeviceName, WIFI_OPT_FAILED); return EXECUTED; } else { - LOGE("Successfully set the device name."); + WIFI_LOGE("Successfully set the device name."); deviceManager.GetThisDevice().SetDeviceName(deviceName); + p2pStateMachine.BroadcastThisDeviceChanaged(deviceManager.GetThisDevice()); p2pStateMachine.BroadcastActionResult(P2pActionCallback::P2pSetDeviceName, WIFI_OPT_SUCCESS); } const std::string ssidPostfixName = std::string("-") + deviceName; retCode = WifiP2PHalInterface::GetInstance().SetP2pSsidPostfix(ssidPostfixName); if (retCode == WifiErrorNo::WIFI_IDL_OPT_FAILED) { - LOGE("Failed to set the SSID prefix"); + WIFI_LOGE("Failed to set the SSID prefix"); } return EXECUTED; } bool P2pEnabledState::ProcessCmdSetWfdInfo(InternalMessage &msg) const { - LOGI("recv CMD: %d", msg.GetMessageName()); + WIFI_LOGI("P2P ProcessCmdSetWfdInfo recv CMD: %{public}d", msg.GetMessageName()); WifiP2pWfdInfo wfdInfo; if (!msg.GetMessageObj(wfdInfo)) { - LOGE("Failed to obtain wfd information."); + WIFI_LOGE("Failed to obtain wfd information."); return EXECUTED; } @@ -549,14 +555,21 @@ bool P2pEnabledState::ProcessCmdSetWfdInfo(InternalMessage &msg) const wfdInfo.GetDeviceInfoElement(subelement); subelement = "0 " + subelement; if (WifiP2PHalInterface::GetInstance().SetWfdDeviceConfig(subelement) != WifiErrorNo::WIFI_IDL_OPT_OK) { - LOGE("Failed to set wfd config:%s.", subelement.c_str()); - return EXECUTED; + WIFI_LOGE("Failed to set wfd config:%{public}s.", subelement.c_str()); + return EXECUTED; } if (WifiP2PHalInterface::GetInstance().SetWfdEnable(wfdInfo.GetWfdEnabled()) != WifiErrorNo::WIFI_IDL_OPT_OK) { - LOGE("Set wifidisplay enabled failed."); + WIFI_LOGE("Set wifidisplay enabled failed."); return EXECUTED; } return EXECUTED; } + +bool P2pEnabledState::ProcessCmdCancelConnect(InternalMessage &msg) const +{ + WIFI_LOGI("P2P ProcessCmdCancelConnect recv CMD: %{public}d", msg.GetMessageName()); + p2pStateMachine.BroadcastActionResult(P2pActionCallback::P2pCancelConnect, ErrCode::WIFI_OPT_FAILED); + return EXECUTED; +} } // namespace Wifi } // namespace OHOS diff --git a/services/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/p2p_enabled_state.h b/wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/p2p_enabled_state.h similarity index 95% rename from services/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/p2p_enabled_state.h rename to wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/p2p_enabled_state.h index 8669b4c14d17b3dc0f2f73dea190e8e491c28d4c..7cb2746349a6d1ca7fec10969528067f16b0d68d 100644 --- a/services/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/p2p_enabled_state.h +++ b/wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/p2p_enabled_state.h @@ -33,7 +33,7 @@ public: * @param None * @return None */ - P2pEnabledState(P2pStateMachine &, WifiP2pGroupManager &, WifiP2pDeviceManager &); + P2pEnabledState(P2pStateMachine &stateMachine, WifiP2pGroupManager &groupMgr, WifiP2pDeviceManager &deviceMgr); /** * @Description Destroy the P2pEnabledState object @@ -223,6 +223,13 @@ private: */ virtual bool ProcessCmdSetWfdInfo(InternalMessage &msg) const; + /** + * @Description Process the cancel connect command received by the state machine + * @param msg - Message body sent by the state machine + * @return - bool true:handle false:not handle + */ + virtual bool ProcessCmdCancelConnect(InternalMessage &msg) const; + private: using ProcessFun = bool (P2pEnabledState::*)(InternalMessage &msg) const; std::map mProcessFunMap; diff --git a/services/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/p2p_enabling_state.cpp b/wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/p2p_enabling_state.cpp similarity index 100% rename from services/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/p2p_enabling_state.cpp rename to wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/p2p_enabling_state.cpp diff --git a/services/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/p2p_enabling_state.h b/wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/p2p_enabling_state.h similarity index 100% rename from services/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/p2p_enabling_state.h rename to wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/p2p_enabling_state.h diff --git a/services/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/p2p_group_formation_state.cpp b/wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/p2p_group_formation_state.cpp similarity index 68% rename from services/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/p2p_group_formation_state.cpp rename to wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/p2p_group_formation_state.cpp index 2077759074efbb9bf6bf32113c639aa165c7e332..2c84684a4f306e1b202ca449c5ed19085d160ba2 100644 --- a/services/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/p2p_group_formation_state.cpp +++ b/wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/p2p_group_formation_state.cpp @@ -14,6 +14,7 @@ */ #include "p2p_group_formation_state.h" #include "p2p_state_machine.h" +#include "wifi_p2p_hal_interface.h" #include "wifi_logger.h" DEFINE_WIFILOG_P2P_LABEL("P2pGroupFormationState"); @@ -41,6 +42,21 @@ bool P2pGroupFormationState::ExecuteStateMsg(InternalMessage *msg) p2pStateMachine.BroadcastActionResult(P2pActionCallback::DiscoverDevices, ErrCode::WIFI_OPT_FAILED); break; } + case P2P_STATE_MACHINE_CMD::CMD_DISCOVER_SERVICES: { + p2pStateMachine.BroadcastActionResult(P2pActionCallback::DiscoverServices, ErrCode::WIFI_OPT_FAILED); + break; + } + case P2P_STATE_MACHINE_CMD::CMD_START_LISTEN: { + p2pStateMachine.BroadcastActionResult(P2pActionCallback::StartP2pListen, ErrCode::WIFI_OPT_FAILED); + break; + } + case P2P_STATE_MACHINE_CMD::CMD_CANCEL_CONNECT: { + WifiP2PHalInterface::GetInstance().CancelConnect(); + p2pStateMachine.DealGroupCreationFailed(); + p2pStateMachine.SwitchState(&p2pStateMachine.p2pIdleState); + p2pStateMachine.BroadcastActionResult(P2pActionCallback::P2pCancelConnect, ErrCode::WIFI_OPT_SUCCESS); + break; + } case P2P_STATE_MACHINE_CMD::P2P_EVENT_DEVICE_LOST: { return NOT_EXECUTED; } diff --git a/services/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/p2p_group_formation_state.h b/wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/p2p_group_formation_state.h similarity index 100% rename from services/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/p2p_group_formation_state.h rename to wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/p2p_group_formation_state.h diff --git a/services/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/p2p_group_join_state.cpp b/wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/p2p_group_join_state.cpp similarity index 86% rename from services/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/p2p_group_join_state.cpp rename to wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/p2p_group_join_state.cpp index b5aeef0cf39c9332a3f9c66e6f6302b224d384ad..17790cbdc2604217f85bd35f4642f459cf969466 100644 --- a/services/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/p2p_group_join_state.cpp +++ b/wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/p2p_group_join_state.cpp @@ -27,13 +27,17 @@ P2pGroupJoinState::P2pGroupJoinState( {} void P2pGroupJoinState::GoInState() { - WIFI_LOGI(" GoInState"); + WIFI_LOGI("GoInState"); p2pStateMachine.NotifyUserInvitationReceivedMessage(); + const int exceptionTimeOut = 120000; + p2pStateMachine.MessageExecutedLater( + static_cast(P2P_STATE_MACHINE_CMD::INTERNAL_CONN_USER_TIME_OUT), exceptionTimeOut); } void P2pGroupJoinState::GoOutState() { - WIFI_LOGI(" GoOutState"); + WIFI_LOGI("GoOutState"); + p2pStateMachine.StopTimer(static_cast(P2P_STATE_MACHINE_CMD::INTERNAL_CONN_USER_TIME_OUT)); } bool P2pGroupJoinState::ExecuteStateMsg(InternalMessage *msg) @@ -45,7 +49,7 @@ bool P2pGroupJoinState::ExecuteStateMsg(InternalMessage *msg) if (wps.GetWpsMethod() == WpsMethod::WPS_METHOD_KEYPAD) { std::string inputPin; if (!msg->GetMessageObj(inputPin)) { - WIFI_LOGD("Failed to obtain the pin code."); + WIFI_LOGW("Failed to obtain the pin code."); break; } WpsInfo wpsPin = wps; @@ -84,6 +88,10 @@ bool P2pGroupJoinState::ExecuteStateMsg(InternalMessage *msg) p2pStateMachine.SwitchState(&p2pStateMachine.p2pGroupFormedState); break; } + case P2P_STATE_MACHINE_CMD::INTERNAL_CONN_USER_TIME_OUT: { + p2pStateMachine.SwitchState(&p2pStateMachine.p2pGroupFormedState); + break; + } default: return NOT_EXECUTED; } diff --git a/services/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/p2p_group_join_state.h b/wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/p2p_group_join_state.h similarity index 94% rename from services/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/p2p_group_join_state.h rename to wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/p2p_group_join_state.h index 48e3583662389996c454c119b2237fddefa5be25..7281a3552965ba9dcd5322c5475d2c1993eb5e68 100644 --- a/services/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/p2p_group_join_state.h +++ b/wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/p2p_group_join_state.h @@ -31,7 +31,7 @@ public: * @param None * @return None */ - P2pGroupJoinState(P2pStateMachine &, WifiP2pGroupManager &, WifiP2pDeviceManager &); + P2pGroupJoinState(P2pStateMachine &stateMachine, WifiP2pGroupManager &groupMgr, WifiP2pDeviceManager &deviceMgr); /** * @Description Destroy the P2pGroupJoinState object diff --git a/services/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/p2p_group_operating_state.cpp b/wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/p2p_group_operating_state.cpp similarity index 75% rename from services/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/p2p_group_operating_state.cpp rename to wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/p2p_group_operating_state.cpp index dc9bb5cebd3cdd22bd7564a275372f7558e1a85e..6fc8f74b6b2aa443e3897adb36cfd4ceeaa240a9 100644 --- a/services/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/p2p_group_operating_state.cpp +++ b/wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/p2p_group_operating_state.cpp @@ -1,5 +1,5 @@ /* - * Copyright (C) 2021 Huawei Device Co., Ltd. + * Copyright (C) 2021-2022 Huawei Device Co., Ltd. * 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 @@ -12,28 +12,37 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + #include "p2p_group_operating_state.h" #include "wifi_p2p_hal_interface.h" #include "p2p_state_machine.h" #include "wifi_logger.h" +#include "if_config.h" DEFINE_WIFILOG_P2P_LABEL("P2pGroupOperatingState"); namespace OHOS { namespace Wifi { -P2pGroupOperatingState::P2pGroupOperatingState( - P2pStateMachine &stateMachine, WifiP2pGroupManager &groupMgr, WifiP2pDeviceManager &deviceMgr) - : State("P2pGroupOperatingState"), mProcessFunMap(), p2pStateMachine(stateMachine), groupManager(groupMgr), deviceManager(deviceMgr) +P2pGroupOperatingState::P2pGroupOperatingState(P2pStateMachine &stateMachine, WifiP2pGroupManager &groupMgr, + WifiP2pDeviceManager &deviceMgr) + : State("P2pGroupOperatingState"), + mProcessFunMap(), + p2pStateMachine(stateMachine), + groupManager(groupMgr), + deviceManager(deviceMgr) {} + void P2pGroupOperatingState::GoInState() { WIFI_LOGI(" GoInState"); + WifiSettings::GetInstance().SetExplicitGroup(false); Init(); } void P2pGroupOperatingState::GoOutState() { WIFI_LOGI(" GoOutState"); + WifiSettings::GetInstance().SetExplicitGroup(false); } void P2pGroupOperatingState::Init() @@ -52,13 +61,15 @@ void P2pGroupOperatingState::Init() std::make_pair(P2P_STATE_MACHINE_CMD::CMD_REMOVE_GROUP, &P2pGroupOperatingState::ProcessCmdRemoveGroup)); mProcessFunMap.insert( std::make_pair(P2P_STATE_MACHINE_CMD::CMD_DELETE_GROUP, &P2pGroupOperatingState::ProcessCmdDeleteGroup)); + mProcessFunMap.insert(std::make_pair(P2P_STATE_MACHINE_CMD::CMD_HID2D_CREATE_GROUP, + &P2pGroupOperatingState::ProcessCmdHid2dCreateGroup)); } bool P2pGroupOperatingState::ProcessCmdCreateGroup(const InternalMessage &msg) const { WifiErrorNo ret = WIFI_IDL_OPT_FAILED; const int minValidNetworkid = 0; - WifiP2pConfig config; + WifiP2pConfigInternal config; msg.GetMessageObj(config); int freq = p2pStateMachine.GetAvailableFreqByBand(config.GetGoBand()); int netId = config.GetNetId(); @@ -74,16 +85,22 @@ bool P2pGroupOperatingState::ProcessCmdCreateGroup(const InternalMessage &msg) c WIFI_LOGW("Some configuration settings failed!"); } ret = WifiP2PHalInterface::GetInstance().GroupAdd(true, netId, freq); + p2pStateMachine.UpdateGroupManager(); + p2pStateMachine.UpdatePersistentGroups(); } } else if (netId == PERSISTENT_NET_ID || netId == TEMPORARY_NET_ID) { /** * Create a new persistence group. */ - WIFI_LOGE("Create a new %s group.", (netId == PERSISTENT_NET_ID) ? "persistence" : "temporary"); - if (config.GetPassphrase().empty() && config.GetNetworkName().empty()) { + WIFI_LOGE("Create a new %{public}s group.", (netId == PERSISTENT_NET_ID) ? "persistence" : "temporary"); + if (config.GetPassphrase().empty() && config.GetGroupName().empty()) { + WifiSettings::GetInstance().SetExplicitGroup(true); ret = WifiP2PHalInterface::GetInstance().GroupAdd((netId == PERSISTENT_NET_ID) ? true : false, netId, freq); - } else if (!config.GetPassphrase().empty() && !config.GetNetworkName().empty() && + p2pStateMachine.UpdateGroupManager(); + p2pStateMachine.UpdatePersistentGroups(); + } else if (!config.GetPassphrase().empty() && !config.GetGroupName().empty() && config.GetPassphrase().length() >= MIN_PSK_LEN && config.GetPassphrase().length() <= MAX_PSK_LEN) { + WifiSettings::GetInstance().SetExplicitGroup(true); if (p2pStateMachine.DealCreateNewGroupWithConfig(config, freq)) { ret = WIFI_IDL_OPT_OK; } @@ -93,17 +110,18 @@ bool P2pGroupOperatingState::ProcessCmdCreateGroup(const InternalMessage &msg) c } if (WifiErrorNo::WIFI_IDL_OPT_FAILED == ret) { WIFI_LOGE("p2p configure to CreateGroup failed."); - p2pStateMachine.BroadcastActionResult(P2pActionCallback::FormGroup, WIFI_OPT_FAILED); + p2pStateMachine.BroadcastActionResult(P2pActionCallback::CreateGroup, WIFI_OPT_FAILED); p2pStateMachine.SwitchState(&p2pStateMachine.p2pIdleState); } else { const int cgTimedOut = 5000; WIFI_LOGI("p2p configure to CreateGroup successful."); p2pStateMachine.MessageExecutedLater( static_cast(P2P_STATE_MACHINE_CMD::CREATE_GROUP_TIMED_OUT), cgTimedOut); - p2pStateMachine.BroadcastActionResult(P2pActionCallback::FormGroup, WIFI_OPT_SUCCESS); + p2pStateMachine.BroadcastActionResult(P2pActionCallback::CreateGroup, WIFI_OPT_SUCCESS); } return EXECUTED; } + bool P2pGroupOperatingState::ProcessGroupStartedEvt(const InternalMessage &msg) const { p2pStateMachine.StopTimer(static_cast(P2P_STATE_MACHINE_CMD::CREATE_GROUP_TIMED_OUT)); @@ -117,20 +135,30 @@ bool P2pGroupOperatingState::ProcessGroupStartedEvt(const InternalMessage &msg) /** * Update groups. */ - p2pStateMachine.UpdatePersistentGroups(); + p2pStateMachine.UpdateGroupManager(); group.SetNetworkId(groupManager.GetGroupNetworkId(group.GetOwner(), group.GetGroupName())); WIFI_LOGI("the group network id is %{public}d set id is %{public}d", group.GetNetworkId(), p2pStateMachine.groupManager.GetGroupNetworkId(group.GetOwner(), group.GetGroupName())); - } - if (group.GetNetworkId() == TEMPORARY_NET_ID) { - group.SetIsPersistent(false); + p2pStateMachine.UpdatePersistentGroups(); + } else { + group.SetNetworkId(TEMPORARY_NET_ID); WIFI_LOGI("This is a temporary group."); } + + std::string goAddr = group.GetOwner().GetDeviceAddress(); if (group.IsGroupOwner()) { /* append setting the device name if this is GO */ - owner = group.GetOwner(); - owner.SetDeviceName(deviceManager.GetThisDevice().GetDeviceName()); - group.SetOwner(owner); + WifiP2pDevice thisDevice = deviceManager.GetThisDevice(); + thisDevice.SetP2pDeviceStatus(P2pDeviceStatus::PDS_CONNECTED); + thisDevice.SetDeviceAddress(goAddr); + group.SetOwner(thisDevice); + group.SetExplicitGroup(WifiSettings::GetInstance().IsExplicitGroup()); + } else { + WifiP2pDevice dev = deviceManager.GetDevices(goAddr); + dev.SetP2pDeviceStatus(P2pDeviceStatus::PDS_CONNECTED); + if (dev.IsValid()) { + group.SetOwner(dev); + } } group.SetP2pGroupStatus(P2pGroupStatus::GS_STARTED); p2pStateMachine.groupManager.SetCurrentGroup(group); @@ -143,6 +171,7 @@ bool P2pGroupOperatingState::ProcessGroupStartedEvt(const InternalMessage &msg) } else { p2pStateMachine.StartDhcpClient(); } + SharedLinkManager::SetSharedLinkCount(SHARED_LINKE_COUNT_ON_CONNECTED); p2pStateMachine.ChangeConnectedStatus(P2pConnectedState::P2P_CONNECTED); p2pStateMachine.SwitchState(&p2pStateMachine.p2pGroupFormedState); return EXECUTED; @@ -154,9 +183,10 @@ bool P2pGroupOperatingState::ProcessCreateGroupTimeOut(const InternalMessage &ms p2pStateMachine.SwitchState(&p2pStateMachine.p2pIdleState); return EXECUTED; } + bool P2pGroupOperatingState::ProcessGroupRemovedEvt(const InternalMessage &msg) const { - WIFI_LOGI("recv event: %{public}d", msg.GetMessageName()); + WIFI_LOGI("recv group remove event: %{public}d", msg.GetMessageName()); if (groupManager.GetCurrentGroup().IsPersistent()) { groupManager.StashGroups(); WifiP2pGroupInfo copy = groupManager.GetCurrentGroup(); @@ -165,6 +195,13 @@ bool P2pGroupOperatingState::ProcessGroupRemovedEvt(const InternalMessage &msg) groupManager.SetCurrentGroup(copy); groupManager.StashGroups(); } + if (groupManager.GetCurrentGroup().GetInterface() == p2pStateMachine.p2pDevIface) { + p2pStateMachine.p2pDevIface = ""; + } + p2pStateMachine.ChangeConnectedStatus(P2pConnectedState::P2P_DISCONNECTED); + IpPool::ReleaseIpPool(); + IfConfig::GetInstance().FlushIpAddr(groupManager.GetCurrentGroup().GetInterface(), IpType::IPTYPE_IPV4); + SharedLinkManager::SetSharedLinkCount(SHARED_LINKE_COUNT_ON_DISCONNECTED); if (groupManager.GetCurrentGroup().IsGroupOwner()) { if (!p2pStateMachine.StopDhcpServer()) { WIFI_LOGW("failed to stop Dhcp server."); @@ -178,10 +215,10 @@ bool P2pGroupOperatingState::ProcessGroupRemovedEvt(const InternalMessage &msg) } WifiP2pGroupInfo invalidGroup; groupManager.SetCurrentGroup(invalidGroup); - p2pStateMachine.ChangeConnectedStatus(P2pConnectedState::P2P_DISCONNECTED); p2pStateMachine.SwitchState(&p2pStateMachine.p2pIdleState); return EXECUTED; } + bool P2pGroupOperatingState::ProcessCmdDisable(const InternalMessage &msg) const { /** @@ -190,6 +227,7 @@ bool P2pGroupOperatingState::ProcessCmdDisable(const InternalMessage &msg) const p2pStateMachine.DelayMessage(&msg); return ProcessCmdRemoveGroup(msg); } + bool P2pGroupOperatingState::ProcessCmdRemoveGroup(const InternalMessage &msg) const { /** @@ -216,6 +254,9 @@ bool P2pGroupOperatingState::ProcessCmdRemoveGroup(const InternalMessage &msg) c * Only started groups can be removed. */ WIFI_LOGI("now remove : %{private}s.", group.GetInterface().c_str()); + if (p2pStateMachine.p2pDevIface == group.GetInterface()) { + p2pStateMachine.p2pDevIface = ""; + } ret = WifiP2PHalInterface::GetInstance().GroupRemove(group.GetInterface()); if (ret) { WIFI_LOGE("P2P group removal failed."); @@ -226,6 +267,7 @@ bool P2pGroupOperatingState::ProcessCmdRemoveGroup(const InternalMessage &msg) c p2pStateMachine.SwitchState(&p2pStateMachine.p2pIdleState); p2pStateMachine.BroadcastActionResult(P2pActionCallback::RemoveGroup, WIFI_OPT_FAILED); } else { + p2pStateMachine.ChangeConnectedStatus(P2pConnectedState::P2P_DISCONNECTED); WIFI_LOGI("The P2P group is successfully removed."); p2pStateMachine.BroadcastActionResult(P2pActionCallback::RemoveGroup, WIFI_OPT_SUCCESS); } @@ -236,6 +278,7 @@ bool P2pGroupOperatingState::ProcessCmdRemoveGroup(const InternalMessage &msg) c } return EXECUTED; } + bool P2pGroupOperatingState::ProcessCmdDeleteGroup(const InternalMessage &msg) const { /** @@ -267,12 +310,34 @@ bool P2pGroupOperatingState::ProcessCmdDeleteGroup(const InternalMessage &msg) c p2pStateMachine.BroadcastActionResult(P2pActionCallback::DeleteGroup, WIFI_OPT_FAILED); } else { WIFI_LOGI("The P2P group is deleted successfully."); + p2pStateMachine.UpdateGroupManager(); p2pStateMachine.UpdatePersistentGroups(); p2pStateMachine.BroadcastActionResult(P2pActionCallback::DeleteGroup, WIFI_OPT_SUCCESS); } return EXECUTED; } +bool P2pGroupOperatingState::ProcessCmdHid2dCreateGroup(const InternalMessage &msg) const +{ + WifiErrorNo ret = WIFI_IDL_OPT_FAILED; + int freq = 0; + msg.GetMessageObj(freq); + WIFI_LOGI("Create a hid2d group, frequency: %{public}d.", freq); + ret = WifiP2PHalInterface::GetInstance().GroupAdd(true, PERSISTENT_NET_ID, freq); + if (WifiErrorNo::WIFI_IDL_OPT_FAILED == ret) { + WIFI_LOGE("p2p configure to CreateGroup failed."); + p2pStateMachine.BroadcastActionResult(P2pActionCallback::CreateHid2dGroup, WIFI_OPT_FAILED); + p2pStateMachine.SwitchState(&p2pStateMachine.p2pIdleState); + } else { + const int cgTimedOut = 5000; + WIFI_LOGI("p2p configure hid2d group successful."); + p2pStateMachine.MessageExecutedLater( + static_cast(P2P_STATE_MACHINE_CMD::CREATE_GROUP_TIMED_OUT), cgTimedOut); + p2pStateMachine.BroadcastActionResult(P2pActionCallback::CreateHid2dGroup, WIFI_OPT_SUCCESS); + } + return EXECUTED; +} + bool P2pGroupOperatingState::ExecuteStateMsg(InternalMessage *msg) { if (msg == nullptr) { diff --git a/services/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/p2p_group_operating_state.h b/wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/p2p_group_operating_state.h similarity index 89% rename from services/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/p2p_group_operating_state.h rename to wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/p2p_group_operating_state.h index faab48782c2a79cc548f64a7a91776be1a8ca1f8..1a7dceb722b2b6c5d676a32f8aba2095d71224c0 100644 --- a/services/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/p2p_group_operating_state.h +++ b/wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/p2p_group_operating_state.h @@ -1,5 +1,5 @@ /* - * Copyright (C) 2021 Huawei Device Co., Ltd. + * Copyright (C) 2021-2022 Huawei Device Co., Ltd. * 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 @@ -12,6 +12,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + #ifndef OHOS_P2P_GROUP_OPERATING_STATE_H #define OHOS_P2P_GROUP_OPERATING_STATE_H @@ -27,12 +28,13 @@ class P2pGroupOperatingState : public State { FRIEND_GTEST(P2pGroupOperatingState); public: - /** + /* * * @Description Construct a new P2pGroupOperatingState object * @param None * @return None */ - P2pGroupOperatingState(P2pStateMachine &, WifiP2pGroupManager &, WifiP2pDeviceManager &); + P2pGroupOperatingState(P2pStateMachine &stateMachine, WifiP2pGroupManager &groupMgr, + WifiP2pDeviceManager &deviceMgr); /** * @Description Destroy the P2pGroupOperatingState object @@ -119,6 +121,13 @@ private: */ virtual bool ProcessCmdDeleteGroup(const InternalMessage &msg) const; + /** + * @Description Process the hid2d create group command received by the state machine + * @param msg - Message body sent by the state machine + * @return - bool true:handle false:not handle + */ + virtual bool ProcessCmdHid2dCreateGroup(const InternalMessage &msg) const; + private: using ProcessFun = bool (P2pGroupOperatingState::*)(const InternalMessage &msg) const; std::map mProcessFunMap; diff --git a/services/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/p2p_idle_state.cpp b/wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/p2p_idle_state.cpp similarity index 83% rename from services/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/p2p_idle_state.cpp rename to wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/p2p_idle_state.cpp index b9b03a23f7f46e3beacd2ad6c683d174505bf625..e5c4cb6d0531b656bd09e8f4a67a1b9d147b7215 100644 --- a/services/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/p2p_idle_state.cpp +++ b/wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/p2p_idle_state.cpp @@ -1,5 +1,5 @@ /* - * Copyright (C) 2021 Huawei Device Co., Ltd. + * Copyright (C) 2021-2022 Huawei Device Co., Ltd. * 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 @@ -12,6 +12,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + #include "p2p_idle_state.h" #include "wifi_p2p_hal_interface.h" #include "p2p_state_machine.h" @@ -64,6 +65,12 @@ void P2pIdleState::Init() std::make_pair(P2P_STATE_MACHINE_CMD::P2P_EVENT_GROUP_STARTED, &P2pIdleState::ProcessGroupStartedEvt)); mProcessFunMap.insert(std::make_pair( P2P_STATE_MACHINE_CMD::P2P_EVENT_INVITATION_RECEIVED, &P2pIdleState::ProcessInvitationReceivedEvt)); + mProcessFunMap.insert(std::make_pair(P2P_STATE_MACHINE_CMD::CMD_HID2D_CREATE_GROUP, + &P2pIdleState::ProcessCmdHid2dCreateGroup)); + mProcessFunMap.insert( + std::make_pair(P2P_STATE_MACHINE_CMD::CMD_HID2D_CONNECT, &P2pIdleState::ProcessCmdHid2dConnect)); + mProcessFunMap.insert( + std::make_pair(P2P_STATE_MACHINE_CMD::P2P_EVENT_IFACE_CREATED, &P2pIdleState::ProcessP2pIfaceCreatedEvt)); } bool P2pIdleState::ProcessCmdStopDiscPeer(InternalMessage &msg) const @@ -85,9 +92,9 @@ bool P2pIdleState::ProcessCmdStopDiscPeer(InternalMessage &msg) const bool P2pIdleState::ProcessCmdConnect(InternalMessage &msg) const { - WifiP2pConfig config; + WifiP2pConfigInternal config; if (!msg.GetMessageObj(config)) { - WIFI_LOGD("p2p connect Parameter error."); + WIFI_LOGW("p2p connect Parameter error."); p2pStateMachine.BroadcastActionResult(P2pActionCallback::P2pConnect, ErrCode::WIFI_OPT_INVALID_PARAM); return EXECUTED; } @@ -95,7 +102,7 @@ bool P2pIdleState::ProcessCmdConnect(InternalMessage &msg) const P2pConfigErrCode ret = p2pStateMachine.IsConfigUnusable(p2pStateMachine.savedP2pConfig); if (ret != P2pConfigErrCode::SUCCESS) { - WIFI_LOGD("Invalid device information."); + WIFI_LOGW("Invalid device information."); if (ret == P2pConfigErrCode::MAC_EMPTY) { p2pStateMachine.BroadcastActionResult(P2pActionCallback::P2pConnect, ErrCode::WIFI_OPT_INVALID_PARAM); } else if (ret == P2pConfigErrCode::MAC_NOT_FOUND) { @@ -131,6 +138,27 @@ bool P2pIdleState::ProcessCmdConnect(InternalMessage &msg) const return EXECUTED; } +bool P2pIdleState::ProcessCmdHid2dConnect(InternalMessage &msg) const +{ + WIFI_LOGI("Idle state hid2d connect recv CMD: %{public}d", msg.GetMessageName()); + + Hid2dConnectConfig config; + if (!msg.GetMessageObj(config)) { + WIFI_LOGE("Hid2d connect:Failed to obtain config info."); + return EXECUTED; + } + + if (!p2pStateMachine.p2pDevIface.empty()) { + WIFI_LOGE("Hid2d connect:exists dev iface %{public}s", p2pStateMachine.p2pDevIface.c_str()); + } + if (WifiErrorNo::WIFI_IDL_OPT_OK != + WifiP2PHalInterface::GetInstance().Hid2dConnect(config)) { + WIFI_LOGE("Hid2d Connection failed."); + p2pStateMachine.BroadcastActionResult(P2pActionCallback::Hid2dConnect, ErrCode::WIFI_OPT_FAILED); + } + return EXECUTED; +} + bool P2pIdleState::ProcessProvDiscPbcReqEvt(InternalMessage &msg) const { WIFI_LOGI("recv CMD: %{public}d", msg.GetMessageName()); @@ -145,9 +173,9 @@ bool P2pIdleState::ProcessProvDiscEnterPinEvt(InternalMessage &msg) const bool P2pIdleState::ProcessNegotReqEvt(InternalMessage &msg) const { - WifiP2pConfig conf; + WifiP2pConfigInternal conf; if (!msg.GetMessageObj(conf)) { - WIFI_LOGD("Failed to obtain conf."); + WIFI_LOGW("Failed to obtain conf."); return EXECUTED; } p2pStateMachine.savedP2pConfig = conf; @@ -159,10 +187,10 @@ bool P2pIdleState::ProcessProvDiscShowPinEvt(InternalMessage &msg) const { WifiP2pTempDiscEvent provDisc; if (!msg.GetMessageObj(provDisc)) { - WIFI_LOGD("Failed to obtain provDisc."); + WIFI_LOGW("Failed to obtain provDisc."); return EXECUTED; } - WifiP2pConfig config; + WifiP2pConfigInternal config; WpsInfo wps; wps.SetWpsMethod(WpsMethod::WPS_METHOD_KEYPAD); wps.SetPin(provDisc.GetPin()); @@ -209,11 +237,12 @@ bool P2pIdleState::ProcessGroupStartedEvt(InternalMessage &msg) const /** * Update groups. */ - p2pStateMachine.UpdatePersistentGroups(); + p2pStateMachine.UpdateGroupManager(); group.SetNetworkId(groupManager.GetGroupNetworkId(group.GetOwner(), group.GetGroupName())); WIFI_LOGI("the group network id is %{public}d set id is %{public}d", group.GetNetworkId(), p2pStateMachine.groupManager.GetGroupNetworkId(group.GetOwner(), group.GetGroupName())); + p2pStateMachine.UpdatePersistentGroups(); } group.SetP2pGroupStatus(P2pGroupStatus::GS_STARTED); p2pStateMachine.groupManager.SetCurrentGroup(group); @@ -232,7 +261,7 @@ bool P2pIdleState::ProcessGroupStartedEvt(InternalMessage &msg) const p2pStateMachine.BroadcastP2pPeersChanged(); } else { - WIFI_LOGD("fail:No GO device information is found."); + WIFI_LOGW("fail:No GO device information is found."); } } else { WifiP2pGroupInfo currGrp = p2pStateMachine.groupManager.GetCurrentGroup(); @@ -246,6 +275,7 @@ bool P2pIdleState::ProcessGroupStartedEvt(InternalMessage &msg) const return EXECUTED; } } + SharedLinkManager::SetSharedLinkCount(SHARED_LINKE_COUNT_ON_CONNECTED); p2pStateMachine.ChangeConnectedStatus(P2pConnectedState::P2P_CONNECTED); p2pStateMachine.SwitchState(&p2pStateMachine.p2pGroupFormedState); return EXECUTED; @@ -255,7 +285,7 @@ bool P2pIdleState::ProcessInvitationReceivedEvt(InternalMessage &msg) const { WifiP2pGroupInfo group; if (!msg.GetMessageObj(group)) { - WIFI_LOGD("p2p invitation received: Parameter error."); + WIFI_LOGW("p2p invitation received: Parameter error."); return EXECUTED; } const WifiP2pDevice &owner = group.GetOwner(); @@ -301,7 +331,7 @@ bool P2pIdleState::ProcessInvitationReceivedEvt(InternalMessage &msg) const wps.SetWpsMethod(WpsMethod::WPS_METHOD_KEYPAD); } - WifiP2pConfig config; + WifiP2pConfigInternal config; config.SetDeviceAddress(owner.GetDeviceAddress()); config.SetWpsInfo(wps); p2pStateMachine.savedP2pConfig = config; @@ -310,6 +340,30 @@ bool P2pIdleState::ProcessInvitationReceivedEvt(InternalMessage &msg) const return EXECUTED; } +bool P2pIdleState::ProcessCmdHid2dCreateGroup(InternalMessage &msg) const +{ + p2pStateMachine.DelayMessage(&msg); + p2pStateMachine.SwitchState(&p2pStateMachine.p2pGroupOperatingState); + return EXECUTED; +} + +bool P2pIdleState::ProcessP2pIfaceCreatedEvt(InternalMessage &msg) const +{ + if (msg.GetParam1() != 0) { + WIFI_LOGE("p2p interface created event receive: type error."); + return EXECUTED; + } + + std::string ifName; + if (!msg.GetMessageObj(ifName)) { + WIFI_LOGE("p2p interface created event receive: Parameter error."); + return EXECUTED; + } + p2pStateMachine.p2pDevIface = ifName; + p2pStateMachine.SwitchState(&p2pStateMachine.p2pGroupNegotiationState); + return EXECUTED; +} + bool P2pIdleState::ExecuteStateMsg(InternalMessage *msg) { if (msg == nullptr) { diff --git a/services/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/p2p_idle_state.h b/wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/p2p_idle_state.h similarity index 83% rename from services/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/p2p_idle_state.h rename to wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/p2p_idle_state.h index 9e3606c970b535a652606a2b6ec6a7709c1495ec..eda046fd705d990f090250d6c4facb9b4aefb82c 100644 --- a/services/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/p2p_idle_state.h +++ b/wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/p2p_idle_state.h @@ -1,5 +1,5 @@ /* - * Copyright (C) 2021 Huawei Device Co., Ltd. + * Copyright (C) 2021-2022 Huawei Device Co., Ltd. * 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 @@ -12,6 +12,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + #ifndef OHOS_P2P_IDLE_STATE_H #define OHOS_P2P_IDLE_STATE_H @@ -32,7 +33,7 @@ public: * @param None * @return None */ - P2pIdleState(P2pStateMachine &, WifiP2pGroupManager &, WifiP2pDeviceManager &); + P2pIdleState(P2pStateMachine &stateMachine, WifiP2pGroupManager &groupMgr, WifiP2pDeviceManager &deviceMgr); /** * @Description Destroy the P2pIdleState object @@ -147,6 +148,27 @@ private: */ virtual bool ProcessInvitationReceivedEvt(InternalMessage &msg) const; + /** + * @Description Process the hid2d create group command received by the state machine + * @param msg - Message body sent by the state machine + * @return - bool true:handle false:not handle + */ + virtual bool ProcessCmdHid2dCreateGroup(InternalMessage &msg) const; + + /** + * @Description Process the hid2d connect command received by the state machine + * @param msg - Message body sent by the state machine + * @return - bool true:handle false:not handle + */ + virtual bool ProcessCmdHid2dConnect(InternalMessage &msg) const; + + /** + * @Description Process p2p interface created event received by the state machine + * @param msg - Message body sent by the state machine + * @param @return - bool true:handle false:not handle + */ + virtual bool ProcessP2pIfaceCreatedEvt(InternalMessage &msg) const; + private: using ProcessFun = bool (P2pIdleState::*)(InternalMessage &msg) const; std::map mProcessFunMap; diff --git a/services/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/p2p_interface.cpp b/wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/p2p_interface.cpp similarity index 72% rename from services/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/p2p_interface.cpp rename to wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/p2p_interface.cpp index 38d88e9fa2c20a348ae4c91fd4e7884437292c2d..7740ecadf3dd4befd389ee6b472f34dbdf47ac5c 100644 --- a/services/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/p2p_interface.cpp +++ b/wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/p2p_interface.cpp @@ -1,5 +1,5 @@ /* - * Copyright (C) 2021 Huawei Device Co., Ltd. + * Copyright (C) 2021-2022 Huawei Device Co., Ltd. * 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 @@ -12,6 +12,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + #include "p2p_interface.h" #include "wifi_internal_msg.h" #include "wifi_logger.h" @@ -53,6 +54,7 @@ extern "C" IP2pService *Create(void) extern "C" void Destroy(IP2pService *pservice) { delete pservice; + pservice = nullptr; } ErrCode P2pInterface::EnableP2p() @@ -110,9 +112,9 @@ ErrCode P2pInterface::StopP2pListen() return p2pService.StopP2pListen(); } -ErrCode P2pInterface::FormGroup(const WifiP2pConfig &config) +ErrCode P2pInterface::CreateGroup(const WifiP2pConfig &config) { - return p2pService.FormGroup(config); + return p2pService.CreateGroup(config); } ErrCode P2pInterface::RemoveGroup() @@ -130,9 +132,9 @@ ErrCode P2pInterface::P2pConnect(const WifiP2pConfig &config) return p2pService.P2pConnect(config); } -ErrCode P2pInterface::P2pDisConnect() +ErrCode P2pInterface::P2pCancelConnect() { - return p2pService.P2pDisConnect(); + return p2pService.P2pCancelConnect(); } ErrCode P2pInterface::SetP2pDeviceName(const std::string &devName) @@ -145,9 +147,9 @@ ErrCode P2pInterface::SetP2pWfdInfo(const WifiP2pWfdInfo &wfdInfo) return p2pService.SetP2pWfdInfo(wfdInfo); } -ErrCode P2pInterface::QueryP2pInfo(WifiP2pInfo &connInfo) +ErrCode P2pInterface::QueryP2pLinkedInfo(WifiP2pLinkedInfo &linkedInfo) { - return p2pService.QueryP2pInfo(connInfo); + return p2pService.QueryP2pLinkedInfo(linkedInfo); } ErrCode P2pInterface::GetCurrentGroup(WifiP2pGroupInfo &group) @@ -175,6 +177,11 @@ ErrCode P2pInterface::QueryP2pDevices(std::vector &devices) return p2pService.QueryP2pDevices(devices); } +ErrCode P2pInterface::QueryP2pLocalDevice(WifiP2pDevice &device) +{ + return p2pService.QueryP2pLocalDevice(device); +} + ErrCode P2pInterface::QueryP2pGroups(std::vector &groups) { return p2pService.QueryP2pGroups(groups); @@ -189,5 +196,62 @@ ErrCode P2pInterface::RegisterP2pServiceCallbacks(const IP2pServiceCallbacks &ca { return p2pService.RegisterP2pServiceCallbacks(callbacks); } + +ErrCode P2pInterface::Hid2dCreateGroup(const int frequency, FreqType type) +{ + return p2pService.Hid2dCreateGroup(frequency, type); +} + +ErrCode P2pInterface::Hid2dConnect(const Hid2dConnectConfig& config) +{ + return p2pService.Hid2dConnect(config); +} + +ErrCode P2pInterface::Hid2dGetSelfWifiCfgInfo(SelfCfgType cfgType, + char cfgData[CFG_DATA_MAX_BYTES], int* getDatValidLen) +{ + return p2pService.Hid2dGetSelfWifiCfgInfo(cfgType, cfgData, getDatValidLen); +} + +ErrCode P2pInterface::Hid2dSetPeerWifiCfgInfo(PeerCfgType cfgType, + char cfgData[CFG_DATA_MAX_BYTES], int setDataValidLen) +{ + return p2pService.Hid2dSetPeerWifiCfgInfo(cfgType, cfgData, setDataValidLen); +} + +ErrCode P2pInterface::Hid2dRequestGcIp(const std::string& gcMac, std::string& ipAddr) +{ + return p2pService.Hid2dRequestGcIp(gcMac, ipAddr); +} + +void P2pInterface::IncreaseSharedLink(void) +{ + p2pService.IncreaseSharedLink(); +} + +void P2pInterface::DecreaseSharedLink(void) +{ + p2pService.DecreaseSharedLink(); +} + +int P2pInterface::GetSharedLinkCount(void) +{ + return p2pService.GetSharedLinkCount(); +} + +int P2pInterface::GetP2pRecommendChannel(void) +{ + return p2pService.GetP2pRecommendChannel(); +} + +ErrCode P2pInterface::Hid2dSetUpperScene(const std::string& ifName, const Hid2dUpperScene& scene) +{ + return p2pService.Hid2dSetUpperScene(ifName, scene); +} + +ErrCode P2pInterface::MonitorCfgChange(void) +{ + return p2pService.MonitorCfgChange(); +} } // namespace Wifi } // namespace OHOS diff --git a/services/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/p2p_interface.h b/wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/p2p_interface.h similarity index 61% rename from services/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/p2p_interface.h rename to wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/p2p_interface.h index 938dd7f52bdf91fb7ef71747d6bf860612503f6e..455ffa65f4cbf5632075c1c514be7221358298da 100644 --- a/services/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/p2p_interface.h +++ b/wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/p2p_interface.h @@ -1,5 +1,5 @@ /* - * Copyright (C) 2021 Huawei Device Co., Ltd. + * Copyright (C) 2021-2022 Huawei Device Co., Ltd. * 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 @@ -12,6 +12,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + #ifndef OHOS_P2P_INTERFACE_H #define OHOS_P2P_INTERFACE_H @@ -45,6 +46,7 @@ public: * @Description Construct a new P2pInterface object. */ P2pInterface(); + /** * @Description Destroy the P2pInterface object. */ @@ -53,44 +55,51 @@ public: public: /** * @Description - Enable the P2P mode. - * @return - ErrCode + * @return ErrCode - operation result */ virtual ErrCode EnableP2p() override; + /** * @Description - Disable the P2P mode. - * @return - ErrCode + * @return ErrCode - operation result */ virtual ErrCode DisableP2p() override; + /** * @Description - Start P2P device discovery. - * @return - ErrCode + * @return ErrCode - operation result */ virtual ErrCode DiscoverDevices() override; + /** * @Description - Stop P2P device discovery. - * @return - ErrCode + * @return ErrCode - operation result */ virtual ErrCode StopDiscoverDevices() override; + /** * @Description - Start P2P services discovery. - * @return - ErrCode + * @return ErrCode - operation result */ virtual ErrCode DiscoverServices() override; + /** * @Description - Stop P2P services discovery. - * @return - ErrCode + * @return ErrCode - operation result */ virtual ErrCode StopDiscoverServices() override; + /** * @Description - Register local P2P service. * @param srvInfo - local service information - * @return - ErrCode + * @return ErrCode - operation result */ virtual ErrCode PutLocalP2pService(const WifiP2pServiceInfo &srvInfo) override; + /** * @Description - Delete local P2P service. * @param srvInfo - local service information - * @return - ErrCode + * @return ErrCode - operation result */ virtual ErrCode DeleteLocalP2pService(const WifiP2pServiceInfo &srvInfo) override; @@ -98,7 +107,7 @@ public: * @Description - Request specified services. * @param device - requested target device * @param request - initiated service request data - * @return - ErrCode + * @return ErrCode - operation result */ virtual ErrCode RequestService(const WifiP2pDevice &device, const WifiP2pServiceRequest &request) override; @@ -106,42 +115,49 @@ public: * @Description - Start the P2P listening. Unit: millisecond. * @param period - listening period * @param interval - listening interval - * @return - ErrCode + * @return ErrCode - operation result */ virtual ErrCode StartP2pListen(int period, int interval) override; + /** * @Description - Stop the P2P listening. - * @return - ErrCode + * @return ErrCode - operation result */ virtual ErrCode StopP2pListen() override; + /** * @Description - Create a P2P group. * @param config - config for creating group - * @return - ErrCode + * @return ErrCode - operation result */ - virtual ErrCode FormGroup(const WifiP2pConfig &config) override; + virtual ErrCode CreateGroup(const WifiP2pConfig &config) override; + /** * @Description - Remove the current P2P group. - * @return - ErrCode + * @return ErrCode - operation result */ virtual ErrCode RemoveGroup() override; + /** * @Description - Delete a persistent group. * @param group - specified group - * @return - ErrCode + * @return ErrCode - operation result */ virtual ErrCode DeleteGroup(const WifiP2pGroupInfo &group) override; + /** * @Description - Connect to a P2P device. * @param config - config for connection - * @return - ErrCode + * @return ErrCode - operation result */ virtual ErrCode P2pConnect(const WifiP2pConfig &config) override; + /** - * @Description - Disconnect. - * @return - ErrCode + * @Description - Canceling a P2P connection. + * @return ErrCode - operation result */ - virtual ErrCode P2pDisConnect() override; + virtual ErrCode P2pCancelConnect() override; + /** * @Description - Set this device name. * @@ -149,72 +165,176 @@ public: * @return ErrCode */ virtual ErrCode SetP2pDeviceName(const std::string &devName) override; - + /** * @Description - Query P2P connection information. - * @param connInfo - object that stores connection information - * @return - ErrCode + * @param linkedInfo - object that stores connection information + * @return ErrCode - operation result */ - virtual ErrCode QueryP2pInfo(WifiP2pInfo &connInfo) override; + virtual ErrCode QueryP2pLinkedInfo(WifiP2pLinkedInfo &linkedInfo) override; /** * @Description set p2p wifi display info * @param wfdInfo - wifi display info - * @return ErrCode - operate result + * @return ErrCode - operation result */ virtual ErrCode SetP2pWfdInfo(const WifiP2pWfdInfo &wfdInfo) override; /** * @Description - Get the current group information. * @param group - object that stores the current group - * @return - ErrCode + * @return ErrCode - operation result */ virtual ErrCode GetCurrentGroup(WifiP2pGroupInfo &group) override; + /** * @Description - Obtain the P2P status. * @param status - object that stores P2P status - * @return - ErrCode + * @return ErrCode - operation result */ virtual ErrCode GetP2pEnableStatus(int &status) override; + /** * @Description - Obtain the P2P discovery status. * @param status - object that stores discovery status - * @return - ErrCode + * @return ErrCode - operation result */ virtual ErrCode GetP2pDiscoverStatus(int &status) override; + /** * @Description - Obtain the P2P connection status. * @param status - object that stores connection status - * @return - ErrCode + * @return ErrCode - operation result */ virtual ErrCode GetP2pConnectedStatus(int &status) override; + /** * @Description - Query the information about the found devices. * @param devices - list of queryed device - * @return - ErrCode + * @return ErrCode - operation result */ virtual ErrCode QueryP2pDevices(std::vector &devices) override; + + /** + * @Description - Query the information about own device. + * @param device - own device + * @return ErrCode - operation result + */ + virtual ErrCode QueryP2pLocalDevice(WifiP2pDevice &device) override; + /** * @Description - Obtain information about all groups. * @param groups - list of group information - * @return - ErrCode + * @return ErrCode - operation result */ virtual ErrCode QueryP2pGroups(std::vector &groups) override; + /** * @Description - Query the information about the found services. * @param services - list of service information - * @return - ErrCode + * @return ErrCode - operation result */ virtual ErrCode QueryP2pServices(std::vector &services) override; + /** * @Description - Register all callbacks provided by the P2P. * @param callbacks - all callbacks added - * @return - ErrCode + * @return ErrCode - operation result */ virtual ErrCode RegisterP2pServiceCallbacks(const IP2pServiceCallbacks &callbacks) override; + /** + * @Description Create hid2d group, used on the GO side. + * + * @param frequency - frequency + * @param type - frequency type + * @return ErrCode - operation result + */ + virtual ErrCode Hid2dCreateGroup(const int frequency, FreqType type) override; + + /** + * @Description Connect to a specified group using hid2d, used on the GC side. + * + * @param config - connection parameters + * @return ErrCode - operation result + */ + virtual ErrCode Hid2dConnect(const Hid2dConnectConfig& config) override; + + /** + * @Description Get self config info + * + * @param cfgType - config type + * @param cfgData - config data + * @param getDatValidLen - data length + * @return ErrCode - operate result + */ + virtual ErrCode Hid2dGetSelfWifiCfgInfo(SelfCfgType cfgType, + char cfgData[CFG_DATA_MAX_BYTES], int* getDatValidLen) override; + + /** + * @Description Set self config info + * + * @param cfgType - config type + * @param cfgData - config data + * @param setDataValidLen - data length + * @return ErrCode - operate result + */ + virtual ErrCode Hid2dSetPeerWifiCfgInfo(PeerCfgType cfgType, + char cfgData[CFG_DATA_MAX_BYTES], int setDataValidLen) override; + + /** + * @Description Set self config info + * + * @param gcMac - gc mac address + * @param ipAddr - allocated ip address + * @return ErrCode - operate result + */ + virtual ErrCode Hid2dRequestGcIp(const std::string& gcMac, std::string& ipAddr) override; + + /** + * @Description Increase the reference count of the hid2d service. + * + */ + virtual void IncreaseSharedLink(void) override; + + /** + * @Description Decrease the reference count of the hid2d service. + * + */ + virtual void DecreaseSharedLink(void) override; + + /** + * @Description Get the reference count of the hid2d service. + * + * @return int - reference count + */ + virtual int GetSharedLinkCount(void) override; + + /** + * @Description - Get P2P recommended channel. + * + * @return - int - Recommended channel + */ + virtual int GetP2pRecommendChannel(void) override; + + /** + * @Description Set the scene of upper layer + * + * @param ifName - interface name + * @param scene - scene + * @return ErrCode - operate result + */ + virtual ErrCode Hid2dSetUpperScene(const std::string& ifName, const Hid2dUpperScene& scene) override; + + /** + * @Description Monitor the wifi configuration change + * + * @return ErrCode - operate result + */ + virtual ErrCode MonitorCfgChange(void) override; + private: - WifiP2pGroupManager groupManager; /* group manager */ + WifiP2pGroupManager groupManager; /* group manager */ WifiP2pDeviceManager deviceMgr; /* device manager */ WifiP2pServiceManager svrMgr; diff --git a/services/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/p2p_inviting_state.cpp b/wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/p2p_inviting_state.cpp similarity index 68% rename from services/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/p2p_inviting_state.cpp rename to wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/p2p_inviting_state.cpp index 346721c235651836cfa16e1d5f2c01a68be2346a..82e63e5b58bcb8cb9b08fb418212dffbea072bb5 100644 --- a/services/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/p2p_inviting_state.cpp +++ b/wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/p2p_inviting_state.cpp @@ -14,6 +14,7 @@ */ #include "p2p_inviting_state.h" #include "p2p_state_machine.h" +#include "wifi_p2p_hal_interface.h" #include "wifi_logger.h" DEFINE_WIFILOG_P2P_LABEL("P2pInvitingState"); @@ -41,6 +42,21 @@ bool P2pInvitingState::ExecuteStateMsg(InternalMessage *msg) p2pStateMachine.BroadcastActionResult(P2pActionCallback::DiscoverDevices, ErrCode::WIFI_OPT_FAILED); break; } + case P2P_STATE_MACHINE_CMD::CMD_DISCOVER_SERVICES: { + p2pStateMachine.BroadcastActionResult(P2pActionCallback::DiscoverServices, ErrCode::WIFI_OPT_FAILED); + break; + } + case P2P_STATE_MACHINE_CMD::CMD_START_LISTEN: { + p2pStateMachine.BroadcastActionResult(P2pActionCallback::StartP2pListen, ErrCode::WIFI_OPT_FAILED); + break; + } + case P2P_STATE_MACHINE_CMD::CMD_CANCEL_CONNECT: { + WifiP2PHalInterface::GetInstance().CancelConnect(); + p2pStateMachine.DealGroupCreationFailed(); + p2pStateMachine.SwitchState(&p2pStateMachine.p2pIdleState); + p2pStateMachine.BroadcastActionResult(P2pActionCallback::P2pCancelConnect, ErrCode::WIFI_OPT_SUCCESS); + break; + } case P2P_STATE_MACHINE_CMD::P2P_EVENT_DEVICE_LOST: { /* Do nothing */ return NOT_EXECUTED; diff --git a/services/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/p2p_inviting_state.h b/wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/p2p_inviting_state.h similarity index 94% rename from services/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/p2p_inviting_state.h rename to wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/p2p_inviting_state.h index ad5cf64852794f3ed7b22e2b19042015d9b0bd9f..fb3c203b251052d782eefe28248057621328c263 100644 --- a/services/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/p2p_inviting_state.h +++ b/wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/p2p_inviting_state.h @@ -32,7 +32,7 @@ public: * @param None * @return None */ - P2pInvitingState(P2pStateMachine &, WifiP2pGroupManager &, WifiP2pDeviceManager &); + P2pInvitingState(P2pStateMachine &stateMachine, WifiP2pGroupManager &groupMgr, WifiP2pDeviceManager &deviceMgr); /** * @Description Destroy the P2pInvitingState object diff --git a/services/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/p2p_macro.h b/wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/p2p_macro.h similarity index 100% rename from services/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/p2p_macro.h rename to wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/p2p_macro.h diff --git a/services/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/p2p_monitor.cpp b/wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/p2p_monitor.cpp similarity index 93% rename from services/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/p2p_monitor.cpp rename to wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/p2p_monitor.cpp index 33824415c2f2d8c713e6fd957e771b5e4ac8d2a4..57437ec64ac5f6d5db57e3a0f00ed87de411faf0 100644 --- a/services/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/p2p_monitor.cpp +++ b/wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/p2p_monitor.cpp @@ -1,5 +1,5 @@ /* - * Copyright (C) 2021 Huawei Device Co., Ltd. + * Copyright (C) 2021-2022 Huawei Device Co., Ltd. * 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 @@ -17,6 +17,7 @@ #include "wifi_p2p_hal_interface.h" #include "dhcpd_interface.h" #include "wifi_logger.h" +#include "wifi_common_util.h" DEFINE_WIFILOG_P2P_LABEL("P2pMonitor"); @@ -65,6 +66,7 @@ void P2pMonitor::MonitorBegins(const std::string &iface) std::bind(&P2pMonitor::WpaEventApStaConnected, this, _1), std::bind(&P2pMonitor::OnConnectSupplicantFailed, this), std::bind(&P2pMonitor::WpaEventServDiscReq, this, _1), + std::bind(&P2pMonitor::WpaEventP2pIfaceCreated, this, _1, _2), }; WifiP2PHalInterface::GetInstance().RegisterP2pCallback(callback); @@ -101,7 +103,7 @@ void P2pMonitor::MessageToStateMachine( if (setMonitorIface.count(iface) > 0) { auto iter = mapHandler.find(iface); if (iter != mapHandler.end()) { - WIFI_LOGI("P2p Monitor event: iface [%{private}s], eventID [%{public}d]", + WIFI_LOGI("P2p Monitor event: iface [%{public}s], eventID [%{public}d]", iface.c_str(), static_cast(msgName)); const auto &handler = iter->second; @@ -164,7 +166,7 @@ void P2pMonitor::Broadcast2SmDeviceLost(const std::string &iface, const WifiP2pD MessageToStateMachine(iface, P2P_STATE_MACHINE_CMD::P2P_EVENT_DEVICE_LOST, 0, 0, anyDevice); } -void P2pMonitor::Broadcast2SmGoNegRequest(const std::string &iface, const WifiP2pConfig &config) const +void P2pMonitor::Broadcast2SmGoNegRequest(const std::string &iface, const WifiP2pConfigInternal &config) const { std::any anyConfig = config; MessageToStateMachine(iface, P2P_STATE_MACHINE_CMD::P2P_EVENT_GO_NEG_REQUEST, 0, 0, anyConfig); @@ -286,6 +288,12 @@ void P2pMonitor::Broadcast2SmConnectSupplicantFailed(const std::string &iface) c MessageToStateMachine(iface, P2P_STATE_MACHINE_CMD::WPA_CONN_FAILED_EVENT, 0, 0, anyNone); } +void P2pMonitor::Broadcast2SmP2pIfaceCreated(const std::string &iface, int type, const std::string &event) const +{ + std::any anyEvent = event; + MessageToStateMachine(iface, P2P_STATE_MACHINE_CMD::P2P_EVENT_IFACE_CREATED, type, 0, anyEvent); +} + void P2pMonitor::OnConnectSupplicant(int status) const { WIFI_LOGD("OnConnectSupplicant callback"); @@ -295,7 +303,7 @@ void P2pMonitor::OnConnectSupplicant(int status) const void P2pMonitor::WpaEventDeviceFound(const IdlP2pDeviceFound &deviceInfo) const { const int minWfdLength = 6; - WIFI_LOGD("onDeviceFound callback"); + WIFI_LOGI("onDeviceFound callback"); WifiP2pDevice device; device.SetDeviceName(deviceInfo.deviceName); if (device.GetDeviceName().empty()) { @@ -326,7 +334,7 @@ void P2pMonitor::WpaEventDeviceFound(const IdlP2pDeviceFound &deviceInfo) const void P2pMonitor::WpaEventDeviceLost(const std::string &p2pDeviceAddress) const { - WIFI_LOGD("onDeviceLost callback, p2pDeviceAddress:%{private}s", p2pDeviceAddress.c_str()); + WIFI_LOGI("onDeviceLost callback, p2pDeviceAddress:%{private}s", p2pDeviceAddress.c_str()); WifiP2pDevice device; device.SetDeviceAddress(p2pDeviceAddress); if (device.GetDeviceAddress().empty()) { @@ -340,8 +348,8 @@ void P2pMonitor::WpaEventDeviceLost(const std::string &p2pDeviceAddress) const void P2pMonitor::WpaEventGoNegRequest(const std::string &srcAddress, short passwordId) const { - WIFI_LOGD("WpaEventGoNegRequest srcAddress:%{private}s, passwordId:%{private}hd", srcAddress.c_str(), passwordId); - WifiP2pConfig config; + WIFI_LOGI("WpaEventGoNegRequest srcAddress:%{private}s, passwordId:%{private}hd", srcAddress.c_str(), passwordId); + WifiP2pConfigInternal config; config.SetDeviceAddress(srcAddress); if (config.GetDeviceAddress().empty()) { WIFI_LOGE("ERROR!"); @@ -373,20 +381,20 @@ void P2pMonitor::WpaEventGoNegRequest(const std::string &srcAddress, short passw void P2pMonitor::WpaEventGoNegSuccess(void) const { - WIFI_LOGD("onGoNegotiationSuccess callback"); + WIFI_LOGI("onGoNegotiationSuccess callback"); Broadcast2SmGoNegSuccess(selectIfacName); } void P2pMonitor::WpaEventGoNegFailure(int status) const { - WIFI_LOGD("onGoNegotiationFailure callback status:%{public}d", status); + WIFI_LOGI("onGoNegotiationFailure callback status:%{public}d", status); P2pStatus p2pStatus = IntStatusToP2pStatus(status); Broadcast2SmGoNegFailure(selectIfacName, p2pStatus); } void P2pMonitor::WpaEventInvitationReceived(const IdlP2pInvitationInfo &recvInfo) const { - WIFI_LOGD("onInvitationReceived callback"); + WIFI_LOGI("onInvitationReceived callback"); WifiP2pGroupInfo group; group.SetNetworkId(recvInfo.persistentNetworkId); @@ -418,7 +426,8 @@ void P2pMonitor::WpaEventInvitationReceived(const IdlP2pInvitationInfo &recvInfo void P2pMonitor::WpaEventInvitationResult(const std::string &bssid, int status) const { - WIFI_LOGD("onInvitationResult callback, bssid:%{private}s, status:%{public}d", bssid.c_str(), status); + WIFI_LOGI("onInvitationResult callback, bssid:%{public}s, status:%{public}d", + MacAnonymize(bssid).c_str(), status); P2pStatus p2pStatus = IntStatusToP2pStatus(status); Broadcast2SmInvitationResult(selectIfacName, p2pStatus); } @@ -584,5 +593,16 @@ void P2pMonitor::OnConnectSupplicantFailed(void) const WIFI_LOGD("OnConnectSupplicantFailed callback"); Broadcast2SmConnectSupplicantFailed(selectIfacName); } + +void P2pMonitor::WpaEventP2pIfaceCreated(const std::string &ifName, int isGo) const +{ + WIFI_LOGI("onP2pIfaceCreated callback, ifname:%{private}s, isGo:%{public}s", ifName.c_str(), + (isGo == 0) ? "false" : "true"); + if (ifName.empty()) { + WIFI_LOGE("ERROR! No ifname!"); + return; + } + Broadcast2SmP2pIfaceCreated(selectIfacName, isGo, ifName); +} } // namespace Wifi } // namespace OHOS diff --git a/services/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/p2p_monitor.h b/wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/p2p_monitor.h similarity index 95% rename from services/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/p2p_monitor.h rename to wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/p2p_monitor.h index 1747d27b90a278f3cb7c63580825b68274f971a2..f7017ea1aa33a956f6a94c3c04ff5abb5085ed59 100644 --- a/services/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/p2p_monitor.h +++ b/wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/p2p_monitor.h @@ -113,7 +113,7 @@ private: * @param iface - network interface for event processing * @param config - config of P2P */ - virtual void Broadcast2SmGoNegRequest(const std::string &iface, const WifiP2pConfig &config) const; + virtual void Broadcast2SmGoNegRequest(const std::string &iface, const WifiP2pConfigInternal &config) const; /** * @Description Broadcast GO negotiation success event. * @@ -243,6 +243,15 @@ private: */ virtual void Broadcast2SmConnectSupplicantFailed(const std::string &iface) const; + /** + * @Description Broadcast p2p interface created event. + * + * @param iface - network interface for event processing + * @param type - 0: GC, 1: GO + * @param event - the name of interface created + */ + virtual void Broadcast2SmP2pIfaceCreated(const std::string &iface, int type, const std::string &event) const; + private: /** * @Description - Register the connection supplicant result callback function. @@ -385,6 +394,13 @@ private: */ void OnConnectSupplicantFailed(void) const; + /** + * @Description Register the callback function for p2p interface created + * @param ifName - the name of interface created + * @param isGo - 0: GC, 1: GO + */ + void WpaEventP2pIfaceCreated(const std::string &ifName, int isGo) const; + private: /** * The current implementation cannot obtain abundant HAL instances like Andoird and cannot distinguish which @@ -397,4 +413,4 @@ private: }; } // namespace Wifi } // namespace OHOS -#endif \ No newline at end of file +#endif diff --git a/services/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/p2p_state_machine.cpp b/wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/p2p_state_machine.cpp similarity index 75% rename from services/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/p2p_state_machine.cpp rename to wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/p2p_state_machine.cpp index cdb0e1cba5f03e930a6a48ac97b63aae7c8d47fc..0340fc137e11e1cfc342f8153b4f493b73bc7422 100644 --- a/services/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/p2p_state_machine.cpp +++ b/wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/p2p_state_machine.cpp @@ -1,5 +1,5 @@ /* - * Copyright (C) 2021 Huawei Device Co., Ltd. + * Copyright (C) 2021-2022 Huawei Device Co., Ltd. * 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 @@ -12,24 +12,26 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -#include "p2p_state_machine.h" -#include +#include "p2p_state_machine.h" #include - -#include "wifi_p2p_hal_interface.h" +#include #include "dhcpd_interface.h" -#include "wifi_global_func.h" +#include "ip_tools.h" #include "wifi_broadcast_helper.h" -#include "wifi_p2p_upnp_service_response.h" -#include "wifi_p2p_dns_sd_service_response.h" -#include "wifi_p2p_dns_sd_service_info.h" +#include "wifi_global_func.h" #include "wifi_logger.h" +#include "wifi_net_agent.h" +#include "wifi_p2p_dns_sd_service_info.h" +#include "wifi_p2p_dns_sd_service_response.h" +#include "wifi_p2p_hal_interface.h" +#include "wifi_p2p_upnp_service_response.h" DEFINE_WIFILOG_P2P_LABEL("P2pStateMachine"); namespace OHOS { namespace Wifi { +bool P2pStateMachine::m_isNeedDhcp = true; P2pStateMachine::P2pStateMachine(P2pMonitor &monitor, WifiP2pGroupManager &groupMgr, WifiP2pDeviceManager &setDeviceMgr, WifiP2pServiceManager &setSvrMgr, AuthorizingNegotiationRequestState &authorizingNegotiationRequestState, @@ -61,7 +63,8 @@ P2pStateMachine::P2pStateMachine(P2pMonitor &monitor, WifiP2pGroupManager &group p2pGroupOperatingState(groupOperatingState), p2pIdleState(idleState), p2pInvitingState(invitingState), - p2pProvisionDiscoveryState(provisionDiscoveryState) + p2pProvisionDiscoveryState(provisionDiscoveryState), + p2pDevIface() { Initialize(); } @@ -152,8 +155,8 @@ void P2pStateMachine::UpdateOwnDevice(P2pDeviceStatus status) void P2pStateMachine::InitializeThisDevice() { - constexpr size_t randomLen = 4; std::string deviceName; + constexpr size_t randomLen = 4; P2pVendorConfig p2pVendorCfg; int ret = WifiSettings::GetInstance().GetP2pVendorConfig(p2pVendorCfg); if (ret < 0) { @@ -175,40 +178,31 @@ void P2pStateMachine::InitializeThisDevice() deviceManager.GetThisDevice().SetSecondaryDeviceType(p2pVendorCfg.GetSecondaryDeviceType()); } -void P2pStateMachine::UpdatePersistentGroups() const +void P2pStateMachine::UpdateGroupManager() const { - std::map mapGroups; - WifiErrorNo retCode = WifiP2PHalInterface::GetInstance().ListNetworks(mapGroups); - if (retCode != WifiErrorNo::WIFI_IDL_OPT_OK) { - WIFI_LOGE("Failed to get p2p networks."); + std::map wpaGroups; + WifiErrorNo retCode = WifiP2PHalInterface::GetInstance().ListNetworks(wpaGroups); + if (retCode == WifiErrorNo::WIFI_IDL_OPT_FAILED) { + WIFI_LOGE("Failed to get listNetworks"); return; } - - for (auto iter : mapGroups) { - WifiP2pGroupInfo &p2pGroupInfo = iter.second; - if (deviceManager.GetThisDevice() == p2pGroupInfo.GetOwner()) { - p2pGroupInfo.SetOwner(deviceManager.GetThisDevice()); - } - groupManager.UpdateWpaGroup(p2pGroupInfo); + for (auto wpaGroup = wpaGroups.begin(); wpaGroup != wpaGroups.end(); ++wpaGroup) { + groupManager.UpdateWpaGroup(wpaGroup->second); } + groupManager.UpdateGroupsNetwork(wpaGroups); +} +void P2pStateMachine::UpdatePersistentGroups() const +{ + WIFI_LOGI("UpdatePersistentGroups"); std::vector groups; groups = groupManager.GetGroups(); - for (auto it : groups) { - if (mapGroups.find(it.GetNetworkId()) == mapGroups.end()) { - WifiP2pGroupInfo removeGroup; - removeGroup.SetNetworkId(it.GetNetworkId()); - groupManager.RemoveGroup(removeGroup); - } - } WifiSettings::GetInstance().SetWifiP2pGroupInfo(groups); - - if (retCode == WifiErrorNo::WIFI_IDL_OPT_OK) { - BroadcastPersistentGroupsChanged(); - } + WifiSettings::GetInstance().SyncWifiP2pGroupInfoConfig(); + BroadcastPersistentGroupsChanged(); } -bool P2pStateMachine::ReawakenPersistentGroup(WifiP2pConfig &config) const +bool P2pStateMachine::ReawakenPersistentGroup(WifiP2pConfigInternal &config) const { const WifiP2pDevice device = FetchNewerDeviceInfo(config.GetDeviceAddress()); if (!device.IsValid()) { @@ -217,10 +211,13 @@ bool P2pStateMachine::ReawakenPersistentGroup(WifiP2pConfig &config) const } bool isJoin = device.IsGroupOwner(); - const std::string networkName = config.GetNetworkName(); + std::string groupName = config.GetGroupName(); if (isJoin && !device.IsGroupLimit()) { - int networkId = groupManager.GetGroupNetworkId(device, networkName); + if (groupName.empty()) { + groupName = device.GetNetworkName(); + } + int networkId = groupManager.GetGroupNetworkId(device, groupName); if (networkId >= 0) { /** * If GO is running on the peer device and the GO has been connected, @@ -247,9 +244,9 @@ bool P2pStateMachine::ReawakenPersistentGroup(WifiP2pConfig &config) const if (config.GetNetId() >= 0) { if (config.GetDeviceAddress() == groupManager.GetGroupOwnerAddr(config.GetNetId())) { networkId = config.GetNetId(); - } else { - networkId = groupManager.GetGroupNetworkId(device); } + } else { + networkId = groupManager.GetGroupNetworkId(device); } if (networkId < 0) { /** @@ -268,6 +265,7 @@ bool P2pStateMachine::ReawakenPersistentGroup(WifiP2pConfig &config) const if (WifiErrorNo::WIFI_IDL_OPT_OK != WifiP2PHalInterface::GetInstance().Reinvoke(networkId, device.GetDeviceAddress())) { WIFI_LOGE("Failed to reinvoke."); + UpdateGroupManager(); UpdatePersistentGroups(); return false; } else { @@ -288,12 +286,20 @@ WifiP2pDevice P2pStateMachine::FetchNewerDeviceInfo(const std::string &deviceAdd WIFI_LOGE("Invalid device address."); return device; } - return deviceManager.GetDevices(device.GetDeviceAddress()); + WifiP2pDevice newDevice = deviceManager.GetDevices(deviceAddr); + if (WifiP2PHalInterface::GetInstance().GetP2pPeer(deviceAddr, device) == + WifiErrorNo::WIFI_IDL_OPT_OK) { + int groupCap = device.GetGroupCapabilitys(); + deviceManager.UpdateDeviceGroupCap(deviceAddr, groupCap); + newDevice.SetGroupCapabilitys(groupCap); + newDevice.SetNetworkName(device.GetNetworkName()); + } + return newDevice; } void P2pStateMachine::DealGroupCreationFailed() { - WifiP2pInfo info; + WifiP2pLinkedInfo info; info.SetConnectState(P2pConnectedState::P2P_DISCONNECTED); WifiSettings::GetInstance().SaveP2pInfo(info); groupManager.SaveP2pInfo(info); @@ -310,13 +316,14 @@ void P2pStateMachine::RemoveGroupByNetworkId(int networkId) const if (WifiP2PHalInterface::GetInstance().RemoveNetwork(networkId) != WifiErrorNo::WIFI_IDL_OPT_OK) { WIFI_LOGE("failed to remove networkId, networkId is %{public}d.", networkId); } + UpdateGroupManager(); UpdatePersistentGroups(); BroadcastPersistentGroupsChanged(); } void P2pStateMachine::SetWifiP2pInfoWhenGroupFormed(const std::string &groupOwnerAddress) { - WifiP2pInfo p2pInfo; + WifiP2pLinkedInfo p2pInfo; WifiSettings::GetInstance().GetP2pInfo(p2pInfo); p2pInfo.SetIsGroupOwner(groupManager.GetCurrentGroup().IsGroupOwner()); p2pInfo.SetIsGroupOwnerAddress(groupOwnerAddress); @@ -357,7 +364,7 @@ void P2pStateMachine::BroadcastP2pServicesChanged() const void P2pStateMachine::BroadcastP2pConnectionChanged() const { - WifiP2pInfo p2pInfo; + WifiP2pLinkedInfo p2pInfo; WifiSettings::GetInstance().GetP2pInfo(p2pInfo); if (p2pServiceCallbacks.OnP2pConnectionChangedEvent) { p2pServiceCallbacks.OnP2pConnectionChangedEvent(p2pInfo); @@ -399,23 +406,59 @@ void P2pStateMachine::BroadcastActionResult(P2pActionCallback action, ErrCode re WifiBroadCastHelper::Send("ActionResult", static_cast(action), static_cast(result)); } +void P2pStateMachine::BroadcastServiceResult(P2pServicerProtocolType serviceType, + const std::vector &respData, const WifiP2pDevice &srcDevice) const +{ + if (p2pServiceCallbacks.OnP2pServiceAvailable) { + p2pServiceCallbacks.OnP2pServiceAvailable(serviceType, respData, srcDevice); + } + WifiBroadCastHelper::Send("ServiceResult", static_cast(serviceType), srcDevice); +} + +void P2pStateMachine::BroadcastDnsSdServiceResult( + const std::string &instName, const std::string ®Type, const WifiP2pDevice &srcDevice) const +{ + if (p2pServiceCallbacks.OnP2pDnsSdServiceAvailable) { + p2pServiceCallbacks.OnP2pDnsSdServiceAvailable(instName, regType, srcDevice); + } + WifiBroadCastHelper::Send("DnsSdServiceResult", instName, regType, srcDevice); +} + +void P2pStateMachine::BroadcastDnsSdTxtRecordResult(const std::string &wholeDomainName, + const std::map &txtMap, const WifiP2pDevice &srcDevice) const +{ + if (p2pServiceCallbacks.OnP2pDnsSdTxtRecordAvailable) { + p2pServiceCallbacks.OnP2pDnsSdTxtRecordAvailable(wholeDomainName, txtMap, srcDevice); + } + WifiBroadCastHelper::Send("DnsSdTxtRecordResult", wholeDomainName, txtMap, srcDevice); +} + +void P2pStateMachine::BroadcastUpnpServiceResult( + const std::vector &uniqueServiceNames, const WifiP2pDevice &srcDevice) const +{ + if (p2pServiceCallbacks.OnP2pUpnpServiceAvailable) { + p2pServiceCallbacks.OnP2pUpnpServiceAvailable(uniqueServiceNames, srcDevice); + } + WifiBroadCastHelper::Send("UpnpServiceResult", uniqueServiceNames, srcDevice); +} + void P2pStateMachine::RegisterP2pServiceCallbacks(const IP2pServiceCallbacks &callback) { p2pServiceCallbacks = callback; } -bool P2pStateMachine::IsUsableNetworkName(std::string nwName) +bool P2pStateMachine::IsUsableGroupName(std::string nwName) { if (nwName.empty()) { return false; } - if (nwName.length() < MIN_NETWORK_NAME_LENGTH || nwName.length() > MAX_NETWORK_NAME_LENGTH) { + if (nwName.length() < MIN_GROUP_NAME_LENGTH || nwName.length() > MAX_GROUP_NAME_LENGTH) { return false; } return true; } -P2pConfigErrCode P2pStateMachine::IsConfigUnusable(const WifiP2pConfig &config) +P2pConfigErrCode P2pStateMachine::IsConfigUnusable(const WifiP2pConfigInternal &config) { constexpr unsigned NETWORK_NAME_MAX_LENGTH = 32; constexpr int GROUP_OWNER_MAX_INTENT = 15; @@ -429,21 +472,22 @@ P2pConfigErrCode P2pStateMachine::IsConfigUnusable(const WifiP2pConfig &config) if (!device.IsValid()) { return P2pConfigErrCode::MAC_NOT_FOUND; } - if (config.GetGroupOwnerIntent() < 0 || config.GetGroupOwnerIntent() > GROUP_OWNER_MAX_INTENT) { + if (config.GetGroupOwnerIntent() < AUTO_GROUP_OWNER_VALUE || + config.GetGroupOwnerIntent() > GROUP_OWNER_MAX_INTENT) { return P2pConfigErrCode::ERR_INTENT; } - if (config.GetNetworkName().length() > NETWORK_NAME_MAX_LENGTH || config.GetNetworkName().length() < 1) { + if (config.GetGroupName().length() > NETWORK_NAME_MAX_LENGTH) { return P2pConfigErrCode::ERR_SIZE_NW_NAME; } return P2pConfigErrCode::SUCCESS; } -bool P2pStateMachine::IsConfigUsableAsGroup(WifiP2pConfig config) +bool P2pStateMachine::IsConfigUsableAsGroup(WifiP2pConfigInternal config) { if (config.GetDeviceAddress().empty()) { return false; } - if (IsUsableNetworkName(config.GetNetworkName()) && !config.GetPassphrase().empty()) { + if (IsUsableGroupName(config.GetGroupName()) && !config.GetPassphrase().empty()) { return true; } return false; @@ -479,6 +523,7 @@ void P2pStateMachine::NotifyUserInvitationSentMessage(const std::string &pin, co dialog.SetButton("OK", event, nullptr); AbstractUI::GetInstance().ShowAlerDialog(dialog); } + void P2pStateMachine::NotifyUserProvDiscShowPinRequestMessage(const std::string &pin, const std::string &peerAddress) { WIFI_LOGI("P2pStateMachine::NotifyUserProvDiscShowPinRequestMessage enter"); @@ -498,6 +543,7 @@ void P2pStateMachine::NotifyUserProvDiscShowPinRequestMessage(const std::string dialog.SetButton("accepts", acceptEvent, nullptr); AbstractUI::GetInstance().ShowAlerDialog(dialog); } + void P2pStateMachine::NotifyUserInvitationReceivedMessage() { WIFI_LOGI("P2pStateMachine::NotifyUserInvitationReceivedMessage enter"); @@ -545,7 +591,7 @@ void P2pStateMachine::NotifyUserInvitationReceivedMessage() AbstractUI::GetInstance().ShowAlerDialog(dialog); } -void P2pStateMachine::P2pConnectByShowingPin(const WifiP2pConfig &config) const +void P2pStateMachine::P2pConnectByShowingPin(const WifiP2pConfigInternal &config) const { if (config.GetDeviceAddress().empty()) { WIFI_LOGE("Invalid address parameter."); @@ -587,7 +633,8 @@ void P2pStateMachine::HandlerDiscoverPeers() void P2pStateMachine::ChangeConnectedStatus(P2pConnectedState connectedState) { - WifiP2pInfo p2pInfo; + WIFI_LOGI("ChangeConnectedStatus, connectedState: %{public}d", connectedState); + WifiP2pLinkedInfo p2pInfo; WifiSettings::GetInstance().GetP2pInfo(p2pInfo); p2pInfo.SetConnectState(connectedState); WifiSettings::GetInstance().SaveP2pInfo(p2pInfo); @@ -604,13 +651,14 @@ void P2pStateMachine::ChangeConnectedStatus(P2pConnectedState connectedState) UpdateOwnDevice(P2pDeviceStatus::PDS_AVAILABLE); ClearWifiP2pInfo(); BroadcastP2pConnectionChanged(); + deviceManager.UpdateAllDeviceStatus(P2pDeviceStatus::PDS_AVAILABLE); } return; } void P2pStateMachine::ClearWifiP2pInfo() { - WifiP2pInfo p2pInfo; + WifiP2pLinkedInfo p2pInfo; WifiSettings::GetInstance().SaveP2pInfo(p2pInfo); groupManager.SaveP2pInfo(p2pInfo); } @@ -627,8 +675,12 @@ bool P2pStateMachine::StartDhcpServer() currGroup.SetGoIpAddress(ipv4.GetAddressWithString()); groupManager.SetCurrentGroup(currGroup); if (!m_DhcpdInterface.SetDhcpEventFunc(groupManager.GetCurrentGroup().GetInterface(), pDhcpResultNotify.get())) { - WIFI_LOGW("Set dhcp notify failed."); + WIFI_LOGE("Set dhcp notify failed."); } + WIFI_LOGI("Start add route"); + WifiNetAgent::GetInstance().AddRoute(groupManager.GetCurrentGroup().GetInterface(), + ipv4.GetAddressWithString(), ipv4.GetAddressPrefixLength()); + WIFI_LOGI("Start dhcp server for P2p finished."); return true; } @@ -647,8 +699,8 @@ P2pStateMachine::DhcpResultNotify::~DhcpResultNotify() void P2pStateMachine::DhcpResultNotify::OnSuccess(int status, const std::string &ifname, DhcpResult &result) { - WIFI_LOGI("Enter DhcpResultNotify::OnSuccess, status: %{public}d, ifname: %{public}s", status, ifname.c_str()); - WifiP2pInfo p2pInfo; + WIFI_LOGI("Enter P2P DhcpResultNotify::OnSuccess, status: %{public}d, ifname: %{public}s", status, ifname.c_str()); + WifiP2pLinkedInfo p2pInfo; WifiSettings::GetInstance().GetP2pInfo(p2pInfo); WIFI_LOGI("Set GO IP: %{private}s", result.strServer.c_str()); p2pInfo.SetIsGroupOwnerAddress(result.strServer); @@ -658,6 +710,9 @@ void P2pStateMachine::DhcpResultNotify::OnSuccess(int status, const std::string WifiSettings::GetInstance().SaveP2pInfo(p2pInfo); groupManager.SaveP2pInfo(p2pInfo); pP2pStateMachine->BroadcastP2pConnectionChanged(); + WIFI_LOGI("Start add route on dhcp success"); + WifiNetAgent::GetInstance().AddRoute(ifname, result.strYourCli, IpTools::GetMaskLength(result.strSubnet)); + WIFI_LOGI("DhcpResultNotify::OnSuccess end"); } void P2pStateMachine::DhcpResultNotify::OnFailed(int status, const std::string &ifname, const std::string &reason) @@ -666,17 +721,24 @@ void P2pStateMachine::DhcpResultNotify::OnFailed(int status, const std::string & status, reason.c_str(), ifname.c_str()); + if (pP2pStateMachine->p2pDevIface == ifname) { + pP2pStateMachine->p2pDevIface = ""; + } WifiP2PHalInterface::GetInstance().GroupRemove(ifname); } void P2pStateMachine::DhcpResultNotify::OnSerExitNotify(const std::string& ifname) { - WIFI_LOGD("Dhcp exit notify.ifname:%s.", ifname.c_str()); - pP2pStateMachine->SendMessage(static_cast(P2P_STATE_MACHINE_CMD::CMD_P2P_DISABLE)); + WIFI_LOGI("Dhcp exit notify.ifname:%{public}s!", ifname.c_str()); } void P2pStateMachine::StartDhcpClient() { + if (!GetIsNeedDhcp()) { + WIFI_LOGI("The service of this time does not need DHCP."); + return; + } + if (pDhcpService.get() == nullptr) { WIFI_LOGE("pDhcpService is nullptr, cannot start dhcp client."); return; @@ -689,7 +751,7 @@ void P2pStateMachine::StartDhcpClient() } else { WIFI_LOGE("pDhcpService or pDhcpResultNotify is nullptr, cannot get dhcp result."); } - WIFI_LOGI("Start Dhcp Cilent"); + WIFI_LOGI("Start Dhcp Client"); } void P2pStateMachine::HandleP2pServiceResp(const WifiP2pServiceResponse &resp, const WifiP2pDevice &dev) const @@ -700,6 +762,38 @@ void P2pStateMachine::HandleP2pServiceResp(const WifiP2pServiceResponse &resp, c WIFI_LOGD("Service protocol is not available."); return; } + if (resp.GetProtocolType() == P2pServicerProtocolType::SERVICE_TYPE_BONJOUR) { + WifiP2pDnsSdServiceResponse dnsSrvResp = WifiP2pDnsSdServiceResponse(resp); + if (!dnsSrvResp.ParseData()) { + WIFI_LOGE("Parse WifiP2pDnsServiceResponse failed!"); + return; + } + serviceManager.UpdateServiceName(dev.GetDeviceAddress(), dynamic_cast(dnsSrvResp)); + if (dnsSrvResp.GetDnsType() == WifiP2pDnsSdServiceInfo::DNS_PTR_TYPE) { + BroadcastDnsSdServiceResult(dnsSrvResp.GetInstanceName(), dnsSrvResp.GetQueryName(), dev); + return; + } + if (dnsSrvResp.GetDnsType() == WifiP2pDnsSdServiceInfo::DNS_TXT_TYPE) { + BroadcastDnsSdTxtRecordResult(dnsSrvResp.GetQueryName(), dnsSrvResp.GetTxtRecord(), dev); + return; + } + WIFI_LOGE("Parse WifiP2pDnsSdServiceResponse Dnstype failed!"); + return; + } + if (resp.GetProtocolType() == P2pServicerProtocolType::SERVICE_TYPE_UP_NP) { + WifiP2pUpnpServiceResponse upnpSrvResp = + WifiP2pUpnpServiceResponse::Create(resp.GetServiceStatus(), resp.GetTransactionId(), resp.GetData()); + if (upnpSrvResp.ParseData()) { + serviceManager.UpdateServiceName( + dev.GetDeviceAddress(), dynamic_cast(upnpSrvResp)); + BroadcastUpnpServiceResult(upnpSrvResp.GetUniqueServNames(), dev); + } else { + WIFI_LOGE("Parse WifiP2pUpnpServiceResponse failed!"); + } + return; + } + + BroadcastServiceResult(resp.GetProtocolType(), resp.GetData(), dev); return; } @@ -712,6 +806,11 @@ int P2pStateMachine::GetAvailableFreqByBand(GroupOwnerBand band) const } if (WifiP2PHalInterface::GetInstance().P2pGetSupportFrequenciesByBand(static_cast(band), freqList) == WifiErrorNo::WIFI_IDL_OPT_FAILED) { + constexpr int DEFAULT_5G_FREQUENCY = 5745; // channal:149, frequency:5745 + if (band == GroupOwnerBand::GO_BAND_5GHZ) { + WIFI_LOGE("Get support frequencies failed, use default 5g frequency!"); + return DEFAULT_5G_FREQUENCY; + } WIFI_LOGE("Cannot get support frequencies according to band, choose random frequency"); return 0; } @@ -721,13 +820,14 @@ int P2pStateMachine::GetAvailableFreqByBand(GroupOwnerBand band) const return retFreq; } -bool P2pStateMachine::SetGroupConfig(const WifiP2pConfig &config, bool newGroup) const +bool P2pStateMachine::SetGroupConfig(const WifiP2pConfigInternal &config, bool newGroup) const { WifiErrorNo ret; IdlP2pGroupConfig wpaConfig; + WifiP2pGroupInfo group; if (newGroup) { WIFI_LOGI("SetGroupConfig, new group"); - wpaConfig.ssid = config.GetNetworkName(); + wpaConfig.ssid = config.GetGroupName(); wpaConfig.psk = config.GetPassphrase(); wpaConfig.bssid = deviceManager.GetThisDevice().GetDeviceAddress(); const int p2pDisabled = 2; @@ -741,8 +841,8 @@ bool P2pStateMachine::SetGroupConfig(const WifiP2pConfig &config, bool newGroup) if (ret == WifiErrorNo::WIFI_IDL_OPT_FAILED) { WIFI_LOGW("P2pGetGroupConfig failed"); } - if (!config.GetNetworkName().empty()) { - wpaConfig.ssid = config.GetNetworkName(); + if (!config.GetGroupName().empty()) { + wpaConfig.ssid = config.GetGroupName(); } else { wpaConfig.ssid = knownConfig.ssid; } @@ -760,6 +860,10 @@ bool P2pStateMachine::SetGroupConfig(const WifiP2pConfig &config, bool newGroup) wpaConfig.disabled = knownConfig.disabled; wpaConfig.mode = knownConfig.mode; } + group.SetGroupName(config.GetGroupName()); + group.SetPassphrase(config.GetPassphrase()); + group.SetNetworkId(config.GetNetId()); + groupManager.AddOrUpdateGroup(group); ret = WifiP2PHalInterface::GetInstance().P2pSetGroupConfig(config.GetNetId(), wpaConfig); if (ret == WifiErrorNo::WIFI_IDL_OPT_FAILED) { return false; @@ -768,15 +872,15 @@ bool P2pStateMachine::SetGroupConfig(const WifiP2pConfig &config, bool newGroup) } } -bool P2pStateMachine::DealCreateNewGroupWithConfig(const WifiP2pConfig &config, int freq) const +bool P2pStateMachine::DealCreateNewGroupWithConfig(const WifiP2pConfigInternal &config, int freq) const { - WifiP2pConfig cfgBuf = config; + WifiP2pConfigInternal cfgBuf = config; int createdNetId = -1; int netId = cfgBuf.GetNetId(); std::vector groupInfo = groupManager.GetGroups(); for (auto iter = groupInfo.begin(); iter != groupInfo.end(); ++iter) { - if (iter->GetGroupName() == config.GetNetworkName()) { + if (iter->GetGroupName() == config.GetGroupName()) { WIFI_LOGE("Cannot use a exist group name!"); return false; } @@ -792,27 +896,46 @@ bool P2pStateMachine::DealCreateNewGroupWithConfig(const WifiP2pConfig &config, } if (ret == WIFI_IDL_OPT_FAILED || netId == TEMPORARY_NET_ID) { - WIFI_LOGD("Remove network %d!", createdNetId); - WifiP2PHalInterface::GetInstance().RemoveNetwork(createdNetId); + WIFI_LOGD("Remove network %{public}d!", createdNetId); + WifiP2PHalInterface::GetInstance().RemoveNetwork(createdNetId); + WifiP2pGroupInfo removedInfo; + removedInfo.SetNetworkId(createdNetId); + groupManager.RemoveGroup(removedInfo); } - - return (ret == WIFI_IDL_OPT_FAILED) ? false : true ; + + UpdateGroupManager(); + UpdatePersistentGroups(); + return (ret == WIFI_IDL_OPT_FAILED) ? false : true; +} + +bool P2pStateMachine::IsInterfaceReuse() const +{ + return P2P_INTERFACE == "wlan0"; } void P2pStateMachine::UpdateGroupInfoToWpa() const { - WifiErrorNo ret = WifiP2PHalInterface::GetInstance().RemoveNetwork(-1); - if (ret != WIFI_IDL_OPT_OK) { - WIFI_LOGE("Failed to delete all group info before update group info to wpa! Stop update!"); + WIFI_LOGI("Start update group info to wpa"); + /* 1) In the scenario of interface reuse, the configuration of sta may be deleted + * 2) Dont remove p2p networks of wpa_s in initial phase after device reboot + */ + if (IsInterfaceReuse()) { return; } std::vector grpInfo = groupManager.GetGroups(); + if (grpInfo.size() > 0) { + if (WifiP2PHalInterface::GetInstance().RemoveNetwork(-1) != WIFI_IDL_OPT_OK) { + WIFI_LOGE("Failed to delete all group info before update group info to wpa! Stop update!"); + return; + } + } + int createdNetId = -1; WifiP2pGroupInfo grpBuf; IdlP2pGroupConfig wpaConfig; for (unsigned int i = 0; i < grpInfo.size(); ++i) { grpBuf = grpInfo.at(i); - ret = WifiP2PHalInterface::GetInstance().P2pAddNetwork(createdNetId); + WifiErrorNo ret = WifiP2PHalInterface::GetInstance().P2pAddNetwork(createdNetId); if (ret == WIFI_IDL_OPT_OK) { grpBuf.SetNetworkId(createdNetId); wpaConfig.ssid = grpBuf.GetGroupName(); @@ -829,10 +952,22 @@ void P2pStateMachine::UpdateGroupInfoToWpa() const WifiP2PHalInterface::GetInstance().P2pSetGroupConfig(createdNetId, wpaConfig); grpInfo.at(i) = grpBuf; } else { - WIFI_LOGW("AddNetwork failed when add %s group!", grpBuf.GetGroupName().c_str()); + WIFI_LOGW("AddNetwork failed when add %{public}s group!", grpBuf.GetGroupName().c_str()); } } return; } + +bool P2pStateMachine::GetIsNeedDhcp() const +{ + WIFI_LOGI("Get need dhcp flag %{public}d", (int)m_isNeedDhcp); + return m_isNeedDhcp; +} + +void P2pStateMachine::SetIsNeedDhcp(bool isNeedDhcp) +{ + WIFI_LOGI("Set need dhcp flag %{public}d", (int)isNeedDhcp); + m_isNeedDhcp = isNeedDhcp; +} } // namespace Wifi } // namespace OHOS diff --git a/services/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/p2p_state_machine.h b/wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/p2p_state_machine.h similarity index 81% rename from services/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/p2p_state_machine.h rename to wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/p2p_state_machine.h index 9302a722ee90669a09cea07c773747e2c7c9057c..4944a9ce1d5fb36890a04fc1113298a79ddb8952 100644 --- a/services/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/p2p_state_machine.h +++ b/wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/p2p_state_machine.h @@ -1,5 +1,5 @@ /* - * Copyright (C) 2021 Huawei Device Co., Ltd. + * Copyright (C) 2021-2022 Huawei Device Co., Ltd. * 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 @@ -40,11 +40,12 @@ #include "p2p_inviting_state.h" #include "provision_discovery_state.h" #include "abstract_ui.h" +#include "wifi_hid2d_service_utils.h" namespace OHOS { namespace Wifi { -const int MIN_NETWORK_NAME_LENGTH = 9; -const int MAX_NETWORK_NAME_LENGTH = 32; +const int MIN_GROUP_NAME_LENGTH = 9; +const int MAX_GROUP_NAME_LENGTH = 32; const int DISC_TIMEOUT_S = 120; class P2pStateMachine : public StateMachine { class DhcpResultNotify : public IDhcpResultNotify { @@ -132,6 +133,12 @@ public: */ virtual void RegisterP2pServiceCallbacks(const IP2pServiceCallbacks &callback); + /** + * @Description - Set is need dhcp. + * @param isNeedDhcp - true: need, false: not need + */ + void SetIsNeedDhcp(bool isNeedDhcp); + private: /** * @Description Handle event of CMD_DEVICE_DISCOVERS @@ -151,6 +158,10 @@ private: * @param status - new device status */ virtual void UpdateOwnDevice(P2pDeviceStatus status); + /** + * @Description - Update groupManager from wpa_supplicant. + */ + virtual void UpdateGroupManager() const; /** * @Description - Update persistent groups and broadcast persistent groups status update event. */ @@ -163,7 +174,7 @@ private: * @return - bool true:It is a persistent group and the reinvoke succeeds. false:Not a persistent group or reinvoke failure. */ - virtual bool ReawakenPersistentGroup(WifiP2pConfig &config) const; + virtual bool ReawakenPersistentGroup(WifiP2pConfigInternal &config) const; /** * @Description - Updates the latest device information based on the device address and returns. @@ -182,7 +193,7 @@ private: */ virtual void RemoveGroupByNetworkId(int networkId) const; /** - * @Description Updating the WifiP2pInfo information when a group is formed. + * @Description Updating the WifiP2pLinkedInfo information when a group is formed. * @param groupOwnerAddress - address of the group owner */ virtual void SetWifiP2pInfoWhenGroupFormed(const std::string &groupOwnerAddress); @@ -198,14 +209,14 @@ private: * @return true - available * @return false - not available */ - virtual bool IsUsableNetworkName(std::string nwName); + virtual bool IsUsableGroupName(std::string nwName); /** * @Description Check whether the specified P2P configuration is unavailable. * * @param config - specified P2P configuration * @return P2pConfigErrCode - error code of WifiP2pConfig */ - virtual P2pConfigErrCode IsConfigUnusable(const WifiP2pConfig &config); + virtual P2pConfigErrCode IsConfigUnusable(const WifiP2pConfigInternal &config); /** * @Description If the P2P is configured with a network name and passphrase, the configuration is valid as a group. * @@ -213,7 +224,7 @@ private: * @return true - valid * @return false - invalid */ - virtual bool IsConfigUsableAsGroup(WifiP2pConfig config); + virtual bool IsConfigUsableAsGroup(WifiP2pConfigInternal config); /** * @Description Purging service discovery requests in WPAS. * @@ -257,7 +268,7 @@ private: * @return true - all settings succeeded * @return false - one of settings failed */ - virtual bool SetGroupConfig(const WifiP2pConfig &config, bool newGroup) const; + virtual bool SetGroupConfig(const WifiP2pConfigInternal &config, bool newGroup) const; /** * @Description Processing function of using configuration to create a group. * @@ -266,13 +277,25 @@ private: * @return true - created successfully * @return false - creation failed */ - virtual bool DealCreateNewGroupWithConfig(const WifiP2pConfig &config, int freq) const; + virtual bool DealCreateNewGroupWithConfig(const WifiP2pConfigInternal &config, int freq) const; /** * @Description Update persistent group's info to wpa. * */ virtual void UpdateGroupInfoToWpa() const; + /** + * @Description Get is need dhcp. + * + */ + bool GetIsNeedDhcp() const; + + /** + * @Description Is interface reuse. + * + */ + bool IsInterfaceReuse() const; + private: /** * @Description - Broadcast state change event. @@ -311,6 +334,41 @@ private: * @param result - action confirmation result */ virtual void BroadcastActionResult(P2pActionCallback action, ErrCode result) const; + /** + * @Description Broadcast receive p2p service response result in addition to bonjour and upnp. + * + * @param serviceType - protocol type + * @param respData - service response data + * @param srcDevice - source device + */ + virtual void BroadcastServiceResult(P2pServicerProtocolType serviceType, + const std::vector &respData, const WifiP2pDevice &srcDevice) const; + /** + * @Description Broadcast receive bonjour service response result. + * + * @param instName - instance name + * @param regType - registration type + * @param srcDevice - source device + */ + virtual void BroadcastDnsSdServiceResult( + const std::string &instName, const std::string ®Type, const WifiP2pDevice &srcDevice) const; + /** + * @Description Broadcast receive the result of bonjour txt record for a service. + * + * @param wholeDomainName - the whole domain name + * @param txtMap - txt record data as a map of key/value pairs + * @param srcDevice source device + */ + virtual void BroadcastDnsSdTxtRecordResult(const std::string &wholeDomainName, + const std::map &txtMap, const WifiP2pDevice &srcDevice) const; + /** + * @Description Broadcast receive upnp service response result. + * + * @param uniqueServiceNames - the list of unique service names + * @param srcDevice - source device + */ + virtual void BroadcastUpnpServiceResult( + const std::vector &uniqueServiceNames, const WifiP2pDevice &srcDevice) const; /** * @Description - Start the dhcp server and save the IP address to be assigned. @@ -329,12 +387,12 @@ private: virtual void NotifyUserInvitationReceivedMessage(); private: - virtual void P2pConnectByShowingPin(const WifiP2pConfig &config) const; + virtual void P2pConnectByShowingPin(const WifiP2pConfigInternal &config) const; private: IP2pServiceCallbacks p2pServiceCallbacks; /* state machine -> service callback */ std::string p2pIface; /* P2P iface */ - WifiP2pConfig savedP2pConfig; /* record P2P config when communicating with the peer device */ + WifiP2pConfigInternal savedP2pConfig; /* record P2P config when communicating with the peer device */ P2pMonitor &p2pMonitor; /* P2P monitor */ WifiP2pGroupManager &groupManager; /* group manager */ WifiP2pDeviceManager &deviceManager; /* device manager */ @@ -358,6 +416,8 @@ private: P2pIdleState &p2pIdleState; P2pInvitingState &p2pInvitingState; ProvisionDiscoveryState &p2pProvisionDiscoveryState; + static bool m_isNeedDhcp; + std::string p2pDevIface; }; } // namespace Wifi } // namespace OHOS diff --git a/services/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/provision_discovery_state.cpp b/wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/provision_discovery_state.cpp similarity index 81% rename from services/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/provision_discovery_state.cpp rename to wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/provision_discovery_state.cpp index d3b9358b692443a2dcefcfbe02e8f3ec6e4b51b5..8672a26254de12e58a992e15ba7f81c8ed9a0494 100644 --- a/services/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/provision_discovery_state.cpp +++ b/wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/provision_discovery_state.cpp @@ -49,6 +49,10 @@ void ProvisionDiscoveryState::Init() { mProcessFunMap.insert( std::make_pair(P2P_STATE_MACHINE_CMD::CMD_DEVICE_DISCOVERS, &ProvisionDiscoveryState::ProcessCmdDiscoverPeer)); + mProcessFunMap.insert( + std::make_pair(P2P_STATE_MACHINE_CMD::CMD_DISCOVER_SERVICES, &ProvisionDiscoveryState::ProcessCmdDiscServices)); + mProcessFunMap.insert( + std::make_pair(P2P_STATE_MACHINE_CMD::CMD_START_LISTEN, &ProvisionDiscoveryState::ProcessCmdStartListen)); mProcessFunMap.insert(std::make_pair( P2P_STATE_MACHINE_CMD::P2P_EVENT_PROV_DISC_PBC_RESP, &ProvisionDiscoveryState::ProcessProvDiscPbcRspEvt)); mProcessFunMap.insert(std::make_pair( @@ -57,6 +61,8 @@ void ProvisionDiscoveryState::Init() P2P_STATE_MACHINE_CMD::P2P_EVENT_PROV_DISC_SHOW_PIN, &ProvisionDiscoveryState::ProcessProvDiscShowPinEvt)); mProcessFunMap.insert(std::make_pair( P2P_STATE_MACHINE_CMD::P2P_EVENT_PROV_DISC_FAILURE, &ProvisionDiscoveryState::ProcessProvDiscFailEvt)); + mProcessFunMap.insert(std::make_pair( + P2P_STATE_MACHINE_CMD::CMD_CANCEL_CONNECT, &ProvisionDiscoveryState::ProcessCmdCancelConnect)); } bool ProvisionDiscoveryState::ProcessCmdDiscoverPeer(InternalMessage &msg) const @@ -66,6 +72,20 @@ bool ProvisionDiscoveryState::ProcessCmdDiscoverPeer(InternalMessage &msg) const return EXECUTED; } +bool ProvisionDiscoveryState::ProcessCmdDiscServices(InternalMessage &msg) const +{ + WIFI_LOGI("recv CMD: %{public}d", msg.GetMessageName()); + p2pStateMachine.BroadcastActionResult(P2pActionCallback::DiscoverServices, ErrCode::WIFI_OPT_FAILED); + return EXECUTED; +} + +bool ProvisionDiscoveryState::ProcessCmdStartListen(InternalMessage &msg) const +{ + WIFI_LOGI("recv CMD: %{public}d", msg.GetMessageName()); + p2pStateMachine.BroadcastActionResult(P2pActionCallback::StartP2pListen, ErrCode::WIFI_OPT_FAILED); + return EXECUTED; +} + bool ProvisionDiscoveryState::ProcessProvDiscPbcRspEvt(InternalMessage &msg) const { WifiP2pTempDiscEvent provDisc; @@ -148,6 +168,16 @@ bool ProvisionDiscoveryState::ProcessProvDiscFailEvt(InternalMessage &msg) const return EXECUTED; } +bool ProvisionDiscoveryState::ProcessCmdCancelConnect(InternalMessage &msg) const +{ + WIFI_LOGI("recv event: %{public}d", msg.GetMessageName()); + WifiP2PHalInterface::GetInstance().CancelConnect(); + p2pStateMachine.DealGroupCreationFailed(); + p2pStateMachine.SwitchState(&p2pStateMachine.p2pIdleState); + p2pStateMachine.BroadcastActionResult(P2pActionCallback::P2pCancelConnect, ErrCode::WIFI_OPT_SUCCESS); + return EXECUTED; +} + bool ProvisionDiscoveryState::ExecuteStateMsg(InternalMessage *msg) { if (msg == nullptr) { diff --git a/services/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/provision_discovery_state.h b/wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/provision_discovery_state.h similarity index 79% rename from services/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/provision_discovery_state.h rename to wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/provision_discovery_state.h index 3ea8976d5b8f8c2873ee7899b7f9ae409facc291..5bd6c850f471266887325fefb55330db2072283b 100644 --- a/services/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/provision_discovery_state.h +++ b/wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/provision_discovery_state.h @@ -32,7 +32,8 @@ public: * @param None * @return None */ - ProvisionDiscoveryState(P2pStateMachine &, WifiP2pGroupManager &, WifiP2pDeviceManager &); + ProvisionDiscoveryState(P2pStateMachine &stateMachine, WifiP2pGroupManager &setGroupMgr, + WifiP2pDeviceManager &setDeviceMgr); /** * @Description Destroy the Provision Discovery State object @@ -77,6 +78,20 @@ private: */ virtual bool ProcessCmdDiscoverPeer(InternalMessage &msg) const; + /** + * @Description Process the discover services command received by the state machine + * @param msg - Message body sent by the state machine + * @return - bool true:handle false:not handle + */ + virtual bool ProcessCmdDiscServices(InternalMessage &msg) const; + + /** + * @Description Process the start listen command received by the state machine + * @param msg - Message body sent by the state machine + * @return - bool true:handle false:not handle + */ + virtual bool ProcessCmdStartListen(InternalMessage &msg) const; + /** * @Description Process the provision discover pbc response message received by the state machine * @param msg - Message body sent by the state machine @@ -105,6 +120,13 @@ private: */ virtual bool ProcessProvDiscFailEvt(InternalMessage &msg) const; + /** + * @Description Process the cancel connect message received by the state machine + * @param msg - Message body sent by the state machine + * @return - bool true:handle false:not handle + */ + virtual bool ProcessCmdCancelConnect(InternalMessage &msg) const; + private: using ProcessFun = bool (ProvisionDiscoveryState::*)(InternalMessage &msg) const; std::map mProcessFunMap; diff --git a/services/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/wifi_p2p_device_manager.cpp b/wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/wifi_p2p_device_manager.cpp similarity index 95% rename from services/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/wifi_p2p_device_manager.cpp rename to wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/wifi_p2p_device_manager.cpp index bd8e0959b9ab5ccd67b580b57706d5d1a70da32e..897e7fa8998d10a8d18759651a01615013131b4a 100644 --- a/services/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/wifi_p2p_device_manager.cpp +++ b/wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/wifi_p2p_device_manager.cpp @@ -154,6 +154,15 @@ bool WifiP2pDeviceManager::UpdateDeviceStatus(const WifiP2pDevice &device) return UpdateDeviceStatus(device.GetDeviceAddress(), device.GetP2pDeviceStatus()); } +bool WifiP2pDeviceManager::UpdateAllDeviceStatus(const P2pDeviceStatus status) +{ + std::unique_lock lock(deviceMutex); + for (auto it = p2pDevices.begin(); it != p2pDevices.end(); it++) { + it->SetP2pDeviceStatus(status); + } + return true; +} + WifiP2pDevice WifiP2pDeviceManager::GetDevices(const std::string &deviceAddress) { std::unique_lock lock(deviceMutex); diff --git a/services/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/wifi_p2p_device_manager.h b/wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/wifi_p2p_device_manager.h similarity index 93% rename from services/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/wifi_p2p_device_manager.h rename to wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/wifi_p2p_device_manager.h index 4f724c432d892d8ff24f2e3c929f1ec27c518f54..9e3ef43397f3d2e2999ea20e2a9804feba918249 100644 --- a/services/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/wifi_p2p_device_manager.h +++ b/wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/wifi_p2p_device_manager.h @@ -1,5 +1,5 @@ /* - * Copyright (C) 2021 Huawei Device Co., Ltd. + * Copyright (C) 2021-2022 Huawei Device Co., Ltd. * 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 @@ -16,7 +16,7 @@ #define OHOS_P2P_DEVICE_MANAGER_H #include -#include "wifi_msg.h" +#include "wifi_p2p_msg.h" namespace OHOS { namespace Wifi { @@ -38,6 +38,7 @@ class WifiP2pDeviceManager { friend class P2pIdleState; friend class P2pInvitingState; friend class ProvisionDiscoveryState; + friend class WifiP2pService; public: /** * @Description Destroy the Wifi P2p Device Manager object. @@ -115,6 +116,12 @@ public: * @return - bool true:success false:failed */ virtual bool UpdateDeviceStatus(const WifiP2pDevice &device); + /** + * @Description - Updates the status of P2P devices based on the device information. + * @param status - status that needs to be updated + * @return - bool true:success false:failed + */ + virtual bool UpdateAllDeviceStatus(const P2pDeviceStatus status); /** * @Description - Obtain information about a P2P device based on the device address. * @param devices - MAC of the device diff --git a/services/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/wifi_p2p_dns_sd_service_info.cpp b/wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/wifi_p2p_dns_sd_service_info.cpp similarity index 96% rename from services/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/wifi_p2p_dns_sd_service_info.cpp rename to wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/wifi_p2p_dns_sd_service_info.cpp index 2653d76c7d010a5817ec42577a49c2afe2bb0d4d..a79ec5daca215fe4f32d01e6bd0d0313faf26dd7 100644 --- a/services/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/wifi_p2p_dns_sd_service_info.cpp +++ b/wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/wifi_p2p_dns_sd_service_info.cpp @@ -55,6 +55,7 @@ WifiP2pDnsSdServiceInfo WifiP2pDnsSdServiceInfo::Create(const std::string &insta WifiP2pDnsSdServiceInfo dnsSdServInfo(queries); dnsSdServInfo.SetServiceName(svrName); + dnsSdServInfo.SetServicerProtocolType(P2pServicerProtocolType::SERVICE_TYPE_BONJOUR); return dnsSdServInfo; } std::string WifiP2pDnsSdServiceInfo::BuildPtrServiceQuery( @@ -99,7 +100,9 @@ std::string WifiP2pDnsSdServiceInfo::BuildTxtServiceQuery(const std::string &ins } if (!svrName.empty()) { - ret += std::string("00"); + if (!rawData.empty()) { + ret += std::string("00"); + } ret.append(Bin2HexStr(std::string(";"))); std::vector buf; buf.push_back(static_cast(svrName.length())); diff --git a/services/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/wifi_p2p_dns_sd_service_info.h b/wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/wifi_p2p_dns_sd_service_info.h similarity index 100% rename from services/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/wifi_p2p_dns_sd_service_info.h rename to wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/wifi_p2p_dns_sd_service_info.h diff --git a/services/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/wifi_p2p_dns_sd_service_request.cpp b/wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/wifi_p2p_dns_sd_service_request.cpp similarity index 100% rename from services/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/wifi_p2p_dns_sd_service_request.cpp rename to wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/wifi_p2p_dns_sd_service_request.cpp diff --git a/services/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/wifi_p2p_dns_sd_service_request.h b/wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/wifi_p2p_dns_sd_service_request.h similarity index 100% rename from services/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/wifi_p2p_dns_sd_service_request.h rename to wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/wifi_p2p_dns_sd_service_request.h diff --git a/services/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/wifi_p2p_dns_sd_service_response.cpp b/wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/wifi_p2p_dns_sd_service_response.cpp similarity index 99% rename from services/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/wifi_p2p_dns_sd_service_response.cpp rename to wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/wifi_p2p_dns_sd_service_response.cpp index 4c3c299fda748b7b287c9fa5b9786ec279f7989a..c6529f0119f16676dfda9abb3b40d83cb0fd1d32 100644 --- a/services/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/wifi_p2p_dns_sd_service_response.cpp +++ b/wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/wifi_p2p_dns_sd_service_response.cpp @@ -50,8 +50,9 @@ bool WifiP2pDnsSdServiceResponse::FetchTxtData(std::istringstream &istream) if (t > (istream.str().size() - istream.tellg())) { return false; } - std::unique_ptr ptr = std::make_unique(t); + std::unique_ptr ptr = std::make_unique(t + 1); istream.read(ptr.get(), t); + ptr[t] = '\0'; std::istringstream iss(ptr.get()); std::string keyVal[2]; getline(iss, keyVal[0], '='); diff --git a/services/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/wifi_p2p_dns_sd_service_response.h b/wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/wifi_p2p_dns_sd_service_response.h similarity index 100% rename from services/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/wifi_p2p_dns_sd_service_response.h rename to wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/wifi_p2p_dns_sd_service_response.h diff --git a/services/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/wifi_p2p_dns_txt_record.cpp b/wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/wifi_p2p_dns_txt_record.cpp similarity index 94% rename from services/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/wifi_p2p_dns_txt_record.cpp rename to wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/wifi_p2p_dns_txt_record.cpp index 696315337011b13fe435c85ce097dcb5230d4e6b..b543b3d4944f4a95c407f3b59f5366aad47837c2 100644 --- a/services/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/wifi_p2p_dns_txt_record.cpp +++ b/wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/wifi_p2p_dns_txt_record.cpp @@ -39,8 +39,8 @@ void WifiP2PDnsTxtRecord::InsertData( insertIndex += (data[insertIndex] + mapLengthSize) & 0xff; } - int addLength = keyBytes.size() + valBytes.size() + ((valBytes.size() == 0) ? 0 : mapLengthSize); - int newDataLength = addLength + mapLengthSize + oldData.size(); + int addLength = (int)keyBytes.size() + (int)valBytes.size() + ((valBytes.size() == 0) ? 0 : mapLengthSize); + int newDataLength = addLength + mapLengthSize + (int)oldData.size(); data.clear(); @@ -108,7 +108,7 @@ bool WifiP2PDnsTxtRecord::SetRecord(const std::string &key, const std::string &v } for (unsigned long index = 0; index < key.length(); ++index) { if (key[index] == '=') { - WIFI_LOGE("= is invaild in keys!"); + WIFI_LOGE("= is invalid in keys!"); return false; } keyBytes.push_back(static_cast(*(key.c_str() + index))); @@ -134,4 +134,4 @@ const std::vector &WifiP2PDnsTxtRecord::GetData() const return data; } } // namespace Wifi -} // namespace OHOS \ No newline at end of file +} // namespace OHOS diff --git a/services/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/wifi_p2p_dns_txt_record.h b/wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/wifi_p2p_dns_txt_record.h similarity index 100% rename from services/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/wifi_p2p_dns_txt_record.h rename to wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/wifi_p2p_dns_txt_record.h diff --git a/services/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/wifi_p2p_group_info_proxy.cpp b/wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/wifi_p2p_group_info_proxy.cpp similarity index 97% rename from services/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/wifi_p2p_group_info_proxy.cpp rename to wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/wifi_p2p_group_info_proxy.cpp index 688fd6046a6c1ab52d2dc2a8895f7729d573ef7f..01aa461bb6ac8fc231c6558109e0128ac308cee3 100644 --- a/services/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/wifi_p2p_group_info_proxy.cpp +++ b/wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/wifi_p2p_group_info_proxy.cpp @@ -189,6 +189,11 @@ void WifiP2pGroupInfoProxy::ClearClientDevices() groupsInfo.ClearClientDevices(); } +bool WifiP2pGroupInfoProxy::IsExplicitGroup() const +{ + return groupsInfo.IsExplicitGroup(); +} + WifiP2pGroupInfoProxy &WifiP2pGroupInfoProxy::operator=(const WifiP2pGroupInfo &group) { std::unique_lock lock(proxyMutex); @@ -202,4 +207,4 @@ WifiP2pGroupInfoProxy::operator WifiP2pGroupInfo() const return groupsInfo; } } // namespace Wifi -} // namespace OHOS \ No newline at end of file +} // namespace OHOS diff --git a/services/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/wifi_p2p_group_info_proxy.h b/wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/wifi_p2p_group_info_proxy.h similarity index 95% rename from services/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/wifi_p2p_group_info_proxy.h rename to wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/wifi_p2p_group_info_proxy.h index 8be86fad9267cf97d79dd95eb1268b4dceb47922..52ac9ba47b3652a6cb82decb4883cb55cb8db357 100644 --- a/services/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/wifi_p2p_group_info_proxy.h +++ b/wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/wifi_p2p_group_info_proxy.h @@ -1,5 +1,5 @@ /* - * Copyright (C) 2021 Huawei Device Co., Ltd. + * Copyright (C) 2021-2022 Huawei Device Co., Ltd. * 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 @@ -16,7 +16,7 @@ #define OHOS_P2P_WIFI_P2P_GROUP_INFO_PROXY_H #include -#include "wifi_msg.h" +#include "wifi_p2p_msg.h" namespace OHOS { namespace Wifi { @@ -80,6 +80,7 @@ public: std::vector GetClientDevices() const; void SetClientDevices(const std::vector &devices); void ClearClientDevices(); + bool IsExplicitGroup() const; public: ~WifiP2pGroupInfoProxy() = default; @@ -104,4 +105,4 @@ private: } // namespace Wifi } // namespace OHOS -#endif // OHOS_P2P_WIFI_P2P_GROUP_INFO_PROXY_H \ No newline at end of file +#endif // OHOS_P2P_WIFI_P2P_GROUP_INFO_PROXY_H diff --git a/services/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/wifi_p2p_group_manager.cpp b/wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/wifi_p2p_group_manager.cpp similarity index 93% rename from services/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/wifi_p2p_group_manager.cpp rename to wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/wifi_p2p_group_manager.cpp index 39b5190b26109f77e69f9ebc65946fc9ced92058..12457af092f7490ba1194383f24d9c7d44eeb4e1 100644 --- a/services/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/wifi_p2p_group_manager.cpp +++ b/wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/wifi_p2p_group_manager.cpp @@ -1,5 +1,5 @@ /* - * Copyright (C) 2021 Huawei Device Co., Ltd. + * Copyright (C) 2021-2022 Huawei Device Co., Ltd. * 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 @@ -21,7 +21,6 @@ namespace OHOS { namespace Wifi { - WifiP2pGroupManager::WifiP2pGroupManager() : groupsInfo(), currentGroup(), groupMutex(), p2pConnInfo() {} @@ -50,6 +49,19 @@ bool WifiP2pGroupManager::AddGroup(const WifiP2pGroupInfo &group) groupsInfo.push_back(group); return true; } + +bool WifiP2pGroupManager::AddOrUpdateGroup(const WifiP2pGroupInfo &group) +{ + std::unique_lock lock(groupMutex); + for (auto it = groupsInfo.begin(); it != groupsInfo.end(); ++it) { + if (*it == group) { + groupsInfo.erase(it); + break; + } + } + groupsInfo.push_back(group); + return true; +} bool WifiP2pGroupManager::RemoveGroup(const WifiP2pGroupInfo &group) { std::unique_lock lock(groupMutex); @@ -87,7 +99,6 @@ void WifiP2pGroupManager::UpdateWpaGroup(const WifiP2pGroupInfo &group) int WifiP2pGroupManager::RemoveClientFromGroup(int networkId, const std::string &deviceAddress) { - bool isRemoveSucceed = false; WifiP2pDevice device; device.SetDeviceAddress(deviceAddress); @@ -97,7 +108,6 @@ int WifiP2pGroupManager::RemoveClientFromGroup(int networkId, const std::string if (networkId == it->GetNetworkId()) { if (it->IsContainsDevice(device)) { it->RemoveClientDevice(device); - isRemoveSucceed = true; } break; } @@ -209,12 +219,12 @@ void WifiP2pGroupManager::RefreshCurrentGroupFromGroups() } } -void WifiP2pGroupManager::SaveP2pInfo(const WifiP2pInfo &connInfo) +void WifiP2pGroupManager::SaveP2pInfo(const WifiP2pLinkedInfo &linkedInfo) { - p2pConnInfo = connInfo; + p2pConnInfo = linkedInfo; } -const WifiP2pInfo &WifiP2pGroupManager::GetP2pInfo() const +const WifiP2pLinkedInfo &WifiP2pGroupManager::GetP2pInfo() const { return p2pConnInfo; } diff --git a/services/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/wifi_p2p_group_manager.h b/wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/wifi_p2p_group_manager.h similarity index 86% rename from services/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/wifi_p2p_group_manager.h rename to wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/wifi_p2p_group_manager.h index 313c58d1bad53b015e0508f3917c343982fb13a9..626abd46199b2d71301aee2d5bc0292f7ad816db 100644 --- a/services/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/wifi_p2p_group_manager.h +++ b/wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/wifi_p2p_group_manager.h @@ -1,5 +1,5 @@ /* - * Copyright (C) 2021 Huawei Device Co., Ltd. + * Copyright (C) 2021-2022 Huawei Device Co., Ltd. * 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 @@ -12,6 +12,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + #ifndef OHOS_P2P_GROUP_MANAGER_H #define OHOS_P2P_GROUP_MANAGER_H @@ -34,34 +35,47 @@ public: * @return None */ WifiP2pGroupManager(); + /** * @Description Destroy the WifiP2pGroupManager object. * @param None * @return None */ virtual ~WifiP2pGroupManager() = default; + /** * @Description - Reads the stored group information during initialization. * @param None * @return None */ virtual void Initialize(); + /** * @Description - Stores and serializes the current group information. */ virtual void StashGroups(); + /** * @Description - Adding a P2P group. * @param group - P2P group to be added * @return true: adding succeeded false: adding failed */ virtual bool AddGroup(const WifiP2pGroupInfo &group); + + /** + * @Description - Adding or Updating a P2P group. + * @param group - P2P group to be modified or add + * @return true: adding or Updating succeeded false: adding or Updating failed + */ + virtual bool AddOrUpdateGroup(const WifiP2pGroupInfo &group); + /** * @Description - Remove a P2P group. * @param group - P2P group to be removed * @return true: delete successfully false: delete failed */ virtual bool RemoveGroup(const WifiP2pGroupInfo &group); + /** * @Description - Clear all P2P groups. * @param None @@ -83,6 +97,7 @@ public: * @return - int number of clients in the group */ virtual int RemoveClientFromGroup(int networkId, const std::string &deviceAddress); + /** * @Description - Obtaining all groups. * @param None @@ -96,12 +111,14 @@ public: * @return - int -1:not found >=0:network ID of the corresponding group */ virtual int GetNetworkIdFromClients(const WifiP2pDevice &device); + /** * @Description Get the network id of the group owner profile with the specified p2p device address. * @param device - P2P devices to be matched * @return int -1: not found >=0: network ID of the P2P device */ virtual int GetGroupNetworkId(const WifiP2pDevice &device); + /** * @Description Get the network id of the group owner profile with the specified p2p device address and the ssid. @@ -110,30 +127,35 @@ public: * @return int -1: not found >=0: network ID of the P2P device */ virtual int GetGroupNetworkId(const WifiP2pDevice &device, const std::string &ssid); + /** * @Description Get the group owner mac address with the specified networkId. * @param netId - specifies the network ID of the group * @return std::string not null: MAC address of the group owner null: not found */ virtual std::string GetGroupOwnerAddr(int netId); + /** * @Description Specifies whether the group with networkId is included in the group list. * @param netId - specifies the network ID of a group * @return true:contains false:not contains */ virtual bool IsInclude(int netId); + /** * @Description Store P2P group connection information. * - * @param connInfo - group connection information + * @param linkedInfo - group connection information */ - virtual void SaveP2pInfo(const WifiP2pInfo &connInfo); + virtual void SaveP2pInfo(const WifiP2pLinkedInfo &linkedInfo); + /** * @Description Get P2P group connection information. * - * @return const WifiP2pInfo& group connection information + * @return const WifiP2pLinkedInfo& group connection information */ - virtual const WifiP2pInfo &GetP2pInfo() const; + virtual const WifiP2pLinkedInfo &GetP2pInfo() const; + /** * @Description Obtain the group information from the WPA, match and update the network ID. * @@ -150,20 +172,34 @@ public: { currentGroup.AddClientDevice(device); } + + inline void RemoveCurrGroupClient(const WifiP2pDevice &device) + { + currentGroup.RemoveClientDevice(device); + } + + inline bool IsCurrGroupClientEmpty(void) + { + return currentGroup.IsClientDevicesEmpty(); + } + inline void SetCurrentGroup(const WifiP2pGroupInfo &group) { currentGroup = group; RefreshCurrentGroupFromGroups(); } + inline const WifiP2pGroupInfoProxy &GetCurrentGroup() const { return currentGroup; } + private: /** * @Description - Synchronize from the current group to all registry groups. */ void RefreshGroupsFromCurrentGroup(); + /** * @Description - From all record groups, update to the current group in use. */ @@ -173,7 +209,7 @@ private: std::vector groupsInfo; WifiP2pGroupInfoProxy currentGroup; std::mutex groupMutex; - WifiP2pInfo p2pConnInfo; /* group connection information */ + WifiP2pLinkedInfo p2pConnInfo; /* group connection information */ }; } // namespace Wifi } // namespace OHOS diff --git a/services/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/wifi_p2p_service.cpp b/wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/wifi_p2p_service.cpp similarity index 59% rename from services/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/wifi_p2p_service.cpp rename to wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/wifi_p2p_service.cpp index af16816a6d54d5f2cd10df0622c6b524e07deab2..67838d684b6c80a7dbb0786f5ae8fc3bf5cffb24 100644 --- a/services/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/wifi_p2p_service.cpp +++ b/wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/wifi_p2p_service.cpp @@ -1,5 +1,5 @@ /* - * Copyright (C) 2021 Huawei Device Co., Ltd. + * Copyright (C) 2021-2022 Huawei Device Co., Ltd. * 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 @@ -12,12 +12,14 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + #include "wifi_p2p_service.h" -#include "wifi_settings.h" -#include "wifi_errcode.h" -#include "p2p_define.h" #include "abstract_ui.h" +#include "p2p_define.h" +#include "wifi_common_util.h" +#include "wifi_errcode.h" #include "wifi_logger.h" +#include "wifi_settings.h" DEFINE_WIFILOG_P2P_LABEL("WifiP2pService"); @@ -70,12 +72,14 @@ ErrCode WifiP2pService::DiscoverServices() p2pStateMachine.SendMessage(static_cast(P2P_STATE_MACHINE_CMD::CMD_DISCOVER_SERVICES)); return ErrCode::WIFI_OPT_SUCCESS; } + ErrCode WifiP2pService::StopDiscoverServices() { WIFI_LOGI("StopDiscoverServices"); p2pStateMachine.SendMessage(static_cast(P2P_STATE_MACHINE_CMD::CMD_STOP_DISCOVER_SERVICES)); return ErrCode::WIFI_OPT_SUCCESS; } + ErrCode WifiP2pService::PutLocalP2pService(const WifiP2pServiceInfo &srvInfo) { WIFI_LOGI("PutLocalP2pService"); @@ -83,6 +87,7 @@ ErrCode WifiP2pService::PutLocalP2pService(const WifiP2pServiceInfo &srvInfo) p2pStateMachine.SendMessage(static_cast(P2P_STATE_MACHINE_CMD::CMD_PUT_LOCAL_SERVICE), info); return ErrCode::WIFI_OPT_SUCCESS; } + ErrCode WifiP2pService::DeleteLocalP2pService(const WifiP2pServiceInfo &srvInfo) { WIFI_LOGI("DeleteLocalP2pService"); @@ -112,10 +117,15 @@ ErrCode WifiP2pService::StopP2pListen() p2pStateMachine.SendMessage(static_cast(P2P_STATE_MACHINE_CMD::CMD_STOP_LISTEN)); return ErrCode::WIFI_OPT_SUCCESS; } -ErrCode WifiP2pService::FormGroup(const WifiP2pConfig &config) + +ErrCode WifiP2pService::CreateGroup(const WifiP2pConfig &config) { - WIFI_LOGI("FormGroup"); - const std::any info = config; + WIFI_LOGI("CreateGroup"); + WifiP2pConfigInternal configInternal(config); + WpsInfo wps; + wps.SetWpsMethod(WpsMethod::WPS_METHOD_PBC); + configInternal.SetWpsInfo(wps); + const std::any info = configInternal; p2pStateMachine.SendMessage(static_cast(P2P_STATE_MACHINE_CMD::CMD_FORM_GROUP), info); return ErrCode::WIFI_OPT_SUCCESS; } @@ -138,15 +148,22 @@ ErrCode WifiP2pService::DeleteGroup(const WifiP2pGroupInfo &group) ErrCode WifiP2pService::P2pConnect(const WifiP2pConfig &config) { WIFI_LOGI("P2pConnect"); - const std::any info = config; + WifiP2pConfigInternal configInternal(config); + WpsInfo wps; + wps.SetWpsMethod(WpsMethod::WPS_METHOD_PBC); + configInternal.SetWpsInfo(wps); + p2pStateMachine.SetIsNeedDhcp(true); + const std::any info = configInternal; p2pStateMachine.SendMessage(static_cast(P2P_STATE_MACHINE_CMD::CMD_CONNECT), info); return ErrCode::WIFI_OPT_SUCCESS; } -ErrCode WifiP2pService::P2pDisConnect() +ErrCode WifiP2pService::P2pCancelConnect() { - return RemoveGroup(); + WIFI_LOGI("P2pCancelConnect"); + p2pStateMachine.SendMessage(static_cast(P2P_STATE_MACHINE_CMD::CMD_CANCEL_CONNECT)); + return ErrCode::WIFI_OPT_SUCCESS; } ErrCode WifiP2pService::SetP2pDeviceName(const std::string &devName) @@ -159,22 +176,23 @@ ErrCode WifiP2pService::SetP2pDeviceName(const std::string &devName) ErrCode WifiP2pService::SetP2pWfdInfo(const WifiP2pWfdInfo &wfdInfo) { - WIFI_LOGD("enable = %d device info = %d port = %d throughput = %d\n", + WIFI_LOGD("enable = %{public}d device info = %{public}d port = %{public}d throughput = %{public}d\n", wfdInfo.GetWfdEnabled(), wfdInfo.GetDeviceInfo(), wfdInfo.GetCtrlPort(), wfdInfo.GetMaxThroughput()); p2pStateMachine.SendMessage(static_cast(P2P_STATE_MACHINE_CMD::CMD_SET_WFD_INFO), wfdInfo); return ErrCode::WIFI_OPT_SUCCESS; } -ErrCode WifiP2pService::QueryP2pInfo(WifiP2pInfo &connInfo) + +ErrCode WifiP2pService::QueryP2pLinkedInfo(WifiP2pLinkedInfo &linkedInfo) { - WIFI_LOGI("QueryP2pInfo"); - connInfo = groupManager.GetP2pInfo(); + WIFI_LOGI("QueryP2pLinkedInfo"); + linkedInfo = groupManager.GetP2pInfo(); return ErrCode::WIFI_OPT_SUCCESS; } ErrCode WifiP2pService::GetCurrentGroup(WifiP2pGroupInfo &group) { WIFI_LOGI("GetCurrentGroup"); - WifiP2pInfo p2pInfo; + WifiP2pLinkedInfo p2pInfo; WifiSettings::GetInstance().GetP2pInfo(p2pInfo); if (p2pInfo.GetConnectState() == P2pConnectedState::P2P_DISCONNECTED) { return ErrCode::WIFI_OPT_FAILED; @@ -201,7 +219,7 @@ ErrCode WifiP2pService::GetP2pDiscoverStatus(int &status) ErrCode WifiP2pService::GetP2pConnectedStatus(int &status) { WIFI_LOGI("GetP2pConnectedStatus"); - WifiP2pInfo p2pInfo; + WifiP2pLinkedInfo p2pInfo; WifiSettings::GetInstance().GetP2pInfo(p2pInfo); status = static_cast(p2pInfo.GetConnectState()); return ErrCode::WIFI_OPT_SUCCESS; @@ -214,6 +232,13 @@ ErrCode WifiP2pService::QueryP2pDevices(std::vector &devices) return ErrCode::WIFI_OPT_SUCCESS; } +ErrCode WifiP2pService::QueryP2pLocalDevice(WifiP2pDevice &device) +{ + LOGI("QueryP2pLocalDevice"); + device = deviceManager.GetThisDevice(); + return ErrCode::WIFI_OPT_SUCCESS; +} + ErrCode WifiP2pService::QueryP2pGroups(std::vector &groups) { WIFI_LOGI("QueryP2pGroups"); @@ -240,5 +265,127 @@ void WifiP2pService::UnRegisterP2pServiceCallbacks() IP2pServiceCallbacks callbacks = {}; RegisterP2pServiceCallbacks(callbacks); } + +ErrCode WifiP2pService::Hid2dCreateGroup(const int frequency, FreqType type) +{ + WIFI_LOGI("Create hid2d group"); + const std::any info = frequency; + p2pStateMachine.SendMessage(static_cast(P2P_STATE_MACHINE_CMD::CMD_HID2D_CREATE_GROUP), info); + return ErrCode::WIFI_OPT_SUCCESS; +} + +ErrCode WifiP2pService::Hid2dConnect(const Hid2dConnectConfig& config) +{ + WIFI_LOGI("Hid2dConnect"); + + bool isNeedDhcp = true; + if (config.GetDhcpMode() == DhcpMode::CONNECT_GO_NODHCP || + config.GetDhcpMode() == DhcpMode::CONNECT_AP_NODHCP) { + isNeedDhcp = false; + } + p2pStateMachine.SetIsNeedDhcp(isNeedDhcp); + const std::any info = config; + p2pStateMachine.SendMessage(static_cast(P2P_STATE_MACHINE_CMD::CMD_HID2D_CONNECT), info); + return ErrCode::WIFI_OPT_SUCCESS; +} + +ErrCode WifiP2pService::Hid2dGetSelfWifiCfgInfo(SelfCfgType cfgType, + char cfgData[CFG_DATA_MAX_BYTES], int* getDatValidLen) +{ + WIFI_LOGI("Hid2dGetSelfWifiCfgInfo"); + *getDatValidLen = 0; + return WIFI_OPT_SUCCESS; +} + +ErrCode WifiP2pService::Hid2dSetPeerWifiCfgInfo(PeerCfgType cfgType, + char cfgData[CFG_DATA_MAX_BYTES], int setDataValidLen) +{ + WIFI_LOGI("Hid2dSetPeerWifiCfgInfo"); + return WIFI_OPT_SUCCESS; +} + +ErrCode WifiP2pService::Hid2dRequestGcIp(const std::string& gcMac, std::string& ipAddr) +{ + WIFI_LOGI("Hid2dRequestGcIp"); + + WifiP2pGroupInfo group; + ErrCode ret = GetCurrentGroup(group); + if (ret != WIFI_OPT_SUCCESS) { + WIFI_LOGI("Apply IP get current group failed!"); + } + IpPool::InitIpPool(group.GetGoIpAddress()); + ipAddr = IpPool::GetIp(gcMac); + return WIFI_OPT_SUCCESS; +} + +void WifiP2pService::IncreaseSharedLink(void) +{ + WIFI_LOGI("IncreaseSharedLink"); + SharedLinkManager::IncreaseSharedLink(); +} + +void WifiP2pService::DecreaseSharedLink(void) +{ + WIFI_LOGI("DecreaseSharedLink"); + SharedLinkManager::DecreaseSharedLink(); +} + +int WifiP2pService::GetSharedLinkCount(void) +{ + WIFI_LOGI("GetSharedLinkCount"); + return SharedLinkManager::GetSharedLinkCount(); +} + +int WifiP2pService::GetP2pRecommendChannel(void) +{ + WIFI_LOGI("GetP2pRecommendChannel"); + + int channel = 0; // 0 is invalid channel + + WifiLinkedInfo linkedInfo; + WifiSettings::GetInstance().GetLinkedInfo(linkedInfo); + if (linkedInfo.connState == CONNECTED) { + channel = FrequencyToChannel(linkedInfo.frequency); + WIFI_LOGI("Recommend linked channel: %{public}d", channel); + return channel; + } + + ChannelsTable channels; + std::vector vec5GChannels; + WifiSettings::GetInstance().GetValidChannels(channels); + if (channels.find(BandType::BAND_5GHZ) != channels.end()) { + vec5GChannels = channels[BandType::BAND_5GHZ]; + } + + const int COMMON_USING_5G_CHANNEL = 149; + const int COMMON_USING_2G_CHANNEL = 6; + if (!vec5GChannels.empty()) { + auto it = std::find(vec5GChannels.begin(), vec5GChannels.end(), COMMON_USING_5G_CHANNEL); + if (it != vec5GChannels.end()) { + channel = COMMON_USING_5G_CHANNEL; + } else { + channel = vec5GChannels[0]; + } + WIFI_LOGI("Recommend 5G channel: %{public}d", channel); + return channel; + } + WIFI_LOGI("Recommend 2G channel: %{public}d", COMMON_USING_2G_CHANNEL); + return COMMON_USING_2G_CHANNEL; +} + +ErrCode WifiP2pService::Hid2dSetUpperScene(const std::string& ifName, const Hid2dUpperScene& scene) +{ + WIFI_LOGI("Hid2dSetUpperScene"); + /* Not support currently */ + WIFI_LOGI("Set upper scene, ifName=%{public}s, scene=%{public}u, fps=%{public}d, bw=%{public}u", + ifName.c_str(), scene.scene, scene.fps, scene.bw); + return WIFI_OPT_SUCCESS; +} + +ErrCode WifiP2pService::MonitorCfgChange(void) +{ + WIFI_LOGI("MonitorCfgChange"); + return WIFI_OPT_SUCCESS; +} } // namespace Wifi } // namespace OHOS diff --git a/services/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/wifi_p2p_service.h b/wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/wifi_p2p_service.h similarity index 56% rename from services/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/wifi_p2p_service.h rename to wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/wifi_p2p_service.h index 50d4d8b9e637be8b46532f2cca870a9b090e7fae..98d6aa3ea92b2a244738abcf5d834eb406602aad 100644 --- a/services/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/wifi_p2p_service.h +++ b/wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/wifi_p2p_service.h @@ -1,5 +1,5 @@ /* - * Copyright (C) 2021 Huawei Device Co., Ltd. + * Copyright (C) 2021-2022 Huawei Device Co., Ltd. * 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 @@ -12,6 +12,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + #ifndef OHOS_P2P_SERVICE_H #define OHOS_P2P_SERVICE_H @@ -28,7 +29,8 @@ public: /** * @Description Construct a new WifiP2pService object. */ - explicit WifiP2pService(P2pStateMachine &, WifiP2pDeviceManager &, WifiP2pGroupManager &, WifiP2pServiceManager &); + explicit WifiP2pService(P2pStateMachine &p2pStateMachine, WifiP2pDeviceManager &setDeviceMgr, + WifiP2pGroupManager &setGroupMgr, WifiP2pServiceManager &setSvrMgr); /** * @Description Destroy the WifiP2pService object. */ @@ -37,44 +39,44 @@ public: public: /** * @Description - Enable the P2P mode. - * @return - ErrCode + * @return ErrCode - operation result */ virtual ErrCode EnableP2p() override; /** * @Description - Disable the P2P mode. - * @return - ErrCode + * @return ErrCode - operation result */ virtual ErrCode DisableP2p() override; /** * @Description - Start P2P device search. - * @return - ErrCode + * @return ErrCode - operation result */ virtual ErrCode DiscoverDevices() override; /** * @Description - Stop P2P device search. - * @return - ErrCode + * @return ErrCode - operation result */ virtual ErrCode StopDiscoverDevices() override; /** * @Description - Start P2P service search. - * @return - ErrCode + * @return ErrCode - operation result */ virtual ErrCode DiscoverServices() override; /** * @Description - Stop P2P service search. - * @return - ErrCode + * @return ErrCode - operation result */ virtual ErrCode StopDiscoverServices() override; /** * @Description - Register the local P2P service. * @param srvInfo - local service information - * @return - ErrCode + * @return ErrCode - operation result */ virtual ErrCode PutLocalP2pService(const WifiP2pServiceInfo &srvInfo) override; /** * @Description - Delete the local P2P service. * @param srvInfo - local service information - * @return - ErrCode + * @return ErrCode - operation result */ virtual ErrCode DeleteLocalP2pService(const WifiP2pServiceInfo &srvInfo) override; @@ -82,49 +84,49 @@ public: * @Description - Request specified services. * @param device - requested target device * @param request - initiated service request data - * @return - ErrCode + * @return ErrCode - operation result */ virtual ErrCode RequestService(const WifiP2pDevice &device, const WifiP2pServiceRequest &request) override; /** * @Description - Start the P2P listening. Unit: millisecond. * @param period - listening period * @param interval - listening interval - * @return - ErrCode + * @return ErrCode - operation result */ virtual ErrCode StartP2pListen(int period, int interval) override; /** * @Description - Stop the P2P listening. - * @return - ErrCode + * @return ErrCode - operation result */ virtual ErrCode StopP2pListen() override; /** * @Description - Create a P2P group. * @param config - config for creating group - * @return - ErrCode + * @return ErrCode - operation result */ - virtual ErrCode FormGroup(const WifiP2pConfig &config) override; + virtual ErrCode CreateGroup(const WifiP2pConfig &config) override; /** * @Description - Remove the current P2P group. - * @return - ErrCode + * @return ErrCode - operation result */ virtual ErrCode RemoveGroup() override; /** * @Description - Delete a persistent group. * @param group - specified group - * @return - ErrCode + * @return ErrCode - operation result */ virtual ErrCode DeleteGroup(const WifiP2pGroupInfo &group) override; /** * @Description - Connect to a P2P device. * @param config - config for connection - * @return - ErrCode + * @return ErrCode - operation result */ virtual ErrCode P2pConnect(const WifiP2pConfig &config) override; /** - * @Description - Disconnect. - * @return - ErrCode + * @Description - Canceling a P2P connection. + * @return ErrCode - operation result */ - virtual ErrCode P2pDisConnect() override; + virtual ErrCode P2pCancelConnect() override; /** * @Description - Set this device name. * @@ -134,56 +136,62 @@ public: virtual ErrCode SetP2pDeviceName(const std::string &devName) override; /** * @Description - Query P2P connection information. - * @param connInfo - object that stores connection information - * @return - ErrCode + * @param linkedInfo - object that stores connection information + * @return ErrCode - operation result */ - virtual ErrCode QueryP2pInfo(WifiP2pInfo &connInfo) override; + virtual ErrCode QueryP2pLinkedInfo(WifiP2pLinkedInfo &linkedInfo) override; /** * @Description - Get the current group information. * @param group - object that stores the current group - * @return - ErrCode + * @return ErrCode - operation result */ virtual ErrCode GetCurrentGroup(WifiP2pGroupInfo &group) override; /** * @Description - Obtain the P2P status. * @param status - object that stores P2P status - * @return - ErrCode + * @return ErrCode - operation result */ virtual ErrCode GetP2pEnableStatus(int &status) override; /** * @Description - Obtain the P2P discovery status. * @param status - object that stores discovery status - * @return - ErrCode + * @return ErrCode - operation result */ virtual ErrCode GetP2pDiscoverStatus(int &status) override; /** * @Description - Obtain the P2P connection status. * @param status - object that stores connection status - * @return - ErrCode + * @return ErrCode - operation result */ virtual ErrCode GetP2pConnectedStatus(int &status) override; /** * @Description - Query the information about the found devices. * @param devices - list of queryed device - * @return - ErrCode + * @return ErrCode - operation result */ virtual ErrCode QueryP2pDevices(std::vector &devices) override; + /** + * @Description - Query the information about own device. + * @param device - own device + * @return ErrCode - operation result + */ + virtual ErrCode QueryP2pLocalDevice(WifiP2pDevice &device) override; /** * @Description - Obtain information about all groups. * @param groups - list of group information - * @return - ErrCode + * @return ErrCode - operation result */ virtual ErrCode QueryP2pGroups(std::vector &groups) override; /** * @Description - Query the information about the found services. * @param services - list of service information - * @return - ErrCode + * @return ErrCode - operation result */ virtual ErrCode QueryP2pServices(std::vector &services) override; /** * @Description - Register all callbacks provided by the P2P. * @param callbacks - all callbacks added - * @return - ErrCode + * @return ErrCode - operation result */ virtual ErrCode RegisterP2pServiceCallbacks(const IP2pServiceCallbacks &callbacks) override; @@ -191,10 +199,100 @@ public: * @Description set p2p wifi display info * * @param wfdInfo - wifi display info - * @return ErrCode - operate result + * @return ErrCode - operation result */ virtual ErrCode SetP2pWfdInfo(const WifiP2pWfdInfo &wfdInfo) override; + /** + * @Description Create hid2d group, used on the GO side. + * + * @param frequency - frequency + * @param type - frequency type + * @return ErrCode - operation result + */ + virtual ErrCode Hid2dCreateGroup(const int frequency, FreqType type) override; + + /** + * @Description Connect to a specified group using hid2d, used on the GC side. + * + * @param config - connection parameters + * @return ErrCode - operation result + */ + virtual ErrCode Hid2dConnect(const Hid2dConnectConfig& config) override; + + /** + * @Description Get self config info + * + * @param cfgType - config type + * @param cfgData - config data + * @param getDatValidLen - data length + * @return ErrCode - operate result + */ + virtual ErrCode Hid2dGetSelfWifiCfgInfo(SelfCfgType cfgType, + char cfgData[CFG_DATA_MAX_BYTES], int* getDatValidLen) override; + + /** + * @Description Set self config info + * + * @param cfgType - config type + * @param cfgData - config data + * @param setDataValidLen - data length + * @return ErrCode - operate result + */ + virtual ErrCode Hid2dSetPeerWifiCfgInfo(PeerCfgType cfgType, + char cfgData[CFG_DATA_MAX_BYTES], int setDataValidLen) override; + + /** + * @Description Set self config info + * + * @param gcMac - gc mac address + * @param ipAddr - allocated ip address + * @return ErrCode - operate result + */ + virtual ErrCode Hid2dRequestGcIp(const std::string& gcMac, std::string& ipAddr) override; + + /** + * @Description Increase the reference count of the hid2d service. + * + */ + virtual void IncreaseSharedLink(void) override; + + /** + * @Description Decrease the reference count of the hid2d service. + * + */ + virtual void DecreaseSharedLink(void) override; + + /** + * @Description Get the reference count of the hid2d service. + * + * @return int - reference count + */ + virtual int GetSharedLinkCount(void) override; + + /** + * @Description - Get P2P recommended channel. + * + * @return - int - Recommended channel + */ + virtual int GetP2pRecommendChannel(void) override; + + /** + * @Description Set the scene of upper layer + * + * @param ifName - interface name + * @param scene - scene + * @return ErrCode - operate result + */ + virtual ErrCode Hid2dSetUpperScene(const std::string& ifName, const Hid2dUpperScene& scene) override; + + /** + * @Description Monitor the wifi configuration change + * + * @return ErrCode - operate result + */ + virtual ErrCode MonitorCfgChange(void) override; + private: /** * @Description - P2P state machine deregistration event callback. diff --git a/services/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/wifi_p2p_service_manager.cpp b/wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/wifi_p2p_service_manager.cpp similarity index 99% rename from services/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/wifi_p2p_service_manager.cpp rename to wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/wifi_p2p_service_manager.cpp index beb1a69fac0f53ca9e6f72e8e41f0b4666213c50..ffce8f56bb989d0cb51c60c0584293df0001d01d 100644 --- a/services/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/wifi_p2p_service_manager.cpp +++ b/wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/wifi_p2p_service_manager.cpp @@ -369,7 +369,7 @@ bool WifiP2pServiceManager::UpdateServiceName(const std::string &devAddr, const { auto iter = deviceService.find(devAddr); if (iter == deviceService.end()) { - WIFI_LOGE("Cannot find %s, update service name failed!", devAddr.c_str()); + WIFI_LOGE("Cannot find %{public}s, update service name failed!", devAddr.c_str()); return false; } diff --git a/services/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/wifi_p2p_service_manager.h b/wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/wifi_p2p_service_manager.h similarity index 100% rename from services/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/wifi_p2p_service_manager.h rename to wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/wifi_p2p_service_manager.h diff --git a/services/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/wifi_p2p_service_request_list.cpp b/wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/wifi_p2p_service_request_list.cpp similarity index 100% rename from services/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/wifi_p2p_service_request_list.cpp rename to wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/wifi_p2p_service_request_list.cpp diff --git a/services/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/wifi_p2p_service_request_list.h b/wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/wifi_p2p_service_request_list.h similarity index 100% rename from services/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/wifi_p2p_service_request_list.h rename to wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/wifi_p2p_service_request_list.h diff --git a/services/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/wifi_p2p_service_response_list.cpp b/wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/wifi_p2p_service_response_list.cpp similarity index 99% rename from services/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/wifi_p2p_service_response_list.cpp rename to wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/wifi_p2p_service_response_list.cpp index 373c23fc08513d6ebdc0c95aeddd20453bcaae87..f3fe88153c4b9f26756291d641d0a707c6c5d1d4 100644 --- a/services/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/wifi_p2p_service_response_list.cpp +++ b/wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/wifi_p2p_service_response_list.cpp @@ -76,7 +76,7 @@ WifiP2pServiceResponseList WifiP2pServiceResponseList::ReverseFilterSerivceRespo bool WifiP2pServiceResponseList::MergerAndDeduplicate(const WifiP2pServiceResponseList &respList) { if (p2pDevice.GetDeviceAddress() != respList.GetDevice().GetDeviceAddress()) { - WIFI_LOGE("Diffrent device!"); + WIFI_LOGE("Different device!"); return false; } diff --git a/services/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/wifi_p2p_service_response_list.h b/wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/wifi_p2p_service_response_list.h similarity index 100% rename from services/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/wifi_p2p_service_response_list.h rename to wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/wifi_p2p_service_response_list.h diff --git a/services/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/wifi_p2p_temp_disc_event.cpp b/wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/wifi_p2p_temp_disc_event.cpp similarity index 100% rename from services/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/wifi_p2p_temp_disc_event.cpp rename to wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/wifi_p2p_temp_disc_event.cpp diff --git a/services/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/wifi_p2p_temp_disc_event.h b/wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/wifi_p2p_temp_disc_event.h similarity index 100% rename from services/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/wifi_p2p_temp_disc_event.h rename to wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/wifi_p2p_temp_disc_event.h diff --git a/services/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/wifi_p2p_upnp_service_info.cpp b/wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/wifi_p2p_upnp_service_info.cpp similarity index 91% rename from services/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/wifi_p2p_upnp_service_info.cpp rename to wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/wifi_p2p_upnp_service_info.cpp index 3833a9df4a4ed5598c1043f4624adceb502c5d3f..fb780cb5a1e3e7c9780374212052a9a86394a2af 100644 --- a/services/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/wifi_p2p_upnp_service_info.cpp +++ b/wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/wifi_p2p_upnp_service_info.cpp @@ -33,6 +33,7 @@ WifiP2pUpnpServiceInfo WifiP2pUpnpServiceInfo::Create(const std::string &uuid, c } WifiP2pUpnpServiceInfo upnpServInfo(upnpInfo); upnpServInfo.SetServiceName(svrName); + upnpServInfo.SetServicerProtocolType(P2pServicerProtocolType::SERVICE_TYPE_UP_NP); return upnpServInfo; } @@ -42,7 +43,9 @@ std::string WifiP2pUpnpServiceInfo::BuildWpaQuery( std::string query; query.append("upnp "); char version[4] = {'\0'}; - snprintf_s(version, sizeof(version), sizeof(version) - 1, "%02x ", VERSION_1_0); + if (snprintf_s(version, sizeof(version), sizeof(version) - 1, "%02x ", VERSION_1_0) < 0) { + return ""; + } query.append(std::string(version)); query.append(std::string("uuid:")); query.append(uuid); diff --git a/services/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/wifi_p2p_upnp_service_info.h b/wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/wifi_p2p_upnp_service_info.h similarity index 100% rename from services/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/wifi_p2p_upnp_service_info.h rename to wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/wifi_p2p_upnp_service_info.h index 1f4595af6aa570b76b70d40925e1dcac346ed5e9..6cc9ad614ba7cb2ccac9c3b0ee7644762a1ef989 100644 --- a/services/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/wifi_p2p_upnp_service_info.h +++ b/wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/wifi_p2p_upnp_service_info.h @@ -35,6 +35,11 @@ namespace Wifi { */ static WifiP2pUpnpServiceInfo Create(const std::string &uuid, const std::string &device, const std::vector &services, const std::string &svrName); + /** + * @Description Destroy the WifiP2pUpnpServiceInfo object. + * + */ + ~WifiP2pUpnpServiceInfo() = default; private: /** @@ -53,11 +58,6 @@ namespace Wifi { * @param queryList - the character string list used to supplicant command */ explicit WifiP2pUpnpServiceInfo(std::vector &queryList); - /** - * @Description Destroy the WifiP2pUpnpServiceInfo object. - * - */ - ~WifiP2pUpnpServiceInfo() = default; }; } // namespace Wifi } // namespace OHOS diff --git a/services/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/wifi_p2p_upnp_service_request.cpp b/wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/wifi_p2p_upnp_service_request.cpp similarity index 81% rename from services/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/wifi_p2p_upnp_service_request.cpp rename to wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/wifi_p2p_upnp_service_request.cpp index 0edc03388d5f361fb43888b5a1f897b6dcd4cb42..2dd5170a0e1401fcc6edf0da59e37077a201f14f 100644 --- a/services/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/wifi_p2p_upnp_service_request.cpp +++ b/wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/wifi_p2p_upnp_service_request.cpp @@ -39,9 +39,13 @@ WifiP2pUpnpServiceRequest WifiP2pUpnpServiceRequest::Create(std::string searchTa std::string query; char version[4] = {'\0'}; if (searchTarget.empty()) { - WIFI_LOGE("failed, search target cann't be nullptr, something wrong may happen."); + WIFI_LOGE("failed, search target can't be nullptr, something wrong may happen."); + } + if (snprintf_s(version, sizeof(version), sizeof(version) - 1, "%02x ", WifiP2pUpnpServiceInfo::VERSION_1_0) < 0) { + WIFI_LOGE("ifiP2pUpnpServiceRequest::Create snprintf_s failed."); + WifiP2pUpnpServiceRequest retErr; + return retErr; } - snprintf_s(version, sizeof(version), sizeof(version) - 1, "%02x ", WifiP2pUpnpServiceInfo::VERSION_1_0); query.append(std::string(version)); query.append(WifiP2pServiceInfo::Bin2HexStr(searchTarget)); WifiP2pUpnpServiceRequest ret(query); @@ -49,4 +53,4 @@ WifiP2pUpnpServiceRequest WifiP2pUpnpServiceRequest::Create(std::string searchTa return ret; } } // namespace Wifi -} // namespace OHOS \ No newline at end of file +} // namespace OHOS diff --git a/services/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/wifi_p2p_upnp_service_request.h b/wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/wifi_p2p_upnp_service_request.h similarity index 100% rename from services/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/wifi_p2p_upnp_service_request.h rename to wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/wifi_p2p_upnp_service_request.h diff --git a/services/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/wifi_p2p_upnp_service_response.cpp b/wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/wifi_p2p_upnp_service_response.cpp similarity index 100% rename from services/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/wifi_p2p_upnp_service_response.cpp rename to wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/wifi_p2p_upnp_service_response.cpp diff --git a/services/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/wifi_p2p_upnp_service_response.h b/wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/wifi_p2p_upnp_service_response.h similarity index 100% rename from services/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/wifi_p2p_upnp_service_response.h rename to wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/wifi_p2p_upnp_service_response.h diff --git a/services/wifi_standard/wifi_framework/wifi_manage/wifi_p2p_callback_proxy.cpp b/wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_p2p_callback_proxy.cpp similarity index 78% rename from services/wifi_standard/wifi_framework/wifi_manage/wifi_p2p_callback_proxy.cpp rename to wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_p2p_callback_proxy.cpp index ce4610a02551c583ef3cc87ffc13c874fe4dbe04..7183de4006cf555a8b6b4d927744aa906b08a5c0 100644 --- a/services/wifi_standard/wifi_framework/wifi_manage/wifi_p2p_callback_proxy.cpp +++ b/wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_p2p_callback_proxy.cpp @@ -1,5 +1,5 @@ /* - * Copyright (C) 2021 Huawei Device Co., Ltd. + * Copyright (C) 2021-2022 Huawei Device Co., Ltd. * 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 @@ -12,6 +12,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + #include "wifi_p2p_callback_proxy.h" #include "wifi_logger.h" #include "define.h" @@ -33,6 +34,10 @@ void WifiP2pCallbackProxy::OnP2pStateChanged(int state) MessageOption option; MessageParcel data; MessageParcel reply; + if (!data.WriteInterfaceToken(GetDescriptor())) { + WIFI_LOGE("Write interface token error: %{public}s", __func__); + return; + } data.WriteInt32(0); data.WriteInt32(state); int error = Remote()->SendRequest(WIFI_CBK_CMD_P2P_STATE_CHANGE, data, reply, option); @@ -53,6 +58,10 @@ void WifiP2pCallbackProxy::OnP2pPersistentGroupsChanged(void) MessageOption option; MessageParcel data; MessageParcel reply; + if (!data.WriteInterfaceToken(GetDescriptor())) { + WIFI_LOGE("Write interface token error: %{public}s", __func__); + return; + } data.WriteInt32(0); int error = Remote()->SendRequest(WIFI_CBK_CMD_PERSISTENT_GROUPS_CHANGE, data, reply, option); if (error != ERR_NONE) { @@ -88,6 +97,10 @@ void WifiP2pCallbackProxy::OnP2pThisDeviceChanged(const WifiP2pDevice &device) MessageOption option; MessageParcel data; MessageParcel reply; + if (!data.WriteInterfaceToken(GetDescriptor())) { + WIFI_LOGE("Write interface token error: %{public}s", __func__); + return; + } data.WriteInt32(0); WriteWifiP2pDeviceData(data, device); int error = Remote()->SendRequest(WIFI_CBK_CMD_THIS_DEVICE_CHANGE, data, reply, option); @@ -108,6 +121,10 @@ void WifiP2pCallbackProxy::OnP2pPeersChanged(const std::vector &d MessageOption option; MessageParcel data; MessageParcel reply; + if (!data.WriteInterfaceToken(GetDescriptor())) { + WIFI_LOGE("Write interface token error: %{public}s", __func__); + return; + } data.WriteInt32(0); int size = devices.size(); data.WriteInt32(size); @@ -132,6 +149,10 @@ void WifiP2pCallbackProxy::OnP2pServicesChanged(const std::vector(info.GetConnectState())); data.WriteBool(info.IsGroupOwner()); @@ -185,6 +210,10 @@ void WifiP2pCallbackProxy::OnP2pDiscoveryChanged(bool isChange) MessageOption option; MessageParcel data; MessageParcel reply; + if (!data.WriteInterfaceToken(GetDescriptor())) { + WIFI_LOGE("Write interface token error: %{public}s", __func__); + return; + } data.WriteInt32(0); data.WriteBool(isChange); int error = Remote()->SendRequest(WIFI_CBK_CMD_DISCOVERY_CHANGE, data, reply, option); @@ -205,6 +234,10 @@ void WifiP2pCallbackProxy::OnP2pActionResult(P2pActionCallback action, ErrCode c MessageOption option; MessageParcel data; MessageParcel reply; + if (!data.WriteInterfaceToken(GetDescriptor())) { + WIFI_LOGE("Write interface token error: %{public}s", __func__); + return; + } data.WriteInt32(0); data.WriteInt32(static_cast(action)); data.WriteInt32(static_cast(code)); @@ -219,5 +252,31 @@ void WifiP2pCallbackProxy::OnP2pActionResult(P2pActionCallback action, ErrCode c } return; } + +void WifiP2pCallbackProxy::OnConfigChanged(CfgType type, char* cfgData, int dataLen) +{ + WIFI_LOGD("WifiP2pCallbackProxy::OnConfigChanged"); + MessageOption option; + MessageParcel data; + MessageParcel reply; + if (!data.WriteInterfaceToken(GetDescriptor())) { + WIFI_LOGE("Write interface token error: %{public}s", __func__); + return; + } + data.WriteInt32(0); + data.WriteInt32(static_cast(type)); + data.WriteInt32(dataLen); + data.WriteBuffer(cfgData, dataLen); + int error = Remote()->SendRequest(WIFI_CBK_CMD_CFG_CHANGE, data, reply, option); + if (error != ERR_NONE) { + WIFI_LOGE("Set Attr(%{public}d) failed,error code is %{public}d", WIFI_CBK_CMD_CFG_CHANGE, error); + return; + } + int exception = reply.ReadInt32(); + if (exception) { + WIFI_LOGI("notify wifi p2p action callback result failed!"); + } + return; +} } // namespace Wifi } // namespace OHOS diff --git a/services/wifi_standard/wifi_framework/wifi_manage/wifi_p2p_callback_proxy.h b/wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_p2p_callback_proxy.h similarity index 85% rename from services/wifi_standard/wifi_framework/wifi_manage/wifi_p2p_callback_proxy.h rename to wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_p2p_callback_proxy.h index 835df17541564f846563fd8c5993ce6ddf5c0cbd..e737ce374c0a4176c8658e62440f7d6ee26a372e 100644 --- a/services/wifi_standard/wifi_framework/wifi_manage/wifi_p2p_callback_proxy.h +++ b/wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_p2p_callback_proxy.h @@ -63,9 +63,9 @@ public: /** * @Description Connection status change * - * @param info - WifiP2pInfo object + * @param info - WifiP2pLinkedInfo object */ - void OnP2pConnectionChanged(const WifiP2pInfo &info) override; + void OnP2pConnectionChanged(const WifiP2pLinkedInfo &info) override; /** * @Description Discover status change @@ -78,12 +78,21 @@ public: * @Description P2p callback result * * @param action - DiscoverDevices/StopDiscoverDevices/DiscoverServices/StopDiscoverServices - * /PutLocalP2pService/StartP2pListen/StopP2pListen/FormGroup/RemoveGroup - * /DeleteGroup/P2pConnect/P2pDisConnect + * /PutLocalP2pService/StartP2pListen/StopP2pListen/CreateGroup/RemoveGroup + * /DeleteGroup/P2pConnect/P2pCancelConnect * @param code - Return code */ void OnP2pActionResult(P2pActionCallback action, ErrCode code) override; + /** + * @Description Config changed callback. + * + * @param type - Config type + * @param cfgData - Config data + * @param dataLen - Config data length + */ + void OnConfigChanged(CfgType type, char* cfgData, int dataLen) override; + private: void WriteWifiP2pDeviceData(MessageParcel &data, const WifiP2pDevice &device); diff --git a/services/wifi_standard/wifi_framework/wifi_manage/wifi_p2p_death_recipient.cpp b/wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_p2p_death_recipient.cpp similarity index 100% rename from services/wifi_standard/wifi_framework/wifi_manage/wifi_p2p_death_recipient.cpp rename to wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_p2p_death_recipient.cpp diff --git a/services/wifi_standard/wifi_framework/wifi_manage/wifi_p2p_death_recipient.h b/wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_p2p_death_recipient.h similarity index 100% rename from services/wifi_standard/wifi_framework/wifi_manage/wifi_p2p_death_recipient.h rename to wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_p2p_death_recipient.h diff --git a/services/wifi_standard/wifi_framework/wifi_manage/wifi_p2p_service_impl.cpp b/wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_p2p_service_impl.cpp similarity index 53% rename from services/wifi_standard/wifi_framework/wifi_manage/wifi_p2p_service_impl.cpp rename to wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_p2p_service_impl.cpp index fbea0b9e67f411a6e06c70dcfa5788cbc8e99842..f6e781df393adb77769358ab18bffefeff5902ef 100644 --- a/services/wifi_standard/wifi_framework/wifi_manage/wifi_p2p_service_impl.cpp +++ b/wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_p2p_service_impl.cpp @@ -1,5 +1,5 @@ /* - * Copyright (C) 2021 Huawei Device Co., Ltd. + * Copyright (C) 2021-2022 Huawei Device Co., Ltd. * 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 @@ -12,15 +12,23 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + #include "wifi_p2p_service_impl.h" -#include "wifi_permission_utils.h" +#include +#include "define.h" +#include "if_config.h" +#include "ip_tools.h" #include "wifi_auth_center.h" +#include "wifi_common_util.h" #include "wifi_config_center.h" -#include "wifi_manager.h" -#include "wifi_service_manager.h" +#include "wifi_dumper.h" +#include "wifi_hid2d_service_utils.h" #include "wifi_internal_event_dispatcher.h" #include "wifi_logger.h" -#include "define.h" +#include "wifi_manager.h" +#include "wifi_net_agent.h" +#include "wifi_permission_utils.h" +#include "wifi_service_manager.h" DEFINE_WIFILOG_P2P_LABEL("WifiP2pServiceImpl"); @@ -52,7 +60,7 @@ WifiP2pServiceImpl::~WifiP2pServiceImpl() void WifiP2pServiceImpl::OnStart() { if (mState == ServiceRunningState::STATE_RUNNING) { - WIFI_LOGD("P2p service has already started."); + WIFI_LOGI("P2p service has already started."); return; } if (!Init()) { @@ -92,11 +100,11 @@ ErrCode WifiP2pServiceImpl::CheckCanEnableP2p(void) return WIFI_OPT_PERMISSION_DENIED; } if (WifiConfigCenter::GetInstance().GetAirplaneModeState() == 1) { - WIFI_LOGD("current airplane mode and can not use p2p, open failed!"); + WIFI_LOGW("current airplane mode and can not use p2p, open failed!"); return WIFI_OPT_FORBID_AIRPLANE; } if (WifiConfigCenter::GetInstance().GetPowerSavingModeState() == 1) { - WIFI_LOGD("current power saving mode and can not use p2p, open failed!"); + WIFI_LOGW("current power saving mode and can not use p2p, open failed!"); return WIFI_OPT_FORBID_POWSAVING; } return WIFI_OPT_SUCCESS; @@ -112,7 +120,7 @@ ErrCode WifiP2pServiceImpl::EnableP2p(void) WifiOprMidState curState = WifiConfigCenter::GetInstance().GetP2pMidState(); if (curState != WifiOprMidState::CLOSED) { - WIFI_LOGD("current p2p state is %{public}d", static_cast(curState)); + WIFI_LOGW("current p2p state is %{public}d", static_cast(curState)); if (curState == WifiOprMidState::CLOSING) { return WIFI_OPT_OPEN_FAIL_WHEN_CLOSING; } else { @@ -162,7 +170,7 @@ ErrCode WifiP2pServiceImpl::DisableP2p(void) WifiOprMidState curState = WifiConfigCenter::GetInstance().GetP2pMidState(); if (curState != WifiOprMidState::RUNNING) { - WIFI_LOGD("current p2p state is %{public}d", static_cast(curState)); + WIFI_LOGI("current p2p state is %{public}d", static_cast(curState)); if (curState == WifiOprMidState::OPENING) { return WIFI_OPT_CLOSE_FAIL_WHEN_OPENING; } else { @@ -189,13 +197,22 @@ ErrCode WifiP2pServiceImpl::DisableP2p(void) ErrCode WifiP2pServiceImpl::DiscoverDevices(void) { WIFI_LOGI("DiscoverDevices"); - if (WifiPermissionUtils::VerifyGetWifiDirectDevicePermission() == PERMISSION_DENIED) { - WIFI_LOGE("DiscoverDevices:VerifyGetWifiDirectDevicePermission PERMISSION_DENIED!"); - return WIFI_OPT_PERMISSION_DENIED; + if (WifiPermissionUtils::VerifyGetWifiInfoInternalPermission() == PERMISSION_DENIED) { + WIFI_LOGE("DiscoverDevices:VerifyGetWifiInfoInternalPermission PERMISSION_DENIED!"); + + if (WifiPermissionUtils::VerifyGetWifiInfoPermission() == PERMISSION_DENIED) { + WIFI_LOGE("DiscoverDevices:VerifyGetWifiInfoPermission PERMISSION_DENIED!"); + return WIFI_OPT_PERMISSION_DENIED; + } + + if (WifiPermissionUtils::VerifyGetScanInfosPermission() == PERMISSION_DENIED) { + WIFI_LOGE("DiscoverDevices:VerifyGetScanInfosPermission PERMISSION_DENIED!"); + return WIFI_OPT_PERMISSION_DENIED; + } } if (!IsP2pServiceRunning()) { - WIFI_LOGE("P2pService is not runing!"); + WIFI_LOGE("P2pService is not running!"); return WIFI_OPT_P2P_NOT_OPENED; } @@ -210,8 +227,13 @@ ErrCode WifiP2pServiceImpl::DiscoverDevices(void) ErrCode WifiP2pServiceImpl::StopDiscoverDevices(void) { WIFI_LOGI("StopDiscoverDevices"); + if (WifiPermissionUtils::VerifyGetWifiInfoPermission() == PERMISSION_DENIED) { + WIFI_LOGE("StopDiscoverDevices:VerifyGetWifiInfoPermission PERMISSION_DENIED!"); + return WIFI_OPT_PERMISSION_DENIED; + } + if (!IsP2pServiceRunning()) { - WIFI_LOGE("P2pService is not runing!"); + WIFI_LOGE("P2pService is not running!"); return WIFI_OPT_P2P_NOT_OPENED; } @@ -232,7 +254,7 @@ ErrCode WifiP2pServiceImpl::DiscoverServices(void) } if (!IsP2pServiceRunning()) { - WIFI_LOGE("P2pService is not runing!"); + WIFI_LOGE("P2pService is not running!"); return WIFI_OPT_P2P_NOT_OPENED; } @@ -248,7 +270,7 @@ ErrCode WifiP2pServiceImpl::StopDiscoverServices(void) { WIFI_LOGI("StopDiscoverServices"); if (!IsP2pServiceRunning()) { - WIFI_LOGE("P2pService is not runing!"); + WIFI_LOGE("P2pService is not running!"); return WIFI_OPT_P2P_NOT_OPENED; } @@ -269,7 +291,7 @@ ErrCode WifiP2pServiceImpl::RequestService(const WifiP2pDevice &device, const Wi } if (!IsP2pServiceRunning()) { - WIFI_LOGE("P2pService is not runing!"); + WIFI_LOGE("P2pService is not running!"); return WIFI_OPT_P2P_NOT_OPENED; } @@ -285,7 +307,7 @@ ErrCode WifiP2pServiceImpl::PutLocalP2pService(const WifiP2pServiceInfo &srvInfo { WIFI_LOGI("PutLocalP2pService, service name is [%{public}s]", srvInfo.GetServiceName().c_str()); if (!IsP2pServiceRunning()) { - WIFI_LOGE("P2pService is not runing!"); + WIFI_LOGE("P2pService is not running!"); return WIFI_OPT_P2P_NOT_OPENED; } @@ -301,7 +323,7 @@ ErrCode WifiP2pServiceImpl::DeleteLocalP2pService(const WifiP2pServiceInfo &srvI { WIFI_LOGI("DeleteLocalP2pService, service name is [%{public}s]", srvInfo.GetServiceName().c_str()); if (!IsP2pServiceRunning()) { - WIFI_LOGE("P2pService is not runing!"); + WIFI_LOGE("P2pService is not running!"); return WIFI_OPT_P2P_NOT_OPENED; } @@ -322,7 +344,7 @@ ErrCode WifiP2pServiceImpl::StartP2pListen(int period, int interval) } if (!IsP2pServiceRunning()) { - WIFI_LOGE("P2pService is not runing!"); + WIFI_LOGE("P2pService is not running!"); return WIFI_OPT_P2P_NOT_OPENED; } @@ -343,7 +365,7 @@ ErrCode WifiP2pServiceImpl::StopP2pListen() } if (!IsP2pServiceRunning()) { - WIFI_LOGE("P2pService is not runing!"); + WIFI_LOGE("P2pService is not running!"); return WIFI_OPT_P2P_NOT_OPENED; } @@ -355,16 +377,16 @@ ErrCode WifiP2pServiceImpl::StopP2pListen() return pService->StopP2pListen(); } -ErrCode WifiP2pServiceImpl::FormGroup(const WifiP2pConfig &config) +ErrCode WifiP2pServiceImpl::CreateGroup(const WifiP2pConfig &config) { - WIFI_LOGI("FormGroup, network name is [%{public}s]", config.GetNetworkName().c_str()); - if (WifiPermissionUtils::VerifyGetWifiDirectDevicePermission() == PERMISSION_DENIED) { - WIFI_LOGE("FormGroup:VerifyGetWifiDirectDevicePermission PERMISSION_DENIED!"); + WIFI_LOGI("CreateGroup, network name is [%{public}s]", config.GetGroupName().c_str()); + if (WifiPermissionUtils::VerifyGetWifiInfoPermission() == PERMISSION_DENIED) { + WIFI_LOGE("CreateGroup:VerifyGetWifiInfoPermission PERMISSION_DENIED!"); return WIFI_OPT_PERMISSION_DENIED; } if (!IsP2pServiceRunning()) { - WIFI_LOGE("P2pService is not runing!"); + WIFI_LOGE("P2pService is not running!"); return WIFI_OPT_P2P_NOT_OPENED; } @@ -373,14 +395,19 @@ ErrCode WifiP2pServiceImpl::FormGroup(const WifiP2pConfig &config) WIFI_LOGE("Get P2P service failed!"); return WIFI_OPT_P2P_NOT_OPENED; } - return pService->FormGroup(config); + return pService->CreateGroup(config); } ErrCode WifiP2pServiceImpl::RemoveGroup() { WIFI_LOGI("RemoveGroup"); + if (WifiPermissionUtils::VerifyGetWifiInfoPermission() == PERMISSION_DENIED) { + WIFI_LOGE("RemoveGroup:VerifyGetWifiInfoPermission PERMISSION_DENIED!"); + return WIFI_OPT_PERMISSION_DENIED; + } + if (!IsP2pServiceRunning()) { - WIFI_LOGE("P2pService is not runing!"); + WIFI_LOGE("P2pService is not running!"); return WIFI_OPT_P2P_NOT_OPENED; } @@ -395,8 +422,18 @@ ErrCode WifiP2pServiceImpl::RemoveGroup() ErrCode WifiP2pServiceImpl::DeleteGroup(const WifiP2pGroupInfo &group) { WIFI_LOGI("DeleteGroup, group name [%{public}s]", group.GetGroupName().c_str()); + if (WifiPermissionUtils::VerifySetWifiInfoPermission() == PERMISSION_DENIED) { + WIFI_LOGE("DeleteGroup:VerifySetWifiInfoPermission PERMISSION_DENIED!"); + return WIFI_OPT_PERMISSION_DENIED; + } + + if (WifiPermissionUtils::VerifyWifiConnectionPermission() == PERMISSION_DENIED) { + WIFI_LOGE("DeleteGroup:VerifyWifiConnectionPermission PERMISSION_DENIED!"); + return WIFI_OPT_PERMISSION_DENIED; + } + if (!IsP2pServiceRunning()) { - WIFI_LOGE("P2pService is not runing!"); + WIFI_LOGE("P2pService is not running!"); return WIFI_OPT_P2P_NOT_OPENED; } @@ -411,13 +448,22 @@ ErrCode WifiP2pServiceImpl::DeleteGroup(const WifiP2pGroupInfo &group) ErrCode WifiP2pServiceImpl::P2pConnect(const WifiP2pConfig &config) { WIFI_LOGI("P2pConnect device address [%{private}s]", config.GetDeviceAddress().c_str()); - if (WifiPermissionUtils::VerifyGetWifiDirectDevicePermission() == PERMISSION_DENIED) { - WIFI_LOGE("P2pConnect:VerifyGetWifiDirectDevicePermission PERMISSION_DENIED!"); - return WIFI_OPT_PERMISSION_DENIED; + if (WifiPermissionUtils::VerifyGetWifiInfoInternalPermission() == PERMISSION_DENIED) { + WIFI_LOGE("P2pConnect:VerifyGetWifiInfoInternalPermission PERMISSION_DENIED!"); + + if (WifiPermissionUtils::VerifyGetWifiInfoPermission() == PERMISSION_DENIED) { + WIFI_LOGE("P2pConnect:VerifyGetWifiInfoPermission PERMISSION_DENIED!"); + return WIFI_OPT_PERMISSION_DENIED; + } + + if (WifiPermissionUtils::VerifyGetScanInfosPermission() == PERMISSION_DENIED) { + WIFI_LOGE("P2pConnect:VerifyGetScanInfosPermission PERMISSION_DENIED!"); + return WIFI_OPT_PERMISSION_DENIED; + } } if (!IsP2pServiceRunning()) { - WIFI_LOGE("P2pService is not runing!"); + WIFI_LOGE("P2pService is not running!"); return WIFI_OPT_P2P_NOT_OPENED; } @@ -429,11 +475,16 @@ ErrCode WifiP2pServiceImpl::P2pConnect(const WifiP2pConfig &config) return pService->P2pConnect(config); } -ErrCode WifiP2pServiceImpl::P2pDisConnect() +ErrCode WifiP2pServiceImpl::P2pCancelConnect() { - WIFI_LOGI("P2pDisConnect"); + WIFI_LOGI("P2pCancelConnect"); + if (WifiPermissionUtils::VerifyGetWifiInfoPermission() == PERMISSION_DENIED) { + WIFI_LOGE("P2pCancelConnect:VerifyGetWifiInfoPermission PERMISSION_DENIED!"); + return WIFI_OPT_PERMISSION_DENIED; + } + if (!IsP2pServiceRunning()) { - WIFI_LOGE("P2pService is not runing!"); + WIFI_LOGE("P2pService is not running!"); return WIFI_OPT_P2P_NOT_OPENED; } @@ -442,14 +493,19 @@ ErrCode WifiP2pServiceImpl::P2pDisConnect() WIFI_LOGE("Get P2P service failed!"); return WIFI_OPT_P2P_NOT_OPENED; } - return pService->P2pDisConnect(); + return pService->P2pCancelConnect(); } -ErrCode WifiP2pServiceImpl::QueryP2pInfo(WifiP2pInfo &connInfo) +ErrCode WifiP2pServiceImpl::QueryP2pLinkedInfo(WifiP2pLinkedInfo &linkedInfo) { - WIFI_LOGI("QueryP2pInfo group owner address [%{private}s]", connInfo.GetGroupOwnerAddress().c_str()); + WIFI_LOGI("QueryP2pLinkedInfo group owner address [%{private}s]", linkedInfo.GetGroupOwnerAddress().c_str()); + if (WifiPermissionUtils::VerifyGetWifiInfoPermission() == PERMISSION_DENIED) { + WIFI_LOGE("QueryP2pLinkedInfo:VerifyGetWifiInfoPermission PERMISSION_DENIED!"); + return WIFI_OPT_PERMISSION_DENIED; + } + if (!IsP2pServiceRunning()) { - WIFI_LOGE("P2pService is not runing!"); + WIFI_LOGE("P2pService is not running!"); return WIFI_OPT_P2P_NOT_OPENED; } @@ -458,14 +514,38 @@ ErrCode WifiP2pServiceImpl::QueryP2pInfo(WifiP2pInfo &connInfo) WIFI_LOGE("Get P2P service failed!"); return WIFI_OPT_P2P_NOT_OPENED; } - return pService->QueryP2pInfo(connInfo); + + ErrCode ret = pService->QueryP2pLinkedInfo(linkedInfo); + if (ret == WIFI_OPT_SUCCESS) { + if (WifiPermissionUtils::VerifyGetWifiLocalMacPermission() == PERMISSION_DENIED) { + WIFI_LOGE("QueryP2pLinkedInfo:VerifyGetWifiLocalMacPermission PERMISSION_DENIED!"); + linkedInfo.SetIsGroupOwnerAddress("00.00.00.00"); + } + } + + return ret; } ErrCode WifiP2pServiceImpl::GetCurrentGroup(WifiP2pGroupInfo &group) { WIFI_LOGI("GetCurrentGroup"); + + if (WifiPermissionUtils::VerifyGetWifiInfoInternalPermission() == PERMISSION_DENIED) { + WIFI_LOGE("GetCurrentGroup:VerifyGetWifiInfoInternalPermission PERMISSION_DENIED!"); + + if (WifiPermissionUtils::VerifyGetWifiInfoPermission() == PERMISSION_DENIED) { + WIFI_LOGE("GetCurrentGroup:VerifyGetWifiInfoPermission PERMISSION_DENIED!"); + return WIFI_OPT_PERMISSION_DENIED; + } + + if (WifiPermissionUtils::VerifyGetScanInfosPermission() == PERMISSION_DENIED) { + WIFI_LOGE("GetCurrentGroup:VerifyGetScanInfosPermission PERMISSION_DENIED!"); + return WIFI_OPT_PERMISSION_DENIED; + } + } + if (!IsP2pServiceRunning()) { - WIFI_LOGE("P2pService is not runing!"); + WIFI_LOGE("P2pService is not running!"); return WIFI_OPT_P2P_NOT_OPENED; } @@ -488,7 +568,7 @@ ErrCode WifiP2pServiceImpl::GetP2pDiscoverStatus(int &status) { WIFI_LOGI("GetP2pDiscoverStatus"); if (!IsP2pServiceRunning()) { - WIFI_LOGE("P2pService is not runing!"); + WIFI_LOGE("P2pService is not running!"); return WIFI_OPT_P2P_NOT_OPENED; } @@ -504,7 +584,7 @@ ErrCode WifiP2pServiceImpl::GetP2pConnectedStatus(int &status) { WIFI_LOGI("GetP2pConnectedStatus"); if (!IsP2pServiceRunning()) { - WIFI_LOGE("P2pService is not runing!"); + WIFI_LOGE("P2pService is not running!"); return WIFI_OPT_P2P_NOT_OPENED; } @@ -516,11 +596,46 @@ ErrCode WifiP2pServiceImpl::GetP2pConnectedStatus(int &status) return pService->GetP2pConnectedStatus(status); } -ErrCode WifiP2pServiceImpl::QueryP2pDevices(std::vector &devives) +ErrCode WifiP2pServiceImpl::QueryP2pDevices(std::vector &devices) { WIFI_LOGI("QueryP2pDevices"); - if (WifiPermissionUtils::VerifyGetWifiDirectDevicePermission() == PERMISSION_DENIED) { - WIFI_LOGE("QueryP2pDevices:VerifyGetWifiDirectDevicePermission PERMISSION_DENIED!"); + if (WifiPermissionUtils::VerifyGetWifiInfoInternalPermission() == PERMISSION_DENIED) { + WIFI_LOGE("QueryP2pDevices:VerifyGetWifiInfoInternalPermission PERMISSION_DENIED!"); + + if (WifiPermissionUtils::VerifyGetWifiInfoPermission() == PERMISSION_DENIED) { + WIFI_LOGE("QueryP2pDevices:VerifyGetWifiInfoPermission PERMISSION_DENIED!"); + return WIFI_OPT_PERMISSION_DENIED; + } + + if (WifiPermissionUtils::VerifyGetScanInfosPermission() == PERMISSION_DENIED) { + WIFI_LOGE("QueryP2pDevices:VerifyGetScanInfosPermission PERMISSION_DENIED!"); + return WIFI_OPT_PERMISSION_DENIED; + } + } + + if (!IsP2pServiceRunning()) { + WIFI_LOGE("P2pService is not running!"); + return WIFI_OPT_P2P_NOT_OPENED; + } + + IP2pService *pService = WifiServiceManager::GetInstance().GetP2pServiceInst(); + if (pService == nullptr) { + WIFI_LOGE("Get P2P service failed!"); + return WIFI_OPT_P2P_NOT_OPENED; + } + return pService->QueryP2pDevices(devices); +} + +ErrCode WifiP2pServiceImpl::QueryP2pLocalDevice(WifiP2pDevice &device) +{ + WIFI_LOGI("QueryP2pLocalDevice"); + if (WifiPermissionUtils::VerifyGetWifiInfoPermission() == PERMISSION_DENIED) { + WIFI_LOGE("QueryP2pLocalDevice:VerifyGetWifiInfoPermission PERMISSION_DENIED!"); + return WIFI_OPT_PERMISSION_DENIED; + } + + if (WifiPermissionUtils::VerifyGetWifiConfigPermission() == PERMISSION_DENIED) { + WIFI_LOGE("QueryP2pLocalDevice:VerifyGetWifiConfigPermission PERMISSION_DENIED!"); return WIFI_OPT_PERMISSION_DENIED; } @@ -534,19 +649,33 @@ ErrCode WifiP2pServiceImpl::QueryP2pDevices(std::vector &devives) WIFI_LOGE("Get P2P service failed!"); return WIFI_OPT_P2P_NOT_OPENED; } - return pService->QueryP2pDevices(devives); + + ErrCode ret = pService->QueryP2pLocalDevice(device); + if (WifiPermissionUtils::VerifyGetWifiLocalMacPermission() == PERMISSION_DENIED) { + WIFI_LOGE("QueryP2pLocalDevice:VerifyGetWifiLocalMacPermission PERMISSION_DENIED!"); + device.SetDeviceAddress("00:00:00:00:00:00"); + } + return ret; } ErrCode WifiP2pServiceImpl::QueryP2pGroups(std::vector &groups) { WIFI_LOGI("QueryP2pGroups"); - if (WifiPermissionUtils::VerifyGetWifiDirectDevicePermission() == PERMISSION_DENIED) { - WIFI_LOGE("QueryP2pGroups:VerifyGetWifiDirectDevicePermission PERMISSION_DENIED!"); - return WIFI_OPT_PERMISSION_DENIED; + if (WifiPermissionUtils::VerifyGetWifiInfoInternalPermission() == PERMISSION_DENIED) { + WIFI_LOGE("QueryP2pGroups:VerifyGetWifiInfoInternalPermission PERMISSION_DENIED!"); + if (WifiPermissionUtils::VerifyGetWifiDirectDevicePermission() == PERMISSION_DENIED) { + WIFI_LOGE("QueryP2pGroups:VerifyGetWifiDirectDevicePermission PERMISSION_DENIED!"); + return WIFI_OPT_PERMISSION_DENIED; + } + + if (WifiPermissionUtils::VerifyGetWifiInfoPermission() == PERMISSION_DENIED) { + WIFI_LOGE("QueryP2pGroups:VerifyGetWifiInfoPermission PERMISSION_DENIED!"); + return WIFI_OPT_PERMISSION_DENIED; + } } if (!IsP2pServiceRunning()) { - WIFI_LOGE("P2pService is not runing!"); + WIFI_LOGE("P2pService is not running!"); return WIFI_OPT_P2P_NOT_OPENED; } @@ -562,7 +691,7 @@ ErrCode WifiP2pServiceImpl::QueryP2pServices(std::vector &se { WIFI_LOGI("QueryP2pServices"); if (!IsP2pServiceRunning()) { - WIFI_LOGE("P2pService is not runing!"); + WIFI_LOGE("P2pService is not running!"); return WIFI_OPT_P2P_NOT_OPENED; } @@ -599,7 +728,7 @@ bool WifiP2pServiceImpl::IsP2pServiceRunning() { WifiOprMidState curState = WifiConfigCenter::GetInstance().GetP2pMidState(); if (curState != WifiOprMidState::RUNNING) { - WIFI_LOGD("p2p service does not started!"); + WIFI_LOGW("p2p service does not started!"); return false; } return true; @@ -607,14 +736,24 @@ bool WifiP2pServiceImpl::IsP2pServiceRunning() ErrCode WifiP2pServiceImpl::SetP2pDeviceName(const std::string &deviceName) { - WIFI_LOGI("SetDeviceName:%s", deviceName.c_str()); + WIFI_LOGI("SetP2pDeviceName:%{public}s", deviceName.c_str()); + if (WifiPermissionUtils::VerifySetWifiInfoPermission() == PERMISSION_DENIED) { + WIFI_LOGE("SetP2pDeviceName:VerifySetWifiInfoPermission PERMISSION_DENIED!"); + return WIFI_OPT_PERMISSION_DENIED; + } + + if (WifiPermissionUtils::VerifyWifiConnectionPermission() == PERMISSION_DENIED) { + WIFI_LOGE("SetP2pDeviceName:VerifyWifiConnectionPermission PERMISSION_DENIED!"); + return WIFI_OPT_PERMISSION_DENIED; + } + int length = deviceName.length(); if (length > DEVICE_NAME_LENGTH || length < 0) { return WIFI_OPT_INVALID_PARAM; } WifiConfigCenter::GetInstance().SetP2pDeviceName(deviceName); if (!IsP2pServiceRunning()) { - WIFI_LOGE("P2pService is not runing!"); + WIFI_LOGE("P2pService is not running!"); return WIFI_OPT_SUCCESS; } IP2pService *pService = WifiServiceManager::GetInstance().GetP2pServiceInst(); @@ -624,11 +763,12 @@ ErrCode WifiP2pServiceImpl::SetP2pDeviceName(const std::string &deviceName) } return pService->SetP2pDeviceName(deviceName); } + ErrCode WifiP2pServiceImpl::SetP2pWfdInfo(const WifiP2pWfdInfo &wfdInfo) { WIFI_LOGI("SetP2pWfdInfo"); if (!IsP2pServiceRunning()) { - WIFI_LOGE("P2pService is not runing!"); + WIFI_LOGE("P2pService is not running!"); return WIFI_OPT_P2P_NOT_OPENED; } IP2pService *pService = WifiServiceManager::GetInstance().GetP2pServiceInst(); @@ -638,5 +778,258 @@ ErrCode WifiP2pServiceImpl::SetP2pWfdInfo(const WifiP2pWfdInfo &wfdInfo) } return pService->SetP2pWfdInfo(wfdInfo); } + +ErrCode WifiP2pServiceImpl::Hid2dRequestGcIp(const std::string& gcMac, std::string& ipAddr) +{ + WIFI_LOGI("Hid2dRequestGcIp"); + if (!IsP2pServiceRunning()) { + WIFI_LOGE("P2pService is not runing!"); + return WIFI_OPT_P2P_NOT_OPENED; + } + IP2pService *pService = WifiServiceManager::GetInstance().GetP2pServiceInst(); + if (pService == nullptr) { + WIFI_LOGE("Get P2P service failed!"); + return WIFI_OPT_P2P_NOT_OPENED; + } + return pService->Hid2dRequestGcIp(gcMac, ipAddr); +} + +ErrCode WifiP2pServiceImpl::Hid2dSharedlinkIncrease() +{ + WIFI_LOGI("Hid2dSharedlinkIncrease"); + int status = static_cast(P2pConnectedState::P2P_DISCONNECTED); + ErrCode ret = GetP2pConnectedStatus(status); + if (ret != WIFI_OPT_SUCCESS) { + WIFI_LOGI("Hid2dSharedlinkIncrease get P2P connect status error!"); + return ret; + } + if (status != static_cast(P2pConnectedState::P2P_CONNECTED)) { + WIFI_LOGE("Hid2dSharedlinkIncrease P2P not in connected state!"); + return WIFI_OPT_FAILED; + } + IP2pService *pService = WifiServiceManager::GetInstance().GetP2pServiceInst(); + if (pService == nullptr) { + WIFI_LOGE("Get P2P service failed!"); + return WIFI_OPT_FAILED; + } + pService->IncreaseSharedLink(); + return WIFI_OPT_SUCCESS; +} + +ErrCode WifiP2pServiceImpl::Hid2dSharedlinkDecrease() +{ + WIFI_LOGI("Hid2dSharedlinkDecrease"); + if (!IsP2pServiceRunning()) { + WIFI_LOGE("P2pService is not runing!"); + return WIFI_OPT_P2P_NOT_OPENED; + } + IP2pService *pService = WifiServiceManager::GetInstance().GetP2pServiceInst(); + if (pService == nullptr) { + WIFI_LOGE("Get P2P service failed!"); + return WIFI_OPT_P2P_NOT_OPENED; + } + pService->DecreaseSharedLink(); + if (pService->GetSharedLinkCount() == 0) { + WIFI_LOGI("Shared link count == 0, remove group!"); + RemoveGroup(); + } + return WIFI_OPT_SUCCESS; +} + +ErrCode WifiP2pServiceImpl::Hid2dCreateGroup(const int frequency, FreqType type) +{ + WIFI_LOGI("Hid2dCreateGroup"); + if (WifiPermissionUtils::VerifyGetWifiInfoPermission() == PERMISSION_DENIED) { + WIFI_LOGE("CreateGroup:VerifyGetWifiInfoPermission PERMISSION_DENIED!"); + return WIFI_OPT_PERMISSION_DENIED; + } + + if (!IsP2pServiceRunning()) { + WIFI_LOGE("P2pService is not running!"); + return WIFI_OPT_P2P_NOT_OPENED; + } + + IP2pService *pService = WifiServiceManager::GetInstance().GetP2pServiceInst(); + if (pService == nullptr) { + WIFI_LOGE("Get P2P service failed!"); + return WIFI_OPT_P2P_NOT_OPENED; + } + return pService->Hid2dCreateGroup(frequency, type); +} + +ErrCode WifiP2pServiceImpl::Hid2dRemoveGcGroup(const std::string& gcIfName) +{ + WIFI_LOGI("Hid2dRemoveGcGroup:, gcIfName: %{public}s", gcIfName.c_str()); + // TO Imple: delete by interface + return RemoveGroup(); +} + +ErrCode WifiP2pServiceImpl::Hid2dConnect(const Hid2dConnectConfig& config) +{ + WIFI_LOGI("Hid2dConnect"); + if (WifiPermissionUtils::VerifyGetWifiDirectDevicePermission() == PERMISSION_DENIED) { + WIFI_LOGE("Hid2dConnect:VerifyGetWifiDirectDevicePermission PERMISSION_DENIED!"); + return WIFI_OPT_PERMISSION_DENIED; + } + + if (!IsP2pServiceRunning()) { + WIFI_LOGE("P2pService is not running!"); + return WIFI_OPT_P2P_NOT_OPENED; + } + + IP2pService *pService = WifiServiceManager::GetInstance().GetP2pServiceInst(); + if (pService == nullptr) { + WIFI_LOGE("Get P2P service failed!"); + return WIFI_OPT_P2P_NOT_OPENED; + } + return pService->Hid2dConnect(config); +} + +ErrCode WifiP2pServiceImpl::Hid2dConfigIPAddr(const std::string& ifName, const IpAddrInfo& ipInfo) +{ + WIFI_LOGI("Hid2dConfigIPAddr, ifName: %{public}s", ifName.c_str()); + IfConfig::GetInstance().AddIpAddr(ifName, ipInfo.ip, ipInfo.netmask, IpType::IPTYPE_IPV4); + WifiNetAgent::GetInstance().AddRoute(ifName, ipInfo.ip, IpTools::GetMaskLength(ipInfo.netmask)); + return WIFI_OPT_SUCCESS; +} + +ErrCode WifiP2pServiceImpl::Hid2dReleaseIPAddr(const std::string& ifName) +{ + WIFI_LOGI("Hid2dReleaseIPAddr"); + IfConfig::GetInstance().FlushIpAddr(ifName, IpType::IPTYPE_IPV4); + return WIFI_OPT_SUCCESS; +} + +ErrCode WifiP2pServiceImpl::Hid2dGetRecommendChannel(const RecommendChannelRequest& request, + RecommendChannelResponse& response) +{ + WIFI_LOGI("Hid2dGetRecommendChannel"); + if (!IsP2pServiceRunning()) { + WIFI_LOGE("P2pService is not runing!"); + return WIFI_OPT_P2P_NOT_OPENED; + } + IP2pService *pService = WifiServiceManager::GetInstance().GetP2pServiceInst(); + if (pService == nullptr) { + WIFI_LOGE("Get P2P service failed!"); + return WIFI_OPT_P2P_NOT_OPENED; + } + int channel = pService->GetP2pRecommendChannel(); + int freq = ChannelToFrequency(channel); + WIFI_LOGI("Get recommended channel: %{public}d, freq: %{public}d", channel, freq); + response.centerFreq = freq; + response.status = RecommendStatus::RS_SUCCESS; + return WIFI_OPT_SUCCESS; +} + +ErrCode WifiP2pServiceImpl::Hid2dGetChannelListFor5G(std::vector& vecChannelList) +{ + WIFI_LOGI("Hid2dGetChannelListFor5G"); + ChannelsTable channels; + WifiSettings::GetInstance().GetValidChannels(channels); + if (channels.find(BandType::BAND_5GHZ) != channels.end()) { + vecChannelList = channels[BandType::BAND_5GHZ]; + } + + std::string strChannel; + for (auto channel : vecChannelList) { + strChannel += std::to_string(channel) + ","; + } + WIFI_LOGI("5G channel list[%{public}d]: %{public}s", + (int)vecChannelList.size(), strChannel.c_str()); + return WIFI_OPT_SUCCESS; +} + +ErrCode WifiP2pServiceImpl::Hid2dGetSelfWifiCfgInfo(SelfCfgType cfgType, + char cfgData[CFG_DATA_MAX_BYTES], int* getDatValidLen) +{ + WIFI_LOGI("Hid2dGetSelfWifiCfgInfo"); + if (!IsP2pServiceRunning()) { + WIFI_LOGE("P2pService is not runing!"); + return WIFI_OPT_P2P_NOT_OPENED; + } + + IP2pService *pService = WifiServiceManager::GetInstance().GetP2pServiceInst(); + if (pService == nullptr) { + WIFI_LOGE("Get P2P service failed!"); + return WIFI_OPT_P2P_NOT_OPENED; + } + return pService->Hid2dGetSelfWifiCfgInfo(cfgType, cfgData, getDatValidLen); +} + +ErrCode WifiP2pServiceImpl::Hid2dSetPeerWifiCfgInfo(PeerCfgType cfgType, + char cfgData[CFG_DATA_MAX_BYTES], int setDataValidLen) +{ + WIFI_LOGI("Hid2dSetPeerWifiCfgInfo"); + if (!IsP2pServiceRunning()) { + WIFI_LOGE("P2pService is not runing!"); + return WIFI_OPT_P2P_NOT_OPENED; + } + + IP2pService *pService = WifiServiceManager::GetInstance().GetP2pServiceInst(); + if (pService == nullptr) { + WIFI_LOGE("Get P2P service failed!"); + return WIFI_OPT_P2P_NOT_OPENED; + } + return pService->Hid2dSetPeerWifiCfgInfo(cfgType, cfgData, setDataValidLen); +} + +ErrCode WifiP2pServiceImpl::Hid2dSetUpperScene(const std::string& ifName, const Hid2dUpperScene& scene) +{ + WIFI_LOGI("Hid2dSetUpperScene"); + if (!IsP2pServiceRunning()) { + WIFI_LOGE("P2pService is not runing!"); + return WIFI_OPT_P2P_NOT_OPENED; + } + + IP2pService *pService = WifiServiceManager::GetInstance().GetP2pServiceInst(); + if (pService == nullptr) { + WIFI_LOGE("Get P2P service failed!"); + return WIFI_OPT_P2P_NOT_OPENED; + } + return pService->Hid2dSetUpperScene(ifName, scene); +} + +ErrCode WifiP2pServiceImpl::MonitorCfgChange(void) +{ + WIFI_LOGI("MonitorCfgChange"); + if (!IsP2pServiceRunning()) { + WIFI_LOGE("P2pService is not runing!"); + return WIFI_OPT_P2P_NOT_OPENED; + } + + IP2pService *pService = WifiServiceManager::GetInstance().GetP2pServiceInst(); + if (pService == nullptr) { + WIFI_LOGE("Get P2P service failed!"); + return WIFI_OPT_P2P_NOT_OPENED; + } + return pService->MonitorCfgChange(); +} + +void WifiP2pServiceImpl::SaBasicDump(std::string& result) +{ + result.append("P2P enable status: "); + int status = WifiConfigCenter::GetInstance().GetP2pState(); + std::string strStatus = (status == static_cast(P2pState::P2P_STATE_STARTED)) ? "enable" : "disable"; + result.append(strStatus); + result += "\n"; +} + +int32_t WifiP2pServiceImpl::Dump(int32_t fd, const std::vector& args) +{ + WIFI_LOGI("Enter p2p dump func."); + std::vector vecArgs; + std::transform(args.begin(), args.end(), std::back_inserter(vecArgs), [](const std::u16string &arg) { + return Str16ToStr8(arg); + }); + + WifiDumper dumper; + std::string result; + dumper.P2pDump(SaBasicDump, vecArgs, result); + if (!SaveStringToFd(fd, result)) { + WIFI_LOGE("WiFi P2p save string to fd failed."); + return ERR_OK; + } + return ERR_OK; +} } // namespace Wifi -} // namespace OHOS \ No newline at end of file +} // namespace OHOS diff --git a/services/wifi_standard/wifi_framework/wifi_manage/wifi_p2p_service_impl.h b/wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_p2p_service_impl.h similarity index 49% rename from services/wifi_standard/wifi_framework/wifi_manage/wifi_p2p_service_impl.h rename to wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_p2p_service_impl.h index f91b36a8b1728be6e20b0e46ebf2ef346313ab31..5bccdd2e245ece58ceb30d2f060343f14be6985a 100644 --- a/services/wifi_standard/wifi_framework/wifi_manage/wifi_p2p_service_impl.h +++ b/wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_p2p_service_impl.h @@ -1,5 +1,5 @@ /* - * Copyright (C) 2021 Huawei Device Co., Ltd. + * Copyright (C) 2021-2022 Huawei Device Co., Ltd. * 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 @@ -12,6 +12,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + #ifndef OHOS_WIFI_P2P_SERVICE_IMPL_H #define OHOS_WIFI_P2P_SERVICE_IMPL_H @@ -39,42 +40,42 @@ public: /** * @Description Enabling the P2P Mode * - * @return ErrCode - operate result + * @return ErrCode - operation result */ ErrCode EnableP2p(void) override; /** * @Description Disable the P2P mode * - * @return ErrCode - operate result + * @return ErrCode - operation result */ ErrCode DisableP2p(void) override; /** * @Description Start Wi-Fi P2P device search * - * @return ErrCode - operate result + * @return ErrCode - operation result */ ErrCode DiscoverDevices(void) override; /** * @Description Stop Wi-Fi P2P device search * - * @return ErrCode - operate result + * @return ErrCode - operation result */ ErrCode StopDiscoverDevices(void) override; /** * @Description Start the search for the Wi-Fi P2P service * - * @return ErrCode - operate result + * @return ErrCode - operation result */ ErrCode DiscoverServices(void) override; /** * @Description Stop the search for the Wi-Fi P2P service * - * @return ErrCode - operate result + * @return ErrCode - operation result */ ErrCode StopDiscoverServices(void) override; @@ -83,7 +84,7 @@ public: * * @param device - WifiP2pDevice object * @param request - WifiP2pServiceRequest object - * @return ErrCode - operate result + * @return ErrCode - operation result */ ErrCode RequestService(const WifiP2pDevice &device, const WifiP2pServiceRequest &request) override; @@ -91,7 +92,7 @@ public: * @Description Register the local P2P service * * @param srvInfo - WifiP2pServiceInfo object - * @return ErrCode - operate result + * @return ErrCode - operation result */ ErrCode PutLocalP2pService(const WifiP2pServiceInfo &srvInfo) override; @@ -99,7 +100,7 @@ public: * @Description Delete the local P2P service * * @param srvInfo - WifiP2pServiceInfo object - * @return ErrCode - operate result + * @return ErrCode - operation result */ ErrCode DeleteLocalP2pService(const WifiP2pServiceInfo &srvInfo) override; @@ -108,14 +109,14 @@ public: * * @param period - period * @param interval - interval - * @return ErrCode - operate result + * @return ErrCode - operation result */ ErrCode StartP2pListen(int period, int interval) override; /** * @Description Disable Wi-Fi P2P listening * - * @return ErrCode - operate result + * @return ErrCode - operation result */ ErrCode StopP2pListen(void) override; @@ -123,15 +124,15 @@ public: * @Description Creating a P2P Group * * @param config - WifiP2pGroupInfo object - * @return ErrCode - operate result + * @return ErrCode - operation result */ - ErrCode FormGroup(const WifiP2pConfig &config) override; + ErrCode CreateGroup(const WifiP2pConfig &config) override; /** * @Description Remove a P2P Group * * - * @return ErrCode - operate result + * @return ErrCode - operation result */ ErrCode RemoveGroup(void) override; @@ -139,7 +140,7 @@ public: * @Description Delete a p2p Group * * @param group - WifiP2pGroupInfo object - * @return ErrCode - operate result + * @return ErrCode - operation result */ ErrCode DeleteGroup(const WifiP2pGroupInfo &group) override; @@ -147,30 +148,30 @@ public: * @Description P2P connection * * @param config - WifiP2pConfig object - * @return ErrCode - operate result + * @return ErrCode - operation result */ ErrCode P2pConnect(const WifiP2pConfig &config) override; /** - * @Description P2P disconnection + * @Description Canceling a P2P connection * - * @return ErrCode - operate result + * @return ErrCode - operation result */ - ErrCode P2pDisConnect(void) override; + ErrCode P2pCancelConnect(void) override; /** * @Description Querying Wi-Fi P2P Connection Information * - * @param connInfo - Get the WifiP2pInfo msg - * @return ErrCode - operate result + * @param linkedInfo - Get the WifiP2pLinkedInfo msg + * @return ErrCode - operation result */ - ErrCode QueryP2pInfo(WifiP2pInfo &connInfo) override; + ErrCode QueryP2pLinkedInfo(WifiP2pLinkedInfo &linkedInfo) override; /** * @Description Get the Current Group object * * @param group - the WifiP2pGroupInfo object - * @return ErrCode - operate result + * @return ErrCode - operation result */ ErrCode GetCurrentGroup(WifiP2pGroupInfo &group) override; @@ -178,7 +179,7 @@ public: * @Description Obtains the P2P switch status * * @param status - the P2P switch status - * @return ErrCode - operate result + * @return ErrCode - operation result */ ErrCode GetP2pEnableStatus(int &status) override; @@ -194,23 +195,31 @@ public: * @Description Obtains the P2P connection status * * @param status - the P2P connection status - * @return ErrCode - operate result + * @return ErrCode - operation result */ ErrCode GetP2pConnectedStatus(int &status) override; /** * @Description Query the information about the found devices * - * @param devives - Get result vector of WifiP2pDevice - * @return ErrCode - operate result + * @param devices - Get result vector of WifiP2pDevice + * @return ErrCode - operation result + */ + ErrCode QueryP2pDevices(std::vector &devices) override; + + /** + * @Description Query the information about the local device + * + * @param devives - Get result of WifiP2pDevice + * @return ErrCode - operation result */ - ErrCode QueryP2pDevices(std::vector &devives) override; + ErrCode QueryP2pLocalDevice(WifiP2pDevice &device) override; /** * @Description Query the information about the found groups * * @param groups - Get result vector of WifiP2pGroupInfo - * @return ErrCode - operate result + * @return ErrCode - operation result */ ErrCode QueryP2pGroups(std::vector &groups) override; @@ -218,7 +227,7 @@ public: * @Description Query the service information * * @param services - Get result vector of Device - * @return ErrCode - operate result + * @return ErrCode - operation result */ ErrCode QueryP2pServices(std::vector &services) override; @@ -226,7 +235,7 @@ public: * @Description Register callback function * * @param callback - IWifiP2pCallback object - * @return ErrCode - operate result + * @return ErrCode - operation result */ ErrCode RegisterCallBack(const sptr &callback) override; @@ -242,7 +251,7 @@ public: * @Description set the device name * * @param deviceName - device name - * @return ErrCode - operate result + * @return ErrCode - operation result */ ErrCode SetP2pDeviceName(const std::string &deviceName) override; @@ -250,14 +259,145 @@ public: * @Description set p2p wifi display info * * @param wfdInfo - wifi display info - * @return ErrCode - operate result + * @return ErrCode - operation result */ ErrCode SetP2pWfdInfo(const WifiP2pWfdInfo &wfdInfo) override; + /** + * @Description Request an IP address to the Gc from the IP address pool, used on the GO side. + * + * @param gcMac - gc mac address + * @param ipAddr - applied ip address + * @return ErrCode - operation result + */ + ErrCode Hid2dRequestGcIp(const std::string& gcMac, std::string& ipAddr) override; + + /** + * @Description Increase(+1) hid2d shared link reference counting + * + * @return ErrCode - operation result + */ + ErrCode Hid2dSharedlinkIncrease() override; + + /** + * @Description Decrease(-1) hid2d shared link reference counting + * + * @return ErrCode - operation result + */ + ErrCode Hid2dSharedlinkDecrease() override; + + /** + * @Description Create hid2d group, used on the GO side. + * + * @param frequency - frequency + * @param type - frequency type + * @return ErrCode - operation result + */ + ErrCode Hid2dCreateGroup(const int frequency, FreqType type) override; + + /** + * @Description The GC side actively disconnects from the GO, used on the GC side. + * + * @param gcIfName - network interface name + * @return ErrCode - operation result + */ + ErrCode Hid2dRemoveGcGroup(const std::string& gcIfName) override; + + /** + * @Description Connect to a specified group using hid2d, used on the GC side. + * + * @param config - connection parameters + * @return ErrCode - operation result + */ + ErrCode Hid2dConnect(const Hid2dConnectConfig& config) override; + + /** + * @Description Configuring IP addresses for P2P network interfaces, used on the GC side. + * + * @param ifName - network interface name + * @param ipInfo - IP infos + * @return ErrCode - operation result + */ + ErrCode Hid2dConfigIPAddr(const std::string& ifName, const IpAddrInfo& ipInfo) override; + + /** + * @Description Clear IP address when the P2P connection is disconnected, used on the GC side. + * + * @param ifName - network interface name + * @return ErrCode - operation result + */ + ErrCode Hid2dReleaseIPAddr(const std::string& ifName) override; + + /** + * @Description Obtain the recommended channel and bandwidth for link setup + * + * @param request - request data + * @param response - response result + * @return ErrCode - operation result + */ + ErrCode Hid2dGetRecommendChannel(const RecommendChannelRequest& request, + RecommendChannelResponse& response) override; + + /** + * @Description get 5G channel list + * + * @param vecChannelList - result for channel list + * @return ErrCode - operation result + */ + ErrCode Hid2dGetChannelListFor5G(std::vector& vecChannelList) override; + + /** + * @Description get the self wifi configuration information + * + * @param cfgType - configuration type + * @param cfgData - the queried data of wifi configuration + * @param getDatValidLen - the valid data length in the array `cfgData` + * @return ErrCode - operation result + */ + ErrCode Hid2dGetSelfWifiCfgInfo(SelfCfgType cfgType, + char cfgData[CFG_DATA_MAX_BYTES], int* getDatValidLen) override; + + /** + * @Description set the peer wifi configuration information + * + * @param cfgType - configuration type + * @param cfgData - the wifi configuration data to be set + * @param setDataValidLen - the valid data length in the array `cfgData` + * @return ErrCode - operation result + */ + ErrCode Hid2dSetPeerWifiCfgInfo(PeerCfgType cfgType, + char cfgData[CFG_DATA_MAX_BYTES], int setDataValidLen) override; + + /** + * @Description Set the scene of upper layer + * + * @param ifName - interface name + * @param scene - scene + * @return ErrCode - operate result + */ + ErrCode Hid2dSetUpperScene(const std::string& ifName, const Hid2dUpperScene& scene) override; + + /** + * @Description Monitor the wifi configuration change + * + * @return ErrCode - operate result + */ + ErrCode MonitorCfgChange(void) override; + + /** + * @Description dump p2p information + * + * @param fd - file descriptor + * @param args - dump arguments + * @return ErrCode - operation result + */ + int32_t Dump(int32_t fd, const std::vector& args) override; + private: bool Init(); ErrCode CheckCanEnableP2p(void); bool IsP2pServiceRunning(); + static void SaBasicDump(std::string& result); private: static sptr instance; diff --git a/services/wifi_standard/wifi_framework/wifi_manage/wifi_p2p_stub.cpp b/wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_p2p_stub.cpp similarity index 64% rename from services/wifi_standard/wifi_framework/wifi_manage/wifi_p2p_stub.cpp rename to wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_p2p_stub.cpp index 6e6dc528bac9df7a031795941e17b9659e353db6..fa01fa93a2f7ae94602dd12d4b1254d4ace2a175 100644 --- a/services/wifi_standard/wifi_framework/wifi_manage/wifi_p2p_stub.cpp +++ b/wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_p2p_stub.cpp @@ -1,5 +1,5 @@ /* - * Copyright (C) 2021 Huawei Device Co., Ltd. + * Copyright (C) 2021-2022 Huawei Device Co., Ltd. * 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 @@ -44,12 +44,12 @@ void WifiP2pStub::InitHandleMap() handleFuncMap[WIFI_SVR_CMD_P2P_DELETE_LOCAL_SERVICES] = &WifiP2pStub::OnDeleteLocalP2pService; handleFuncMap[WIFI_SVR_CMD_P2P_START_LISTEN] = &WifiP2pStub::OnStartP2pListen; handleFuncMap[WIFI_SVR_CMD_P2P_STOP_LISTEN] = &WifiP2pStub::OnStopP2pListen; - handleFuncMap[WIFI_SVR_CMD_P2P_FORM_GROUP] = &WifiP2pStub::OnFormGroup; + handleFuncMap[WIFI_SVR_CMD_P2P_CREATE_GROUP] = &WifiP2pStub::OnCreateGroup; handleFuncMap[WIFI_SVR_CMD_P2P_REMOVE_GROUP] = &WifiP2pStub::OnRemoveGroup; handleFuncMap[WIFI_SVR_CMD_P2P_DELETE_GROUP] = &WifiP2pStub::OnDeleteGroup; handleFuncMap[WIFI_SVR_CMD_P2P_CONNECT] = &WifiP2pStub::OnP2pConnect; - handleFuncMap[WIFI_SVR_CMD_P2P_DISCONNECT] = &WifiP2pStub::OnP2pDisConnect; - handleFuncMap[WIFI_SVR_CMD_P2P_QUERY_INFO] = &WifiP2pStub::OnQueryP2pInfo; + handleFuncMap[WIFI_SVR_CMD_P2P_CANCEL_CONNECT] = &WifiP2pStub::OnP2pCancelConnect; + handleFuncMap[WIFI_SVR_CMD_P2P_QUERY_INFO] = &WifiP2pStub::OnQueryP2pLinkedInfo; handleFuncMap[WIFI_SVR_CMD_P2P_GET_CURRENT_GROUP] = &WifiP2pStub::OnGetCurrentGroup; handleFuncMap[WIFI_SVR_CMD_P2P_GET_ENABLE_STATUS] = &WifiP2pStub::OnGetP2pEnableStatus; handleFuncMap[WIFI_SVR_CMD_P2P_GET_DISCOVER_STATUS] = &WifiP2pStub::OnGetP2pDiscoverStatus; @@ -61,11 +61,30 @@ void WifiP2pStub::InitHandleMap() handleFuncMap[WIFI_SVR_CMD_GET_SUPPORTED_FEATURES] = &WifiP2pStub::OnGetSupportedFeatures; handleFuncMap[WIFI_SVR_CMD_P2P_SET_DEVICE_NAME] = &WifiP2pStub::OnSetP2pDeviceName; handleFuncMap[WIFI_SVR_CMD_P2P_SET_WFD_INFO] = &WifiP2pStub::OnSetP2pWfdInfo; + handleFuncMap[WIFI_SVR_CMD_P2P_HID2D_APPLY_IP] = &WifiP2pStub::OnHid2dRequestGcIp; + handleFuncMap[WIFI_SVR_CMD_P2P_HID2D_SHARED_LINK_INCREASE] = &WifiP2pStub::OnHid2dSharedlinkIncrease; + handleFuncMap[WIFI_SVR_CMD_P2P_HID2D_SHARED_LINK_DECREASE] = &WifiP2pStub::OnHid2dSharedlinkDecrease; + handleFuncMap[WIFI_SVR_CMD_P2P_HID2D_CREATE_GROUP] = &WifiP2pStub::OnHid2dCreateGroup; + handleFuncMap[WIFI_SVR_CMD_P2P_HID2D_REMOVE_GC_GROUP] = &WifiP2pStub::OnHid2dRemoveGcGroup; + handleFuncMap[WIFI_SVR_CMD_P2P_HID2D_CONNECT] = &WifiP2pStub::OnHid2dConnect; + handleFuncMap[WIFI_SVR_CMD_P2P_HID2D_CONFIG_IP] = &WifiP2pStub::OnHid2dConfigIPAddr; + handleFuncMap[WIFI_SVR_CMD_P2P_HID2D_RELEASE_IP] = &WifiP2pStub::OnHid2dReleaseIPAddr; + handleFuncMap[WIFI_SVR_CMD_GET_P2P_RECOMMENDED_CHANNEL] = &WifiP2pStub::OnHid2dGetRecommendChannel; + handleFuncMap[WIFI_SVR_CMD_GET_5G_CHANNEL_LIST] = &WifiP2pStub::OnHid2dGetChannelListFor5G; + handleFuncMap[WIFI_SVR_CMD_GET_SELF_WIFI_CFG] = &WifiP2pStub::OnHid2dGetSelfWifiCfgInfo; + handleFuncMap[WIFI_SVR_CMD_SET_PEER_WIFI_CFG] = &WifiP2pStub::OnHid2dSetPeerWifiCfgInfo; + handleFuncMap[WIFI_SVR_CMD_P2P_QUERY_LOCAL_DEVICE] = &WifiP2pStub::OnQueryP2pLocalDevice; + handleFuncMap[WIFI_SVR_CMD_SET_UPPER_SCENE] = &WifiP2pStub::OnHid2dSetUpperScene; return; } int WifiP2pStub::OnRemoteRequest(uint32_t code, MessageParcel &data, MessageParcel &reply, MessageOption &option) { + if (data.ReadInterfaceToken() != GetDescriptor()) { + WIFI_LOGE("P2p stub token verification error: %{public}d", code); + return WIFI_OPT_FAILED; + } + int exception = data.ReadInt32(); if (exception) { return WIFI_OPT_FAILED; @@ -142,7 +161,11 @@ void WifiP2pStub::OnRequestService(uint32_t code, MessageParcel &data, MessagePa WIFI_LOGD("run %{public}s code %{public}u, datasize %{public}zu", __func__, code, data.GetRawDataSize()); WifiP2pDevice device; WifiP2pServiceRequest request; - ReadWifiP2pServiceRequest(data, device, request); + if (!ReadWifiP2pServiceRequest(data, device, request)) { + reply.WriteInt32(0); + reply.WriteInt32(WIFI_OPT_INVALID_PARAM); + return; + } ErrCode ret = RequestService(device, request); reply.WriteInt32(0); reply.WriteInt32(ret); @@ -153,7 +176,11 @@ void WifiP2pStub::OnPutLocalP2pService(uint32_t code, MessageParcel &data, Messa { WIFI_LOGD("run %{public}s code %{public}u, datasize %{public}zu", __func__, code, data.GetRawDataSize()); WifiP2pServiceInfo config; - ReadWifiP2pServiceInfo(data, config); + if (!ReadWifiP2pServiceInfo(data, config)) { + reply.WriteInt32(0); + reply.WriteInt32(WIFI_OPT_INVALID_PARAM); + return; + } ErrCode ret = PutLocalP2pService(config); reply.WriteInt32(0); reply.WriteInt32(ret); @@ -165,7 +192,11 @@ void WifiP2pStub::OnDeleteLocalP2pService( { WIFI_LOGD("run %{public}s code %{public}u, datasize %{public}zu", __func__, code, data.GetRawDataSize()); WifiP2pServiceInfo config; - ReadWifiP2pServiceInfo(data, config); + if (!ReadWifiP2pServiceInfo(data, config)) { + reply.WriteInt32(0); + reply.WriteInt32(WIFI_OPT_INVALID_PARAM); + return; + } ErrCode ret = DeleteLocalP2pService(config); reply.WriteInt32(0); reply.WriteInt32(ret); @@ -192,12 +223,12 @@ void WifiP2pStub::OnStopP2pListen(uint32_t code, MessageParcel &data, MessagePar return; } -void WifiP2pStub::OnFormGroup(uint32_t code, MessageParcel &data, MessageParcel &reply, MessageOption &option) +void WifiP2pStub::OnCreateGroup(uint32_t code, MessageParcel &data, MessageParcel &reply, MessageOption &option) { WIFI_LOGD("run %{public}s code %{public}u, datasize %{public}zu", __func__, code, data.GetRawDataSize()); WifiP2pConfig config; ReadWifiP2pConfigData(data, config); - ErrCode ret = FormGroup(config); + ErrCode ret = CreateGroup(config); reply.WriteInt32(0); reply.WriteInt32(ret); return; @@ -216,7 +247,11 @@ void WifiP2pStub::OnDeleteGroup(uint32_t code, MessageParcel &data, MessageParce { WIFI_LOGD("run %{public}s code %{public}u, datasize %{public}zu", __func__, code, data.GetRawDataSize()); WifiP2pGroupInfo config; - ReadWifiP2pGroupData(data, config); + if (!ReadWifiP2pGroupData(data, config)) { + reply.WriteInt32(0); + reply.WriteInt32(WIFI_OPT_INVALID_PARAM); + return; + } ErrCode ret = DeleteGroup(config); reply.WriteInt32(0); reply.WriteInt32(ret); @@ -235,20 +270,20 @@ void WifiP2pStub::OnP2pConnect(uint32_t code, MessageParcel &data, MessageParcel return; } -void WifiP2pStub::OnP2pDisConnect(uint32_t code, MessageParcel &data, MessageParcel &reply, MessageOption &option) +void WifiP2pStub::OnP2pCancelConnect(uint32_t code, MessageParcel &data, MessageParcel &reply, MessageOption &option) { WIFI_LOGD("run %{public}s code %{public}u, datasize %{public}zu", __func__, code, data.GetRawDataSize()); - ErrCode ret = P2pDisConnect(); + ErrCode ret = P2pCancelConnect(); reply.WriteInt32(0); reply.WriteInt32(ret); return; } -void WifiP2pStub::OnQueryP2pInfo(uint32_t code, MessageParcel &data, MessageParcel &reply, MessageOption &option) +void WifiP2pStub::OnQueryP2pLinkedInfo(uint32_t code, MessageParcel &data, MessageParcel &reply, MessageOption &option) { WIFI_LOGD("run %{public}s code %{public}u, datasize %{public}zu", __func__, code, data.GetRawDataSize()); - WifiP2pInfo config; - ErrCode ret = QueryP2pInfo(config); + WifiP2pLinkedInfo config; + ErrCode ret = QueryP2pLinkedInfo(config); reply.WriteInt32(0); reply.WriteInt32(ret); @@ -318,22 +353,34 @@ void WifiP2pStub::OnGetP2pConnectedStatus( void WifiP2pStub::OnQueryP2pDevices(uint32_t code, MessageParcel &data, MessageParcel &reply, MessageOption &option) { WIFI_LOGD("run %{public}s code %{public}u, datasize %{public}zu", __func__, code, data.GetRawDataSize()); - std::vector devives; - ErrCode ret = QueryP2pDevices(devives); + std::vector devices; + ErrCode ret = QueryP2pDevices(devices); reply.WriteInt32(0); reply.WriteInt32(ret); - if (ret == WIFI_OPT_SUCCESS) { - int size = devives.size(); + int size = devices.size(); reply.WriteInt32(size); for (int i = 0; i < size; ++i) { - WriteWifiP2pDeviceData(reply, devives[i]); + WriteWifiP2pDeviceData(reply, devices[i]); } } return; } +void WifiP2pStub::OnQueryP2pLocalDevice(uint32_t code, MessageParcel &data, MessageParcel &reply, MessageOption &option) +{ + WIFI_LOGI("run %{public}s code %{public}u, datasize %{public}zu", __func__, code, data.GetRawDataSize()); + WifiP2pDevice device; + ErrCode ret = QueryP2pLocalDevice(device); + reply.WriteInt32(0); + reply.WriteInt32(ret); + if (ret == WIFI_OPT_SUCCESS) { + WriteWifiP2pDeviceData(reply, device); + } + return; +} + void WifiP2pStub::OnQueryP2pGroups(uint32_t code, MessageParcel &data, MessageParcel &reply, MessageOption &option) { WIFI_LOGD("run %{public}s code %{public}u, datasize %{public}zu", __func__, code, data.GetRawDataSize()); @@ -371,34 +418,42 @@ void WifiP2pStub::OnQueryP2pServices(uint32_t code, MessageParcel &data, Message return; } -void WifiP2pStub::ReadWifiP2pServiceInfo(MessageParcel &data, WifiP2pServiceInfo &info) +bool WifiP2pStub::ReadWifiP2pServiceInfo(MessageParcel &data, WifiP2pServiceInfo &info) { + constexpr int MAX_QUERY_SIZE = 256; info.SetServiceName(data.ReadCString()); info.SetDeviceAddress(data.ReadCString()); info.SetServicerProtocolType(static_cast(data.ReadInt32())); std::vector queryList; int size = data.ReadInt32(); + if (size > MAX_QUERY_SIZE) { + return false; + } for (int i = 0; i < size; i++) { std::string str = data.ReadCString(); queryList.push_back(str); } info.SetQueryList(queryList); - return; + return true; } -void WifiP2pStub::ReadWifiP2pServiceRequest(MessageParcel &data, WifiP2pDevice &device, WifiP2pServiceRequest &request) +bool WifiP2pStub::ReadWifiP2pServiceRequest(MessageParcel &data, WifiP2pDevice &device, WifiP2pServiceRequest &request) { + constexpr int MAX_QUERY_SIZE = 256; ReadWifiP2pDeviceData(data, device); request.SetProtocolType(static_cast(data.ReadInt32())); request.SetTransactionId(data.ReadInt32()); int size = data.ReadInt32(); + if (size > MAX_QUERY_SIZE) { + return false; + } std::vector query; for (int i = 0; i < size; i++) { unsigned char chr = data.ReadInt8(); query.push_back(chr); } request.SetQuery(query); - return; + return true; } void WifiP2pStub::WriteWifiP2pServiceInfo(MessageParcel &reply, const WifiP2pServiceInfo &info) @@ -448,8 +503,9 @@ void WifiP2pStub::WriteWifiP2pDeviceData(MessageParcel &reply, const WifiP2pDevi reply.WriteInt32(device.GetGroupCapabilitys()); } -void WifiP2pStub::ReadWifiP2pGroupData(MessageParcel &data, WifiP2pGroupInfo &info) +bool WifiP2pStub::ReadWifiP2pGroupData(MessageParcel &data, WifiP2pGroupInfo &info) { + constexpr int MAX_DEV_SIZE = 256; info.SetIsGroupOwner(data.ReadBool()); WifiP2pDevice device; ReadWifiP2pDeviceData(data, device); @@ -463,11 +519,15 @@ void WifiP2pStub::ReadWifiP2pGroupData(MessageParcel &data, WifiP2pGroupInfo &in info.SetNetworkId(data.ReadInt32()); info.SetGoIpAddress(data.ReadCString()); int size = data.ReadInt32(); + if (size > MAX_DEV_SIZE) { + return false; + } for (auto it = 0; it < size; ++it) { WifiP2pDevice cliDev; ReadWifiP2pDeviceData(data, cliDev); info.AddClientDevice(cliDev); } + return true; } void WifiP2pStub::WriteWifiP2pGroupData(MessageParcel &reply, const WifiP2pGroupInfo &info) @@ -493,15 +553,10 @@ void WifiP2pStub::ReadWifiP2pConfigData(MessageParcel &data, WifiP2pConfig &conf { config.SetDeviceAddress(data.ReadCString()); config.SetPassphrase(data.ReadCString()); - config.SetNetworkName(data.ReadCString()); + config.SetGroupName(data.ReadCString()); config.SetGoBand(static_cast(data.ReadInt32())); config.SetNetId(data.ReadInt32()); config.SetGroupOwnerIntent(data.ReadInt32()); - WpsInfo wpsInfo; - wpsInfo.SetWpsMethod(static_cast(data.ReadInt32())); - wpsInfo.SetBssid(data.ReadCString()); - wpsInfo.SetPin(data.ReadCString()); - config.SetWpsInfo(wpsInfo); } sptr WifiP2pStub::GetCallback() const @@ -516,14 +571,14 @@ void WifiP2pStub::OnRegisterCallBack(uint32_t code, MessageParcel &data, Message do { sptr remote = data.ReadRemoteObject(); if (remote == nullptr) { - WIFI_LOGD("Failed to readRemoteObject!"); + WIFI_LOGE("Failed to readRemoteObject!"); break; } callback_ = iface_cast(remote); if (callback_ == nullptr) { callback_ = new (std::nothrow) WifiP2pCallbackProxy(remote); - WIFI_LOGD("create new `WifiP2pCallbackProxy`!"); + WIFI_LOGI("create new `WifiP2pCallbackProxy`!"); } if (mSingleCallback) { @@ -540,6 +595,7 @@ void WifiP2pStub::OnRegisterCallBack(uint32_t code, MessageParcel &data, Message } ret = WIFI_OPT_SUCCESS; } + MonitorCfgChange(); } while (0); reply.WriteInt32(0); @@ -562,6 +618,7 @@ void WifiP2pStub::OnGetSupportedFeatures( return; } + void WifiP2pStub::OnSetP2pDeviceName(uint32_t code, MessageParcel &data, MessageParcel &reply, MessageOption &option) { WIFI_LOGD("run %{public}s code %{public}u, datasize %{public}zu", __func__, code, data.GetRawDataSize()); @@ -572,6 +629,7 @@ void WifiP2pStub::OnSetP2pDeviceName(uint32_t code, MessageParcel &data, Message return; } + void WifiP2pStub::OnSetP2pWfdInfo(uint32_t code, MessageParcel &data, MessageParcel &reply, MessageOption &option) { WIFI_LOGD("run %{public}s code %{public}u, datasize %{public}zu", __func__, code, data.GetRawDataSize()); @@ -584,9 +642,210 @@ void WifiP2pStub::OnSetP2pWfdInfo(uint32_t code, MessageParcel &data, MessagePar int ret = SetP2pWfdInfo(wfdInfo); reply.WriteInt32(0); reply.WriteInt32(ret); - return; } + +void WifiP2pStub::OnHid2dRequestGcIp(uint32_t code, MessageParcel &data, + MessageParcel &reply, MessageOption &option) +{ + WIFI_LOGD("run %{public}s code %{public}u, datasize %{public}zu", __func__, code, data.GetRawDataSize()); + + std::string gcMac = data.ReadCString(); + std::string ipAddr; + int ret = Hid2dRequestGcIp(gcMac, ipAddr); + reply.WriteInt32(0); + reply.WriteInt32(ret); + if (ret == WIFI_OPT_SUCCESS) { + reply.WriteCString(ipAddr.c_str()); + } +} + +void WifiP2pStub::OnHid2dSharedlinkIncrease(uint32_t code, MessageParcel &data, + MessageParcel &reply, MessageOption &option) +{ + WIFI_LOGD("run %{public}s code %{public}u, datasize %{public}zu", __func__, code, data.GetRawDataSize()); + + int ret = Hid2dSharedlinkIncrease(); + reply.WriteInt32(0); + reply.WriteInt32(ret); +} + +void WifiP2pStub::OnHid2dSharedlinkDecrease(uint32_t code, MessageParcel &data, + MessageParcel &reply, MessageOption &option) +{ + WIFI_LOGD("run %{public}s code %{public}u, datasize %{public}zu", __func__, code, data.GetRawDataSize()); + int ret = Hid2dSharedlinkDecrease(); + reply.WriteInt32(0); + reply.WriteInt32(ret); +} + +void WifiP2pStub::OnHid2dCreateGroup(uint32_t code, MessageParcel &data, + MessageParcel &reply, MessageOption &option) +{ + WIFI_LOGD("run %{public}s code %{public}u, datasize %{public}zu", __func__, code, data.GetRawDataSize()); + + int frequency = data.ReadInt32(); + int type = data.ReadInt32(); + int ret = Hid2dCreateGroup(frequency, FreqType(type)); + reply.WriteInt32(0); + reply.WriteInt32(ret); +} + +void WifiP2pStub::OnHid2dRemoveGcGroup(uint32_t code, MessageParcel &data, + MessageParcel &reply, MessageOption &option) +{ + WIFI_LOGD("run %{public}s code %{public}u, datasize %{public}zu", __func__, code, data.GetRawDataSize()); + + std::string gcIfName = data.ReadCString(); + int ret = Hid2dRemoveGcGroup(gcIfName); + reply.WriteInt32(0); + reply.WriteInt32(ret); +} + +void WifiP2pStub::OnHid2dConnect(uint32_t code, MessageParcel &data, + MessageParcel &reply, MessageOption &option) +{ + WIFI_LOGD("run %{public}s code %{public}u, datasize %{public}zu", __func__, code, data.GetRawDataSize()); + + Hid2dConnectConfig config; + config.SetSsid(data.ReadCString()); + config.SetBssid(data.ReadCString()); + config.SetPreSharedKey(data.ReadCString()); + config.SetFrequency(data.ReadInt32()); + config.SetDhcpMode(DhcpMode(data.ReadInt32())); + + int ret = Hid2dConnect(config); + reply.WriteInt32(0); + reply.WriteInt32(ret); +} + +void WifiP2pStub::OnHid2dConfigIPAddr(uint32_t code, MessageParcel &data, + MessageParcel &reply, MessageOption &option) +{ + WIFI_LOGD("run %{public}s code %{public}u, datasize %{public}zu", __func__, code, data.GetRawDataSize()); + + IpAddrInfo ipInfo; + std::string ifName = data.ReadCString(); + ipInfo.ip = data.ReadCString(); + ipInfo.gateway = data.ReadCString(); + ipInfo.netmask = data.ReadCString(); + int ret = Hid2dConfigIPAddr(ifName, ipInfo); + reply.WriteInt32(0); + reply.WriteInt32(ret); +} + +void WifiP2pStub::OnHid2dReleaseIPAddr(uint32_t code, MessageParcel &data, + MessageParcel &reply, MessageOption &option) +{ + WIFI_LOGD("run %{public}s code %{public}u, datasize %{public}zu", __func__, code, data.GetRawDataSize()); + + std::string ifName = data.ReadCString(); + int ret = Hid2dReleaseIPAddr(ifName); + reply.WriteInt32(0); + reply.WriteInt32(ret); +} + +void WifiP2pStub::OnHid2dGetRecommendChannel( + uint32_t code, MessageParcel &data, MessageParcel &reply, MessageOption &option) +{ + WIFI_LOGD("run %{public}s code %{public}u, datasize %{public}zu", __func__, code, data.GetRawDataSize()); + RecommendChannelRequest request; + RecommendChannelResponse response; + request.remoteIfName = data.ReadCString(); + request.remoteIfMode = data.ReadInt32(); + request.localIfName = data.ReadCString(); + request.localIfMode = data.ReadInt32(); + request.prefBand = data.ReadInt32(); + request.prefBandwidth = PreferBandwidth(data.ReadInt32()); + ErrCode ret = Hid2dGetRecommendChannel(request, response); + reply.WriteInt32(0); + reply.WriteInt32(ret); + if (ret == WIFI_OPT_SUCCESS) { + reply.WriteInt32(static_cast(response.status)); + reply.WriteInt32(response.index); + reply.WriteInt32(response.centerFreq); + reply.WriteInt32(response.centerFreq1); + reply.WriteInt32(response.centerFreq2); + reply.WriteInt32(response.bandwidth); + } +} + +void WifiP2pStub::OnHid2dGetChannelListFor5G( + uint32_t code, MessageParcel &data, MessageParcel &reply, MessageOption &option) +{ + WIFI_LOGD("run %{public}s code %{public}u, datasize %{public}zu", __func__, code, data.GetRawDataSize()); + + std::vector vecChannelList; + ErrCode ret = Hid2dGetChannelListFor5G(vecChannelList); + reply.WriteInt32(0); + reply.WriteInt32(ret); + if (ret == WIFI_OPT_SUCCESS) { + reply.WriteInt32((int)vecChannelList.size()); + for (auto& channel : vecChannelList) { + reply.WriteInt32(channel); + } + } +} + +void WifiP2pStub::OnHid2dGetSelfWifiCfgInfo( + uint32_t code, MessageParcel &data, MessageParcel &reply, MessageOption &option) +{ + WIFI_LOGD("run %{public}s code %{public}u, datasize %{public}zu", __func__, code, data.GetRawDataSize()); + + int cfgType = data.ReadInt32(); + int len = 0; + char cfgData[CFG_DATA_MAX_BYTES]; + if (memset_s(cfgData, CFG_DATA_MAX_BYTES, 0, CFG_DATA_MAX_BYTES) != EOK) { + WIFI_LOGE("`%{public}s` memset_s failed!", __func__); + } + ErrCode ret = Hid2dGetSelfWifiCfgInfo(SelfCfgType(cfgType), cfgData, &len); + reply.WriteInt32(0); + reply.WriteInt32(ret); + reply.WriteInt32(len); + if (ret == WIFI_OPT_SUCCESS && len > 0) { + reply.WriteBuffer(cfgData, len); + } +} + +void WifiP2pStub::OnHid2dSetPeerWifiCfgInfo( + uint32_t code, MessageParcel &data, MessageParcel &reply, MessageOption &option) +{ + WIFI_LOGD("run %{public}s code %{public}u, datasize %{public}zu", __func__, code, data.GetRawDataSize()); + + char cfgData[CFG_DATA_MAX_BYTES]; + if (memset_s(cfgData, CFG_DATA_MAX_BYTES, 0, CFG_DATA_MAX_BYTES) != EOK) { + WIFI_LOGE("`%{public}s` memset_s failed!", __func__); + } + int cfgType = data.ReadInt32(); + int len = data.ReadInt32(); + const char *dataBuffer = (const char *)data.ReadBuffer(len); + if (memcpy_s(cfgData, CFG_DATA_MAX_BYTES, dataBuffer, len) != EOK) { + WIFI_LOGE("`%{public}s` memcpy_s failed!", __func__); + reply.WriteInt32(0); + reply.WriteInt32(WIFI_OPT_FAILED); + return; + } + ErrCode ret = Hid2dSetPeerWifiCfgInfo(PeerCfgType(cfgType), cfgData, len); + reply.WriteInt32(0); + reply.WriteInt32(ret); +} + +void WifiP2pStub::OnHid2dSetUpperScene( + uint32_t code, MessageParcel &data, MessageParcel &reply, MessageOption &option) +{ + WIFI_LOGD("run %{public}s code %{public}u, datasize %{public}zu", __func__, code, data.GetRawDataSize()); + + std::string ifName = data.ReadCString(); + Hid2dUpperScene scene; + scene.mac = data.ReadCString(); + scene.scene = data.ReadUint32(); + scene.fps = data.ReadInt32(); + scene.bw = data.ReadUint32(); + ErrCode ret = Hid2dSetUpperScene(ifName, scene); + reply.WriteInt32(0); + reply.WriteInt32(ret); +} + bool WifiP2pStub::IsSingleCallback() const { return mSingleCallback; diff --git a/services/wifi_standard/wifi_framework/wifi_manage/wifi_p2p_stub.h b/wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_p2p_stub.h similarity index 69% rename from services/wifi_standard/wifi_framework/wifi_manage/wifi_p2p_stub.h rename to wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_p2p_stub.h index 13c63fcaa1e3327898b8fd81516ac94ab923067c..5001dd10e615e49ebec7e43cf5707decc868a7a4 100644 --- a/services/wifi_standard/wifi_framework/wifi_manage/wifi_p2p_stub.h +++ b/wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_p2p_stub.h @@ -1,5 +1,5 @@ /* - * Copyright (C) 2021 Huawei Device Co., Ltd. + * Copyright (C) 2021-2022 Huawei Device Co., Ltd. * 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 @@ -38,6 +38,9 @@ public: bool IsSingleCallback() const; void SetSingleCallback(const bool isSingleCallback); + + virtual ErrCode MonitorCfgChange(void) = 0; + protected: sptr GetCallback() const; @@ -54,12 +57,12 @@ private: void OnDeleteLocalP2pService(uint32_t code, MessageParcel &data, MessageParcel &reply, MessageOption &option); void OnStartP2pListen(uint32_t code, MessageParcel &data, MessageParcel &reply, MessageOption &option); void OnStopP2pListen(uint32_t code, MessageParcel &data, MessageParcel &reply, MessageOption &option); - void OnFormGroup(uint32_t code, MessageParcel &data, MessageParcel &reply, MessageOption &option); + void OnCreateGroup(uint32_t code, MessageParcel &data, MessageParcel &reply, MessageOption &option); void OnRemoveGroup(uint32_t code, MessageParcel &data, MessageParcel &reply, MessageOption &option); void OnDeleteGroup(uint32_t code, MessageParcel &data, MessageParcel &reply, MessageOption &option); void OnP2pConnect(uint32_t code, MessageParcel &data, MessageParcel &reply, MessageOption &option); - void OnP2pDisConnect(uint32_t code, MessageParcel &data, MessageParcel &reply, MessageOption &option); - void OnQueryP2pInfo(uint32_t code, MessageParcel &data, MessageParcel &reply, MessageOption &option); + void OnP2pCancelConnect(uint32_t code, MessageParcel &data, MessageParcel &reply, MessageOption &option); + void OnQueryP2pLinkedInfo(uint32_t code, MessageParcel &data, MessageParcel &reply, MessageOption &option); void OnGetCurrentGroup(uint32_t code, MessageParcel &data, MessageParcel &reply, MessageOption &option); void OnGetP2pEnableStatus(uint32_t code, MessageParcel &data, MessageParcel &reply, MessageOption &option); void OnGetP2pDiscoverStatus(uint32_t code, MessageParcel &data, MessageParcel &reply, MessageOption &option); @@ -71,14 +74,28 @@ private: void OnGetSupportedFeatures(uint32_t code, MessageParcel &data, MessageParcel &reply, MessageOption &option); void OnSetP2pDeviceName(uint32_t code, MessageParcel &data, MessageParcel &reply, MessageOption &option); void OnSetP2pWfdInfo(uint32_t code, MessageParcel &data, MessageParcel &reply, MessageOption &option); - void ReadWifiP2pServiceInfo(MessageParcel &data, WifiP2pServiceInfo &info); - void ReadWifiP2pServiceRequest(MessageParcel &data, WifiP2pDevice &device, WifiP2pServiceRequest &request); + void OnHid2dRequestGcIp(uint32_t code, MessageParcel &data, MessageParcel &reply, MessageOption &option); + void OnHid2dSharedlinkIncrease(uint32_t code, MessageParcel &data, MessageParcel &reply, MessageOption &option); + void OnHid2dSharedlinkDecrease(uint32_t code, MessageParcel &data, MessageParcel &reply, MessageOption &option); + void OnHid2dCreateGroup(uint32_t code, MessageParcel &data, MessageParcel &reply, MessageOption &option); + void OnHid2dRemoveGcGroup(uint32_t code, MessageParcel &data, MessageParcel &reply, MessageOption &option); + void OnHid2dConnect(uint32_t code, MessageParcel &data, MessageParcel &reply, MessageOption &option); + void OnHid2dConfigIPAddr(uint32_t code, MessageParcel &data, MessageParcel &reply, MessageOption &option); + void OnHid2dReleaseIPAddr(uint32_t code, MessageParcel &data, MessageParcel &reply, MessageOption &option); + void OnHid2dGetRecommendChannel(uint32_t code, MessageParcel &data, MessageParcel &reply, MessageOption &option); + void OnHid2dGetChannelListFor5G(uint32_t code, MessageParcel &data, MessageParcel &reply, MessageOption &option); + void OnHid2dGetSelfWifiCfgInfo(uint32_t code, MessageParcel &data, MessageParcel &reply, MessageOption &option); + void OnHid2dSetPeerWifiCfgInfo(uint32_t code, MessageParcel &data, MessageParcel &reply, MessageOption &option); + void OnHid2dSetUpperScene(uint32_t code, MessageParcel &data, MessageParcel &reply, MessageOption &option); + bool ReadWifiP2pServiceInfo(MessageParcel &data, WifiP2pServiceInfo &info); + bool ReadWifiP2pServiceRequest(MessageParcel &data, WifiP2pDevice &device, WifiP2pServiceRequest &request); void WriteWifiP2pServiceInfo(MessageParcel &reply, const WifiP2pServiceInfo &info); void ReadWifiP2pDeviceData(MessageParcel &data, WifiP2pDevice &device); void WriteWifiP2pDeviceData(MessageParcel &reply, const WifiP2pDevice &device); - void ReadWifiP2pGroupData(MessageParcel &data, WifiP2pGroupInfo &info); + bool ReadWifiP2pGroupData(MessageParcel &data, WifiP2pGroupInfo &info); void WriteWifiP2pGroupData(MessageParcel &reply, const WifiP2pGroupInfo &info); void ReadWifiP2pConfigData(MessageParcel &data, WifiP2pConfig &config); + void OnQueryP2pLocalDevice(uint32_t code, MessageParcel &data, MessageParcel &reply, MessageOption &option); private: HandleFuncMap handleFuncMap; diff --git a/interfaces/innerkits/native_cpp/napi/wifi_napi_utils.h b/wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_protect.cpp old mode 100755 new mode 100644 similarity index 35% rename from interfaces/innerkits/native_cpp/napi/wifi_napi_utils.h rename to wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_protect.cpp index b9eb6395de094f1634afe096cec1053c9330e2ac..e7531402c7428b64b42efcb7ee999bd7131b0fcd --- a/interfaces/innerkits/native_cpp/napi/wifi_napi_utils.h +++ b/wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_protect.cpp @@ -1,47 +1,80 @@ -/* - * Copyright (C) 2021 Huawei Device Co., Ltd. - * 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 WIFI_NAPI_UTILS_H_ -#define WIFI_NAPI_UTILS_H_ - -#include -#include "napi/native_api.h" -#include "napi/native_node_api.h" - -namespace OHOS { -namespace Wifi { -napi_value UndefinedNapiValue(const napi_env& env); -napi_value JsObjectToString(const napi_env& env, const napi_value& object, - const char* fieldStr, const int bufLen, std::string& fieldRef); -napi_value JsObjectToInt(const napi_env& env, const napi_value& object, const char* fieldStr, int& fieldRef); -napi_value JsObjectToBool(const napi_env& env, const napi_value& object, const char* fieldStr, bool& fieldRef); -void SetValueUtf8String(const napi_env& env, const char* fieldStr, const char* str, napi_value& result); -void SetValueInt32(const napi_env& env, const char* fieldStr, const int intValue, napi_value& result); -void SetValueInt64(const napi_env& env, const char* fieldStr, const int64_t intValue, napi_value& result); - -struct AsyncCallbackInfo { - napi_env env; - napi_async_work asyncWork; - napi_deferred deferred; - napi_ref callback[2] = { 0 }; - void *obj; - napi_value result; - bool isSuccess; -}; - -} // namespace Wifi -} // namespace OHOS - -#endif +/* + * Copyright (C) 2021 Huawei Device Co., Ltd. + * 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 "wifi_protect.h" + +namespace OHOS { +namespace Wifi { +WifiProtect::WifiProtect( + const WifiProtectType &protectType, const WifiProtectMode &protectMode, const std::string &name) + : mName(name), + mType(protectType), + mMode(protectMode), + mAcqTimestamp(0) +{} + +WifiProtect::WifiProtect(const std::string &name) + : mName(name), + mType(WifiProtectType::WIFI_PROTECT_COMMON), + mMode(WifiProtectMode::WIFI_PROTECT_FULL), + mAcqTimestamp(0) +{} + +WifiProtect::WifiProtect() + : mName(""), + mType(WifiProtectType::WIFI_PROTECT_COMMON), + mMode(WifiProtectMode::WIFI_PROTECT_FULL), + mAcqTimestamp(0) +{} + +WifiProtect::~WifiProtect() +{} + +void WifiProtect::SetProtectType(const WifiProtectType &protectType) +{ + mType = protectType; +} + +WifiProtectType WifiProtect::GetProtectType() const +{ + return mType; +} + +void WifiProtect::SetProtectMode(const WifiProtectMode &protectMode) +{ + mMode = protectMode; +} + +WifiProtectMode WifiProtect::GetProtectMode() const +{ + return mMode; +} + +void WifiProtect::SetName(const std::string &name) +{ + mName = name; +} + +std::string WifiProtect::GetName() const +{ + return mName; +} + +long WifiProtect::GetAcqTimestamp() const +{ + return mAcqTimestamp; +} +} // namespace Wifi +} // namespace OHOS \ No newline at end of file diff --git a/wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_protect.h b/wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_protect.h new file mode 100644 index 0000000000000000000000000000000000000000..d469dc4c3981985fd61dd5cd177fd88303f36f79 --- /dev/null +++ b/wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_protect.h @@ -0,0 +1,112 @@ +/* + * Copyright (C) 2021 Huawei Device Co., Ltd. + * 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 OHOS_WIFIPROTECT_H +#define OHOS_WIFIPROTECT_H + +#include +#include "wifi_msg.h" + +namespace OHOS { +namespace Wifi { +class WifiProtect { +public: + /** + * @Description Construct a new Wifi Protect object + * + * @param protectType - protect type + * @param protectMode - protect mode + * @param name - protect name, which is a unique identifier + */ + WifiProtect(const WifiProtectType &protectType, const WifiProtectMode &protectMode, const std::string &name); + + /** + * @Description Construct a new Wifi Full Protect object + * + * @param tag - protect name, which is a unique identifier + */ + explicit WifiProtect(const std::string &name); + + /** + * @Description Construct a new Default Wifi Protect object + * + */ + WifiProtect(); + + /** + * @Description Destroy the Wifi Protect object + * + */ + ~WifiProtect(); + + /** + * @Description Set the Tag object + * + * @param tag - protect name + */ + void SetName(const std::string &name); + + /** + * @Description Get the Tag object + * + * @return std::string - Wifi protect Tag + */ + std::string GetName() const; + + /** + * @Description Set the Protect Type object + * + * @param protectType - protect type + */ + void SetProtectType(const WifiProtectType &protectType); + + /** + * @Description Get the Protect Type object + * + * @return WifiProtectType - protect type + */ + WifiProtectType GetProtectType() const; + + /** + * @Description Set the Protect Mode object + * + * @param protectMode - protect mode + */ + void SetProtectMode(const WifiProtectMode &protectMode); + + /** + * @Description Get the Protect Mode object + * + * @return WifiProtectMode - protect mode + */ + WifiProtectMode GetProtectMode() const; + + /** + * @Description Get the Acq Timestamp + * + * @return long - timestamp + */ + long GetAcqTimestamp() const; + +private: + std::string mName; + /* not used: int mUid; */ + WifiProtectType mType; + WifiProtectMode mMode; + long mAcqTimestamp; +}; +} // namespace Wifi +} // namespace OHOS +#endif diff --git a/wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_protect_manager.cpp b/wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_protect_manager.cpp new file mode 100644 index 0000000000000000000000000000000000000000..1131c23dbd783136d3047b6f64f2dc9b451c4af5 --- /dev/null +++ b/wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_protect_manager.cpp @@ -0,0 +1,276 @@ +/* + * Copyright (C) 2021 Huawei Device Co., Ltd. + * 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 "wifi_protect_manager.h" +#include "wifi_log.h" +#include "wifi_chip_hal_interface.h" +#include "wifi_supplicant_hal_interface.h" + +#undef LOG_TAG +#define LOG_TAG "OHWIFI_MANAGER_LOCK_MANAGER" + +namespace OHOS { +namespace Wifi { +WifiProtectManager::WifiProtectManager() +{ + mWifiConnected = false; + mScreenOn = false; + mForceHiPerfMode = false; + mForceLowLatencyMode = false; + mCurrentOpMode = WifiProtectMode::WIFI_PROTECT_NO_HELD; + mFullHighPerfProtectsAcquired = 0; + mFullHighPerfProtectsReleased = 0; + mFullLowLatencyProtectsAcquired = 0; + mFullLowLatencyProtectsReleased = 0; + mWifiProtects.clear(); +} + +WifiProtectManager::~WifiProtectManager() +{} + +WifiProtectManager &WifiProtectManager::GetInstance() +{ + static WifiProtectManager instance; + return instance; +} + +bool WifiProtectManager::IsValidProtectMode(WifiProtectMode &protectMode) +{ + if (protectMode != WifiProtectMode::WIFI_PROTECT_FULL && protectMode != WifiProtectMode::WIFI_PROTECT_SCAN_ONLY && + protectMode != WifiProtectMode::WIFI_PROTECT_FULL_HIGH_PERF && + protectMode != WifiProtectMode::WIFI_PROTECT_FULL_LOW_LATENCY) { + return false; + } + + return true; +} + +WifiProtectMode WifiProtectManager::GetNearlyProtectMode() +{ + /* If Wifi Client is not connected, then all protects are not effective */ + if (!mWifiConnected) { + return WifiProtectMode::WIFI_PROTECT_NO_HELD; + } + + /* Check if mode is forced to hi-perf */ + if (mForceHiPerfMode) { + return WifiProtectMode::WIFI_PROTECT_FULL_HIGH_PERF; + } + + /* Check if mode is forced to low-latency */ + if (mForceLowLatencyMode) { + return WifiProtectMode::WIFI_PROTECT_FULL_LOW_LATENCY; + } + + if (mFullHighPerfProtectsAcquired > mFullHighPerfProtectsReleased) { + return WifiProtectMode::WIFI_PROTECT_FULL_HIGH_PERF; + } + + return WifiProtectMode::WIFI_PROTECT_NO_HELD; +} + +bool WifiProtectManager::InitWifiProtect(const WifiProtectType &protectType, const std::string &protectName) +{ + WifiProtect* pProtect = new WifiProtect(protectType, WifiProtectMode::WIFI_PROTECT_FULL, protectName); + mWifiProtects.push_back(pProtect); + return true; +} + +bool WifiProtectManager::GetWifiProtect(const WifiProtectMode &protectMode, const std::string name) +{ + bool isAlreadyExist = false; + + std::vector::iterator itor = mWifiProtects.begin(); + while (itor != mWifiProtects.end()) { + if ((*itor)->GetName() == name) { + LOGD("old name = %{public}s, and new Name = %{public}s", + (*itor)->GetName().c_str(), + (*itor)->GetName().c_str()); + isAlreadyExist = true; + break; + } + itor++; + } + + if (isAlreadyExist) { + LOGD("attempted to add a protect when already holding one"); + return false; + } + + WifiProtect *pProtect = new WifiProtect(name); + if (pProtect == nullptr) { + LOGE("Wifi protect pointer is null."); + return false; + } + pProtect->SetProtectMode(protectMode); + return AddProtect(pProtect); +} + +bool WifiProtectManager::ChangeToPerfMode(bool isEnabled) +{ + mForceHiPerfMode = isEnabled; + mForceLowLatencyMode = false; + if (!ChangeWifiPowerMode()) { + LOGE("Failed to force hi-perf mode, returning to normal mode"); + mForceHiPerfMode = false; + return false; + } + + return true; +} +void WifiProtectManager::HandleScreenStateChanged(bool screenOn) +{ + mScreenOn = screenOn; +} + +void WifiProtectManager::UpdateWifiClientConnected(bool isConnected) +{ + mWifiConnected = isConnected; +} + +bool WifiProtectManager::AddProtect(WifiProtect *pProtect) +{ + mWifiProtects.push_back(pProtect); + switch (pProtect->GetProtectMode()) { + case WifiProtectMode::WIFI_PROTECT_FULL_HIGH_PERF: + if (mWifiConnected) { + ++mFullHighPerfProtectsAcquired; + } + break; + case WifiProtectMode::WIFI_PROTECT_FULL_LOW_LATENCY: + ++mFullLowLatencyProtectsAcquired; + break; + default: + break; + } + + ChangeWifiPowerMode(); + LOGD("GetWifiProtect finished!"); + return true; +} + +bool WifiProtectManager::PutWifiProtect(const std::string &name) +{ + WifiProtect *pWifiProtect = RemoveProtect(name); + if (pWifiProtect == nullptr) { + /* attempting to release a protect that does not exist. */ + return false; + } + + switch (pWifiProtect->GetProtectMode()) { + case WifiProtectMode::WIFI_PROTECT_FULL_HIGH_PERF: + if (mWifiConnected) { + ++mFullHighPerfProtectsReleased; + } + break; + case WifiProtectMode::WIFI_PROTECT_FULL_LOW_LATENCY: + ++mFullLowLatencyProtectsReleased; + break; + default: + break; + } + + /* Recalculate the operating mode */ + ChangeWifiPowerMode(); + LOGD("PutWifiProtect finished!"); + + delete pWifiProtect; + pWifiProtect = nullptr; + return true; +} + +WifiProtect *WifiProtectManager::RemoveProtect(const std::string &name) +{ + WifiProtect *pProtect = nullptr; + std::vector::iterator itor = mWifiProtects.begin(); + while (itor != mWifiProtects.end()) { + if ((*itor)->GetName() == name) { + pProtect = *itor; + itor = mWifiProtects.erase(itor); + break; + } + itor++; + } + return pProtect; +} + +bool WifiProtectManager::ChangeWifiPowerMode() +{ + WifiProtectMode newProtectMode = GetNearlyProtectMode(); + if (newProtectMode == mCurrentOpMode) { + /* No action is needed */ + return true; + } + + /* Otherwise, we need to change current mode, first reset it to normal */ + switch (mCurrentOpMode) { + case WifiProtectMode::WIFI_PROTECT_FULL_HIGH_PERF: + if (!WifiSupplicantHalInterface::GetInstance().SetPowerSave(true)) { + LOGE("Failed to reset the OpMode from hi-perf to Normal"); + return false; + } + break; + case WifiProtectMode::WIFI_PROTECT_FULL_LOW_LATENCY: + + break; + case WifiProtectMode::WIFI_PROTECT_NO_HELD: + default: + /* No action */ + break; + } + + /* Set the current mode, before we attempt to set the new mode */ + mCurrentOpMode = WifiProtectMode::WIFI_PROTECT_NO_HELD; + + /* Now switch to the new opMode */ + switch (newProtectMode) { + case WifiProtectMode::WIFI_PROTECT_FULL_HIGH_PERF: + if (!WifiSupplicantHalInterface::GetInstance().SetPowerSave(false)) { + LOGE("Failed to set the OpMode to hi-perf"); + return false; + } + break; + case WifiProtectMode::WIFI_PROTECT_FULL_LOW_LATENCY: + if (!SetLowLatencyMode(true)) { + LOGE("Failed to set the OpMode to low-latency"); + return false; + } + break; + case WifiProtectMode::WIFI_PROTECT_NO_HELD: + /* No action */ + break; + default: + /* Invalid mode, don't change currentOpMode , and exit with error */ + LOGE("Invalid new opMode: %{public}d", (int)newProtectMode); + return false; + } + + /* Now set the mode to the new value */ + mCurrentOpMode = newProtectMode; + return true; +} + +bool WifiProtectManager::SetLowLatencyMode(bool enabled) +{ + /* Only set power save mode */ + if (!WifiSupplicantHalInterface::GetInstance().SetPowerSave(!enabled)) { + LOGE("Failed to set power save mode"); + return false; + } + + return true; +} +} // namespace Wifi +} // namespace OHOS \ No newline at end of file diff --git a/wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_protect_manager.h b/wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_protect_manager.h new file mode 100644 index 0000000000000000000000000000000000000000..ceb1894b4fe4194722e929713a486ee96cc3d2d9 --- /dev/null +++ b/wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_protect_manager.h @@ -0,0 +1,129 @@ +/* + * Copyright (C) 2021-2022 Huawei Device Co., Ltd. + * 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 OHOS_WIFI_PROTECT_MANAGER_H +#define OHOS_WIFI_PROTECT_MANAGER_H + +#include +#include "wifi_protect.h" +#include "wifi_msg.h" + +namespace OHOS { +namespace Wifi { +class WifiProtectManager { +public: + ~WifiProtectManager(); + static WifiProtectManager &GetInstance(); + + /** + * @Description Validate that the protect mode is valid + * + * @param protectMode - The protect mode to verify + * @return true - valid + * @return false - invalid + */ + static bool IsValidProtectMode(WifiProtectMode &protectMode); + + /** + * @Description Get the nearly protect type currently held by the WifiProtectManager + * + * @return WifiProtectMode - currently held protect + */ + WifiProtectMode GetNearlyProtectMode(); + + /** + * @Description Create a Wifi Protect. + * + * @param protectMode - representation of the Wifi Protect type + * @param protectName - represent the protect name + * @return true - create the protect success + * @return false - create protect failed + */ + bool InitWifiProtect(const WifiProtectType &protectType, const std::string &protectName); + + /** + * @Description Allowing a calling app to acquire a Wifi Protect in the supplied mode + * + * @param protectMode - representation of the Wifi Protect type + * @param name - represent the protect + * @return true - acquired the protect success + * @return false - acquired protect failed + */ + bool GetWifiProtect(const WifiProtectMode &protectMode, const std::string name); + + /** + * @Description Applications to release a WiFi Wake protect + * + * @param name - represent the protect + * @return true - put protect success + * @return false - put failed, the caller did not hold this protect + */ + bool PutWifiProtect(const std::string &name); + + /** + * @Description Set hi-perf mode protect state + * + * @param isEnabled - True to force hi-perf mode, false to leave it up to acquired wifiProtects + * @return true - success + * @return false - failed + */ + bool ChangeToPerfMode(bool isEnabled); + + /** + * @Description Handler for screen state (on/off) changes + * + * @param screenOn - screen on/off state + */ + void HandleScreenStateChanged(bool screenOn); + + /** + * @Description Handler for Wifi Client mode state changes + * + * @param isConnected - wifi client connect state + */ + void UpdateWifiClientConnected(bool isConnected); + + /** + * @Description set low latency mode + * + * @param enabled - true: enable low latency, false: disable low latency + * @return bool - operation result + */ + bool SetLowLatencyMode(bool enabled); + +private: + WifiProtectManager(); + bool AddProtect(WifiProtect *pProtect); + bool ReleaseProtect(const std::string &name); + WifiProtect *RemoveProtect(const std::string &name); + bool ChangeWifiPowerMode(); + +private: + std::vector mWifiProtects; + WifiProtectMode mCurrentOpMode; + int mFullHighPerfProtectsAcquired; + int mFullHighPerfProtectsReleased; + int mFullLowLatencyProtectsAcquired; + int mFullLowLatencyProtectsReleased; + /* Not used: long mCurrentSessionStartTimeMs; */ + bool mWifiConnected; + bool mScreenOn; + bool mForceHiPerfMode; + bool mForceLowLatencyMode; +}; +} // namespace Wifi +} // namespace OHOS + +#endif \ No newline at end of file diff --git a/wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_sa_service_lite.c b/wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_sa_service_lite.c new file mode 100644 index 0000000000000000000000000000000000000000..5a373194f9d404de4605064cdb09f04aa2861b78 --- /dev/null +++ b/wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_sa_service_lite.c @@ -0,0 +1,96 @@ +/* + * Copyright (C) 2022 Huawei Device Co., Ltd. + * 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 "iproxy_server.h" +#include "ohos_errno.h" +#include "ohos_init.h" +#include "samgr_lite.h" +#include "service.h" +#include "wifi_ipc_lite_adapter.h" +#include "wifi_log.h" + +static const int STACK_SIZE = 0x800; +static const int QUEUE_SIZE = 20; + +typedef struct WifiSaInterface { + INHERIT_SERVER_IPROXY; +} WifiSaInterface; + +typedef struct WifiSaService { + INHERIT_SERVICE; + INHERIT_IUNKNOWNENTRY(WifiSaInterface); + Identity identity; +} WifiSaService; + +static const char *GetName(Service *service) +{ + return WIFI_SERVICE_LITE; +} + +static BOOL Initialize(Service *service, Identity identity) +{ + if (service == NULL) { + return FALSE; + } + WifiSaService *wifiService = (WifiSaService *)service; + wifiService->identity = identity; + return TRUE; +} + +static BOOL MessageHandle(Service *service, Request *msg) +{ + return TRUE; +} + +static TaskConfig GetTaskConfig(Service *service) +{ + TaskConfig config = {LEVEL_HIGH, PRI_NORMAL, STACK_SIZE, QUEUE_SIZE, SINGLE_TASK}; + return config; +} + +static int Invoke(IServerProxy *proxy, int funcId, void *origin, IpcIo *req, IpcIo *reply) +{ + LOGI("[WifiSaServer] begin to call Invoke, funcId is %{public}d", funcId); + return EC_SUCCESS; +} + +static WifiSaService g_wifiSaService = { + .GetName = GetName, + .Initialize = Initialize, + .MessageHandle = MessageHandle, + .GetTaskConfig = GetTaskConfig, + SERVER_IPROXY_IMPL_BEGIN, + .Invoke = Invoke, + IPROXY_END, +}; + +static void Init(void) +{ + LOGI("[WifiSaServer] Init start."); + BOOL ret; + ret = SAMGR_GetInstance()->RegisterService((Service *)&g_wifiSaService); + if (ret == FALSE) { + LOGE("[WifiSaServer] register service fail."); + return; + } + ret = SAMGR_GetInstance()->RegisterDefaultFeatureApi(WIFI_SERVICE_LITE, GET_IUNKNOWN(g_wifiSaService)); + if (ret == FALSE) { + LOGE("[WifiSaServer] register default api fail."); + } +} +SYSEX_SERVICE_INIT(Init); \ No newline at end of file diff --git a/wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_scan/BUILD.gn b/wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_scan/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..4ffab92bddb85738f5a7c59aef564d3b7ee08fc0 --- /dev/null +++ b/wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_scan/BUILD.gn @@ -0,0 +1,117 @@ +# Copyright (C) 2021-2022 Huawei Device Co., Ltd. +# 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. + +if (defined(ohos_lite)) { + import("//build/lite/config/component/lite_component.gni") + import("//foundation/communication/wifi/wifi/wifi_lite.gni") +} else { + import("//build/ohos.gni") + import("//foundation/communication/wifi/wifi/wifi.gni") +} + +local_base_sources = [ + "../common/handler.cpp", + "../common/internal_message.cpp", + "../common/message_queue.cpp", + "../common/state.cpp", + "../common/state_machine.cpp", + "scan_interface.cpp", + "scan_monitor.cpp", + "scan_service.cpp", + "scan_state_machine.cpp", +] + +local_base_include_dirs = [ + "$WIFI_ROOT_DIR/frameworks/native/interfaces", + "$WIFI_ROOT_DIR/services/wifi_standard/ipc_framework/interface", + "$WIFI_ROOT_DIR/services/wifi_standard/ipc_framework/cRPC/include", + "$WIFI_ROOT_DIR/services/wifi_standard/wifi_framework/wifi_toolkit/include", + "$WIFI_ROOT_DIR/services/wifi_standard/wifi_framework/wifi_toolkit/config", + "$WIFI_ROOT_DIR/services/wifi_standard/wifi_framework/wifi_toolkit/log", + "$WIFI_ROOT_DIR/services/wifi_standard/wifi_framework/wifi_toolkit/utils", + "$WIFI_ROOT_DIR/services/wifi_standard/wifi_framework/wifi_toolkit/net_helper", + "$WIFI_ROOT_DIR/services/wifi_standard/wifi_framework/wifi_manage/common", + "$WIFI_ROOT_DIR/services/wifi_standard/wifi_framework/wifi_manage/wifi_scan", + "$WIFI_ROOT_DIR/services/wifi_standard/wifi_framework/wifi_manage/", + "$WIFI_ROOT_DIR/services/wifi_standard/wifi_framework/wifi_manage/idl_client", + "$WIFI_ROOT_DIR/services/wifi_standard/wifi_framework/wifi_manage/idl_client/idl_interface", + "$WIFI_ROOT_DIR/services/wifi_standard/wifi_framework/wifi_manage/wifi_sta/net_conf", + "$WIFI_ROOT_DIR/services/wifi_standard/wifi_framework/wifi_manage/wifi_sta", + "$WIFI_ROOT_DIR/services/wifi_standard/include", + "$WIFI_ROOT_DIR/utils/inc", +] + +if (defined(ohos_lite)) { + shared_library("wifi_scan_service") { + sources = local_base_sources + include_dirs = local_base_include_dirs + include_dirs += [ + "//base/hiviewdfx/hilog_lite/interfaces/native/innerkits", + "//third_party/bounds_checking_function/include", + ] + + deps = [ + "$WIFI_ROOT_DIR/services/wifi_standard/wifi_framework/wifi_manage:wifi_service_base", + "$WIFI_ROOT_DIR/services/wifi_standard/wifi_framework/wifi_manage/idl_client:wifi_idl_client", + "$WIFI_ROOT_DIR/services/wifi_standard/wifi_framework/wifi_toolkit:wifi_toolkit", + "$WIFI_ROOT_DIR/utils:wifi_utils", + "//base/hiviewdfx/hilog_lite/frameworks/featured:hilog_shared", + "//third_party/bounds_checking_function:libsec_shared", + ] + + defines = [ "OHOS_ARCH_LITE" ] + configs -= [ "//build/lite/config:language_cpp" ] + cflags_cc = [ + "-std=c++17", + "-fno-rtti", + ] + ldflags = [ + "-fPIC", + "-Wl,-E", + ] + } +} else { + ohos_shared_library("wifi_scan_service") { + install_enable = true + sources = local_base_sources + + include_dirs = local_base_include_dirs + include_dirs += [ + "//commonlibrary/c_utils/base/include", + "//base/hiviewdfx/hilog/interfaces/native/innerkits/include", + ] + + deps = [ + "$WIFI_ROOT_DIR/services/wifi_standard/wifi_framework/wifi_manage/idl_client:wifi_idl_client", + "$WIFI_ROOT_DIR/services/wifi_standard/wifi_framework/wifi_toolkit:wifi_toolkit", + "$WIFI_ROOT_DIR/utils:wifi_utils", + ] + + external_deps = [ + "c_utils:utils", + "hiviewdfx_hilog_native:libhilog", + ] + cflags_cc = [ + "-std=c++17", + "-fno-rtti", + ] + + ldflags = [ + "-fPIC", + "-Wl,-E", + ] + + part_name = "wifi" + subsystem_name = "communication" + } +} diff --git a/services/wifi_standard/wifi_framework/wifi_manage/wifi_scan/iscan_service.h b/wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_scan/iscan_service.h similarity index 81% rename from services/wifi_standard/wifi_framework/wifi_manage/wifi_scan/iscan_service.h rename to wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_scan/iscan_service.h index 4be934564b1567819475f00c6d90297c1941ed2b..e4471b2650cd6f2490a978deb2f348b904092d62 100644 --- a/services/wifi_standard/wifi_framework/wifi_manage/wifi_scan/iscan_service.h +++ b/wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_scan/iscan_service.h @@ -50,6 +50,13 @@ public: * @return success: WIFI_OPT_SUCCESS, failed: WIFI_OPT_FAILED */ virtual ErrCode ScanWithParam(const WifiScanParams &wifiScanParams) = 0; + /** + * @Description Disable/Restore the scanning operation. + * + * * @param params - disable or not. + * @return success: WIFI_OPT_SUCCESS, failed: WIFI_OPT_FAILED + */ + virtual ErrCode DisableScan(bool disable) = 0; /** * @Description Processes interface service screen change request. * @@ -70,7 +77,13 @@ public: * @param appMode operate app mode[in] * @return success: WIFI_OPT_SUCCESS, failed: WIFI_OPT_FAILED */ - virtual ErrCode OnAppRunningModeChanged(int appMode) = 0; + virtual ErrCode OnAppRunningModeChanged(ScanMode appRunMode) = 0; + /** + * @Description Updates the MovingFreeze state when the associated state changes. + * + * @return success: WIFI_OPT_SUCCESS, failed: WIFI_OPT_FAILED + */ + virtual ErrCode OnMovingFreezeStateChange() = 0; /** * @Description Processes interface service custom scene change request. * @@ -79,6 +92,13 @@ public: * @return success: WIFI_OPT_SUCCESS, failed: WIFI_OPT_FAILED */ virtual ErrCode OnCustomControlStateChanged(int customScene, int customSceneStatus) = 0; + /** + * @Description Get custom scene state. + * + * @param sceneMap custom scene state map[out] + * @return success: WIFI_OPT_SUCCESS, failed: WIFI_OPT_FAILED + */ + virtual ErrCode OnGetCustomSceneState(std::map& sceneMap) const = 0; /** * @Description Processes interface service scan control info change request. * diff --git a/services/wifi_standard/wifi_framework/wifi_manage/wifi_scan/iscan_service_callbacks.h b/wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_scan/iscan_service_callbacks.h similarity index 93% rename from services/wifi_standard/wifi_framework/wifi_manage/wifi_scan/iscan_service_callbacks.h rename to wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_scan/iscan_service_callbacks.h index 7b18eeab257a2fdfcb16ea66f62b5e2a35409396..c1e495a002962f9f79f4361275d6d2ca842cdf1c 100644 --- a/services/wifi_standard/wifi_framework/wifi_manage/wifi_scan/iscan_service_callbacks.h +++ b/wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_scan/iscan_service_callbacks.h @@ -26,6 +26,7 @@ struct IScanSerivceCallbacks { std::function OnScanStopEvent; std::function OnScanFinishEvent; std::function &)> OnScanInfoEvent; + std::function &)> OnStoreScanInfoEvent; }; } // namespace Wifi } // namespace OHOS diff --git a/services/wifi_standard/wifi_framework/wifi_manage/wifi_scan/scan_common.h b/wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_scan/scan_common.h old mode 100755 new mode 100644 similarity index 96% rename from services/wifi_standard/wifi_framework/wifi_manage/wifi_scan/scan_common.h rename to wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_scan/scan_common.h index 39cb9f0e7c5f8e70abab99aa0882b1f48fd27ba8..de381653ebb1916c496ebe96c67c28e27d86a01d --- a/services/wifi_standard/wifi_framework/wifi_manage/wifi_scan/scan_common.h +++ b/wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_scan/scan_common.h @@ -52,6 +52,7 @@ struct ScanConfig { int backScanPeriod; /* Scan interval for background scan */ bool fullScanFlag; /* Flag indicating whether the request is full scan */ bool externFlag; /* Flag indicating whether the request is an external scan */ + bool scanningWithParamFlag; /* Flag Indicating whether scanning with parameter */ std::string ssid; /* The network name */ std::string bssid; /* The address of the access point */ int scanStyle; /* Type of scan to perform */ @@ -62,6 +63,7 @@ struct ScanConfig { backScanPeriod = 0; fullScanFlag = false; externFlag = false; + scanningWithParamFlag = false; scanStyle = 0xFF; } }; @@ -101,12 +103,13 @@ struct StoreScanConfig { int64_t scanTime; /* Scan Start Time */ bool fullScanFlag; /* Flag of scan without specifying parameters */ bool externFlag; /* Flag indicating whether the request is an external scan. */ - + bool scanningWithParamFlag; /* Flag Indicating whether scanning with parameter */ StoreScanConfig() { scanTime = 0; fullScanFlag = false; externFlag = false; + scanningWithParamFlag = false; } }; @@ -166,7 +169,7 @@ enum ScanStatus { SCAN_FINISHED_STATUS = 1, /* End processing completed */ COMMON_SCAN_SUCCESS = 2, /* Notify the scan result after the common scan is complete */ COMMON_SCAN_FAILED = 3, /* Common scan failure */ - PNO_SCAN_RESULT = 4, /* The PNO scan is complete and the scanning result is notified */ + PNO_SCAN_INFO = 4, /* The PNO scan is complete and the scanning result is notified */ PNO_SCAN_FAILED = 5, /* Failed to start the PNO scanning */ SCAN_INNER_EVENT = 6, /* Report internal events */ SCAN_STATUS_INVALID /* Invalid value */ diff --git a/services/wifi_standard/wifi_framework/wifi_manage/wifi_scan/scan_interface.cpp b/wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_scan/scan_interface.cpp similarity index 63% rename from services/wifi_standard/wifi_framework/wifi_manage/wifi_scan/scan_interface.cpp rename to wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_scan/scan_interface.cpp index da8b40f0962eb4c65b8ca1916acebc6919d0f72b..addf90c44d227031a2af3fe5bffc78d581998d46 100644 --- a/services/wifi_standard/wifi_framework/wifi_manage/wifi_scan/scan_interface.cpp +++ b/wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_scan/scan_interface.cpp @@ -1,5 +1,5 @@ /* - * Copyright (C) 2021 Huawei Device Co., Ltd. + * Copyright (C) 2021-2022 Huawei Device Co., Ltd. * 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 @@ -15,7 +15,7 @@ #include "scan_interface.h" #include "wifi_logger.h" -DEFINE_WIFILOG_SCAN_LABEL("ScanStateMachine"); +DEFINE_WIFILOG_SCAN_LABEL("ScanInterface"); namespace OHOS { namespace Wifi { @@ -38,6 +38,7 @@ extern "C" IScanService *Create(void) extern "C" void Destroy(ScanInterface *scanInterface) { delete scanInterface; + scanInterface = nullptr; } ErrCode ScanInterface::Init() @@ -63,56 +64,65 @@ ErrCode ScanInterface::Init() ErrCode ScanInterface::UnInit() { WIFI_LOGI("Enter ScanInterface::UnInit.\n"); - + CHECK_NULL_AND_RETURN(pScanService, WIFI_OPT_FAILED); pScanService->UnInitScanService(); - return WIFI_OPT_SUCCESS; } ErrCode ScanInterface::Scan(bool externFlag) { WIFI_LOGI("Enter ScanInterface::Scan\n"); - + CHECK_NULL_AND_RETURN(pScanService, WIFI_OPT_FAILED); return pScanService->Scan(externFlag); } ErrCode ScanInterface::ScanWithParam(const WifiScanParams &wifiScanParams) { WIFI_LOGI("Enter ScanInterface::ScanWithParam\n"); - + CHECK_NULL_AND_RETURN(pScanService, WIFI_OPT_FAILED); return pScanService->ScanWithParam(wifiScanParams); } +ErrCode ScanInterface::DisableScan(bool disable) +{ + WIFI_LOGI("Enter ScanInterface::DisableScan, disable=%{public}d.", disable); + CHECK_NULL_AND_RETURN(pScanService, WIFI_OPT_FAILED); + return pScanService->DisableScan(disable); +} + ErrCode ScanInterface::OnScreenStateChanged(int screenState) { - WIFI_LOGI("Enter ScanInterface::OnScreenStateChanged\n"); + WIFI_LOGI("Enter ScanInterface::OnScreenStateChanged, screenState=%{public}d.", screenState); - if (screenState != STATE_OPEN && screenState != STATE_CLOSE) { + if (screenState != MODE_STATE_OPEN && screenState != MODE_STATE_CLOSE) { WIFI_LOGE("screenState param is error"); return WIFI_OPT_INVALID_PARAM; } - bool screenOn = true; - if (screenState == STATE_CLOSE) { - screenOn = false; - } - pScanService->HandleScreenStatusChanged(screenOn); + CHECK_NULL_AND_RETURN(pScanService, WIFI_OPT_FAILED); + pScanService->HandleScreenStatusChanged(); return WIFI_OPT_SUCCESS; } ErrCode ScanInterface::OnClientModeStatusChanged(int staStatus) { - WIFI_LOGI("Enter ScanInterface::OnClientModeStatusChanged\n"); - + WIFI_LOGI("Enter ScanInterface::OnClientModeStatusChanged, staStatus=%{public}d.", staStatus); + CHECK_NULL_AND_RETURN(pScanService, WIFI_OPT_FAILED); pScanService->HandleStaStatusChanged(staStatus); pScanService->SetStaCurrentTime(); return WIFI_OPT_SUCCESS; } -ErrCode ScanInterface::OnAppRunningModeChanged(int appMode) +ErrCode ScanInterface::OnAppRunningModeChanged(ScanMode appRunMode) { - WIFI_LOGI("Enter ScanInterface::OnAppRunningModeChanged\n"); + WIFI_LOGI("Enter ScanInterface::OnAppRunningModeChanged, appRunMode=%{public}d\n", static_cast(appRunMode)); + return WIFI_OPT_SUCCESS; +} - pScanService->SetOperateAppMode(appMode); +ErrCode ScanInterface::OnMovingFreezeStateChange() +{ + LOGI("Enter ScanInterface::OnMovingFreezeStateChange"); + CHECK_NULL_AND_RETURN(pScanService, WIFI_OPT_FAILED); + pScanService->HandleMovingFreezeChanged(); return WIFI_OPT_SUCCESS; } @@ -120,18 +130,27 @@ ErrCode ScanInterface::OnCustomControlStateChanged(int customScene, int customSc { WIFI_LOGI("Enter ScanInterface::OnCustomControlStateChanged\n"); - if (customSceneStatus != STATE_OPEN && customSceneStatus != STATE_CLOSE) { + if (customSceneStatus != MODE_STATE_OPEN && customSceneStatus != MODE_STATE_CLOSE) { WIFI_LOGE("screenState param is error"); return WIFI_OPT_INVALID_PARAM; } + CHECK_NULL_AND_RETURN(pScanService, WIFI_OPT_FAILED); pScanService->HandleCustomStatusChanged(customScene, customSceneStatus); return WIFI_OPT_SUCCESS; } +ErrCode ScanInterface::OnGetCustomSceneState(std::map& sceneMap) const +{ + WIFI_LOGI("Enter ScanInterface::OnGetCustomSceneState\n"); + CHECK_NULL_AND_RETURN(pScanService, WIFI_OPT_FAILED); + pScanService->HandleGetCustomSceneState(sceneMap); + return WIFI_OPT_SUCCESS; +} + ErrCode ScanInterface::OnControlStrategyChanged() { WIFI_LOGI("Enter ScanInterface::OnControlStrategyChanged\n"); - + CHECK_NULL_AND_RETURN(pScanService, WIFI_OPT_FAILED); pScanService->ClearScanControlValue(); pScanService->GetScanControlInfo(); pScanService->SystemScanProcess(true); diff --git a/services/wifi_standard/wifi_framework/wifi_manage/wifi_scan/scan_interface.h b/wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_scan/scan_interface.h similarity index 81% rename from services/wifi_standard/wifi_framework/wifi_manage/wifi_scan/scan_interface.h rename to wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_scan/scan_interface.h index 06da44c944caf97cf3e7f8a9ff4e88d8839c1136..5063ded1469b179320f4a4f40e99e8b7315b8009 100644 --- a/services/wifi_standard/wifi_framework/wifi_manage/wifi_scan/scan_interface.h +++ b/wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_scan/scan_interface.h @@ -16,6 +16,8 @@ #ifndef OHOS_WIFI_SCAN_INTERFACE_H #define OHOS_WIFI_SCAN_INTERFACE_H +#include +#include "define.h" #include "iscan_service.h" #include "scan_service.h" @@ -53,6 +55,13 @@ public: * @return success: WIFI_OPT_SUCCESS, failed: WIFI_OPT_FAILED */ ErrCode ScanWithParam(const WifiScanParams &wifiScanParams); + /** + * @Description Disable/Restore the scanning operation. + * + * * @param params - disable or not. + * @return success: WIFI_OPT_SUCCESS, failed: WIFI_OPT_FAILED + */ + ErrCode DisableScan(bool disable); /** * @Description Processes interface service screen change request. * @@ -73,7 +82,13 @@ public: * @param appMode operate app mode[in] * @return success: WIFI_OPT_SUCCESS, failed: WIFI_OPT_FAILED */ - ErrCode OnAppRunningModeChanged(int appMode); + ErrCode OnAppRunningModeChanged(ScanMode appRunMode); + /** + * @Description Updates the MovingFreeze state when the associated state changes. + * + * @return success: WIFI_OPT_SUCCESS, failed: WIFI_OPT_FAILED + */ + ErrCode OnMovingFreezeStateChange(); /** * @Description Processes interface service custom scene change request. * @@ -82,6 +97,13 @@ public: * @return success: WIFI_OPT_SUCCESS, failed: WIFI_OPT_FAILED */ ErrCode OnCustomControlStateChanged(int customScene, int customSceneStatus); + /** + * @Description Get custom scene state. + * + * @param sceneMap custom scene state map[out] + * @return success: WIFI_OPT_SUCCESS, failed: WIFI_OPT_FAILED + */ + ErrCode OnGetCustomSceneState(std::map& customSceneStateMap) const; /** * @Description Processes interface service scan control info change request. * diff --git a/services/wifi_standard/wifi_framework/wifi_manage/wifi_scan/scan_monitor.cpp b/wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_scan/scan_monitor.cpp old mode 100755 new mode 100644 similarity index 100% rename from services/wifi_standard/wifi_framework/wifi_manage/wifi_scan/scan_monitor.cpp rename to wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_scan/scan_monitor.cpp diff --git a/services/wifi_standard/wifi_framework/wifi_manage/wifi_scan/scan_monitor.h b/wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_scan/scan_monitor.h old mode 100755 new mode 100644 similarity index 100% rename from services/wifi_standard/wifi_framework/wifi_manage/wifi_scan/scan_monitor.h rename to wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_scan/scan_monitor.h diff --git a/services/wifi_standard/wifi_framework/wifi_manage/wifi_scan/scan_service.cpp b/wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_scan/scan_service.cpp old mode 100755 new mode 100644 similarity index 59% rename from services/wifi_standard/wifi_framework/wifi_manage/wifi_scan/scan_service.cpp rename to wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_scan/scan_service.cpp index d1eb516b3db9c76f34554c9ac1af344d2275bf41..4d957d705cfbd7fda341d199550b6752db9299c0 --- a/services/wifi_standard/wifi_framework/wifi_manage/wifi_scan/scan_service.cpp +++ b/wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_scan/scan_service.cpp @@ -1,5 +1,5 @@ /* - * Copyright (C) 2021 Huawei Device Co., Ltd. + * Copyright (C) 2021-2022 Huawei Device Co., Ltd. * 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 @@ -12,11 +12,16 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -#include + #include "scan_service.h" +#include +#include "log_helper.h" +#include "wifi_global_func.h" +#include "wifi_internal_msg.h" #include "wifi_logger.h" #include "wifi_settings.h" #include "wifi_sta_hal_interface.h" +#include "wifi_common_util.h" DEFINE_WIFILOG_SCAN_LABEL("ScanService"); @@ -28,16 +33,20 @@ ScanService::ScanService() scanStartedFlag(false), scanConfigStoreIndex(0), pnoScanStartTime(0), - isScreenOn(true), staStatus(static_cast(OperateResState::DISCONNECT_DISCONNECTED)), isPnoScanBegined(false), autoNetworkSelection(false), lastSystemScanTime(0), pnoScanFailedNum(0), - operateAppMode(0), - customScene(SCAN_SCENE_ALL), + disableScanFlag(false), staCurrentTime(0), - customCurrentTime(0) + customCurrentTime(0), + staSceneForbidCount(0), + customSceneForbidCount(0), + scanTrustMode(false), + isAbsFreezeState(false), + isAbsFreezeScaned(false), + scanResultBackup(-1) {} ScanService::~ScanService() @@ -46,10 +55,12 @@ ScanService::~ScanService() if (pScanMonitor != nullptr) { delete pScanMonitor; + pScanMonitor = nullptr; } if (pScanStateMachine != nullptr) { delete pScanStateMachine; + pScanStateMachine = nullptr; } } @@ -58,7 +69,6 @@ bool ScanService::InitScanService(const IScanSerivceCallbacks &scanSerivceCallba WIFI_LOGI("Enter ScanService::InitScanService.\n"); mScanSerivceCallbacks = scanSerivceCallbacks; - pScanStateMachine = new (std::nothrow) ScanStateMachine(); if (pScanStateMachine == nullptr) { WIFI_LOGE("Alloc pScanStateMachine failed.\n"); @@ -92,33 +102,42 @@ bool ScanService::InitScanService(const IScanSerivceCallbacks &scanSerivceCallba WIFI_IDL_OPT_OK)) { WIFI_LOGE("GetSupportFrequencies failed.\n"); } - GetScanControlInfo(); - GetScreenState(); + pScanMonitor->SetScanStateMachine(pScanStateMachine); pScanStateMachine->SendMessage(static_cast(CMD_SCAN_PREPARE)); + GetScanControlInfo(); + return true; } void ScanService::UnInitScanService() { WIFI_LOGI("Enter ScanService::UnInitScanService.\n"); - pScanStateMachine->SendMessage(static_cast(CMD_SCAN_FINISH)); - scanStartedFlag = false; - pScanStateMachine->StopTimer(static_cast(SYSTEM_SCAN_TIMER)); pScanStateMachine->StopTimer(static_cast(DISCONNECTED_SCAN_TIMER)); pScanStateMachine->StopTimer(static_cast(RESTART_PNO_SCAN_TIMER)); + pScanStateMachine->SendMessage(static_cast(CMD_SCAN_FINISH)); + scanStartedFlag = false; return; } +void ScanService::RegisterScanCallbacks(const IScanSerivceCallbacks &iScanSerivceCallbacks) +{ + mScanSerivceCallbacks = iScanSerivceCallbacks; +} + void ScanService::HandleScanStatusReport(ScanStatusReport &scanStatusReport) { WIFI_LOGI("Enter ScanService::HandleScanStatusReport.\n"); switch (scanStatusReport.status) { case SCAN_STARTED_STATUS: { + if (pScanStateMachine == nullptr) { + WIFI_LOGE("HandleScanStatusReport-SCAN_STARTED_STATUS pScanStateMachine is null\n"); + return; + } scanStartedFlag = true; - /* Pno scan maybe has started, stop it first */ + /* Pno scan maybe has started, stop it first. */ pScanStateMachine->SendMessage(CMD_STOP_PNO_SCAN); mScanSerivceCallbacks.OnScanStartEvent(); SystemScanProcess(true); @@ -136,13 +155,17 @@ void ScanService::HandleScanStatusReport(ScanStatusReport &scanStatusReport) HandleCommonScanFailed(scanStatusReport.requestIndexList); break; } - case PNO_SCAN_RESULT: { + case PNO_SCAN_INFO: { pnoScanFailedNum = 0; HandlePnoScanInfo(scanStatusReport.scanInfoList); break; } case PNO_SCAN_FAILED: { - /* Start the timer and restart the PNO scanning after a delay */ + if (pScanStateMachine == nullptr) { + WIFI_LOGE("HandleScanStatusReport-PNO_SCAN_FAILED pScanStateMachine is null\n"); + return; + } + /* Start the timer and restart the PNO scanning after a delay. */ pScanStateMachine->StartTimer(static_cast(RESTART_PNO_SCAN_TIMER), RESTART_PNO_SCAN_TIME); EndPnoScan(); break; @@ -184,25 +207,23 @@ void ScanService::HandleInnerEventReport(ScanInnerEventType innerEvent) ErrCode ScanService::Scan(bool externFlag) { - WIFI_LOGI("Enter ScanService::Scan.\n"); - + WIFI_LOGI("Enter ScanService::Scan, externFlag:%{public}d.\n", externFlag); if (!scanStartedFlag) { WIFI_LOGE("Scan service has not started.\n"); return WIFI_OPT_FAILED; } if (externFlag) { - int appId = 0; - if (!AllowExternScan(appId)) { - WIFI_LOGE("AllowExternScan return false.\n"); - return WIFI_OPT_FAILED; + ErrCode rlt = ApplyScanPolices(ScanType::SCAN_TYPE_EXTERN); + if (rlt != WIFI_OPT_SUCCESS) { + return rlt; } } ScanConfig scanConfig; /* * Invoke the interface provided by the configuration center to obtain the - * hidden network list + * hidden network list. */ if (!GetHiddenNetworkSsidList(scanConfig.hiddenNetworkSsid)) { WIFI_LOGE("GetHiddenNetworkSsidList failed.\n"); @@ -229,10 +250,9 @@ ErrCode ScanService::ScanWithParam(const WifiScanParams ¶ms) return WIFI_OPT_FAILED; } - int appId = 0; - if (!AllowExternScan(appId)) { - WIFI_LOGE("AllowExternScan return false.\n"); - return WIFI_OPT_FAILED; + ErrCode rlt = ApplyScanPolices(ScanType::SCAN_TYPE_EXTERN); + if (rlt != WIFI_OPT_SUCCESS) { + return rlt; } if ((params.band < static_cast(SCAN_BAND_UNSPECIFIED)) || @@ -241,7 +261,7 @@ ErrCode ScanService::ScanWithParam(const WifiScanParams ¶ms) return WIFI_OPT_FAILED; } - /* When the frequency is specified, the band must be SCAN_BAND_UNSPECIFIED */ + /* When the frequency is specified, the band must be SCAN_BAND_UNSPECIFIED. */ if (params.freqs.empty() && (params.band == static_cast(SCAN_BAND_UNSPECIFIED))) { WIFI_LOGE("params is error.\n"); return WIFI_OPT_FAILED; @@ -257,7 +277,7 @@ ErrCode ScanService::ScanWithParam(const WifiScanParams ¶ms) } else { /* * Invoke the interface provided by the configuration center to obtain the - * hidden network list + * hidden network list. */ if (!GetHiddenNetworkSsidList(scanConfig.hiddenNetworkSsid)) { WIFI_LOGE("GetHiddenNetworkSsidList failed.\n"); @@ -269,6 +289,7 @@ ErrCode ScanService::ScanWithParam(const WifiScanParams ¶ms) scanConfig.ssid = params.ssid; scanConfig.bssid = params.bssid; scanConfig.externFlag = true; + scanConfig.scanningWithParamFlag = true; scanConfig.scanStyle = SCAN_TYPE_HIGH_ACCURACY; if (!SingleScan(scanConfig)) { @@ -279,6 +300,14 @@ ErrCode ScanService::ScanWithParam(const WifiScanParams ¶ms) return WIFI_OPT_SUCCESS; } +ErrCode ScanService::DisableScan(bool disable) +{ + LOGI("Enter ScanService::DisableScan"); + std::unique_lock lock(scanControlInfoMutex); + disableScanFlag = disable; + return WIFI_OPT_SUCCESS; +} + bool ScanService::SingleScan(ScanConfig &scanConfig) { WIFI_LOGI("Enter ScanService::SingleScan.\n"); @@ -299,24 +328,29 @@ bool ScanService::SingleScan(ScanConfig &scanConfig) interConfig.scanFreqs.assign(scanConfig.scanFreqs.begin(), scanConfig.scanFreqs.end()); /* * When band is SCAN_BAND_BOTH_WITH_DFS, need to scan all frequency, - * scanFreqs can be empty + * scanFreqs can be empty. */ } else if (scanConfig.scanBand != SCAN_BAND_BOTH_WITH_DFS) { - /* Converting frequency bands to frequencies */ + /* Converting frequency bands to frequencies. */ if (!GetBandFreqs(scanConfig.scanBand, interConfig.scanFreqs)) { WIFI_LOGE("GetBandFreqs failed.\n"); return false; } } - /* Save the configuration */ + /* Save the configuration. */ int requestIndex = StoreRequestScanConfig(scanConfig, interConfig); if (requestIndex == MAX_SCAN_CONFIG_STORE_INDEX) { WIFI_LOGE("StoreRequestScanConfig failed.\n"); return false; } - /* Construct a message */ + std::unique_lock lock(scanConfigMapMutex); + if (pScanStateMachine == nullptr) { + WIFI_LOGE("pScanStateMachine is null.\n"); + return false; + } + /* Construct a message. */ InternalMessage *interMessage = pScanStateMachine->CreateMessage(static_cast(CMD_START_COMMON_SCAN), requestIndex); if (interMessage == nullptr) { @@ -331,8 +365,8 @@ bool ScanService::SingleScan(ScanConfig &scanConfig) WIFI_LOGE("AddScanMessageBody failed.\n"); return false; } - pScanStateMachine->SendMessage(interMessage); + return true; } @@ -444,7 +478,9 @@ int ScanService::StoreRequestScanConfig(const ScanConfig &scanConfig, const Inte static_cast(times.tv_sec) * SECOND_TO_MICRO_SECOND + times.tv_nsec / SECOND_TO_MILLI_SECOND; storeScanConfig.fullScanFlag = scanConfig.fullScanFlag; storeScanConfig.externFlag = scanConfig.externFlag; + storeScanConfig.scanningWithParamFlag = scanConfig.scanningWithParamFlag; + std::unique_lock lock(scanConfigMapMutex); scanConfigMap.insert(std::pair(scanConfigStoreIndex, storeScanConfig)); return scanConfigStoreIndex; @@ -454,6 +490,12 @@ void ScanService::HandleCommonScanFailed(std::vector &requestIndexList) { WIFI_LOGI("Enter ScanService::HandleCommonScanFailed.\n"); + if (staStatus != static_cast(OperateResState::DISCONNECT_DISCONNECTED) && + staStatus != static_cast(OperateResState::CONNECT_AP_CONNECTED)) { + return; + } + + std::unique_lock lock(scanConfigMapMutex); for (std::vector::iterator reqIter = requestIndexList.begin(); reqIter != requestIndexList.end(); ++reqIter) { ScanConfigMap::iterator configIter = scanConfigMap.find(*reqIter); /* No configuration found. */ @@ -461,8 +503,10 @@ void ScanService::HandleCommonScanFailed(std::vector &requestIndexList) continue; } - /* Notification of the end of scanning */ + /* Notification of the end of scanning. */ mScanSerivceCallbacks.OnScanFinishEvent(static_cast(ScanHandleNotify::SCAN_FAIL)); + scanResultBackup = static_cast(ScanHandleNotify::SCAN_FAIL); + scanConfigMap.erase(*reqIter); } @@ -474,41 +518,45 @@ void ScanService::HandleCommonScanInfo( { WIFI_LOGI("Enter ScanService::HandleCommonScanInfo.\n"); - bool fullScanInclude = false; bool fullScanStored = false; - for (std::vector::iterator reqIter = requestIndexList.begin(); reqIter != requestIndexList.end(); ++reqIter) { - ScanConfigMap::iterator configIter = scanConfigMap.find(*reqIter); - /* No configuration found. */ - if (configIter == scanConfigMap.end()) { - continue; - } - - /* Full Scan Info */ - if (configIter->second.fullScanFlag) { - fullScanInclude = true; - if (fullScanStored) { - scanConfigMap.erase(*reqIter); + { + std::unique_lock lock(scanConfigMapMutex); + for (std::vector::iterator reqIter = requestIndexList.begin(); reqIter != requestIndexList.end(); + ++reqIter) { + ScanConfigMap::iterator configIter = scanConfigMap.find(*reqIter); + /* No configuration found. */ + if (configIter == scanConfigMap.end()) { continue; } - if (StoreFullScanInfo(configIter->second, scanInfoList)) { - fullScanStored = true; - mScanSerivceCallbacks.OnScanFinishEvent(static_cast(ScanHandleNotify::SCAN_OK)); + /* Full Scan Info. */ + if (configIter->second.fullScanFlag) { + if (fullScanStored) { + scanConfigMap.erase(*reqIter); + continue; + } + + if (StoreFullScanInfo(configIter->second, scanInfoList)) { + fullScanStored = true; + mScanSerivceCallbacks.OnScanFinishEvent(static_cast(ScanHandleNotify::SCAN_OK)); + scanResultBackup = static_cast(ScanHandleNotify::SCAN_OK); + } else { + WIFI_LOGE("StoreFullScanInfo failed.\n"); + } + /* Specify Scan Info. */ } else { - WIFI_LOGE("StoreFullScanInfo failed.\n"); - } - /* Specify Scan Info */ - } else { - if (!StoreUserScanInfo(configIter->second, scanInfoList)) { - WIFI_LOGE("StoreUserScanInfo failed.\n"); + if (!StoreUserScanInfo(configIter->second, scanInfoList)) { + WIFI_LOGE("StoreUserScanInfo failed.\n"); + } + mScanSerivceCallbacks.OnScanFinishEvent(static_cast(ScanHandleNotify::SCAN_OK)); + scanResultBackup = static_cast(ScanHandleNotify::SCAN_OK); } - mScanSerivceCallbacks.OnScanFinishEvent(static_cast(ScanHandleNotify::SCAN_OK)); - } - scanConfigMap.erase(*reqIter); + scanConfigMap.erase(*reqIter); + } } - /* Send the scanning result to the module registered for listening */ + /* Send the scanning result to the module registered for listening. */ ScanInfoHandlerMap::iterator handleIter = scanInfoHandlerMap.begin(); for (; handleIter != scanInfoHandlerMap.end(); ++handleIter) { if (handleIter->second) { @@ -526,29 +574,56 @@ bool ScanService::StoreFullScanInfo( const StoreScanConfig &scanConfig, const std::vector &scanInfoList) { WIFI_LOGI("Enter ScanService::StoreFullScanInfo.\n"); - - /* Filtering result */ + /* Filtering result. */ WIFI_LOGI("scanConfig.scanTime is %" PRIu64 ".\n", scanConfig.scanTime); WIFI_LOGI("Receive %{public}d scan results.\n", (int)(scanInfoList.size())); - std::vector filterScanInfo; - std::vector::const_iterator iter = scanInfoList.begin(); - for (; iter != scanInfoList.end(); ++iter) { - char tmpBuf[128] = ""; - EncryptLogMsg(iter->ssid.c_str(), tmpBuf, sizeof(tmpBuf)); + if (scanInfoList.size() == 0) { + /* Don't overwrite ScanInfoList */ + return true; + } + + std::vector storeInfoList; + for (auto iter = scanInfoList.begin(); iter != scanInfoList.end(); ++iter) { + if (iter->ssid.empty()) { + continue; + } WifiScanInfo scanInfo; scanInfo.bssid = iter->bssid; scanInfo.ssid = iter->ssid; scanInfo.capabilities = iter->capabilities; scanInfo.frequency = iter->frequency; + scanInfo.channelWidth = iter->channelWidth; + scanInfo.centerFrequency0 = iter->centerFrequency0; + scanInfo.centerFrequency1 = iter->centerFrequency1; scanInfo.rssi = iter->rssi; + scanInfo.securityType = iter->securityType; + scanInfo.infoElems = iter->infoElems; + scanInfo.features = iter->features; scanInfo.timestamp = iter->timestamp; scanInfo.band = iter->band; - scanInfo.securityType = iter->securityType; + storeInfoList.push_back(scanInfo); + } - filterScanInfo.push_back(scanInfo); + std::vector results; + int ret = WifiSettings::GetInstance().GetScanInfoList(results); + if (ret != 0) { + WIFI_LOGW("GetScanInfoList return error. \n"); + } + for (auto iter = results.begin(); iter != results.end(); ++iter) { + bool find = false; + for (auto storedIter = storeInfoList.begin(); storedIter != storeInfoList.end(); ++storedIter) { + if (iter->bssid == storedIter->bssid) { + find = true; + break; + } + } + if (!find) { + storeInfoList.push_back(*iter); + } } - if (WifiSettings::GetInstance().SaveScanInfoList(filterScanInfo) != 0) { + WIFI_LOGI("Save %{public}d scan results.", (int)(storeInfoList.size())); + if (WifiSettings::GetInstance().SaveScanInfoList(storeInfoList) != 0) { WIFI_LOGE("WifiSettings::GetInstance().SaveScanInfoList failed.\n"); return false; } @@ -556,13 +631,10 @@ bool ScanService::StoreFullScanInfo( return true; } -bool ScanService::StoreUserScanInfo( - const StoreScanConfig &scanConfig, const std::vector &scanInfoList) +bool ScanService::StoreUserScanInfo(const StoreScanConfig &scanConfig, std::vector &scanInfoList) { WIFI_LOGI("Enter ScanService::StoreUserScanInfo.\n"); - /* Filtering result */ - std::vector filterScanInfo; std::vector::const_iterator iter = scanInfoList.begin(); for (; iter != scanInfoList.end(); ++iter) { /* Timestamp filtering */ @@ -570,7 +642,7 @@ bool ScanService::StoreUserScanInfo( continue; } - /* frequency filtering */ + /* frequency filtering. */ if (!scanConfig.scanFreqs.empty()) { if (std::find(scanConfig.scanFreqs.begin(), scanConfig.scanFreqs.end(), iter->frequency) == scanConfig.scanFreqs.end()) { @@ -578,32 +650,22 @@ bool ScanService::StoreUserScanInfo( } } - /* SSID filtering */ + /* SSID filtering. */ if ((!scanConfig.ssid.empty()) && (scanConfig.ssid != iter->ssid)) { continue; } - /* BSSID filtering */ + /* BSSID filtering. */ if ((!scanConfig.bssid.empty()) && (scanConfig.bssid != iter->bssid)) { continue; } - - WifiScanInfo scanInfo; - scanInfo.bssid = iter->bssid; - scanInfo.ssid = iter->ssid; - scanInfo.capabilities = iter->capabilities; - scanInfo.frequency = iter->frequency; - scanInfo.rssi = iter->rssi; - scanInfo.timestamp = iter->timestamp; - scanInfo.band = iter->band; - scanInfo.securityType = iter->securityType; - filterScanInfo.push_back(scanInfo); } /* - * The specified parameter scanning is initiated by the system and is not - * stored in the configuration center + * The specified parameter scanning is initiated by the system and + * store in the configuration center. */ + ReportStoreScanInfos(scanInfoList); return true; } @@ -611,36 +673,19 @@ bool ScanService::StoreUserScanInfo( void ScanService::ReportScanInfos(std::vector &interScanList) { WIFI_LOGI("Enter ScanService::ReportScanInfos.\n"); + mScanSerivceCallbacks.OnScanInfoEvent(interScanList); return; } -void ScanService::ConvertScanInfos( - const std::vector &interScanList, std::vector &scanInfoList) +void ScanService::ReportStoreScanInfos(std::vector &interScanList) { - WIFI_LOGI("Enter ScanService::ConvertScanInfos.\n"); + WIFI_LOGI("Enter ScanService::ReportStoreScanInfos.\n"); - /* Filtering result */ - std::vector::const_iterator iter = interScanList.begin(); - for (; iter != interScanList.end(); ++iter) { - WifiScanInfo scanInfo; - scanInfo.bssid = iter->bssid; - scanInfo.ssid = iter->ssid; - scanInfo.capabilities = iter->capabilities; - scanInfo.frequency = iter->frequency; - scanInfo.rssi = iter->rssi; - scanInfo.timestamp = iter->timestamp; - scanInfo.band = iter->band; - scanInfo.securityType = iter->securityType; - scanInfoList.push_back(scanInfo); - } + mScanSerivceCallbacks.OnStoreScanInfoEvent(interScanList); return; } -/** - * @Description Start PNO scanning - * @return success: true, failed: false - */ bool ScanService::BeginPnoScan() { WIFI_LOGI("Enter ScanService::BeginPnoScan.\n"); @@ -650,8 +695,8 @@ bool ScanService::BeginPnoScan() return false; } - if (!AllowPnoScan()) { - WIFI_LOGI("AllowPnoScan return false.\n"); + ErrCode rlt = ApplyScanPolices(ScanType::SCAN_TYPE_PNO); + if (rlt != WIFI_OPT_SUCCESS) { return false; } @@ -698,7 +743,10 @@ bool ScanService::BeginPnoScan() bool ScanService::PnoScan(const PnoScanConfig &pnoScanConfig, const InterScanConfig &interScanConfig) { WIFI_LOGI("Enter ScanService::PnoScan.\n"); - + if (pScanStateMachine == nullptr) { + WIFI_LOGE("pScanStateMachine is null.\n"); + return false; + } /* Construct a message. */ InternalMessage *interMessage = pScanStateMachine->CreateMessage(CMD_START_PNO_SCAN); if (interMessage == nullptr) { @@ -744,19 +792,19 @@ bool ScanService::AddPnoScanMessageBody(InternalMessage *interMessage, const Pno interMessage->AddIntMessageBody(pnoScanConfig.minRssi5Ghz); interMessage->AddIntMessageBody(pnoScanConfig.hiddenNetworkSsid.size()); - std::vector::const_iterator iter = pnoScanConfig.hiddenNetworkSsid.begin(); + auto iter = pnoScanConfig.hiddenNetworkSsid.begin(); for (; iter != pnoScanConfig.hiddenNetworkSsid.end(); ++iter) { interMessage->AddStringMessageBody(*iter); } interMessage->AddIntMessageBody(pnoScanConfig.savedNetworkSsid.size()); - std::vector::const_iterator iter2 = pnoScanConfig.savedNetworkSsid.begin(); + auto iter2 = pnoScanConfig.savedNetworkSsid.begin(); for (; iter2 != pnoScanConfig.savedNetworkSsid.end(); ++iter2) { interMessage->AddStringMessageBody(*iter2); } interMessage->AddIntMessageBody(pnoScanConfig.freqs.size()); - std::vector::const_iterator iter3 = pnoScanConfig.freqs.begin(); + auto iter3 = pnoScanConfig.freqs.begin(); for (; iter3 != pnoScanConfig.freqs.end(); ++iter3) { interMessage->AddIntMessageBody(*iter3); } @@ -773,8 +821,8 @@ void ScanService::HandlePnoScanInfo(std::vector &scanInfoList) for (; iter != scanInfoList.end(); ++iter) { if ((iter->timestamp / SECOND_TO_MILLI_SECOND) > pnoScanStartTime) { filterScanInfo.push_back(*iter); - WIFI_LOGI("InterScanInfo.bssid is %s.\n", iter->bssid.c_str()); - WIFI_LOGI("InterScanInfo.ssid is %s.\n", iter->ssid.c_str()); + WIFI_LOGI("InterScanInfo.bssid is %{private}s.\n", MacAnonymize(iter->bssid).c_str()); + WIFI_LOGI("InterScanInfo.ssid is %{public}s.\n", SsidAnonymize(iter->ssid).c_str()); WIFI_LOGI("InterScanInfo.capabilities is %{public}s.\n", iter->capabilities.c_str()); WIFI_LOGI("InterScanInfo.frequency is %{public}d.\n", iter->frequency); WIFI_LOGI("InterScanInfo.rssi is %{public}d.\n", iter->rssi); @@ -782,7 +830,7 @@ void ScanService::HandlePnoScanInfo(std::vector &scanInfoList) } } - /* Send the scanning result to the module registered for listening */ + /* Send the scanning result to the module registered for listening. */ PnoScanInfoHandlerMap::iterator handleIter = pnoScanInfoHandlerMap.begin(); for (; handleIter != pnoScanInfoHandlerMap.end(); ++handleIter) { if (handleIter->second) { @@ -790,7 +838,7 @@ void ScanService::HandlePnoScanInfo(std::vector &scanInfoList) } } - /* send message to main service */ + /* send message to main service. */ ReportScanInfos(filterScanInfo); return; @@ -803,24 +851,25 @@ void ScanService::EndPnoScan() if (!isPnoScanBegined) { return; } - + if (pScanStateMachine == nullptr) { + WIFI_LOGE("pScanStateMachine is null.\n"); + return; + } pScanStateMachine->SendMessage(CMD_STOP_PNO_SCAN); isPnoScanBegined = false; return; } -void ScanService::HandleScreenStatusChanged(bool screenOn) +void ScanService::HandleScreenStatusChanged() { WIFI_LOGI("Enter ScanService::HandleScreenStatusChanged."); - - isScreenOn = screenOn; SystemScanProcess(false); return; } void ScanService::HandleStaStatusChanged(int status) { - WIFI_LOGI("Enter ScanService::HandleStaStatusChanged."); + WIFI_LOGI("Enter ScanService::HandleStaStatusChanged, change to status: %{public}d.", status); staStatus = status; switch (staStatus) { @@ -838,42 +887,77 @@ void ScanService::HandleStaStatusChanged(int status) } } + staSceneForbidCount = 0; return; } +void ScanService::HandleMovingFreezeChanged() +{ + LOGI("Enter ScanService::HandleMovingFreezeChanged."); + ScanMode appRunMode = WifiSettings::GetInstance().GetAppRunningState(); + int freezeState = WifiSettings::GetInstance().GetFreezeModeState(); + int noChargerPlugModeState = WifiSettings::GetInstance().GetNoChargerPlugModeState(); + + bool movingFreeze = (appRunMode == ScanMode::APP_BACKGROUND_SCAN || appRunMode == ScanMode::SYS_BACKGROUND_SCAN) && + (freezeState == MODE_STATE_OPEN) && (noChargerPlugModeState == MODE_STATE_OPEN); + bool movingFreezeBakup = IsMovingFreezeState(); + + SetMovingFreezeState(movingFreeze); + WIFI_LOGD("moving freeze changed: movingFreeze=%{public}d, movingFreezeBakup=%{public}d", movingFreeze, + movingFreezeBakup); + /* Moving -> Freeze, set the scanned flag to false. */ + if (!movingFreezeBakup && movingFreeze) { + WIFI_LOGW("set movingFreeze scanned false."); + SetMovingFreezeScaned(false); + } +} + void ScanService::HandleCustomStatusChanged(int customScene, int customSceneStatus) { - LOGI("Enter ScanService::HandleCustomStatusChanged."); + WIFI_LOGI("Enter ScanService::HandleCustomStatusChanged."); + WIFI_LOGD("sizeof(time_t):%{public}d", int(sizeof(time_t))); time_t now = time(nullptr); - LOGD("customScene:%d, status:%d", customScene, customSceneStatus); - if (customSceneStatus == STATE_OPEN) { + WIFI_LOGI("customScene:%{public}d, status:%{public}d", customScene, customSceneStatus); + if (customSceneStatus == MODE_STATE_OPEN) { customSceneTimeMap.insert(std::pair(customScene, now)); } - if (customSceneStatus == STATE_CLOSE) { + if (customSceneStatus == MODE_STATE_CLOSE) { customSceneTimeMap.erase(customScene); } SystemScanProcess(false); + customSceneForbidCount = 0; return; } +void ScanService::HandleGetCustomSceneState(std::map& sceneMap) const +{ + sceneMap = customSceneTimeMap; +} + void ScanService::SystemScanProcess(bool scanAtOnce) { - WIFI_LOGI("Enter ScanService::SystemScanProcess."); + WIFI_LOGI("Enter ScanService::SystemScanProcess, scanAtOnce:%{public}d.", scanAtOnce); StopSystemScan(); - WIFI_LOGD("isScreenOn is:%{public}d", isScreenOn); - if (isScreenOn) { - for (auto iter = scanControlInfo.scanIntervalList.begin(); iter != scanControlInfo.scanIntervalList.end(); - ++iter) { - if (iter->scanScene == SCAN_SCENE_ALL && iter->scanMode == ScanMode::SYSTEM_TIMER_SCAN && - iter->isSingle == false) { - WIFI_LOGD("iter->intervalMode is:%{public}d", iter->intervalMode); - WIFI_LOGD("iter->interval is:%{public}d", iter->interval); - WIFI_LOGD("iter->count is:%{public}d", iter->count); - systemScanIntervalMode.scanIntervalMode.intervalMode = iter->intervalMode; - systemScanIntervalMode.scanIntervalMode.interval = iter->interval; - systemScanIntervalMode.scanIntervalMode.count = iter->count; + + int state = WifiSettings::GetInstance().GetScreenState(); + WIFI_LOGI("Screen state(1:OPEN, 2:CLOSE): %{public}d.", state); + if (state == MODE_STATE_OPEN) { + { + std::unique_lock lock(scanControlInfoMutex); + int i = 0; + for (auto iter = scanControlInfo.scanIntervalList.begin(); iter != scanControlInfo.scanIntervalList.end(); + ++iter) { + if (iter->scanScene == SCAN_SCENE_ALL && iter->scanMode == ScanMode::SYSTEM_TIMER_SCAN && + iter->isSingle == false) { + WIFI_LOGI("iter[%{public}d]: intervalMode:%{public}d, interval:%{public}d, count:%{public}d", + i++, iter->intervalMode, iter->interval, iter->count); + systemScanIntervalMode.scanIntervalMode.intervalMode = iter->intervalMode; + systemScanIntervalMode.scanIntervalMode.interval = iter->interval; + systemScanIntervalMode.scanIntervalMode.count = iter->count; + systemScanIntervalMode.expScanCount = 0; + } } } StartSystemTimerScan(scanAtOnce); @@ -890,7 +974,10 @@ void ScanService::SystemScanProcess(bool scanAtOnce) void ScanService::StopSystemScan() { WIFI_LOGI("Enter ScanService::StopSystemScan."); - + if (pScanStateMachine == nullptr) { + WIFI_LOGE("pScanStateMachine is null.\n"); + return; + } pScanStateMachine->StopTimer(static_cast(SYSTEM_SCAN_TIMER)); EndPnoScan(); pnoScanFailedNum = 0; @@ -900,14 +987,13 @@ void ScanService::StopSystemScan() void ScanService::StartSystemTimerScan(bool scanAtOnce) { - WIFI_LOGI("Enter ScanService::StartSystemTimerScan."); - - if (!AllowSystemTimerScan()) { - WIFI_LOGI("AllowSystemTimerScan return false."); + WIFI_LOGI("Enter ScanService::StartSystemTimerScan, scanAtOnce: %{public}d.", scanAtOnce); + ErrCode rlt = ApplyScanPolices(ScanType::SCAN_TYPE_SYSTEMTIMER); + if (rlt != WIFI_OPT_SUCCESS) { return; } - struct timespec times = {0, 0}; + struct timespec times = { 0, 0 }; clock_gettime(CLOCK_MONOTONIC, ×); int64_t nowTime = static_cast(times.tv_sec) * SECOND_TO_MILLI_SECOND + times.tv_nsec / SECOND_TO_MICRO_SECOND; @@ -918,23 +1004,22 @@ void ScanService::StartSystemTimerScan(bool scanAtOnce) /* * The scan is performed immediately, the first scan is required, - * or the time since the last scan is longer than the scan interval + * or the time since the last scan is longer than the scan interval. */ int scanTime = SYSTEM_SCAN_INIT_TIME; - WIFI_LOGD("interval:%{public}d", systemScanIntervalMode.scanIntervalMode.interval); if (systemScanIntervalMode.scanIntervalMode.interval > 0) { scanTime = systemScanIntervalMode.scanIntervalMode.interval; } if (scanAtOnce || (lastSystemScanTime == 0) || (sinceLastScan >= systemScanIntervalMode.scanIntervalMode.interval)) { - if (!Scan(false)) { + if (Scan(false) != WIFI_OPT_SUCCESS) { WIFI_LOGE("Scan failed."); } lastSystemScanTime = nowTime; } else { scanTime = systemScanIntervalMode.scanIntervalMode.interval - sinceLastScan; } - WIFI_LOGD("scanTime: %{public}d, interval:%{public}d, count:%{public}d", + WIFI_LOGI("StartSystemTimerScan, scanTime: %{public}d, interval:%{public}d, count:%{public}d", scanTime, systemScanIntervalMode.scanIntervalMode.interval, systemScanIntervalMode.scanIntervalMode.count); @@ -952,7 +1037,10 @@ void ScanService::HandleSystemScanTimeout() void ScanService::DisconnectedTimerScan() { WIFI_LOGI("Enter ScanService::DisconnectedTimerScan.\n"); - + if (pScanStateMachine == nullptr) { + WIFI_LOGE("pScanStateMachine is null.\n"); + return; + } pScanStateMachine->StartTimer(static_cast(DISCONNECTED_SCAN_TIMER), DISCONNECTED_SCAN_INTERVAL); return; } @@ -964,8 +1052,11 @@ void ScanService::HandleDisconnectedScanTimeout() if (staStatus != static_cast(OperateResState::DISCONNECT_DISCONNECTED)) { return; } - - if (!Scan(false)) { + if (pScanStateMachine == nullptr) { + WIFI_LOGE("pScanStateMachine is null.\n"); + return; + } + if (Scan(false) != WIFI_OPT_SUCCESS) { WIFI_LOGE("Scan failed."); } pScanStateMachine->StartTimer(static_cast(DISCONNECTED_SCAN_TIMER), DISCONNECTED_SCAN_INTERVAL); @@ -994,219 +1085,384 @@ void ScanService::GetScanControlInfo() { WIFI_LOGI("Enter ScanService::GetScanControlInfo.\n"); + std::unique_lock lock(scanControlInfoMutex); if (WifiSettings::GetInstance().GetScanControlInfo(scanControlInfo) != 0) { WIFI_LOGE("WifiSettings::GetInstance().GetScanControlInfo failed"); } - - return; -} - -void ScanService::GetScreenState() -{ - WIFI_LOGI("Enter ScanService::GetScreenState.\n"); - int screenState = WifiSettings::GetInstance().GetScreenState(); - isScreenOn = true; - if (screenState == SCREEN_CLOSED) { - isScreenOn = false; - } - - return; -} - -void ScanService::SetOperateAppMode(int appMode) -{ - WIFI_LOGI("Enter ScanService::SetOperateAppMode.\n"); - operateAppMode = appMode; - return; } -ScanMode ScanService::GetOperateAppMode() -{ - WIFI_LOGI("Enter ScanService::GetOperateAppMode.\n"); - ScanMode scanMode = ScanMode::SYS_FOREGROUND_SCAN; - switch (operateAppMode) { - case APP_FOREGROUND_SCAN: - scanMode = ScanMode::APP_FOREGROUND_SCAN; - break; - - case APP_BACKGROUND_SCAN: - scanMode = ScanMode::APP_BACKGROUND_SCAN; - break; - - case SYS_FOREGROUND_SCAN: - scanMode = ScanMode::SYS_FOREGROUND_SCAN; - break; - - case SYS_BACKGROUND_SCAN: - scanMode = ScanMode::SYS_BACKGROUND_SCAN; - break; - - default: - WIFI_LOGE("operateAppMode %{public}d is invalid.", operateAppMode); - break; - } - - return scanMode; -} - -bool ScanService::AllowExternScan(int appId) +ErrCode ScanService::AllowExternScan() { WIFI_LOGI("Enter ScanService::AllowExternScan.\n"); int staScene = GetStaScene(); - ScanMode scanMode = GetOperateAppMode(); - WIFI_LOGD("staScene is %{public}d, scanMode is %{public}d", staScene, (int)scanMode); + ScanMode scanMode = WifiSettings::GetInstance().GetAppRunningState(); + WIFI_LOGI("AllowExternScan, staScene is %{public}d, scanMode is %{public}d", staScene, (int)scanMode); + + if (!AllowExternScanByThermal()) { + WIFI_LOGW("extern scan not allow by thermal level"); + return WIFI_OPT_FAILED; + } if (!AllowExternScanByForbid(staScene, scanMode)) { - WIFI_LOGD("extern scan not allow by forbid mode"); - return false; + WIFI_LOGW("extern scan not allow by forbid mode"); + return WIFI_OPT_FAILED; } + int appId = 0; if (!AllowExternScanByInterval(appId, staScene, scanMode)) { - WIFI_LOGD("extern scan not allow by interval mode"); - return false; + WIFI_LOGW("extern scan not allow by interval mode"); + return WIFI_OPT_FAILED; + } + if (!AllowScanByMovingFreeze()) { + WIFI_LOGW("extern scan not allow by moving freeze mode"); + return WIFI_OPT_MOVING_FREEZE_CTRL; } - WIFI_LOGD("extern scan has allowed"); - return true; + if (!AllowScanByDisableScanCtrl()) { + WIFI_LOGW("extern scan not allow by disable scan control."); + return WIFI_OPT_FAILED; + } + + WIFI_LOGI("extern scan has allowed"); + return WIFI_OPT_SUCCESS; } -bool ScanService::AllowSystemTimerScan() +ErrCode ScanService::AllowSystemTimerScan() { WIFI_LOGI("Enter ScanService::AllowSystemTimerScan.\n"); if (staStatus != static_cast(OperateResState::DISCONNECT_DISCONNECTED) && staStatus != static_cast(OperateResState::CONNECT_AP_CONNECTED)) { - return false; + WIFI_LOGW("system timer scan not allowed for staStatus: %{public}d.", staStatus); + return WIFI_OPT_FAILED; } - /* The network is connected and cannot be automatically switched */ + /* The network is connected and cannot be automatically switched. */ autoNetworkSelection = WifiSettings::GetInstance().GetWhetherToAllowNetworkSwitchover(); if ((staStatus == static_cast(OperateResState::CONNECT_AP_CONNECTED)) && (!autoNetworkSelection)) { - return false; + WIFI_LOGW("system timer scan not allowed for CONNECT_AP_CONNECTED"); + return WIFI_OPT_FAILED; } int staScene = GetStaScene(); /* Determines whether to allow scanning based on the STA status. */ if (staScene == SCAN_SCENE_MAX) { - return false; + WIFI_LOGW("system timer scan not allowed for invalid staScene: %{public}d", staScene); + return WIFI_OPT_FAILED; } if (!AllowScanDuringStaScene(staScene, ScanMode::SYSTEM_TIMER_SCAN)) { - WIFI_LOGD("system timer scan not allowed, staScene is %{public}d", staScene); - return false; + WIFI_LOGW("system timer scan not allowed, staScene: %{public}d", staScene); + return WIFI_OPT_FAILED; } if (!AllowScanDuringCustomScene(ScanMode::SYSTEM_TIMER_SCAN)) { - WIFI_LOGD("system timer scan not allowed"); - return false; + WIFI_LOGW("system timer scan not allowed"); + return WIFI_OPT_FAILED; } - for (auto iter = scanControlInfo.scanIntervalList.begin(); iter != scanControlInfo.scanIntervalList.end(); ++iter) { - if (iter->scanScene == SCAN_SCENE_ALL && iter->scanMode == ScanMode::SYSTEM_TIMER_SCAN && - iter->isSingle == false) { - if (!SystemScanByInterval(systemScanIntervalMode.expScanCount, - systemScanIntervalMode.scanIntervalMode.interval, - systemScanIntervalMode.scanIntervalMode.count)) { - return false; + if (!AllowScanByMovingFreeze()) { + return WIFI_OPT_MOVING_FREEZE_CTRL; + } + + { + std::unique_lock lock(scanControlInfoMutex); + for (auto iter = scanControlInfo.scanIntervalList.begin(); iter != scanControlInfo.scanIntervalList.end(); + ++iter) { + if (iter->scanScene == SCAN_SCENE_ALL && iter->scanMode == ScanMode::SYSTEM_TIMER_SCAN && + iter->isSingle == false) { + if (!SystemScanByInterval(systemScanIntervalMode.expScanCount, + systemScanIntervalMode.scanIntervalMode.interval, systemScanIntervalMode.scanIntervalMode.count)) { + return WIFI_OPT_FAILED; + } } } } - WIFI_LOGD("allow system timer scan"); - return true; + if (!AllowScanByDisableScanCtrl()) { + WIFI_LOGW("system timer scan not allow by disable scan control."); + return WIFI_OPT_FAILED; + } + + WIFI_LOGI("allow system timer scan"); + return WIFI_OPT_SUCCESS; } -bool ScanService::AllowPnoScan() +ErrCode ScanService::AllowPnoScan() { WIFI_LOGI("Enter ScanService::AllowPnoScan.\n"); if (staStatus != static_cast(OperateResState::DISCONNECT_DISCONNECTED)) { - return false; + WIFI_LOGE("NOT allow PNO scan for staStatus: %{public}d", staStatus); + return WIFI_OPT_FAILED; } int staScene = GetStaScene(); if (staScene == SCAN_SCENE_MAX) { - return false; + WIFI_LOGE("NOT allow PNO scan for staScene: %{public}d", staScene); + return WIFI_OPT_FAILED; } if (!AllowScanDuringStaScene(staScene, ScanMode::PNO_SCAN)) { - WIFI_LOGD("pnoScan is not allowed for forbid map, staScene is %{public}d", staScene); - return false; + WIFI_LOGW("pnoScan is not allowed for forbid map, staScene is %{public}d", staScene); + return WIFI_OPT_FAILED; } if (!AllowScanDuringCustomScene(ScanMode::PNO_SCAN)) { WIFI_LOGD("pnoScan is not allowed for forbid map"); - return false; + return WIFI_OPT_FAILED; + } + if (!AllowScanByMovingFreeze()) { + return WIFI_OPT_MOVING_FREEZE_CTRL; } - for (auto iter = scanControlInfo.scanIntervalList.begin(); iter != scanControlInfo.scanIntervalList.end(); ++iter) { - if (iter->scanScene == SCAN_SCENE_ALL && iter->scanMode == ScanMode::PNO_SCAN && iter->isSingle == false) { - pnoScanIntervalMode.scanIntervalMode.intervalMode = iter->intervalMode; - pnoScanIntervalMode.scanIntervalMode.interval = iter->interval; - pnoScanIntervalMode.scanIntervalMode.count = iter->count; - if (!PnoScanByInterval(pnoScanIntervalMode.fixedScanCount, - pnoScanIntervalMode.fixedCurrentTime, - pnoScanIntervalMode.scanIntervalMode.interval, - pnoScanIntervalMode.scanIntervalMode.count)) { - WIFI_LOGD("pnoScan is not allowed for interval mode"); - return false; + { + std::unique_lock lock(scanControlInfoMutex); + for (auto iter = scanControlInfo.scanIntervalList.begin(); iter != scanControlInfo.scanIntervalList.end(); + ++iter) { + if (iter->scanScene == SCAN_SCENE_ALL && iter->scanMode == ScanMode::PNO_SCAN && iter->isSingle == false) { + pnoScanIntervalMode.scanIntervalMode.intervalMode = iter->intervalMode; + pnoScanIntervalMode.scanIntervalMode.interval = iter->interval; + pnoScanIntervalMode.scanIntervalMode.count = iter->count; + if (!PnoScanByInterval(pnoScanIntervalMode.fixedScanCount, pnoScanIntervalMode.fixedCurrentTime, + pnoScanIntervalMode.scanIntervalMode.interval, pnoScanIntervalMode.scanIntervalMode.count)) { + WIFI_LOGW("pnoScan is not allowed for interval mode"); + return WIFI_OPT_FAILED; + } } } } - WIFI_LOGD("pno scan is allowed"); - return true; + + if (!AllowScanByDisableScanCtrl()) { + WIFI_LOGW("pnoScan not allow by disable scan control."); + return WIFI_OPT_FAILED; + } + + WIFI_LOGI("pno scan is allowed"); + return WIFI_OPT_SUCCESS; } -bool ScanService::AllowExternScanByForbid(int staScene, ScanMode scanMode) +ErrCode ScanService::AllowScanByType(ScanType scanType) { - WIFI_LOGI("Enter ScanService::AllowExternScanByForbid.\n"); + LOGI("Enter ScanService::AllowScanByType, scanType: %{public}d.", scanType); - if (IsExternScanning()) { - if (!AllowScanDuringScanning(scanMode)) { - return false; - } - if (!AllowScanDuringScanning(ScanMode::ALL_EXTERN_SCAN)) { - return false; - } + ErrCode allScanResult = WIFI_OPT_SUCCESS; + switch (scanType) { + case ScanType::SCAN_TYPE_EXTERN: + allScanResult = AllowExternScan(); + break; + case ScanType::SCAN_TYPE_SYSTEMTIMER: + allScanResult = AllowSystemTimerScan(); + break; + case ScanType::SCAN_TYPE_PNO: + allScanResult = AllowPnoScan(); + break; + default: + LOGE("scanType error.\n"); + break; } - if (isScreenOn == false) { - if (!AllowScanDuringScreenOff(scanMode)) { - return false; - } - if (!AllowScanDuringScreenOff(ScanMode::ALL_EXTERN_SCAN)) { - return false; - } - } - if (!AllowScanDuringStaScene(staScene, scanMode)) { - return false; - } - if (!AllowScanDuringStaScene(staScene, ScanMode::ALL_EXTERN_SCAN)) { - return false; - } - if (!AllowScanDuringCustomScene(scanMode)) { - return false; - } - if (!AllowScanDuringCustomScene(ScanMode::ALL_EXTERN_SCAN)) { - return false; - } - return true; + WIFI_LOGW("AllowScanByType, allScanResult:%{public}d.", static_cast(allScanResult)); + return allScanResult; } -bool ScanService::AllowExternScanByInterval(int appId, int staScene, ScanMode scanMode) +void ScanService::SetScanTrustMode() { - WIFI_LOGI("Enter ScanService::AllowExternScanByInterval.\n"); + std::unique_lock lock(scanControlInfoMutex); + scanTrustMode = true; +} - if (!AllowExternScanByIntervalMode(appId, staScene, scanMode)) { - return false; - } - if (!AllowExternScanByIntervalMode(appId, staScene, ScanMode::ALL_EXTERN_SCAN)) { - return false; - } - if (!AllowExternScanByIntervalMode(appId, SCAN_SCENE_ALL, scanMode)) { - return false; - } - if (!AllowExternScanByIntervalMode(appId, SCAN_SCENE_ALL, ScanMode::ALL_EXTERN_SCAN)) { +void ScanService::ResetToNonTrustMode() +{ + std::unique_lock lock(scanControlInfoMutex); + scanTrustMode = false; +} + +bool ScanService::IsScanTrustMode() const +{ + std::unique_lock lock(scanControlInfoMutex); + return scanTrustMode; +} + +void ScanService::AddScanTrustSceneId(int sceneId) +{ + std::unique_lock lock(scanControlInfoMutex); + scanTrustSceneIds.emplace(sceneId); +} + +void ScanService::ClearScanTrustSceneIds() +{ + std::unique_lock lock(scanControlInfoMutex); + scanTrustSceneIds.clear(); +} + +bool ScanService::IsInScanTrust(int sceneId) const +{ + std::unique_lock lock(scanControlInfoMutex); + if (scanTrustSceneIds.find(sceneId) != scanTrustSceneIds.end()) { + return true; + } + + return false; +} + +void ScanService::SetMovingFreezeState(bool state) +{ + std::unique_lock lock(scanControlInfoMutex); + isAbsFreezeState = state; +} + +bool ScanService::IsMovingFreezeState() const +{ + std::unique_lock lock(scanControlInfoMutex); + return isAbsFreezeState; +} + +void ScanService::SetMovingFreezeScaned(bool scanned) +{ + std::unique_lock lock(scanControlInfoMutex); + isAbsFreezeScaned = scanned; +} + +bool ScanService::IsMovingFreezeScaned() const +{ + std::unique_lock lock(scanControlInfoMutex); + return isAbsFreezeScaned; +} + +ErrCode ScanService::ApplyTrustListPolicy(ScanType scanType) +{ + LOGI("Enter ScanService::ApplyTrustListPolicy."); + ErrCode policyResult = WIFI_OPT_SUCCESS; + + SetScanTrustMode(); + policyResult = AllowScanByType(scanType); + if (policyResult != WIFI_OPT_SUCCESS) { + WIFI_LOGW("AllowScanByType failed."); + } + ResetToNonTrustMode(); + WIFI_LOGI("apply trust list policy, ErrCode=%{public}d", static_cast(policyResult)); + + return policyResult; +} + +ErrCode ScanService::ApplyScanPolices(ScanType type) +{ + LOGI("Enter ScanService::ApplyScanPolices, type: %{public}d", type); + /* Obtains app parameters and scenario status parameters. */ + auto appPackageName = WifiSettings::GetInstance().GetAppPackageName(); + auto trustListPolicies = WifiSettings::GetInstance().ReloadTrustListPolicies(); + auto movingFreezePolicy = WifiSettings::GetInstance().ReloadMovingFreezePolicy(); + ErrCode rlt = WIFI_OPT_SUCCESS; + if (appPackageName.empty()) { + rlt = AllowScanByType(type); + WIFI_LOGW("appPackageName empty, apply scan polices rlt: %{public}d.", static_cast(rlt)); + if (scanResultBackup != -1 && rlt == WIFI_OPT_MOVING_FREEZE_CTRL) { + mScanSerivceCallbacks.OnScanFinishEvent(scanResultBackup); + } + return rlt; + } + + /* Generates an scene id list based on appPackageName. */ + ClearScanTrustSceneIds(); + for (auto &policy : trustListPolicies) { + if (IsPackageInTrustList(policy.trustList, policy.sceneId, appPackageName)) { + AddScanTrustSceneId(policy.sceneId); + } + } + const int movingFreezeSceneId = -1; + if (IsPackageInTrustList(movingFreezePolicy.trustList, movingFreezeSceneId, appPackageName)) { + AddScanTrustSceneId(movingFreezeSceneId); + } + + rlt = ApplyTrustListPolicy(type); + if (rlt != WIFI_OPT_SUCCESS) { + if (scanResultBackup != -1 && rlt == WIFI_OPT_MOVING_FREEZE_CTRL) { + WIFI_LOGE("trust list policy, but moving freeze ctrl failed."); + mScanSerivceCallbacks.OnScanFinishEvent(scanResultBackup); + } + return rlt; + } + WIFI_LOGD("apply scan policies result: scan control ok."); + return WIFI_OPT_SUCCESS; +} + +bool ScanService::AllowExternScanByThermal() +{ + WIFI_LOGI("Enter ScanService::AllowExternScanByThermal.\n"); + + auto level = WifiSettings::GetInstance().GetThermalLevel(); + static const int THERMAL_LEVEL_HOT = 3; + if (level >= THERMAL_LEVEL_HOT) { + WIFI_LOGW("ScanService::AllowExternScanByThermal, level=%{public}d is higher than hot\n", level); + return false; + } + return true; +} + +bool ScanService::AllowExternScanByForbid(int staScene, ScanMode scanMode) +{ + WIFI_LOGI("Enter ScanService::AllowExternScanByForbid, staScene:%{public}d, scanMode:%{public}d.", + staScene, scanMode); + + if (IsExternScanning()) { + if (!AllowScanDuringScanning(scanMode)) { + return false; + } + if (!AllowScanDuringScanning(ScanMode::ALL_EXTERN_SCAN)) { + return false; + } + } + + int state = WifiSettings::GetInstance().GetScreenState(); + if (state == MODE_STATE_CLOSE) { + if (!AllowScanDuringScreenOff(scanMode)) { + return false; + } + if (!AllowScanDuringScreenOff(ScanMode::ALL_EXTERN_SCAN)) { + return false; + } + } + if (!AllowScanDuringStaScene(staScene, scanMode)) { return false; } + if (!AllowScanDuringStaScene(staScene, ScanMode::ALL_EXTERN_SCAN)) { + return false; + } + if (!AllowScanDuringCustomScene(scanMode)) { + return false; + } + if (!AllowScanDuringCustomScene(ScanMode::ALL_EXTERN_SCAN)) { + return false; + } + + return true; +} + +bool ScanService::AllowExternScanByInterval(int appId, int staScene, ScanMode scanMode) +{ + WIFI_LOGI("Enter ScanService::AllowExternScanByInterval.\n"); + + if (!AllowExternScanByIntervalMode(appId, staScene, scanMode)) { + return false; + } + if (!AllowExternScanByIntervalMode(appId, staScene, ScanMode::ALL_EXTERN_SCAN)) { + return false; + } + if (!AllowExternScanByIntervalMode(appId, SCAN_SCENE_FREQUENCY_ORIGIN, scanMode)) { + return false; + } + if (!AllowExternScanByIntervalMode(appId, SCAN_SCENE_FREQUENCY_ORIGIN, ScanMode::ALL_EXTERN_SCAN)) { + return false; + } + int noChargerPlugModeState = WifiSettings::GetInstance().GetNoChargerPlugModeState(); + if (noChargerPlugModeState == MODE_STATE_OPEN) { + WIFI_LOGI("No charger plug mode state."); + if (!AllowExternScanByIntervalMode(appId, SCAN_SCENE_FREQUENCY_CUSTOM, scanMode)) { + return false; + } + if (!AllowExternScanByIntervalMode(appId, SCAN_SCENE_FREQUENCY_CUSTOM, ScanMode::ALL_EXTERN_SCAN)) { + return false; + } + } if (!AllowExternScanByCustomScene(appId, scanMode)) { return false; } @@ -1233,15 +1489,22 @@ int ScanService::GetStaScene() case static_cast(OperateResState::CONNECT_OBTAINING_IP): return SCAN_SCENE_OBTAINING_IP; + case static_cast(OperateResState::CONNECT_ASSOCIATING): + return SCAN_SCENE_ASSOCIATING; + + case static_cast(OperateResState::CONNECT_ASSOCIATED): + return SCAN_SCENE_ASSOCIATED; + default: return SCAN_SCENE_MAX; } } -bool ScanService::IsExternScanning() +bool ScanService::IsExternScanning() const { WIFI_LOGI("Enter ScanService::IsExternScanning.\n"); + std::unique_lock lock(scanConfigMapMutex); for (auto iter = scanConfigMap.begin(); iter != scanConfigMap.end(); ++iter) { if (iter->second.externFlag) { return true; @@ -1250,6 +1513,19 @@ bool ScanService::IsExternScanning() return false; } +bool ScanService::IsScanningWithParam() +{ + WIFI_LOGI("Enter ScanService::IsScanningWithParam.\n"); + + std::unique_lock lock(scanConfigMapMutex); + for (auto iter = scanConfigMap.begin(); iter != scanConfigMap.end(); ++iter) { + if (iter->second.scanningWithParamFlag) { + return true; + } + } + return false; +} + void ScanService::GetAllowBandFreqsControlInfo(ScanBandType &scanBand, std::vector &freqs) { WIFI_LOGI("Enter ScanService::GetAllowBandFreqsControlInfo.\n"); @@ -1270,14 +1546,17 @@ void ScanService::GetAllowBandFreqsControlInfo(ScanBandType &scanBand, std::vect if (!AllowScanDuringCustomScene(ScanMode::BAND_5GHZ_SCAN)) { allow5Ghz = false; } - auto forbidIter = scanControlInfo.scanForbidMap.find(SCAN_SCENE_ALL); - if (forbidIter != scanControlInfo.scanForbidMap.end()) { - for (auto iter = forbidIter->second.begin(); iter != forbidIter->second.end(); ++iter) { - if (iter->scanMode == ScanMode::BAND_24GHZ_SCAN) { - allow24Ghz = false; - } - if (iter->scanMode == ScanMode::BAND_5GHZ_SCAN) { - allow5Ghz = false; + + { + std::unique_lock lock(scanControlInfoMutex); + for (auto iter = scanControlInfo.scanForbidList.begin(); iter != scanControlInfo.scanForbidList.end(); ++iter) { + if (iter->scanScene == SCAN_SCENE_ALL) { + if (iter->scanMode == ScanMode::BAND_24GHZ_SCAN) { + allow24Ghz = false; + } + if (iter->scanMode == ScanMode::BAND_5GHZ_SCAN) { + allow5Ghz = false; + } } } } @@ -1351,7 +1630,7 @@ void ScanService::Delete24GhzFreqs(std::vector &freqs) auto iter = freqs.begin(); while (iter != freqs.end()) { if (*iter < FREQS_24G_MAX_VALUE) { - freqs.erase(iter); + iter = freqs.erase(iter); } else { ++iter; } @@ -1367,7 +1646,7 @@ void ScanService::Delete5GhzFreqs(std::vector &freqs) auto iter = freqs.begin(); while (iter != freqs.end()) { if (*iter > FREQS_5G_MIN_VALUE) { - freqs.erase(iter); + iter = freqs.erase(iter); } else { ++iter; } @@ -1412,22 +1691,10 @@ bool ScanService::GetHiddenNetworkSsidList(std::vector &hiddenNetwo } } + WIFI_LOGI("Find %{public}d hidden NetworkSsid.\n", (int)hiddenNetworkSsid.size()); return true; } -void ScanService::SetCustomScene(int scene, time_t currentTime) -{ - WIFI_LOGI("Enter ScanService::SetCustomScene.\n"); - - if (scene < static_cast(SCAN_SCENE_DEEP_SLEEP) || scene >= static_cast(SCAN_SCENE_ALL)) { - WIFI_LOGE("invalid CustomScene status:%{public}d", scene); - return; - } - customSceneTimeMap[scene] = currentTime; - - return; -} - void ScanService::ClearScanControlValue() { WIFI_LOGI("Enter ScanService::ClearScanControlValue.\n"); @@ -1446,34 +1713,47 @@ void ScanService::SetStaCurrentTime() time_t now = time(0); staCurrentTime = now; + int state = WifiSettings::GetInstance().GetScreenState(); + if (state == MODE_STATE_CLOSE) { + if (ApplyScanPolices(ScanType::SCAN_TYPE_PNO) != WIFI_OPT_SUCCESS) { + EndPnoScan(); + pnoScanFailedNum = 0; + pScanStateMachine->StopTimer(static_cast(RESTART_PNO_SCAN_TIMER)); + } + } return; } -bool ScanService::AllowScanDuringScanning(ScanMode scanMode) +bool ScanService::AllowScanDuringScanning(ScanMode scanMode) const { WIFI_LOGI("Enter ScanService::AllowScanDuringScanning.\n"); - auto forbidIter = scanControlInfo.scanForbidMap.find(SCAN_SCENE_SCANNING); - if (forbidIter != scanControlInfo.scanForbidMap.end()) { - for (auto iter = forbidIter->second.begin(); iter != forbidIter->second.end(); ++iter) { - if (iter->scanMode == scanMode) { - return false; - } + std::unique_lock lock(scanControlInfoMutex); + for (auto iter = scanControlInfo.scanForbidList.begin(); iter != scanControlInfo.scanForbidList.end(); ++iter) { + if (iter->scanScene == SCAN_SCENE_SCANNING && iter->scanMode == scanMode) { + WIFI_LOGW("scan not allow by scanning scene."); + return false; } } return true; } -bool ScanService::AllowScanDuringScreenOff(ScanMode scanMode) +bool ScanService::AllowScanDuringScreenOff(ScanMode scanMode) const { WIFI_LOGI("Enter ScanService::AllowScanDuringScreenOff.\n"); - auto forbidIter = scanControlInfo.scanForbidMap.find(SCAN_SCENE_SCREEN_OFF); - if (forbidIter != scanControlInfo.scanForbidMap.end()) { - for (auto iter = forbidIter->second.begin(); iter != forbidIter->second.end(); ++iter) { - if (iter->scanMode == scanMode) { - return false; - } + bool isTrustListMode = IsScanTrustMode(); + bool isInList = IsInScanTrust(SCAN_SCENE_SCREEN_OFF); + if (isTrustListMode && isInList) { + WIFI_LOGI("Trust list mode,sceneId(SCAN_SCENE_SCREEN_OFF) in the list,return true."); + return true; + } + + std::unique_lock lock(scanControlInfoMutex); + for (auto iter = scanControlInfo.scanForbidList.begin(); iter != scanControlInfo.scanForbidList.end(); ++iter) { + if (iter->scanScene == SCAN_SCENE_SCREEN_OFF && iter->scanMode == scanMode) { + WIFI_LOGW("scan not allow by screen off scene."); + return false; } } return true; @@ -1481,31 +1761,39 @@ bool ScanService::AllowScanDuringScreenOff(ScanMode scanMode) bool ScanService::AllowScanDuringStaScene(int staScene, ScanMode scanMode) { - WIFI_LOGI("Enter ScanService::AllowScanDuringStaScene.\n"); - - time_t now = time(0); + WIFI_LOGI("Enter ScanService::AllowScanDuringStaScene, staScene:%{public}d, scanMode:%{public}d", + staScene, scanMode); - auto forbidIter = scanControlInfo.scanForbidMap.find(staScene); - if (forbidIter != scanControlInfo.scanForbidMap.end()) { - for (auto iter = forbidIter->second.begin(); iter != forbidIter->second.end(); ++iter) { - /* forbid scan mode found in scan scene */ - if (iter->scanMode == scanMode) { - /* Unconditional scan control for forbidCount times */ - if (iter->forbidCount > 0) { - iter->forbidCount--; - return false; - } - /* forbidCount=0 and forbidTime=0, directly forbid scan */ - if (iter->forbidTime == 0) { - return false; - } - /* Scan interval less than forbidTime, forbid scan */ - if (iter->forbidTime > 0 && iter->forbidTime > now - staCurrentTime) { - return false; - } + time_t now = time(nullptr); + if (now < 0) { + WIFI_LOGW("time return invalid!\n."); + return false; + } + std::unique_lock lock(scanControlInfoMutex); + for (auto iter = scanControlInfo.scanForbidList.begin(); iter != scanControlInfo.scanForbidList.end(); ++iter) { + WIFI_LOGI("now - staCurrentTime:%{public}d, iter->forbidTime:%{public}d", int(now - staCurrentTime), + iter->forbidTime); + /* forbid scan mode found in scan scene. */ + if (iter->scanScene == staScene && iter->scanMode == scanMode) { + /* forbidCount=0 and forbidTime=0, directly forbid scan. */ + if ((iter->forbidTime == 0) && (iter->forbidCount == 0)) { + WIFI_LOGW("Scan is forbidden by staScene."); + return false; + } + /* Unconditional scan control for forbidCount times */ + if ((iter->forbidCount > 0) && (iter->forbidCount - staSceneForbidCount > 0)) { + WIFI_LOGW("Scan is forbidden in forbidCount."); + staSceneForbidCount++; + return false; + } + /* Scan interval less than forbidTime, forbid scan. */ + if ((iter->forbidTime > 0) && (now - staCurrentTime <= iter->forbidTime)) { + WIFI_LOGW("Scan is forbidden in forbidTime."); + return false; } } } + return true; } @@ -1513,31 +1801,47 @@ bool ScanService::AllowScanDuringCustomScene(ScanMode scanMode) { WIFI_LOGI("Enter ScanService::AllowScanDuringCustomScene.\n"); - time_t now = time(0); - auto customIter = customSceneTimeMap.begin(); - for (; customIter != customSceneTimeMap.end(); ++customIter) { - auto forbidIter = scanControlInfo.scanForbidMap.find(customIter->first); - if (forbidIter != scanControlInfo.scanForbidMap.end()) { - for (auto iter = forbidIter->second.begin(); iter != forbidIter->second.end(); ++iter) { - /* forbid scan mode found in scan scene */ - if (iter->scanMode == scanMode) { - /* Unconditional scan control for forbidCount times */ - if (iter->forbidCount > 0) { - iter->forbidCount--; - return false; - } - /* forbidCount=0 and forbidTime=0, directly forbid scan */ - if (iter->forbidTime == 0) { - return false; - } - /* Scan interval less than forbidTime, forbid scan */ - if (iter->forbidTime > 0 && iter->forbidTime > now - customIter->second) { - return false; - } - } + bool isTrustListMode = IsScanTrustMode(); + for (auto customIter = customSceneTimeMap.begin(); customIter != customSceneTimeMap.end(); ++customIter) { + if (isTrustListMode && IsInScanTrust(customIter->first)) { + WIFI_LOGD("Trust list mode,sceneId(%{public}d) in the list, continue.", customIter->first); + continue; + } + + if (!AllowCustomSceneCheck(customIter, scanMode)) { + return false; + } + } + return true; +} + +bool ScanService::AllowCustomSceneCheck(const std::map::const_iterator &customIter, ScanMode scanMode) +{ + std::unique_lock lock(scanControlInfoMutex); + for (auto iter = scanControlInfo.scanForbidList.begin(); iter != scanControlInfo.scanForbidList.end(); ++iter) { + if (iter->scanScene == customIter->first && iter->scanMode == scanMode) { + /* forbidCount=0 and forbidTime=0, directly forbid scan. */ + if ((iter->forbidTime == 0) && (iter->forbidCount == 0)) { + WIFI_LOGW("Scan is forbidden by staScene."); + return false; + } + /* Unconditional scan control for forbidCount times. */ + if (iter->forbidCount > 0 && iter->forbidCount - customSceneForbidCount > 0) { + customSceneForbidCount++; + WIFI_LOGW("Unconditional scan control for forbidCount times, customSceneForbidCount:%{public}d.", + customSceneForbidCount); + return false; + } + /* Scan interval less than forbidTime, forbid scan. */ + time_t now = time(nullptr); + if (iter->forbidTime > 0 && iter->forbidTime > now - customIter->second) { + WIFI_LOGW("Scan interval less than forbidTime, forbid scan, forbidTime:%{public}d.", + iter->forbidTime); + return false; } } } + return true; } @@ -1545,14 +1849,19 @@ bool ScanService::AllowExternScanByIntervalMode(int appId, int scanScene, ScanMo { WIFI_LOGI("Enter ScanService::AllowExternScanByIntervalMode.\n"); + bool isTrustListMode = IsScanTrustMode(); + if (isTrustListMode && IsInScanTrust(scanScene)) { + WIFI_LOGD("Trust list mode,sceneId(%{public}d) in the list, return true.", scanScene); + return true; + } + + std::unique_lock lock(scanControlInfoMutex); for (auto intervalListIter = scanControlInfo.scanIntervalList.begin(); intervalListIter != scanControlInfo.scanIntervalList.end(); ++intervalListIter) { - WIFI_LOGD( - "scanScene:%{public}d, scanMode:%{public}d", intervalListIter->scanScene, intervalListIter->scanMode); /* Determine whether control is required in the current scene and scan mode. */ if (intervalListIter->scanScene == scanScene && intervalListIter->scanMode == scanMode) { - /* If a single application is distinguished */ + /* If a single application is distinguished. */ if (intervalListIter->isSingle) { if (!AllowSingleAppScanByInterval(appId, *intervalListIter)) { return false; @@ -1562,7 +1871,6 @@ bool ScanService::AllowExternScanByIntervalMode(int appId, int scanScene, ScanMo return false; } } - break; } } return true; @@ -1572,101 +1880,47 @@ bool ScanService::AllowExternScanByCustomScene(int appId, ScanMode scanMode) { WIFI_LOGI("Enter ScanService::AllowExternScanByCustomScene.\n"); - auto customIter = customSceneTimeMap.begin(); - for (; customIter != customSceneTimeMap.end(); ++customIter) { - for (auto intervalListIter = scanControlInfo.scanIntervalList.begin(); - intervalListIter != scanControlInfo.scanIntervalList.end(); - ++intervalListIter) { - /* Determine whether control is required in the current scene and scan mode. */ - if (intervalListIter->scanScene == customIter->first && intervalListIter->scanMode == scanMode) { - /* If a single application is distinguished */ - if (intervalListIter->isSingle) { - if (!AllowSingleAppScanByInterval(appId, *intervalListIter)) { - return false; - } - } else { - if (!AllowFullAppScanByInterval(appId, *intervalListIter)) { - return false; - } - } - break; - } + bool isTrustListMode = IsScanTrustMode(); + for (auto customIter = customSceneTimeMap.begin(); customIter != customSceneTimeMap.end(); ++customIter) { + if (isTrustListMode && IsInScanTrust(customIter->first)) { + WIFI_LOGD("Trust list mode,sceneId(%{public}d) in the list, continue.", customIter->first); + continue; } - } - return true; -} -bool ScanService::AllowSingleAppScanByInterval(int appId, ScanIntervalMode scanIntervalMode) -{ - WIFI_LOGI("Enter ScanService::AllowSingleAppScan.\n"); - - bool appIdExisted = false; - for (auto forbidListIter = appForbidList.begin(); forbidListIter != appForbidList.end(); ++forbidListIter) { - if (forbidListIter->appID == appId && - forbidListIter->scanIntervalMode.scanScene == scanIntervalMode.scanScene && - forbidListIter->scanIntervalMode.scanMode == scanIntervalMode.scanMode) { - appIdExisted = true; - } - } - /* If the appId is the first scan request, add it to appForbidList. */ - if (!appIdExisted) { - SingleAppForbid singleAppForbid; - singleAppForbid.appID = appId; - singleAppForbid.scanIntervalMode.scanScene = scanIntervalMode.scanScene; - singleAppForbid.scanIntervalMode.scanMode = scanIntervalMode.scanMode; - singleAppForbid.scanIntervalMode.interval = scanIntervalMode.interval; - singleAppForbid.scanIntervalMode.intervalMode = scanIntervalMode.intervalMode; - singleAppForbid.scanIntervalMode.count = scanIntervalMode.count; - appForbidList.push_back(singleAppForbid); - } - for (auto iter = appForbidList.begin(); iter != appForbidList.end(); ++iter) { - if (iter->appID == appId && iter->scanIntervalMode.scanScene == scanIntervalMode.scanScene && - iter->scanIntervalMode.scanMode == scanIntervalMode.scanMode) { - if (!ExternScanByInterval(appId, *iter)) { - return false; - } + if (!AllowExternCustomSceneCheck(customIter, appId, scanMode)) { + return false; } } return true; } -bool ScanService::AllowFullAppScanByInterval(int appId, ScanIntervalMode scanIntervalMode) +bool ScanService::AllowExternCustomSceneCheck(const std::map::const_iterator &customIter, int appId, + ScanMode scanMode) { - WIFI_LOGI("Enter ScanService::AllowFullAppScan.\n"); - - bool fullAppExisted = false; - for (auto fullAppForbidIter = fullAppForbidList.begin(); fullAppForbidIter != fullAppForbidList.end(); - ++fullAppForbidIter) { - if (fullAppForbidIter->scanIntervalMode.scanScene == scanIntervalMode.scanScene && - fullAppForbidIter->scanIntervalMode.scanMode == scanIntervalMode.scanMode) { - fullAppExisted = true; - } - } - if (!fullAppExisted) { - SingleAppForbid singleAppForbid; - singleAppForbid.scanIntervalMode.scanScene = scanIntervalMode.scanScene; - singleAppForbid.scanIntervalMode.scanMode = scanIntervalMode.scanMode; - singleAppForbid.scanIntervalMode.interval = scanIntervalMode.interval; - singleAppForbid.scanIntervalMode.intervalMode = scanIntervalMode.intervalMode; - singleAppForbid.scanIntervalMode.count = scanIntervalMode.count; - fullAppForbidList.push_back(singleAppForbid); - } - for (auto iter = fullAppForbidList.begin(); iter != fullAppForbidList.end(); ++iter) { - if (iter->scanIntervalMode.scanScene == scanIntervalMode.scanScene && - iter->scanIntervalMode.scanMode == scanIntervalMode.scanMode) { - if (!ExternScanByInterval(appId, *iter)) { + std::unique_lock lock(scanControlInfoMutex); + for (auto intervalListIter = scanControlInfo.scanIntervalList.begin(); + intervalListIter != scanControlInfo.scanIntervalList.end(); ++intervalListIter) { + /* Determine whether control is required in the current scene and scan mode. */ + if (intervalListIter->scanScene == customIter->first && intervalListIter->scanMode == scanMode && + intervalListIter->isSingle) { + /* If a single application is distinguished. */ + if (!AllowSingleAppScanByInterval(appId, *intervalListIter)) { return false; } + } else if (intervalListIter->scanScene == customIter->first && intervalListIter->scanMode == scanMode && + !intervalListIter->isSingle) { + if (!AllowFullAppScanByInterval(appId, *intervalListIter)) + return false; } } return true; } -bool ScanService::PnoScanByInterval(int &fixedScanCount, time_t &fixedScanTime, int &interval, int &count) +bool ScanService::PnoScanByInterval(int &fixedScanCount, time_t &fixedScanTime, int interval, int count) { WIFI_LOGI("Enter ScanService::PnoScanByInterval.\n"); - time_t now = time(0); + time_t now = time(nullptr); /* First scan */ if (fixedScanCount == 0) { fixedScanCount++; @@ -1700,33 +1954,27 @@ bool ScanService::SystemScanByInterval(int &expScanCount, int &interval, int &co return true; } -bool ScanService::ExternScanByInterval(int appID, SingleAppForbid &singleAppForbid) +bool ScanService::ExternScanByInterval(int appId, SingleAppForbid &singleAppForbid) { WIFI_LOGI("Enter ScanService::ExternScanByInterval.\n"); switch (singleAppForbid.scanIntervalMode.intervalMode) { case IntervalMode::INTERVAL_FIXED: - return AllowScanByIntervalFixed(singleAppForbid.fixedScanCount, - singleAppForbid.fixedCurrentTime, - singleAppForbid.scanIntervalMode.interval, - singleAppForbid.scanIntervalMode.count); + return AllowScanByIntervalFixed(singleAppForbid.fixedScanCount, singleAppForbid.fixedCurrentTime, + singleAppForbid.scanIntervalMode.interval, singleAppForbid.scanIntervalMode.count); case IntervalMode::INTERVAL_EXP: - return AllowScanByIntervalExp(singleAppForbid.expScanCount, - singleAppForbid.scanIntervalMode.interval, + return AllowScanByIntervalExp(singleAppForbid.expScanCount, singleAppForbid.scanIntervalMode.interval, singleAppForbid.scanIntervalMode.count); case IntervalMode::INTERVAL_CONTINUE: - return AllowScanByIntervalContinue(singleAppForbid.continueScanTime, - singleAppForbid.lessThanIntervalNum, - singleAppForbid.scanIntervalMode.interval, - singleAppForbid.scanIntervalMode.count); + return AllowScanByIntervalContinue(singleAppForbid.continueScanTime, singleAppForbid.lessThanIntervalCount, + singleAppForbid.scanIntervalMode.interval, singleAppForbid.scanIntervalMode.count); case IntervalMode::INTERVAL_BLOCKLIST: - return AllowScanByIntervalBlocklist(appID, - singleAppForbid.blockListScanTime, - singleAppForbid.lessThanIntervalNum, - singleAppForbid.scanIntervalMode.interval, + WIFI_LOGI("INTERVAL_BLOCKLIST IntervalMode.\n"); + return AllowScanByIntervalBlocklist(appId, singleAppForbid.blockListScanTime, + singleAppForbid.lessThanIntervalCount, singleAppForbid.scanIntervalMode.interval, singleAppForbid.scanIntervalMode.count); default: @@ -1734,11 +1982,81 @@ bool ScanService::ExternScanByInterval(int appID, SingleAppForbid &singleAppForb } } +bool ScanService::AllowSingleAppScanByInterval(int appId, ScanIntervalMode scanIntervalMode) +{ + WIFI_LOGI("Enter ScanService::AllowSingleAppScanByInterval.\n"); + + bool appIdExisted = false; + for (auto forbidListIter = appForbidList.begin(); forbidListIter != appForbidList.end(); ++forbidListIter) { + if (forbidListIter->appID == appId && + forbidListIter->scanIntervalMode.scanScene == scanIntervalMode.scanScene && + forbidListIter->scanIntervalMode.scanMode == scanIntervalMode.scanMode) { + appIdExisted = true; + } + } + /* If the appId is the first scan request, add it to appForbidList. */ + if (!appIdExisted) { + SingleAppForbid singleAppForbid; + singleAppForbid.appID = appId; + singleAppForbid.scanIntervalMode.scanScene = scanIntervalMode.scanScene; + singleAppForbid.scanIntervalMode.scanMode = scanIntervalMode.scanMode; + singleAppForbid.scanIntervalMode.interval = scanIntervalMode.interval; + singleAppForbid.scanIntervalMode.intervalMode = scanIntervalMode.intervalMode; + singleAppForbid.scanIntervalMode.count = scanIntervalMode.count; + appForbidList.push_back(singleAppForbid); + } + for (auto iter = appForbidList.begin(); iter != appForbidList.end(); ++iter) { + if (iter->appID == appId && iter->scanIntervalMode.scanScene == scanIntervalMode.scanScene && + iter->scanIntervalMode.scanMode == scanIntervalMode.scanMode) { + if (!ExternScanByInterval(appId, *iter)) { + WIFI_LOGI("AllowSingleAppScanByInterval:false."); + return false; + } + } + } + WIFI_LOGI("AllowSingleAppScanByInterval:true."); + return true; +} + +bool ScanService::AllowFullAppScanByInterval(int appId, ScanIntervalMode scanIntervalMode) +{ + WIFI_LOGI("Enter ScanService::AllowFullAppScanByInterval.\n"); + + bool fullAppExisted = false; + for (auto fullAppForbidIter = fullAppForbidList.begin(); fullAppForbidIter != fullAppForbidList.end(); + ++fullAppForbidIter) { + if (fullAppForbidIter->scanIntervalMode.scanScene == scanIntervalMode.scanScene && + fullAppForbidIter->scanIntervalMode.scanMode == scanIntervalMode.scanMode) { + fullAppExisted = true; + } + } + if (!fullAppExisted) { + SingleAppForbid singleAppForbid; + singleAppForbid.scanIntervalMode.scanScene = scanIntervalMode.scanScene; + singleAppForbid.scanIntervalMode.scanMode = scanIntervalMode.scanMode; + singleAppForbid.scanIntervalMode.interval = scanIntervalMode.interval; + singleAppForbid.scanIntervalMode.intervalMode = scanIntervalMode.intervalMode; + singleAppForbid.scanIntervalMode.count = scanIntervalMode.count; + fullAppForbidList.push_back(singleAppForbid); + } + for (auto iter = fullAppForbidList.begin(); iter != fullAppForbidList.end(); ++iter) { + if (iter->scanIntervalMode.scanScene == scanIntervalMode.scanScene && + iter->scanIntervalMode.scanMode == scanIntervalMode.scanMode) { + if (!ExternScanByInterval(appId, *iter)) { + WIFI_LOGI("AllowFullAppScanByInterval:false."); + return false; + } + } + } + WIFI_LOGI("AllowFullAppScanByInterval:true."); + return true; +} + bool ScanService::AllowScanByIntervalFixed(int &fixedScanCount, time_t &fixedScanTime, int &interval, int &count) { WIFI_LOGI("Enter ScanService::AllowScanByIntervalFixed.\n"); - time_t now = time(0); + time_t now = time(nullptr); /* First scan */ if (fixedScanCount == 0) { fixedScanCount++; @@ -1751,7 +2069,7 @@ bool ScanService::AllowScanByIntervalFixed(int &fixedScanCount, time_t &fixedSca fixedScanTime = now; return true; } - /** + /* * * Scan is forbidden because the scanning interval is less than interval * and the number of scan times exceeds count. */ @@ -1778,13 +2096,14 @@ bool ScanService::AllowScanByIntervalExp(int &expScanCount, int &interval, int & return true; } -bool ScanService::AllowScanByIntervalContinue( - time_t &continueScanTime, int &lessThanIntervalNum, int &interval, int &count) +bool ScanService::AllowScanByIntervalContinue(time_t &continueScanTime, int &lessThanIntervalCount, int &interval, + int &count) { WIFI_LOGI("Enter ScanService::AllowScanByIntervalContinue.\n"); - WIFI_LOGD("lessThanIntervalNum:%d, interval:%d, count:%d", lessThanIntervalNum, interval, count); - time_t now = time(0); + WIFI_LOGD("lessThanIntervalCount:%{public}d, interval:%{public}d, count:%{public}d", lessThanIntervalCount, + interval, count); + time_t now = time(nullptr); /* First scan */ if (continueScanTime == 0) { continueScanTime = now; @@ -1792,27 +2111,27 @@ bool ScanService::AllowScanByIntervalContinue( } /* If count is less than interval, the subsequent interval must be greater than interval. */ if (now - continueScanTime < interval) { - lessThanIntervalNum++; - if (lessThanIntervalNum < count) { + lessThanIntervalCount++; + if (lessThanIntervalCount < count) { continueScanTime = now; return true; } /* If the scanning interval is not exceeded continuously, the counter is cleared. */ - lessThanIntervalNum = 0; + lessThanIntervalCount = 0; return false; } /* If the scanning interval is not exceeded continuously, the counter is cleared. */ - lessThanIntervalNum = 0; + lessThanIntervalCount = 0; continueScanTime = now; return true; } bool ScanService::AllowScanByIntervalBlocklist( - int appId, time_t &blockListScanTime, int &lessThanIntervalNum, int &interval, int &count) + int appId, time_t &blockListScanTime, int &lessThanIntervalCount, int &interval, int &count) { WIFI_LOGI("Enter ScanService::AllowScanByIntervalBlocklist.\n"); - time_t now = time(0); + time_t now = time(nullptr); if (now - blockListScanTime >= interval) { for (auto iter = scanBlocklist.begin(); iter != scanBlocklist.end();) { if (*iter == appId) { @@ -1826,12 +2145,13 @@ bool ScanService::AllowScanByIntervalBlocklist( } /* If the app ID is in the blocklist, extern scan is forbidden. */ if (std::find(scanBlocklist.begin(), scanBlocklist.end(), appId) != scanBlocklist.end()) { - WIFI_LOGD("extern scan not allowed by blocklist"); + WIFI_LOGW("extern scan not allowed by blocklist"); return false; } /* First scan */ if (blockListScanTime == 0) { blockListScanTime = now; + WIFI_LOGW("blockListScanTime, first scan."); return true; } /** @@ -1839,9 +2159,10 @@ bool ScanService::AllowScanByIntervalBlocklist( * the user is added to the blocklist and cannot be scanned. */ if (now - blockListScanTime < interval) { - lessThanIntervalNum++; - if (lessThanIntervalNum < count) { + lessThanIntervalCount++; + if (lessThanIntervalCount < count) { blockListScanTime = now; + WIFI_LOGD("blockListScanTime, lessThanIntervalCount(%{public}d),return true.", lessThanIntervalCount); return true; } /** @@ -1849,10 +2170,68 @@ bool ScanService::AllowScanByIntervalBlocklist( * is greater than count, the user is blocklisted forbidding scanning. */ scanBlocklist.push_back(appId); + WIFI_LOGI("scanBlocklist.push_back(appId), return false."); return false; } blockListScanTime = now; return true; } + +bool ScanService::AllowScanByDisableScanCtrl() +{ + std::unique_lock lock(scanControlInfoMutex); + return !disableScanFlag; +} + +bool ScanService::AllowScanByMovingFreeze() +{ + LOGI("Enter ScanService::AllowScanByMovingFreeze.\n"); + + /* moving freeze trust mode. */ + bool isTrustListMode = IsScanTrustMode(); + if (isTrustListMode && IsInScanTrust(-1)) { + WIFI_LOGD("Trust list mode,sceneId(MovingFreeze) in the list, return true."); + return true; + } + + if (!IsMovingFreezeState()) { + WIFI_LOGD("It's not in the movingfreeze mode, return true."); + return true; + } + + if (!IsMovingFreezeScaned()) { + SetMovingFreezeScaned(true); + WIFI_LOGD("In movingfreeze mode, return true for the first scan."); + return true; + } else { + WIFI_LOGW("In movingfreeze mode, return false for the already scanned."); + return false; + } + + return true; +} + +bool ScanService::IsPackageInTrustList(const std::string &trustList, int sceneId, + const std::string &appPackageName) const +{ + std::vector trustPackages; + SplitString(trustList, "|", trustPackages); + + bool bFind = false; + for (const auto &package : trustPackages) { + if (package == appPackageName) { + WIFI_LOGD("IsPackageInTrustList=true"); + bFind = true; + break; + } + } + + if (!bFind) { + WIFI_LOGD("sceneId=%{public}d, appName=%{public}s trustList=%{public}s, not in the lists.", sceneId, + appPackageName.c_str(), trustList.c_str()); + } + + return bFind; +} } // namespace Wifi } // namespace OHOS diff --git a/services/wifi_standard/wifi_framework/wifi_manage/wifi_scan/scan_service.h b/wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_scan/scan_service.h old mode 100755 new mode 100644 similarity index 66% rename from services/wifi_standard/wifi_framework/wifi_manage/wifi_scan/scan_service.h rename to wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_scan/scan_service.h index 04c2d04abfd556ef110623521b6c479ba5b63bdf..7a02b67c4e68f18190663a24626cc94afbe9eba0 --- a/services/wifi_standard/wifi_framework/wifi_manage/wifi_scan/scan_service.h +++ b/wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_scan/scan_service.h @@ -15,24 +15,24 @@ #ifndef OHOS_WIFI_SCAN_SERVICE_H #define OHOS_WIFI_SCAN_SERVICE_H -#include #include +#include +#include #include +#include +#include #include "iscan_service_callbacks.h" -#include "wifi_log.h" -#include "wifi_error_no.h" #include "define.h" +#include "wifi_scan_msg.h" +#include "wifi_errcode.h" #include "scan_common.h" #include "scan_monitor.h" #include "scan_state_machine.h" -#include "wifi_internal_msg.h" -#include "log_helper.h" namespace OHOS { namespace Wifi { const int DISCONNECTED_SCAN_INTERVAL = 20 * 60 * 1000; const int RESTART_PNO_SCAN_TIME = 5 * 1000; -const int SCREEN_CLOSED = 2; const int FREQS_24G_MAX_VALUE = 2500; const int FREQS_5G_MIN_VALUE = 5000; const int SECOND_TO_MICRO_SECOND = 1000000; @@ -43,10 +43,6 @@ const int CUSTOM_SCAN_SCENE = 2; const int SCREEN_SCAN_SCENE = 3; const int OTHER_SCAN_SCENE = 4; const int SYSTEM_SCAN_INIT_TIME = 20; -const int APP_FOREGROUND_SCAN = 0; -const int APP_BACKGROUND_SCAN = 1; -const int SYS_FOREGROUND_SCAN = 2; -const int SYS_BACKGROUND_SCAN = 3; class ScanService { FRIEND_GTEST(ScanService); @@ -65,6 +61,12 @@ public: * */ virtual void UnInitScanService(); + /** + * @Description Registers the callback function of the scanning module to the interface service. + * + * @param scanSerivceCallbacks callback function + */ + virtual void RegisterScanCallbacks(const IScanSerivceCallbacks &iScanSerivceCallbacks); /** * @Description Start a complete Wi-Fi scan. * @@ -79,6 +81,13 @@ public: * @return success: WIFI_OPT_SUCCESS, failed: WIFI_OPT_FAILED */ virtual ErrCode ScanWithParam(const WifiScanParams ¶ms); + /** + * @Description Disable/Restore the scanning operation. + * + * * @param params - disable or not. + * @return WIFI_OPT_SUCCESS: success, WIFI_OPT_FAILED: failed + */ + ErrCode DisableScan(bool disable); /** * @Description Starting a Single Scan. * @@ -86,6 +95,10 @@ public: * @return success: true, failed: false */ bool SingleScan(ScanConfig &scanConfig); + /** + * @Description Start PNO scanning + * @return success: true, failed: false + */ bool BeginPnoScan(); /** * @Description Start PNO scanning @@ -122,15 +135,19 @@ public: /** * @Description Screen State (On/Off) Change Handler * - * @param screenOn - screen state[in] */ - virtual void HandleScreenStatusChanged(bool screenOn); + virtual void HandleScreenStatusChanged(); /** * @Description STA status change processing * * @param state - STA state[in] */ virtual void HandleStaStatusChanged(int status); + /** + * @Description movingfreeze status change processing + * + */ + virtual void HandleMovingFreezeChanged(); /** * @Description custom scene status change processing * @@ -138,24 +155,18 @@ public: * @param customSceneStatus custom scene status[in] */ virtual void HandleCustomStatusChanged(int customScene, int customSceneStatus); - /** - * @Description Sets the type of the app to be operated. + * @Description Get custom scene state. * - * @param appMode - Type of the app to be scanned. + * @param customState custom scene state map[out] + * @return */ - virtual void SetOperateAppMode(int appMode); + virtual void HandleGetCustomSceneState(std::map& sceneMap) const; /** * @Description Query and save the scan control policy. * */ virtual void GetScanControlInfo(); - /** - * @Description Obtain the scenario set by the customer through changeState. - * - * @param scene - Scenario value corresponding to the scenario - */ - virtual void SetCustomScene(int scene, time_t currentTime); /** * @Description When scanning control changes, the count data needs to be cleared. * @@ -173,39 +184,51 @@ private: using PnoScanInfoHandlerMap = std::map; IScanSerivceCallbacks mScanSerivceCallbacks; - ScanStateMachine *pScanStateMachine; /* Scanning state machine pointer */ - ScanMonitor *pScanMonitor; /* Scanning Monitor Pointer */ - bool scanStartedFlag; /* The scanning is started */ + ScanStateMachine *pScanStateMachine; /* Scanning state machine pointer */ + ScanMonitor *pScanMonitor; /* Scanning Monitor Pointer */ + bool scanStartedFlag; /* The scanning is started */ ScanInfoHandlerMap scanInfoHandlerMap; /* Map of obtaining the scanning result */ PnoScanInfoHandlerMap pnoScanInfoHandlerMap; /* Map of obtaining PNO scanning results */ - ScanConfigMap scanConfigMap; /* Save Scan Configuration */ - int scanConfigStoreIndex; /* Index for saving the scan configuration */ - int64_t pnoScanStartTime; /* PNO scanning start time */ - bool isScreenOn; /* Screen state */ - int staStatus; /* STA state */ - bool isPnoScanBegined; /* The PNO scanning has been started */ - bool autoNetworkSelection; /* Automatic network selection */ - int64_t lastSystemScanTime; /* Last System Scan Time */ - int pnoScanFailedNum; /* Number of PNO Scan Failures */ - ScanControlInfo scanControlInfo; /* Scan Control Policy */ - int operateAppMode; /* Operation app type */ - std::vector freqs2G; /* The support frequencys for 2.4G */ - std::vector freqs5G; /* The support frequencys for 5G */ - std::vector freqsDfs; /* The support frequencys for DFS */ - SystemScanIntervalMode systemScanIntervalMode; /* Store system scan data */ - PnoScanIntervalMode pnoScanIntervalMode; /* Store pno scan data */ - int customScene; /* Customer-defined scenario */ - time_t staCurrentTime; /* Indicates the time when the STA enters the STA scenario */ + ScanConfigMap scanConfigMap; /* Save Scan Configuration */ + int scanConfigStoreIndex; /* Index for saving the scan configuration */ + int64_t pnoScanStartTime; /* PNO scanning start time */ + int staStatus; /* STA state */ + bool isPnoScanBegined; /* The PNO scanning has been started */ + bool autoNetworkSelection; /* Automatic network selection */ + int64_t lastSystemScanTime; /* Last System Scan Time */ + int pnoScanFailedNum; /* Number of PNO Scan Failures */ + ScanControlInfo scanControlInfo; /* Scan Control Policy */ + bool disableScanFlag; /* Disable Scan Flag. */ + std::vector freqs2G; /* The support frequencys for 2.4G */ + std::vector freqs5G; /* The support frequencys for 5G */ + std::vector freqsDfs; /* The support frequencys for DFS */ + SystemScanIntervalMode systemScanIntervalMode; /* Store system scan data */ + PnoScanIntervalMode pnoScanIntervalMode; /* Store pno scan data */ + time_t staCurrentTime; /* Indicates the time when the STA enters the STA scenario */ time_t customCurrentTime; /* Indicates the time when the STA enters the Customer-defined scenario */ - std::vector appForbidList; /* Store extern app scan data */ - std::vector scanBlocklist; /* - * If the number of consecutive count times is less than - * the value of interval, the user is added to the blocklist - * and cannot be scanned. - */ - std::vector fullAppForbidList; /* Stores data that is scanned and controlled regardless of - applications. */ - std::map customSceneTimeMap; /* Record the time when a scene is entered. */ + std::vector appForbidList; /* Store extern app scan data */ + /* + * If the number of consecutive count times is less than the value of + * interval, the user is added to the blocklist and cannot be scanned. + */ + std::vector scanBlocklist; + /* Stores data that is scanned and controlled regardless of applications. */ + std::vector fullAppForbidList; + std::map customSceneTimeMap; /* Record the time when a scene is entered. */ + int staSceneForbidCount; + int customSceneForbidCount; + mutable std::mutex scanConfigMapMutex; + mutable std::mutex scanControlInfoMutex; + enum class ScanType { + SCAN_TYPE_EXTERN = 0, + SCAN_TYPE_SYSTEMTIMER, + SCAN_TYPE_PNO, + }; + bool scanTrustMode; /* scan trustlist mode */ + std::unordered_set scanTrustSceneIds; /* scan scene ids */ + bool isAbsFreezeState; /* absolute freeze state. */ + bool isAbsFreezeScaned; /* scanned in freeze state. */ + int scanResultBackup; /* scan result backup. */ /** * @Description Obtains the frequency of a specified band. @@ -246,7 +269,7 @@ private: * @param scanInfoList - scan result list[in] * @return success: true, failed: false */ - bool StoreUserScanInfo(const StoreScanConfig &scanConfig, const std::vector &scanInfoList); + bool StoreUserScanInfo(const StoreScanConfig &scanConfig, std::vector &scanInfoList); /** * @Description Sends the scanning result to the interface service, * which then sends the scanning result to the connection @@ -255,14 +278,16 @@ private: * @param scanInfoList - scan result list[in] */ void ReportScanInfos(std::vector &interScanList); + /** - * @Description Convert the scanning result to the format of the interface service. + * @Description Sends the store scanning result to the interface service, + * which then sends the store scanning result to the connection + * management module for processing. * * @param scanInfoList - scan result list[in] - * @param scanInfoList - Converted list[out] */ - void ConvertScanInfos( - const std::vector &interScanList, std::vector &scanInfoList); + void ReportStoreScanInfos(std::vector &interScanList); + /** * @Description Enter the PNO scanning message body. * @@ -321,36 +346,120 @@ private: * */ void RestartPnoScanTimeOut(); - /** - * @Description Querying the screen status. - * - */ - void GetScreenState(); /** * @Description Determines whether external scanning is allowed based on the scanning policy. * - * @param appId - ID of the app to be scanned.[in] * @return success: true, failed: false */ - bool AllowExternScan(int appId); + ErrCode AllowExternScan(); /** * @Description Determine whether to allow scheduled system scanning. * * @return success: true, failed: false */ - bool AllowSystemTimerScan(); + ErrCode AllowSystemTimerScan(); /** * @Description Determines whether to allow PNO scanning based on the scanning policy. * * @return success: true, failed: false */ - bool AllowPnoScan(); + ErrCode AllowPnoScan(); /** + * @Description Determines whether to allow scanning based on the scanning type.. + * + * @param scanType - scan type: 0 - Extern; 1 - SystemTimer 2 Pno + * @return true: allow, false: not allowed. + */ + ErrCode AllowScanByType(ScanType scanType); + /** + * @Description Set the current mode to trust list mode. + * + */ + void SetScanTrustMode(); + /** + * @Description Reset to non scan trust list mode. + * + */ + void ResetToNonTrustMode(); + /** + * @Description Is it the trust list mode? + * + * @param sceneId - current scene id[out]. + * @return true: success, false: failed + */ + bool IsScanTrustMode() const; + /** + * @Description Add the scene id to trust list. + * Assume that the scene id of moving freeze is -1. + * + * @param sceneId - scene id. + */ + void AddScanTrustSceneId(int sceneId); + /** + * @Description Clear trust list. + * + */ + void ClearScanTrustSceneIds(); + /** + * @Description Is sceneId in trust list. + * + * @param sceneId - scene id. + */ + bool IsInScanTrust(int sceneId) const; + /** + * @Description Set the moving freeze status by state. + * + * @param state - state value. + */ + void SetMovingFreezeState(bool state); + /** + * @Description Is it the moving freeze state? + * + * @return true: success, false: failed + */ + bool IsMovingFreezeState() const; + /** + * @Description Set the moving freeze state to scanned. + * + * @param scanned - scanned flag. + */ + void SetMovingFreezeScaned(bool scanned); + /** + * @Description Whether scanned in moving freeze state.? + * + */ + bool IsMovingFreezeScaned() const; + /** + * @Description Apply trustlists scanning policies. + * + * @param scanType - scan type: 0 - Extern; 1 - SystemTimer 2 Pno + * @return true: success, false: failed + */ + ErrCode ApplyTrustListPolicy(ScanType scanType); + /* * + * @Description Apply trustlists and moving freeze scanning policies. + * + * @param scanType - type: 0 - Extern; 1 - SystemTimer 2 Pno + * @return WIFI_OPT_SUCCESS: success, + * WIFI_OPT_FAILED: general scan control fail, + * WIFI_OPT_MOVING_FREEZE_CTRL: moving freeze scan control fail. + */ + ErrCode ApplyScanPolices(ScanType type); + /* * * @Description Obtains the current screen. * * @return success: ScanScene, failed: SCAN_SCENE_MAX */ int GetStaScene(); + + /** + * @Description Determine whether scanning is allowed and scan the control policy through thermal level. + * + * @return true - allow extern scan + * @return false - not allow extern scan + */ + bool AllowExternScanByThermal(); + /** * @Description Determine whether scanning is allowed and scan the control policy through forbidMap. * @@ -375,7 +484,13 @@ private: * * @return success: true, failed: false */ - bool IsExternScanning(); + bool IsExternScanning() const; + /** + * @Description Indicates whether scanning with parameter. + * + * @return success: true, failed: false + */ + bool IsScanningWithParam(); /** * @Description Adjust the frequency band and frequency based on the scanning policy. * @@ -409,12 +524,6 @@ private: * @param freqs - frequency list[in] */ void Delete5GhzFreqs(std::vector &freqs); - /** - * @Description Obtains the type of the app to be operated. - * - * @return success: ScanMode, failed: others - */ - ScanMode GetOperateAppMode(); /** * @Description Get the ssid of saved networks. * @@ -445,7 +554,7 @@ private: * @return true - success * @return false - failed */ - bool AllowScanDuringScanning(ScanMode scanMode); + bool AllowScanDuringScanning(ScanMode scanMode) const; /** * @Description Check whether the scan mode can be used during screen off under the forbid mode control. * @@ -453,7 +562,7 @@ private: * @return true - success * @return false - failed */ - bool AllowScanDuringScreenOff(ScanMode scanMode); + bool AllowScanDuringScreenOff(ScanMode scanMode) const; /** * @Description * @@ -509,16 +618,16 @@ private: * @return true - success * @return false - failed */ - bool PnoScanByInterval(int &fixedScanCount, time_t &fixedScanTime, int &interval, int &count); + bool PnoScanByInterval(int &fixedScanCount, time_t &fixedScanTime, int interval, int count); /** - * @Description + * @Description Determines whether to allow extern scan based on scanInterval control mode. * - * @param appID Determines whether to allow extern scan based on scanInterval control mode. + * @param appId ID of the app to be scanned[in] * @param singleAppForbid Stored External Scan Parameters[in] * @return true * @return false */ - bool ExternScanByInterval(int appID, SingleAppForbid &singleAppForbid); + bool ExternScanByInterval(int appId, SingleAppForbid &singleAppForbid); /** * @Description Determine whether external scanning of a single application can be distinguished. * @@ -532,7 +641,7 @@ private: * @Description Check whether external scanning is allowed regardless of a single application. * * @param appId ID of the app to be scanned[in] - * @param scanIntervalMode scan control policy parameters[in] + * @param scanIntervalMode intervalMode scan control policy parameters[in] * @return true * @return false */ @@ -562,28 +671,70 @@ private: * @Description Determines whether external scanning is allowed in scanning control in INTERVAL_CONTINUE mode. * * @param continueScanTime INTERVAL_CONTINUE intervalMode scan time[in] - * @param lessThanIntervalNum INTERVAL_CONTINUE intervalMode scan count[in] + * @param lessThanIntervalCount INTERVAL_CONTINUE intervalMode scan count[in] * @param interval scan interval[in] * @param count scan count[in] * @return true * @return false */ - bool AllowScanByIntervalContinue(time_t &continueScanTime, int &lessThanIntervalNum, int &interval, int &count); + bool AllowScanByIntervalContinue(time_t &continueScanTime, int &lessThanIntervalCount, int &interval, int &count); /** * @Description Determines whether external scanning is allowed in scanning control in INTERVAL_BLOCKLIST mode. * * @param appId ID of the app to be scanned[in] * @param blockListScanTime INTERVAL_BLOCKLIST intervalMode scan time[in] - * @param lessThanIntervalNum INTERVAL_BLOCKLIST intervalMode scan count[in] + * @param lessThanIntervalCount INTERVAL_BLOCKLIST intervalMode scan count[in] * @param interval scan interval[in] * @param count scan count[in] * @return true * @return false */ bool AllowScanByIntervalBlocklist( - int appId, time_t &blockListScanTime, int &lessThanIntervalNum, int &interval, int &count); + int appId, time_t &blockListScanTime, int &lessThanIntervalCount, int &interval, int &count); + + /** + * @Description Determines whether scanning is allowed by disable scan control. + * + * @return true: allow, false: not allowed. + */ + bool AllowScanByDisableScanCtrl(); + + /** + * @Description Determines whether scanning is allowed in movingfreeze mode. + * + * @return true: allow, false: not allowed. + */ + bool AllowScanByMovingFreeze(); + + /** + * @Description Is the app in the trustlist? + * + * @param trustList trustlist[in] + * @param sceneId scene id[in] + * @param appPackageName app package name[in] + * @return true: in the trustlist, false: not in the trustlist. + */ + bool IsPackageInTrustList(const std::string& trustList, int sceneId, const std::string &appPackageName) const; + /* * + * @Description all scan check at custom check. + * + * @param customIter custom iterator[in] + * @param scanMode scene mode[in] + * @return true: allow, false: not allowed. + */ + bool AllowCustomSceneCheck(const std::map::const_iterator &customIter, ScanMode scanMode); + /* * + * @Description all extern scan check at custom check. + * + * @param customIter custom iterator[in] + * @param appId app id[in] + * @param scanMode scene mode[in] + * @return true: allow, false: not allowed. + */ + bool AllowExternCustomSceneCheck(const std::map::const_iterator &customIter, int appId, + ScanMode scanMode); }; } // namespace Wifi } // namespace OHOS -#endif \ No newline at end of file +#endif diff --git a/services/wifi_standard/wifi_framework/wifi_manage/wifi_scan/scan_state_machine.cpp b/wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_scan/scan_state_machine.cpp old mode 100755 new mode 100644 similarity index 93% rename from services/wifi_standard/wifi_framework/wifi_manage/wifi_scan/scan_state_machine.cpp rename to wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_scan/scan_state_machine.cpp index 776a5b779eed373a7fd2f58133b02aeff046db23..2f0a5ad35f8333c1fa5206d79d26fa750369f5e4 --- a/services/wifi_standard/wifi_framework/wifi_manage/wifi_scan/scan_state_machine.cpp +++ b/wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_scan/scan_state_machine.cpp @@ -1,5 +1,5 @@ /* - * Copyright (C) 2021 Huawei Device Co., Ltd. + * Copyright (C) 2021-2022 Huawei Device Co., Ltd. * 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 @@ -12,15 +12,19 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + #include "scan_state_machine.h" +#include "wifi_error_no.h" #include "wifi_logger.h" #include "wifi_settings.h" #include "wifi_sta_hal_interface.h" - -DEFINE_WIFILOG_SCAN_LABEL("ScanStateMachine"); +#include "wifi_common_util.h" namespace OHOS { namespace Wifi { +DEFINE_WIFILOG_SCAN_LABEL("ScanStateMachine"); +std::shared_mutex ScanStateMachine::lock; + ScanStateMachine::ScanStateMachine() : StateMachine("ScanStateMachine"), quitFlag(false), @@ -52,47 +56,58 @@ ScanStateMachine::~ScanStateMachine() if (initState != nullptr) { delete initState; + initState = nullptr; } if (hardwareReadyState != nullptr) { delete hardwareReadyState; + hardwareReadyState = nullptr; } if (commonScanState != nullptr) { delete commonScanState; + commonScanState = nullptr; } if (commonScanUnworkedState != nullptr) { delete commonScanUnworkedState; + commonScanUnworkedState = nullptr; } if (commonScanningState != nullptr) { delete commonScanningState; + commonScanningState = nullptr; } if (pnoScanState != nullptr) { delete pnoScanState; + pnoScanState = nullptr; } if (pnoScanHardwareState != nullptr) { delete pnoScanHardwareState; + pnoScanHardwareState = nullptr; } StopPnoScanHardware(); if (commonScanAfterPnoState != nullptr) { delete commonScanAfterPnoState; + commonScanAfterPnoState = nullptr; } if (pnoScanSoftwareState != nullptr) { delete pnoScanSoftwareState; + pnoScanSoftwareState = nullptr; } if (pnoSwScanFreeState != nullptr) { delete pnoSwScanFreeState; + pnoSwScanFreeState = nullptr; } if (pnoSwScanningState != nullptr) { delete pnoSwScanningState; + pnoSwScanningState = nullptr; } } @@ -110,11 +125,11 @@ bool ScanStateMachine::InitScanStateMachine() if (InitCommonScanState() != true) { return false; - }; + } if (InitPnoScanState() != true) { return false; - }; + } BuildScanStateTree(); SetFirstState(initState); @@ -146,8 +161,11 @@ ScanStateMachine::InitState::~InitState() void ScanStateMachine::InitState::GoInState() { WIFI_LOGI("Enter ScanStateMachine::InitState::GoInState.\n"); - pScanStateMachine->runningScans.clear(); - pScanStateMachine->waitingScans.clear(); + { + std::unique_lock guard(lock); + pScanStateMachine->runningScans.clear(); + pScanStateMachine->waitingScans.clear(); + } if (pScanStateMachine->quitFlag) { WIFI_LOGI("Notify finish ScanStateMachine.\n"); @@ -464,13 +482,11 @@ void ScanStateMachine::PnoScanHardware::GoInState() WIFI_LOGE("StartPnoScanHardware failed."); return; } - return; } void ScanStateMachine::PnoScanHardware::GoOutState() { WIFI_LOGI("Enter ScanStateMachine::PnoScanHardware::GoOutState.\n"); - return; } bool ScanStateMachine::PnoScanHardware::ExecuteStateMsg(InternalMessage *msg) @@ -514,7 +530,6 @@ ScanStateMachine::CommonScanAfterPno::CommonScanAfterPno(ScanStateMachine *paraS : State("CommonScanAfterPno") { pScanStateMachine = paraScanStateMachine; - return; } ScanStateMachine::CommonScanAfterPno::~CommonScanAfterPno() @@ -524,7 +539,6 @@ void ScanStateMachine::CommonScanAfterPno::GoInState() { WIFI_LOGI("Enter ScanStateMachine::CommonScanAfterPno::GoInState.\n"); pScanStateMachine->CommonScanAfterPnoProcess(); - return; } void ScanStateMachine::CommonScanAfterPno::GoOutState() @@ -534,8 +548,6 @@ void ScanStateMachine::CommonScanAfterPno::GoOutState() pScanStateMachine->StopTimer(static_cast(WAIT_SCAN_RESULT_TIMER)); } pScanStateMachine->remainWaitResultTimer = false; - - return; } bool ScanStateMachine::CommonScanAfterPno::ExecuteStateMsg(InternalMessage *msg) @@ -598,14 +610,12 @@ void ScanStateMachine::PnoScanSoftware::GoInState() if (!pScanStateMachine->StartNewSoftwareScan()) { WIFI_LOGE("failed to start new softwareScan"); } - return; } void ScanStateMachine::PnoScanSoftware::GoOutState() { WIFI_LOGI("Enter ScanStateMachine::PnoScanSoftware::GoOutState.\n"); pScanStateMachine->StopTimer(static_cast(SOFTWARE_PNO_SCAN_TIMER)); - return; } bool ScanStateMachine::PnoScanSoftware::ExecuteStateMsg(InternalMessage *msg) @@ -638,13 +648,11 @@ ScanStateMachine::PnoSwScanFree::~PnoSwScanFree() void ScanStateMachine::PnoSwScanFree::GoInState() { WIFI_LOGI("Enter ScanStateMachine::PnoSwScanFree::GoInState.\n"); - return; } void ScanStateMachine::PnoSwScanFree::GoOutState() { WIFI_LOGI("Enter ScanStateMachine::PnoSwScanFree::GoOutState.\n"); - return; } bool ScanStateMachine::PnoSwScanFree::ExecuteStateMsg(InternalMessage *msg) @@ -695,14 +703,12 @@ ScanStateMachine::PnoSwScanning::~PnoSwScanning() void ScanStateMachine::PnoSwScanning::GoInState() { WIFI_LOGI("Enter ScanStateMachine::PnoSwScanning::GoInState.\n"); - return; } void ScanStateMachine::PnoSwScanning::GoOutState() { WIFI_LOGI("Enter ScanStateMachine::PnoSwScanning::GoOutState.\n"); pScanStateMachine->StopTimer(static_cast(WAIT_SCAN_RESULT_TIMER)); - return; } bool ScanStateMachine::PnoSwScanning::ExecuteStateMsg(InternalMessage *msg) @@ -762,10 +768,11 @@ void ScanStateMachine::CommonScanRequestProcess(InternalMessage *interMessage) WIFI_LOGE("invalid scan type"); return; } - waitingScans.insert(std::pair(requestIndex, scanConfig)); + { + std::unique_lock guard(lock); + waitingScans.insert(std::pair(requestIndex, scanConfig)); + } StartNewCommonScan(); - - return; } bool ScanStateMachine::GetCommonScanRequestInfo( @@ -783,7 +790,6 @@ bool ScanStateMachine::GetCommonScanRequestInfo( WIFI_LOGE("GetCommonScanConfig failed."); return false; } - return true; } @@ -824,7 +830,6 @@ bool ScanStateMachine::GetCommonScanConfig(InternalMessage *interMessage, InterS scanConfig.maxScansCache = interMessage->GetIntFromMessage(); scanConfig.maxBackScanPeriod = interMessage->GetIntFromMessage(); scanConfig.scanStyle = interMessage->GetIntFromMessage(); - return true; } @@ -832,45 +837,46 @@ void ScanStateMachine::StartNewCommonScan() { WIFI_LOGI("Enter ScanStateMachine::StartNewCommonScan.\n"); - if (waitingScans.size() == 0) { - ContinuePnoScanProcess(); - return; - } - - ClearRunningScanSettings(); - bool hasFullScan = false; - /* Traverse the request list and combine parameters */ - std::map::iterator configIter = waitingScans.begin(); - for (; configIter != waitingScans.end(); ++configIter) { - runningScanSettings.scanStyle = MergeScanStyle(runningScanSettings.scanStyle, configIter->second.scanStyle); - - std::vector::iterator hiddenIter = configIter->second.hiddenNetworkSsid.begin(); - /* Remove duplicate hidden list */ - for (; hiddenIter != configIter->second.hiddenNetworkSsid.end(); ++hiddenIter) { - if (std::find(runningScanSettings.hiddenNetworkSsid.begin(), - runningScanSettings.hiddenNetworkSsid.end(), - *hiddenIter) != runningScanSettings.hiddenNetworkSsid.end()) { - continue; - } - runningScanSettings.hiddenNetworkSsid.push_back(*hiddenIter); + { + std::shared_lock guard(lock); + if (waitingScans.size() == 0) { + ContinuePnoScanProcess(); + return; } + ClearRunningScanSettings(); + bool hasFullScan = false; + /* Traverse the request list and combine parameters */ + std::map::iterator configIter = waitingScans.begin(); + for (; configIter != waitingScans.end(); ++configIter) { + runningScanSettings.scanStyle = MergeScanStyle(runningScanSettings.scanStyle, configIter->second.scanStyle); + std::vector::iterator hiddenIter = configIter->second.hiddenNetworkSsid.begin(); + /* Remove duplicate hidden list */ + for (; hiddenIter != configIter->second.hiddenNetworkSsid.end(); ++hiddenIter) { + if (std::find(runningScanSettings.hiddenNetworkSsid.begin(), + runningScanSettings.hiddenNetworkSsid.end(), + *hiddenIter) != runningScanSettings.hiddenNetworkSsid.end()) { + continue; + } + runningScanSettings.hiddenNetworkSsid.push_back(*hiddenIter); + } - if (!hasFullScan) { - /* When scanFreqs is empty, it means that scan all frequenties */ - if (configIter->second.scanFreqs.empty()) { - runningScanSettings.scanFreqs.clear(); - runningFullScanFlag = true; - hasFullScan = true; - } else { - std::vector::iterator freqIter = configIter->second.scanFreqs.begin(); - /* Repetitions are eliminated */ - for (; freqIter != configIter->second.scanFreqs.end(); ++freqIter) { - if (std::find(runningScanSettings.scanFreqs.begin(), - runningScanSettings.scanFreqs.end(), - *freqIter) != runningScanSettings.scanFreqs.end()) { - continue; + if (!hasFullScan) { + /* When scanFreqs is empty, it means that scan all frequenties */ + if (configIter->second.scanFreqs.empty()) { + runningScanSettings.scanFreqs.clear(); + runningFullScanFlag = true; + hasFullScan = true; + } else { + std::vector::iterator freqIter = configIter->second.scanFreqs.begin(); + /* Repetitions are eliminated */ + for (; freqIter != configIter->second.scanFreqs.end(); ++freqIter) { + if (std::find(runningScanSettings.scanFreqs.begin(), + runningScanSettings.scanFreqs.end(), + *freqIter) != runningScanSettings.scanFreqs.end()) { + continue; + } + runningScanSettings.scanFreqs.push_back(*freqIter); } - runningScanSettings.scanFreqs.push_back(*freqIter); } } } @@ -882,12 +888,11 @@ void ScanStateMachine::StartNewCommonScan() return; } + std::unique_lock guard(lock); runningScans.swap(waitingScans); waitingScans.clear(); SwitchState(commonScanningState); WIFI_LOGI("StartNewCommonScan success.\n"); - - return; } void ScanStateMachine::ClearRunningScanSettings() @@ -908,7 +913,7 @@ bool ScanStateMachine::StartSingleCommonScan(WifiScanParam &scanParam) for (auto hiddenIter = scanParam.hiddenNetworkSsid.begin(); hiddenIter != scanParam.hiddenNetworkSsid.end(); ++hiddenIter) { - WIFI_LOGI("hidden ssid is %{public}s.\n", hiddenIter->c_str()); + WIFI_LOGI("hidden ssid is %{public}s.\n", SsidAnonymize(*hiddenIter).c_str()); } WIFI_LOGI("Begin call Scan.\n"); @@ -924,7 +929,6 @@ bool ScanStateMachine::StartSingleCommonScan(WifiScanParam &scanParam) * fails */ StartTimer(static_cast(WAIT_SCAN_RESULT_TIMER), MAX_WAIT_SCAN_RESULT_TIME); - return true; } @@ -940,12 +944,12 @@ void ScanStateMachine::CommonScanWhenRunning(InternalMessage *interMessage) } if (ActiveCoverNewScan(scanConfig)) { + std::unique_lock guard(lock); runningScans.insert(std::pair(requestIndex, scanConfig)); } else { + std::unique_lock guard(lock); waitingScans.insert(std::pair(requestIndex, scanConfig)); } - - return; } bool ScanStateMachine::ActiveCoverNewScan(InterScanConfig &interScanConfig) @@ -992,7 +996,6 @@ bool ScanStateMachine::ActiveCoverNewScan(InterScanConfig &interScanConfig) return false; } } - return true; } @@ -1012,9 +1015,8 @@ void ScanStateMachine::CommonScanInfoProcess() if (scanStatusReportHandler) { scanStatusReportHandler(scanStatusReport); } + std::unique_lock guard(lock); runningScans.clear(); - - return; } void ScanStateMachine::GetSecurityTypeAndBand(std::vector &scanInfos) @@ -1077,8 +1079,6 @@ void ScanStateMachine::ReportStatusChange(ScanStatus status) if (scanStatusReportHandler) { scanStatusReportHandler(scanStatusReport); } - - return; } void ScanStateMachine::ReportScanInnerEvent(ScanInnerEventType innerEvent) @@ -1091,8 +1091,6 @@ void ScanStateMachine::ReportScanInnerEvent(ScanInnerEventType innerEvent) if (scanStatusReportHandler) { scanStatusReportHandler(scanStatusReport); } - - return; } void ScanStateMachine::ReportCommonScanFailed(int requestIndex) @@ -1109,8 +1107,6 @@ void ScanStateMachine::ReportCommonScanFailed(int requestIndex) if (scanStatusReportHandler) { scanStatusReportHandler(scanStatusReport); } - - return; } void ScanStateMachine::ReportCommonScanFailedAndClear(bool runningFlag) @@ -1120,9 +1116,11 @@ void ScanStateMachine::ReportCommonScanFailedAndClear(bool runningFlag) ScanStatusReport scanStatusReport; if (runningFlag) { GetRunningIndexList(scanStatusReport.requestIndexList); + std::unique_lock guard(lock); runningScans.clear(); } else { GetWaitingIndexList(scanStatusReport.requestIndexList); + std::unique_lock guard(lock); waitingScans.clear(); } @@ -1134,28 +1132,24 @@ void ScanStateMachine::ReportCommonScanFailedAndClear(bool runningFlag) if (scanStatusReportHandler) { scanStatusReportHandler(scanStatusReport); } - - return; } void ScanStateMachine::GetRunningIndexList(std::vector &runningIndexList) { + std::shared_lock guard(lock); std::map::iterator iter = runningScans.begin(); for (; iter != runningScans.end(); ++iter) { runningIndexList.push_back(iter->first); } - - return; } void ScanStateMachine::GetWaitingIndexList(std::vector &waitingIndexList) { + std::shared_lock guard(lock); std::map::iterator iter = waitingScans.begin(); for (; iter != waitingScans.end(); ++iter) { waitingIndexList.push_back(iter->first); } - - return; } bool ScanStateMachine::VerifyScanStyle(int scanStyle) @@ -1195,7 +1189,7 @@ int ScanStateMachine::MergeScanStyle(int currentScanStyle, int newScanStyle) void ScanStateMachine::RemoveCommonScanRequest(int requestIndex) { WIFI_LOGI("Enter ScanStateMachine::RemoveCommonScanRequest.\n"); - + std::unique_lock guard(lock); if (runningScans.count(requestIndex) == 1) { runningScans.erase(requestIndex); } @@ -1203,8 +1197,6 @@ void ScanStateMachine::RemoveCommonScanRequest(int requestIndex) if (waitingScans.count(requestIndex) == 1) { waitingScans.erase(requestIndex); } - - return; } void ScanStateMachine::PnoScanRequestProcess(InternalMessage *interMessage) @@ -1221,8 +1213,6 @@ void ScanStateMachine::PnoScanRequestProcess(InternalMessage *interMessage) } else { SwitchState(pnoScanSoftwareState); } - - return; } void ScanStateMachine::ContinuePnoScanProcess() @@ -1259,8 +1249,6 @@ void ScanStateMachine::PnoScanHardwareProcess(InternalMessage *interMessage) WIFI_LOGE("StartPnoScanHardware failed."); return; } - - return; } bool ScanStateMachine::StartPnoScanHardware() @@ -1294,7 +1282,6 @@ bool ScanStateMachine::StartPnoScanHardware() return false; } runningHwPnoFlag = true; - return true; } @@ -1315,7 +1302,6 @@ void ScanStateMachine::StopPnoScanHardware() } runningHwPnoFlag = false; - return; } void ScanStateMachine::UpdatePnoScanRequest(InternalMessage *interMessage) @@ -1326,8 +1312,6 @@ void ScanStateMachine::UpdatePnoScanRequest(InternalMessage *interMessage) WIFI_LOGE("GetPnoScanRequestInfo failed."); return; } - - return; } bool ScanStateMachine::GetPnoScanRequestInfo(InternalMessage *interMessage) @@ -1407,7 +1391,6 @@ bool ScanStateMachine::GetPnoScanConfig(InternalMessage *interMessage, PnoScanCo } pnoScanConfig.freqs.push_back(freqs); } - return true; } @@ -1440,7 +1423,7 @@ void ScanStateMachine::ReportPnoScanInfos(std::vector &scanInfos) WIFI_LOGI("Enter ScanStateMachine::ReportPnoScanInfos.\n"); ScanStatusReport scanStatusReport; - scanStatusReport.status = PNO_SCAN_RESULT; + scanStatusReport.status = PNO_SCAN_INFO; scanStatusReport.scanInfoList.assign(scanInfos.begin(), scanInfos.end()); if (scanStatusReportHandler) { scanStatusReportHandler(scanStatusReport); @@ -1452,7 +1435,7 @@ bool ScanStateMachine::NeedCommonScanAfterPno(std::vector &scanIn { WIFI_LOGI("Enter ScanStateMachine::NeedCommonScanAfterPno.\n"); if (scanInfos.size() > 0) { - WIFI_LOGI("Enter UpdateNetworkScoreCache.[%{public}s]\n", scanInfos[0].bssid.c_str()); + WIFI_LOGI("Enter UpdateNetworkScoreCache.[%{public}s]\n", MacAnonymize(scanInfos[0].bssid).c_str()); } return false; } @@ -1471,8 +1454,6 @@ void ScanStateMachine::CommonScanAfterPnoProcess() SwitchState(pnoScanHardwareState); return; } - - return; } void ScanStateMachine::CommonScanAfterPnoResult() @@ -1486,7 +1467,6 @@ void ScanStateMachine::CommonScanAfterPnoResult() } ReportPnoScanInfos(scanInfos); - return; } void ScanStateMachine::PnoScanFailedProcess() @@ -1497,8 +1477,6 @@ void ScanStateMachine::PnoScanFailedProcess() runningSwPnoFlag = false; ClearPnoScanConfig(); ReportStatusChange(PNO_SCAN_FAILED); - - return; } void ScanStateMachine::ClearPnoScanConfig() @@ -1533,7 +1511,6 @@ bool ScanStateMachine::GetScanInfos(std::vector &scanInfos) } WIFI_LOGI("End: QueryScanInfos."); GetSecurityTypeAndBand(scanInfos); - return true; } @@ -1546,7 +1523,6 @@ bool ScanStateMachine::StartNewSoftwareScan() return false; } StartTimer(int(SOFTWARE_PNO_SCAN_TIMER), (runningPnoScanConfig.scanInterval) * SECOND_TO_MILLI_SECOND); - return true; } @@ -1571,7 +1547,6 @@ bool ScanStateMachine::RepeatStartCommonScan() runningSwPnoFlag = true; SwitchState(pnoSwScanningState); - return true; } @@ -1587,7 +1562,6 @@ void ScanStateMachine::StopPnoScanSoftware() StopTimer(int(WAIT_SCAN_RESULT_TIMER)); /* Stop the PNO software scanning timer. */ StopTimer(int(SOFTWARE_PNO_SCAN_TIMER)); - runningSwPnoFlag = false; return; } @@ -1610,8 +1584,6 @@ void ScanStateMachine::PnoScanSoftwareProcess(InternalMessage *interMessage) WIFI_LOGE("StartPnoScanSoftware failed."); return; } - - return; } void ScanStateMachine::SoftwareScanInfoProcess() @@ -1624,7 +1596,6 @@ void ScanStateMachine::SoftwareScanInfoProcess() } ReportPnoScanInfos(scanInfos); - return; } bool ScanStateMachine::InitCommonScanState() @@ -1660,7 +1631,6 @@ bool ScanStateMachine::InitCommonScanState() WIFI_LOGE("Alloc commonScanningState failed.\n"); return false; } - return true; } @@ -1703,7 +1673,6 @@ bool ScanStateMachine::InitPnoScanState() WIFI_LOGE("Alloc pnoSwScanningState failed.\n"); return false; } - return true; } diff --git a/services/wifi_standard/wifi_framework/wifi_manage/wifi_scan/scan_state_machine.h b/wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_scan/scan_state_machine.h old mode 100755 new mode 100644 similarity index 98% rename from services/wifi_standard/wifi_framework/wifi_manage/wifi_scan/scan_state_machine.h rename to wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_scan/scan_state_machine.h index 9c12e00d790f8f7aa6cf70e42446bc9594d033de..8ff917c15b3e8076d3f53df0cd8d44acb3d6ceb9 --- a/services/wifi_standard/wifi_framework/wifi_manage/wifi_scan/scan_state_machine.h +++ b/wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_scan/scan_state_machine.h @@ -1,5 +1,5 @@ /* - * Copyright (C) 2021 Huawei Device Co., Ltd. + * Copyright (C) 2021-2022 Huawei Device Co., Ltd. * 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 @@ -12,21 +12,23 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + #ifndef OHOS_SCAN_STATE_MACHINE_H #define OHOS_SCAN_STATE_MACHINE_H #include +#include #include +#include #include #include #include -#include "wifi_log.h" -#include "wifi_error_no.h" -#include "wifi_scan_param.h" #include "scan_common.h" #include "state_machine.h" -#include "wifi_msg.h" #include "wifi_errcode.h" +#include "wifi_log.h" +#include "wifi_msg.h" +#include "wifi_scan_param.h" namespace OHOS { namespace Wifi { @@ -248,7 +250,7 @@ public: }; private: - bool quitFlag; /* Scanning state machine exit flag */ + std::atomic quitFlag; /* Scanning state machine exit flag */ InitState *initState; /* Scanning initial status pointer */ HardwareReady *hardwareReadyState; /* Pointer to the hardware startup completion status */ CommonScan *commonScanState; /* Pointer to the common scanning status */ @@ -287,6 +289,8 @@ private: */ bool runningSwPnoFlag; /* Software PNO scanning is in progress. */ + static std::shared_mutex lock; /* data lock */ + /** * @Description Processing of Scan Requests Received in Idle State. * diff --git a/services/wifi_standard/wifi_framework/wifi_manage/wifi_scan_callback_proxy.cpp b/wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_scan_callback_proxy.cpp similarity index 87% rename from services/wifi_standard/wifi_framework/wifi_manage/wifi_scan_callback_proxy.cpp rename to wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_scan_callback_proxy.cpp index 78877dece6a9e8830e77d4b32bfb031182c1adca..d7658365aa94d05225a215e9fdc879b481cdb486 100644 --- a/services/wifi_standard/wifi_framework/wifi_manage/wifi_scan_callback_proxy.cpp +++ b/wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_scan_callback_proxy.cpp @@ -1,5 +1,5 @@ /* - * Copyright (C) 2021 Huawei Device Co., Ltd. + * Copyright (C) 2021-2022 Huawei Device Co., Ltd. * 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 @@ -34,13 +34,16 @@ void WifiScanCallbackProxy::OnWifiScanStateChanged(int state) MessageParcel data; MessageParcel reply; MessageOption option(MessageOption::TF_ASYNC); - + if (!data.WriteInterfaceToken(GetDescriptor())) { + WIFI_LOGE("Write interface token error: %{public}s", __func__); + return; + } data.WriteInt32(0); data.WriteInt32(state); int error = Remote()->SendRequest(WIFI_CBK_CMD_SCAN_STATE_CHANGE, data, reply, option); switch (error) { case NO_ERROR: - WIFI_LOGD("OnWifiScanStateChanged callback sucessed!"); + WIFI_LOGD("OnWifiScanStateChanged callback succeeded!"); break; case DEAD_OBJECT: { WIFI_LOGE("Failed to SendRequest, remote object has dead!"); @@ -61,4 +64,4 @@ void WifiScanCallbackProxy::OnWifiScanStateChanged(int state) return; } } // namespace Wifi -} // namespace OHOS \ No newline at end of file +} // namespace OHOS diff --git a/services/wifi_standard/wifi_framework/wifi_manage/wifi_scan_callback_proxy.h b/wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_scan_callback_proxy.h similarity index 78% rename from services/wifi_standard/wifi_framework/wifi_manage/wifi_scan_callback_proxy.h rename to wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_scan_callback_proxy.h index 23df160b12b144b72405be7c46f7a7c0fd64debe..615ce02e1b39813c46a642007e6a0b21d243522a 100644 --- a/services/wifi_standard/wifi_framework/wifi_manage/wifi_scan_callback_proxy.h +++ b/wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_scan_callback_proxy.h @@ -16,21 +16,36 @@ #define OHOS_I_WIFI_SCAN_CALLBACK_PROXY_H #include "i_wifi_scan_callback.h" +#ifdef OHOS_ARCH_LITE +#include "serializer.h" +#else #include "iremote_proxy.h" +#endif namespace OHOS { namespace Wifi { +#ifdef OHOS_ARCH_LITE +class WifiScanCallbackProxy : public IWifiScanCallback { +public: + explicit WifiScanCallbackProxy(SvcIdentity *sid); +#else class WifiScanCallbackProxy : public IRemoteProxy { public: explicit WifiScanCallbackProxy(const sptr &impl); +#endif virtual ~WifiScanCallbackProxy(); void OnWifiScanStateChanged(int state) override; private: +#ifdef OHOS_ARCH_LITE + SvcIdentity sid_; + static const int DEFAULT_IPC_SIZE = 256; +#else static inline BrokerDelegator g_delegator; +#endif }; } // namespace Wifi } // namespace OHOS -#endif \ No newline at end of file +#endif diff --git a/wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_scan_callback_proxy_lite.cpp b/wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_scan_callback_proxy_lite.cpp new file mode 100644 index 0000000000000000000000000000000000000000..ba54b5a7dad3d74b5e772557219ad54d48bc6a11 --- /dev/null +++ b/wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_scan_callback_proxy_lite.cpp @@ -0,0 +1,58 @@ +/* + * Copyright (C) 2022 Huawei Device Co., Ltd. + * 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 "wifi_scan_callback_proxy.h" +#include "define.h" +#include "ipc_skeleton.h" +#include "rpc_errno.h" +#include "wifi_logger.h" + +DEFINE_WIFILOG_SCAN_LABEL("WifiScanCallbackProxyLite"); + +namespace OHOS { +namespace Wifi { +WifiScanCallbackProxy::WifiScanCallbackProxy(SvcIdentity *sid) : sid_(*sid) +{} + +WifiScanCallbackProxy::~WifiScanCallbackProxy() +{ + ReleaseSvc(sid_); +} + +void WifiScanCallbackProxy::OnWifiScanStateChanged(int state) +{ + WIFI_LOGD("OnWifiScanStateChanged, state:%{public}d", state); + IpcIo data; + uint8_t buff[DEFAULT_IPC_SIZE]; + IpcIoInit(&data, buff, DEFAULT_IPC_SIZE, 0); + (void)WriteInt32(&data, 0); + (void)WriteInt32(&data, state); + IpcIo reply; + MessageOption option; + MessageOptionInit(&option); + option.flags = TF_OP_ASYNC; + int ret = SendRequest(sid_, WIFI_CBK_CMD_SCAN_STATE_CHANGE, &data, &reply, option, nullptr); + switch (ret) { + case ERR_NONE: + WIFI_LOGD("OnWifiScanStateChanged callback succeeded!"); + break; + default: { + WIFI_LOGE("OnWifiScanStateChanged,connect done failed, error: %{public}d!", ret); + break; + } + } +} +} // namespace Wifi +} // namespace OHOS diff --git a/services/wifi_standard/wifi_framework/wifi_manage/wifi_scan_death_recipient.cpp b/wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_scan_death_recipient.cpp similarity index 100% rename from services/wifi_standard/wifi_framework/wifi_manage/wifi_scan_death_recipient.cpp rename to wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_scan_death_recipient.cpp diff --git a/services/wifi_standard/wifi_framework/wifi_manage/wifi_scan_death_recipient.h b/wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_scan_death_recipient.h similarity index 100% rename from services/wifi_standard/wifi_framework/wifi_manage/wifi_scan_death_recipient.h rename to wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_scan_death_recipient.h diff --git a/wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_scan_feature_lite.cpp b/wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_scan_feature_lite.cpp new file mode 100644 index 0000000000000000000000000000000000000000..b2ba42e8710146c55fda0331d43e63bfb23915d2 --- /dev/null +++ b/wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_scan_feature_lite.cpp @@ -0,0 +1,112 @@ +/* + * Copyright (C) 2022 Huawei Device Co., Ltd. + * 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 "iproxy_server.h" +#include "ohos_errno.h" +#include "ohos_init.h" +#include "samgr_lite.h" +#include "service.h" +#include "wifi_log.h" +#include "wifi_ipc_lite_adapter.h" +#include "wifi_scan_service_impl.h" + +using namespace OHOS::Wifi; + +static std::shared_ptr g_scanServiceImpl = WifiScanServiceImpl::GetInstance(); + +typedef struct WifiScanApi { + INHERIT_SERVER_IPROXY; +} WifiScanApi; + +typedef struct WifiScanFeature { + INHERIT_FEATURE; + INHERIT_IUNKNOWNENTRY(WifiScanApi); + Identity identity; + Service *parent; +} WifiScanFeature; + +static const char *GetName(Feature *feature) +{ + return WIFI_FEATRUE_SCAN; +} + +static void OnInitialize(Feature *feature, Service *parent, Identity identity) +{ + if (feature != NULL) { + WifiScanFeature *scanFeature = (WifiScanFeature *)feature; + scanFeature->identity = identity; + scanFeature->parent = parent; + } + if (g_scanServiceImpl != NULL) { + g_scanServiceImpl->OnStart(); + } +} + +static void OnStop(Feature *feature, Identity identity) +{ + if (g_scanServiceImpl != NULL) { + g_scanServiceImpl->OnStop(); + } + if (feature != NULL) { + WifiScanFeature *scanFeature = (WifiScanFeature *)feature; + scanFeature->identity.queueId = NULL; + scanFeature->identity.featureId = -1; + scanFeature->identity.serviceId = -1; + } +} + +static BOOL OnMessage(Feature *feature, Request *request) +{ + return TRUE; +} + +static int Invoke(IServerProxy *proxy, int funcId, void *origin, IpcIo *req, IpcIo *reply) +{ + LOGI("[WifiScanFeature] begin to call Invoke, funcId is %{public}d", funcId); + if (g_scanServiceImpl != NULL) { + return g_scanServiceImpl->OnRemoteRequest(funcId, req, reply); + } + return EC_FAILURE; +} + +static WifiScanFeature g_scanFeature = { + .GetName = GetName, + .OnInitialize = OnInitialize, + .OnStop = OnStop, + .OnMessage = OnMessage, + SERVER_IPROXY_IMPL_BEGIN, + .Invoke = Invoke, + IPROXY_END, + .identity = {-1, -1, NULL}, +}; + +static void Init(void) +{ + LOGI("[WifiScanFeature] Init start."); + BOOL ret = SAMGR_GetInstance()->RegisterFeature(WIFI_SERVICE_LITE, (Feature *)&g_scanFeature); + if (ret == FALSE) { + LOGE("[WifiScanFeature] register feature fail."); + return; + } + ret = SAMGR_GetInstance()->RegisterFeatureApi(WIFI_SERVICE_LITE, + WIFI_FEATRUE_SCAN, GET_IUNKNOWN(g_scanFeature)); + if (ret == FALSE) { + LOGE("[WifiScanFeature] register feature api fail."); + } +} +SYSEX_FEATURE_INIT(Init); diff --git a/services/wifi_standard/wifi_framework/wifi_manage/wifi_scan_service_impl.cpp b/wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_scan_service_impl.cpp similarity index 58% rename from services/wifi_standard/wifi_framework/wifi_manage/wifi_scan_service_impl.cpp rename to wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_scan_service_impl.cpp index a18cebaaa1d496ba4e4dfb2328378621d0a134d7..2aa11eebb52c68329635df6420d1153d3a2b5d48 100644 --- a/services/wifi_standard/wifi_framework/wifi_manage/wifi_scan_service_impl.cpp +++ b/wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_scan_service_impl.cpp @@ -1,5 +1,5 @@ /* - * Copyright (C) 2021 Huawei Device Co., Ltd. + * Copyright (C) 2021-2022 Huawei Device Co., Ltd. * 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 @@ -14,31 +14,48 @@ */ #include "wifi_scan_service_impl.h" -#include "wifi_msg.h" +#ifndef OHOS_ARCH_LITE +#include +#endif +#include "define.h" #include "permission_def.h" -#include "wifi_permission_utils.h" #include "wifi_auth_center.h" #include "wifi_config_center.h" -#include "wifi_manager.h" -#include "wifi_service_manager.h" +#include "wifi_dumper.h" +#ifdef OHOS_ARCH_LITE +#include "wifi_internal_event_dispatcher_lite.h" +#else #include "wifi_internal_event_dispatcher.h" +#endif #include "wifi_internal_msg.h" #include "wifi_logger.h" -#include "define.h" +#include "wifi_manager.h" +#include "wifi_msg.h" +#include "wifi_permission_utils.h" #include "wifi_scan_callback_proxy.h" +#include "wifi_service_manager.h" DEFINE_WIFILOG_SCAN_LABEL("WifiScanServiceImpl"); namespace OHOS { namespace Wifi { std::mutex WifiScanServiceImpl::g_instanceLock; +#ifdef OHOS_ARCH_LITE +std::shared_ptr WifiScanServiceImpl::g_instance; +std::shared_ptr WifiScanServiceImpl::GetInstance() +#else sptr WifiScanServiceImpl::g_instance; const bool REGISTER_RESULT = SystemAbility::MakeAndRegisterAbility(WifiScanServiceImpl::GetInstance().GetRefPtr()); sptr WifiScanServiceImpl::GetInstance() +#endif { if (g_instance == nullptr) { std::lock_guard autoLock(g_instanceLock); if (g_instance == nullptr) { +#ifdef OHOS_ARCH_LITE + auto service = std::make_shared(); +#else auto service = new (std::nothrow) WifiScanServiceImpl; +#endif g_instance = service; } } @@ -46,7 +63,11 @@ sptr WifiScanServiceImpl::GetInstance() } WifiScanServiceImpl::WifiScanServiceImpl() +#ifdef OHOS_ARCH_LITE + : mPublishFlag(false), mState(ServiceRunningState::STATE_NOT_START) +#else : SystemAbility(WIFI_SCAN_ABILITY_ID, true), mPublishFlag(false), mState(ServiceRunningState::STATE_NOT_START) +#endif {} WifiScanServiceImpl::~WifiScanServiceImpl() @@ -55,7 +76,7 @@ WifiScanServiceImpl::~WifiScanServiceImpl() void WifiScanServiceImpl::OnStart() { if (mState == ServiceRunningState::STATE_RUNNING) { - WIFI_LOGD("Service has already started."); + WIFI_LOGW("Service has already started."); return; } if (!Init()) { @@ -78,7 +99,11 @@ void WifiScanServiceImpl::OnStop() bool WifiScanServiceImpl::Init() { if (!mPublishFlag) { +#ifdef OHOS_ARCH_LITE + bool ret = true; +#else bool ret = Publish(WifiScanServiceImpl::GetInstance()); +#endif if (!ret) { WIFI_LOGE("Failed to publish scan service!"); return false; @@ -91,8 +116,8 @@ bool WifiScanServiceImpl::Init() ErrCode WifiScanServiceImpl::SetScanControlInfo(const ScanControlInfo &info) { WIFI_LOGI("WifiScanServiceImpl::SetScanControlInfo"); - if (WifiPermissionUtils::VerifyGetWifiInfoPermission() == PERMISSION_DENIED) { - WIFI_LOGE("SetScanControlInfo:VerifyGetWifiInfoPermission PERMISSION_DENIED!"); + if (WifiPermissionUtils::VerifySetWifiInfoPermission() == PERMISSION_DENIED) { + WIFI_LOGE("SetScanControlInfo:VerifySetWifiInfoPermission PERMISSION_DENIED!"); return WIFI_OPT_PERMISSION_DENIED; } @@ -111,9 +136,18 @@ ErrCode WifiScanServiceImpl::SetScanControlInfo(const ScanControlInfo &info) ErrCode WifiScanServiceImpl::Scan() { WIFI_LOGI("Scan"); - if (WifiPermissionUtils::VerifyGetWifiInfoPermission() == PERMISSION_DENIED) { - WIFI_LOGE("Scan:VerifyGetWifiInfoPermission PERMISSION_DENIED!"); - return WIFI_OPT_PERMISSION_DENIED; + if (WifiPermissionUtils::VerifyGetWifiInfoInternalPermission() == PERMISSION_DENIED) { + WIFI_LOGE("Scan:VerifyGetWifiInfoInternalPermission PERMISSION_DENIED!"); + + if (WifiPermissionUtils::VerifySetWifiInfoPermission() == PERMISSION_DENIED) { + WIFI_LOGE("Scan:VerifySetWifiInfoPermission PERMISSION_DENIED!"); + return WIFI_OPT_PERMISSION_DENIED; + } + + if (WifiPermissionUtils::VerifyGetScanInfosPermission() == PERMISSION_DENIED) { + WIFI_LOGE("Scan:VerifyGetScanInfosPermission PERMISSION_DENIED!"); + return WIFI_OPT_PERMISSION_DENIED; + } } if (!IsScanServiceRunning()) { @@ -124,15 +158,28 @@ ErrCode WifiScanServiceImpl::Scan() if (pService == nullptr) { return WIFI_OPT_SCAN_NOT_OPENED; } - return pService->Scan(true); + ErrCode ret = pService->Scan(true); + if (ret != WIFI_OPT_SUCCESS) { + WIFI_LOGE("Scan failed: %{public}d!", static_cast(ret)); + } + return ret; } ErrCode WifiScanServiceImpl::AdvanceScan(const WifiScanParams ¶ms) { WIFI_LOGI("Scan with WifiScanParams, band %{public}u", params.band); - if (WifiPermissionUtils::VerifyGetWifiInfoPermission() == PERMISSION_DENIED) { - WIFI_LOGE("Scan with WifiScanParams:VerifyGetWifiInfoPermission PERMISSION_DENIED!"); - return WIFI_OPT_PERMISSION_DENIED; + if (WifiPermissionUtils::VerifyGetWifiInfoInternalPermission() == PERMISSION_DENIED) { + WIFI_LOGE("AdvanceScan:VerifyGetWifiInfoInternalPermission PERMISSION_DENIED!"); + + if (WifiPermissionUtils::VerifySetWifiInfoPermission() == PERMISSION_DENIED) { + WIFI_LOGE("AdvanceScan:VerifySetWifiInfoPermission PERMISSION_DENIED!"); + return WIFI_OPT_PERMISSION_DENIED; + } + + if (WifiPermissionUtils::VerifyGetScanInfosPermission() == PERMISSION_DENIED) { + WIFI_LOGE("AdvanceScan:VerifyGetScanInfosPermission PERMISSION_DENIED!"); + return WIFI_OPT_PERMISSION_DENIED; + } } if (!IsScanServiceRunning()) { @@ -162,20 +209,29 @@ ErrCode WifiScanServiceImpl::GetScanInfoList(std::vector &result) { WIFI_LOGI("GetScanInfoList"); - if (WifiPermissionUtils::VerifyGetWifiInfoPermission() == PERMISSION_DENIED) { - WIFI_LOGE("GetScanInfoList:VerifyGetWifiInfoPermission PERMISSION_DENIED!"); - return WIFI_OPT_PERMISSION_DENIED; - } + if (WifiPermissionUtils::VerifyGetWifiInfoInternalPermission() == PERMISSION_DENIED) { + WIFI_LOGE("GetScanInfoList:VerifyGetWifiInfoInternalPermission PERMISSION_DENIED!"); + if (WifiPermissionUtils::VerifyGetWifiInfoPermission() == PERMISSION_DENIED) { + WIFI_LOGE("GetScanInfoList:VerifyGetWifiInfoPermission PERMISSION_DENIED!"); + return WIFI_OPT_PERMISSION_DENIED; + } - if (WifiPermissionUtils::VerifyGetWifiInfoPermission() == PERMISSION_DENIED) { - WIFI_LOGE("GetScanInfoList:VerifyGetWifiInfoPermission PERMISSION_DENIED!"); - return WIFI_OPT_PERMISSION_DENIED; + if ((WifiPermissionUtils::VerifyGetScanInfosPermission() == PERMISSION_DENIED) && + (WifiPermissionUtils::VerifyGetWifiPeersMacPermission() == PERMISSION_DENIED)) { + WIFI_LOGE("GetScanInfoList:GET_WIFI_PEERS_MAC && LOCATION PERMISSION_DENIED!"); + return WIFI_OPT_PERMISSION_DENIED; + } } + WifiConfigCenter::GetInstance().GetScanInfoList(result); return WIFI_OPT_SUCCESS; } +#ifdef OHOS_ARCH_LITE +ErrCode WifiScanServiceImpl::RegisterCallBack(const std::shared_ptr &callback) +#else ErrCode WifiScanServiceImpl::RegisterCallBack(const sptr &callback) +#endif { WIFI_LOGI("WifiScanServiceImpl::RegisterCallBack!"); WifiInternalEventDispatcher::GetInstance().SetSingleScanCallback(callback); @@ -200,10 +256,39 @@ bool WifiScanServiceImpl::IsScanServiceRunning() { WifiOprMidState curState = WifiConfigCenter::GetInstance().GetScanMidState(); if (curState != WifiOprMidState::RUNNING) { - WIFI_LOGD("scan service does not started!"); + WIFI_LOGW("scan service does not started!"); return false; } return true; } + +void WifiScanServiceImpl::SaBasicDump(std::string& result) +{ + WifiScanServiceImpl impl; + bool isRunning = impl.IsScanServiceRunning(); + result.append("Is scan service running: "); + std::string strRunning = isRunning ? "true" : "false"; + result += strRunning + "\n"; +} + +#ifndef OHOS_ARCH_LITE +int32_t WifiScanServiceImpl::Dump(int32_t fd, const std::vector& args) +{ + WIFI_LOGI("Enter scan dump func."); + std::vector vecArgs; + std::transform(args.begin(), args.end(), std::back_inserter(vecArgs), [](const std::u16string &arg) { + return Str16ToStr8(arg); + }); + + WifiDumper dumper; + std::string result; + dumper.ScanDump(SaBasicDump, vecArgs, result); + if (!SaveStringToFd(fd, result)) { + WIFI_LOGE("WiFi scan save string to fd failed."); + return ERR_OK; + } + return ERR_OK; +} +#endif } // namespace Wifi } // namespace OHOS \ No newline at end of file diff --git a/services/wifi_standard/wifi_framework/wifi_manage/wifi_scan_service_impl.h b/wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_scan_service_impl.h similarity index 71% rename from services/wifi_standard/wifi_framework/wifi_manage/wifi_scan_service_impl.h rename to wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_scan_service_impl.h index 590c667f698899afed37cc869392038eafa07b9f..30989988d9f2a4310d8784a12c201d6de387f431 100644 --- a/services/wifi_standard/wifi_framework/wifi_manage/wifi_scan_service_impl.h +++ b/wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_scan_service_impl.h @@ -1,5 +1,5 @@ /* - * Copyright (C) 2021 Huawei Device Co., Ltd. + * Copyright (C) 2021-2022 Huawei Device Co., Ltd. * 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 @@ -16,9 +16,13 @@ #ifndef OHOS_WIFI_SCAN_SERVICE_H #define OHOS_WIFI_SCAN_SERVICE_H +#ifdef OHOS_ARCH_LITE +#include "wifi_scan_stub_lite.h" +#else #include "system_ability.h" #include "wifi_scan_stub.h" #include "iremote_object.h" +#endif namespace OHOS { namespace Wifi { @@ -26,32 +30,56 @@ enum ServiceRunningState { STATE_NOT_START, STATE_RUNNING }; + +#ifdef OHOS_ARCH_LITE +class WifiScanServiceImpl : public WifiScanStub { +#else class WifiScanServiceImpl : public SystemAbility, public WifiScanStub { DECLARE_SYSTEM_ABILITY(WifiScanServiceImpl); +#endif public: WifiScanServiceImpl(); virtual ~WifiScanServiceImpl(); +#ifdef OHOS_ARCH_LITE + static std::shared_ptr GetInstance(); + + void OnStart(); + void OnStop(); +#else static sptr GetInstance(); void OnStart() override; void OnStop() override; +#endif ErrCode SetScanControlInfo(const ScanControlInfo &info) override; ErrCode Scan() override; ErrCode AdvanceScan(const WifiScanParams ¶ms) override; ErrCode IsWifiClosedScan(bool &bOpen) override; ErrCode GetScanInfoList(std::vector &result) override; +#ifdef OHOS_ARCH_LITE + ErrCode RegisterCallBack(const std::shared_ptr &callback) override; +#else ErrCode RegisterCallBack(const sptr &callback) override; +#endif ErrCode GetSupportedFeatures(long &features) override; +#ifndef OHOS_ARCH_LITE + int32_t Dump(int32_t fd, const std::vector& args) override; +#endif private: bool Init(); bool IsScanServiceRunning(); + static void SaBasicDump(std::string& result); private: +#ifdef OHOS_ARCH_LITE + static std::shared_ptr g_instance; +#else static sptr g_instance; +#endif static std::mutex g_instanceLock; bool mPublishFlag = false; ServiceRunningState mState; diff --git a/services/wifi_standard/wifi_framework/wifi_manage/wifi_scan_stub.cpp b/wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_scan_stub.cpp old mode 100755 new mode 100644 similarity index 79% rename from services/wifi_standard/wifi_framework/wifi_manage/wifi_scan_stub.cpp rename to wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_scan_stub.cpp index 4c4de8efe33dc6295e59614cb2b56ef97609ce0a..5c711e715a3243fb646f7c77bf4a37770190b1fe --- a/services/wifi_standard/wifi_framework/wifi_manage/wifi_scan_stub.cpp +++ b/wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_scan_stub.cpp @@ -1,5 +1,5 @@ /* - * Copyright (C) 2021 Huawei Device Co., Ltd. + * Copyright (C) 2021-2022 Huawei Device Co., Ltd. * 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 @@ -21,9 +21,10 @@ #include "wifi_internal_event_dispatcher.h" #include "wifi_scan_death_recipient.h" +DEFINE_WIFILOG_SCAN_LABEL("WifiScanStub"); + namespace OHOS { namespace Wifi { -DEFINE_WIFILOG_SCAN_LABEL("WifiScanStub"); WifiScanStub::WifiScanStub() : callback_(nullptr), mSingleCallback(false) {} @@ -32,7 +33,12 @@ WifiScanStub::~WifiScanStub() int WifiScanStub::OnRemoteRequest(uint32_t code, MessageParcel &data, MessageParcel &reply, MessageOption &option) { - WIFI_LOGD("WifiScanStub::OnRemoteRequest,code:%{public}d", code); + WIFI_LOGD("WifiScanStub::OnRemoteRequest,code:%{public}u", code); + + if (data.ReadInterfaceToken() != GetDescriptor()) { + WIFI_LOGE("Scan stub token verification error: %{public}d", code); + return WIFI_OPT_FAILED; + } int exception = data.ReadInt32(); if (exception) { @@ -83,45 +89,37 @@ sptr WifiScanStub::GetCallback() const int WifiScanStub::OnSetScanControlInfo(uint32_t code, MessageParcel &data, MessageParcel &reply, MessageOption &option) { - WIFI_LOGD("run OnSetScanControlInfo code %{public}u, datasize %zu", code, data.GetRawDataSize()); + WIFI_LOGD("run OnSetScanControlInfo code %{public}u, datasize %{public}zu", code, data.GetRawDataSize()); + constexpr int MAX_SIZE = 1024; ScanControlInfo info; - int forbidMapSize = data.ReadInt32(); - for (int i = 0; i < forbidMapSize; i++) { - int tmp = data.ReadInt32(); - int modeMapSize = data.ReadInt32(); - std::vector scanModeList; - for (int j = 0; j < modeMapSize; j++) { - ScanForbidMode scanForbidMode; - int tmpScanMode = data.ReadInt32(); - if (tmpScanMode < 0 || tmpScanMode >= int(ScanMode::SCAN_MODE_MAX)) { - continue; - } - scanForbidMode.scanMode = ScanMode(tmpScanMode); - scanForbidMode.forbidTime = data.ReadInt32(); - scanForbidMode.forbidCount = data.ReadInt32(); - scanModeList.push_back(scanForbidMode); - } - if (tmp < 0 || tmp >= int(SCAN_SCENE_MAX)) { - continue; - } - info.scanForbidMap.insert(std::pair>(tmp, scanModeList)); + int forbidListSize = data.ReadInt32(); + if (forbidListSize > MAX_SIZE) { + reply.WriteInt32(0); + reply.WriteInt32(WIFI_OPT_INVALID_PARAM); + return WIFI_OPT_INVALID_PARAM; + } + for (int i = 0; i < forbidListSize; i++) { + ScanForbidMode scanForbidMode; + scanForbidMode.scanScene = data.ReadInt32(); + scanForbidMode.scanMode = static_cast(data.ReadInt32()); + scanForbidMode.forbidTime = data.ReadInt32(); + scanForbidMode.forbidCount = data.ReadInt32(); + info.scanForbidList.push_back(scanForbidMode); } int intervalSize = data.ReadInt32(); + if (intervalSize > MAX_SIZE) { + reply.WriteInt32(0); + reply.WriteInt32(WIFI_OPT_INVALID_PARAM); + return WIFI_OPT_INVALID_PARAM; + } for (int i = 0; i < intervalSize; i++) { ScanIntervalMode scanIntervalMode; scanIntervalMode.scanScene = data.ReadInt32(); - int mode = data.ReadInt32(); - if (mode < 0 || mode >= int(ScanMode::SCAN_MODE_MAX)) { - continue; - } - scanIntervalMode.scanMode = ScanMode(mode); - scanIntervalMode.isSingle = data.ReadInt32(); - scanIntervalMode.intervalMode = (IntervalMode)data.ReadInt32(); + scanIntervalMode.scanMode = static_cast(data.ReadInt32()); + scanIntervalMode.isSingle = data.ReadBool(); + scanIntervalMode.intervalMode = static_cast(data.ReadInt32()); scanIntervalMode.interval = data.ReadInt32(); - if (scanIntervalMode.interval < MIN_SCAN_INTERVAL) { - continue; - } scanIntervalMode.count = data.ReadInt32(); info.scanIntervalList.push_back(scanIntervalMode); } @@ -135,7 +133,7 @@ int WifiScanStub::OnSetScanControlInfo(uint32_t code, MessageParcel &data, Messa int WifiScanStub::OnScan(uint32_t code, MessageParcel &data, MessageParcel &reply, MessageOption &option) { - WIFI_LOGD("run OnScan code %{public}u, datasize %zu", code, data.GetRawDataSize()); + WIFI_LOGD("run OnScan code %{public}u, datasize %{public}zu", code, data.GetRawDataSize()); ErrCode ret = Scan(); reply.WriteInt32(0); reply.WriteInt32(ret); @@ -145,11 +143,17 @@ int WifiScanStub::OnScan(uint32_t code, MessageParcel &data, MessageParcel &repl int WifiScanStub::OnScanByParams(uint32_t code, MessageParcel &data, MessageParcel &reply, MessageOption &option) { - WIFI_LOGD("run OnScanByParams code %{public}u, datasize %zu", code, data.GetRawDataSize()); + WIFI_LOGD("run OnScanByParams code %{public}u, datasize %{public}zu", code, data.GetRawDataSize()); + constexpr int MAX_FREQS_SIZE = 512; WifiScanParams params; params.ssid = data.ReadCString(); params.bssid = data.ReadCString(); int size = data.ReadInt32(); + if (size > MAX_FREQS_SIZE) { + reply.WriteInt32(0); + reply.WriteInt32(WIFI_OPT_INVALID_PARAM); + return WIFI_OPT_INVALID_PARAM; + } for (int i = 0; i < size; i++) { int tmp = data.ReadInt32(); params.freqs.push_back(tmp); @@ -165,7 +169,7 @@ int WifiScanStub::OnScanByParams(uint32_t code, MessageParcel &data, MessageParc int WifiScanStub::OnIsWifiClosedScan(uint32_t code, MessageParcel &data, MessageParcel &reply, MessageOption &option) { - WIFI_LOGD("run OnIsWifiClosedScan code %{public}u, datasize %zu", code, data.GetRawDataSize()); + WIFI_LOGD("run OnIsWifiClosedScan code %{public}u, datasize %{public}zu", code, data.GetRawDataSize()); bool bOpen = false; ErrCode ret = IsWifiClosedScan(bOpen); reply.WriteInt32(0); @@ -178,7 +182,7 @@ int WifiScanStub::OnIsWifiClosedScan(uint32_t code, MessageParcel &data, Message int WifiScanStub::OnGetScanInfoList(uint32_t code, MessageParcel &data, MessageParcel &reply, MessageOption &option) { - WIFI_LOGD("run OnGetScanInfoList code %{public}u, datasize %zu", code, data.GetRawDataSize()); + WIFI_LOGD("run OnGetScanInfoList code %{public}u, datasize %{public}zu", code, data.GetRawDataSize()); std::vector result; ErrCode ret = GetScanInfoList(result); reply.WriteInt32(0); @@ -216,19 +220,19 @@ int WifiScanStub::OnGetScanInfoList(uint32_t code, MessageParcel &data, MessageP int WifiScanStub::OnRegisterCallBack(uint32_t code, MessageParcel &data, MessageParcel &reply, MessageOption &option) { - WIFI_LOGD("run %{public}s code %{public}u, datasize %zu", __func__, code, data.GetRawDataSize()); + WIFI_LOGD("run %{public}s code %{public}u, datasize %{public}zu", __func__, code, data.GetRawDataSize()); ErrCode ret = WIFI_OPT_FAILED; do { sptr remote = data.ReadRemoteObject(); if (remote == nullptr) { - WIFI_LOGD("Failed to readRemoteObject!"); + WIFI_LOGE("Failed to readRemoteObject!"); break; } callback_ = iface_cast(remote); if (callback_ == nullptr) { callback_ = new (std::nothrow) WifiScanCallbackProxy(remote); - WIFI_LOGD("create new `WifiScanCallbackProxy`!"); + WIFI_LOGI("create new `WifiScanCallbackProxy`!"); } if (mSingleCallback) { diff --git a/services/wifi_standard/wifi_framework/wifi_manage/wifi_scan_stub.h b/wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_scan_stub.h similarity index 100% rename from services/wifi_standard/wifi_framework/wifi_manage/wifi_scan_stub.h rename to wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_scan_stub.h diff --git a/wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_scan_stub_lite.cpp b/wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_scan_stub_lite.cpp new file mode 100644 index 0000000000000000000000000000000000000000..1afb2b058438338c5925ac7405686795e4ab7549 --- /dev/null +++ b/wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_scan_stub_lite.cpp @@ -0,0 +1,267 @@ +/* + * Copyright (C) 2022 Huawei Device Co., Ltd. + * 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 "wifi_scan_stub_lite.h" +#include "define.h" +#include "ipc_skeleton.h" +#include "rpc_errno.h" +#include "wifi_logger.h" +#include "wifi_msg.h" +#include "wifi_scan_callback_proxy.h" + +DEFINE_WIFILOG_SCAN_LABEL("WifiScanStubLite"); + +namespace OHOS { +namespace Wifi { +WifiScanStub::WifiScanStub() : callback_(nullptr) +{} + +WifiScanStub::~WifiScanStub() +{} + +int WifiScanStub::OnRemoteRequest(uint32_t code, IpcIo *req, IpcIo *reply) +{ + WIFI_LOGD("WifiScanStub::OnRemoteRequest,code:%{public}u", code); + if (req == nullptr || reply == nullptr) { + WIFI_LOGE("req:%{public}d, reply:%{public}d", req == nullptr, reply == nullptr); + return ERR_FAILED; + } + + int exception = ERR_FAILED; + (void)ReadInt32(req, &exception); + if (exception) { + return WIFI_OPT_FAILED; + } + + int ret = -1; + switch (code) { + case WIFI_SVR_CMD_SET_SCAN_CONTROL_INFO: { + ret = OnSetScanControlInfo(code, req, reply); + break; + } + case WIFI_SVR_CMD_FULL_SCAN: { + ret = OnScan(code, req, reply); + break; + } + case WIFI_SVR_CMD_SPECIFIED_PARAMS_SCAN: { + ret = OnScanByParams(code, req, reply); + break; + } + case WIFI_SVR_CMD_IS_SCAN_ALWAYS_ACTIVE: { + ret = OnIsWifiClosedScan(code, req, reply); + break; + } + case WIFI_SVR_CMD_GET_SCAN_INFO_LIST: { + ret = OnGetScanInfoList(code, req, reply); + break; + } + case WIFI_SVR_CMD_REGISTER_SCAN_CALLBACK: { + ret = OnRegisterCallBack(code, req, reply); + break; + } + case WIFI_SVR_CMD_GET_SUPPORTED_FEATURES: { + ret = OnGetSupportedFeatures(code, req, reply); + break; + } + default: { + ret = -1; + } + } + return ret; +} + +std::shared_ptr WifiScanStub::GetCallback() const +{ + return callback_; +} + +int WifiScanStub::OnSetScanControlInfo(uint32_t code, IpcIo *req, IpcIo *reply) +{ + WIFI_LOGD("WifiScanStub run %{public}s code %{public}u", __func__, code); + int tmpInt; + constexpr int MAX_SIZE = 1024; + ScanControlInfo info; + int forbidListSize = 0; + (void)ReadInt32(req, &forbidListSize); + if (forbidListSize > MAX_SIZE) { + (void)WriteInt32(reply, 0); + (void)WriteInt32(reply, WIFI_OPT_INVALID_PARAM); + return WIFI_OPT_INVALID_PARAM; + } + for (int i = 0; i < forbidListSize; i++) { + ScanForbidMode scanForbidMode; + (void)ReadInt32(req, &scanForbidMode.scanScene); + (void)ReadInt32(req, &tmpInt); + scanForbidMode.scanMode = static_cast(tmpInt); + (void)ReadInt32(req, &scanForbidMode.forbidTime); + (void)ReadInt32(req, &scanForbidMode.forbidCount); + info.scanForbidList.push_back(scanForbidMode); + } + + int intervalSize = 0; + (void)ReadInt32(req, &intervalSize); + if (intervalSize > MAX_SIZE) { + (void)WriteInt32(reply, 0); + (void)WriteInt32(reply, WIFI_OPT_INVALID_PARAM); + return WIFI_OPT_INVALID_PARAM; + } + for (int i = 0; i < intervalSize; i++) { + ScanIntervalMode scanIntervalMode; + (void)ReadInt32(req, &scanIntervalMode.scanScene); + (void)ReadInt32(req, &tmpInt); + scanIntervalMode.scanMode = static_cast(tmpInt); + (void)ReadBool(req, &scanIntervalMode.isSingle); + (void)ReadInt32(req, &tmpInt); + scanIntervalMode.intervalMode = static_cast(tmpInt); + (void)ReadInt32(req, &scanIntervalMode.interval); + (void)ReadInt32(req, &scanIntervalMode.count); + info.scanIntervalList.push_back(scanIntervalMode); + } + + ErrCode ret = SetScanControlInfo(info); + (void)WriteInt32(reply, 0); + (void)WriteInt32(reply, ret); + + return ret; +} + +int WifiScanStub::OnScan(uint32_t code, IpcIo *req, IpcIo *reply) +{ + WIFI_LOGD("WifiScanStub run %{public}s code %{public}u", __func__, code); + ErrCode ret = Scan(); + (void)WriteInt32(reply, 0); + (void)WriteInt32(reply, ret); + + return ret; +} + +int WifiScanStub::OnScanByParams(uint32_t code, IpcIo *req, IpcIo *reply) +{ + WIFI_LOGD("WifiScanStub run %{public}s code %{public}u", __func__, code); + size_t readLen; + constexpr int MAX_FREQS_SIZE = 512; + WifiScanParams params; + params.ssid = (char *)ReadString(req, &readLen); + params.bssid = (char *)ReadString(req, &readLen); + int size = 0; + (void)ReadInt32(req, &size); + if (size > MAX_FREQS_SIZE) { + (void)WriteInt32(reply, 0); + (void)WriteInt32(reply, WIFI_OPT_INVALID_PARAM); + return WIFI_OPT_INVALID_PARAM; + } + int tmp; + for (int i = 0; i < size; i++) { + (void)ReadInt32(req, &tmp); + params.freqs.push_back(tmp); + } + (void)ReadUint32(req, ¶ms.band); + + ErrCode ret = AdvanceScan(params); + (void)WriteInt32(reply, 0); + (void)WriteInt32(reply, ret); + + return ret; +} + +int WifiScanStub::OnIsWifiClosedScan(uint32_t code, IpcIo *req, IpcIo *reply) +{ + WIFI_LOGD("WifiScanStub run %{public}s code %{public}u", __func__, code); + bool bOpen = false; + ErrCode ret = IsWifiClosedScan(bOpen); + (void)WriteInt32(reply, 0); + (void)WriteInt32(reply, ret); + if (ret == WIFI_OPT_SUCCESS) { + (void)WriteBool(reply, bOpen); + } + return ret; +} + +int WifiScanStub::OnGetScanInfoList(uint32_t code, IpcIo *req, IpcIo *reply) +{ + WIFI_LOGD("WifiScanStub run %{public}s code %{public}u", __func__, code); + std::vector result; + ErrCode ret = GetScanInfoList(result); + (void)WriteInt32(reply, 0); + (void)WriteInt32(reply, ret); + if (ret != WIFI_OPT_SUCCESS) { + return ret; + } + + unsigned int size = result.size(); + (void)WriteInt32(reply, size); + for (unsigned int i = 0; i < size; ++i) { + (void)WriteString(reply, result[i].bssid.c_str()); + (void)WriteString(reply, result[i].ssid.c_str()); + (void)WriteString(reply, result[i].capabilities.c_str()); + (void)WriteInt32(reply, result[i].frequency); + (void)WriteInt32(reply, result[i].rssi); + (void)WriteUint64(reply, result[i].timestamp); + (void)WriteInt32(reply, result[i].band); + (void)WriteInt32(reply, static_cast(result[i].securityType)); + (void)WriteInt32(reply, static_cast(result[i].channelWidth)); + (void)WriteInt32(reply, result[i].centerFrequency0); + (void)WriteInt32(reply, result[i].centerFrequency1); + (void)WriteUint64(reply, result[i].features); + (void)WriteInt32(reply, result[i].infoElems.size()); + for (unsigned int m = 0; m < result[i].infoElems.size(); ++m) { + (void)WriteUint32(reply, result[i].infoElems[m].id); + (void)WriteInt32(reply, result[i].infoElems[m].content.size()); + for (unsigned int n = 0; n < result[i].infoElems[m].content.size(); ++n) { + (void)WriteInt8(reply, result[i].infoElems[m].content[n]); + } + } + } + return ret; +} + +int WifiScanStub::OnRegisterCallBack(uint32_t code, IpcIo *req, IpcIo *reply) +{ + WIFI_LOGD("run %{public}s code %{public}u", __func__, code); + ErrCode ret = WIFI_OPT_FAILED; + SvcIdentity sid; + bool readSid = ReadRemoteObject(req, &sid); + if (!readSid) { + WIFI_LOGE("read SvcIdentity failed"); + (void)WriteInt32(reply, 0); + (void)WriteInt32(reply, ret); + return ret; + } + + callback_ = std::make_shared(&sid); + WIFI_LOGD("create new WifiScanCallbackProxy!"); + ret = RegisterCallBack(callback_); + + (void)WriteInt32(reply, 0); + (void)WriteInt32(reply, ret); + return 0; +} + +int WifiScanStub::OnGetSupportedFeatures(uint32_t code, IpcIo *req, IpcIo *reply) +{ + WIFI_LOGD("WifiScanStub run %{public}s code %{public}u", __func__, code); + long features = 0; + int ret = GetSupportedFeatures(features); + (void)WriteInt32(reply, 0); + (void)WriteInt32(reply, ret); + + if (ret == WIFI_OPT_SUCCESS) { + (void)WriteUint64(reply, features); + } + + return ret; +} +} // namespace Wifi +} // namespace OHOS diff --git a/wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_scan_stub_lite.h b/wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_scan_stub_lite.h new file mode 100644 index 0000000000000000000000000000000000000000..c2c6b59d0760a45c119af2f671f4b61d3f59671c --- /dev/null +++ b/wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_scan_stub_lite.h @@ -0,0 +1,49 @@ +/* + * Copyright (C) 2022 Huawei Device Co., Ltd. + * 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 OHOS_WIFI_SCAN_STUB_LITE_H +#define OHOS_WIFI_SCAN_STUB_LITE_H + +#include +#include "i_wifi_scan.h" +#include "i_wifi_scan_callback.h" +#include "serializer.h" + +namespace OHOS { +namespace Wifi { +class WifiScanStub : public IWifiScan { +public: + WifiScanStub(); + virtual ~WifiScanStub() override; + + virtual int OnRemoteRequest(uint32_t code, IpcIo *req, IpcIo *reply); + +protected: + std::shared_ptr GetCallback() const; + +private: + int OnSetScanControlInfo(uint32_t code, IpcIo *req, IpcIo *reply); + int OnScan(uint32_t code, IpcIo *req, IpcIo *reply); + int OnScanByParams(uint32_t code, IpcIo *req, IpcIo *reply); + int OnIsWifiClosedScan(uint32_t code, IpcIo *req, IpcIo *reply); + int OnGetScanInfoList(uint32_t code, IpcIo *req, IpcIo *reply); + int OnRegisterCallBack(uint32_t code, IpcIo *req, IpcIo *reply); + int OnGetSupportedFeatures(uint32_t code, IpcIo *req, IpcIo *reply); + + std::shared_ptr callback_; +}; +} // namespace Wifi +} // namespace OHOS +#endif diff --git a/tests/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/test/wifi_p2p_test_entry.cpp b/wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_service_main_lite.c similarity index 55% rename from tests/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/test/wifi_p2p_test_entry.cpp rename to wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_service_main_lite.c index 4d6c9d3975b5bb2f64cf580649df7a2e115bb077..f386fe12fbd7c2b0db2f00cfc82a0a9946038336 100644 --- a/tests/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/test/wifi_p2p_test_entry.cpp +++ b/wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_service_main_lite.c @@ -1,5 +1,5 @@ /* - * Copyright (C) 2021 Huawei Device Co., Ltd. + * Copyright (C) 2022 Huawei Device Co., Ltd. * 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 @@ -12,16 +12,28 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -#include -#include "global_test.h" +#include +#include "samgr_lite.h" +#include "wifi_log.h" -using ::testing::ext::TestSize; +#undef LOG_TAG +#define LOG_TAG "wifi_service_main_lite" + +#define SLEEP_TIME 1 + +void __attribute__((weak)) OHOS_SystemInit(void) +{ +#ifdef __LINUX__ + sleep(SLEEP_TIME); // delay start to make sure register success +#endif + SAMGR_Bootstrap(); +}; int main(int argc, char *argv[]) { - testing::InitGoogleTest(&argc, argv); - testing::Environment *env = new GlobalTest(); - testing::AddGlobalTestEnvironment(env); - return RUN_ALL_TESTS(); -} \ No newline at end of file + LOGD("Wifi service system init enter"); + OHOS_SystemInit(); + LOGD("Wifi service system init exit"); + pause(); +} diff --git a/services/wifi_standard/wifi_framework/wifi_manage/wifi_service_manager.cpp b/wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_service_manager.cpp similarity index 60% rename from services/wifi_standard/wifi_framework/wifi_manage/wifi_service_manager.cpp rename to wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_service_manager.cpp index 40a6f06da86d76af17db4d8b34e26a9dbdc8d829..7eb1e0db2f86afff85bff77f6492cc82058e2030 100644 --- a/services/wifi_standard/wifi_framework/wifi_manage/wifi_service_manager.cpp +++ b/wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_service_manager.cpp @@ -1,5 +1,5 @@ /* - * Copyright (C) 2021 Huawei Device Co., Ltd. + * Copyright (C) 2021-2022 Huawei Device Co., Ltd. * 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 @@ -12,16 +12,16 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + #include "wifi_service_manager.h" #include #include "wifi_logger.h" #include "define.h" #include "wifi_settings.h" -DEFINE_WIFILOG_LABEL("WifiServiceManager"); - namespace OHOS { namespace Wifi { +DEFINE_WIFILOG_LABEL("WifiServiceManager"); WifiServiceManager &WifiServiceManager::GetInstance() { static WifiServiceManager gWifiServiceManager; @@ -36,11 +36,27 @@ WifiServiceManager::~WifiServiceManager() int WifiServiceManager::Init() { +#ifdef OHOS_ARCH_LITE + mServiceDllMap.insert(std::make_pair(WIFI_SERVICE_STA, "libwifi_sta_service.so")); + mServiceDllMap.insert(std::make_pair(WIFI_SERVICE_SCAN, "libwifi_scan_service.so")); +#ifdef FEATURE_AP_SUPPORT + mServiceDllMap.insert(std::make_pair(WIFI_SERVICE_AP, "libwifi_ap_service.so")); +#endif +#ifdef FEATURE_P2P_SUPPORT + mServiceDllMap.insert(std::make_pair(WIFI_SERVICE_P2P, "libwifi_p2p_service.so")); +#endif + mServiceDllMap.insert(std::make_pair(WIFI_SERVICE_AWARE, "libwifi_aware_service.so")); +#else mServiceDllMap.insert(std::make_pair(WIFI_SERVICE_STA, "libwifi_sta_service.z.so")); mServiceDllMap.insert(std::make_pair(WIFI_SERVICE_SCAN, "libwifi_scan_service.z.so")); +#ifdef FEATURE_AP_SUPPORT mServiceDllMap.insert(std::make_pair(WIFI_SERVICE_AP, "libwifi_ap_service.z.so")); +#endif +#ifdef FEATURE_P2P_SUPPORT mServiceDllMap.insert(std::make_pair(WIFI_SERVICE_P2P, "libwifi_p2p_service.z.so")); +#endif mServiceDllMap.insert(std::make_pair(WIFI_SERVICE_AWARE, "libwifi_aware_service.z.so")); +#endif return 0; } @@ -70,7 +86,10 @@ int WifiServiceManager::CheckPreLoadService(void) int WifiServiceManager::LoadStaService(const std::string &dlname, bool bCreate) { + WIFI_LOGI("WifiServiceManager::LoadStaService"); + std::unique_lock lock(mStaMutex); if (mStaServiceHandle.handle != nullptr) { + WIFI_LOGE("WifiServiceManager::handle is not null: %{public}s", dlname.c_str()); return 0; } mStaServiceHandle.handle = dlopen(dlname.c_str(), RTLD_LAZY); @@ -81,7 +100,7 @@ int WifiServiceManager::LoadStaService(const std::string &dlname, bool bCreate) mStaServiceHandle.create = (IStaService *(*)()) dlsym(mStaServiceHandle.handle, "Create"); mStaServiceHandle.destroy = (void *(*)(IStaService *))dlsym(mStaServiceHandle.handle, "Destroy"); if (mStaServiceHandle.create == nullptr || mStaServiceHandle.destroy == nullptr) { - WIFI_LOGE("%{public}s dlsym Create or Destory failed!", dlname.c_str()); + WIFI_LOGE("%{public}s dlsym Create or Destroy failed!", dlname.c_str()); dlclose(mStaServiceHandle.handle); mStaServiceHandle.Clear(); return -1; @@ -94,7 +113,10 @@ int WifiServiceManager::LoadStaService(const std::string &dlname, bool bCreate) int WifiServiceManager::LoadScanService(const std::string &dlname, bool bCreate) { + WIFI_LOGI("WifiServiceManager::LoadScanService"); + std::unique_lock lock(mScanMutex); if (mScanServiceHandle.handle != nullptr) { + WIFI_LOGE("WifiServiceManager::handle is not null: %{public}s", dlname.c_str()); return 0; } mScanServiceHandle.handle = dlopen(dlname.c_str(), RTLD_LAZY); @@ -105,7 +127,7 @@ int WifiServiceManager::LoadScanService(const std::string &dlname, bool bCreate) mScanServiceHandle.create = (IScanService *(*)()) dlsym(mScanServiceHandle.handle, "Create"); mScanServiceHandle.destroy = (void *(*)(IScanService *))dlsym(mScanServiceHandle.handle, "Destroy"); if (mScanServiceHandle.create == nullptr || mScanServiceHandle.destroy == nullptr) { - WIFI_LOGE("%{public}s dlsym Create or Destory failed!", dlname.c_str()); + WIFI_LOGE("%{public}s dlsym Create or Destroy failed!", dlname.c_str()); dlclose(mScanServiceHandle.handle); mScanServiceHandle.Clear(); return -1; @@ -116,9 +138,13 @@ int WifiServiceManager::LoadScanService(const std::string &dlname, bool bCreate) return 0; } +#ifdef FEATURE_AP_SUPPORT int WifiServiceManager::LoadApService(const std::string &dlname, bool bCreate) { + WIFI_LOGI("WifiServiceManager::LoadApService"); + std::unique_lock lock(mApMutex); if (mApServiceHandle.handle != nullptr) { + WIFI_LOGE("WifiServiceManager::handle is not null: %{public}s", dlname.c_str()); return 0; } mApServiceHandle.handle = dlopen(dlname.c_str(), RTLD_LAZY); @@ -126,23 +152,32 @@ int WifiServiceManager::LoadApService(const std::string &dlname, bool bCreate) WIFI_LOGE("dlopen %{public}s failed: %{public}s!", dlname.c_str(), dlerror()); return -1; } - mApServiceHandle.create = (IApService *(*)()) dlsym(mApServiceHandle.handle, "Create"); + mApServiceHandle.create = (IApService *(*)(int)) dlsym(mApServiceHandle.handle, "Create"); mApServiceHandle.destroy = (void *(*)(IApService *))dlsym(mApServiceHandle.handle, "Destroy"); if (mApServiceHandle.create == nullptr || mApServiceHandle.destroy == nullptr) { - WIFI_LOGE("%{public}s dlsym Create or Destory failed!", dlname.c_str()); + WIFI_LOGE("%{public}s dlsym Create or Destroy failed!", dlname.c_str()); dlclose(mApServiceHandle.handle); mApServiceHandle.Clear(); return -1; } if (bCreate) { - mApServiceHandle.pService = mApServiceHandle.create(); + IApService *service = mApServiceHandle.create(0); + auto ret = mApServiceHandle.pService.emplace(0, service); + if (!ret.second) { + mApServiceHandle.pService[0] = service; + } } return 0; } +#endif +#ifdef FEATURE_P2P_SUPPORT int WifiServiceManager::LoadP2pService(const std::string &dlname, bool bCreate) { + WIFI_LOGI("WifiServiceManager::LoadP2pService"); + std::unique_lock lock(mP2pMutex); if (mP2pServiceHandle.handle != nullptr) { + WIFI_LOGE("WifiServiceManager::handle is not null: %{public}s", dlname.c_str()); return 0; } mP2pServiceHandle.handle = dlopen(dlname.c_str(), RTLD_LAZY); @@ -153,7 +188,7 @@ int WifiServiceManager::LoadP2pService(const std::string &dlname, bool bCreate) mP2pServiceHandle.create = (IP2pService *(*)()) dlsym(mP2pServiceHandle.handle, "Create"); mP2pServiceHandle.destroy = (void *(*)(IP2pService *))dlsym(mP2pServiceHandle.handle, "Destroy"); if (mP2pServiceHandle.create == nullptr || mP2pServiceHandle.destroy == nullptr) { - WIFI_LOGE("%{public}s dlsym Create or Destory failed!", dlname.c_str()); + WIFI_LOGE("%{public}s dlsym Create or Destroy failed!", dlname.c_str()); dlclose(mP2pServiceHandle.handle); mP2pServiceHandle.Clear(); return -1; @@ -163,6 +198,8 @@ int WifiServiceManager::LoadP2pService(const std::string &dlname, bool bCreate) } return 0; } +#endif + int WifiServiceManager::CheckAndEnforceService(const std::string &name, bool bCreate) { WIFI_LOGD("WifiServiceManager::CheckAndEnforceService name: %{public}s", name.c_str()); @@ -172,81 +209,102 @@ int WifiServiceManager::CheckAndEnforceService(const std::string &name, bool bCr return -1; } WIFI_LOGD("WifiServiceManager::CheckAndEnforceService get dllname: %{public}s", dlname.c_str()); - std::unique_lock lock(mMutex); if (name == WIFI_SERVICE_STA) { return LoadStaService(dlname, bCreate); } if (name == WIFI_SERVICE_SCAN) { return LoadScanService(dlname, bCreate); } +#ifdef FEATURE_AP_SUPPORT if (name == WIFI_SERVICE_AP) { return LoadApService(dlname, bCreate); } +#endif +#ifdef FEATURE_P2P_SUPPORT if (name == WIFI_SERVICE_P2P) { return LoadP2pService(dlname, bCreate); } +#endif return -1; } IStaService *WifiServiceManager::GetStaServiceInst() { + WIFI_LOGI("WifiServiceManager::GetStaServiceInst"); + std::unique_lock lock(mStaMutex); if (mStaServiceHandle.handle == nullptr) { + WIFI_LOGE("WifiServiceManager, Sta handle is null"); return nullptr; } if (mStaServiceHandle.pService == nullptr) { - std::unique_lock lock(mMutex); - if (mStaServiceHandle.pService == nullptr) { - mStaServiceHandle.pService = mStaServiceHandle.create(); - } + mStaServiceHandle.pService = mStaServiceHandle.create(); } return mStaServiceHandle.pService; } IScanService *WifiServiceManager::GetScanServiceInst() { + WIFI_LOGI("WifiServiceManager::GetScanServiceInst"); + std::unique_lock lock(mScanMutex); if (mScanServiceHandle.handle == nullptr) { + WIFI_LOGE("WifiServiceManager, Scan handle is null"); return nullptr; } if (mScanServiceHandle.pService == nullptr) { - std::unique_lock lock(mMutex); - if (mScanServiceHandle.pService == nullptr) { - mScanServiceHandle.pService = mScanServiceHandle.create(); - } + mScanServiceHandle.pService = mScanServiceHandle.create(); } return mScanServiceHandle.pService; } -IApService *WifiServiceManager::GetApServiceInst() +#ifdef FEATURE_AP_SUPPORT +IApService *WifiServiceManager::GetApServiceInst(int id) { + WIFI_LOGI("WifiServiceManager::GetApServiceInst"); + std::unique_lock lock(mApMutex); if (mApServiceHandle.handle == nullptr) { + WIFI_LOGE("Get ap service instance handle is null."); return nullptr; } - if (mApServiceHandle.pService == nullptr) { - std::unique_lock lock(mMutex); - if (mApServiceHandle.pService == nullptr) { - mApServiceHandle.pService = mApServiceHandle.create(); - } + + auto findInstance = [this, id]() -> IApService* { + auto it = mApServiceHandle.pService.find(id); + return (it != mApServiceHandle.pService.end()) ? it->second : nullptr; + }; + auto apInstance = findInstance(); + if (apInstance != nullptr) { + WIFI_LOGI("Ap service instance is exist %{public}d", id); + return apInstance; } - return mApServiceHandle.pService; + + WIFI_LOGI("[Get] create a new ap service instance: %{public}d", id); + IApService *service = mApServiceHandle.create(id); + mApServiceHandle.pService[id] = service; + return service; } +#endif +#ifdef FEATURE_P2P_SUPPORT IP2pService *WifiServiceManager::GetP2pServiceInst() { + WIFI_LOGI("WifiServiceManager::GetP2pServiceInst"); + std::unique_lock lock(mP2pMutex); if (mP2pServiceHandle.handle == nullptr) { + WIFI_LOGE("WifiServiceManager, P2p handle is null"); return nullptr; } if (mP2pServiceHandle.pService == nullptr) { - std::unique_lock lock(mMutex); - if (mP2pServiceHandle.pService == nullptr) { - mP2pServiceHandle.pService = mP2pServiceHandle.create(); - } + mP2pServiceHandle.pService = mP2pServiceHandle.create(); } return mP2pServiceHandle.pService; } +#endif int WifiServiceManager::UnloadStaService(bool bPreLoad) { + WIFI_LOGI("WifiServiceManager::UnloadStaService"); + std::unique_lock lock(mStaMutex); if (mStaServiceHandle.handle == nullptr) { + WIFI_LOGE("WifiServiceManager::UnloadStaService handle is null"); return 0; } if (mStaServiceHandle.pService != nullptr) { @@ -262,7 +320,10 @@ int WifiServiceManager::UnloadStaService(bool bPreLoad) int WifiServiceManager::UnloadScanService(bool bPreLoad) { + WIFI_LOGI("WifiServiceManager::UnloadScanService"); + std::unique_lock lock(mScanMutex); if (mScanServiceHandle.handle == nullptr) { + WIFI_LOGE("WifiServiceManager::UnloadScanService handle is null"); return 0; } if (mScanServiceHandle.pService != nullptr) { @@ -276,25 +337,49 @@ int WifiServiceManager::UnloadScanService(bool bPreLoad) return 0; } -int WifiServiceManager::UnloadApService(bool bPreLoad) +#ifdef FEATURE_AP_SUPPORT +int WifiServiceManager::UnloadApService(bool bPreLoad, int id) { - if (mApServiceHandle.handle == nullptr) { - return 0; - } - if (mApServiceHandle.pService != nullptr) { - mApServiceHandle.destroy(mApServiceHandle.pService); - mApServiceHandle.pService = nullptr; + WIFI_LOGI("WifiServiceManager::UnloadApService id=%{public}d, max_id=%{public}d", id, AP_INSTANCE_MAX_NUM); + { + std::unique_lock lock(mApMutex); + if (mApServiceHandle.handle == nullptr) { + WIFI_LOGE("WifiServiceManager::UnloadApService handle is null"); + return 0; + } } - if (!bPreLoad) { - dlclose(mApServiceHandle.handle); - mApServiceHandle.Clear(); + + /* Unload all ap service */ + if (id == ALL_AP_ID) { + for (int i = 0; i < AP_INSTANCE_MAX_NUM; i++) { + UnloadApService(bPreLoad, i); + } + } else { + std::unique_lock lock(mApMutex); + auto iter = mApServiceHandle.pService.find(id); + if (iter != mApServiceHandle.pService.end()) { + if (iter->second != nullptr) { + mApServiceHandle.destroy(iter->second); + iter->second = nullptr; + } + mApServiceHandle.pService.erase(id); + } + if (!bPreLoad && mApServiceHandle.pService.empty()) { + dlclose(mApServiceHandle.handle); + mApServiceHandle.Clear(); + } } return 0; } +#endif +#ifdef FEATURE_P2P_SUPPORT int WifiServiceManager::UnloadP2pService(bool bPreLoad) { + WIFI_LOGI("WifiServiceManager::UnloadP2pService"); + std::unique_lock lock(mP2pMutex); if (mP2pServiceHandle.handle == nullptr) { + WIFI_LOGE("WifiServiceManager::UnloadP2pService handle is null"); return 0; } if (mP2pServiceHandle.pService != nullptr) { @@ -307,35 +392,43 @@ int WifiServiceManager::UnloadP2pService(bool bPreLoad) } return 0; } +#endif -int WifiServiceManager::UnloadService(const std::string &name) +int WifiServiceManager::UnloadService(const std::string &name, int id) { bool bPreLoad = WifiSettings::GetInstance().IsModulePreLoad(name); - WIFI_LOGD("WifiServiceManager::UnloadService name: %{public}s", name.c_str()); - std::unique_lock lock(mMutex); + WIFI_LOGI("WifiServiceManager::UnloadService name: %{public}s", name.c_str()); if (name == WIFI_SERVICE_STA) { return UnloadStaService(bPreLoad); } if (name == WIFI_SERVICE_SCAN) { return UnloadScanService(bPreLoad); } +#ifdef FEATURE_AP_SUPPORT if (name == WIFI_SERVICE_AP) { - return UnloadApService(bPreLoad); + return UnloadApService(bPreLoad, id); } +#endif +#ifdef FEATURE_P2P_SUPPORT if (name == WIFI_SERVICE_P2P) { return UnloadP2pService(bPreLoad); } +#endif return -1; } void WifiServiceManager::UninstallAllService() { - WIFI_LOGD("WifiServiceManager::UninstallAllService"); + WIFI_LOGI("WifiServiceManager::UninstallAllService"); UnloadStaService(false); UnloadScanService(false); - UnloadApService(false); +#ifdef FEATURE_AP_SUPPORT + UnloadApService(false, ALL_AP_ID); /* all ap services */ +#endif +#ifdef FEATURE_P2P_SUPPORT UnloadP2pService(false); +#endif return; } } // namespace Wifi -} // namespace OHOS \ No newline at end of file +} // namespace OHOS diff --git a/services/wifi_standard/wifi_framework/wifi_manage/wifi_service_manager.h b/wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_service_manager.h similarity index 87% rename from services/wifi_standard/wifi_framework/wifi_manage/wifi_service_manager.h rename to wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_service_manager.h index 95a3027a528de0142d1812126b886677656ada0b..6f59df00b9d925e60f2714364cac0470718dfbf4 100644 --- a/services/wifi_standard/wifi_framework/wifi_manage/wifi_service_manager.h +++ b/wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_service_manager.h @@ -22,8 +22,12 @@ #include "ista_service.h" #include "iscan_service.h" +#ifdef FEATURE_AP_SUPPORT #include "i_ap_service.h" +#endif +#ifdef FEATURE_P2P_SUPPORT #include "ip2p_service.h" +#endif namespace OHOS { namespace Wifi { @@ -63,12 +67,14 @@ struct ScanServiceHandle { } }; +#ifdef FEATURE_AP_SUPPORT +#define ALL_AP_ID 0xffff struct ApServiceHandle { void *handle; - IApService *(*create)(); + IApService *(*create)(int id); void *(*destroy)(IApService *); - IApService *pService; - ApServiceHandle() : handle(nullptr), create(nullptr), destroy(nullptr), pService(nullptr) + std::map pService; + ApServiceHandle() : handle(nullptr), create(nullptr), destroy(nullptr) {} ~ApServiceHandle() {} @@ -77,10 +83,12 @@ struct ApServiceHandle { handle = nullptr; create = nullptr; destroy = nullptr; - pService = nullptr; + pService.clear(); } }; +#endif +#ifdef FEATURE_P2P_SUPPORT struct P2pServiceHandle { void *handle; IP2pService *(*create)(); @@ -98,6 +106,7 @@ struct P2pServiceHandle { pService = nullptr; } }; +#endif class WifiServiceManager { public: @@ -141,19 +150,23 @@ public: */ IScanService *GetScanServiceInst(void); +#ifdef FEATURE_AP_SUPPORT /** * @Description Get the Ap Service Inst object * * @return IApService* - ap service pointer, if ap not supported, nullptr is returned */ - IApService *GetApServiceInst(void); + IApService *GetApServiceInst(int id = 0); +#endif +#ifdef FEATURE_P2P_SUPPORT /** * @Description Get the P2P Service Inst object * * @return IP2pService* - p2p service pointer, if p2p not supported, nullptr is returned */ IP2pService *GetP2pServiceInst(void); +#endif /** * @Description unload a feature service @@ -161,7 +174,7 @@ public: * @param name - feature service name * @return int - 0 success */ - int UnloadService(const std::string &name); + int UnloadService(const std::string &name, int id = 0); /** * @Description Uninstall all loaded feature services @@ -176,18 +189,29 @@ private: int UnloadStaService(bool bPreLoad); int LoadScanService(const std::string &dlname, bool bCreate); int UnloadScanService(bool bPreLoad); +#ifdef FEATURE_AP_SUPPORT int LoadApService(const std::string &dlname, bool bCreate); - int UnloadApService(bool bPreLoad); + int UnloadApService(bool bPreLoad, int id = 0); +#endif +#ifdef FEATURE_P2P_SUPPORT int LoadP2pService(const std::string &dlname, bool bCreate); int UnloadP2pService(bool bPreLoad); +#endif private: - std::mutex mMutex; + std::mutex mStaMutex; + std::mutex mScanMutex; + std::mutex mP2pMutex; + std::mutex mApMutex; std::unordered_map mServiceDllMap; StaServiceHandle mStaServiceHandle; ScanServiceHandle mScanServiceHandle; +#ifdef FEATURE_AP_SUPPORT ApServiceHandle mApServiceHandle; +#endif +#ifdef FEATURE_P2P_SUPPORT P2pServiceHandle mP2pServiceHandle; +#endif }; } // namespace Wifi } // namespace OHOS diff --git a/wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_sta/BUILD.gn b/wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_sta/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..cecfd7770636959fa2aded3461a613d2dc0800ad --- /dev/null +++ b/wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_sta/BUILD.gn @@ -0,0 +1,134 @@ +# Copyright (C) 2021-2022 Huawei Device Co., Ltd. +# 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. + +if (defined(ohos_lite)) { + import("//build/lite/config/component/lite_component.gni") + import("//foundation/communication/wifi/wifi/wifi_lite.gni") +} else { + import("//build/ohos.gni") + import("//foundation/communication/wifi/wifi/wifi.gni") +} + +local_base_sources = [ + "../common/handler.cpp", + "../common/internal_message.cpp", + "../common/message_queue.cpp", + "../common/state.cpp", + "../common/state_machine.cpp", + "sta_auto_connect_service.cpp", + "sta_interface.cpp", + "sta_monitor.cpp", + "sta_network_check.cpp", + "sta_saved_device_appraisal.cpp", + "sta_service.cpp", + "sta_state_machine.cpp", +] + +local_base_include_dirs = [ + "$WIFI_ROOT_DIR/services/wifi_standard/sdk/include", + "$WIFI_ROOT_DIR/frameworks/native/interfaces", + "$WIFI_ROOT_DIR/services/wifi_standard/ipc_framework/interface", + "$WIFI_ROOT_DIR/services/wifi_standard/ipc_framework/cRPC/include", + "$WIFI_ROOT_DIR/services/wifi_standard/wifi_framework/wifi_toolkit/include", + "$WIFI_ROOT_DIR/services/wifi_standard/wifi_framework/wifi_toolkit/net_helper", + "$WIFI_ROOT_DIR/services/wifi_standard/wifi_framework/wifi_toolkit/log", + "$WIFI_ROOT_DIR/services/wifi_standard/wifi_framework/wifi_toolkit/utils", + "$WIFI_ROOT_DIR/services/wifi_standard/wifi_framework/wifi_toolkit/config", + "$WIFI_ROOT_DIR/services/wifi_standard/wifi_framework/wifi_manage/common", + "$WIFI_ROOT_DIR/services/wifi_standard/wifi_framework/wifi_manage/wifi_scan", + "$WIFI_ROOT_DIR/services/wifi_standard/wifi_framework/wifi_manage/idl_client", + "$WIFI_ROOT_DIR/services/wifi_standard/wifi_framework/wifi_manage/idl_client/idl_interface", + "$WIFI_ROOT_DIR/services/wifi_standard/wifi_framework/wifi_manage/wifi_sta/net_conf", + "$WIFI_ROOT_DIR/services/wifi_standard/wifi_framework/wifi_manage/wifi_sta", + "$DHCP_ROOT_DIR/services/mgr_service/include", + "$DHCP_ROOT_DIR/interfaces/inner_api/include", + "$DHCP_ROOT_DIR/interfaces/inner_api/interfaces", + "$WIFI_ROOT_DIR/utils/inc", + "$WIFI_ROOT_DIR/services/wifi_standard/wifi_framework/wifi_manage", + "$WIFI_ROOT_DIR/services/wifi_standard/wifi_framework/wifi_manage/wifi_common", + "$WIFI_ROOT_DIR/services/wifi_standard/include", +] + +if (defined(ohos_lite)) { + shared_library("wifi_sta_service") { + sources = local_base_sources + + include_dirs = local_base_include_dirs + include_dirs += [ + "//base/hiviewdfx/hilog_lite/interfaces/native/innerkits", + "//third_party/bounds_checking_function/include", + ] + + deps = [ + "$DHCP_ROOT_DIR/services/mgr_service:dhcp_manager_service", + "$WIFI_ROOT_DIR/services/wifi_standard/wifi_framework/wifi_manage:wifi_service_base", + "$WIFI_ROOT_DIR/services/wifi_standard/wifi_framework/wifi_manage/idl_client:wifi_idl_client", + "$WIFI_ROOT_DIR/services/wifi_standard/wifi_framework/wifi_toolkit:wifi_toolkit", + "$WIFI_ROOT_DIR/utils:wifi_utils", + "//base/hiviewdfx/hilog_lite/frameworks/featured:hilog_shared", + "//third_party/bounds_checking_function:libsec_shared", + ] + + configs -= [ "//build/lite/config:language_cpp" ] + cflags_cc = [ + "-std=c++17", + "-fno-rtti", + ] + + defines = [ "OHOS_ARCH_LITE" ] + ldflags = [ + "-fPIC", + "-Wl,-E", + ] + } +} else { + ohos_shared_library("wifi_sta_service") { + install_enable = true + sources = local_base_sources + + include_dirs = local_base_include_dirs + include_dirs += [ + "//base/hiviewdfx/hilog/interfaces/native/innerkits/include", + "//foundation/communication/ipc/interfaces/innerkits/ipc_core/include", + "//commonlibrary/c_utils/base/include", + ] + + cflags_cc = [ + "-std=c++17", + "-fno-rtti", + ] + + ldflags = [ + "-fPIC", + "-Wl,-E", + ] + + deps = [ + "$DHCP_ROOT_DIR/services/mgr_service:dhcp_manager_service", + "$WIFI_ROOT_DIR/services/wifi_standard/wifi_framework/wifi_manage:wifi_manager_service", + "$WIFI_ROOT_DIR/services/wifi_standard/wifi_framework/wifi_manage/idl_client:wifi_idl_client", + "$WIFI_ROOT_DIR/services/wifi_standard/wifi_framework/wifi_manage/wifi_common:wifi_common_service", + "$WIFI_ROOT_DIR/services/wifi_standard/wifi_framework/wifi_toolkit:wifi_toolkit", + "$WIFI_ROOT_DIR/utils:wifi_utils", + ] + + external_deps = [ + "c_utils:utils", + "hiviewdfx_hilog_native:libhilog", + "netmanager_base:net_conn_manager_if", + ] + + part_name = "wifi" + subsystem_name = "communication" + } +} diff --git a/services/wifi_standard/wifi_framework/wifi_manage/wifi_sta/ista_service.h b/wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_sta/ista_service.h similarity index 78% rename from services/wifi_standard/wifi_framework/wifi_manage/wifi_sta/ista_service.h rename to wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_sta/ista_service.h index 4d636e587497a56d2bdbced15c28057bb8c6c4d9..686a47bea5f1073575893f4c702718d1f6fd37a8 100644 --- a/services/wifi_standard/wifi_framework/wifi_manage/wifi_sta/ista_service.h +++ b/wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_sta/ista_service.h @@ -72,12 +72,55 @@ public: * @Return success: WIFI_OPT_SUCCESS fail: WIFI_OPT_FAILED */ virtual ErrCode Disconnect() = 0; + /** + * @Description ReConnect network + * + * @Return success: WIFI_OPT_SUCCESS fail: WIFI_OPT_FAILED + */ + virtual ErrCode ReConnect() = 0; /** * @Description ReAssociate network * * @Return success: WIFI_OPT_SUCCESS fail: WIFI_OPT_FAILED */ virtual ErrCode ReAssociate() = 0; + + /** + * @Description Add a specified candidate hotspot configuration. + * + * @param uid - call app uid + * @param config - WifiDeviceConfig object + * @param netWorkId - the network id of the hotspot configuration.(out) + * @Return success: WIFI_OPT_SUCCESS fail: WIFI_OPT_FAILED + */ + virtual ErrCode AddCandidateConfig(const int uid, const WifiDeviceConfig &config, int& netWorkId) = 0; + + /** + * @Description Connect to a candidate specified network. + * + * @param uid - call app uid + * @param networkId - the candidate device network id + * @Return ErrCode - operation result + */ + virtual ErrCode ConnectToCandidateConfig(const int uid, const int networkId) = 0; + + /** + * @Description Remove the wifi candidate device config equals to input network id + * + * @param uid - call app uid + * @param networkId - the candidate device network id + * @return ErrCode - operation result + */ + virtual ErrCode RemoveCandidateConfig(const int uid, const int networkId) = 0; + + /** + * @Description Remove all the wifi candidate device config equals to input uid + * + * @param uid - call app uid + * @return ErrCode - operation result + */ + virtual ErrCode RemoveAllCandidateConfig(const int uid) = 0; + /** * @Description Add a network to config * @@ -160,6 +203,13 @@ public: * @return ErrCode - success: WIFI_OPT_SUCCESS fail: WIFI_OPT_FAILED */ virtual ErrCode RegisterStaServiceCallback(const StaServiceCallback &callbacks) = 0; + /** + * @Description send suspend mode for wpa. + * + * @param mode: true for suspend, false for resume. + * @return WifiErrorNo + */ + virtual ErrCode SetSuspendMode(bool mode) = 0; }; } // namespace Wifi } // namespace OHOS diff --git a/services/wifi_standard/wifi_framework/wifi_manage/wifi_sta/sta_auto_connect_service.cpp b/wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_sta/sta_auto_connect_service.cpp old mode 100755 new mode 100644 similarity index 80% rename from services/wifi_standard/wifi_framework/wifi_manage/wifi_sta/sta_auto_connect_service.cpp rename to wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_sta/sta_auto_connect_service.cpp index b640c4c834678002b50c0324f7edf5b9da264297..725cb5e987f93ad169121d8d9c5e9e3e19d3e932 --- a/services/wifi_standard/wifi_framework/wifi_manage/wifi_sta/sta_auto_connect_service.cpp +++ b/wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_sta/sta_auto_connect_service.cpp @@ -16,6 +16,7 @@ #include "wifi_logger.h" #include "wifi_sta_hal_interface.h" #include "wifi_settings.h" +#include "wifi_common_util.h" DEFINE_WIFILOG_LABEL("StaAutoConnectService"); @@ -24,7 +25,7 @@ namespace Wifi { StaAutoConnectService::StaAutoConnectService(StaStateMachine *staStateMachine) : pStaStateMachine(staStateMachine), pSavedDeviceAppraisal(nullptr), - firmwareRoamFlag(false), + firmwareRoamFlag(true), maxBlockedBssidNum(BLOCKLIST_INVALID_SIZE), selectDeviceLastTime(0), pAppraisals {nullptr, nullptr, nullptr, nullptr, nullptr, nullptr} @@ -76,15 +77,21 @@ void StaAutoConnectService::OnScanInfosReadyHandler(const std::vector blockedBssids; GetBlockedBssids(blockedBssids); WifiDeviceConfig electedDevice; if (AutoSelectDevice(electedDevice, scanInfos, blockedBssids, info) == WIFI_OPT_SUCCESS) { - WIFI_LOGI("AutoSelectDevice succeed.\n"); + WIFI_LOGI("AutoSelectDevice succeed: " + "[networkId:%{public}d, ssid:%{public}s, bssid:%{public}s, psk len:%{public}d].", + electedDevice.networkId, SsidAnonymize(electedDevice.ssid).c_str(), + MacAnonymize(electedDevice.bssid).c_str(), (int)electedDevice.preSharedKey.length()); ConnectElectedDevice(electedDevice); } else { - WIFI_LOGI("Exit network selection.\n"); + WIFI_LOGI("AutoSelectDevice return fail."); return; } } @@ -145,11 +152,18 @@ bool StaAutoConnectService::AddOrDelBlockedBssids(std::string bssid, bool enable void StaAutoConnectService::GetBlockedBssids(std::vector &blockedBssids) { - WIFI_LOGI("Enter StaAutoConnectService::GetBlockedBssids.\n"); - for (auto iter = blockedBssidMap.begin(); iter != blockedBssidMap.end(); ++iter) { blockedBssids.push_back(iter->first); } + WIFI_LOGI("StaAutoConnectService::GetBlockedBssids, blockedBssids count: %{public}d.", + (int)blockedBssids.size()); + return; +} + +void StaAutoConnectService::ClearAllBlockedBssids() +{ + WIFI_LOGI("Enter StaAutoConnectService::ClearAllBlockedBssids.\n"); + blockedBssidMap.clear(); return; } @@ -157,6 +171,7 @@ void StaAutoConnectService::ClearOvertimeBlockedBssid() { WIFI_LOGI("Enter StaAutoConnectService::ClearOvertimeBlockedBssid.\n"); if (blockedBssidMap.empty()) { + WIFI_LOGI("blockedBssidMap is empty !\n"); return; } bool updated = false; @@ -165,6 +180,8 @@ void StaAutoConnectService::ClearOvertimeBlockedBssid() BlockedBssidInfo status = iter->second; time_t now = time(0); int currentTimeStap = (int)now; + WIFI_LOGI("blockedFlag:%{public}d, currentTimeStap:%{public}d, blockedTime:%{public}d.\n", + status.blockedFlag, currentTimeStap, status.blockedTime); if (status.blockedFlag && ((currentTimeStap - status.blockedTime) >= MAX_BSSID_BLOCKLIST_TIME)) { blockedBssidMap.erase(iter++); updated = true; @@ -182,7 +199,7 @@ void StaAutoConnectService::ConnectElectedDevice(WifiDeviceConfig &electedDevice { WIFI_LOGI("Enter StaAutoConnectService::ConnectElectedDevice.\n"); if (electedDevice.bssid.empty()) { - WIFI_LOGE("electedDevice is null.\n"); + WIFI_LOGE("electedDevice bssid is empty."); return; } @@ -192,18 +209,18 @@ void StaAutoConnectService::ConnectElectedDevice(WifiDeviceConfig &electedDevice currentConnectedNetwork.ssid == electedDevice.ssid && currentConnectedNetwork.bssid != electedDevice.bssid) { /* Frameworks start roaming only when firmware is not supported */ if (!firmwareRoamFlag) { - WIFI_LOGI("Roaming connectTo.\n"); + WIFI_LOGI("Roaming connectTo, networkId: %{public}d.\n", electedDevice.networkId); pStaStateMachine->StartRoamToNetwork(electedDevice.bssid); - WIFI_LOGI("connecTo network bssid is %s", electedDevice.bssid.c_str()); } - } else if (currentConnectedNetwork.detailedState == DetailedState::DISCONNECTED) { - WIFI_LOGI("connecTo save network.\n"); + } else if (currentConnectedNetwork.detailedState == DetailedState::DISCONNECTED || + currentConnectedNetwork.detailedState == DetailedState::CONNECTION_TIMEOUT || + currentConnectedNetwork.detailedState == DetailedState::FAILED || + currentConnectedNetwork.detailedState == DetailedState::PASSWORD_ERROR) { pStaStateMachine->SendMessage(WIFI_SVR_CMD_STA_CONNECT_SAVED_NETWORK, electedDevice.networkId, NETWORK_SELECTED_FOR_CONNECTION_MANAGEMENT); - WIFI_LOGI("connecTo networkId is %{public}d", electedDevice.networkId); - WIFI_LOGI("connecTo bssid is %s", electedDevice.bssid.c_str()); - WIFI_LOGI("connecTo preShareKey is %s", electedDevice.preSharedKey.c_str()); + WIFI_LOGI("connectTo save networkId: %{public}d, preShareKey len: %{public}d.\n", + electedDevice.networkId, (int)electedDevice.preSharedKey.length()); } else { WIFI_LOGE("The current connection status is %{public}d.\n", currentConnectedNetwork.detailedState); } @@ -304,7 +321,7 @@ ErrCode StaAutoConnectService::AutoSelectDevice(WifiDeviceConfig &electedDevice, { WIFI_LOGI("Enter StaAutoConnectService::SelectNetwork.\n"); if (scanInfos.empty()) { - WIFI_LOGE("No scanInfo.\n"); + WIFI_LOGE("scanInfo is empty."); return WIFI_OPT_FAILED; } @@ -314,9 +331,6 @@ ErrCode StaAutoConnectService::AutoSelectDevice(WifiDeviceConfig &electedDevice, return WIFI_OPT_FAILED; } - /* Before initiating network selection, update all configured networks. */ - RefreshConfigDevice(); - std::vector availableScanInfos; /* Filter out unnecessary networks. */ GetAvailableScanInfos(availableScanInfos, scanInfos, blockedBssids, info); @@ -385,9 +399,10 @@ bool StaAutoConnectService::RoamingEncryptionModeCheck( mgmt = "NONE"; } if (mgmt == network.keyMgmt) { - WIFI_LOGI("The Current network bssid %s signal strength is %{public}d", info.bssid.c_str(), info.rssi); - WIFI_LOGI( - "The Roaming network bssid %s signal strength is %{public}d", scanInfo.bssid.c_str(), scanInfo.rssi); + WIFI_LOGI("The Current network bssid %{public}s signal strength is %{public}d", + MacAnonymize(info.bssid).c_str(), info.rssi); + WIFI_LOGI("The Roaming network bssid %{public}s signal strength is %{public}d", + MacAnonymize(scanInfo.bssid).c_str(), scanInfo.rssi); int rssi = scanInfo.rssi - info.rssi; if (rssi > MIN_ROAM_RSSI_DIFF) { WIFI_LOGI("Roming network rssi - Current network rssi > 6."); @@ -406,59 +421,59 @@ bool StaAutoConnectService::RoamingEncryptionModeCheck( bool StaAutoConnectService::AllowAutoSelectDevice(const std::vector &scanInfos, WifiLinkedInfo &info) { - WIFI_LOGI("Enter StaAutoConnectService::AllowAutoSelectDevice.\n"); + WIFI_LOGI("Allow auto select device, connState=%{public}d, detailedState=%{public}d\n", + info.connState, info.detailedState); if (scanInfos.empty()) { WIFI_LOGE("No network,skip network selection.\n"); return false; } - /* Connected to the network */ - if (info.detailedState == DetailedState::WORKING) { - WIFI_LOGI("The current connection status is Connected and working.\n"); - - /* Configure whether to automatically switch the network. */ - if (!WifiSettings::GetInstance().GetWhetherToAllowNetworkSwitchover()) { - WIFI_LOGE("Automatic network switching is not allowed in user " - "configuration.\n"); - return false; - } - /* - * Indicates whether the minimum interval is the minimum interval since the - * last network selection. - */ - if (selectDeviceLastTime != 0) { - int gap = static_cast(time(0)) - selectDeviceLastTime; - if (gap < MIN_SELECT_NETWORK_TIME) { - WIFI_LOGE("%ds time before we selected the network(30s).\n", gap); + switch (info.detailedState) { + case DetailedState::WORKING: + /* Configure whether to automatically switch the network. */ + if (!WifiSettings::GetInstance().GetWhetherToAllowNetworkSwitchover()) { + WIFI_LOGE("Automatic network switching is not allowed in user configuration.\n"); return false; } - } + /* Indicates whether the minimum interval is the minimum interval since the last network selection. */ + if (selectDeviceLastTime != 0) { + int gap = static_cast(time(0)) - selectDeviceLastTime; + if (gap < MIN_SELECT_NETWORK_TIME) { + WIFI_LOGE("%ds time before we selected the network(30s).\n", gap); + return false; + } + } - if (CurrentDeviceGoodEnough(scanInfos, info)) { - WIFI_LOGE("The current network is suffice.\n"); + if (!CurrentDeviceGoodEnough(scanInfos, info)) { + WIFI_LOGI("The current network is insuffice.\n"); + return true; + } return false; - } else { - WIFI_LOGI("The current network is insuffice.\n"); + + case DetailedState::DISCONNECTED: + case DetailedState::CONNECTION_TIMEOUT: + case DetailedState::FAILED: + WIFI_LOGI("Auto Select is allowed, detailedState: %{public}d\n", info.detailedState); + return true; + case DetailedState::PASSWORD_ERROR: + WIFI_LOGI("Password error, clear blocked bssids, auto connect to ap quickly.\n"); + ClearAllBlockedBssids(); return true; - } - } else if (info.detailedState == DetailedState::DISCONNECTED) { - WIFI_LOGI("The current connection status is Disconnected.\n"); - return true; - } else if (info.detailedState == DetailedState::NOTWORKING) { - WIFI_LOGI("The current network cannot access the Internet.\n"); - /* Configure whether to automatically switch the network. */ - if (!WifiSettings::GetInstance().GetWhetherToAllowNetworkSwitchover()) { - WIFI_LOGE("Automatic network switching is not allowed in user " - "configuration.\n"); - return false; - } else { + case DetailedState::NOTWORKING: + WIFI_LOGI("The current network cannot access the Internet.\n"); + /* Configure whether to automatically switch the network. */ + if (!WifiSettings::GetInstance().GetWhetherToAllowNetworkSwitchover()) { + WIFI_LOGE("Automatic network switching is not allowed in user configuration.\n"); + return false; + } return true; - } - } else { - WIFI_LOGE("The current connection status is %{public}d.\n", info.detailedState); - return false; + + default: + WIFI_LOGE("not allowed auto select!\n"); + return false; } + return false; } bool StaAutoConnectService::CurrentDeviceGoodEnough(const std::vector &scanInfos, WifiLinkedInfo &info) @@ -542,23 +557,6 @@ bool StaAutoConnectService::Whether5GDevice(int frequency) } } -void StaAutoConnectService::RefreshConfigDevice() -{ - WIFI_LOGI("Enter StaAutoConnectService::RefreshConfigDevice.\n"); - std::vector configs; - WifiSettings::GetInstance().GetDeviceConfig(configs); - if (configs.empty()) { - WIFI_LOGE("No config networks.\n"); - return; - } - for (auto network : configs) { - if (network.status == 1) { - WIFI_LOGI("The network is disable.networkId is %{public}d.", network.networkId); - } - } - return; -} - void StaAutoConnectService::GetAvailableScanInfos(std::vector &availableScanInfos, const std::vector &scanInfos, std::vector &blockedBssids, WifiLinkedInfo &info) { @@ -580,19 +578,21 @@ void StaAutoConnectService::GetAvailableScanInfos(std::vector &av auto itr = find(blockedBssids.begin(), blockedBssids.end(), scanInfo.bssid); if (itr != blockedBssids.end()) { /* Skip Blocklist Network */ - WIFI_LOGI("Skip blocklistedBssid network %s.\n", scanInfo.ssid.c_str()); + WIFI_LOGI("Skip blocklistedBssid network, ssid: %{public}s.\n", SsidAnonymize(scanInfo.ssid).c_str()); continue; } /* Skipping networks with weak signals */ if (scanInfo.frequency < MIN_5GHZ_BAND_FREQUENCY) { if (scanInfo.rssi <= MIN_RSSI_VALUE_24G) { - WIFI_LOGI("Skip network %s with low 2.4G signals %{public}d.\n", scanInfo.ssid.c_str(), scanInfo.rssi); + WIFI_LOGI("Skip network %{public}s with low 2.4G signals %{public}d.\n", + SsidAnonymize(scanInfo.ssid).c_str(), scanInfo.rssi); continue; } } else { if (scanInfo.rssi <= MIN_RSSI_VALUE_5G) { - WIFI_LOGI("Skip network %s with low 5G signals %{public}d.\n", scanInfo.ssid.c_str(), scanInfo.rssi); + WIFI_LOGI("Skip network %{public}s with low 5G signals %{public}d.\n", + SsidAnonymize(scanInfo.ssid).c_str(), scanInfo.rssi); continue; } } @@ -611,4 +611,4 @@ void StaAutoConnectService::GetAvailableScanInfos(std::vector &av return; } } // namespace Wifi -} // namespace OHOS \ No newline at end of file +} // namespace OHOS diff --git a/services/wifi_standard/wifi_framework/wifi_manage/wifi_sta/sta_auto_connect_service.h b/wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_sta/sta_auto_connect_service.h old mode 100755 new mode 100644 similarity index 97% rename from services/wifi_standard/wifi_framework/wifi_manage/wifi_sta/sta_auto_connect_service.h rename to wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_sta/sta_auto_connect_service.h index b4936c6b4b25aba093464466736ff3f39d2ca8ce..4f7d7004116cc63255881aa258be4182ef40309a --- a/services/wifi_standard/wifi_framework/wifi_manage/wifi_sta/sta_auto_connect_service.h +++ b/wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_sta/sta_auto_connect_service.h @@ -1,5 +1,5 @@ /* - * Copyright (C) 2021 Huawei Device Co., Ltd. + * Copyright (C) 2021-2022 Huawei Device Co., Ltd. * 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 @@ -32,7 +32,7 @@ namespace OHOS { namespace Wifi { static const int MAX_BSSID_BLOCKLIST_COUNT = 3; static const int AP_CANNOT_HANDLE_NEW_STA = 17; -static const int MAX_BSSID_BLOCKLIST_TIME = 5 * 60; +static const int MAX_BSSID_BLOCKLIST_TIME = 60; // 60s static const int BLOCKLIST_INVALID_SIZE = -1; static const int STA_CAP_ROAMING = 0x800000; static const int MIN_APPRAISAL_PRIORITY = 6; @@ -109,6 +109,11 @@ private: ~BlockedBssidInfo(){} }; std::unordered_map blockedBssidMap; + /** + * @Description Clear all BSSIDs in BSSID Blocklist + * + */ + void ClearAllBlockedBssids(); /** * @Description Refreshing the BSSID Blocklist * @@ -151,7 +156,7 @@ private: */ bool SetRoamBlockedBssidFirmware(const std::vector &blocklistBssids) const; /** - * @Description Connect to a elected device + * @Description Connect to an elected device * * @param electedDevice - Elected Device(in) */ @@ -209,11 +214,6 @@ private: * @Return success : true failed : false */ bool RoamingEncryptionModeCheck(WifiDeviceConfig &electedDevice, InterScanInfo scanInfo, WifiLinkedInfo &info); - /** - * @Description Updating the Configuration Center Device. - * - */ - void RefreshConfigDevice(); /** * @Description Whether the device is a 2.4G device. * diff --git a/services/wifi_standard/wifi_framework/wifi_manage/wifi_sta/sta_define.h b/wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_sta/sta_define.h similarity index 75% rename from services/wifi_standard/wifi_framework/wifi_manage/wifi_sta/sta_define.h rename to wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_sta/sta_define.h index 4ecebb028c2a2cc7bd2b3e68ba485260576caa6f..f1b90c927c45ebcb5e6450565f038f081cd1c0fa 100644 --- a/services/wifi_standard/wifi_framework/wifi_manage/wifi_sta/sta_define.h +++ b/wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_sta/sta_define.h @@ -1,5 +1,5 @@ /* - * Copyright (C) 2021 Huawei Device Co., Ltd. + * Copyright (C) 2021-2022 Huawei Device Co., Ltd. * 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 @@ -12,6 +12,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + #ifndef OHOS_STA_DEFINE_H #define OHOS_STA_DEFINE_H @@ -24,19 +25,15 @@ namespace Wifi { #define WIFI_SVR_CMD_STA_ENABLE_WIFI 0x2001 #define WIFI_SVR_CMD_STA_DISABLE_WIFI 0x2002 -#define WIFI_SVR_CMD_STA_START_SUPPLICANT 0x2003 -#define WIFI_SVR_CMD_STA_OPERATIONAL_MODE 0x2004 -#define WIFI_SVR_CMD_STA_STOP_SUPPLICANT 0x2005 -#define WIFI_SVR_CMD_STA_CONNECT_NETWORK 0x2006 -#define WIFI_SVR_CMD_STA_CONNECT_SAVED_NETWORK 0x2007 -#define WIFI_SVR_CMD_STA_REMOVE_DEVICE_CONFIG 0x2008 -#define WIFI_SVR_CMD_STA_RECONNECT_NETWORK 0x2009 -#define WIFI_SVR_CMD_STA_REMOVE_All_DEVICE_CONFIG 0x2010 -#define WIFI_SVR_CMD_STA_REASSOCIATE_NETWORK 0x200A -#define WIFI_SVR_CMD_STA_DISCONNECT 0x200B -#define WIFI_SVR_CMD_STA_STARTWPS 0x200C -#define WIFI_SVR_CMD_STA_CANCELWPS 0x200D -#define WIFI_SVR_COM_STA_START_ROAM 0x200E +#define WIFI_SVR_CMD_STA_OPERATIONAL_MODE 0x2003 +#define WIFI_SVR_CMD_STA_CONNECT_NETWORK 0x2004 +#define WIFI_SVR_CMD_STA_CONNECT_SAVED_NETWORK 0x2005 +#define WIFI_SVR_CMD_STA_RECONNECT_NETWORK 0x2006 +#define WIFI_SVR_CMD_STA_REASSOCIATE_NETWORK 0x2007 +#define WIFI_SVR_CMD_STA_DISCONNECT 0x2008 +#define WIFI_SVR_CMD_STA_STARTWPS 0x2009 +#define WIFI_SVR_CMD_STA_CANCELWPS 0x200A +#define WIFI_SVR_COM_STA_START_ROAM 0x200B #define WIFI_SVR_CMD_STA_ERROR 0x3001 #define WIFI_SVR_CMD_STA_SUP_CONNECTION_EVENT 0x3002 @@ -61,6 +58,10 @@ namespace Wifi { #define WIFI_SVR_CMD_STA_CONFIG_MULTIPLE_PBC_DETECTED 0x3015 #define WIFI_SVR_CMD_STA_WPA_STATE_CHANGE_EVENT 0x3016 #define WIFI_SVR_CMD_STA_WPA_PASSWD_WRONG_EVENT 0x3017 +#define WIFI_SVR_CMD_STA_WPA_FULL_CONNECT_EVENT 0x3018 +#define WIFI_SVR_CMD_STA_WPA_ASSOC_REJECT_EVENT 0x3019 +#define WIFI_SVR_CMD_STA_BSSID_CHANGED_EVENT 0x301A +#define WIFI_SVR_CMD_STA_DHCP_RESULT_NOTIFY_EVENT 0x301B #define WPA_BLOCK_LIST_CLEAR_EVENT 0x4001 @@ -78,21 +79,15 @@ const int NETWORK_5G_BAND = 2; #define BAND_2_G 1 #define BAND_5_G 2 -typedef enum EnumStaIpType { - IPTYPE_IPV4, - IPTYPE_IPV6, - IPTYPE_MIX, - IPTYPE_BUTT, -} StaIpType; - typedef enum EnumStaNetState { - NETWORK_STATE_UNKNOW, + NETWORK_STATE_UNKNOWN, NETWORK_STATE_WORKING, + NETWORK_CHECK_PORTAL, NETWORK_STATE_NOWORKING, NETWORK_STATE_BUTT, } StaNetState; -typedef std::function NetStateHandler; +using NetStateHandler = std::function; } // namespace Wifi } // namespace OHOS #endif /* OHOS_STA_DEFINE_H */ diff --git a/services/wifi_standard/wifi_framework/wifi_manage/wifi_sta/sta_device_appraisal.h b/wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_sta/sta_device_appraisal.h old mode 100755 new mode 100644 similarity index 100% rename from services/wifi_standard/wifi_framework/wifi_manage/wifi_sta/sta_device_appraisal.h rename to wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_sta/sta_device_appraisal.h diff --git a/services/wifi_standard/wifi_framework/wifi_manage/wifi_sta/sta_interface.cpp b/wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_sta/sta_interface.cpp old mode 100755 new mode 100644 similarity index 65% rename from services/wifi_standard/wifi_framework/wifi_manage/wifi_sta/sta_interface.cpp rename to wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_sta/sta_interface.cpp index d4a64ec592540db0afff40faac486795031a03c2..4e7a96912059a9c678afe57e7863f841d2149736 --- a/services/wifi_standard/wifi_framework/wifi_manage/wifi_sta/sta_interface.cpp +++ b/wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_sta/sta_interface.cpp @@ -1,5 +1,5 @@ /* - * Copyright (C) 2021 Huawei Device Co., Ltd. + * Copyright (C) 2021-2022 Huawei Device Co., Ltd. * 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 @@ -12,6 +12,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + #include "sta_interface.h" #include "sta_service.h" #include "wifi_logger.h" @@ -28,6 +29,7 @@ StaInterface::~StaInterface() WIFI_LOGI("StaInterface::~StaInterface"); if (pStaService != nullptr) { delete pStaService; + pStaService = nullptr; } } @@ -39,11 +41,12 @@ extern "C" IStaService *Create(void) extern "C" void Destroy(IStaService *pservice) { delete pservice; + pservice = nullptr; } ErrCode StaInterface::EnableWifi() { - WIFI_LOGD("Enter StaInterface::EnableWifi.\n"); + WIFI_LOGI("Enter StaInterface::EnableWifi.\n"); if(pStaService == nullptr) { pStaService = new (std::nothrow) StaService(); if (pStaService == nullptr) { @@ -70,6 +73,7 @@ ErrCode StaInterface::EnableWifi() ErrCode StaInterface::DisableWifi() { LOGD("Enter StaInterface::DisableWifi.\n"); + CHECK_NULL_AND_RETURN(pStaService, WIFI_OPT_FAILED); if (pStaService->DisableWifi() != WIFI_OPT_SUCCESS) { LOGD("DisableWifi failed.\n"); return WIFI_OPT_FAILED; @@ -80,6 +84,7 @@ ErrCode StaInterface::DisableWifi() ErrCode StaInterface::ConnectToNetwork(int networkId) { LOGD("Enter StaInterface::Connect.\n"); + CHECK_NULL_AND_RETURN(pStaService, WIFI_OPT_FAILED); if (pStaService->ConnectToNetwork(networkId) != WIFI_OPT_SUCCESS) { LOGD("ConnectTo failed.\n"); return WIFI_OPT_FAILED; @@ -90,6 +95,7 @@ ErrCode StaInterface::ConnectToNetwork(int networkId) ErrCode StaInterface::ConnectToDevice(const WifiDeviceConfig &config) { LOGD("Enter StaInterface::Connect.\n"); + CHECK_NULL_AND_RETURN(pStaService, WIFI_OPT_FAILED); if (pStaService->ConnectToDevice(config) != WIFI_OPT_SUCCESS) { LOGD("ConnectTo failed.\n"); return WIFI_OPT_FAILED; @@ -97,9 +103,21 @@ ErrCode StaInterface::ConnectToDevice(const WifiDeviceConfig &config) return WIFI_OPT_SUCCESS; } +ErrCode StaInterface::ReConnect() +{ + LOGD("Enter StaInterface::ReConnect.\n"); + CHECK_NULL_AND_RETURN(pStaService, WIFI_OPT_FAILED); + if (pStaService->ReConnect() != WIFI_OPT_SUCCESS) { + LOGD("ReConnect failed.\n"); + return WIFI_OPT_FAILED; + } + return WIFI_OPT_SUCCESS; +} + ErrCode StaInterface::ReAssociate() { LOGD("Enter StaInterface::ReAssociate.\n"); + CHECK_NULL_AND_RETURN(pStaService, WIFI_OPT_FAILED); if (pStaService->ReAssociate() != WIFI_OPT_SUCCESS) { LOGD("ReAssociate failed.\n"); return WIFI_OPT_FAILED; @@ -110,6 +128,7 @@ ErrCode StaInterface::ReAssociate() ErrCode StaInterface::Disconnect() { LOGD("Enter StaInterface::Disconnect.\n"); + CHECK_NULL_AND_RETURN(pStaService, WIFI_OPT_FAILED); if (pStaService->Disconnect() != WIFI_OPT_SUCCESS) { LOGD("Disconnect failed.\n"); return WIFI_OPT_FAILED; @@ -117,9 +136,50 @@ ErrCode StaInterface::Disconnect() return WIFI_OPT_SUCCESS; } +ErrCode StaInterface::AddCandidateConfig(const int uid, const WifiDeviceConfig &config, int& netWorkId) +{ + LOGD("Enter StaInterface::AddCandidateConfig.\n"); + CHECK_NULL_AND_RETURN(pStaService, WIFI_OPT_FAILED); + return pStaService->AddCandidateConfig(uid, config, netWorkId); +} + +ErrCode StaInterface::ConnectToCandidateConfig(const int uid, const int networkId) +{ + LOGD("Enter StaInterface::ConnectToCandidateConfig.\n"); + CHECK_NULL_AND_RETURN(pStaService, WIFI_OPT_FAILED); + if (pStaService->ConnectToCandidateConfig(uid, networkId) != WIFI_OPT_SUCCESS) { + LOGE("ConnectToCandidateConfig failed.\n"); + return WIFI_OPT_FAILED; + } + return WIFI_OPT_SUCCESS; +} + +ErrCode StaInterface::RemoveCandidateConfig(const int uid, const int networkId) +{ + LOGD("Enter StaInterface::RemoveCandidateConfig.\n"); + CHECK_NULL_AND_RETURN(pStaService, WIFI_OPT_FAILED); + if (pStaService->RemoveCandidateConfig(uid, networkId) != WIFI_OPT_SUCCESS) { + LOGE("RemoveCandidateConfig failed.\n"); + return WIFI_OPT_FAILED; + } + return WIFI_OPT_SUCCESS; +} + +ErrCode StaInterface::RemoveAllCandidateConfig(const int uid) +{ + LOGD("Enter StaInterface::RemoveAllCandidateConfig.\n"); + CHECK_NULL_AND_RETURN(pStaService, WIFI_OPT_FAILED); + if (pStaService->RemoveAllCandidateConfig(uid) != WIFI_OPT_SUCCESS) { + LOGE("RemoveAllCandidateConfig failed.\n"); + return WIFI_OPT_FAILED; + } + return WIFI_OPT_SUCCESS; +} + int StaInterface::AddDeviceConfig(const WifiDeviceConfig &config) { LOGD("Enter StaInterface::AddDeviceConfig.\n"); + CHECK_NULL_AND_RETURN(pStaService, WIFI_OPT_FAILED); return pStaService->AddDeviceConfig(config); } @@ -132,6 +192,7 @@ int StaInterface::UpdateDeviceConfig(const WifiDeviceConfig &config) ErrCode StaInterface::RemoveDevice(int networkId) { LOGD("Enter StaInterface::RemoveDeviceConfig.\n"); + CHECK_NULL_AND_RETURN(pStaService, WIFI_OPT_FAILED); if (pStaService->RemoveDevice(networkId) != WIFI_OPT_SUCCESS) { LOGD("RemoveDeviceConfig failed.\n"); return WIFI_OPT_FAILED; @@ -142,9 +203,9 @@ ErrCode StaInterface::RemoveDevice(int networkId) ErrCode StaInterface::RemoveAllDevice() { WIFI_LOGD("Enter StaInterface::RemoveAllDevice.\n"); - + CHECK_NULL_AND_RETURN(pStaService, WIFI_OPT_FAILED); if (pStaService->RemoveAllDevice() != WIFI_OPT_SUCCESS) { - WIFI_LOGD("RemoveAllDevice failed.\n"); + WIFI_LOGW("RemoveAllDevice failed.\n"); return WIFI_OPT_FAILED; } return WIFI_OPT_SUCCESS; @@ -152,18 +213,21 @@ ErrCode StaInterface::RemoveAllDevice() ErrCode StaInterface::EnableDeviceConfig(int networkId, bool attemptEnable) { LOGD("Enter StaInterface::EnableDeviceConfig.\n"); + CHECK_NULL_AND_RETURN(pStaService, WIFI_OPT_FAILED); return pStaService->EnableDeviceConfig(networkId, attemptEnable); } ErrCode StaInterface::DisableDeviceConfig(int networkId) { LOGD("Enter StaInterface::DisableDeviceConfig.\n"); + CHECK_NULL_AND_RETURN(pStaService, WIFI_OPT_FAILED); return pStaService->DisableDeviceConfig(networkId); } ErrCode StaInterface::StartWps(const WpsConfig &config) { LOGD("Enter StaInterface::StartWps.\n"); + CHECK_NULL_AND_RETURN(pStaService, WIFI_OPT_FAILED); if (pStaService->StartWps(config) != WIFI_OPT_SUCCESS) { LOGD("StartWps failed.\n"); return WIFI_OPT_FAILED; @@ -174,6 +238,7 @@ ErrCode StaInterface::StartWps(const WpsConfig &config) ErrCode StaInterface::CancelWps() { LOGD("Enter StaInterface::CancelWps.\n"); + CHECK_NULL_AND_RETURN(pStaService, WIFI_OPT_FAILED); if (pStaService->CancelWps() != WIFI_OPT_SUCCESS) { LOGD("CancelWps failed.\n"); return WIFI_OPT_FAILED; @@ -184,6 +249,7 @@ ErrCode StaInterface::CancelWps() ErrCode StaInterface::ConnectivityManager(const std::vector &scanInfos) { LOGI("Enter Connection management.\n"); + CHECK_NULL_AND_RETURN(pStaService, WIFI_OPT_FAILED); if (pStaService->AutoConnectService(scanInfos) != WIFI_OPT_SUCCESS) { LOGD("ConnectivityManager failed.\n"); return WIFI_OPT_FAILED; @@ -194,6 +260,7 @@ ErrCode StaInterface::ConnectivityManager(const std::vector &scan ErrCode StaInterface::SetCountryCode(const std::string &countryCode) { LOGD("Enter StaInterface::SetCountryCode.\n"); + CHECK_NULL_AND_RETURN(pStaService, WIFI_OPT_FAILED); if (pStaService->SetCountryCode(countryCode) != WIFI_OPT_SUCCESS) { LOGD("SetCountryCode failed.\n"); return WIFI_OPT_FAILED; @@ -208,5 +275,14 @@ ErrCode StaInterface::RegisterStaServiceCallback(const StaServiceCallback &callb return WIFI_OPT_SUCCESS; } +ErrCode StaInterface::SetSuspendMode(bool mode) +{ + LOGI("Enter StaInterface::SetSuspendMode, mode=[%{public}d]!", mode); + if (pStaService->SetSuspendMode(mode) != WIFI_OPT_SUCCESS) { + LOGE("SetSuspendMode() failed!"); + return WIFI_OPT_FAILED; + } + return WIFI_OPT_SUCCESS; +} } // namespace Wifi } // namespace OHOS diff --git a/services/wifi_standard/wifi_framework/wifi_manage/wifi_sta/sta_interface.h b/wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_sta/sta_interface.h similarity index 79% rename from services/wifi_standard/wifi_framework/wifi_manage/wifi_sta/sta_interface.h rename to wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_sta/sta_interface.h index df405d4f1c90a7fba61570a1e80135e8c8793190..7ff968249e83ff8736f068215a38e009e20ea5bc 100644 --- a/services/wifi_standard/wifi_framework/wifi_manage/wifi_sta/sta_interface.h +++ b/wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_sta/sta_interface.h @@ -76,12 +76,50 @@ public: * @Return success: WIFI_OPT_SUCCESS fail: WIFI_OPT_FAILED */ virtual ErrCode Disconnect() override; + /** + * @Description ReConnect network + * + * @Return success: WIFI_OPT_SUCCESS fail: WIFI_OPT_FAILED + */ + virtual ErrCode ReConnect() override; /** * @Description ReAssociate network * * @Return success: WIFI_OPT_SUCCESS fail: WIFI_OPT_FAILED */ virtual ErrCode ReAssociate() override; + /** + * @Description Add a specified candidate hotspot configuration. + * + * @param uid - call app uid + * @param config - WifiDeviceConfig object + * @param netWorkId - the network id of the hotspot configuration.(out) + * @Return success: WIFI_OPT_SUCCESS fail: WIFI_OPT_FAILED + */ + ErrCode AddCandidateConfig(const int uid, const WifiDeviceConfig &config, int& netWorkId) override; + /** + * @Description Connecting to a candidate specified network. + * + * @param uid - call app uid + * @param networkId - the candidate device network id + * @Return ErrCode - operation result + */ + ErrCode ConnectToCandidateConfig(const int uid, const int networkId) override; + /** + * @Description Remove the wifi candidate device config equals to input network id + * + * @param uid - call app uid + * @param networkId - the candidate device network id + * @return ErrCode - operation result + */ + ErrCode RemoveCandidateConfig(const int uid, const int networkId) override; + /** + * @Description Remove all the wifi candidate device config equals to input uid + * + * @param uid - call app uid + * @return ErrCode - operation result + */ + ErrCode RemoveAllCandidateConfig(const int uid) override; /** * @Description Add a network to config * @@ -164,7 +202,13 @@ public: * @return ErrCode - success: WIFI_OPT_SUCCESS fail: WIFI_OPT_FAILED */ virtual ErrCode RegisterStaServiceCallback(const StaServiceCallback &callbacks) override; - + /** + * @Description send suspend mode for wpa. + * + * @param mode: true for suspend, false for resume. + * @return WifiErrorNo + */ + virtual ErrCode SetSuspendMode(bool mode) override; private: StaServiceCallback staCallback; StaService *pStaService; diff --git a/services/wifi_standard/wifi_framework/wifi_manage/wifi_sta/sta_monitor.cpp b/wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_sta/sta_monitor.cpp similarity index 64% rename from services/wifi_standard/wifi_framework/wifi_manage/wifi_sta/sta_monitor.cpp rename to wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_sta/sta_monitor.cpp index 368f7fb0c7cf4f565328621d7cd5ae21eb71efc7..306502cdc27227e13d5a663763c48f81fd8d2820 100644 --- a/services/wifi_standard/wifi_framework/wifi_manage/wifi_sta/sta_monitor.cpp +++ b/wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_sta/sta_monitor.cpp @@ -1,5 +1,5 @@ /* - * Copyright (C) 2021 Huawei Device Co., Ltd. + * Copyright (C) 2021-2022 Huawei Device Co., Ltd. * 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 @@ -18,6 +18,7 @@ #include "wifi_logger.h" #include "wifi_supplicant_hal_interface.h" #include "wifi_sta_hal_interface.h" +#include "wifi_common_util.h" DEFINE_WIFILOG_LABEL("StaMonitor"); @@ -37,10 +38,13 @@ ErrCode StaMonitor::InitStaMonitor() using namespace std::placeholders; WifiEventCallback callBack = { std::bind(&StaMonitor::OnConnectChangedCallBack, this, _1, _2, _3), + std::bind(&StaMonitor::OnBssidChangedCallBack, this, _1, _2), std::bind(&StaMonitor::OnWpaStateChangedCallBack, this, _1), std::bind(&StaMonitor::OnWpaSsidWrongKeyCallBack, this, _1), std::bind(&StaMonitor::OnWpsPbcOverlapCallBack, this, _1), - std::bind(&StaMonitor::OnWpsTimeOutCallBack, this, _1) + std::bind(&StaMonitor::OnWpsTimeOutCallBack, this, _1), + std::bind(&StaMonitor::onWpaConnectionFullCallBack, this, _1), + std::bind(&StaMonitor::onWpaConnectionRejectCallBack, this, _1) }; if (WifiStaHalInterface::GetInstance().RegisterStaEventCallback(callBack) != WIFI_IDL_OPT_OK) { @@ -70,16 +74,27 @@ void StaMonitor::SetStateMachine(StaStateMachine *paraStaStateMachine) pStaStateMachine = paraStaStateMachine; return; } -void StaMonitor::OnConnectChangedCallBack(int status, int networkId,const std::string &bssid) + +void StaMonitor::OnConnectChangedCallBack(int status, int networkId, const std::string &bssid) { - WIFI_LOGI("OnConnectChangedCallBack() status:%{public}d,networkId=%{public}d,bssid={private}%s", + WIFI_LOGI("OnConnectChangedCallBack() status:%{public}d,networkId=%{public}d,bssid=%{public}s", status, networkId, - bssid.c_str()); + MacAnonymize(bssid).c_str()); if (pStaStateMachine == nullptr) { WIFI_LOGE("The statemachine pointer is null."); return; } + + WifiLinkedInfo linkedInfo; + pStaStateMachine->GetLinkedInfo(linkedInfo); + /* P2P affects STA, causing problems or incorrect data updates */ + if ((linkedInfo.connState == ConnState::CONNECTED) && + (linkedInfo.bssid != bssid) && (!pStaStateMachine->IsRoaming())) { + WIFI_LOGI("Sta ignored the event for bssid is mismatch, isRoam:%{public}d.", + pStaStateMachine->IsRoaming()); + return; + } switch (status) { case WPA_CB_CONNECTED: { pStaStateMachine->OnNetworkConnectionEvent(networkId, bssid); @@ -94,6 +109,30 @@ void StaMonitor::OnConnectChangedCallBack(int status, int networkId,const std::s } } +void StaMonitor::OnBssidChangedCallBack(const std::string &reason, const std::string &bssid) +{ + WIFI_LOGI("OnBssidChangedCallBack() reason:%{public}s,bssid=%{public}s", + reason.c_str(), + MacAnonymize(bssid).c_str()); + if (pStaStateMachine == nullptr) { + WIFI_LOGE("The statemachine pointer is null."); + return; + } + + WifiLinkedInfo linkedInfo; + pStaStateMachine->GetLinkedInfo(linkedInfo); + if (linkedInfo.connState != ConnState::CONNECTED) { + WIFI_LOGW("Sta ignored the event for NOT in connected status!, connState: %{public}d", + linkedInfo.connState); + return; + } + if (linkedInfo.bssid == bssid) { + WIFI_LOGW("Sta ignored the event for bssid is the same."); + return; + } + pStaStateMachine->OnBssidChangedEvent(reason, bssid); +} + void StaMonitor::OnWpaStateChangedCallBack(int status) { WIFI_LOGI("OnWpaStateChangedCallBack() status:%{public}d\n", status); @@ -118,8 +157,33 @@ void StaMonitor::OnWpaSsidWrongKeyCallBack(int status) return; } /* Notification state machine wpa password wrong event. */ - pStaStateMachine->SendMessage(WIFI_SVR_CMD_STA_WPA_PASSWD_WRONG_EVENT, status); + pStaStateMachine->SendMessage(WIFI_SVR_CMD_STA_WPA_PASSWD_WRONG_EVENT); } + +void StaMonitor::onWpaConnectionFullCallBack(int status) +{ + LOGI("onWpaConnectionFullCallBack() status:%d.\n", status); + if (pStaStateMachine == nullptr) { + WIFI_LOGE("The statemachine pointer is null."); + return; + } + + /* Notification state machine wpa password wrong event. */ + pStaStateMachine->SendMessage(WIFI_SVR_CMD_STA_WPA_FULL_CONNECT_EVENT); +} + +void StaMonitor::onWpaConnectionRejectCallBack(int status) +{ + LOGI("onWpsConnectionRejectCallBack() status:%d.\n", status); + if (pStaStateMachine == nullptr) { + WIFI_LOGE("The statemachine pointer is null."); + return; + } + + /* Notification state machine wpa password wrong event. */ + pStaStateMachine->SendMessage(WIFI_SVR_CMD_STA_WPA_ASSOC_REJECT_EVENT); +} + void StaMonitor::OnWpsPbcOverlapCallBack(int status) { WIFI_LOGI("OnWpsPbcOverlapCallBack() status:%{public}d\n", status); diff --git a/services/wifi_standard/wifi_framework/wifi_manage/wifi_sta/sta_monitor.h b/wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_sta/sta_monitor.h similarity index 79% rename from services/wifi_standard/wifi_framework/wifi_manage/wifi_sta/sta_monitor.h rename to wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_sta/sta_monitor.h index 1c717141a5042e623026647d711856707a113dbf..e011bd2ba8a136da4695d4dd70a102cc2a4a3f35 100644 --- a/services/wifi_standard/wifi_framework/wifi_manage/wifi_sta/sta_monitor.h +++ b/wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_sta/sta_monitor.h @@ -59,15 +59,21 @@ public: * @param status : status codes [in] * @param networkId - network id [in] * @param bssid - bssid of the network [in] - * @param pInstance - handles [in] */ void OnConnectChangedCallBack(int status, int networkId,const std::string &bssid); + /** + * @Description : Callback of the connection state change event. + * + * @param reason : reason for bssid change [in] + * @param bssid: bssid of the network [in] + */ + void OnBssidChangedCallBack(const std::string &reason, const std::string &bssid); + /** * @Description : Callback of the wpa state change event. * * @param status - status codes [in] - * @param pInstance - handles [in] */ void OnWpaStateChangedCallBack(int status); @@ -75,15 +81,27 @@ public: * @Description : Callback of the Wpa ssid wrong key event. * * @param status - status codes [in] - * @param pInstance - handles [in] */ void OnWpaSsidWrongKeyCallBack(int status); + /** + * @Description : Callback of the Connection Full event. + * + * @param status - status codes [in] + */ + void onWpaConnectionFullCallBack(int status); + + /** + * @Description : Callback of the Connection Refused event. + * + * @param status - status codes [in] + */ + void onWpaConnectionRejectCallBack(int status); + /** * @Description : Callback of the WPS_OVERLAP event. * * @param status - status codes [in] - * @param pInstance - handles [in] */ void OnWpsPbcOverlapCallBack(int status); @@ -91,7 +109,6 @@ public: * @Description : Callback of the WPS_TIMEOUT event. * * @param status - status codes [in] - * @param pInstance - handles [in] */ void OnWpsTimeOutCallBack(int status); diff --git a/services/wifi_standard/wifi_framework/wifi_manage/wifi_sta/sta_network_check.cpp b/wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_sta/sta_network_check.cpp similarity index 39% rename from services/wifi_standard/wifi_framework/wifi_manage/wifi_sta/sta_network_check.cpp rename to wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_sta/sta_network_check.cpp index d9926f680b9e839ea68bf3f4f5ca426eefea0a74..0790bbd262e0ffd8c3d0f851e09d174bc3f973a7 100644 --- a/services/wifi_standard/wifi_framework/wifi_manage/wifi_sta/sta_network_check.cpp +++ b/wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_sta/sta_network_check.cpp @@ -1,5 +1,5 @@ /* - * Copyright (C) 2021 Huawei Device Co., Ltd. + * Copyright (C) 2021-2022 Huawei Device Co., Ltd. * 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 @@ -12,21 +12,31 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + #include "sta_network_check.h" -#include "if_config.h" #include "wifi_logger.h" DEFINE_WIFILOG_LABEL("StaNetworkCheck"); namespace OHOS { namespace Wifi { +constexpr int NET_ERR_OK = 200; +constexpr int NET_ERR_CREATED = 201; +constexpr int NET_ERR_NO_CONTENT = 204; +constexpr int NET_ERR_BAD_REQUEST = 400; + +constexpr int NET_ERR_REDIRECT_CLASS_MAX = 399; +constexpr int NET_ERR_REQUEST_ERROR_CLASS_MAX = 499; + StaNetworkCheck::StaNetworkCheck(NetStateHandler handle) { + WIFI_LOGI("StaNetworkCheck constructor\n"); pDealNetCheckThread = nullptr; netStateHandler = handle; - lastNetState = NETWORK_STATE_UNKNOW; + lastNetState = NETWORK_STATE_UNKNOWN; isStopNetCheck = true; isExitNetCheckThread = false; + isExited = true; } StaNetworkCheck::~StaNetworkCheck() @@ -36,53 +46,122 @@ StaNetworkCheck::~StaNetworkCheck() WIFI_LOGI("StaNetworkCheck::~StaNetworkCheck complete\n"); } -void StaNetworkCheck::HttpDetection() +bool StaNetworkCheck::HttpDetection() { WIFI_LOGI("Enter httpDetection"); + if (netStateHandler == nullptr) { + WIFI_LOGE("Handler func is null, ignore net detect of this time."); + return false; + } /* Detect portal hotspot and send message to InterfaceSeervice if result is yes. */ HttpRequest httpRequest; std::string httpReturn; std::string httpMsg(DEFAULT_PORTAL_HTTPS_URL); + const std::string genStr("generate_204"); + const std::string contStr("Content-Length:"); if (httpRequest.HttpGet(httpMsg, httpReturn) == 0) { - if (httpReturn.find("204") != std::string::npos) { + size_t retCode = httpReturn.find("HTTP/"); + int codeNum = 0; + if (retCode >= 0) { + constexpr int NET_ERROR_POS = 8; + constexpr int NET_ERROR_LEN = 5; + codeNum = std::atoi(httpReturn.substr(retCode + NET_ERROR_POS, NET_ERROR_LEN).c_str()); + } + + size_t contLenStr = httpReturn.find(contStr); + int contLenNum = 0; + if (contLenStr > 0) { + constexpr int NET_CONTENT_LENGTH = 6; + contLenNum = std::atoi(httpReturn.substr(contLenStr + contStr.length(), NET_CONTENT_LENGTH).c_str()); + } + + constexpr int PORTAL_CONTENT_LENGTH_MIN = 4; + if (codeNum == NET_ERR_NO_CONTENT) { WIFI_LOGE("This network is normal!"); - if ((lastNetState != NETWORK_STATE_WORKING) && (isExitNetCheckThread == false) && + if ((lastNetState.load() != NETWORK_STATE_WORKING) && (isExitNetCheckThread == false) && (isStopNetCheck == false)) { - netStateHandler(StaNetState::NETWORK_STATE_WORKING); + netStateHandler(StaNetState::NETWORK_STATE_WORKING, ""); } lastNetState = NETWORK_STATE_WORKING; - return; - } else { + return true; + } else if (codeNum != NET_ERR_NO_CONTENT && + (codeNum >= NET_ERR_CREATED && codeNum <= NET_ERR_REDIRECT_CLASS_MAX)) { /* Callback result to InterfaceService. */ WIFI_LOGI("This network is portal AP, need certification!"); - return; + std::string urlTmp; + const std::string locStr("Location: "); + size_t startStr = httpReturn.find(locStr); + if (startStr > 0) { + startStr += locStr.length(); + size_t endstr = httpReturn.find(genStr, startStr); + if (endstr > 0) { + endstr += genStr.length(); + urlTmp = httpReturn.substr(startStr, endstr-startStr); + } + netStateHandler(StaNetState::NETWORK_CHECK_PORTAL, urlTmp); + } + return false; + } else if ((codeNum == NET_ERR_OK || + (codeNum >= NET_ERR_BAD_REQUEST && codeNum <= NET_ERR_REQUEST_ERROR_CLASS_MAX)) && + contLenNum > PORTAL_CONTENT_LENGTH_MIN) { + WIFI_LOGI("This network is portal AP, need certification!"); + std::string urlTmp; + const std::string locStr("http"); + size_t startStr = httpReturn.find(locStr); + if (startStr > 0) { + size_t endstr = httpReturn.find(genStr, startStr); + if (endstr > 0) { + endstr += genStr.length(); + urlTmp = httpReturn.substr(startStr, endstr-startStr); + } + netStateHandler(StaNetState::NETWORK_CHECK_PORTAL, urlTmp); + } + return false; + } else { + WIFI_LOGE("http msg error[%s]!", httpReturn.c_str()); + netStateHandler(StaNetState::NETWORK_STATE_NOWORKING, ""); + lastNetState = NETWORK_STATE_NOWORKING; + return true; } } - WIFI_LOGE("This network cant online!"); - if ((lastNetState != NETWORK_STATE_NOWORKING) && (isExitNetCheckThread == false) && (isStopNetCheck == false)) { - netStateHandler(StaNetState::NETWORK_STATE_NOWORKING); + WIFI_LOGE("This network can't online!"); + if ((lastNetState.load() != NETWORK_STATE_NOWORKING) && (isExitNetCheckThread == false) && (isStopNetCheck == false)) { + netStateHandler(StaNetState::NETWORK_STATE_NOWORKING, ""); } lastNetState = NETWORK_STATE_NOWORKING; + return true; } void StaNetworkCheck::RunNetCheckThreadFunc() { WIFI_LOGI("enter RunNetCheckThreadFunc!\n"); + int timeoutMs = 3000; + isExited = false; for (;;) { - std::unique_lock lck(mMutex); - while (isStopNetCheck) { - WIFI_LOGI("waiting for sigal\n"); + while (isStopNetCheck && !isExitNetCheckThread) { + LOGI("waiting for signal.\n"); + std::unique_lock lck(mMutex); mCondition.wait(lck); } - if (isExitNetCheckThread) { WIFI_LOGI("break the loop\n"); + isExited = true; break; } - lck.unlock(); - HttpDetection(); - sleep(1); + if (!HttpDetection()) { + isStopNetCheck = true; + } + if (!isExitNetCheckThread) { + std::unique_lock lck(mMutex); + if (mCondition_timeout.wait_for(lck, std::chrono::milliseconds(timeoutMs)) == std::cv_status::timeout) { + LOGI("mCondition_timeout timeout.\n"); + } else { + LOGI("Wake up, break the loop.\n"); + isExited = true; + break; + } + } } } @@ -99,33 +178,36 @@ ErrCode StaNetworkCheck::InitNetCheckThread() void StaNetworkCheck::StopNetCheckThread() { WIFI_LOGI("enter StopNetCheckThread!\n"); - std::unique_lock lck(mMutex); isStopNetCheck = true; } void StaNetworkCheck::SignalNetCheckThread() { WIFI_LOGI("enter SignalNetCheckThread!\n"); - lastNetState = NETWORK_STATE_UNKNOW; + lastNetState = NETWORK_STATE_UNKNOWN; isStopNetCheck = false; - std::unique_lock lck(mMutex); mCondition.notify_one(); } void StaNetworkCheck::ExitNetCheckThread() { - { - isStopNetCheck = false; + isStopNetCheck = false; + isExitNetCheckThread = true; + while (!isExited) { isExitNetCheckThread = true; - std::unique_lock lck(mMutex); mCondition.notify_one(); + mCondition_timeout.notify_one(); + std::this_thread::sleep_for(std::chrono::milliseconds(1)); // sleep 1 ms } - if (pDealNetCheckThread != nullptr) { - pDealNetCheckThread->join(); + if (pDealNetCheckThread->joinable()) { + LOGI("Exit net check join()"); + pDealNetCheckThread->join(); + } delete pDealNetCheckThread; pDealNetCheckThread = nullptr; + LOGI("Exit net check done"); } } } // namespace Wifi -} // namespace OHOS \ No newline at end of file +} // namespace OHOS diff --git a/services/wifi_standard/wifi_framework/wifi_manage/wifi_sta/sta_network_check.h b/wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_sta/sta_network_check.h similarity index 85% rename from services/wifi_standard/wifi_framework/wifi_manage/wifi_sta/sta_network_check.h rename to wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_sta/sta_network_check.h index 577e15be49036e013c62c66746984d5f3eac3b59..b3552009dc7f04fb9c837a494ffe36b716a595b3 100644 --- a/services/wifi_standard/wifi_framework/wifi_manage/wifi_sta/sta_network_check.h +++ b/wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_sta/sta_network_check.h @@ -1,5 +1,5 @@ /* - * Copyright (C) 2021 Huawei Device Co., Ltd. + * Copyright (C) 2021-2022 Huawei Device Co., Ltd. * 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 @@ -16,17 +16,18 @@ #ifndef OHOS_WIFI_NET_CHECK_H #define OHOS_WIFI_NET_CHECK_H -#include +#include +#include #include #include -#include -#include #include #include -#include "wifi_log.h" -#include "sta_define.h" +#include +#include #include "http_request.h" +#include "sta_define.h" #include "wifi_errcode.h" +#include "wifi_log.h" #define DEFAULT_PORTAL_HTTPS_URL "" @@ -55,33 +56,35 @@ public: */ virtual void StopNetCheckThread(); + /** + * @Description : Exit the NetCheck thread. + * + */ + virtual void ExitNetCheckThread(); + private: std::thread *pDealNetCheckThread; NetStateHandler netStateHandler; - StaNetState lastNetState; + std::atomic lastNetState; /** * @Description : Detect Internet ability * */ - void HttpDetection(); + bool HttpDetection(); /** * @Description : NetCheck thread function * */ void RunNetCheckThreadFunc(); - /** - * @Description : Exit the NetCheck thread. - * - */ - - void ExitNetCheckThread(); private: std::mutex mMutex; std::condition_variable mCondition; - bool isStopNetCheck; - bool isExitNetCheckThread; + std::condition_variable mCondition_timeout; + std::atomic isStopNetCheck; + std::atomic isExitNetCheckThread; + std::atomic isExited; }; } // namespace Wifi } // namespace OHOS diff --git a/services/wifi_standard/wifi_framework/wifi_manage/wifi_sta/sta_saved_device_appraisal.cpp b/wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_sta/sta_saved_device_appraisal.cpp old mode 100755 new mode 100644 similarity index 79% rename from services/wifi_standard/wifi_framework/wifi_manage/wifi_sta/sta_saved_device_appraisal.cpp rename to wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_sta/sta_saved_device_appraisal.cpp index 3b2db99a4c9aaac75fad6946bfc1ca1fa1a37ea2..bafe1c616d78975b2c0b3fe5e52b6b91c8716cc3 --- a/services/wifi_standard/wifi_framework/wifi_manage/wifi_sta/sta_saved_device_appraisal.cpp +++ b/wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_sta/sta_saved_device_appraisal.cpp @@ -15,6 +15,7 @@ #include "sta_saved_device_appraisal.h" #include "wifi_logger.h" #include "wifi_settings.h" +#include "wifi_common_util.h" DEFINE_WIFILOG_LABEL("StaSavedDeviceAppraisal"); @@ -31,6 +32,7 @@ StaSavedDeviceAppraisal::StaSavedDeviceAppraisal(bool supportFmRoamingFlag) frequency5GHzScore(WifiSettings::GetInstance().GetScoretacticsFrequency5GHzScore()), userSelectedDeviceScore(WifiSettings::GetInstance().GetScoretacticsLastSelectionScore()), safetyDeviceScore(WifiSettings::GetInstance().GetScoretacticsSecurityScore()), + normalDeviceScore(WifiSettings::GetInstance().GetScoretacticsNormalScore()), firmwareRoamFlag(supportFmRoamingFlag) {} StaSavedDeviceAppraisal::~StaSavedDeviceAppraisal() @@ -48,33 +50,35 @@ ErrCode StaSavedDeviceAppraisal::DeviceAppraisals( scanInfoElected.rssi = VALUE_LIMIT_MIN_RSSI; for (auto scanInfo : scanInfos) { - if (scanInfo.bssid.size() == 0) { - continue; - } - WifiDeviceConfig device; - if (WifiSettings::GetInstance().GetDeviceConfig(scanInfo.bssid, DEVICE_CONFIG_INDEX_BSSID, device) == -1) { - WIFI_LOGI("Skip unsaved Network %s.", scanInfo.ssid.c_str()); /* Skipping Unsaved Networks */ + if (WifiSettings::GetInstance().GetDeviceConfig(scanInfo.ssid, DEVICE_CONFIG_INDEX_SSID, device) != 0) { + WIFI_LOGI("Skip unsaved ssid Network %{public}s.", SsidAnonymize(scanInfo.ssid).c_str()); continue; } - if (!WhetherSkipDevice(device)) { + if (WhetherSkipDevice(device)) { continue; } int score = 0; AppraiseDeviceQuality(score, scanInfo, device, info); - WIFI_LOGI( - "The device %s score is %{public}d.rssi is %{public}d.\n", scanInfo.ssid.c_str(), score, scanInfo.rssi); + WIFI_LOGI("The device networkId:%{public}d ssid:%{public}s score:%{public}d rssi:%{public}d.", + device.networkId, SsidAnonymize(scanInfo.ssid).c_str(), score, scanInfo.rssi); if (score > highestScore || (score == highestScore && scanInfo.rssi > scanInfoElected.rssi)) { highestScore = score; scanInfoElected.rssi = scanInfo.rssi; electedDevice = device; sign = 1; + WIFI_LOGI("set highestScore: %{public}d, ssid: %{public}s", highestScore, SsidAnonymize(device.ssid).c_str()); + } else { + WIFI_LOGI("The config %{public}s is ignored!\n", MacAnonymize(scanInfo.ssid).c_str()); } } if (sign == 1) { + WIFI_LOGI("DeviceAppraisals, Selected device, networkId:%{public}d, ssid:%{public}s, bssid:%{public}s.", + electedDevice.networkId, SsidAnonymize(electedDevice.ssid).c_str(), + MacAnonymize(electedDevice.bssid).c_str()); if (info.connState == ConnState::CONNECTED && electedDevice.networkId == info.networkId) { WifiDeviceConfig networkInfo; electedDevice = networkInfo; @@ -94,16 +98,20 @@ bool StaSavedDeviceAppraisal::WhetherSkipDevice(WifiDeviceConfig &device) { /* Skip this type of device and evaluate it by other appraisals */ if (device.isPasspoint || device.isEphemeral) { - WIFI_LOGI("Skip isPasspoint or isEphemeral Network %s.", device.ssid.c_str()); - return false; + WIFI_LOGI("Skip isPasspoint or isEphemeral Network %{public}s.", SsidAnonymize(device.ssid).c_str()); + return true; } - if ((device.status != static_cast(WifiDeviceConfigStatus::ENABLED)) && - (device.status != static_cast(WifiDeviceConfigStatus::CURRENT))) { - WIFI_LOGI("Skip disable Network %s.NetworkId is %{public}d", device.ssid.c_str(), device.networkId); - return false; + if (device.status == static_cast(WifiDeviceConfigStatus::DISABLED)) { + WIFI_LOGI("Skip disabled Network %{public}s.", SsidAnonymize(device.ssid).c_str()); + return true; + } + std::string bssid = WifiSettings::GetInstance().GetConnectTimeoutBssid(); + if (!bssid.empty() && bssid == device.bssid) { + WIFI_LOGI("Skip the connect timeout Network %{public}s.", SsidAnonymize(device.ssid).c_str()); + return true; } - return true; + return false; } void StaSavedDeviceAppraisal::AppraiseDeviceQuality( @@ -123,6 +131,12 @@ void StaSavedDeviceAppraisal::AppraiseDeviceQuality( WIFI_LOGI("5G score is %{public}d.\n", frequency5GHzScore); } + /* normal device config: bonus point */ + if (device.uid == WIFI_INVALID_UID) { + score += normalDeviceScore; + WIFI_LOGI("normal score is %{public}d.\n", normalDeviceScore); + } + /* Bonus points for last user selection */ int userLastSelectedNetworkId = WifiSettings::GetInstance().GetUserLastSelectedNetworkId(); if (userLastSelectedNetworkId != INVALID_NETWORK_ID && userLastSelectedNetworkId == device.networkId) { diff --git a/services/wifi_standard/wifi_framework/wifi_manage/wifi_sta/sta_saved_device_appraisal.h b/wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_sta/sta_saved_device_appraisal.h similarity index 99% rename from services/wifi_standard/wifi_framework/wifi_manage/wifi_sta/sta_saved_device_appraisal.h rename to wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_sta/sta_saved_device_appraisal.h index 6e0cb1a62684909beee4b568a9c97beb09b87476..47150ab9a50cdfa05516c6446aa98fb58f7ddc4e 100644 --- a/services/wifi_standard/wifi_framework/wifi_manage/wifi_sta/sta_saved_device_appraisal.h +++ b/wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_sta/sta_saved_device_appraisal.h @@ -48,6 +48,7 @@ private: int frequency5GHzScore; int userSelectedDeviceScore; int safetyDeviceScore; + int normalDeviceScore; bool firmwareRoamFlag; /** diff --git a/services/wifi_standard/wifi_framework/wifi_manage/wifi_sta/sta_service.cpp b/wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_sta/sta_service.cpp old mode 100755 new mode 100644 similarity index 55% rename from services/wifi_standard/wifi_framework/wifi_manage/wifi_sta/sta_service.cpp rename to wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_sta/sta_service.cpp index ed43bac48789b60cc3675fd14221b1942880bebb..51ae164204629caf58fc365fc01d6f6d3aa3fd09 --- a/services/wifi_standard/wifi_framework/wifi_manage/wifi_sta/sta_service.cpp +++ b/wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_sta/sta_service.cpp @@ -1,5 +1,5 @@ /* - * Copyright (C) 2021 Huawei Device Co., Ltd. + * Copyright (C) 2021-2022 Huawei Device Co., Ltd. * 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 @@ -12,16 +12,20 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + #include "sta_service.h" -#include "wifi_logger.h" #include "sta_define.h" #include "sta_service_callback.h" +#ifndef OHOS_ARCH_LITE +#include "wifi_internal_event_dispatcher.h" +#endif +#include "wifi_logger.h" +#include "wifi_settings.h" #include "wifi_sta_hal_interface.h" #include "wifi_supplicant_hal_interface.h" -#include "wifi_settings.h" +#include "wifi_common_util.h" DEFINE_WIFILOG_LABEL("StaService"); - namespace OHOS { namespace Wifi { StaService::StaService() @@ -87,13 +91,13 @@ ErrCode StaService::InitStaService(const StaServiceCallback &callbacks) return WIFI_OPT_FAILED; } WIFI_LOGI("Init staservice successfully.\n"); - return WIFI_OPT_SUCCESS; } ErrCode StaService::EnableWifi() const { WIFI_LOGI("Enter StaService::EnableWifi.\n"); + CHECK_NULL_AND_RETURN(pStaStateMachine, WIFI_OPT_FAILED); pStaStateMachine->SendMessage(WIFI_SVR_CMD_STA_ENABLE_WIFI, STA_CONNECT_MODE); return WIFI_OPT_SUCCESS; } @@ -101,28 +105,107 @@ ErrCode StaService::EnableWifi() const ErrCode StaService::DisableWifi() const { WIFI_LOGI("Enter StaService::DisableWifi.\n"); + CHECK_NULL_AND_RETURN(pStaStateMachine, WIFI_OPT_FAILED); pStaStateMachine->SendMessage(WIFI_SVR_CMD_STA_DISABLE_WIFI); return WIFI_OPT_SUCCESS; } +ErrCode StaService::AddCandidateConfig(const int uid, const WifiDeviceConfig &config, int& netWorkId) const +{ + LOGI("Enter StaService::AddCandidateConfig.\n"); + + netWorkId = INVALID_NETWORK_ID; + constexpr int UID_UNTRUSTED_CONFIG_LEN = 16; + std::vector tempConfigs; + WifiSettings::GetInstance().GetAllCandidateConfig(uid, tempConfigs); + if (tempConfigs.size() >= UID_UNTRUSTED_CONFIG_LEN) { + LOGE("AddCandidateConfig failed, exceed max num: %{public}d\n", UID_UNTRUSTED_CONFIG_LEN); + return WIFI_OPT_FAILED; + } + + if (config.keyMgmt == KEY_MGMT_NONE || config.keyMgmt == KEY_MGMT_WEP) { + LOGE("StaService::AddCandidateConfig unsupport open or wep key!"); + return WIFI_OPT_NOT_SUPPORTED; + } + WifiDeviceConfig tempDeviceConfig = config; + tempDeviceConfig.uid = uid; + netWorkId = AddDeviceConfig(tempDeviceConfig); + return (netWorkId == INVALID_NETWORK_ID) ? WIFI_OPT_FAILED : WIFI_OPT_SUCCESS; +} + +ErrCode StaService::RemoveCandidateConfig(const int uid, const int networkId) const +{ + LOGD("Enter StaService::RemoveCandidateConfig.\n"); + WifiDeviceConfig config; + if (WifiSettings::GetInstance().GetCandidateConfig(uid, networkId, config) == INVALID_NETWORK_ID) { + LOGE("RemoveCandidateConfig-GetCandidateConfig no foud failed!"); + return WIFI_OPT_FAILED; + } + + /* Remove network configuration. */ + return RemoveDevice(config.networkId); +} + +ErrCode StaService::RemoveAllCandidateConfig(const int uid) const +{ + LOGD("Enter StaService::RemoveAllCandidateConfig.\n"); + std::vector tempConfigs; + WifiSettings::GetInstance().GetAllCandidateConfig(uid, tempConfigs); + for (const auto &config : tempConfigs) { + if (RemoveDevice(config.networkId) != WIFI_OPT_SUCCESS) { + LOGE("RemoveAllCandidateConfig-RemoveDevice() failed!"); + } + } + return WIFI_OPT_SUCCESS; +} + +ErrCode StaService::ConnectToCandidateConfig(const int uid, const int networkId) const +{ + LOGI("Enter StaService::ConnectToCandidateConfig.\n"); + WifiDeviceConfig config; + if (WifiSettings::GetInstance().GetCandidateConfig(uid, networkId, config) == INVALID_NETWORK_ID) { + LOGE("StaService::ConnectToCandidateConfig:GetCandidateConfig is null!"); + return WIFI_OPT_FAILED; + } + + if (config.keyMgmt == KEY_MGMT_NONE) { + LOGE("StaService::ConnectToCandidateConfig unsupport open or wep key!"); + return WIFI_OPT_NOT_SUPPORTED; + } + + pStaAutoConnectService->EnableOrDisableBssid(config.bssid, true, 0); + pStaStateMachine->SendMessage(WIFI_SVR_CMD_STA_CONNECT_SAVED_NETWORK, networkId, NETWORK_SELECTED_BY_THE_USER); + return WIFI_OPT_SUCCESS; +} + int StaService::AddDeviceConfig(const WifiDeviceConfig &config) const { LOGI("Enter StaService::AddDeviceConfig.\n"); + CHECK_NULL_AND_RETURN(pStaStateMachine, WIFI_OPT_FAILED); int netWorkId = INVALID_NETWORK_ID; + bool isUpdate = false; + std::string bssid; WifiDeviceConfig tempDeviceConfig; if (WifiSettings::GetInstance().GetDeviceConfig(config.ssid, config.keyMgmt, tempDeviceConfig) == 0) { - LOGD("A network with the same name already exists in the configuration center!\n"); netWorkId = tempDeviceConfig.networkId; - pStaAutoConnectService->EnableOrDisableBssid(config.bssid, true, 0); + LOGI("The same network name already exists in settings! netWorkId:%{public}d, ssid:%{public}s.", + netWorkId, SsidAnonymize(config.ssid).c_str()); + CHECK_NULL_AND_RETURN(pStaAutoConnectService, WIFI_OPT_FAILED); + bssid = config.bssid.empty() ? tempDeviceConfig.bssid : config.bssid; + pStaAutoConnectService->EnableOrDisableBssid(bssid, true, 0); + isUpdate = true; } else { if (WifiStaHalInterface::GetInstance().GetNextNetworkId(netWorkId) != WIFI_IDL_OPT_OK) { LOGE("StaService::AddDeviceConfig GetNextNetworkId failed!"); - return netWorkId; + return INVALID_NETWORK_ID; } - LOGD("StaService::AddDeviceConfig Add a new network and GetNextNetworkId() succeed!"); + LOGI("StaService::AddDeviceConfig alloc new id[%{public}d] succeed!", netWorkId); } tempDeviceConfig = config; tempDeviceConfig.networkId = netWorkId; + if (!bssid.empty()) { + tempDeviceConfig.bssid = bssid; + } /* Setting the network to wpa */ if(pStaStateMachine->ConvertDeviceCfg(tempDeviceConfig) != WIFI_OPT_SUCCESS) { @@ -133,6 +216,8 @@ int StaService::AddDeviceConfig(const WifiDeviceConfig &config) const /* Add the new network to WifiSettings. */ WifiSettings::GetInstance().AddDeviceConfig(tempDeviceConfig); WifiSettings::GetInstance().SyncDeviceConfig(); + ConfigChange changeType = isUpdate ? ConfigChange::CONFIG_UPDATE : ConfigChange::CONFIG_ADD; + NotifyDeviceConfigChange(changeType); return netWorkId; } @@ -141,28 +226,78 @@ int StaService::UpdateDeviceConfig(const WifiDeviceConfig &config) const return AddDeviceConfig(config); } +ErrCode StaService::RemoveDevice(int networkId) const +{ + LOGI("Enter StaService::RemoveDevice, networkId = %{public}d.\n", networkId); + /* Remove network configuration. */ + if (WifiStaHalInterface::GetInstance().RemoveDevice(networkId) != WIFI_IDL_OPT_OK) { + LOGE("RemoveDeviceConfig() failed!"); + return WIFI_OPT_FAILED; + } + if (WifiStaHalInterface::GetInstance().SaveDeviceConfig() != WIFI_IDL_OPT_OK) { + LOGW("RemoveDevice-SaveDeviceConfig() failed!"); + } else { + LOGD("RemoveDevice-SaveDeviceConfig() succeed!"); + } + WifiDeviceConfig config; + if (WifiSettings::GetInstance().GetDeviceConfig(networkId, config) == 0) { + CHECK_NULL_AND_RETURN(pStaAutoConnectService, WIFI_OPT_FAILED); + pStaAutoConnectService->EnableOrDisableBssid(config.bssid, true, 0); + } + /* Remove network configuration directly without notification to InterfaceService. */ + WifiSettings::GetInstance().RemoveDevice(networkId); + WifiSettings::GetInstance().SyncDeviceConfig(); + NotifyDeviceConfigChange(ConfigChange::CONFIG_REMOVE); + return WIFI_OPT_SUCCESS; +} + +ErrCode StaService::RemoveAllDevice() const +{ + LOGI("Enter StaService::RemoveAllDevice.\n"); + if (WifiStaHalInterface::GetInstance().ClearDeviceConfig() == WIFI_IDL_OPT_OK) { + LOGD("Remove all device config successfully!"); + if (WifiStaHalInterface::GetInstance().SaveDeviceConfig() != WIFI_IDL_OPT_OK) { + LOGE("WifiStaHalInterface:RemoveAllDevice:SaveDeviceConfig failed!"); + } + } else { + LOGE("WifiStaHalInterface:RemoveAllDevice failed!"); + return WIFI_OPT_FAILED; + } + + WifiSettings::GetInstance().ClearDeviceConfig(); + if (WifiSettings::GetInstance().SyncDeviceConfig() != 0) { + LOGE("RemoveAllDevice-SyncDeviceConfig() failed!"); + return WIFI_OPT_FAILED; + } + NotifyDeviceConfigChange(ConfigChange::CONFIG_REMOVE); + return WIFI_OPT_SUCCESS; +} + ErrCode StaService::ConnectToDevice(const WifiDeviceConfig &config) const { - LOGI("Enter StaService::ConnectToDevice.\n"); + LOGI("Enter StaService::ConnectToDevice, ssid = %{public}s.\n", SsidAnonymize(config.ssid).c_str()); + CHECK_NULL_AND_RETURN(pStaStateMachine, WIFI_OPT_FAILED); int netWorkId = AddDeviceConfig(config); if(netWorkId == INVALID_NETWORK_ID) { - LOGD("StaService::ConnectTo AddDeviceConfig failed!"); + LOGD("StaService::ConnectToDevice, AddDeviceConfig failed!"); return WIFI_OPT_FAILED; } - LOGD("StaService::ConnectTo AddDeviceConfig succeed!"); + LOGI("StaService::ConnectToDevice, netWorkId: %{public}d", netWorkId); pStaStateMachine->SendMessage(WIFI_SVR_CMD_STA_CONNECT_NETWORK, netWorkId, NETWORK_SELECTED_BY_THE_USER); return WIFI_OPT_SUCCESS; } ErrCode StaService::ConnectToNetwork(int networkId) const { - LOGI("Enter StaService::ConnectToNetwork, networkId is %d.\n", networkId); + LOGI("Enter StaService::ConnectToNetwork, networkId is %{public}d.", networkId); WifiDeviceConfig config; if (WifiSettings::GetInstance().GetDeviceConfig(networkId, config) != 0) { LOGE("WifiDeviceConfig is null!"); return WIFI_OPT_FAILED; } - + CHECK_NULL_AND_RETURN(pStaAutoConnectService, WIFI_OPT_FAILED); + CHECK_NULL_AND_RETURN(pStaStateMachine, WIFI_OPT_FAILED); + LOGI("StaService::ConnectToNetwork, ssid = %{public}s.", SsidAnonymize(config.ssid).c_str()); pStaAutoConnectService->EnableOrDisableBssid(config.bssid, true, 0); pStaStateMachine->SendMessage(WIFI_SVR_CMD_STA_CONNECT_SAVED_NETWORK, networkId, NETWORK_SELECTED_BY_THE_USER); return WIFI_OPT_SUCCESS; @@ -171,43 +306,14 @@ ErrCode StaService::ConnectToNetwork(int networkId) const ErrCode StaService::ReAssociate() const { WIFI_LOGI("Enter StaService::ReAssociate.\n"); + CHECK_NULL_AND_RETURN(pStaStateMachine, WIFI_OPT_FAILED); pStaStateMachine->SendMessage(WIFI_SVR_CMD_STA_REASSOCIATE_NETWORK); return WIFI_OPT_SUCCESS; } -ErrCode StaService::RemoveDevice(int networkId) const -{ - LOGD("Enter StaService::RemoveDeviceConfigProcess.\n"); - /* Remove network configuration. */ - if (WifiStaHalInterface::GetInstance().RemoveDevice(networkId) != WIFI_IDL_OPT_OK) { - LOGE("RemoveDeviceConfig() failed!"); - return WIFI_OPT_FAILED; - } - if (WifiStaHalInterface::GetInstance().SaveDeviceConfig() != WIFI_IDL_OPT_OK) { - LOGW("RemoveDeviceConfig-SaveDeviceConfig() failed!"); - } else { - LOGD("RemoveDeviceConfig-SaveDeviceConfig() succeed!"); - } - WifiDeviceConfig config; - if (WifiSettings::GetInstance().GetDeviceConfig(networkId, config) == 0) { - pStaAutoConnectService->EnableOrDisableBssid(config.bssid, true, 0); - } - /* Remove network configuration directly without notification to InterfaceService. */ - WifiSettings::GetInstance().RemoveDevice(networkId); - WifiSettings::GetInstance().SyncDeviceConfig(); - return WIFI_OPT_SUCCESS; -} - -ErrCode StaService::RemoveAllDevice() const -{ - WIFI_LOGI("Enter StaService::RemoveAllDevice.\n"); - pStaStateMachine->SendMessage(WIFI_SVR_CMD_STA_REMOVE_All_DEVICE_CONFIG); - return WIFI_OPT_SUCCESS; -} - ErrCode StaService::EnableDeviceConfig(int networkId, bool attemptEnable) const { - WIFI_LOGD("Enter StaService::EnableDeviceConfig! networkid is %{public}d", networkId); + WIFI_LOGI("Enter StaService::EnableDeviceConfig, networkid is %{public}d", networkId); /* Update wifi status. */ if (WifiSettings::GetInstance().SetDeviceState(networkId, (int)WifiDeviceConfigStatus::ENABLED, attemptEnable) < @@ -215,23 +321,27 @@ ErrCode StaService::EnableDeviceConfig(int networkId, bool attemptEnable) const WIFI_LOGE("Enable device config failed!"); return WIFI_OPT_FAILED; } + WifiSettings::GetInstance().SyncDeviceConfig(); return WIFI_OPT_SUCCESS; } ErrCode StaService::DisableDeviceConfig(int networkId) const { - WIFI_LOGD("Enter StaService::DisableDeviceConfig.networkid is %{public}d", networkId); + WIFI_LOGI("Enter StaService::DisableDeviceConfig, networkid is %{public}d", networkId); if (WifiSettings::GetInstance().SetDeviceState(networkId, (int)WifiDeviceConfigStatus::DISABLED) < 0) { WIFI_LOGE("Disable device config failed!"); return WIFI_OPT_FAILED; } + WifiSettings::GetInstance().SyncDeviceConfig(); return WIFI_OPT_SUCCESS; } ErrCode StaService::Disconnect() const { WIFI_LOGI("Enter StaService::Disconnect.\n"); + CHECK_NULL_AND_RETURN(pStaAutoConnectService, WIFI_OPT_FAILED); + CHECK_NULL_AND_RETURN(pStaStateMachine, WIFI_OPT_FAILED); WifiLinkedInfo linkedInfo; WifiSettings::GetInstance().GetLinkedInfo(linkedInfo); if (pStaAutoConnectService->EnableOrDisableBssid(linkedInfo.bssid, false, AP_CANNOT_HANDLE_NEW_STA)) { @@ -244,6 +354,7 @@ ErrCode StaService::Disconnect() const ErrCode StaService::StartWps(const WpsConfig &config) const { WIFI_LOGI("Enter StaService::StartWps.\n"); + CHECK_NULL_AND_RETURN(pStaStateMachine, WIFI_OPT_FAILED); InternalMessage *msg = pStaStateMachine->CreateMessage(); msg->SetMessageName(WIFI_SVR_CMD_STA_STARTWPS); msg->SetParam1(static_cast(config.setup)); @@ -256,13 +367,14 @@ ErrCode StaService::StartWps(const WpsConfig &config) const ErrCode StaService::CancelWps() const { WIFI_LOGI("Enter StaService::CanceltWps.\n"); + CHECK_NULL_AND_RETURN(pStaStateMachine, WIFI_OPT_FAILED); pStaStateMachine->SendMessage(WIFI_SVR_CMD_STA_CANCELWPS); return WIFI_OPT_SUCCESS; } ErrCode StaService::SetCountryCode(const std::string &countryCode) const { - LOGI("Enter StaService::SetCountryCode, countryCode=[%s]!", countryCode.c_str()); + LOGI("Enter StaService::SetCountryCode, countryCode=[%{public}s]!", countryCode.c_str()); if (WifiSupplicantHalInterface::GetInstance().WpaSetCountryCode(countryCode) != WIFI_IDL_OPT_OK) { LOGE("WpaSetCountryCode() failed!"); return WIFI_OPT_FAILED; @@ -275,8 +387,8 @@ ErrCode StaService::SetCountryCode(const std::string &countryCode) const ErrCode StaService::AutoConnectService(const std::vector &scanInfos) { WIFI_LOGI("Enter StaService::AutoConnectService.\n"); + CHECK_NULL_AND_RETURN(pStaAutoConnectService, WIFI_OPT_FAILED); pStaAutoConnectService->OnScanInfosReadyHandler(scanInfos); - pStaStateMachine->SyncLinkInfo(scanInfos); return WIFI_OPT_SUCCESS; } @@ -290,5 +402,33 @@ void StaService::RegisterStaServiceCallback(const StaServiceCallback &callbacks) pStaStateMachine->RegisterStaServiceCallback(callbacks); } +ErrCode StaService::ReConnect() const +{ + WIFI_LOGI("Enter StaService::ReConnect.\n"); + CHECK_NULL_AND_RETURN(pStaStateMachine, WIFI_OPT_FAILED); + pStaStateMachine->SendMessage(WIFI_SVR_CMD_STA_RECONNECT_NETWORK); + return WIFI_OPT_SUCCESS; +} + +ErrCode StaService::SetSuspendMode(bool mode) const +{ + LOGI("Enter StaService::SetSuspendMode, mode=[%{public}d]!", mode); + if (WifiSupplicantHalInterface::GetInstance().WpaSetSuspendMode(mode) != WIFI_IDL_OPT_OK) { + LOGE("WpaSetSuspendMode() failed!"); + return WIFI_OPT_FAILED; + } + return WIFI_OPT_SUCCESS; +} + +void StaService::NotifyDeviceConfigChange(ConfigChange value) const +{ + WIFI_LOGI("Notify device config change: %{public}d\n", static_cast(value)); +#ifndef OHOS_ARCH_LITE + WifiEventCallbackMsg cbMsg; + cbMsg.msgCode = WIFI_CBK_MSG_DEVICE_CONFIG_CHANGE; + cbMsg.msgData = static_cast(value); + WifiInternalEventDispatcher::GetInstance().AddBroadCastMsg(cbMsg); +#endif +} } // namespace Wifi } // namespace OHOS diff --git a/services/wifi_standard/wifi_framework/wifi_manage/wifi_sta/sta_service.h b/wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_sta/sta_service.h old mode 100755 new mode 100644 similarity index 78% rename from services/wifi_standard/wifi_framework/wifi_manage/wifi_sta/sta_service.h rename to wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_sta/sta_service.h index c7bc5d209e825e6015b54fde3b6dd8770956aa4f..c797dca10fb257946f608a1d9dd69c732ebc275b --- a/services/wifi_standard/wifi_framework/wifi_manage/wifi_sta/sta_service.h +++ b/wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_sta/sta_service.h @@ -87,7 +87,38 @@ public: * @Return success: WIFI_OPT_SUCCESS fail: WIFI_OPT_FAILED */ virtual ErrCode ReAssociate() const; - + /** + * @Description Add a specified candidate hotspot configuration. + * + * @param uid - call app uid + * @param config - WifiDeviceConfig object + * @param netWorkId - the network id of the hotspot configuration.(out) + * @Return success: WIFI_OPT_SUCCESS fail: WIFI_OPT_FAILED + */ + virtual ErrCode AddCandidateConfig(const int uid, const WifiDeviceConfig &config, int& netWorkId) const; + /** + * @Description Connect to a candidate specified network. + * + * @param uid - call app uid + * @param networkId - the candidate device network id + * @Return ErrCode - operation result + */ + virtual ErrCode ConnectToCandidateConfig(const int uid, const int networkId) const; + /** + * @Description Remove the wifi candidate device config equals to input network id + * + * @param uid - call app uid + * @param networkId - the candidate device network id + * @return ErrCode - operation result + */ + virtual ErrCode RemoveCandidateConfig(const int uid, const int networkId) const; + /** + * @Description Remove all the wifi candidate device config equals to input uid + * + * @param uid - call app uid + * @return ErrCode - operation result + */ + virtual ErrCode RemoveAllCandidateConfig(const int uid) const; /** * @Description Update a network to config * @@ -170,6 +201,24 @@ public: */ virtual void RegisterStaServiceCallback(const StaServiceCallback &callbacks) const; + /** + * @Description Reconnect network + * + * @Return success: WIFI_OPT_SUCCESS fail: WIFI_OPT_FAILED + */ + virtual ErrCode ReConnect() const; + + /** + * @Description Set suspend mode to wpa + * + * @param mode - true for suspend mode, false for resume mode + * + * @Return success: WIFI_OPT_SUCCESS, fail: WIFI_OPT_FAILED + */ + virtual ErrCode SetSuspendMode(bool mode) const; + +private: + void NotifyDeviceConfigChange(ConfigChange value) const; private: StaStateMachine *pStaStateMachine; diff --git a/services/wifi_standard/wifi_framework/wifi_manage/wifi_sta/sta_service_callback.h b/wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_sta/sta_service_callback.h similarity index 95% rename from services/wifi_standard/wifi_framework/wifi_manage/wifi_sta/sta_service_callback.h rename to wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_sta/sta_service_callback.h index 950e8dc586509eafe872010174d99ec9f3b84dd2..257e9d61458a51b40c0309a3a88b985561b88b33 100644 --- a/services/wifi_standard/wifi_framework/wifi_manage/wifi_sta/sta_service_callback.h +++ b/wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_sta/sta_service_callback.h @@ -1,5 +1,5 @@ /* - * Copyright (C) 2021 Huawei Device Co., Ltd. + * Copyright (C) 2021-2022 Huawei Device Co., Ltd. * 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 diff --git a/services/wifi_standard/wifi_framework/wifi_manage/wifi_sta/sta_state_machine.cpp b/wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_sta/sta_state_machine.cpp old mode 100755 new mode 100644 similarity index 56% rename from services/wifi_standard/wifi_framework/wifi_manage/wifi_sta/sta_state_machine.cpp rename to wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_sta/sta_state_machine.cpp index b984f65dbabd65ab4b8e024049c7da6b34b04619..e1bb56c54e04d2fefe18570e5cd3336245b34312 --- a/services/wifi_standard/wifi_framework/wifi_manage/wifi_sta/sta_state_machine.cpp +++ b/wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_sta/sta_state_machine.cpp @@ -1,5 +1,5 @@ /* - * Copyright (C) 2021 Huawei Device Co., Ltd. + * Copyright (C) 2021-2022 Huawei Device Co., Ltd. * 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 @@ -12,14 +12,20 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + #include "sta_state_machine.h" #include +#include +#include "if_config.h" +#include "ip_tools.h" #include "log_helper.h" +#include "mac_address.h" #include "sta_monitor.h" +#include "wifi_chip_capability.h" +#include "wifi_common_util.h" #include "wifi_logger.h" -#include "wifi_sta_hal_interface.h" #include "wifi_settings.h" -#include "if_config.h" +#include "wifi_sta_hal_interface.h" #include "wifi_supplicant_hal_interface.h" #ifndef OHOS_WIFI_STA_TEST @@ -28,31 +34,18 @@ #include "mock_dhcp_service.h" #endif -DEFINE_WIFILOG_LABEL("StaStateMachine"); -#define PBC_ANY_BSSID "any" - -const int SLEEPTIME = 3; -const int BAND_ONE = 1; -const int BAND_TWO = 2; - -#define MAC_LENGTH 12 -#define MAC_STEP 2 -#define RAND_SEED_16 16 -#define RAND_SEED_8 8 -#define BUFFER_SIZE 128 - - namespace OHOS { namespace Wifi { +DEFINE_WIFILOG_LABEL("StaStateMachine"); +#define PBC_ANY_BSSID "any" StaStateMachine::StaStateMachine() : StateMachine("StaStateMachine"), - statusId(0), lastNetworkId(INVALID_NETWORK_ID), operationalMode(STA_CONNECT_MODE), targetNetworkId(INVALID_NETWORK_ID), pinCode(0), wpsState(SetupMethod::INVALID), - lastConnectToNetworkTimer(-1), + lastSignalLevel(-1), targetRoamBssid(WPA_BSSID_ANY), currentTpType(IPTYPE_IPV4), isWpsConnect(IsWpsConnected::WPS_INVALID), @@ -61,7 +54,6 @@ StaStateMachine::StaStateMachine() isRoam(false), pDhcpService(nullptr), pDhcpResultNotify(nullptr), - pNetSpeed(nullptr), pNetcheck(nullptr), pRootState(nullptr), pInitState(nullptr), @@ -95,7 +87,6 @@ StaStateMachine::~StaStateMachine() ParsePointer(pGetIpState); ParsePointer(pLinkedState); ParsePointer(pApRoamingState); - ParsePointer(pNetSpeed); if (pDhcpService != nullptr) { if (currentTpType == IPTYPE_IPV4) { pDhcpService->StopDhcpClient(IF_NAME, false); @@ -111,7 +102,7 @@ StaStateMachine::~StaStateMachine() /* ---------------------------Initialization functions------------------------------ */ ErrCode StaStateMachine::InitStaStateMachine() { - WIFI_LOGD("Enter StaStateMachine::InitStaStateMachine.\n"); + WIFI_LOGI("Enter StaStateMachine::InitStaStateMachine.\n"); if (!InitialStateMachine()) { WIFI_LOGE("Initial StateMachine failed.\n"); return WIFI_OPT_FAILED; @@ -132,12 +123,16 @@ ErrCode StaStateMachine::InitStaStateMachine() } pNetcheck = new (std::nothrow) - StaNetworkCheck(std::bind(&StaStateMachine::HandleNetCheckResult, this, std::placeholders::_1)); + StaNetworkCheck(std::bind(&StaStateMachine::HandleNetCheckResult, this, + std::placeholders::_1, std::placeholders::_2)); if (pNetcheck == nullptr) { WIFI_LOGE("pNetcheck is null\n"); return WIFI_OPT_FAILED; } pNetcheck->InitNetCheckThread(); +#ifndef OHOS_ARCH_LITE + NetSupplierInfo = std::make_unique().release(); +#endif return WIFI_OPT_SUCCESS; } @@ -145,35 +140,33 @@ ErrCode StaStateMachine::InitStaStates() { WIFI_LOGE("Enter InitStaStates\n"); int tmpErrNumber; - pRootState = new RootState(); + pRootState = new (std::nothrow)RootState(); tmpErrNumber = JudgmentEmpty(pRootState); - pInitState = new InitState(this); + pInitState = new (std::nothrow)InitState(this); tmpErrNumber += JudgmentEmpty(pInitState); - pWpaStartingState = new WpaStartingState(this); + pWpaStartingState = new (std::nothrow)WpaStartingState(this); tmpErrNumber += JudgmentEmpty(pWpaStartingState); - pWpaStartedState = new WpaStartedState(this); + pWpaStartedState = new (std::nothrow)WpaStartedState(this); tmpErrNumber += JudgmentEmpty(pWpaStartedState); - pWpaStoppingState = new WpaStoppingState(this); + pWpaStoppingState = new (std::nothrow)WpaStoppingState(this); tmpErrNumber += JudgmentEmpty(pWpaStoppingState); - pLinkState = new LinkState(this); + pLinkState = new (std::nothrow)LinkState(this); tmpErrNumber += JudgmentEmpty(pLinkState); - pSeparatingState = new SeparatingState(); + pSeparatingState = new (std::nothrow)SeparatingState(); tmpErrNumber += JudgmentEmpty(pSeparatingState); - pSeparatedState = new SeparatedState(this); + pSeparatedState = new (std::nothrow)SeparatedState(this); tmpErrNumber += JudgmentEmpty(pSeparatedState); - pApLinkedState = new ApLinkedState(this); + pApLinkedState = new (std::nothrow)ApLinkedState(this); tmpErrNumber += JudgmentEmpty(pApLinkedState); - pWpsState = new StaWpsState(this); + pWpsState = new (std::nothrow)StaWpsState(this); tmpErrNumber += JudgmentEmpty(pWpsState); - pGetIpState = new GetIpState(this); + pGetIpState = new (std::nothrow)GetIpState(this); tmpErrNumber += JudgmentEmpty(pGetIpState); - pLinkedState = new LinkedState(); + pLinkedState = new (std::nothrow)LinkedState(this); tmpErrNumber += JudgmentEmpty(pLinkedState); - pApRoamingState = new ApRoamingState(this); + pApRoamingState = new (std::nothrow)ApRoamingState(this); tmpErrNumber += JudgmentEmpty(pApRoamingState); - pNetSpeed = new StaNetWorkSpeed(); - tmpErrNumber += JudgmentEmpty(pNetSpeed); - pDhcpResultNotify = new DhcpResultNotify(this); + pDhcpResultNotify = new (std::nothrow)DhcpResultNotify(this); tmpErrNumber += JudgmentEmpty(pDhcpResultNotify); if (tmpErrNumber != 0) { WIFI_LOGE("InitStaStates some one state is null\n"); @@ -188,6 +181,9 @@ void StaStateMachine::InitWifiLinkedInfo() linkedInfo.ssid = ""; linkedInfo.bssid = ""; linkedInfo.macAddress = ""; + linkedInfo.macType = 0; + linkedInfo.rxLinkSpeed = 0; + linkedInfo.txLinkSpeed = 0; linkedInfo.rssi = 0; linkedInfo.band = 0; linkedInfo.frequency = 0; @@ -197,6 +193,8 @@ void StaStateMachine::InitWifiLinkedInfo() linkedInfo.ifHiddenSSID = false; linkedInfo.chload = 0; linkedInfo.snr = 0; + linkedInfo.isDataRestricted = 0; + linkedInfo.portalUrl = ""; linkedInfo.detailedState = DetailedState::DISCONNECTED; } @@ -206,6 +204,9 @@ void StaStateMachine::InitLastWifiLinkedInfo() lastLinkedInfo.ssid = ""; lastLinkedInfo.bssid = ""; lastLinkedInfo.macAddress = ""; + linkedInfo.macType = 0; + lastLinkedInfo.rxLinkSpeed = 0; + lastLinkedInfo.txLinkSpeed = 0; lastLinkedInfo.rssi = 0; lastLinkedInfo.band = 0; lastLinkedInfo.frequency = 0; @@ -215,6 +216,8 @@ void StaStateMachine::InitLastWifiLinkedInfo() lastLinkedInfo.ifHiddenSSID = false; lastLinkedInfo.chload = 0; lastLinkedInfo.snr = 0; + linkedInfo.isDataRestricted = 0; + linkedInfo.portalUrl = ""; lastLinkedInfo.detailedState = DetailedState::DISCONNECTED; } @@ -237,7 +240,7 @@ void StaStateMachine::BuildStateTree() void StaStateMachine::RegisterStaServiceCallback(const StaServiceCallback &callbacks) { - LOGI("RegisterStaServiceCallback"); + WIFI_LOGI("RegisterStaServiceCallback."); staCallback = callbacks; } @@ -285,7 +288,10 @@ void StaStateMachine::InitState::GoInState() } void StaStateMachine::InitState::GoOutState() -{} +{ + WIFI_LOGI("InitState GoOutState function."); + return; +} bool StaStateMachine::InitState::ExecuteStateMsg(InternalMessage *msg) { @@ -293,36 +299,21 @@ bool StaStateMachine::InitState::ExecuteStateMsg(InternalMessage *msg) return false; } + WIFI_LOGI("InitState-msgCode=%{public}d is received.\n", msg->GetMessageName()); bool ret = NOT_EXECUTED; switch (msg->GetMessageName()) { - case WIFI_SVR_CMD_STA_START_SUPPLICANT: { - ret = EXECUTED; - pStaStateMachine->StartWifiProcess(); - break; - } - case WIFI_SVR_CMD_STA_ENABLE_WIFI: { ret = EXECUTED; pStaStateMachine->operationalMode = msg->GetParam1(); - pStaStateMachine->SendMessage(WIFI_SVR_CMD_STA_START_SUPPLICANT); + pStaStateMachine->StartWifiProcess(); break; } case WIFI_SVR_CMD_STA_OPERATIONAL_MODE: break; - case WIFI_SVR_CMD_STA_REMOVE_DEVICE_CONFIG: { - ret = EXECUTED; - pStaStateMachine->RemoveDeviceConfigProcess(msg); - break; - } - - case WIFI_SVR_CMD_STA_REMOVE_All_DEVICE_CONFIG: { - ret = EXECUTED; - pStaStateMachine->RemoveAllDeviceConfigProcess(); - break; - } default: + WIFI_LOGI("InitState-msgCode=%d not handled.\n", msg->GetMessageName()); break; } return ret; @@ -342,7 +333,15 @@ ErrCode StaStateMachine::ConvertDeviceCfg(const WifiDeviceConfig &config) const idlConfig.eap = config.wifiEapConfig.eap; idlConfig.identity = config.wifiEapConfig.identity; idlConfig.password = config.wifiEapConfig.password; + idlConfig.clientCert = config.wifiEapConfig.clientCert; + idlConfig.privateKey = config.wifiEapConfig.privateKey; + idlConfig.phase2Method = static_cast(config.wifiEapConfig.phase2Method); idlConfig.wepKeyIdx = config.wepTxKeyIndex; + if (strcmp(config.keyMgmt.c_str(), "WEP") == 0) { + /* for wep */ + idlConfig.authAlgorithms = 0x02; + } + for (int i = 0; i < MAX_WEPKEYS_SIZE; i++) { idlConfig.wepKeys[i] = config.wepKeys[i]; } @@ -358,43 +357,83 @@ ErrCode StaStateMachine::ConvertDeviceCfg(const WifiDeviceConfig &config) const return WIFI_OPT_SUCCESS; } +void StaStateMachine::SyncDeviceConfigToWpa() const +{ + WIFI_LOGI("SyncDeviceConfigToWpa"); + /* Reload wifi Configurations. */ + if (WifiSettings::GetInstance().ReloadDeviceConfig() != 0) { + WIFI_LOGE("ReloadDeviceConfig is failed!"); + } + + if (WifiStaHalInterface::GetInstance().ClearDeviceConfig() != WIFI_IDL_OPT_OK) { + WIFI_LOGE("ClearDeviceConfig() failed!"); + } else { + WIFI_LOGD("ClearDeviceConfig() succeeded!"); + std::vector results; + WifiSettings::GetInstance().GetDeviceConfig(results); + for(WifiDeviceConfig result : results) { + WIFI_LOGD("SyncDeviceConfigToWpa:result.networkId=[%d]!", result.networkId); + int networkId = INVALID_NETWORK_ID; + if (WifiStaHalInterface::GetInstance().GetNextNetworkId(networkId) != WIFI_IDL_OPT_OK) { + WIFI_LOGE("GetNextNetworkId failed."); + return; + } + if (networkId != result.networkId) { + WIFI_LOGE("DeviceConfig networkId different from wpa config networkId."); + return; + } + ConvertDeviceCfg(result); + } + WIFI_LOGD("SyncDeviceConfigToWpa-SaveDeviceConfig() succeed!"); + } +} + void StaStateMachine::StartWifiProcess() { + WifiSettings::GetInstance().SetWifiState(static_cast(WifiState::ENABLING)); + staCallback.OnStaOpenRes(OperateResState::OPEN_WIFI_OPENING); int res = WifiStaHalInterface::GetInstance().StartWifi(); if (res == static_cast(WIFI_IDL_OPT_OK)) { - WIFI_LOGD("Start wifi successfully!"); + WIFI_LOGI("Start wifi successfully!"); if (WifiStaHalInterface::GetInstance().WpaAutoConnect(false) != WIFI_IDL_OPT_OK) { WIFI_LOGI("The automatic Wpa connection is disabled failed."); } - /* Reload wifi Configurations. */ - if (WifiSettings::GetInstance().ReloadDeviceConfig() != 0) { - WIFI_LOGE("ReloadDeviceConfig() failed!"); - } - + /* callback the InterfaceService that wifi is enabled successfully. */ + WifiSettings::GetInstance().SetWifiState(static_cast(WifiState::ENABLED)); + staCallback.OnStaOpenRes(OperateResState::OPEN_WIFI_SUCCEED); /* Sets the MAC address of WifiSettings. */ std::string mac; - if ((WifiStaHalInterface::GetInstance().GetStaDeviceMacAddress(mac)) != WIFI_IDL_OPT_OK) { - WIFI_LOGI("GetStaDeviceMacAddress failed!"); - } else { + if ((WifiStaHalInterface::GetInstance().GetStaDeviceMacAddress(mac)) == WIFI_IDL_OPT_OK) { WifiSettings::GetInstance().SetMacAddress(mac); + } else { + WIFI_LOGI("GetStaDeviceMacAddress failed!"); } +#ifndef OHOS_ARCH_LITE + WIFI_LOGI("Register netsupplier"); + std::thread([cb = staCallback]() { + WifiNetAgent::GetInstance().RegisterNetSupplier(); + WifiNetAgent::GetInstance().RegisterNetSupplierCallback(cb); + }).detach(); +#endif /* Initialize Connection Information. */ InitWifiLinkedInfo(); InitLastWifiLinkedInfo(); WifiSettings::GetInstance().SaveLinkedInfo(linkedInfo); - - /* callback the InterfaceService that wifi is enabled successfully. */ - staCallback.OnStaOpenRes(OperateResState::OPEN_WIFI_SUCCEED); + SyncDeviceConfigToWpa(); +#ifndef OHOS_ARCH_LITE + ChipCapability::GetInstance().InitializeChipCapability(); +#endif /* The current state of StaStateMachine transfers to SeparatedState after * enable supplicant. */ SwitchState(pSeparatedState); } else { /* Notify the InterfaceService that wifi is failed to enable wifi. */ - LOGE("StartWifi failed, and errcode is %d", res); + LOGE("StartWifi failed, and errcode is %d.", res); + WifiSettings::GetInstance().SetWifiState(static_cast(WifiState::DISABLED)); + WifiSettings::GetInstance().SetUserLastSelectedNetworkId(INVALID_NETWORK_ID); staCallback.OnStaOpenRes(OperateResState::OPEN_WIFI_FAILED); - staCallback.OnStaOpenRes(OperateResState::OPEN_WIFI_DISABLED); } } @@ -420,6 +459,7 @@ void StaStateMachine::WpaStartingState::GoInState() void StaStateMachine::WpaStartingState::GoOutState() { + LOGI("WpaStartingState GoOutState function."); return; } @@ -452,10 +492,8 @@ StaStateMachine::WpaStartedState::~WpaStartedState() void StaStateMachine::WpaStartedState::GoInState() { - WIFI_LOGD("WpaStartedState GoInState function."); + WIFI_LOGI("WpaStartedState GoInState function."); if (pStaStateMachine->operationalMode == STA_CONNECT_MODE) { - /* Update the wifi status. */ - WifiSettings::GetInstance().SetWifiState(static_cast(WifiState::ENABLING)); pStaStateMachine->SwitchState(pStaStateMachine->pSeparatedState); } else if (pStaStateMachine->operationalMode == STA_DISABLED_MODE) { pStaStateMachine->SwitchState(pStaStateMachine->pWpaStoppingState); @@ -464,38 +502,23 @@ void StaStateMachine::WpaStartedState::GoInState() } void StaStateMachine::WpaStartedState::GoOutState() { + WIFI_LOGI("WpaStartedState GoOutState function."); return; } bool StaStateMachine::WpaStartedState::ExecuteStateMsg(InternalMessage *msg) { if (msg == nullptr) { + LOGI("msg is nullptr"); return false; } + WIFI_LOGI("WpaStartedState ExecuteStateMsg-msgCode:%{public}d.\n", msg->GetMessageName()); bool ret = NOT_EXECUTED; switch (msg->GetMessageName()) { - case WIFI_SVR_CMD_STA_STOP_SUPPLICANT: { - ret = EXECUTED; - pStaStateMachine->StopWifiProcess(); - break; - } - case WIFI_SVR_CMD_STA_DISABLE_WIFI: { ret = EXECUTED; - pStaStateMachine->SendMessage(WIFI_SVR_CMD_STA_STOP_SUPPLICANT); - break; - } - - case WIFI_SVR_CMD_STA_REMOVE_DEVICE_CONFIG: { - ret = EXECUTED; - pStaStateMachine->RemoveDeviceConfigProcess(msg); - break; - } - - case WIFI_SVR_CMD_STA_REMOVE_All_DEVICE_CONFIG: { - ret = EXECUTED; - pStaStateMachine->RemoveAllDeviceConfigProcess(); + pStaStateMachine->StopWifiProcess(); break; } @@ -507,93 +530,46 @@ bool StaStateMachine::WpaStartedState::ExecuteStateMsg(InternalMessage *msg) void StaStateMachine::StopWifiProcess() { - WIFI_LOGD("Enter StaStateMachine::StopWifiProcess.\n"); + WIFI_LOGI("Enter StaStateMachine::StopWifiProcess.\n"); +#ifndef OHOS_ARCH_LITE + WifiNetAgent::GetInstance().UnregisterNetSupplier(); +#endif + WIFI_LOGI("Stop wifi is in process...\n"); + WifiSettings::GetInstance().SetWifiState(static_cast(WifiState::DISABLING)); + staCallback.OnStaCloseRes(OperateResState::CLOSE_WIFI_CLOSING); + StopTimer(static_cast(CMD_SIGNAL_POLL)); if (currentTpType == IPTYPE_IPV4) { pDhcpService->StopDhcpClient(IF_NAME, false); } else { pDhcpService->StopDhcpClient(IF_NAME, true); } isRoam = false; - if (lastNetworkId != INVALID_NETWORK_ID) { - if (statusId == static_cast(WifiDeviceConfigStatus::DISABLED)) { - WIFI_LOGD("The network status is DISABLED:1.\n"); - WifiSettings::GetInstance().SetDeviceState( - lastNetworkId, static_cast(WifiDeviceConfigStatus::DISABLED)); - } else if (statusId == static_cast(WifiDeviceConfigStatus::ENABLED)) { - WIFI_LOGD("The network status is ENABLED:2.\n"); - WifiSettings::GetInstance().SetDeviceState( - lastNetworkId, static_cast(WifiDeviceConfigStatus::ENABLED)); - } - WifiSettings::GetInstance().SyncDeviceConfig(); - } - WIFI_LOGD("linkedInfo network = %{public}d", linkedInfo.networkId); + WifiSettings::GetInstance().SetMacAddress(""); IpInfo ipInfo; WifiSettings::GetInstance().SaveIpInfo(ipInfo); +#ifdef OHOS_ARCH_LITE IfConfig::GetInstance().FlushIpAddr(IF_NAME, IPTYPE_IPV4); +#endif /* clear connection information. */ InitWifiLinkedInfo(); WifiSettings::GetInstance().SaveLinkedInfo(linkedInfo); - WifiErrorNo errorNo = WifiStaHalInterface::GetInstance().StopWifi(); - if (errorNo == WIFI_IDL_OPT_OK) { - /* Notify result to InterfaceService. */ + if (WifiStaHalInterface::GetInstance().StopWifi() == WIFI_IDL_OPT_OK) { + /* Callback result to InterfaceService. */ + WifiSettings::GetInstance().SetWifiState(static_cast(WifiState::DISABLED)); staCallback.OnStaCloseRes(OperateResState::CLOSE_WIFI_SUCCEED); - WIFI_LOGD("Stop WifiProcess successfully!"); + WIFI_LOGI("Stop WifiProcess successfully!"); /* The current state of StaStateMachine transfers to InitState. */ SwitchState(pInitState); } else { - LOGE("StopWifiProcess failed,and errcode is %d", errorNo); + WIFI_LOGE("StopWifiProcess failed."); + WifiSettings::GetInstance().SetWifiState(static_cast(WifiState::UNKNOWN)); staCallback.OnStaCloseRes(OperateResState::CLOSE_WIFI_FAILED); } -} - -void StaStateMachine::RemoveDeviceConfigProcess(const InternalMessage *msg) -{ - if (msg == nullptr) { - return; - } - - WIFI_LOGD("Enter StaStateMachine::RemoveDeviceConfigProcess.\n"); - /* Remove network configuration. */ - if (WifiStaHalInterface::GetInstance().RemoveDevice(msg->GetParam1()) == WIFI_IDL_OPT_OK) { - WIFI_LOGD("Remove device config successfully!"); - - if (WifiStaHalInterface::GetInstance().SaveDeviceConfig() != WIFI_IDL_OPT_OK) { - WIFI_LOGW("RemoveDeviceConfig:SaveDeviceConfig failed!"); - } else { - WIFI_LOGD("RemoveDeviceConfig-SaveDeviceConfig successfully!"); - } - } else { - WIFI_LOGE("RemoveDeviceConfig failed!"); - } - - /* Remove network configuration directly without notification to InterfaceService. */ - WifiSettings::GetInstance().RemoveDevice(msg->GetParam1()); - if (WifiSettings::GetInstance().SyncDeviceConfig() != 0) { - WIFI_LOGE("RemoveDeviceConfigProcess-SyncDeviceConfig() failed!"); - } -} - -void StaStateMachine::RemoveAllDeviceConfigProcess() -{ - WIFI_LOGD("Enter StaStateMachine::RemoveAllDeviceConfigProcess.\n"); - if (WifiStaHalInterface::GetInstance().ClearDeviceConfig() == WIFI_IDL_OPT_OK) { - WIFI_LOGD("Remove all device config successfully!"); - - if (WifiStaHalInterface::GetInstance().SaveDeviceConfig() != WIFI_IDL_OPT_OK) { - WIFI_LOGW("RemoveAllDeviceConfig:SaveDeviceConfig failed!"); - } - } else { - WIFI_LOGE("RemoveAllDeviceConfig failed!"); - } - - WifiSettings::GetInstance().ClearDeviceConfig(); - if (WifiSettings::GetInstance().SyncDeviceConfig() != 0) { - WIFI_LOGE("RemoveAllDeviceConfigProcess-SyncDeviceConfig() failed!"); - } + WifiSettings::GetInstance().SetUserLastSelectedNetworkId(INVALID_NETWORK_ID); } /* --------------------------- state machine WpaStopping State ------------------------------ */ @@ -606,13 +582,16 @@ StaStateMachine::WpaStoppingState::~WpaStoppingState() void StaStateMachine::WpaStoppingState::GoInState() { - WIFI_LOGE("WpaStoppingState GoInState function."); + WIFI_LOGI("WpaStoppingState GoInState function."); pStaStateMachine->SwitchState(pStaStateMachine->pInitState); return; } void StaStateMachine::WpaStoppingState::GoOutState() -{} +{ + WIFI_LOGI("WpaStoppingState GoOutState function."); + return; +} bool StaStateMachine::WpaStoppingState::ExecuteStateMsg(InternalMessage *msg) { @@ -621,11 +600,11 @@ bool StaStateMachine::WpaStoppingState::ExecuteStateMsg(InternalMessage *msg) } bool ret = NOT_EXECUTED; - WIFI_LOGI("RootState-msgCode=%{public}d not handled.\n", msg->GetMessageName()); + WIFI_LOGI("WpaStoppingState-msgCode=%{public}d not handled.\n", msg->GetMessageName()); return ret; } -/* --------------------------- state machine Connect State ------------------------------ */ +/* --------------------------- state machine link State ------------------------------ */ StaStateMachine::LinkState::LinkState(StaStateMachine *staStateMachine) : State("LinkState"), pStaStateMachine(staStateMachine) {} @@ -636,19 +615,21 @@ StaStateMachine::LinkState::~LinkState() void StaStateMachine::LinkState::GoInState() { WIFI_LOGI("LinkState GoInState function."); - return; } void StaStateMachine::LinkState::GoOutState() -{} +{ + WIFI_LOGI("LinkState GoOutState function."); + return; +} bool StaStateMachine::LinkState::ExecuteStateMsg(InternalMessage *msg) { if (msg == nullptr) { return false; } - + LOGI("LinkState ExecuteStateMsg function:msgName=[%{public}d].\n", msg->GetMessageName()); auto iter = pStaStateMachine->staSmHandleFuncMap.find(msg->GetMessageName()); if (iter != pStaStateMachine->staSmHandleFuncMap.end()) { (pStaStateMachine->*(iter->second))(msg); @@ -660,7 +641,7 @@ bool StaStateMachine::LinkState::ExecuteStateMsg(InternalMessage *msg) /* -- state machine Connect State Message processing function -- */ int StaStateMachine::InitStaSMHandleMap() { - staSmHandleFuncMap[CMD_START_CONNECT_SELECTED_NETWORK] = &StaStateMachine::DealConnectToSelectedNetCmd; + staSmHandleFuncMap[CMD_SIGNAL_POLL] = &StaStateMachine::DealSignalPollResult; staSmHandleFuncMap[WIFI_SVR_CMD_STA_CONNECT_NETWORK] = &StaStateMachine::DealConnectToUserSelectedNetwork; staSmHandleFuncMap[WIFI_SVR_CMD_STA_CONNECT_SAVED_NETWORK] = &StaStateMachine::DealConnectToUserSelectedNetwork; staSmHandleFuncMap[WIFI_SVR_CMD_STA_NETWORK_DISCONNECTION_EVENT] = &StaStateMachine::DealDisconnectEvent; @@ -670,123 +651,236 @@ int StaStateMachine::InitStaSMHandleMap() staSmHandleFuncMap[WIFI_SVR_CMD_STA_STARTWPS] = &StaStateMachine::DealStartWpsCmd; staSmHandleFuncMap[WIFI_SVR_CMD_STA_WPS_TIMEOUT_EVNET] = &StaStateMachine::DealWpsConnectTimeOutEvent; staSmHandleFuncMap[WIFI_SVR_CMD_STA_CANCELWPS] = &StaStateMachine::DealCancelWpsCmd; + staSmHandleFuncMap[WIFI_SVR_CMD_STA_RECONNECT_NETWORK] = &StaStateMachine::DealReConnectCmd; staSmHandleFuncMap[WIFI_SVR_CMD_STA_REASSOCIATE_NETWORK] = &StaStateMachine::DealReassociateCmd; staSmHandleFuncMap[WIFI_SVR_COM_STA_START_ROAM] = &StaStateMachine::DealStartRoamCmd; - staSmHandleFuncMap[WIFI_SVR_CMD_STA_WPA_PASSWD_WRONG_EVENT] = &StaStateMachine::DealWpaWrongPskEvent; + staSmHandleFuncMap[WIFI_SVR_CMD_STA_WPA_PASSWD_WRONG_EVENT] = &StaStateMachine::DealWpaLinkFailEvent; + staSmHandleFuncMap[WIFI_SVR_CMD_STA_WPA_FULL_CONNECT_EVENT] = &StaStateMachine::DealWpaLinkFailEvent; + staSmHandleFuncMap[WIFI_SVR_CMD_STA_WPA_ASSOC_REJECT_EVENT] = &StaStateMachine::DealWpaLinkFailEvent; + staSmHandleFuncMap[CMD_START_NETCHECK] = &StaStateMachine::DealNetworkCheck; return WIFI_OPT_SUCCESS; } -void StaStateMachine::DealConnectToUserSelectedNetwork(InternalMessage *msg) +int setRssi(int rssi) { - if (msg == nullptr) { - return; + if (rssi < INVALID_RSSI_VALUE) { + rssi = INVALID_RSSI_VALUE; } - WIFI_LOGI("enter ConnectToUserSelectedNetwork\n"); - int networkId = msg->GetParam1(); - bool forceReconnect = msg->GetParam2(); - - /* Sets network status. */ - WifiSettings::GetInstance().EnableNetwork(networkId, forceReconnect); - StartConnectToNetwork(networkId); + if (rssi > MAX_RSSI_VALUE) { + rssi = MAX_RSSI_VALUE; + } + return rssi; } -void StaStateMachine::DealConnectToSelectedNetCmd(InternalMessage *msg) +void StaStateMachine::DealSignalPollResult(InternalMessage *msg) { + LOGI("enter DealSignalPollResult.\n"); if (msg == nullptr) { + LOGE("InternalMessage msg is null."); return; } + WifiWpaSignalInfo signalInfo; + WifiStaHalInterface::GetInstance().GetConnectSignalInfo(linkedInfo.bssid, signalInfo); + LOGI("DealSignalPollResult, signal:%{public}d, txLinkSpeed:%{public}d, rxLinkSpeed:%{public}d, " + "freq:%{public}d, noise:%{public}d.\n", + signalInfo.signal, signalInfo.txrate, signalInfo.rxrate, signalInfo.frequency, + signalInfo.noise); + if (signalInfo.signal > INVALID_RSSI_VALUE && signalInfo.signal < MAX_RSSI_VALUE) { + if (signalInfo.signal > 0) { + linkedInfo.rssi = setRssi((signalInfo.signal - SIGNAL_INFO)); + } else { + linkedInfo.rssi = setRssi(signalInfo.signal); + } + int currentSignalLevel = WifiSettings::GetInstance().GetSignalLevel(linkedInfo.rssi, linkedInfo.band); + LOGI("DealSignalPollResult, networkId:%{public}d, ssid:%{private}s, rssi:%{public}d, band:%{public}d, " + "connState:%{public}d, detailedState:%{public}d.\n", + linkedInfo.networkId, SsidAnonymize(linkedInfo.ssid).c_str(), linkedInfo.rssi, linkedInfo.band, + linkedInfo.connState, linkedInfo.detailedState); + LOGI("DealSignalPollResult currentSignalLevel:%{public}d, lastSignalLevel:%{public}d.\n", + currentSignalLevel, lastSignalLevel); + if (currentSignalLevel != lastSignalLevel) { + if (staCallback.OnStaRssiLevelChanged != nullptr) { + staCallback.OnStaRssiLevelChanged(linkedInfo.rssi); + } +#ifndef OHOS_ARCH_LITE + if (NetSupplierInfo != nullptr) { + TimeStats timeStats("Call UpdateNetSupplierInfo"); + NetSupplierInfo->isAvailable_ = true; + NetSupplierInfo->isRoaming_ = isRoam; + NetSupplierInfo->strength_ = linkedInfo.rssi; + NetSupplierInfo->frequency_ = linkedInfo.frequency; + WifiNetAgent::GetInstance().UpdateNetSupplierInfo(NetSupplierInfo); + } +#endif + lastSignalLevel = currentSignalLevel; + } + } else { + linkedInfo.rssi = INVALID_RSSI_VALUE; + } - WIFI_LOGD("Enter StaStateMachine::DealConnectToSelectedNetCmd.\n"); - WifiDeviceConfig config; - targetNetworkId = msg->GetParam1(); + if (signalInfo.txrate > 0) { + linkedInfo.txLinkSpeed = signalInfo.txrate; + linkedInfo.linkSpeed = signalInfo.txrate; + if (staCallback.OnStaStreamChanged != nullptr) { + staCallback.OnStaStreamChanged(StreamDirection::STREAM_DIRECTION_UP); + } + } - SetRandomMac(targetNetworkId); + if (signalInfo.rxrate > 0) { + linkedInfo.rxLinkSpeed = signalInfo.rxrate; + if (staCallback.OnStaStreamChanged != nullptr) { + staCallback.OnStaStreamChanged(StreamDirection::STREAM_DIRECTION_DOWN); + } + } - /* Sets linkedinfo */ - linkedInfo.networkId = targetNetworkId; - linkedInfo.ssid = config.ssid; - lastLinkedInfo.networkId = targetNetworkId; - lastLinkedInfo.ssid = config.ssid; + if (signalInfo.frequency > 0) { + linkedInfo.frequency = signalInfo.frequency; + } + linkedInfo.snr = linkedInfo.rssi - signalInfo.noise; + WifiSettings::GetInstance().SaveLinkedInfo(linkedInfo); + ConvertFreqToChannel(); + StartTimer(static_cast(CMD_SIGNAL_POLL), STA_SIGNAL_POLL_DELAY); +} - /* test */ - std::string countryCode; - if (WifiSupplicantHalInterface::GetInstance().WpaGetCountryCode(countryCode) != WIFI_IDL_OPT_OK) { - WIFI_LOGE("WpaGetCountryCode() failed!"); +void StaStateMachine::ConvertFreqToChannel() +{ + WifiDeviceConfig config; + if (WifiSettings::GetInstance().GetDeviceConfig(linkedInfo.networkId, config) != 0) { + LOGE("GetDeviceConfig failed!"); + return; } - WIFI_LOGD("WpaGetCountryCode() success countryCode=%{public}s!", countryCode.c_str()); + config.frequency = linkedInfo.frequency; + if (linkedInfo.frequency >= FREQ_2G_MIN && linkedInfo.frequency <= FREQ_2G_MAX) { + config.band = linkedInfo.band = static_cast(BandType::BAND_2GHZ); + config.channel = (linkedInfo.frequency - FREQ_2G_MIN) / CENTER_FREQ_DIFF + CHANNEL_2G_MIN; + } else if (linkedInfo.frequency == CHANNEL_14_FREQ) { + config.channel = CHANNEL_14; + } else if (linkedInfo.frequency >= FREQ_5G_MIN && linkedInfo.frequency <= FREQ_5G_MAX) { + config.band = linkedInfo.band = static_cast(BandType::BAND_5GHZ); + config.channel = (linkedInfo.frequency - FREQ_5G_MIN) / CENTER_FREQ_DIFF + CHANNEL_5G_MIN; + } + WifiSettings::GetInstance().AddDeviceConfig(config); + return; +} - if (WifiStaHalInterface::GetInstance().EnableNetwork(targetNetworkId) == WIFI_IDL_OPT_OK) { - WIFI_LOGD("EnableNetwork() succeed!"); - int connRes = WifiStaHalInterface::GetInstance().Connect(targetNetworkId); - if (connRes == static_cast(WIFI_IDL_OPT_OK)) { - WIFI_LOGD("Connect() succeed!"); +void StaStateMachine::OnConnectFailed(int networkId) +{ + WIFI_LOGE("Connect to network failed: %{public}d.\n", networkId); + SaveLinkstate(ConnState::DISCONNECTED, DetailedState::FAILED); + staCallback.OnStaConnChanged(OperateResState::CONNECT_ENABLE_NETWORK_FAILED, linkedInfo); + staCallback.OnStaConnChanged(OperateResState::DISCONNECT_DISCONNECTED, linkedInfo); +} - if (WifiStaHalInterface::GetInstance().SaveDeviceConfig() != WIFI_IDL_OPT_OK) { - WIFI_LOGW("SaveDeviceConfig() failed!"); - } else { - WIFI_LOGD("SaveDeviceConfig() succeed!"); - } - /* Update wifi status. */ - WifiSettings::GetInstance().SetWifiState(static_cast(WifiState::ENABLING)); +void StaStateMachine::DealConnectToUserSelectedNetwork(InternalMessage *msg) +{ + LOGI("enter DealConnectToUserSelectedNetwork.\n"); + if (msg == nullptr) { + LOGE("msg is null.\n"); + return; + } - /* Save connection information. */ - SaveLinkstate(ConnState::CONNECTING, DetailedState::CONNECTING); + int networkId = msg->GetParam1(); + bool forceReconnect = msg->GetParam2(); + if (linkedInfo.connState == ConnState::CONNECTED && networkId == linkedInfo.networkId) { + WIFI_LOGE("This network is in use and does not need to be reconnected.\n"); + return; + } - /* Callback result to InterfaceService. */ - staCallback.OnStaConnChanged(OperateResState::CONNECT_CONNECTING, linkedInfo); - StartTimer(static_cast(CMD_NETWORK_CONNECT_TIMEOUT), STA_NETWORK_CONNECTTING_DELAY); - } else { - WIFI_LOGE("Connect failed!"); - staCallback.OnStaConnChanged(OperateResState::CONNECT_SELECT_NETWORK_FAILED, linkedInfo); - } - } else { - WIFI_LOGE("EnableNetwork() failed!"); + /* Save connection information. */ + SaveLinkstate(ConnState::CONNECTING, DetailedState::CONNECTING); + /* Callback result to InterfaceService. */ + staCallback.OnStaConnChanged(OperateResState::CONNECT_CONNECTING, linkedInfo); + if (StartConnectToNetwork(networkId) != WIFI_OPT_SUCCESS) { + OnConnectFailed(networkId); + return; } + /* Sets network status. */ + WifiSettings::GetInstance().EnableNetwork(networkId, forceReconnect); + WifiSettings::GetInstance().SetDeviceAfterConnect(networkId); + WifiSettings::GetInstance().SetDeviceState(networkId, (int)WifiDeviceConfigStatus::ENABLED, false); } void StaStateMachine::DealConnectTimeOutCmd(InternalMessage *msg) { + LOGW("enter DealConnectTimeOutCmd.\n"); if (msg == nullptr) { WIFI_LOGE("msg is nul\n"); } - WIFI_LOGD("enter DealDisableOneNetCmd\n"); - DisableNetwork(linkedInfo.networkId); + + if (linkedInfo.connState == ConnState::CONNECTED) { + WIFI_LOGE("Currently connected and do not process timeout.\n"); + return; + } + + WifiSettings::GetInstance().SetConnectTimeoutBssid(linkedInfo.bssid); InitWifiLinkedInfo(); + SaveLinkstate(ConnState::DISCONNECTED, DetailedState::CONNECTION_TIMEOUT); WifiSettings::GetInstance().SaveLinkedInfo(linkedInfo); staCallback.OnStaConnChanged(OperateResState::CONNECT_CONNECTING_TIMEOUT, linkedInfo); + staCallback.OnStaConnChanged(OperateResState::DISCONNECT_DISCONNECTED, linkedInfo); } void StaStateMachine::DealConnectionEvent(InternalMessage *msg) { if (msg == nullptr) { + WIFI_LOGE("DealConnectionEvent, msg is nullptr.\n"); return; } - WIFI_LOGD("enter DealConnectionEvent"); + WIFI_LOGI("enter DealConnectionEvent"); + WifiSettings::GetInstance().SetDeviceAfterConnect(targetNetworkId); + WifiSettings::GetInstance().SetDeviceState(targetNetworkId, (int)WifiDeviceConfigStatus::ENABLED, false); + WifiSettings::GetInstance().SyncDeviceConfig(); /* Stop clearing the Wpa_blocklist. */ StopTimer(static_cast(WPA_BLOCK_LIST_CLEAR_EVENT)); StopTimer(static_cast(CMD_NETWORK_CONNECT_TIMEOUT)); ConnectToNetworkProcess(msg); + StartTimer(static_cast(CMD_SIGNAL_POLL), 0); if (wpsState != SetupMethod::INVALID) { SyncAllDeviceConfigs(); wpsState = SetupMethod::INVALID; } +#ifndef OHOS_ARCH_LITE + if (NetSupplierInfo != nullptr) { + NetSupplierInfo->isAvailable_ = true; + NetSupplierInfo->isRoaming_ = isRoam; + std::thread([netInfo = NetSupplierInfo]() { + WIFI_LOGI("On connect update net supplier info\n"); + WifiNetAgent::GetInstance().UpdateNetSupplierInfo(netInfo); + }).detach(); + } +#endif /* Callback result to InterfaceService. */ - staCallback.OnStaConnChanged(OperateResState::CONNECT_AP_CONNECTED, linkedInfo); + staCallback.OnStaConnChanged(OperateResState::CONNECT_OBTAINING_IP, linkedInfo); /* The current state of StaStateMachine transfers to GetIpState. */ SwitchState(pGetIpState); + WifiSettings::GetInstance().SetUserLastSelectedNetworkId(INVALID_NETWORK_ID); } void StaStateMachine::DealDisconnectEvent(InternalMessage *msg) { + LOGI("Enter DealDisconnectEvent.\n"); if (msg == nullptr) { WIFI_LOGE("msg is null\n"); } - - WIFI_LOGD("Enter DealDisconnectEvent.\n"); + if (wpsState != SetupMethod::INVALID) { + WIFI_LOGE("wpsState is INVALID\n"); + return; + } +#ifndef OHOS_ARCH_LITE + if (NetSupplierInfo != nullptr) { + NetSupplierInfo->isAvailable_ = false; + std::thread([netInfo = NetSupplierInfo]() { + WIFI_LOGI("On disconnect update net supplier info\n"); + WifiNetAgent::GetInstance().UpdateNetSupplierInfo(netInfo); + }).detach(); + } +#endif + StopTimer(static_cast(CMD_SIGNAL_POLL)); + StopTimer(static_cast(CMD_START_NETCHECK)); pNetcheck->StopNetCheckThread(); if (currentTpType == IPTYPE_IPV4) { pDhcpService->StopDhcpClient(IF_NAME, false); @@ -796,23 +890,13 @@ void StaStateMachine::DealDisconnectEvent(InternalMessage *msg) getIpSucNum = 0; getIpFailNum = 0; isRoam = false; - if (statusId == static_cast(WifiDeviceConfigStatus::DISABLED)) { - WIFI_LOGD("The network status is DISABLED:1.\n"); - WifiSettings::GetInstance().SetDeviceState(lastNetworkId, static_cast(WifiDeviceConfigStatus::DISABLED)); - } else if (statusId == static_cast(WifiDeviceConfigStatus::ENABLED)) { - WIFI_LOGD("The network status is ENABLED:2.\n"); - WifiSettings::GetInstance().SetDeviceState(lastNetworkId, static_cast(WifiDeviceConfigStatus::ENABLED)); - } else { - WIFI_LOGI("The network status is other:%{public}d.\n", statusId); - } - - WifiSettings::GetInstance().SyncDeviceConfig(); - statusId = static_cast(WifiDeviceConfigStatus::INVALID); IpInfo ipInfo; WifiSettings::GetInstance().SaveIpInfo(ipInfo); +#ifdef OHOS_ARCH_LITE IfConfig::GetInstance().FlushIpAddr(IF_NAME, IPTYPE_IPV4); - /* Initialize connection informatoin. */ +#endif + /* Initialize connection information. */ InitWifiLinkedInfo(); if (lastLinkedInfo.detailedState == DetailedState::CONNECTING) { linkedInfo.networkId = lastLinkedInfo.networkId; @@ -826,35 +910,71 @@ void StaStateMachine::DealDisconnectEvent(InternalMessage *msg) /* Callback result to InterfaceService. */ staCallback.OnStaConnChanged(OperateResState::DISCONNECT_DISCONNECTED, linkedInfo); SwitchState(pSeparatedState); + return; } -void StaStateMachine::DealWpaWrongPskEvent(InternalMessage *msg) +void StaStateMachine::DealWpaLinkFailEvent(InternalMessage *msg) { + LOGW("enter DealWpaLinkFailEvent.\n"); if (msg == nullptr) { - WIFI_LOGE("msg is null\n"); + LOGE("msg is null.\n"); + return; } - WIFI_LOGD("enter DealStartWpsCmd\n"); + StopTimer(static_cast(CMD_NETWORK_CONNECT_TIMEOUT)); InitWifiLinkedInfo(); WifiSettings::GetInstance().SaveLinkedInfo(linkedInfo); - staCallback.OnStaConnChanged(OperateResState::CONNECT_PASSWORD_WRONG, linkedInfo); + if (msg->GetMessageName() == WIFI_SVR_CMD_STA_WPA_PASSWD_WRONG_EVENT) { + SaveLinkstate(ConnState::DISCONNECTED, DetailedState::PASSWORD_ERROR); + staCallback.OnStaConnChanged(OperateResState::CONNECT_PASSWORD_WRONG, linkedInfo); + } else if (msg->GetMessageName() == WIFI_SVR_CMD_STA_WPA_FULL_CONNECT_EVENT) { + DisableNetwork(targetNetworkId); + SaveLinkstate(ConnState::DISCONNECTED, DetailedState::CONNECTION_FULL); + staCallback.OnStaConnChanged(OperateResState::CONNECT_CONNECTION_FULL, linkedInfo); + staCallback.OnStaConnChanged(OperateResState::DISCONNECT_DISCONNECTED, linkedInfo); + } else if (msg->GetMessageName() == WIFI_SVR_CMD_STA_WPA_ASSOC_REJECT_EVENT) { + DisableNetwork(targetNetworkId); + SaveLinkstate(ConnState::DISCONNECTED, DetailedState::CONNECTION_REJECT); + staCallback.OnStaConnChanged(OperateResState::CONNECT_CONNECTION_REJECT, linkedInfo); + staCallback.OnStaConnChanged(OperateResState::DISCONNECT_DISCONNECTED, linkedInfo); + } +} + +void StaStateMachine::DealReConnectCmd(InternalMessage *msg) +{ + LOGI("enter DealReConnectCmd.\n"); + if (msg == nullptr) { + WIFI_LOGE("msg is null\n"); + } + + if (linkedInfo.connState == ConnState::CONNECTED) { + WIFI_LOGE("Network is already connected, ignore the re-connect command!\n"); + return; + } + + if (WifiStaHalInterface::GetInstance().Reconnect() == WIFI_IDL_OPT_OK) { + WIFI_LOGI("StaStateMachine ReConnect successfully!"); + /* Callback result to InterfaceService */ + staCallback.OnStaConnChanged(OperateResState::CONNECT_CONNECTING, linkedInfo); + StopTimer(static_cast(CMD_NETWORK_CONNECT_TIMEOUT)); + StartTimer(static_cast(CMD_NETWORK_CONNECT_TIMEOUT), STA_NETWORK_CONNECTTING_DELAY); + } else { + WIFI_LOGE("ReConnect failed!"); + } } void StaStateMachine::DealReassociateCmd(InternalMessage *msg) { + LOGI("enter DealReassociateCmd.\n"); if (msg == nullptr) { WIFI_LOGE("msg is null\n"); } - WIFI_LOGD("enter DealStartWpsCmd\n"); - /* Obtains the current system time, assigns the timestamp of the last - * connection attempt, and prohibits scanning requests within 10 seconds. - */ - lastConnectToNetworkTimer = static_cast(WifiSettings::GetInstance().GetUserLastSelectedNetworkTimeVal()); - WIFI_LOGD("the last time connect to network is %{public}d", lastConnectToNetworkTimer); if (WifiStaHalInterface::GetInstance().Reassociate() == WIFI_IDL_OPT_OK) { /* Callback result to InterfaceService */ - staCallback.OnStaConnChanged(OperateResState::CONNECT_AP_CONNECTED, linkedInfo); - WIFI_LOGD("StaStateMachine::LinkState::ExecuteStateMsg ReAssociate successfully!"); + staCallback.OnStaConnChanged(OperateResState::CONNECT_ASSOCIATING, linkedInfo); + WIFI_LOGD("StaStateMachine ReAssociate successfully!"); + StopTimer(static_cast(CMD_NETWORK_CONNECT_TIMEOUT)); + StartTimer(static_cast(CMD_NETWORK_CONNECT_TIMEOUT), STA_NETWORK_CONNECTTING_DELAY); } else { WIFI_LOGE("ReAssociate failed!"); } @@ -862,16 +982,19 @@ void StaStateMachine::DealReassociateCmd(InternalMessage *msg) void StaStateMachine::DealStartWpsCmd(InternalMessage *msg) { + WIFI_LOGI("enter DealStartWpsCmd\n"); if (msg == nullptr) { return; } - WIFI_LOGD("enter DealStartWpsCmd\n"); - RemoveAllDeviceConfigs(); - StartWpsMode(msg); + if (WifiStaHalInterface::GetInstance().ClearDeviceConfig() != WIFI_IDL_OPT_OK) { + LOGE("ClearDeviceConfig() failed!"); + return; + } - if (wpsState == SetupMethod::DISPLAY) { - WIFI_LOGD("Clear WPA block list every ten second!"); + StartWpsMode(msg); + if ((wpsState == SetupMethod::DISPLAY) || (wpsState == SetupMethod::KEYPAD)) { + WIFI_LOGW("Clear WPA block list every ten second!"); SendMessage(WPA_BLOCK_LIST_CLEAR_EVENT); } } @@ -881,8 +1004,12 @@ void StaStateMachine::StartWpsMode(InternalMessage *msg) if (msg == nullptr) { return; } - - constexpr int multiAp = 0; + /* + * Make judgement to wps configuration information: the function will exit if + * the result is fail, then else continue to chose the Wps starting mode. The + * current state of StaStateMachine transfers to WpsState after Wps code start + * successfully. + */ WifiIdlWpsConfig wpsParam; WpsConfig wpsConfig; wpsConfig.setup = static_cast(msg->GetParam1()); @@ -895,12 +1022,12 @@ void StaStateMachine::StartWpsMode(InternalMessage *msg) wpsParam.anyFlag = 0; wpsParam.bssid = wpsConfig.bssid; } - wpsParam.multiAp = multiAp; + wpsParam.multiAp = MULTI_AP; WIFI_LOGI("wpsConfig setup = %{public}d", wpsConfig.setup); - WIFI_LOGI("wpsParam.AnyFlag = %{public}d, wpsParam.mulitAp = %{public}d, wpsParam.bssid = %s", + WIFI_LOGI("wpsParam.AnyFlag = %{public}d, wpsParam.mulitAp = %{public}d, wpsParam.bssid = %{public}s", wpsParam.anyFlag, wpsParam.multiAp, - wpsParam.bssid.c_str()); + MacAnonymize(wpsParam.bssid).c_str()); if (wpsConfig.setup == SetupMethod::PBC) { if (WifiStaHalInterface::GetInstance().StartWpsPbcMode(wpsParam) == WIFI_IDL_OPT_OK) { @@ -922,42 +1049,44 @@ void StaStateMachine::StartWpsMode(InternalMessage *msg) SwitchState(pWpsState); } else { WIFI_LOGE("StartWpsPinMode() failed!"); - staCallback.OnWpsChanged(WpsStartState::START_PIN_FAILED, pinCode); + staCallback.OnWpsChanged(WpsStartState::START_PIN_FAILED, pinCode); + } + } else if (wpsConfig.setup == SetupMethod::KEYPAD) { + if (WifiStaHalInterface::GetInstance().StartWpsPinMode(wpsParam, pinCode) == WIFI_IDL_OPT_OK) { + wpsState = wpsConfig.setup; + /* Callback result to InterfaceService. */ + staCallback.OnWpsChanged(WpsStartState::START_AP_PIN_SUCCEED, pinCode); + SwitchState(pWpsState); + } else { + LOGE("StartWpsPinMode() failed."); + staCallback.OnWpsChanged(WpsStartState::START_AP_PIN_FAILED, pinCode); } } else { - WIFI_LOGE("Start Wps failed!"); + LOGE("Start Wps failed!"); staCallback.OnWpsChanged(WpsStartState::START_WPS_FAILED, pinCode); } } -void StaStateMachine::RemoveAllDeviceConfigs() -{ - WifiStaHalInterface::GetInstance().ClearDeviceConfig(); - WifiStaHalInterface::GetInstance().SaveDeviceConfig(); - WIFI_LOGD("Remove all device configurations completed!"); - return; -} - void StaStateMachine::DealWpaBlockListClearEvent(InternalMessage *msg) { if (msg != nullptr) { - WIFI_LOGD("enter DealWpaBlockListClearEvent\n"); + WIFI_LOGE("enter DealWpaBlockListClearEvent\n"); } if (WifiStaHalInterface::GetInstance().WpaBlocklistClear() != WIFI_IDL_OPT_OK) { WIFI_LOGE("Clearing the Wpa_blocklist failed\n"); } StartTimer(static_cast(WPA_BLOCK_LIST_CLEAR_EVENT), BLOCK_LIST_CLEAR_TIMER); - WIFI_LOGD("Clearing the Wpa_blocklist.\n"); + WIFI_LOGI("Clearing the Wpa_blocklist.\n"); } void StaStateMachine::DealWpsConnectTimeOutEvent(InternalMessage *msg) { + WIFI_LOGW("enter DealWpsConnectTimeOutEvent\n"); if (msg == nullptr) { + WIFI_LOGE("msg is nullptr!\n"); return; } - WIFI_LOGD("enter DealWpsConnectTimeOutEvent\n"); - WIFI_LOGD("Wps Time out!"); DealCancelWpsCmd(msg); /* Callback InterfaceService that WPS time out. */ @@ -980,6 +1109,8 @@ void StaStateMachine::DealCancelWpsCmd(InternalMessage *msg) staCallback.OnWpsChanged(WpsStartState::STOP_PBC_SUCCEED, pinCode); } else if (wpsState == SetupMethod::DISPLAY) { staCallback.OnWpsChanged(WpsStartState::STOP_PIN_SUCCEED, pinCode); + } else if (wpsState == SetupMethod::KEYPAD) { + staCallback.OnWpsChanged(WpsStartState::STOP_AP_PIN_SUCCEED, pinCode); } if (wpsState != SetupMethod::INVALID) { wpsState = SetupMethod::INVALID; @@ -1002,6 +1133,8 @@ void StaStateMachine::DealCancelWpsCmd(InternalMessage *msg) staCallback.OnWpsChanged(WpsStartState::STOP_PBC_FAILED, pinCode); } else if (wpsState == SetupMethod::DISPLAY) { staCallback.OnWpsChanged(WpsStartState::STOP_PIN_FAILED, pinCode); + } else if (wpsState == SetupMethod::KEYPAD) { + staCallback.OnWpsChanged(WpsStartState::STOP_AP_PIN_FAILED, pinCode); } } SwitchState(pSeparatedState); @@ -1013,7 +1146,7 @@ void StaStateMachine::DealStartRoamCmd(InternalMessage *msg) return; } - WIFI_LOGD("enter DealStartRoamCmd\n"); + WIFI_LOGI("enter DealStartRoamCmd\n"); std::string bssid = msg->GetStringFromMessage(); /* GetDeviceConfig from Configuration center. */ WifiDeviceConfig network; @@ -1031,6 +1164,9 @@ void StaStateMachine::DealStartRoamCmd(InternalMessage *msg) idlConfig.eap = network.wifiEapConfig.eap; idlConfig.identity = network.wifiEapConfig.identity; idlConfig.password = network.wifiEapConfig.password; + idlConfig.clientCert = network.wifiEapConfig.clientCert; + idlConfig.privateKey = network.wifiEapConfig.privateKey; + idlConfig.phase2Method = static_cast(network.wifiEapConfig.phase2Method); if (WifiStaHalInterface::GetInstance().SetDeviceConfig(linkedInfo.networkId, idlConfig) != WIFI_IDL_OPT_OK) { WIFI_LOGE("DealStartRoamCmd SetDeviceConfig() failed!"); @@ -1047,24 +1183,141 @@ void StaStateMachine::DealStartRoamCmd(InternalMessage *msg) linkedInfo.bssid = bssid; WifiSettings::GetInstance().SaveLinkedInfo(linkedInfo); - /* Start roaming */ - SwitchState(pApRoamingState); if (WifiStaHalInterface::GetInstance().Reassociate() != WIFI_IDL_OPT_OK) { WIFI_LOGE("START_ROAM-ReAssociate() failed!"); } WIFI_LOGI("START_ROAM-ReAssociate() succeeded!"); + /* Start roaming */ + SwitchState(pApRoamingState); } -void StaStateMachine::StartConnectToNetwork(int networkId) +ErrCode StaStateMachine::StartConnectToNetwork(int networkId) { - InternalMessage *msg = CreateMessage(); - if (msg == nullptr) { - return; + targetNetworkId = networkId; + SetRandomMac(targetNetworkId); + if (WifiStaHalInterface::GetInstance().EnableNetwork(targetNetworkId) != WIFI_IDL_OPT_OK) { + LOGE("EnableNetwork() failed!"); + return WIFI_OPT_FAILED; } - msg->SetMessageName(CMD_START_CONNECT_SELECTED_NETWORK); - msg->SetParam1(networkId); - SendMessage(msg); + if (WifiStaHalInterface::GetInstance().Connect(targetNetworkId) != WIFI_IDL_OPT_OK) { + LOGE("Connect failed!"); + staCallback.OnStaConnChanged(OperateResState::CONNECT_SELECT_NETWORK_FAILED, linkedInfo); + return WIFI_OPT_FAILED; + } + + if (WifiStaHalInterface::GetInstance().SaveDeviceConfig() != WIFI_IDL_OPT_OK) { + /* OHOS's wpa don't support save command, so don't judge as failure */ + LOGE("SaveDeviceConfig() failed!"); + } + + StopTimer(static_cast(CMD_NETWORK_CONNECT_TIMEOUT)); + StartTimer(static_cast(CMD_NETWORK_CONNECT_TIMEOUT), STA_NETWORK_CONNECTTING_DELAY); + return WIFI_OPT_SUCCESS; +} + +void StaStateMachine::MacAddressGenerate(std::string &strMac) +{ + LOGI("enter MacAddressGenerate\n"); + constexpr int arraySize = 4; + constexpr int macBitSize = 12; + constexpr int firstBit = 1; + constexpr int lastBit = 11; + constexpr int two = 2; + constexpr int hexBase = 16; + constexpr int octBase = 8; + int ret = 0; + char strMacTmp[arraySize] = {0}; + srand(static_cast(time(nullptr))); + for (int i = 0; i < macBitSize; i++) { + if (i != firstBit) { + ret = sprintf_s(strMacTmp, arraySize, "%x", rand() % hexBase); + } else { + ret = sprintf_s(strMacTmp, arraySize, "%x", two * (rand() % octBase)); + } + if (ret == -1) { + LOGE("StaStateMachine::MacAddressGenerate failed, sprintf_s return -1!\n"); + } + strMac += strMacTmp; + if ((i % two) != 0 && (i != lastBit)) { + strMac.append(":"); + } + } +} + +bool StaStateMachine::ComparedKeymgmt(const std::string scanInfoKeymgmt, const std::string deviceKeymgmt) +{ + if (deviceKeymgmt == "WPA-PSK") { + return scanInfoKeymgmt.find("PSK") != std::string::npos; + } else if (deviceKeymgmt == "WPA-EAP") { + return scanInfoKeymgmt.find("EAP") != std::string::npos; + } else if (deviceKeymgmt == "SAE") { + return scanInfoKeymgmt.find("SAE") != std::string::npos; + } else if (deviceKeymgmt == "NONE") { + return (scanInfoKeymgmt.find("PSK") == std::string::npos) && + (scanInfoKeymgmt.find("EAP") == std::string::npos) && (scanInfoKeymgmt.find("SAE") == std::string::npos); + } else { + return false; + } +} + +bool StaStateMachine::SetRandomMac(int networkId) +{ + LOGI("enter SetRandomMac.\n"); + WifiDeviceConfig deviceConfig; + if (WifiSettings::GetInstance().GetDeviceConfig(networkId, deviceConfig) != 0) { + LOGE("SetRandomMac : GetDeviceConfig failed!\n"); + return false; + } + std::string lastMac; + std::string currentMac; + if (deviceConfig.wifiPrivacySetting == WifiPrivacyConfig::DEVICEMAC) { + } else { + WifiStoreRandomMac randomMacInfo; + std::vector scanInfoList; + WifiSettings::GetInstance().GetScanInfoList(scanInfoList); + for (auto scanInfo : scanInfoList) { + if ((deviceConfig.ssid == scanInfo.ssid) && + (ComparedKeymgmt(scanInfo.capabilities, deviceConfig.keyMgmt))) { + randomMacInfo.ssid = scanInfo.ssid; + randomMacInfo.keyMgmt = deviceConfig.keyMgmt; + randomMacInfo.peerBssid = scanInfo.bssid; + break; + } + } + if (randomMacInfo.ssid.empty()) { + LOGE("scanInfo has no target wifi!\n"); + return false; + } + + /* Sets the MAC address of WifiSettings. */ + MacAddressGenerate(randomMacInfo.randomMac); + WifiSettings::GetInstance().AddRandomMac(randomMacInfo); + currentMac = randomMacInfo.randomMac; + } + + if ((WifiStaHalInterface::GetInstance().GetStaDeviceMacAddress(lastMac)) != WIFI_IDL_OPT_OK) { + LOGE("GetStaDeviceMacAddress failed!"); + return false; + } + + if (MacAddress::IsValidMac(currentMac.c_str())) { + LOGI("Check MacAddress successfully.\n"); + if (lastMac != currentMac) { + if (WifiStaHalInterface::GetInstance().SetConnectMacAddr(currentMac) != WIFI_IDL_OPT_OK) { + LOGE("set Mac [%s] failed.\n", currentMac.c_str()); + return false; + } + } + WifiSettings::GetInstance().SetMacAddress(currentMac); + deviceConfig.macAddress = currentMac; + WifiSettings::GetInstance().AddDeviceConfig(deviceConfig); + WifiSettings::GetInstance().SyncDeviceConfig(); + } else { + LOGE("Check MacAddress error.\n"); + return false; + } + return true; } void StaStateMachine::StartRoamToNetwork(std::string bssid) @@ -1079,10 +1332,16 @@ void StaStateMachine::StartRoamToNetwork(std::string bssid) SendMessage(msg); } +bool StaStateMachine::IsRoaming(void) +{ + return isRoam; +} + void StaStateMachine::OnNetworkConnectionEvent(int networkId, std::string bssid) { InternalMessage *msg = CreateMessage(); if (msg == nullptr) { + LOGE("msg is nullptr.\n"); return; } @@ -1092,34 +1351,35 @@ void StaStateMachine::OnNetworkConnectionEvent(int networkId, std::string bssid) SendMessage(msg); } -void StaStateMachine::SyncLinkInfo(const std::vector &scanInfos) +void StaStateMachine::OnBssidChangedEvent(std::string reason, std::string bssid) { - WIFI_LOGI("Enter StaStateMachine::SyncLinkInfo.\n"); - if (scanInfos.empty()) { + InternalMessage *msg = CreateMessage(); + if (msg == nullptr) { + LOGE("msg is nullptr.\n"); return; } - for (auto scanInfo : scanInfos) { - if ((scanInfo.ssid == linkedInfo.ssid) && (scanInfo.bssid == linkedInfo.bssid)) { - InternalMessage *msg = CreateMessage(); - if (msg == nullptr) { - break; - } - msg->SetMessageName(CMD_SYNC_LINKINFO); - msg->SetParam1(scanInfo.rssi); - msg->SetParam2(scanInfo.frequency); - msg->AddStringMessageBody(scanInfo.capabilities); - WIFI_LOGI("scanInfo.rssi == [%{public}d]\n", scanInfo.rssi); - WIFI_LOGI("scanInfo.frequency == [%{public}d]\n", scanInfo.frequency); - WIFI_LOGI("scanInfo.capabilities ==[%{public}s]\n", scanInfo.capabilities.c_str()); - SendMessage(msg); - return; - } + + msg->SetMessageName(WIFI_SVR_CMD_STA_BSSID_CHANGED_EVENT); + msg->AddStringMessageBody(reason); + msg->AddStringMessageBody(bssid); + SendMessage(msg); +} + +void StaStateMachine::OnDhcpResultNotifyEvent(bool result) +{ + InternalMessage *msg = CreateMessage(); + if (msg == nullptr) { + LOGE("msg is nullptr.\n"); + return; } + + msg->SetMessageName(WIFI_SVR_CMD_STA_DHCP_RESULT_NOTIFY_EVENT); + msg->SetParam1(result); + SendMessage(msg); } -/* --------------------------- state machine Disconnecting State ------------------------------ */ -StaStateMachine::SeparatingState::SeparatingState() - : State("SeparatingState") +/* --------------------------- state machine Separating State ------------------------------ */ +StaStateMachine::SeparatingState::SeparatingState() : State("SeparatingState") {} StaStateMachine::SeparatingState::~SeparatingState() @@ -1128,12 +1388,13 @@ StaStateMachine::SeparatingState::~SeparatingState() void StaStateMachine::SeparatingState::GoInState() { WIFI_LOGI("SeparatingState GoInState function."); - return; } void StaStateMachine::SeparatingState::GoOutState() -{} +{ + WIFI_LOGI("SeparatingState GoOutState function."); +} bool StaStateMachine::SeparatingState::ExecuteStateMsg(InternalMessage *msg) { @@ -1142,7 +1403,7 @@ bool StaStateMachine::SeparatingState::ExecuteStateMsg(InternalMessage *msg) } bool ret = NOT_EXECUTED; - WIFI_LOGI("RootState-msgCode=%{public}d not handled.\n", msg->GetMessageName()); + WIFI_LOGI("SeparatingState-msgCode=%{public}d not handled.\n", msg->GetMessageName()); return ret; } @@ -1157,12 +1418,14 @@ StaStateMachine::SeparatedState::~SeparatedState() void StaStateMachine::SeparatedState::GoInState() { WIFI_LOGI("SeparatedState GoInState function."); - return; } void StaStateMachine::SeparatedState::GoOutState() -{} +{ + WIFI_LOGI("SeparatedState GoOutState function."); + return; +} bool StaStateMachine::SeparatedState::ExecuteStateMsg(InternalMessage *msg) { @@ -1170,6 +1433,7 @@ bool StaStateMachine::SeparatedState::ExecuteStateMsg(InternalMessage *msg) return false; } + WIFI_LOGI("SeparatedState-msgCode=%{public}d received.\n", msg->GetMessageName()); bool ret = NOT_EXECUTED; switch (msg->GetMessageName()) { case WIFI_SVR_CMD_STA_NETWORK_DISCONNECTION_EVENT: @@ -1178,7 +1442,7 @@ bool StaStateMachine::SeparatedState::ExecuteStateMsg(InternalMessage *msg) case WIFI_SVR_CMD_STA_ENABLE_WIFI: { ret = EXECUTED; WIFI_LOGE("Wifi has already started! start Wifi failed!"); - /* Callback result to InterfaceService. */ + /* Callback result to InterfaceService. */ pStaStateMachine->staCallback.OnStaOpenRes(OperateResState::OPEN_WIFI_OVERRIDE_OPEN_FAILED); break; } @@ -1205,7 +1469,10 @@ void StaStateMachine::ApLinkedState::GoInState() } void StaStateMachine::ApLinkedState::GoOutState() -{} +{ + WIFI_LOGI("ApLinkedState GoOutState function."); + return; +} bool StaStateMachine::ApLinkedState::ExecuteStateMsg(InternalMessage *msg) { @@ -1213,26 +1480,17 @@ bool StaStateMachine::ApLinkedState::ExecuteStateMsg(InternalMessage *msg) return false; } + WIFI_LOGI("ApLinkedState-msgCode=%{public}d received.\n", msg->GetMessageName()); bool ret = NOT_EXECUTED; switch (msg->GetMessageName()) { - /* The current state of StaStateMachine transfers to DisConnectingState when - * receive the disconnecting message. + /* The current state of StaStateMachine transfers to SeparatingState when + * receive the Separating message. */ case WIFI_SVR_CMD_STA_DISCONNECT: { ret = EXECUTED; pStaStateMachine->DisConnectProcess(); break; } - case CMD_SYNC_LINKINFO: { - ret = EXECUTED; - pStaStateMachine->linkedInfo.rssi = msg->GetParam1(); - pStaStateMachine->linkedInfo.frequency = msg->GetParam2(); - pStaStateMachine->GetBandFromFreQuencies(pStaStateMachine->linkedInfo.frequency); - WifiSettings::GetInstance().SaveLinkedInfo(pStaStateMachine->linkedInfo); - std::string mgmt = msg->GetStringFromMessage(); - pStaStateMachine->SynchronousEncryptionModeAandBand(mgmt); - break; - } case WIFI_SVR_CMD_STA_NETWORK_CONNECTION_EVENT: { ret = EXECUTED; pStaStateMachine->StopTimer(static_cast(WPA_BLOCK_LIST_CLEAR_EVENT)); @@ -1244,99 +1502,42 @@ bool StaStateMachine::ApLinkedState::ExecuteStateMsg(InternalMessage *msg) break; } - case CMD_GET_NETWORK_SPEED: { - ret = EXECUTED; - pStaStateMachine->pNetSpeed->GetNetSpeed( - pStaStateMachine->linkedInfo.rxLinkSpeed, pStaStateMachine->linkedInfo.txLinkSpeed); /* Obtains rate */ - WifiSettings::GetInstance().SaveLinkedInfo(pStaStateMachine->linkedInfo); - pStaStateMachine->StartTimer(static_cast(CMD_GET_NETWORK_SPEED), STA_NETWORK_SPEED_DELAY); - break; - } default: break; } return ret; } -void StaStateMachine::SynchronousEncryptionModeAandBand(std::string mgmt) -{ - WifiDeviceConfig config; - if (WifiSettings::GetInstance().GetDeviceConfig(linkedInfo.networkId, config) != 0) { - WIFI_LOGE("GetDeviceConfig failed!"); - } - config.band = linkedInfo.band; - if (mgmt.find("WPA-PSK") != std::string::npos || mgmt.find("WPA2-PSK") != std::string::npos) { - mgmt = "WPA-PSK"; - config.keyMgmt = mgmt; - } else if (mgmt.find("EAP") != std::string::npos) { - mgmt = "WPA-EAP"; - config.keyMgmt = mgmt; - } else if (mgmt.find("SAE") != std::string::npos) { - mgmt = "SAE"; - config.keyMgmt = mgmt; - } else { - if (mgmt.find("WEP") != std::string::npos) { - WepEncryptionModeIndex(config); - } - } - WifiSettings::GetInstance().AddDeviceConfig(config); - WifiSettings::GetInstance().SyncDeviceConfig(); -} - -void StaStateMachine::WepEncryptionModeIndex(WifiDeviceConfig &config) -{ - for (int i = 0; i < MAX_WEPKEYS_SIZE; i++) { - if (config.wepKeys[i].size() != 0) { - config.wepTxKeyIndex = i + 1; - } - } -} void StaStateMachine::DisConnectProcess() { + WIFI_LOGI("Enter DisConnectProcess!"); + staCallback.OnStaConnChanged(OperateResState::DISCONNECT_DISCONNECTING, linkedInfo); if (WifiStaHalInterface::GetInstance().Disconnect() == WIFI_IDL_OPT_OK) { WIFI_LOGI("Disconnect() succeed!"); +#ifndef OHOS_ARCH_LITE + if (NetSupplierInfo != nullptr) { + NetSupplierInfo->isAvailable_ = false; + std::thread([netInfo = NetSupplierInfo]() { + WIFI_LOGI("Disconnect process update netsupplierinfo"); + WifiNetAgent::GetInstance().UpdateNetSupplierInfo(netInfo); + }).detach(); + } +#endif + WIFI_LOGI("Disconnect update wifi status"); /* Save connection information to WifiSettings. */ SaveLinkstate(ConnState::DISCONNECTED, DetailedState::DISCONNECTED); - DisableNetwork(linkedInfo.networkId); - /* Callback result to InterfaceService. */ - staCallback.OnStaConnChanged(OperateResState::DISCONNECT_DISCONNECTING, linkedInfo); - + getIpSucNum = 0; /* The current state of StaStateMachine transfers to SeparatedState. */ SwitchState(pSeparatedState); } else { + SaveLinkstate(ConnState::DISCONNECTING, DetailedState::FAILED); staCallback.OnStaConnChanged(OperateResState::DISCONNECT_DISCONNECT_FAILED, linkedInfo); WIFI_LOGE("Disconnect() failed!"); } } -void StaStateMachine::GetBandFromFreQuencies(const int &freQuency) -{ - std::vector freqs2G; - std::vector freqs5G; - if ((WifiStaHalInterface::GetInstance().GetSupportFrequencies(BAND_ONE, freqs2G) == WIFI_IDL_OPT_OK)) { - std::vector::iterator it = find(freqs2G.begin(), freqs2G.end(), freQuency); - if (it != freqs2G.end()) { - linkedInfo.band = BAND_2_G; - return; - } - } else { - WIFI_LOGE("GetSupportFrequencies 2.4Gband failed!\n"); - } - - if ((WifiStaHalInterface::GetInstance().GetSupportFrequencies(BAND_TWO, freqs5G) == WIFI_IDL_OPT_OK)) { - std::vector::iterator it = find(freqs5G.begin(), freqs5G.end(), freQuency); - if (it != freqs5G.end()) { - linkedInfo.band = BAND_5_G; - } else { - WIFI_LOGE("frequency convert band failed!\n"); - } - } else { - WIFI_LOGE("GetSupportFrequencies 5Gband failed!\n"); - } -} - /* --------------------------- state machine Wps State ------------------------------ */ StaStateMachine::StaWpsState::StaWpsState(StaStateMachine *staStateMachine) : State("StaWpsState"), pStaStateMachine(staStateMachine) @@ -1352,7 +1553,9 @@ void StaStateMachine::StaWpsState::GoInState() } void StaStateMachine::StaWpsState::GoOutState() -{} +{ + WIFI_LOGI("WpsState GoOutState function."); +} bool StaStateMachine::StaWpsState::ExecuteStateMsg(InternalMessage *msg) { @@ -1375,7 +1578,9 @@ bool StaStateMachine::StaWpsState::ExecuteStateMsg(InternalMessage *msg) pStaStateMachine->ConnectToNetworkProcess(msg); pStaStateMachine->SyncAllDeviceConfigs(); /* Callback result to InterfaceService. */ - pStaStateMachine->staCallback.OnStaConnChanged(OperateResState::CONNECT_AP_CONNECTED, pStaStateMachine->linkedInfo); + pStaStateMachine->SaveLinkstate(ConnState::CONNECTING, DetailedState::OBTAINING_IPADDR); + pStaStateMachine->staCallback.OnStaConnChanged(OperateResState::CONNECT_OBTAINING_IP, + pStaStateMachine->linkedInfo); pStaStateMachine->SwitchState(pStaStateMachine->pGetIpState); break; } @@ -1385,9 +1590,11 @@ bool StaStateMachine::StaWpsState::ExecuteStateMsg(InternalMessage *msg) /* Callback InterfaceService that wps has started successfully. */ WIFI_LOGE("WPS has already started, start wps failed!"); if (setup == SetupMethod::PBC) { - pStaStateMachine->staCallback.OnWpsChanged(WpsStartState::PBC_STARTED_ALREADY, pStaStateMachine->pinCode); - } else if (setup == SetupMethod::DISPLAY) { - pStaStateMachine->staCallback.OnWpsChanged(WpsStartState::PIN_STARTED_ALREADY, pStaStateMachine->pinCode); + pStaStateMachine->staCallback.OnWpsChanged(WpsStartState::PBC_STARTED_ALREADY, + pStaStateMachine->pinCode); + } else if ((setup == SetupMethod::DISPLAY) || (setup == SetupMethod::KEYPAD)) { + pStaStateMachine->staCallback.OnWpsChanged(WpsStartState::PIN_STARTED_ALREADY, + pStaStateMachine->pinCode); } break; } @@ -1395,13 +1602,13 @@ bool StaStateMachine::StaWpsState::ExecuteStateMsg(InternalMessage *msg) ret = EXECUTED; WIFI_LOGI("Wps PBC Overlap!"); /* Callback InterfaceService that PBC is conflicting. */ - pStaStateMachine->staCallback.OnWpsChanged(WpsStartState::START_PBC_FAILED_OVERLAP, pStaStateMachine->pinCode); + pStaStateMachine->staCallback.OnWpsChanged(WpsStartState::START_PBC_FAILED_OVERLAP, + pStaStateMachine->pinCode); pStaStateMachine->SwitchState(pStaStateMachine->pSeparatedState); break; } case WIFI_SVR_CMD_STA_CANCELWPS: { ret = EXECUTED; - pStaStateMachine->SyncAllDeviceConfigs(); pStaStateMachine->DealCancelWpsCmd(msg); break; } @@ -1431,6 +1638,9 @@ void StaStateMachine::SyncAllDeviceConfigs() idlConfig.eap = it->wifiEapConfig.eap; idlConfig.identity = it->wifiEapConfig.identity; idlConfig.password = it->wifiEapConfig.password; + idlConfig.clientCert = it->wifiEapConfig.clientCert; + idlConfig.privateKey = it->wifiEapConfig.privateKey; + idlConfig.phase2Method = static_cast(it->wifiEapConfig.phase2Method); if (WifiStaHalInterface::GetInstance().SetDeviceConfig(it->networkId, idlConfig) != WIFI_IDL_OPT_OK) { WIFI_LOGE("SetDeviceConfig failed!"); } @@ -1447,7 +1657,7 @@ void StaStateMachine::SyncAllDeviceConfigs() } } -/* --------------------------- state machine ObtainingIp State ------------------------------ */ +/* --------------------------- state machine GetIp State ------------------------------ */ StaStateMachine::GetIpState::GetIpState(StaStateMachine *staStateMachine) : State("GetIpState"), pStaStateMachine(staStateMachine) {} @@ -1458,7 +1668,13 @@ StaStateMachine::GetIpState::~GetIpState() void StaStateMachine::GetIpState::GoInState() { WIFI_LOGI("GetIpState GoInState function."); - +#ifdef WIFI_DHCP_DISABLED + SaveLinkstate(ConnState::CONNECTED, DetailedState::WORKING); + staCallback.OnStaConnChanged(OperateResState::CONNECT_NETWORK_ENABLED, linkedInfo); + SwitchState(pLinkedState); + return; +#endif + pStaStateMachine->getIpSucNum = 0; WifiDeviceConfig config; AssignIpMethod assignMethod = AssignIpMethod::DHCP; int ret = WifiSettings::GetInstance().GetDeviceConfig(pStaStateMachine->linkedInfo.networkId, config); @@ -1471,7 +1687,7 @@ void StaStateMachine::GetIpState::GoInState() std::string noProxys = config.wifiProxyconfig.manualProxyConfig.exclusionObjectList; std::string port = std::to_string(config.wifiProxyconfig.manualProxyConfig.serverPort); if (!hostName.empty()) { - IfConfig::GetInstance().SetProxy(false, hostName, port, noProxys, ""); + IfConfig::GetInstance().SetProxy(true, hostName, port, noProxys, ""); } } @@ -1486,24 +1702,24 @@ void StaStateMachine::GetIpState::GoInState() LOGE("ConfigstaticIpAddress failed!\n"); } } else { - LOGD("GetIpState get dhcp result."); - if (pStaStateMachine->isRoam && pStaStateMachine->pDhcpService->GetServerStatus()) { - pStaStateMachine->pDhcpService->RenewDhcpClient(IF_NAME); - pStaStateMachine->pDhcpService->GetDhcpResult(IF_NAME, pStaStateMachine->pDhcpResultNotify, DHCP_TIME); + int dhcpRet = 0; + DhcpServiceInfo dhcpInfo; + pStaStateMachine->pDhcpService->GetDhcpInfo(IF_NAME, dhcpInfo); + LOGI("GetIpState get dhcp result, isRoam=%{public}d, clientRunStatus=%{public}d.", + pStaStateMachine->isRoam, dhcpInfo.clientRunStatus); + pStaStateMachine->currentTpType = static_cast(WifiSettings::GetInstance().GetDhcpIpType()); + if (pStaStateMachine->currentTpType == IPTYPE_IPV6) { + dhcpRet = pStaStateMachine->pDhcpService->StartDhcpClient(IF_NAME, true); } else { - pStaStateMachine->currentTpType = static_cast(WifiSettings::GetInstance().GetDhcpIpType()); - if (pStaStateMachine->currentTpType == IPTYPE_IPV4) { - pStaStateMachine->pDhcpService->StartDhcpClient(IF_NAME, false); - } else { - pStaStateMachine->pDhcpService->StartDhcpClient(IF_NAME, true); - } - if (pStaStateMachine->pDhcpService->GetDhcpResult( - IF_NAME, pStaStateMachine->pDhcpResultNotify, DHCP_TIME) != 0) { - LOGE(" Dhcp connection failed.\n"); - if (pStaStateMachine->staCallback.OnStaConnChanged != nullptr) { - pStaStateMachine->staCallback.OnStaConnChanged(OperateResState::CONNECT_OBTAINING_IP_FAILED, - pStaStateMachine->linkedInfo); - } + dhcpRet = pStaStateMachine->pDhcpService->StartDhcpClient(IF_NAME, false); + } + if ((dhcpRet != 0) || (pStaStateMachine->pDhcpService->GetDhcpResult( + IF_NAME, pStaStateMachine->pDhcpResultNotify, DHCP_TIME) != 0)) { + LOGE(" Dhcp connection failed.\n"); + pStaStateMachine->SaveLinkstate(ConnState::DISCONNECTED, DetailedState::OBTAINING_IPADDR_FAIL); + pStaStateMachine->staCallback.OnStaConnChanged( + OperateResState::CONNECT_OBTAINING_IP_FAILED, pStaStateMachine->linkedInfo); + if (!pStaStateMachine->isRoam) { pStaStateMachine->DisConnectProcess(); } } @@ -1512,7 +1728,9 @@ void StaStateMachine::GetIpState::GoInState() } void StaStateMachine::GetIpState::GoOutState() -{} +{ + WIFI_LOGI("GetIpState GoOutState function."); +} bool StaStateMachine::GetIpState::ExecuteStateMsg(InternalMessage *msg) { @@ -1521,15 +1739,27 @@ bool StaStateMachine::GetIpState::ExecuteStateMsg(InternalMessage *msg) } bool ret = NOT_EXECUTED; - WIFI_LOGI("RootState-msgCode=%{public}d not handled.\n", msg->GetMessageName()); + bool result = false; + WIFI_LOGI("GetIpState-msgCode=%{public}d received.\n", msg->GetMessageName()); + switch (msg->GetMessageName()) { + case WIFI_SVR_CMD_STA_DHCP_RESULT_NOTIFY_EVENT: { + ret = EXECUTED; + result = msg->GetParam1(); + WIFI_LOGI("GetIpState, get ip result:%{public}d.\n", result); + pStaStateMachine->SwitchState(pStaStateMachine->pLinkedState); + break; + } + default: + break; + } + return ret; } -/* --- state machine ObtainingIp State functions ----- */ +/* --- state machine GetIp State functions ----- */ bool StaStateMachine::ConfigStaticIpAddress(StaticIpAddress &staticIpAddress) { WIFI_LOGI("Enter StaStateMachine::SetDhcpResultFromStatic."); - DhcpResult result; switch (currentTpType) { case IPTYPE_IPV4: { @@ -1572,16 +1802,17 @@ bool StaStateMachine::ConfigStaticIpAddress(StaticIpAddress &staticIpAddress) } default: + WIFI_LOGE("Invalid currentTpType: %{public}d", currentTpType); return false; } return true; } -void StaStateMachine::HandleNetCheckResult(StaNetState netState) +void StaStateMachine::HandleNetCheckResult(StaNetState netState, const std::string portalUrl) { - WIFI_LOGI("Enter HandleNetCheckResult"); - if (linkedInfo.connState == ConnState::DISCONNECTED) { - WIFI_LOGE("Network disconnected\n"); + WIFI_LOGI("Enter HandleNetCheckResult, netState:%{public}d.", netState); + if (linkedInfo.connState != ConnState::CONNECTED) { + WIFI_LOGE("connState is NOT in connected state, connState:%{public}d\n", linkedInfo.connState); return; } @@ -1589,45 +1820,21 @@ void StaStateMachine::HandleNetCheckResult(StaNetState netState) WIFI_LOGI("HandleNetCheckResult network state is working\n"); /* Save connection information to WifiSettings. */ SaveLinkstate(ConnState::CONNECTED, DetailedState::WORKING); - statusId = static_cast(WifiDeviceConfigStatus::ENABLED); staCallback.OnStaConnChanged(OperateResState::CONNECT_NETWORK_ENABLED, linkedInfo); - /* The current state of StaStateMachine transfers to LinkedState. */ - SwitchState(pLinkedState); + } else if (netState == StaNetState::NETWORK_CHECK_PORTAL) { + linkedInfo.portalUrl = portalUrl; + SaveLinkstate(ConnState::CONNECTED, DetailedState::CAPTIVE_PORTAL_CHECK); + staCallback.OnStaConnChanged(OperateResState::CONNECT_CHECK_PORTAL, linkedInfo); } else { - WIFI_LOGI("HandleNetCheckResult network state is notworking\n"); + WIFI_LOGI("HandleNetCheckResult network state is notworking.\n"); SaveLinkstate(ConnState::CONNECTED, DetailedState::NOTWORKING); - statusId = static_cast(WifiDeviceConfigStatus::DISABLED); staCallback.OnStaConnChanged(OperateResState::CONNECT_NETWORK_DISABLED, linkedInfo); } } -int StaStateMachine::PortalHttpDetection() -{ - WIFI_LOGI("EnterPortalHttpDetection"); - - /* Detect portal hotspot and send message to InterfaceSeervice if result is yes. */ - HttpRequest httpRequest; - std::string httpReturn; - std::string httpMsg(DEFAULT_PORTAL_HTTPS_URL); - - if (httpRequest.HttpGet(httpMsg, httpReturn) == 0) { - if (httpReturn.find("204") != std::string::npos) { - WIFI_LOGE("This network is not Portal AP!"); - return WIFI_OPT_FAILED; - } else { - /* Notify result to InterfaceService. */ - WIFI_LOGI("This network is portal AP,need certification!"); - staCallback.OnStaConnChanged(OperateResState::CONNECT_CHECK_PORTAL, linkedInfo); - return 0; - } - } - WIFI_LOGE("Portal check failed!"); - return WIFI_OPT_FAILED; -} - /* --------------------------- state machine Connected State ------------------------------ */ -StaStateMachine::LinkedState::LinkedState() - : State("LinkedState") +StaStateMachine::LinkedState::LinkedState(StaStateMachine *staStateMachine) + : State("LinkedState"), pStaStateMachine(staStateMachine) {} StaStateMachine::LinkedState::~LinkedState() @@ -1648,11 +1855,38 @@ void StaStateMachine::LinkedState::GoOutState() bool StaStateMachine::LinkedState::ExecuteStateMsg(InternalMessage *msg) { if (msg == nullptr) { + WIFI_LOGI("msg is nullptr."); return false; } + WIFI_LOGI("LinkedState, reveived msgCode=%{public}d msg.\n", msg->GetMessageName()); bool ret = NOT_EXECUTED; - WIFI_LOGI("RootState-msgCode=%{public}d not handled.\n", msg->GetMessageName()); + switch (msg->GetMessageName()) { + case WIFI_SVR_CMD_STA_BSSID_CHANGED_EVENT: { + ret = EXECUTED; + std::string reason = msg->GetStringFromMessage(); + std::string bssid = msg->GetStringFromMessage(); + WIFI_LOGI("reveived bssid changed event, reason:%{public}s,bssid:%{public}s.\n", + reason.c_str(), MacAnonymize(bssid).c_str()); + if (strcmp(reason.c_str(), "ASSOC_COMPLETE") != 0) { + WIFI_LOGE("Bssid change not for ASSOC_COMPLETE, do nothing."); + return false; + } + if (WifiStaHalInterface::GetInstance().SetWpsBssid(pStaStateMachine->linkedInfo.networkId, + bssid) != WIFI_IDL_OPT_OK) { + WIFI_LOGE("SetWpsBssid return fail."); + return false; + } + pStaStateMachine->isRoam = true; + /* The current state of StaStateMachine transfers to pApRoamingState. */ + pStaStateMachine->SwitchState(pStaStateMachine->pApRoamingState); + break; + } + default: + WIFI_LOGE("NOT handle this event!"); + break; + } + return ret; } @@ -1670,7 +1904,9 @@ void StaStateMachine::ApRoamingState::GoInState() } void StaStateMachine::ApRoamingState::GoOutState() -{} +{ + WIFI_LOGI("ApRoamingState GoOutState function."); +} bool StaStateMachine::ApRoamingState::ExecuteStateMsg(InternalMessage *msg) { @@ -1678,27 +1914,31 @@ bool StaStateMachine::ApRoamingState::ExecuteStateMsg(InternalMessage *msg) return false; } + WIFI_LOGI("ApRoamingState, reveived msgCode=%{public}d msg.", msg->GetMessageName()); bool ret = NOT_EXECUTED; switch (msg->GetMessageName()) { case WIFI_SVR_CMD_STA_NETWORK_CONNECTION_EVENT: { + WIFI_LOGI("ApRoamingState, receive WIFI_SVR_CMD_STA_NETWORK_CONNECTION_EVENT event."); ret = EXECUTED; pStaStateMachine->isRoam = true; + pStaStateMachine->StopTimer(static_cast(CMD_NETWORK_CONNECT_TIMEOUT)); pStaStateMachine->ConnectToNetworkProcess(msg); /* Notify result to InterfaceService. */ - pStaStateMachine->staCallback.OnStaConnChanged( - OperateResState::CONNECT_ASSOCIATED, pStaStateMachine->linkedInfo); - pStaStateMachine->staCallback.OnStaConnChanged( - OperateResState::CONNECT_OBTAINING_IP, pStaStateMachine->linkedInfo); + pStaStateMachine->staCallback.OnStaConnChanged(OperateResState::CONNECT_ASSOCIATED, + pStaStateMachine->linkedInfo); + pStaStateMachine->staCallback.OnStaConnChanged(OperateResState::CONNECT_OBTAINING_IP, + pStaStateMachine->linkedInfo); /* The current state of StaStateMachine transfers to GetIpState. */ pStaStateMachine->SwitchState(pStaStateMachine->pGetIpState); break; } default: + WIFI_LOGI("ApRoamingState-msgCode=%d not handled.", msg->GetMessageName()); break; } - return EXECUTED; + return ret; } void StaStateMachine::ConnectToNetworkProcess(InternalMessage *msg) @@ -1709,54 +1949,58 @@ void StaStateMachine::ConnectToNetworkProcess(InternalMessage *msg) lastNetworkId = msg->GetParam1(); std::string bssid = msg->GetStringFromMessage(); - + WIFI_LOGI("ConnectToNetworkProcess, Receive msg: lastNetworkId=%{public}d, bssid=%{public}s", + lastNetworkId, MacAnonymize(bssid).c_str()); WifiDeviceConfig deviceConfig; int result = WifiSettings::GetInstance().GetDeviceConfig(lastNetworkId, deviceConfig); WIFI_LOGI("Device config networkId = %{public}d", deviceConfig.networkId); - WIFI_LOGI("Connected to AP[networkid=%{public}d], obtaining ip...", lastNetworkId); - /* Update wifi status. */ - WifiSettings::GetInstance().SetWifiState(static_cast(WifiState::ENABLED)); - - /* Save connection information. */ - WifiIdlGetDeviceConfig config; - config.networkId = lastNetworkId; - config.param = "ssid"; - if (WifiStaHalInterface::GetInstance().GetDeviceConfig(config) != WIFI_IDL_OPT_OK) { - WIFI_LOGE("GetDeviceConfig failed!"); - } - if (result == 0 && deviceConfig.bssid == bssid) { - WIFI_LOGI("Device config already exists."); + LOGI("Device Configuration already exists."); } else { - deviceConfig.networkId = lastNetworkId; deviceConfig.bssid = bssid; - deviceConfig.ssid = config.value; - deviceConfig.ssid.erase(0, 1); - deviceConfig.ssid.erase(deviceConfig.ssid.length() - 1, 1); - if (wpsState == SetupMethod::DISPLAY || wpsState == SetupMethod::PBC) { + if ((wpsState == SetupMethod::DISPLAY) || (wpsState == SetupMethod::PBC) || (wpsState == SetupMethod::KEYPAD)) { + /* Save connection information. */ + WifiIdlGetDeviceConfig config; + config.networkId = lastNetworkId; + config.param = "ssid"; + if (WifiStaHalInterface::GetInstance().GetDeviceConfig(config) != WIFI_IDL_OPT_OK) { + LOGE("GetDeviceConfig failed!"); + } + + deviceConfig.networkId = lastNetworkId; + deviceConfig.bssid = bssid; + deviceConfig.ssid = config.value; + /* Remove the double quotation marks at the head and tail. */ + deviceConfig.ssid.erase(0, 1); + deviceConfig.ssid.erase(deviceConfig.ssid.length() - 1, 1); WifiSettings::GetInstance().AddWpsDeviceConfig(deviceConfig); isWpsConnect = IsWpsConnected::WPS_CONNECTED; } else { WifiSettings::GetInstance().AddDeviceConfig(deviceConfig); } WifiSettings::GetInstance().SyncDeviceConfig(); - WIFI_LOGD("Device ssid = %s", deviceConfig.ssid.c_str()); + WIFI_LOGD("Device ssid = %s", SsidAnonymize(deviceConfig.ssid).c_str()); } - WifiSettings::GetInstance().SetDeviceState(lastNetworkId, static_cast(WifiDeviceConfigStatus::CURRENT)); - WIFI_LOGD("The network status is CURRENT:0."); + + std::string macAddr; + WifiSettings::GetInstance().GetMacAddress(macAddr); linkedInfo.networkId = lastNetworkId; linkedInfo.bssid = bssid; linkedInfo.ssid = deviceConfig.ssid; - linkedInfo.macAddress = deviceConfig.macAddress; + linkedInfo.macAddress = macAddr; + linkedInfo.ifHiddenSSID = deviceConfig.hiddenSSID; lastLinkedInfo.bssid = bssid; lastLinkedInfo.macAddress = deviceConfig.macAddress; + lastLinkedInfo.ifHiddenSSID = deviceConfig.hiddenSSID; SetWifiLinkedInfo(lastNetworkId); - SaveLinkstate(ConnState::OBTAINING_IPADDR, DetailedState::OBTAINING_IPADDR); + SaveLinkstate(ConnState::CONNECTING, DetailedState::OBTAINING_IPADDR); } void StaStateMachine::SetWifiLinkedInfo(int networkId) { + WIFI_LOGI("SetWifiLinkedInfo, linkedInfo.networkId=%{public}d, lastLinkedInfo.networkId=%{public}d", + linkedInfo.networkId, lastLinkedInfo.networkId); if (linkedInfo.networkId == INVALID_NETWORK_ID) { if (lastLinkedInfo.networkId != INVALID_NETWORK_ID) { /* Update connection information according to the last connecting information. */ @@ -1775,6 +2019,8 @@ void StaStateMachine::SetWifiLinkedInfo(int networkId) linkedInfo.txLinkSpeed = lastLinkedInfo.txLinkSpeed; linkedInfo.chload = lastLinkedInfo.chload; linkedInfo.snr = lastLinkedInfo.snr; + linkedInfo.isDataRestricted = lastLinkedInfo.isDataRestricted; + linkedInfo.portalUrl = lastLinkedInfo.portalUrl; linkedInfo.detailedState = lastLinkedInfo.detailedState; } else if (networkId != INVALID_NETWORK_ID) { linkedInfo.networkId = networkId; @@ -1786,7 +2032,7 @@ void StaStateMachine::SetWifiLinkedInfo(int networkId) linkedInfo.ssid = config.ssid; linkedInfo.bssid = config.bssid; linkedInfo.band = config.band; - linkedInfo.connState = ConnState::OBTAINING_IPADDR; + linkedInfo.connState = ConnState::CONNECTING; linkedInfo.ifHiddenSSID = config.hiddenSSID; linkedInfo.detailedState = DetailedState::OBTAINING_IPADDR; @@ -1794,7 +2040,7 @@ void StaStateMachine::SetWifiLinkedInfo(int networkId) lastLinkedInfo.ssid = config.ssid; lastLinkedInfo.bssid = config.bssid; lastLinkedInfo.band = config.band; - lastLinkedInfo.connState = ConnState::OBTAINING_IPADDR; + lastLinkedInfo.connState = ConnState::CONNECTING; lastLinkedInfo.ifHiddenSSID = config.hiddenSSID; lastLinkedInfo.detailedState = DetailedState::OBTAINING_IPADDR; } @@ -1802,6 +2048,20 @@ void StaStateMachine::SetWifiLinkedInfo(int networkId) } } +void StaStateMachine::DealNetworkCheck(InternalMessage *msg) +{ + LOGI("enter DealNetworkCheck.\n"); + if (msg == nullptr) { + LOGE("InternalMessage msg is null."); + return; + } + + if (pNetcheck == nullptr) { + LOGE("pNetcheck is null."); + return; + } + pNetcheck->SignalNetCheckThread(); +} /* ------------------ state machine dhcp callback function ----------------- */ @@ -1815,18 +2075,30 @@ StaStateMachine::DhcpResultNotify::~DhcpResultNotify() void StaStateMachine::DhcpResultNotify::OnSuccess(int status, const std::string &ifname, DhcpResult &result) { - WIFI_LOGI("Enter DhcpResultNotify::OnSuccess"); - if (ifname.compare("wlan0") == 0) { - WIFI_LOGD("iptype=%d, ip=%s, gateway=%s, subnet=%s, serverAddress=%s, leaseDuration=%d", - result.iptype, - result.strYourCli.c_str(), - result.strSubnet.c_str(), - result.strRouter1.c_str(), - result.strServer.c_str(), - result.uLeaseTime); + LOGI("Enter Sta DhcpResultNotify::OnSuccess. ifname=[%{public}s] status=[%{public}d]\n", + ifname.c_str(), status); + if ((pStaStateMachine->linkedInfo.detailedState == DetailedState::DISCONNECTING) || + (pStaStateMachine->linkedInfo.detailedState == DetailedState::DISCONNECTED)) { + return; + } + WIFI_LOGI("iptype=%{public}d, ip=%{public}s, gateway=%{public}s, \ + subnet=%{public}s, serverAddress=%{public}s, leaseDuration=%{public}d.", + result.iptype, + IpAnonymize(result.strYourCli).c_str(), + IpAnonymize(result.strRouter1).c_str(), + IpAnonymize(result.strSubnet).c_str(), + IpAnonymize(result.strServer).c_str(), + result.uLeaseTime); + WIFI_LOGI("strDns1=%{public}s, strDns2=%{public}s", IpAnonymize(result.strDns1).c_str(), + IpAnonymize(result.strDns2).c_str()); + + IpInfo ipInfo; + WifiSettings::GetInstance().GetIpInfo(ipInfo); + if (!((IpTools::ConvertIpv4Address(result.strYourCli) == ipInfo.ipAddress) && + (IpTools::ConvertIpv4Address(result.strRouter1) == ipInfo.gateway))) { + result.strDns2 = WifiSettings::GetInstance().GetStrDnsBak(); if (result.iptype == 0) { - IpInfo ipInfo; ipInfo.ipAddress = IpTools::ConvertIpv4Address(result.strYourCli); ipInfo.gateway = IpTools::ConvertIpv4Address(result.strRouter1); ipInfo.netmask = IpTools::ConvertIpv4Address(result.strSubnet); @@ -1836,55 +2108,81 @@ void StaStateMachine::DhcpResultNotify::OnSuccess(int status, const std::string ipInfo.leaseDuration = result.uLeaseTime; WifiSettings::GetInstance().SaveIpInfo(ipInfo); pStaStateMachine->linkedInfo.ipAddress = IpTools::ConvertIpv4Address(result.strYourCli); + pStaStateMachine->linkedInfo.isDataRestricted = + (result.strVendor.find("ANDROID_METERED") == std::string::npos) ? 0 : 1; WifiSettings::GetInstance().SaveLinkedInfo(pStaStateMachine->linkedInfo); +#ifndef OHOS_ARCH_LITE + WIFI_LOGI("Update NetLink info, strYourCli=%{public}s, strSubnet=%{public}s, \ + strRouter1=%{public}s, strDns1=%{public}s, strDns2=%{public}s", + IpAnonymize(result.strYourCli).c_str(), IpAnonymize(result.strSubnet).c_str(), + IpAnonymize(result.strRouter1).c_str(), IpAnonymize(result.strDns1).c_str(), + IpAnonymize(result.strDns2).c_str()); + std::thread([result]() { + WIFI_LOGI("On dhcp success update net linke info"); + WifiNetAgent::GetInstance().UpdateNetLinkInfo(result.strYourCli, result.strSubnet, result.strRouter1, + result.strDns1, result.strDns2); + }).detach(); +#endif } +#ifdef OHOS_ARCH_LITE + IfConfig::GetInstance().SetIfDnsAndRoute(result, result.iptype); +#endif + } - IfConfig::GetInstance().SetIfAddr(result, result.iptype); - if (pStaStateMachine->getIpSucNum == 0) { - pStaStateMachine->SaveLinkstate(ConnState::CONNECTED, DetailedState::CONNECTED); - pStaStateMachine->staCallback.OnStaConnChanged( - OperateResState::CONNECT_AP_CONNECTED, pStaStateMachine->linkedInfo); - /* Wait for the network adapter information to take effect. */ - sleep(SLEEPTIME); + WIFI_LOGI("DhcpResultNotify::OnSuccess, getIpSucNum=%{public}d, isRoam=%{public}d", + pStaStateMachine->getIpSucNum, pStaStateMachine->isRoam); + pStaStateMachine->OnDhcpResultNotifyEvent(true); + if (pStaStateMachine->getIpSucNum == 0 || pStaStateMachine->isRoam) { + pStaStateMachine->SaveLinkstate(ConnState::CONNECTED, DetailedState::CONNECTED); + pStaStateMachine->staCallback.OnStaConnChanged( + OperateResState::CONNECT_AP_CONNECTED, pStaStateMachine->linkedInfo); + /* Delay to wait for the network adapter information to take effect. */ + constexpr int NETCHECK_DELAY_TIME = 2000; // 2000 ms + pStaStateMachine->StartTimer(static_cast(CMD_START_NETCHECK), NETCHECK_DELAY_TIME); + } + pStaStateMachine->getIpSucNum++; - /* Check whether the Internet access is normal by send http. */ - pStaStateMachine->pNetcheck->SignalNetCheckThread(); + WIFI_LOGI("DhcpResultNotify::OnSuccess, stop dhcp client"); + if (pStaStateMachine->pDhcpService != nullptr) { + if (pStaStateMachine->currentTpType == IPTYPE_IPV6) { + pStaStateMachine->pDhcpService->StopDhcpClient(IF_NAME, true); + } else { + pStaStateMachine->pDhcpService->StopDhcpClient(IF_NAME, false); } - pStaStateMachine->getIpSucNum++; - return; } + return; } void StaStateMachine::DhcpResultNotify::OnFailed(int status, const std::string &ifname, const std::string &reason) { - WIFI_LOGI("Enter DhcpResultNotify::OnFailed"); - if (ifname.compare("wlan0") == 0) { - if (pStaStateMachine->currentTpType != IPTYPE_IPV4) { - if (pStaStateMachine->getIpSucNum == 0 && pStaStateMachine->getIpFailNum == 1) { - pStaStateMachine->staCallback.OnStaConnChanged(OperateResState::CONNECT_OBTAINING_IP_FAILED, - pStaStateMachine->linkedInfo); - pStaStateMachine->DisConnectProcess(); - } - } else { - pStaStateMachine->staCallback.OnStaConnChanged( - OperateResState::CONNECT_OBTAINING_IP_FAILED, pStaStateMachine->linkedInfo); - if (!pStaStateMachine->isRoam) { - pStaStateMachine->DisConnectProcess(); - } else { - pStaStateMachine->SaveLinkstate(ConnState::CONNECTED, DetailedState::CONNECTED); - } - } - pStaStateMachine->getIpFailNum++; + LOGI("Enter DhcpResultNotify::OnFailed. ifname=[%s] status=[%d], reason = [%s], detailedState = [%d]\n", + ifname.c_str(), status, reason.c_str(), static_cast(pStaStateMachine->linkedInfo.detailedState)); + if ((pStaStateMachine->linkedInfo.detailedState == DetailedState::DISCONNECTING) || + (pStaStateMachine->linkedInfo.detailedState == DetailedState::DISCONNECTED)) { + return; + } + + LOGI("currentTpType: %{public}d, getIpSucNum: %{public}d, getIpFailNum: %{public}d, isRoam: %{public}d", + pStaStateMachine->currentTpType, pStaStateMachine->getIpSucNum, + pStaStateMachine->getIpFailNum, pStaStateMachine->isRoam); + + if (pStaStateMachine->getIpFailNum == 0) { + pStaStateMachine->staCallback.OnStaConnChanged(OperateResState::CONNECT_OBTAINING_IP_FAILED, + pStaStateMachine->linkedInfo); + pStaStateMachine->DisConnectProcess(); + pStaStateMachine->SaveLinkstate(ConnState::DISCONNECTED, DetailedState::OBTAINING_IPADDR_FAIL); + pStaStateMachine->staCallback.OnStaConnChanged(OperateResState::DISCONNECT_DISCONNECTED, + pStaStateMachine->linkedInfo); } + pStaStateMachine->getIpFailNum++; } void StaStateMachine::DhcpResultNotify::OnSerExitNotify(const std::string &ifname) { - WIFI_LOGI("Enter DhcpResultNotify::OnSerExitNotify"); + LOGI("Enter DhcpResultNotify::OnSerExitNotify. ifname = [%s]\n", ifname.c_str()); } /* ------------------ state machine Comment function ----------------- */ - void StaStateMachine::SaveLinkstate(ConnState state, DetailedState detailState) { linkedInfo.connState = state; @@ -1894,104 +2192,29 @@ void StaStateMachine::SaveLinkstate(ConnState state, DetailedState detailState) WifiSettings::GetInstance().SaveLinkedInfo(linkedInfo); } -void StaStateMachine::DisableNetwork(int networkId) +int StaStateMachine::GetLinkedInfo(WifiLinkedInfo& linkedInfo) { - if (WifiStaHalInterface::GetInstance().DisableNetwork(networkId) == WIFI_IDL_OPT_OK) { - WIFI_LOGI("DisableNetwork() succeed, networkId=%{public}d", networkId); - - if (WifiStaHalInterface::GetInstance().SaveDeviceConfig() == WIFI_IDL_OPT_OK) { - WIFI_LOGI("DisableNetwork-SaveDeviceConfig() succeed!"); - } else { - WIFI_LOGW("DisableNetwork-SaveDeviceConfig() failed!"); - } - } else { - WIFI_LOGE("DisableNetwork() failed, networkId=%{public}d", networkId); - } + return WifiSettings::GetInstance().GetLinkedInfo(linkedInfo); } -void StaStateMachine::SetOperationalMode(int mode) +ErrCode StaStateMachine::DisableNetwork(int networkId) { - SendMessage(WIFI_SVR_CMD_STA_OPERATIONAL_MODE, mode, 0); -} - -void StaStateMachine::MacAddressGenerate(std::string &strMac) -{ - char szMacStr[] = "0123456789abcdef"; - std::random_device rd; - for (int i = 0; i < MAC_LENGTH; i++) { - int rndnum = std::abs((int)rd()); - if (i != 1) { - strMac.push_back(szMacStr[rndnum % RAND_SEED_16]); - } else { - strMac.push_back(szMacStr[MAC_STEP * (rndnum % RAND_SEED_8)]); - } - if ((i % MAC_STEP) != 0 && (i != MAC_LENGTH-1)) { - strMac.push_back(':'); - } + if (WifiStaHalInterface::GetInstance().DisableNetwork(networkId) != WIFI_IDL_OPT_OK) { + LOGE("DisableNetwork() failed, networkId=%d.", networkId); + return WIFI_OPT_FAILED; } -} -bool StaStateMachine::SetRandomMac(const int networkId) -{ - std::string strMac; - WifiDeviceConfig deviceConfig; - if (WifiSettings::GetInstance().GetDeviceConfig(networkId, deviceConfig) == 0) { - if (!deviceConfig.macAddress.empty()) { - strMac = deviceConfig.macAddress; - } else { - MacAddressGenerate(strMac); - deviceConfig.macAddress = strMac; - WifiSettings::GetInstance().AddDeviceConfig(deviceConfig); - WifiSettings::GetInstance().SyncDeviceConfig(); - } - - if (CheckMacFormat(strMac) == 0) { - WIFI_LOGI("Check MacAddress successfully.\n"); - if (WifiStaHalInterface::GetInstance().SetConnectMacAddr(strMac) != WIFI_IDL_OPT_OK) { - WIFI_LOGE("wlan0 set Mac [%s] failed.\n", strMac.c_str()); - return false; - } - return true; - } else { - WIFI_LOGE("Check MacAddress error.\n"); - return false; - } - } else { - WIFI_LOGE("SetRandomMac GetDeviceConfig failed!"); - return false; + if (WifiStaHalInterface::GetInstance().SaveDeviceConfig() != WIFI_IDL_OPT_OK) { + LOGE("DisableNetwork-SaveDeviceConfig() failed!"); + return WIFI_OPT_FAILED; } + LOGI("DisableNetwork-SaveDeviceConfig() succeed!"); + return WIFI_OPT_SUCCESS; } -int StaStateMachine::CheckMacFormat(const std::string &mac) +void StaStateMachine::SetOperationalMode(int mode) { - int status; - const std::string pattern = "^([A-Fa-f0-9]{2}[-,:]){5}[A-Fa-f0-9]{2}$"; - const int cflags = REG_EXTENDED | REG_NEWLINE; - - char ebuf[BUFFER_SIZE] = {0}; - regmatch_t pmatch[1]; - const size_t nmatch = 1; - regex_t reg; - - status = regcomp(®, pattern.c_str(), cflags); - if (status != 0) { - regerror(status, ®, ebuf, sizeof(ebuf)); - fprintf(stderr, "regcomp failed: %s , pattern: %s \n", ebuf, pattern.c_str()); - regfree(®); - return -1; - } - - status = regexec(®, mac.c_str(), nmatch, pmatch, 0); - if (status != 0) { - regerror(status, ®, ebuf, sizeof(ebuf)); - WIFI_LOGE("regexec failed."); - regfree(®); - return -1; - } - - printf("[%s] match success.\n", __FUNCTION__); - regfree(®); - return 0; + SendMessage(WIFI_SVR_CMD_STA_OPERATIONAL_MODE, mode, 0); } } // namespace Wifi -} // namespace OHOS \ No newline at end of file +} // namespace OHOS diff --git a/services/wifi_standard/wifi_framework/wifi_manage/wifi_sta/sta_state_machine.h b/wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_sta/sta_state_machine.h old mode 100755 new mode 100644 similarity index 78% rename from services/wifi_standard/wifi_framework/wifi_manage/wifi_sta/sta_state_machine.h rename to wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_sta/sta_state_machine.h index 4eaf829a4f2e754e799113438b13569129970c17..a092da7ac1df6bebe3e59cd6bc6d1baf588cf053 --- a/services/wifi_standard/wifi_framework/wifi_manage/wifi_sta/sta_state_machine.h +++ b/wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_sta/sta_state_machine.h @@ -1,5 +1,5 @@ /* - * Copyright (C) 2021 Huawei Device Co., Ltd. + * Copyright (C) 2021-2022 Huawei Device Co., Ltd. * 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 @@ -24,42 +24,62 @@ #include "wifi_errcode.h" #include "wifi_msg.h" #include "state_machine.h" -#include "sta_network_speed.h" #include "sta_network_check.h" #include "i_dhcp_result_notify.h" #include "sta_service_callback.h" #include "i_dhcp_service.h" #include "sta_define.h" +#ifndef OHOS_ARCH_LITE +#include "wifi_net_agent.h" +#endif namespace OHOS { namespace Wifi { -static const int STA_CONNECT_MODE = 1; -static const int STA_SCAN_ONLY_MODE = 2; -static const int STA_CAN_ONLY_WITH_WIFI_OFF_MODE = 3; -static const int STA_DISABLED_MODE = 4; -static const int CMD_START_WIFI_SUCCESS = 0x01; -static const int CMD_STOP_WIFI_SUCCESS = 0x02; -static const int CMD_CONNECT_NETWORK = 0x03; -static const int CMD_START_CONNECT_SELECTED_NETWORK = 0x04; -static const int CMD_DISCONNECT_NETWORK = 0X05; -static const int CMD_SYNC_LINKINFO = 0X06; -static const int CMD_GET_NETWORK_SPEED = 0X07; -static const int STA_NETWORK_SPEED_DELAY = 1 * 1000; -static const int CMD_NETWORK_CONNECT_TIMEOUT = 0X08; -static const int STA_NETWORK_CONNECTTING_DELAY = 60 * 1000; -static const int PIN_CODE_LEN = 8; /* pincode length */ - -static const int DHCP_TIME = 15; +constexpr int STA_CONNECT_MODE = 1; +constexpr int STA_SCAN_ONLY_MODE = 2; +constexpr int STA_CAN_ONLY_WITH_WIFI_OFF_MODE = 3; +constexpr int STA_DISABLED_MODE = 4; + +constexpr int CMD_NETWORK_CONNECT_TIMEOUT = 0X01; +constexpr int CMD_SIGNAL_POLL = 0X02; +constexpr int CMD_START_NETCHECK = 0X03; + +constexpr int STA_NETWORK_CONNECTTING_DELAY = 20 * 1000; +constexpr int STA_SIGNAL_POLL_DELAY = 3 * 1000; + +/* pincode length */ +constexpr int PIN_CODE_LEN = 8; + +/* DHCP timeout interval */ +constexpr int DHCP_TIME = 15; +/* rssi thresholds */ +constexpr int INVALID_RSSI_VALUE = -127; +constexpr int MAX_RSSI_VALUE = 200; +constexpr int SIGNAL_INFO = 256; + +/* 2.4g and 5g frequency thresholds */ +constexpr int FREQ_2G_MIN = 2412; +constexpr int FREQ_2G_MAX = 2472; +constexpr int FREQ_5G_MIN = 5170; +constexpr int FREQ_5G_MAX = 5825; +constexpr int CHANNEL_14_FREQ = 2484; +constexpr int CHANNEL_14 = 14; +constexpr int CENTER_FREQ_DIFF = 5; +constexpr int CHANNEL_2G_MIN = 1; +constexpr int CHANNEL_5G_MIN = 34; + +constexpr int MULTI_AP = 0; /* * During the WPS PIN connection, the WPA_SUPPLICANT blocklist is cleared every 10 seconds * until the network connection is successful. */ -static const int BLOCK_LIST_CLEAR_TIMER = 20 * 1000; +constexpr int BLOCK_LIST_CLEAR_TIMER = 20 * 1000; /* Signal levels are classified into: 0 1 2 3 4 ,the max is 4. */ -static const int MAX_LEVEL = 4; +constexpr int MAX_LEVEL = 4; const std::string WPA_BSSID_ANY = "any"; +const std::string IF_NAME = "wlan0"; class StaStateMachine : public StateMachine { FRIEND_GTEST(StaStateMachine); @@ -86,7 +106,7 @@ public: */ class InitState : public State { public: - explicit InitState(StaStateMachine *pStaStateMachine); + explicit InitState(StaStateMachine *staStateMachine); ~InitState() override; void GoInState() override; void GoOutState() override; @@ -101,7 +121,7 @@ public: */ class WpaStartingState : public State { public: - explicit WpaStartingState(StaStateMachine *pStaStateMachine); + explicit WpaStartingState(StaStateMachine *staStateMachine); ~WpaStartingState() override; void InitWpsSettings(); void GoInState() override; @@ -117,7 +137,7 @@ public: */ class WpaStartedState : public State { public: - explicit WpaStartedState(StaStateMachine *pStaStateMachine); + explicit WpaStartedState(StaStateMachine *staStateMachine); ~WpaStartedState() override; void GoInState() override; void GoOutState() override; @@ -132,7 +152,7 @@ public: */ class WpaStoppingState : public State { public: - explicit WpaStoppingState(StaStateMachine *pStaStateMachine); + explicit WpaStoppingState(StaStateMachine *staStateMachine); ~WpaStoppingState() override; void GoInState() override; void GoOutState() override; @@ -147,7 +167,7 @@ public: */ class LinkState : public State { public: - explicit LinkState(StaStateMachine *pStaStateMachine); + explicit LinkState(StaStateMachine *staStateMachine); ~LinkState() override; void GoInState() override; void GoOutState() override; @@ -174,7 +194,7 @@ public: */ class SeparatedState : public State { public: - explicit SeparatedState(StaStateMachine *pStaStateMachine); + explicit SeparatedState(StaStateMachine *staStateMachine); ~SeparatedState() override; void GoInState() override; void GoOutState() override; @@ -189,7 +209,7 @@ public: */ class ApLinkedState : public State { public: - explicit ApLinkedState(StaStateMachine *pStaStateMachine); + explicit ApLinkedState(StaStateMachine *staStateMachine); ~ApLinkedState() override; void GoInState() override; void GoOutState() override; @@ -204,7 +224,7 @@ public: */ class StaWpsState : public State { public: - explicit StaWpsState(StaStateMachine *pStaStateMachine); + explicit StaWpsState(StaStateMachine *staStateMachine); ~StaWpsState() override; void GoInState() override; void GoOutState() override; @@ -219,7 +239,7 @@ public: */ class GetIpState : public State { public: - explicit GetIpState(StaStateMachine *pStaStateMachine); + explicit GetIpState(StaStateMachine *staStateMachine); ~GetIpState() override; void GoInState() override; void GoOutState() override; @@ -234,11 +254,14 @@ public: */ class LinkedState : public State { public: - explicit LinkedState(); + explicit LinkedState(StaStateMachine *staStateMachine); ~LinkedState() override; void GoInState() override; void GoOutState() override; bool ExecuteStateMsg(InternalMessage *msg) override; + + private: + StaStateMachine *pStaStateMachine; }; /** * @Description Definition of member function of ApRoamingState class in StaStateMachine. @@ -246,7 +269,7 @@ public: */ class ApRoamingState : public State { public: - explicit ApRoamingState(StaStateMachine *pStaStateMachine); + explicit ApRoamingState(StaStateMachine *staStateMachine); ~ApRoamingState() override; void GoInState() override; void GoOutState() override; @@ -262,7 +285,7 @@ public: * @Description : Construct a new dhcp result notify object * */ - explicit DhcpResultNotify(StaStateMachine *pStaStateMachine); + explicit DhcpResultNotify(StaStateMachine *staStateMachine); /** * @Description : Destroy the dhcp result notify object @@ -311,6 +334,10 @@ public: * @param bssid - the mac address of network(in) */ void StartRoamToNetwork(std::string bssid); + /** + * @Description if it is roaming now. + */ + bool IsRoaming(void); /** * @Description Connecting events * @@ -318,19 +345,26 @@ public: * @param bssid - bssid - the mac address of wifi(in) */ void OnNetworkConnectionEvent(int networkId, std::string bssid); - /** - * @Description Register sta callback function + * @Description Bssid change events * - * @param callbacks - Callback function pointer storage structure + * @param reason: the reason of bssid changed(in) + * @param bssid: the mac address of wifi(in) */ - void RegisterStaServiceCallback(const StaServiceCallback &callbacks); + void OnBssidChangedEvent(std::string reason, std::string bssid); /** - * @Description Synchronize the linked information + * @Description dhcp result notify events * - * @param scanInfos - the results obtaining by scanning(in) + * @param result: true-success, false-fail(in) */ - void SyncLinkInfo(const std::vector &scanInfos); + void OnDhcpResultNotifyEvent(bool result); + /** + * @Description Register sta callback function + * + * @param callbacks - Callback function pointer storage structure + */ + void RegisterStaServiceCallback(const StaServiceCallback &callbacks); + /** * @Description Convert the deviceConfig structure and set it to wpa_supplicant * @@ -339,6 +373,14 @@ public: */ ErrCode ConvertDeviceCfg(const WifiDeviceConfig &config) const; + /** + * @Description Get linked info. + * + * @param linkedInfo - linked info + * @return int - operation result + */ + int GetLinkedInfo(WifiLinkedInfo& linkedInfo); + private: /** * @Description Destruct state. @@ -405,17 +447,6 @@ private: */ void GetBandFromFreQuencies(const int &freQuency); - /** - * @Description Remove network configuration. - * - * @param msg -Internal message(in) - */ - void RemoveDeviceConfigProcess(const InternalMessage *msg); - /** - * @Description Remove all network configuration. - * - */ - void RemoveAllDeviceConfigProcess(); /** * @Description Processing after a success response is returned after Wi-Fi is enabled successfully, such as setting the MAC address and @@ -423,6 +454,10 @@ private: * */ void StartWifiProcess(); + /** + * @Description Synchronize the deviceConfig structure to wpa_supplicant + */ + void SyncDeviceConfigToWpa() const; /** * @Description Update wifi status and save connection information. * @@ -431,18 +466,26 @@ private: */ void ConnectToNetworkProcess(InternalMessage *msg); + /** + * @Description On connect fail. + * + * @param networkId - the networkId of network which is going to be connected.(in) + */ + void OnConnectFailed(int networkId); + /** * @Description Start to connect to network. * * @param networkId - the networkId of network which is going to be connected.(in) + * @Return success: WIFI_OPT_SUCCESS fail: WIFI_OPT_FAILED */ - void StartConnectToNetwork(int networkId); + ErrCode StartConnectToNetwork(int networkId); /** * @Description Disable network * * @param networkId - the networkId of network which is going to be disabled.(in) */ - void DisableNetwork(int networkId); + ErrCode DisableNetwork(int networkId); /** * @Description Disconnect network * @@ -473,7 +516,7 @@ private: * * @param netState - the state of connecting network(in) */ - void HandleNetCheckResult(StaNetState netState); + void HandleNetCheckResult(StaNetState netState, const std::string portalUrl); /** * @Description Remove all device configurations before enabling WPS. * @@ -484,12 +527,22 @@ private: * */ void SyncAllDeviceConfigs(); - /** * @Description Initialize the connection state processing message map * */ int InitStaSMHandleMap(); + /** + * @Description : Deal SignalPoll Result. + * + * @param msg - Message body received by the state machine[in] + */ + void DealSignalPollResult(InternalMessage *msg); + /** + * @Description : Converting frequencies to channels. + * + */ + void ConvertFreqToChannel(); /** * @Description Connect to selected network. * @@ -544,6 +597,12 @@ private: * @param msg - Message body received by the state machine[in] */ void DealCancelWpsCmd(InternalMessage *msg); + /** + * @Description Reconnect network + * + * @param msg - Message body received by the state machine[in] + */ + void DealReConnectCmd(InternalMessage *msg); /** * @Description Operations after the Reassociate lead is issued * @@ -561,7 +620,7 @@ private: * * @param msg - Message body received by the state machine[in] */ - void DealWpaWrongPskEvent(InternalMessage *msg); + void DealWpaLinkFailEvent(InternalMessage *msg); /** * @Description Wps mode is ON * @@ -573,36 +632,46 @@ private: * */ void ReassociateProcess(); + /** - * @Description Synchronous Encryption Mode Aand Band + * @Description Set a random MAC address. * - * @param mgmt - Encryption Mode[in] + * @param networkId - network id[in] */ - void SynchronousEncryptionModeAandBand(std::string mgmt); + bool SetRandomMac(int networkId); /** - * @Description Set Wep Encryption Mode Index + * @Description Generate a random MAC address. * - * @param config - A Network[in] + * @param strMac - Randomly generated MAC address[out] */ - void WepEncryptionModeIndex(WifiDeviceConfig &config); - - bool SetRandomMac(const int networkId); void MacAddressGenerate(std::string &strMac); - int CheckMacFormat(const std::string &mac); + /** + * @Description Compare the encryption mode of the current network with that of the network in the scanning result. + * + * @param scanInfoKeymgmt - Network encryption mode in the scanning result[in] + * @param deviceKeymgmt - Encryption mode of the current network[in] + */ + bool ComparedKeymgmt(const std::string scanInfoKeymgmt, const std::string deviceKeymgmt); + /** + * @Description : Deal network check cmd. + * + * @param msg - Message body received by the state machine[in] + */ + void DealNetworkCheck(InternalMessage *msg); private: StaSmHandleFuncMap staSmHandleFuncMap; StaServiceCallback staCallback; +#ifndef OHOS_ARCH_LITE + sptr NetSupplierInfo; +#endif - int statusId; int lastNetworkId; int operationalMode; int targetNetworkId; int pinCode; SetupMethod wpsState; - int lastConnectToNetworkTimer; /* Time stamp of the last attempt to connect to - * the network. - */ + int lastSignalLevel; std::string targetRoamBssid; int currentTpType; IsWpsConnected isWpsConnect; @@ -613,7 +682,6 @@ private: WifiLinkedInfo lastLinkedInfo; IDhcpService *pDhcpService; DhcpResultNotify *pDhcpResultNotify; - StaNetWorkSpeed *pNetSpeed; StaNetworkCheck *pNetcheck; RootState *pRootState; diff --git a/wifi/services/wifi_standard/wifi_framework/wifi_toolkit/BUILD.gn b/wifi/services/wifi_standard/wifi_framework/wifi_toolkit/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..201310925178179dbf5c571131bf76f3ed7f8538 --- /dev/null +++ b/wifi/services/wifi_standard/wifi_framework/wifi_toolkit/BUILD.gn @@ -0,0 +1,126 @@ +# Copyright (C) 2022 Huawei Device Co., Ltd. +# 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. + +if (defined(ohos_lite)) { + import("//build/lite/config/component/lite_component.gni") + import("//foundation/communication/wifi/dhcp/dhcp_lite.gni") + import("//foundation/communication/wifi/wifi/wifi_lite.gni") +} else { + import("//build/ohos.gni") + import("//foundation/communication/wifi/dhcp/dhcp.gni") + import("//foundation/communication/wifi/wifi/wifi.gni") +} + +local_base_sources = [ + "$WIFI_ROOT_DIR/frameworks/native/src/wifi_p2p_msg.cpp", + "config/wifi_config_file_spec.cpp", + "config/wifi_settings.cpp", + "log/log_helper.c", + "net_helper/arp_checker.cpp", + "net_helper/base_address.cpp", + "net_helper/dhcpd_interface.cpp", + "net_helper/http_request.cpp", + "net_helper/if_config.cpp", + "net_helper/ip_tools.cpp", + "net_helper/ipv4_address.cpp", + "net_helper/ipv6_address.cpp", + "net_helper/mac_address.cpp", + "net_helper/network_interface.cpp", + "net_helper/raw_socket.cpp", + "utils/wifi_common_event_helper.cpp", + "utils/wifi_encryption_util.cpp", + "utils/wifi_global_func.cpp", +] + +local_base_include_dirs = [ + "$WIFI_ROOT_DIR/services/wifi_standard/wifi_framework/wifi_toolkit/include", + "$WIFI_ROOT_DIR/services/wifi_standard/wifi_framework/wifi_toolkit/log", + "$WIFI_ROOT_DIR/services/wifi_standard/wifi_framework/wifi_toolkit/net_helper", + "$WIFI_ROOT_DIR/services/wifi_standard/wifi_framework/wifi_toolkit/utils", + "$WIFI_ROOT_DIR/services/wifi_standard/wifi_framework/wifi_toolkit/config", + "//commonlibrary/c_utils/base/include", + "//base/hiviewdfx/hilog/interfaces/native/innerkits/include", + "//base/security/huks/interfaces/innerkits/huks_standard/main/include", + "$WIFI_ROOT_DIR/frameworks/native/interfaces", + "$DHCP_ROOT_DIR/interfaces/inner_api/interfaces", + "$DHCP_ROOT_DIR/interfaces/inner_api/include", + "$DHCP_ROOT_DIR/services/mgr_service/include", + "//foundation/communication/ipc/interfaces/innerkits/ipc_core/include", + "$WIFI_ROOT_DIR/services/wifi_standard/include", +] + +if (defined(ohos_lite)) { + shared_library("wifi_toolkit") { + sources = local_base_sources + include_dirs = local_base_include_dirs + + deps = [ + "$DHCP_ROOT_DIR/services/mgr_service:dhcp_manager_service", + "//base/hiviewdfx/hilog_lite/frameworks/featured:hilog_shared", + ] + + defines = [ + "OHOS_ARCH_LITE", + "AP_INSTANCE_MAX_NUM=$wifi_feature_with_ap_num", + ] + + configs -= [ "//build/lite/config:language_cpp" ] + cflags_cc = [ + "-std=c++17", + "-fno-rtti", + ] + ldflags = [ + "-fPIC", + "-Wl,-E", + ] + } +} else { + ohos_shared_library("wifi_toolkit") { + install_enable = true + sources = local_base_sources + + include_dirs = local_base_include_dirs + + deps = [ + "$DHCP_ROOT_DIR/services/mgr_service:dhcp_manager_service", + "//base/hiviewdfx/hilog/interfaces/native/innerkits:libhilog", + ] + + defines = [ "AP_INSTANCE_MAX_NUM=$wifi_feature_with_ap_num" ] + if (wifi_feature_with_encryption) { + defines += [ "FEATURE_ENCRYPTION_SUPPORT" ] + } + + external_deps = [ + "ability_base:want", + "c_utils:utils", + "common_event_service:cesfwk_innerkits", + "eventhandler:libeventhandler", + ] + if (wifi_feature_with_encryption) { + external_deps += [ "huks:libhukssdk" ] + } + cflags_cc = [ + "-std=c++17", + "-fno-rtti", + ] + + ldflags = [ + "-fPIC", + "-Wl,-E", + ] + + part_name = "wifi" + subsystem_name = "communication" + } +} diff --git a/wifi/services/wifi_standard/wifi_framework/wifi_toolkit/config/wifi_config_country_freqs.h b/wifi/services/wifi_standard/wifi_framework/wifi_toolkit/config/wifi_config_country_freqs.h new file mode 100644 index 0000000000000000000000000000000000000000..5af370809b7a0aed66d6a7ca121d17fe61e3ce83 --- /dev/null +++ b/wifi/services/wifi_standard/wifi_framework/wifi_toolkit/config/wifi_config_country_freqs.h @@ -0,0 +1,40 @@ +/* + * Copyright (C) 2022 Huawei Device Co., Ltd. + * 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 OHOS_WIFI_CONFIG_COUNTRY_FREQS_H +#define OHOS_WIFI_CONFIG_COUNTRY_FREQS_H + +#include +#include +#include "wifi_ap_msg.h" + +namespace OHOS { +namespace Wifi { +struct CountryDefaultBandFreqs { + std::string countryCode; + BandType band; + std::vector freqs; +}; + +const std::vector g_countryDefaultFreqs = { + /* CN 2.4G valid frequencies */ + { "CN", BandType::BAND_2GHZ, {2412, 2417, 2422, 2427, 2432, 2437, 2442, 2447, 2452, 2457, 2462, 2467, 2472} }, + /* CN 5G valid frequencies, exclude radar frequencies */ + { "CN", BandType::BAND_5GHZ, {5180, 5200, 5220, 5240, 5745, 5765, 5785, 5805, 5825} }, +}; +} // namespace Wifi +} // namespace OHOS + +#endif // OHOS_WIFI_CONFIG_COUNTRY_FREQS_H \ No newline at end of file diff --git a/services/wifi_standard/wifi_framework/common/config/wifi_config_file_impl.h b/wifi/services/wifi_standard/wifi_framework/wifi_toolkit/config/wifi_config_file_impl.h similarity index 58% rename from services/wifi_standard/wifi_framework/common/config/wifi_config_file_impl.h rename to wifi/services/wifi_standard/wifi_framework/wifi_toolkit/config/wifi_config_file_impl.h index 368d31eab6031237f5ddc21669236058be9c6c30..4ed6ec23aac4d02fffa446cf10f7caaac714064f 100644 --- a/services/wifi_standard/wifi_framework/common/config/wifi_config_file_impl.h +++ b/wifi/services/wifi_standard/wifi_framework/wifi_toolkit/config/wifi_config_file_impl.h @@ -1,5 +1,5 @@ /* - * Copyright (C) 2021 Huawei Device Co., Ltd. + * Copyright (C) 2021-2022 Huawei Device Co., Ltd. * 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 @@ -18,8 +18,10 @@ #include #include #include +#include #include #include "wifi_config_file_spec.h" +#include "wifi_log.h" namespace OHOS { namespace Wifi { @@ -69,6 +71,20 @@ public: */ int SetConfigFilePath(const std::string &fileName); + /** + * @Description read and parses the network section of ini config file, need call SetConfigFilePath first + * + * @return int - 0 Success; >0 parse failed + */ + int ReadNetworkSection(T &item, std::ifstream &fs, std::string &line); + + /** + * @Description read and parses the networks of ini config file, need call SetConfigFilePath first + * + * @return int - 0 Success; >0 parse failed + */ + int ReadNetwork(T &item, std::ifstream &fs, std::string &line); + /** * @Description read and parses the ini config file, need call SetConfigFilePath first * @@ -91,6 +107,13 @@ public: */ int GetValue(std::vector &results); + /** + * @Description Get config values + * + * @return config values + */ + const std::vector& GetValue() const; + /** * @Description Set the config value * @@ -112,32 +135,21 @@ int WifiConfigFileImpl::SetConfigFilePath(const std::string &fileName) } template -int WifiConfigFileImpl::LoadConfig() +int WifiConfigFileImpl::ReadNetworkSection(T &item, std::ifstream &fs, std::string &line) { - std::ifstream fs(mFileName.c_str()); - if (!fs.is_open()) { - return -1; - } - mValues.clear(); - bool bSection = false; - T item; - std::string line; + int sectionError = 0; while (std::getline(fs, line)) { - DelComment(line); TrimString(line); if (line.empty()) { continue; } - if (line[0] == '[' && line[line.length() - 1] == ']') { - if (bSection) { - mValues.push_back(item); - } - bSection = true; - ClearTClass(item); /* template function, needing specialization */ - continue; + if (line[0] == '<' && line[line.length() - 1] == '>') { + return sectionError; } std::string::size_type npos = line.find("="); if (npos == std::string::npos) { + LOGE("Invalid config line"); + sectionError++; continue; } std::string key = line.substr(0, npos); @@ -145,10 +157,66 @@ int WifiConfigFileImpl::LoadConfig() TrimString(key); TrimString(value); /* template function, needing specialization */ - SetTClassKeyValue(item, key, value); + sectionError += SetTClassKeyValue(item, key, value); + } + LOGE("Section config not end correctly"); + sectionError++; + return sectionError; +} + +template +int WifiConfigFileImpl::ReadNetwork(T &item, std::ifstream &fs, std::string &line) +{ + int networkError = 0; + while (std::getline(fs, line)) { + TrimString(line); + if (line.empty()) { + continue; + } + if (line[0] == '<' && line[line.length() - 1] == '>') { + networkError += ReadNetworkSection(item, fs, line); + } else if (line.compare("}") == 0) { + return networkError; + } else { + LOGE("Invalid config line"); + networkError++; + } } - if (bSection) { - mValues.push_back(item); + LOGE("Network config not end correctly"); + networkError++; + return networkError; +} + +template +int WifiConfigFileImpl::LoadConfig() +{ + if (mFileName.empty()) { + LOGE("File name is empty."); + return -1; + } + std::ifstream fs(mFileName.c_str()); + if (!fs.is_open()) { + LOGE("Loading config file: %{public}s, fs.is_open() failed!", mFileName.c_str()); + return -1; + } + mValues.clear(); + T item; + std::string line; + int configError; + while (std::getline(fs, line)) { + TrimString(line); + if (line.empty()) { + continue; + } + if (line[0] == '[' && line[line.length() - 1] == '{') { + ClearTClass(item); /* template function, needing specialization */ + configError = ReadNetwork(item, fs, line); + if (configError > 0) { + LOGE("Parse network failed."); + continue; + } + mValues.push_back(item); + } } fs.close(); return 0; @@ -157,8 +225,13 @@ int WifiConfigFileImpl::LoadConfig() template int WifiConfigFileImpl::SaveConfig() { - std::ofstream fs(mFileName.c_str()); - if (!fs.is_open()) { + if (mFileName.empty()) { + LOGE("File name is empty."); + return -1; + } + FILE* fp = fopen(mFileName.c_str(), "w"); + if (!fp) { + LOGE("Save config file: %{public}s, fopen() failed!", mFileName.c_str()); return -1; } std::ostringstream ss; @@ -168,12 +241,18 @@ int WifiConfigFileImpl::SaveConfig() * here use template function GetTClassName OutTClassString, needing * specialization. */ - ss << "[" << GetTClassName() << "_" << (i + 1) << "]" << std::endl; + ss << "[" << GetTClassName() << "_" << (i + 1) << "] {" << std::endl; ss << OutTClassString(item) << std::endl; + ss << "}" << std::endl; } std::string content = ss.str(); - fs.write(content.c_str(), content.length()); - fs.close(); + int ret = fwrite(content.c_str(), 1, content.length(), fp); + if (ret != (int)content.length()) { + LOGE("Save config file: %{public}s, fwrite() failed!", mFileName.c_str()); + } + (void)fflush(fp); + (void)fsync(fileno(fp)); + (void)fclose(fp); mValues.clear(); /* clear values */ return 0; } @@ -188,7 +267,13 @@ int WifiConfigFileImpl::GetValue(std::vector &results) return 0; } -template +template +const std::vector& WifiConfigFileImpl::GetValue() const +{ + return mValues; +} + +template int WifiConfigFileImpl::SetValue(const std::vector &results) { mValues = results; diff --git a/services/wifi_standard/wifi_framework/common/config/wifi_config_file_spec.cpp b/wifi/services/wifi_standard/wifi_framework/wifi_toolkit/config/wifi_config_file_spec.cpp similarity index 43% rename from services/wifi_standard/wifi_framework/common/config/wifi_config_file_spec.cpp rename to wifi/services/wifi_standard/wifi_framework/wifi_toolkit/config/wifi_config_file_spec.cpp index 64a95bcb04bc203b67afee64454b49d1e39bad7d..77a5178daca5125d0f6a53058947e17ca14ee6d9 100644 --- a/services/wifi_standard/wifi_framework/common/config/wifi_config_file_spec.cpp +++ b/wifi/services/wifi_standard/wifi_framework/wifi_toolkit/config/wifi_config_file_spec.cpp @@ -14,7 +14,10 @@ */ #include "wifi_config_file_spec.h" - +#include "wifi_global_func.h" +#ifdef FEATURE_ENCRYPTION_SUPPORT +#include "wifi_encryption_util.h" +#endif namespace OHOS { namespace Wifi { static void ClearWifiDeviceConfig(WifiDeviceConfig &item) @@ -37,6 +40,9 @@ static void ClearWifiDeviceConfig(WifiDeviceConfig &item) item.wepTxKeyIndex = 0; item.priority = 0; item.hiddenSSID = false; + item.lastConnectTime = -1; + item.numRebootsSinceLastUse = 0; + item.numAssociation = 0; return; } @@ -67,6 +73,9 @@ static void ClearWifiDeviceConfigEap(WifiDeviceConfig &item) item.wifiEapConfig.eap.clear(); item.wifiEapConfig.identity.clear(); item.wifiEapConfig.password.clear(); + item.wifiEapConfig.clientCert.clear(); + item.wifiEapConfig.privateKey.clear(); + item.wifiEapConfig.phase2Method = Phase2Method::NONE; return; } @@ -97,8 +106,27 @@ void ClearTClass(WifiDeviceConfig &item) return; } +static int SetWifiDeviceConfigOutDated(WifiDeviceConfig &item, const std::string &key, const std::string &value) +{ + if (key == "band") { + item.band = std::stoi(value); + } else if (key == "channel") { + item.channel = std::stoi(value); + } else if (key == "level") { + item.level = std::stoi(value); + } else if (key == "isEphemeral") { + item.isEphemeral = std::stoi(value); + } else { + return -1; + } + return 0; +} + static int SetWifiDeviceConfigFirst(WifiDeviceConfig &item, const std::string &key, const std::string &value) { + if (SetWifiDeviceConfigOutDated(item, key, value) == 0) { + return 0; + } if (key == "networkId") { item.networkId = std::stoi(value); } else if (key == "status") { @@ -107,18 +135,19 @@ static int SetWifiDeviceConfigFirst(WifiDeviceConfig &item, const std::string &k item.bssid = value; } else if (key == "ssid") { item.ssid = value; - } else if (key == "band") { - item.band = std::stoi(value); - } else if (key == "channel") { - item.channel = std::stoi(value); + } else if (key == "HexSsid") { + std::vector vec; + vec.clear(); + if (HexStringToVec(value, vec) == 0) { + std::string strSsid(vec.begin(), vec.end()); + item.ssid = strSsid; + } else { + return -1; + } } else if (key == "frequency") { item.frequency = std::stoi(value); - } else if (key == "level") { - item.level = std::stoi(value); } else if (key == "isPasspoint") { item.isPasspoint = std::stoi(value); - } else if (key == "isEphemeral") { - item.isEphemeral = std::stoi(value); } else if (key == "preSharedKey") { item.preSharedKey = value; } else if (key == "keyMgmt") { @@ -127,17 +156,79 @@ static int SetWifiDeviceConfigFirst(WifiDeviceConfig &item, const std::string &k item.wepTxKeyIndex = std::stoi(value); } else if (key == "priority") { item.priority = std::stoi(value); + } else if (key == "uid") { + item.uid = std::stoi(value); + } else if (key == "lastConnectTime") { + item.lastConnectTime = std::stol(value); + } else if (key == "numRebootsSinceLastUse") { + item.numRebootsSinceLastUse = std::stoi(value); + } else if (key == "numAssociation") { + item.numAssociation = std::stoi(value); } else { return -1; } return 0; } -static void SetWifiDeviceConfig(WifiDeviceConfig &item, const std::string &key, const std::string &value) +#ifdef FEATURE_ENCRYPTION_SUPPORT +static int SetWifiDeviceConfigEncrypt(WifiDeviceConfig &item, const std::string &key, const std::string &value) { + int errorKeyValue = 0; + WifiEncryptionInfo mWifiEncryptionInfo; + mWifiEncryptionInfo.SetFile(GetTClassName()); + if (key == "encryptedData") { + item.preSharedKey = value; + } else if (key == "IV") { + WifiEncryptionInfo mWifiEncryptionInfo; + mWifiEncryptionInfo.SetFile(GetTClassName()); + EncryptedData *encry = new EncryptedData(item.preSharedKey, value); + std::string decry = ""; + if (WifiDecryption(mWifiEncryptionInfo, *encry, decry) == HKS_SUCCESS) { + item.preSharedKey = decry; + } else { + item.preSharedKey = ""; + errorKeyValue++; + } + delete encry; + } else if (key.compare(0, strlen("encryWepKeys"), "encryWepKeys") == 0) { + int pos = std::stoi(key.substr(strlen("encryWepKeys") + 1)); + if (pos >= 0 && pos < WEPKEYS_SIZE) { + item.wepKeys[pos] = value; + } + } else if (key == "IVWep") { + if (item.wepTxKeyIndex < 0 || item.wepTxKeyIndex >= WEPKEYS_SIZE) { + item.wepTxKeyIndex = 0; + } + EncryptedData *encryWep = new EncryptedData(item.wepKeys[item.wepTxKeyIndex], value); + std::string decryWep = ""; + if (WifiDecryption(mWifiEncryptionInfo, *encryWep, decryWep) == HKS_SUCCESS) { + item.wepKeys[item.wepTxKeyIndex] = decryWep; + } else { + item.wepKeys[item.wepTxKeyIndex] = ""; + errorKeyValue++; + } + delete encryWep; + } else { + return -1; + } + return errorKeyValue; +} +#endif + +static int SetWifiDeviceConfig(WifiDeviceConfig &item, const std::string &key, const std::string &value) +{ + int errorKeyValue = 0; if (SetWifiDeviceConfigFirst(item, key, value) == 0) { - return; + return errorKeyValue; } +#ifdef FEATURE_ENCRYPTION_SUPPORT + errorKeyValue = SetWifiDeviceConfigEncrypt(item, key, value); + if (errorKeyValue != -1) { + return errorKeyValue; + } else { + errorKeyValue = 0; + } +#endif if (key == "hiddenSSID") { item.hiddenSSID = std::stoi(value); } else if (key.compare(0, strlen("wepKeys"), "wepKeys") == 0) { @@ -145,12 +236,16 @@ static void SetWifiDeviceConfig(WifiDeviceConfig &item, const std::string &key, if (pos >= 0 && pos < WEPKEYS_SIZE) { item.wepKeys[pos] = value; } + } else { + LOGE("Invalid config key value"); + errorKeyValue++; } - return; + return errorKeyValue; } -static void SetWifiDeviceConfigIp(WifiDeviceConfig &item, const std::string &key, const std::string &value) +static int SetWifiDeviceConfigIp(WifiDeviceConfig &item, const std::string &key, const std::string &value) { + int errorKeyValue = 0; if (key == "wifiIpConfig.assignMethod") { item.wifiIpConfig.assignMethod = AssignIpMethod(std::stoi(value)); } else if (key == "wifiIpConfig.staticIpAddress.ipAddress.address.family") { @@ -185,24 +280,72 @@ static void SetWifiDeviceConfigIp(WifiDeviceConfig &item, const std::string &key item.wifiIpConfig.staticIpAddress.dnsServer2.SetIpv6Address(value); } else if (key == "wifiIpConfig.staticIpAddress.domains") { item.wifiIpConfig.staticIpAddress.domains = value; + } else { + LOGE("Invalid config key value"); + errorKeyValue++; } - return; + return errorKeyValue; +} + + +#ifdef FEATURE_ENCRYPTION_SUPPORT +static int SetWifiDeviceConfigEncryptEap(WifiDeviceConfig &item, const std::string &key, const std::string &value) +{ + int errorKeyValue = 0; + WifiEncryptionInfo mWifiEncryptionInfo; + mWifiEncryptionInfo.SetFile(GetTClassName()); + if (key == "wifiEapConfig.encryptedData") { + item.wifiEapConfig.password = value; + } else if (key == "wifiEapConfig.IV") { + EncryptedData *encry = new EncryptedData(item.wifiEapConfig.password, value); + std::string decry = ""; + if (WifiDecryption(mWifiEncryptionInfo, *encry, decry) == HKS_SUCCESS) { + item.wifiEapConfig.password = decry; + } else { + item.wifiEapConfig.password = ""; + errorKeyValue ++; + } + delete encry; + } else { + return -1; + } + return errorKeyValue; } +#endif -static void SetWifiDeviceConfigEap(WifiDeviceConfig &item, const std::string &key, const std::string &value) +static int SetWifiDeviceConfigEap(WifiDeviceConfig &item, const std::string &key, const std::string &value) { + int errorKeyValue = 0; +#ifdef FEATURE_ENCRYPTION_SUPPORT + errorKeyValue = SetWifiDeviceConfigEncryptEap(item, key, value); + if (errorKeyValue != -1) { + return errorKeyValue; + } else { + errorKeyValue = 0; + } +#endif if (key == "wifiEapConfig.eap") { item.wifiEapConfig.eap = value; } else if (key == "wifiEapConfig.identity") { item.wifiEapConfig.identity = value; } else if (key == "wifiEapConfig.password") { item.wifiEapConfig.password = value; + } else if (key == "wifiEapConfig.clientCert") { + item.wifiEapConfig.clientCert = value; + } else if (key == "wifiEapConfig.privateKey") { + item.wifiEapConfig.privateKey = value; + } else if (key == "wifiEapConfig.phase2method") { + item.wifiEapConfig.phase2Method = Phase2Method(std::stoi(value)); + } else { + LOGE("Invalid config key value"); + errorKeyValue++; } - return; + return errorKeyValue; } -static void SetWifiDeviceConfigProxy(WifiDeviceConfig &item, const std::string &key, const std::string &value) +static int SetWifiDeviceConfigProxy(WifiDeviceConfig &item, const std::string &key, const std::string &value) { + int errorKeyValue = 0; if (key == "wifiProxyconfig.configureMethod") { item.wifiProxyconfig.configureMethod = ConfigureProxyMethod(std::stoi(value)); } else if (key == "wifiProxyconfig.autoProxyConfig.pacWebAddress") { @@ -213,32 +356,41 @@ static void SetWifiDeviceConfigProxy(WifiDeviceConfig &item, const std::string & item.wifiProxyconfig.manualProxyConfig.serverPort = std::stoi(value); } else if (key == "wifiProxyconfig.ManualProxyConfig.exclusionObjectList") { item.wifiProxyconfig.manualProxyConfig.exclusionObjectList = value; + } else { + LOGE("Invalid config key value"); + errorKeyValue++; } - return; + return errorKeyValue; } -static void SetWifiDeviceconfigPrivacy(WifiDeviceConfig &item, const std::string &key, const std::string &value) +static int SetWifiDeviceconfigPrivacy(WifiDeviceConfig &item, const std::string &key, const std::string &value) { + int errorKeyValue = 0; if (key == "wifiPrivacySetting") { item.wifiPrivacySetting = WifiPrivacyConfig(std::stoi(value)); + } else { + LOGE("Invalid config key value"); + errorKeyValue++; } + return errorKeyValue; } template<> -void SetTClassKeyValue(WifiDeviceConfig &item, const std::string &key, const std::string &value) +int SetTClassKeyValue(WifiDeviceConfig &item, const std::string &key, const std::string &value) { + int errorKeyValue = 0; if (key.compare(0, strlen("wifiIpConfig"), "wifiIpConfig") == 0) { - SetWifiDeviceConfigIp(item, key, value); + errorKeyValue += SetWifiDeviceConfigIp(item, key, value); } else if (key.compare(0, strlen("wifiEapConfig"), "wifiEapConfig") == 0) { - SetWifiDeviceConfigEap(item, key, value); + errorKeyValue += SetWifiDeviceConfigEap(item, key, value); } else if (key.compare(0, strlen("wifiProxyconfig"), "wifiProxyconfig") == 0) { - SetWifiDeviceConfigProxy(item, key, value); + errorKeyValue += SetWifiDeviceConfigProxy(item, key, value); } else if (key.compare(0, strlen("wifiPrivacySetting"), "wifiPrivacySetting") == 0) { - SetWifiDeviceconfigPrivacy(item, key, value); + errorKeyValue += SetWifiDeviceconfigPrivacy(item, key, value); } else { - SetWifiDeviceConfig(item, key, value); + errorKeyValue += SetWifiDeviceConfig(item, key, value); } - return; + return errorKeyValue; } template<> @@ -247,95 +399,161 @@ std::string GetTClassName() return "WifiDeviceConfig"; } +#ifdef FEATURE_ENCRYPTION_SUPPORT +static std::string OutPutEncryptionDeviceConfig(WifiDeviceConfig &item) +{ + std::ostringstream ss; + WifiEncryptionInfo mWifiEncryptionInfo; + mWifiEncryptionInfo.SetFile(GetTClassName()); + EncryptedData encry; + if (WifiEncryption(mWifiEncryptionInfo, item.preSharedKey, encry) == HKS_SUCCESS) { + ss << " " <<"encryptedData=" << encry.encryptedPassword << std::endl; + ss << " " <<"IV=" << encry.IV << std::endl; + } else { + ss << " " <<"preSharedKey=" << item.preSharedKey << std::endl; + } + ss << " " <<"wepTxKeyIndex=" << item.wepTxKeyIndex << std::endl; + if (item.wepTxKeyIndex < 0 || item.wepTxKeyIndex >= WEPKEYS_SIZE) { + item.wepTxKeyIndex = 0; + } + EncryptedData encryWep; + if (WifiEncryption(mWifiEncryptionInfo, item.wepKeys[item.wepTxKeyIndex], encryWep) == HKS_SUCCESS) { + item.wepKeys[item.wepTxKeyIndex] = encryWep.encryptedPassword; + for (int i = 0; i < WEPKEYS_SIZE; ++i) { + ss << " " <<"encryWepKeys_" << i << "=" << item.wepKeys[i] << std::endl; + } + ss << " " <<"IVWep=" << encryWep.IV << std::endl; + } else { + for (int i = 0; i < WEPKEYS_SIZE; ++i) { + ss << " " <<"wepKeys_" << i << "=" << item.wepKeys[i] << std::endl; + } + } + return ss.str(); +} +#endif + static std::string OutPutWifiDeviceConfig(WifiDeviceConfig &item) { std::ostringstream ss; - ss << "status=" << item.status << std::endl; - ss << "bssid=" << item.bssid << std::endl; - ss << "ssid=" << item.ssid << std::endl; - ss << "band=" << item.band << std::endl; - ss << "channel=" << item.channel << std::endl; - ss << "frequency=" << item.frequency << std::endl; - ss << "level=" << item.level << std::endl; - ss << "isPasspoint=" << item.isPasspoint << std::endl; - ss << "isEphemeral=" << item.isEphemeral << std::endl; - ss << "preSharedKey=" << item.preSharedKey << std::endl; - ss << "keyMgmt=" << item.keyMgmt << std::endl; - ss << "wepTxKeyIndex=" << item.wepTxKeyIndex << std::endl; - ss << "priority=" << item.priority << std::endl; - ss << "hiddenSSID=" << (int)item.hiddenSSID << std::endl; + ss << " " <<"" << std::endl; + ss << " " <<"uid=" << item.uid << std::endl; + ss << " " <<"status=" << item.status << std::endl; + ss << " " <<"bssid=" << item.bssid << std::endl; + ss << " " <<"ssid=" << ValidateString(item.ssid) << std::endl; + ss << " " <<"HexSsid=" << ConvertArrayToHex((uint8_t*)&item.ssid[0], item.ssid.length()) << std::endl; + ss << " " <<"frequency=" << item.frequency << std::endl; + ss << " " <<"isPasspoint=" << item.isPasspoint << std::endl; + ss << " " <<"priority=" << item.priority << std::endl; + ss << " " <<"hiddenSSID=" << (int)item.hiddenSSID << std::endl; + ss << " " <<"keyMgmt=" << item.keyMgmt << std::endl; + ss << " " <<"lastConnectTime=" << item.lastConnectTime << std::endl; + ss << " " <<"numRebootsSinceLastUse=" << item.numRebootsSinceLastUse << std::endl; + ss << " " <<"numAssociation=" << item.numAssociation << std::endl; +#ifdef FEATURE_ENCRYPTION_SUPPORT + ss <" << std::endl; return ss.str(); } static std::string OutPutWifiDeviceConfigIp(WifiDeviceConfig &item) { std::ostringstream ss; - ss << "wifiIpConfig.assignMethod=" << (int)item.wifiIpConfig.assignMethod << std::endl; - ss << "wifiIpConfig.staticIpAddress.ipAddress.address.family=" + ss << " " <<"" << std::endl; + ss << " " <<"wifiIpConfig.assignMethod=" << (int)item.wifiIpConfig.assignMethod << std::endl; + ss << " " <<"wifiIpConfig.staticIpAddress.ipAddress.address.family=" << item.wifiIpConfig.staticIpAddress.ipAddress.address.family << std::endl; - ss << "wifiIpConfig.staticIpAddress.ipAddress.address.addressIpv4=" + ss << " " <<"wifiIpConfig.staticIpAddress.ipAddress.address.addressIpv4=" << item.wifiIpConfig.staticIpAddress.ipAddress.address.GetIpv4Address() << std::endl; - ss << "wifiIpConfig.staticIpAddress.ipAddress.address.addressIpv6=" + ss << " " <<"wifiIpConfig.staticIpAddress.ipAddress.address.addressIpv6=" << item.wifiIpConfig.staticIpAddress.ipAddress.address.GetIpv6Address() << std::endl; - ss << "wifiIpConfig.staticIpAddress.ipAddress.prefixLength=" + ss << " " <<"wifiIpConfig.staticIpAddress.ipAddress.prefixLength=" << item.wifiIpConfig.staticIpAddress.ipAddress.prefixLength << std::endl; - ss << "wifiIpConfig.staticIpAddress.ipAddress.flags=" << item.wifiIpConfig.staticIpAddress.ipAddress.flags + ss << " " <<"wifiIpConfig.staticIpAddress.ipAddress.flags=" << item.wifiIpConfig.staticIpAddress.ipAddress.flags << std::endl; - ss << "wifiIpConfig.staticIpAddress.ipAddress.scope=" << item.wifiIpConfig.staticIpAddress.ipAddress.scope + ss << " " <<"wifiIpConfig.staticIpAddress.ipAddress.scope=" << item.wifiIpConfig.staticIpAddress.ipAddress.scope << std::endl; - ss << "wifiIpConfig.staticIpAddress.gateway.family=" << item.wifiIpConfig.staticIpAddress.gateway.family + ss << " " <<"wifiIpConfig.staticIpAddress.gateway.family=" << item.wifiIpConfig.staticIpAddress.gateway.family << std::endl; - ss << "wifiIpConfig.staticIpAddress.gateway.addressIpv4=" + ss << " " <<"wifiIpConfig.staticIpAddress.gateway.addressIpv4=" << item.wifiIpConfig.staticIpAddress.gateway.GetIpv4Address() << std::endl; - ss << "wifiIpConfig.staticIpAddress.gateway.addressIpv6=" + ss << " " <<"wifiIpConfig.staticIpAddress.gateway.addressIpv6=" << item.wifiIpConfig.staticIpAddress.gateway.GetIpv6Address() << std::endl; - ss << "wifiIpConfig.staticIpAddress.dnsServer1.family=" << item.wifiIpConfig.staticIpAddress.dnsServer1.family - << std::endl; - ss << "wifiIpConfig.staticIpAddress.dnsServer1.addressIpv4=" + ss << " " <<"wifiIpConfig.staticIpAddress.dnsServer1.family=" + << item.wifiIpConfig.staticIpAddress.dnsServer1.family << std::endl; + ss << " " <<"wifiIpConfig.staticIpAddress.dnsServer1.addressIpv4=" << item.wifiIpConfig.staticIpAddress.dnsServer1.GetIpv4Address() << std::endl; - ss << "wifiIpConfig.staticIpAddress.dnsServer1.addressIpv6=" + ss << " " <<"wifiIpConfig.staticIpAddress.dnsServer1.addressIpv6=" << item.wifiIpConfig.staticIpAddress.dnsServer1.GetIpv6Address() << std::endl; - ss << "wifiIpConfig.staticIpAddress.dnsServer2.family=" << item.wifiIpConfig.staticIpAddress.dnsServer2.family - << std::endl; - ss << "wifiIpConfig.staticIpAddress.dnsServer2.addressIpv4=" + ss << " " <<"wifiIpConfig.staticIpAddress.dnsServer2.family=" + << item.wifiIpConfig.staticIpAddress.dnsServer2.family << std::endl; + ss << " " <<"wifiIpConfig.staticIpAddress.dnsServer2.addressIpv4=" << item.wifiIpConfig.staticIpAddress.dnsServer2.GetIpv4Address() << std::endl; - ss << "wifiIpConfig.staticIpAddress.dnsServer2.addressIpv6=" + ss << " " <<"wifiIpConfig.staticIpAddress.dnsServer2.addressIpv6=" << item.wifiIpConfig.staticIpAddress.dnsServer2.GetIpv6Address() << std::endl; - ss << "wifiIpConfig.staticIpAddress.domains=" << item.wifiIpConfig.staticIpAddress.domains << std::endl; + ss << " " <<"wifiIpConfig.staticIpAddress.domains=" << item.wifiIpConfig.staticIpAddress.domains << std::endl; + ss << " " <<"" << std::endl; return ss.str(); } static std::string OutPutWifiDeviceConfigEap(WifiDeviceConfig &item) { std::ostringstream ss; - ss << "wifiEapConfig.eap=" << item.wifiEapConfig.eap << std::endl; - ss << "wifiEapConfig.identity=" << item.wifiEapConfig.identity << std::endl; - ss << "wifiEapConfig.password=" << item.wifiEapConfig.password << std::endl; + if (item.wifiEapConfig.eap.length() == 0) { + return ss.str(); + } + ss << " " <<"" << std::endl; + ss << " " <<"wifiEapConfig.eap=" << item.wifiEapConfig.eap << std::endl; + ss << " " <<"wifiEapConfig.identity=" << item.wifiEapConfig.identity << std::endl; +#ifdef FEATURE_ENCRYPTION_SUPPORT + WifiEncryptionInfo mWifiEncryptionInfo; + mWifiEncryptionInfo.SetFile(GetTClassName()); + EncryptedData encry; + if (WifiEncryption(mWifiEncryptionInfo, item.wifiEapConfig.password, encry) == HKS_SUCCESS) { + ss << " " <<"wifiEapConfig.encryptedData=" << encry.encryptedPassword << std::endl; + ss << " " <<"wifiEapConfig.IV=" << encry.IV << std::endl; + } else { + ss << " " <<"wifiEapConfig.password=" << item.wifiEapConfig.password << std::endl; + } +#else + ss << " " <<"wifiEapConfig.password=" << item.wifiEapConfig.password << std::endl; +#endif + ss << " " <<"wifiEapConfig.clientCert=" << item.wifiEapConfig.clientCert << std::endl; + ss << " " <<"wifiEapConfig.privateKey=" << item.wifiEapConfig.privateKey << std::endl; + ss << " " <<"wifiEapConfig.phase2method=" << static_cast(item.wifiEapConfig.phase2Method) << std::endl; + ss << " " <<"" << std::endl; return ss.str(); } static std::string OutPutWifiDeviceConfigProxy(WifiDeviceConfig &item) { std::ostringstream ss; - ss << "wifiProxyconfig.configureMethod=" << (int)item.wifiProxyconfig.configureMethod << std::endl; - ss << "wifiProxyconfig.autoProxyConfig.pacWebAddress=" << item.wifiProxyconfig.autoProxyConfig.pacWebAddress - << std::endl; - ss << "wifiProxyconfig.ManualProxyConfig.serverHostName=" << item.wifiProxyconfig.manualProxyConfig.serverHostName - << std::endl; - ss << "wifiProxyconfig.ManualProxyConfig.serverPort=" << item.wifiProxyconfig.manualProxyConfig.serverPort - << std::endl; - ss << "wifiProxyconfig.ManualProxyConfig.exclusionObjectList=" + ss << " " <<"" << std::endl; + ss << " " <<"wifiProxyconfig.configureMethod=" << (int)item.wifiProxyconfig.configureMethod << std::endl; + ss << " " <<"wifiProxyconfig.autoProxyConfig.pacWebAddress=" + << item.wifiProxyconfig.autoProxyConfig.pacWebAddress << std::endl; + ss << " " <<"wifiProxyconfig.ManualProxyConfig.serverHostName=" + << item.wifiProxyconfig.manualProxyConfig.serverHostName << std::endl; + ss << " " <<"wifiProxyconfig.ManualProxyConfig.serverPort=" + << item.wifiProxyconfig.manualProxyConfig.serverPort << std::endl; + ss << " " <<"wifiProxyconfig.ManualProxyConfig.exclusionObjectList=" << item.wifiProxyconfig.manualProxyConfig.exclusionObjectList << std::endl; + ss << " " <<"" << std::endl; return ss.str(); } static std::string OutPutWifiDeviceConfigPrivacy(WifiDeviceConfig &item) { std::ostringstream ss; - ss << "wifiPrivacySetting=" << (int)item.wifiPrivacySetting << std::endl; + ss << " " <<"" << std::endl; + ss << " " <<"wifiPrivacySetting=" << (int)item.wifiPrivacySetting << std::endl; + ss << " " <<"" << std::endl; return ss.str(); } @@ -343,8 +561,9 @@ template<> std::string OutTClassString(WifiDeviceConfig &item) { std::ostringstream ss; - ss << OutPutWifiDeviceConfig(item) << OutPutWifiDeviceConfigIp(item) << OutPutWifiDeviceConfigEap(item) - << OutPutWifiDeviceConfigProxy(item) << OutPutWifiDeviceConfigPrivacy(item); + ss << OutPutWifiDeviceConfig(item) << OutPutWifiDeviceConfigIp(item) + << OutPutWifiDeviceConfigEap(item) << OutPutWifiDeviceConfigProxy(item) + << OutPutWifiDeviceConfigPrivacy(item); return ss.str(); } @@ -360,11 +579,54 @@ void ClearTClass(HotspotConfig &item) return; } +#ifdef FEATURE_ENCRYPTION_SUPPORT +static int SetWifiHotspotConfigEncrypt(HotspotConfig &item, const std::string &key, const std::string &value) +{ + int errorKeyValue = 0; + WifiEncryptionInfo mWifiEncryptionInfo; + mWifiEncryptionInfo.SetFile(GetTClassName()); + if (key == "encryptedData") { + item.SetPreSharedKey(value); + } else if (key == "IV") { + EncryptedData *encry = new EncryptedData(item.GetPreSharedKey(), value); + std::string decry = ""; + if (WifiDecryption(mWifiEncryptionInfo, *encry, decry) == HKS_SUCCESS) { + item.SetPreSharedKey(decry); + } else { + item.SetPreSharedKey(""); + errorKeyValue++; + } + delete encry; + } else { + return -1; + } + return errorKeyValue; +} +#endif + template<> -void SetTClassKeyValue(HotspotConfig &item, const std::string &key, const std::string &value) +int SetTClassKeyValue(HotspotConfig &item, const std::string &key, const std::string &value) { + int errorKeyValue = 0; +#ifdef FEATURE_ENCRYPTION_SUPPORT + errorKeyValue = SetWifiHotspotConfigEncrypt(item, key, value); + if (errorKeyValue != -1) { + return errorKeyValue; + } else { + errorKeyValue = 0; + } +#endif if (key == "ssid") { item.SetSsid(value); + } else if (key == "HexSsid") { + std::vector vec; + vec.clear(); + if (HexStringToVec(value, vec) == 0) { + std::string strSsid(vec.begin(), vec.end()); + item.SetSsid(strSsid); + } else { + return -1; + } } else if (key == "preSharedKey") { item.SetPreSharedKey(value); } else if (key == "securityType") { @@ -375,8 +637,11 @@ void SetTClassKeyValue(HotspotConfig &item, const std::string &ke item.SetChannel(std::stoi(value)); } else if (key == "maxConn") { item.SetMaxConn(std::stoi(value)); + } else { + LOGE("Invalid config key value"); + errorKeyValue++; } - return; + return errorKeyValue; } template<> @@ -389,12 +654,27 @@ template<> std::string OutTClassString(HotspotConfig &item) { std::ostringstream ss; - ss << "ssid=" << item.GetSsid() << std::endl; - ss << "preSharedKey=" << item.GetPreSharedKey() << std::endl; - ss << "securityType=" << static_cast(item.GetSecurityType()) << std::endl; - ss << "band=" << static_cast(item.GetBand()) << std::endl; - ss << "channel=" << item.GetChannel() << std::endl; - ss << "maxConn=" << item.GetMaxConn() << std::endl; + ss << " " <<"" << std::endl; + ss << " " <<"ssid=" << ValidateString(item.GetSsid()) << std::endl; + ss << " " <<"HexSsid=" << ConvertArrayToHex((uint8_t*)&item.GetSsid()[0], item.GetSsid().length()) << std::endl; +#ifdef FEATURE_ENCRYPTION_SUPPORT + WifiEncryptionInfo mWifiEncryptionInfo; + mWifiEncryptionInfo.SetFile(GetTClassName()); + EncryptedData encry; + if (WifiEncryption(mWifiEncryptionInfo, item.GetPreSharedKey(), encry) == HKS_SUCCESS) { + ss << " " <<"encryptedData=" << encry.encryptedPassword << std::endl; + ss << " " <<"IV=" << encry.IV << std::endl; + } else { + ss << " " <<"preSharedKey=" << item.GetPreSharedKey() << std::endl; + } +#else + ss << " " <<"preSharedKey=" << item.GetPreSharedKey() << std::endl; +#endif + ss << " " <<"securityType=" << static_cast(item.GetSecurityType()) << std::endl; + ss << " " <<"band=" << static_cast(item.GetBand()) << std::endl; + ss << " " <<"channel=" << item.GetChannel() << std::endl; + ss << " " <<"maxConn=" << item.GetMaxConn() << std::endl; + ss << " " <<"" << std::endl; return ss.str(); } @@ -410,8 +690,9 @@ void ClearTClass(P2pVendorConfig &item) } template<> -void SetTClassKeyValue(P2pVendorConfig &item, const std::string &key, const std::string &value) +int SetTClassKeyValue(P2pVendorConfig &item, const std::string &key, const std::string &value) { + int errorKeyValue = 0; if (key == "randomMacSupport") { item.SetRandomMacSupport(std::stoi(value) != 0); } else if (key == "autoListen") { @@ -422,8 +703,11 @@ void SetTClassKeyValue(P2pVendorConfig &item, const std::string item.SetPrimaryDeviceType(value); } else if (key == "secondaryDeviceType") { item.SetSecondaryDeviceType(value); + } else { + LOGE("Invalid config key value"); + errorKeyValue++; } - return; + return errorKeyValue; } template<> @@ -436,11 +720,13 @@ template<> std::string OutTClassString(P2pVendorConfig &item) { std::ostringstream ss; - ss << "randomMacSupport=" << item.GetRandomMacSupport() << std::endl; - ss << "autoListen=" << item.GetIsAutoListen() << std::endl; - ss << "deviceName=" << item.GetDeviceName() << std::endl; - ss << "primaryDeviceType=" << item.GetPrimaryDeviceType() << std::endl; - ss << "secondaryDeviceType=" << item.GetSecondaryDeviceType() << std::endl; + ss << " " <<"" << std::endl; + ss << " " <<"randomMacSupport=" << item.GetRandomMacSupport() << std::endl; + ss << " " <<"autoListen=" << item.GetIsAutoListen() << std::endl; + ss << " " <<"deviceName=" << item.GetDeviceName() << std::endl; + ss << " " <<"primaryDeviceType=" << item.GetPrimaryDeviceType() << std::endl; + ss << " " <<"secondaryDeviceType=" << item.GetSecondaryDeviceType() << std::endl; + ss << " " <<"" << std::endl; return ss.str(); } @@ -454,16 +740,20 @@ void ClearTClass(StationInfo &item) } template<> -void SetTClassKeyValue(StationInfo &item, const std::string &key, const std::string &value) +int SetTClassKeyValue(StationInfo &item, const std::string &key, const std::string &value) { + int errorKeyValue = 0; if (key == "deviceName") { item.deviceName = value; } else if (key == "bssid") { item.bssid = value; } else if (key == "ipAddr") { item.ipAddr = value; + } else { + LOGE("Invalid config key value"); + errorKeyValue++; } - return; + return errorKeyValue; } template<> @@ -476,9 +766,11 @@ template<> std::string OutTClassString(StationInfo &item) { std::ostringstream ss; - ss << "deviceName=" << item.deviceName << std::endl; - ss << "bssid=" << item.bssid << std::endl; - ss << "ipAddr=" << item.ipAddr << std::endl; + ss << " " <<"" << std::endl; + ss << " " <<"deviceName=" << item.deviceName << std::endl; + ss << " " <<"bssid=" << item.bssid << std::endl; + ss << " " <<"ipAddr=" << item.ipAddr << std::endl; + ss << " " <<"" << std::endl; return ss.str(); } @@ -497,6 +789,7 @@ void ClearTClass(WifiConfig &item) item.scoretacticsFrequency5GHzScore = FREQUENCY_5_GHZ_SCORE; item.scoretacticsLastSelectionScore = LAST_SELECTION_SCORE; item.scoretacticsSecurityScore = SECURITY_SCORE; + item.scoretacticsNormalScore = NORMAL_SCORE; item.whetherToAllowNetworkSwitchover = true; item.dhcpIpType = static_cast(DhcpIpType::DHCP_IPTYPE_MIX); item.defaultWifiInterface = "wlan0"; @@ -516,6 +809,8 @@ void ClearTClass(WifiConfig &item) item.secondRssiLevel5G = RSSI_LEVEL_2_5G; item.thirdRssiLevel5G = RSSI_LEVEL_3_5G; item.fourthRssiLevel5G = RSSI_LEVEL_4_5G; + item.strDnsBak = "8.8.8.8"; + item.isLoadStabak = true; return; } @@ -545,6 +840,8 @@ static int SetWifiConfigValueFirst(WifiConfig &item, const std::string &key, con item.scoretacticsLastSelectionScore = std::stoi(value); } else if (key == "scoretacticsSecurityScore") { item.scoretacticsSecurityScore = std::stoi(value); + } else if (key == "scoretacticsNormalScore") { + item.scoretacticsNormalScore = std::stoi(value); } else if (key == "whetherToAllowNetworkSwitchover") { item.whetherToAllowNetworkSwitchover = (std::stoi(value) != 0); } else if (key == "dhcpIpType") { @@ -557,12 +854,8 @@ static int SetWifiConfigValueFirst(WifiConfig &item, const std::string &key, con return 0; } -template<> -void SetTClassKeyValue(WifiConfig &item, const std::string &key, const std::string &value) +static int SetWifiConfigValueSecond(WifiConfig &item, const std::string &key, const std::string &value) { - if (SetWifiConfigValueFirst(item, key, value) == 0) { - return; - } if (key == "preLoadSta") { item.preLoadSta = (std::stoi(value) != 0); /* 0 -> false 1 -> true */ } else if (key == "preLoadScan") { @@ -595,8 +888,29 @@ void SetTClassKeyValue(WifiConfig &item, const std::string &key, con item.thirdRssiLevel5G = std::stoi(value); } else if (key == "fourthRssiLevel5G") { item.fourthRssiLevel5G = std::stoi(value); + } else if (key == "strDnsBak") { + item.strDnsBak = value; + } else if (key == "isLoadStabak") { + item.isLoadStabak = (std::stoi(value) != 0); + } else { + return -1; } - return; + return 0; +} + +template<> +int SetTClassKeyValue(WifiConfig &item, const std::string &key, const std::string &value) +{ + int errorKeyValue = 0; + if (SetWifiConfigValueFirst(item, key, value) == 0) { + return errorKeyValue; + } + if (SetWifiConfigValueSecond(item, key, value) == 0) { + return errorKeyValue; + } + LOGE("Invalid config key value"); + errorKeyValue++; + return errorKeyValue; } template<> @@ -609,37 +923,42 @@ template<> std::string OutTClassString(WifiConfig &item) { std::ostringstream ss; - ss << "scanAlwaysSwitch=" << item.scanAlwaysSwitch << std::endl; /* bool false->0 true->1 */ - ss << "staAirplaneMode=" << item.staAirplaneMode << std::endl; - ss << "canOpenStaWhenAirplane=" << item.canOpenStaWhenAirplane << std::endl; - ss << "staLastState=" << item.staLastState << std::endl; - ss << "savedDeviceAppraisalPriority=" << item.savedDeviceAppraisalPriority << std::endl; - ss << "scoretacticsScoreSlope=" << item.scoretacticsScoreSlope << std::endl; - ss << "scoretacticsInitScore=" << item.scoretacticsInitScore << std::endl; - ss << "scoretacticsSameBssidScore=" << item.scoretacticsSameBssidScore << std::endl; - ss << "scoretacticsSameNetworkScore=" << item.scoretacticsSameNetworkScore << std::endl; - ss << "scoretacticsFrequency5GHzScore=" << item.scoretacticsFrequency5GHzScore << std::endl; - ss << "scoretacticsLastSelectionScore=" << item.scoretacticsLastSelectionScore << std::endl; - ss << "scoretacticsSecurityScore=" << item.scoretacticsSecurityScore << std::endl; - ss << "whetherToAllowNetworkSwitchover=" << item.whetherToAllowNetworkSwitchover << std::endl; - ss << "dhcpIpType=" << item.dhcpIpType << std::endl; - ss << "defaultWifiInterface=" << item.defaultWifiInterface << std::endl; - ss << "preLoadSta=" << item.preLoadSta << std::endl; - ss << "preLoadScan=" << item.preLoadScan << std::endl; - ss << "preLoadAp=" << item.preLoadAp << std::endl; - ss << "preLoadP2p=" << item.preLoadP2p << std::endl; - ss << "preLoadAware=" << item.preLoadAware << std::endl; - ss << "supportHwPnoFlag=" << item.supportHwPnoFlag << std::endl; - ss << "minRssi2Dot4Ghz=" << item.minRssi2Dot4Ghz << std::endl; - ss << "minRssi5Ghz=" << item.minRssi5Ghz << std::endl; - ss << "firstRssiLevel2G=" << item.firstRssiLevel2G << std::endl; - ss << "secondRssiLevel2G=" << item.secondRssiLevel2G << std::endl; - ss << "thirdRssiLevel2G=" << item.thirdRssiLevel2G << std::endl; - ss << "fourthRssiLevel2G=" << item.fourthRssiLevel2G << std::endl; - ss << "firstRssiLevel5G=" << item.firstRssiLevel5G << std::endl; - ss << "secondRssiLevel5G=" << item.secondRssiLevel5G << std::endl; - ss << "thirdRssiLevel5G=" << item.thirdRssiLevel5G << std::endl; - ss << "fourthRssiLevel5G=" << item.fourthRssiLevel5G << std::endl; + ss << " " <<"" << std::endl; + ss << " " <<"scanAlwaysSwitch=" << item.scanAlwaysSwitch << std::endl; /* bool false->0 true->1 */ + ss << " " <<"staAirplaneMode=" << item.staAirplaneMode << std::endl; + ss << " " <<"canOpenStaWhenAirplane=" << item.canOpenStaWhenAirplane << std::endl; + ss << " " <<"staLastState=" << item.staLastState << std::endl; + ss << " " <<"savedDeviceAppraisalPriority=" << item.savedDeviceAppraisalPriority << std::endl; + ss << " " <<"scoretacticsScoreSlope=" << item.scoretacticsScoreSlope << std::endl; + ss << " " <<"scoretacticsInitScore=" << item.scoretacticsInitScore << std::endl; + ss << " " <<"scoretacticsSameBssidScore=" << item.scoretacticsSameBssidScore << std::endl; + ss << " " <<"scoretacticsSameNetworkScore=" << item.scoretacticsSameNetworkScore << std::endl; + ss << " " <<"scoretacticsFrequency5GHzScore=" << item.scoretacticsFrequency5GHzScore << std::endl; + ss << " " <<"scoretacticsLastSelectionScore=" << item.scoretacticsLastSelectionScore << std::endl; + ss << " " <<"scoretacticsSecurityScore=" << item.scoretacticsSecurityScore << std::endl; + ss << " " <<"scoretacticsNormalScore=" << item.scoretacticsNormalScore << std::endl; + ss << " " <<"whetherToAllowNetworkSwitchover=" << item.whetherToAllowNetworkSwitchover << std::endl; + ss << " " <<"dhcpIpType=" << item.dhcpIpType << std::endl; + ss << " " <<"defaultWifiInterface=" << item.defaultWifiInterface << std::endl; + ss << " " <<"preLoadSta=" << item.preLoadSta << std::endl; + ss << " " <<"preLoadScan=" << item.preLoadScan << std::endl; + ss << " " <<"preLoadAp=" << item.preLoadAp << std::endl; + ss << " " <<"preLoadP2p=" << item.preLoadP2p << std::endl; + ss << " " <<"preLoadAware=" << item.preLoadAware << std::endl; + ss << " " <<"supportHwPnoFlag=" << item.supportHwPnoFlag << std::endl; + ss << " " <<"minRssi2Dot4Ghz=" << item.minRssi2Dot4Ghz << std::endl; + ss << " " <<"minRssi5Ghz=" << item.minRssi5Ghz << std::endl; + ss << " " <<"firstRssiLevel2G=" << item.firstRssiLevel2G << std::endl; + ss << " " <<"secondRssiLevel2G=" << item.secondRssiLevel2G << std::endl; + ss << " " <<"thirdRssiLevel2G=" << item.thirdRssiLevel2G << std::endl; + ss << " " <<"fourthRssiLevel2G=" << item.fourthRssiLevel2G << std::endl; + ss << " " <<"firstRssiLevel5G=" << item.firstRssiLevel5G << std::endl; + ss << " " <<"secondRssiLevel5G=" << item.secondRssiLevel5G << std::endl; + ss << " " <<"thirdRssiLevel5G=" << item.thirdRssiLevel5G << std::endl; + ss << " " <<"fourthRssiLevel5G=" << item.fourthRssiLevel5G << std::endl; + ss << " " <<"strDnsBak=" << item.strDnsBak << std::endl; + ss << " " <<"isLoadStabak=" << item.isLoadStabak << std::endl; + ss << " " <<"" << std::endl; return ss.str(); } @@ -660,8 +979,9 @@ void ClearTClass(WifiP2pGroupInfo &item) item.ClearClientDevices(); } -static void SetWifiP2pDevicClassKeyValue(WifiP2pDevice &item, const std::string &key, const std::string &value) +static int SetWifiP2pDevicClassKeyValue(WifiP2pDevice &item, const std::string &key, const std::string &value) { + int errorKeyValue = 0; if (key == "deviceName") { item.SetDeviceName(value); } else if (key == "deviceAddress") { @@ -676,12 +996,75 @@ static void SetWifiP2pDevicClassKeyValue(WifiP2pDevice &item, const std::string item.SetDeviceCapabilitys(std::stoi(value)); } else if (key == "groupCapabilitys") { item.SetGroupCapabilitys(std::stoi(value)); + } else { + LOGE("Invalid config key value"); + errorKeyValue++; } + return errorKeyValue; +} + +#ifdef FEATURE_ENCRYPTION_SUPPORT +static int SetWifiP2pGroupInfoEncrypt(WifiP2pGroupInfo &item, const std::string &key, const std::string &value) +{ + int errorKeyValue = 0; + WifiEncryptionInfo mWifiEncryptionInfo; + mWifiEncryptionInfo.SetFile(GetTClassName()); + if (key == "encryptedData") { + item.SetPassphrase(value); + } else if (key == "IV") { + EncryptedData *encry = new EncryptedData(item.GetPassphrase(), value); + std::string decry = ""; + if (WifiDecryption(mWifiEncryptionInfo, *encry, decry) == HKS_SUCCESS) { + item.SetPassphrase(decry); + } else { + item.SetPassphrase(""); + errorKeyValue++; + } + delete encry; + } else { + return -1; + } + return errorKeyValue; +} +#endif + +static int SetWifiP2pGroupInfoDev(WifiP2pGroupInfo &item, const std::string &key, const std::string &value) +{ + if (key.compare(0, strlen("ownerDev."), "ownerDev.") == 0) { + WifiP2pDevice owner = item.GetOwner(); + SetWifiP2pDevicClassKeyValue(owner, key.substr(strlen("ownerDev.")), value); + item.SetOwner(owner); + } else if (key.compare(0, strlen("vecDev_"), "vecDev_") == 0) { + std::string::size_type pos = key.find("."); + if (pos == std::string::npos) { + WifiP2pDevice device; + item.AddClientDevice(device); + } else { + unsigned long index = std::stoi(key.substr(strlen("vecDev_"), pos)); + if (index < item.GetClientDevices().size()) { + std::vector clients = item.GetClientDevices(); + SetWifiP2pDevicClassKeyValue(clients[index], key.substr(pos + 1), value); + item.SetClientDevices(clients); + } + } + } else { + return -1; + } + return 0; } template<> -void SetTClassKeyValue(WifiP2pGroupInfo &item, const std::string &key, const std::string &value) +int SetTClassKeyValue(WifiP2pGroupInfo &item, const std::string &key, const std::string &value) { + int errorKeyValue = 0; +#ifdef FEATURE_ENCRYPTION_SUPPORT + errorKeyValue = SetWifiP2pGroupInfoEncrypt(item, key, value); + if (errorKeyValue != -1) { + return errorKeyValue; + } else { + errorKeyValue = 0; + } +#endif if (key == "isGroupOwner") { item.SetIsGroupOwner(std::stoi(value) != 0); } else if (key == "passphrase") { @@ -690,6 +1073,15 @@ void SetTClassKeyValue(WifiP2pGroupInfo &item, const std::stri item.SetInterface(value); } else if (key == "groupName") { item.SetGroupName(value); + } else if (key == "groupNameHex") { + std::vector vec; + vec.clear(); + if (HexStringToVec(value, vec) == 0) { + std::string strSsid(vec.begin(), vec.end()); + item.SetGroupName(strSsid); + } else { + return -1; + } } else if (key == "networkId") { item.SetNetworkId(std::stoi(value)); } else if (key == "frequency") { @@ -700,24 +1092,13 @@ void SetTClassKeyValue(WifiP2pGroupInfo &item, const std::stri item.SetP2pGroupStatus(static_cast(std::stoi(value))); } else if (key == "goIpAddress") { item.SetGoIpAddress(value); - } else if (key.compare(0, strlen("ownerDev."), "ownerDev.") == 0) { - WifiP2pDevice owner = item.GetOwner(); - SetWifiP2pDevicClassKeyValue(owner, key.substr(strlen("ownerDev.")), value); - item.SetOwner(owner); - } else if (key.compare(0, strlen("vecDev_"), "vecDev_") == 0) { - std::string::size_type pos = key.find("."); - if (pos == std::string::npos) { - WifiP2pDevice device; - item.AddClientDevice(device); - } else { - unsigned long index = std::stoi(key.substr(strlen("vecDev_"), pos)); - if (index < item.GetClientDevices().size()) { - std::vector clients = item.GetClientDevices(); - SetWifiP2pDevicClassKeyValue(clients[index], key.substr(pos + 1), value); - item.SetClientDevices(clients); - } - } + } else if (SetWifiP2pGroupInfoDev(item, key, value) == 0) { + return errorKeyValue; + } else { + LOGE("Invalid config key value"); + errorKeyValue++; } + return errorKeyValue; } template<> @@ -726,17 +1107,17 @@ std::string GetTClassName() return "WifiP2pGroupInfo"; } -static std::string OutWifiP2pDevicClassString(const WifiP2pDevice &item, std::string prefix = "") +static std::string OutWifiP2pDeviceClassString(const WifiP2pDevice &item, std::string prefix = "") { std::ostringstream ss; - ss << prefix << "deviceName=" << item.GetDeviceName() << std::endl; - ss << prefix << "deviceAddress=" << item.GetDeviceAddress() << std::endl; - ss << prefix << "primaryDeviceType=" << item.GetPrimaryDeviceType() << std::endl; - ss << prefix << "status=" << static_cast(item.GetP2pDeviceStatus()) << std::endl; - ss << prefix << "supportWpsConfigMethods=" << item.GetWpsConfigMethod() << std::endl; - ss << prefix << "deviceCapabilitys=" << item.GetDeviceCapabilitys() << std::endl; - ss << prefix << "groupCapabilitys=" << item.GetGroupCapabilitys() << std::endl; + ss << " " <" << std::endl; + ss << " " <<"groupName=" << ValidateString(item.GetGroupName()) << std::endl; + ss << " " <<"groupNameHex=" + << ConvertArrayToHex((uint8_t*)&item.GetGroupName()[0], item.GetGroupName().length()) << std::endl; + ss << " " <<"networkId=" << item.GetNetworkId() << std::endl; + ss << " " <<"isGroupOwner=" << item.IsGroupOwner() << std::endl; + ss << " " <<"interface=" << item.GetInterface() << std::endl; +#ifdef FEATURE_ENCRYPTION_SUPPORT + WifiEncryptionInfo mWifiEncryptionInfo; + mWifiEncryptionInfo.SetFile(GetTClassName()); + EncryptedData encry; + if (WifiEncryption(mWifiEncryptionInfo, item.GetPassphrase(), encry) == HKS_SUCCESS) { + ss << " " <<"encryptedData=" << encry.encryptedPassword << std::endl; + ss << " " <<"IV=" << encry.IV << std::endl; + } else { + ss << " " <<"passphrase=" << item.GetPassphrase() << std::endl; + } +#else + ss << " " <<"passphrase=" << item.GetPassphrase() << std::endl; +#endif + ss << " " <<"frequency=" << item.GetFrequency() << std::endl; + ss << " " <<"isPersistent=" << item.IsPersistent() << std::endl; + ss << " " <<"groupStatus=" << static_cast(item.GetP2pGroupStatus()) << std::endl; + ss << " " <<"goIpAddress=" << item.GetGoIpAddress() << std::endl; + ss << OutWifiP2pDeviceClassString(item.GetOwner(), "ownerDev."); int size = item.GetClientDevices().size(); for (int i = 0; i < size; i++) { std::string prefix = "vecDev_" + std::to_string(i) + "."; - ss << "vecDev_=" << i << std::endl; + ss << " " <<"vecDev_=" << i << std::endl; const WifiP2pDevice &tmp = item.GetClientDevices().at(i); - ss << OutWifiP2pDevicClassString(tmp, prefix); + ss << OutWifiP2pDeviceClassString(tmp, prefix); } + ss << " " <<"" << std::endl; + return ss.str(); +} + +template <> +void ClearTClass(TrustListPolicy &item) +{ + item.sceneId = 0; + item.sceneName.clear(); + item.trustList.clear(); + return; +} + +template <> +int SetTClassKeyValue(TrustListPolicy &item, const std::string &key, const std::string &value) +{ + int errorKeyValue = 0; + if (key == "sceneId") { + item.sceneId = std::stoi(value); + } else if (key == "sceneName") { + item.sceneName = value; + } else if (key == "trustList") { + item.trustList = value; + } else { + LOGE("Invalid config key value"); + errorKeyValue++; + } + return errorKeyValue; +} + +template <> +std::string GetTClassName() +{ + return "TrustListPolicy"; +} + +template <> std::string OutTClassString(TrustListPolicy &item) +{ + std::ostringstream ss; + ss << " " <<"" << std::endl; + ss << " " <<"sceneId=" << item.sceneId << std::endl; + ss << " " <<"sceneName=" << item.sceneName << std::endl; + ss << " " <<"trustList=" << item.trustList << std::endl; + ss << " " <<"" << std::endl; + return ss.str(); +} + +template <> void ClearTClass(MovingFreezePolicy &item) +{ + item.trustList.clear(); + return; +} + +template <> +int SetTClassKeyValue(MovingFreezePolicy &item, const std::string &key, const std::string &value) +{ + int errorKeyValue = 0; + if (key == "trustList") { + item.trustList = value; + } else { + LOGE("Invalid config key value"); + errorKeyValue++; + } + return errorKeyValue; +} + +template <> std::string GetTClassName() +{ + return "MovingFreezePolicy"; +} + +template <> std::string OutTClassString(MovingFreezePolicy &item) +{ + std::ostringstream ss; + ss << " " <<"" << std::endl; + ss << " " <<"trustList=" << item.trustList << std::endl; + ss << " " <<"" << std::endl; + return ss.str(); +} + +template <> void ClearTClass(WifiStoreRandomMac &item) +{ + item.ssid.clear(); + item.keyMgmt.clear(); + item.peerBssid.clear(); + item.randomMac.clear(); + return; +} + +template <> +int SetTClassKeyValue(WifiStoreRandomMac &item, const std::string &key, const std::string &value) +{ + int errorKeyValue = 0; + if (key == "ssid") { + item.ssid = value; + } else if (key == "HexSsid") { + std::vector vec; + vec.clear(); + if (HexStringToVec(value, vec) == 0) { + std::string strSsid(vec.begin(), vec.end()); + item.ssid = strSsid; + } else { + return -1; + } + } else if (key == "keyMgmt") { + item.keyMgmt = value; + } else if (key == "peerBssid") { + item.peerBssid = value; + } else if (key == "randomMac") { + item.randomMac = value; + } else { + LOGE("Invalid config key value"); + errorKeyValue++; + } + return errorKeyValue; +} + +template <> std::string GetTClassName() +{ + return "WifiStoreRandomMac"; +} + +template <> std::string OutTClassString(WifiStoreRandomMac &item) +{ + std::ostringstream ss; + ss << " " <<"" << std::endl; + ss << " " <<"ssid=" << ValidateString(item.ssid) << std::endl; + ss << " " <<"HexSsid=" << ConvertArrayToHex((uint8_t*)&item.ssid[0], item.ssid.length()) << std::endl; + ss << " " <<"keyMgmt=" << item.keyMgmt << std::endl; + ss << " " <<"peerBssid=" << item.peerBssid << std::endl; + ss << " " <<"randomMac=" << item.randomMac << std::endl; + ss << " " <<"" << std::endl; return ss.str(); } } // namespace Wifi -} // namespace OHOS +} // namespace OHOS \ No newline at end of file diff --git a/services/wifi_standard/wifi_framework/common/config/wifi_config_file_spec.h b/wifi/services/wifi_standard/wifi_framework/wifi_toolkit/config/wifi_config_file_spec.h similarity index 63% rename from services/wifi_standard/wifi_framework/common/config/wifi_config_file_spec.h rename to wifi/services/wifi_standard/wifi_framework/wifi_toolkit/config/wifi_config_file_spec.h index c76bd86925f655d7f6da8d3332333056de90f325..2cda3aaba1aab7ff71bcd293a3bac4cb4ccdffbe 100644 --- a/services/wifi_standard/wifi_framework/common/config/wifi_config_file_spec.h +++ b/wifi/services/wifi_standard/wifi_framework/wifi_toolkit/config/wifi_config_file_spec.h @@ -21,6 +21,7 @@ #include #include "wifi_internal_msg.h" #include "wifi_p2p_msg.h" + namespace OHOS { namespace Wifi { /* ----------------- template function begin ----------------------- */ @@ -38,6 +39,7 @@ void ClearTClass(T &item) return; } + /** * @Description Set item's data, input key is the item's member and input value is the * member's value @@ -46,15 +48,16 @@ void ClearTClass(T &item) * @param item - T &item * @param key - Item key * @param value - Item value + * @return int - parse error: 0 Success, >0 parse failed */ template -void SetTClassKeyValue(T &item, const std::string &key, const std::string &value) +int SetTClassKeyValue(T &item, const std::string &key, const std::string &value) { /* fixed compile warning, -Werror,-Wunused-parameter */ item; std::ostringstream ss; ss << key << value << std::endl; - return; + return 0; } /** @@ -105,9 +108,10 @@ void ClearTClass(WifiDeviceConfig &item); * @param item - WifiDeviceConfig &item * @param key - WifiDeviceConfig struct member name * @param value - the WifiDeviceConfig item member value + * @return int - parse error: 0 Success, >0 parse failed */ template <> -void SetTClassKeyValue(WifiDeviceConfig &item, const std::string &key, const std::string &value); +int SetTClassKeyValue(WifiDeviceConfig &item, const std::string &key, const std::string &value); /** * @Description Output WifiDeviceConfig class name @@ -145,9 +149,10 @@ void ClearTClass(HotspotConfig &item); * @param item - HotspotConfig &item * @param key - HotspotConfig struct member name * @param value - the HotspotConfig item member value + * @return int - parse error: 0 Success, >0 parse failed */ template <> -void SetTClassKeyValue(HotspotConfig &item, const std::string &key, const std::string &value); +int SetTClassKeyValue(HotspotConfig &item, const std::string &key, const std::string &value); /** * @Description Output HotspotConfig class name @@ -185,9 +190,10 @@ void ClearTClass(P2pVendorConfig &item); * @param item - P2pVendorConfig &item * @param key - P2pVendorConfig struct member name * @param value - the P2pVendorConfig item member value + * @return int - parse error: 0 Success, >0 parse failed */ template<> -void SetTClassKeyValue(P2pVendorConfig &item, const std::string &key, const std::string &value); +int SetTClassKeyValue(P2pVendorConfig &item, const std::string &key, const std::string &value); /** * @Description Output P2pVendorConfig class name @@ -225,9 +231,10 @@ void ClearTClass(StationInfo &item); * @param item - StationInfo &item * @param key - StationInfo struct member name * @param value - the StationInfo item member value + * @return int - parse error: 0 Success, >0 parse failed */ template <> -void SetTClassKeyValue(StationInfo &item, const std::string &key, const std::string &value); +int SetTClassKeyValue(StationInfo &item, const std::string &key, const std::string &value); /** * @Description Output StationInfo class name @@ -265,9 +272,10 @@ void ClearTClass(WifiConfig &item); * @param item - WifiConfig &item * @param key - WifiConfig struct member name * @param value - the WifiConfig item member value + * @return int - parse error: 0 Success, >0 parse failed */ template <> -void SetTClassKeyValue(WifiConfig &item, const std::string &key, const std::string &value); +int SetTClassKeyValue(WifiConfig &item, const std::string &key, const std::string &value); /** * @Description Output WifiConfig class name @@ -305,9 +313,10 @@ void ClearTClass(WifiP2pGroupInfo &item); * @param item - WifiP2pGroupInfo &item * @param key - WifiP2pGroupInfo struct member name * @param value - the WifiP2pGroupInfo item member value + * @return int - parse error: 0 Success, >0 parse failed */ template<> -void SetTClassKeyValue(WifiP2pGroupInfo &item, const std::string &key, const std::string &value); +int SetTClassKeyValue(WifiP2pGroupInfo &item, const std::string &key, const std::string &value); /** * @Description Output WifiP2pGroupInfo class name @@ -328,7 +337,130 @@ std::string GetTClassName(); */ template<> std::string OutTClassString(WifiP2pGroupInfo &item); + +/** + * @Description Clear and init TrustListPolicy + * + * @tparam + * @param item - TrustListPolicy &item + */ +template <> +void ClearTClass(TrustListPolicy &item); + +/** + * @Description Set TrustListPolicy item data + * + * @tparam + * @param item - TrustListPolicy &item + * @param key - TrustListPolicy struct member name + * @param value - the TrustListPolicy item member value + * @return int - parse error: 0 Success, >0 parse failed + */ +template <> +int SetTClassKeyValue(TrustListPolicy &item, const std::string &key, const std::string &value); + +/** + * @Description Output TrustListPolicy class name + * + * @tparam + * @param item - TrustListPolicy &item + * @return std::string - Class name + */ +template <> +std::string GetTClassName(); + +/** + * @Description Output the TrustListPolicy item, format: item's member = the member value + * + * @tparam + * @param item - TrustListPolicy &item + * @return std::string - output total member=value string about the TrustListPolicy item + */ +template <> +std::string OutTClassString(TrustListPolicy &item); + +/** + * @Description Clear and init MovingFreezePolicy + * + * @tparam + * @param item - MovingFreezePolicy &item + */ +template <> +void ClearTClass(MovingFreezePolicy &item); + +/** + * @Description Set MovingFreezePolicy item data + * + * @tparam + * @param item - MovingFreezePolicy &item + * @param key - MovingFreezePolicy struct member name + * @param value - the MovingFreezePolicy item member value + * @return int - parse error: 0 Success, >0 parse failed + */ +template <> +int SetTClassKeyValue(MovingFreezePolicy &item, const std::string &key, const std::string &value); + +/** + * @Description Output MovingFreezePolicy class name + * + * @tparam + * @param item - MovingFreezePolicy &item + * @return std::string - Class name + */ +template <> +std::string GetTClassName(); + +/** + * @Description Output the MovingFreezePolicy item, format: item's member = the member value + * + * @tparam + * @param item - MovingFreezePolicy &item + * @return std::string - output total member=value string about the MovingFreezePolicy item + */ +template <> +std::string OutTClassString(MovingFreezePolicy &item); + +/** + * @Description Clear and init WifiStoreRandomMac + * + * @tparam + * @param item - WifiStoreRandomMac &item + */ +template <> +void ClearTClass(WifiStoreRandomMac &item); + +/** + * @Description Set WifiStoreRandomMac item data + * + * @tparam + * @param item - WifiStoreRandomMac &item + * @param key - WifiStoreRandomMac struct member name + * @param value - the WifiStoreRandomMac item member value + * @return int - parse error: 0 Success, >0 parse failed + */ +template <> +int SetTClassKeyValue(WifiStoreRandomMac &item, const std::string &key, const std::string &value); + +/** + * @Description Output WifiStoreRandomMac class name + * + * @tparam + * @param item - WifiStoreRandomMac &item + * @return std::string - Class name + */ +template <> +std::string GetTClassName(); + +/** + * @Description Output the WifiStoreRandomMac item, format: item's member = the member value + * + * @tparam + * @param item - WifiStoreRandomMac &item + * @return std::string - output total member=value string about the WifiStoreRandomMac item + */ +template <> +std::string OutTClassString(WifiStoreRandomMac &item); /* ----------template function specialization declare end----------- */ } // namespace Wifi } // namespace OHOS -#endif \ No newline at end of file +#endif diff --git a/services/wifi_standard/wifi_framework/common/config/wifi_settings.cpp b/wifi/services/wifi_standard/wifi_framework/wifi_toolkit/config/wifi_settings.cpp similarity index 64% rename from services/wifi_standard/wifi_framework/common/config/wifi_settings.cpp rename to wifi/services/wifi_standard/wifi_framework/wifi_toolkit/config/wifi_settings.cpp index f4b09a25cb5eb11dd1e09400b08f0a40b961c3e0..8a413789cd07dd303e3be58b6dc1321d808a9014 100644 --- a/services/wifi_standard/wifi_framework/common/config/wifi_settings.cpp +++ b/wifi/services/wifi_standard/wifi_framework/wifi_toolkit/config/wifi_settings.cpp @@ -16,7 +16,11 @@ #include #include "define.h" #include "wifi_global_func.h" - +#include "wifi_log.h" +#include "wifi_config_country_freqs.h" +#ifdef FEATURE_ENCRYPTION_SUPPORT +#include "wifi_encryption_util.h" +#endif namespace OHOS { namespace Wifi { WifiSettings &WifiSettings::GetInstance() @@ -29,18 +33,24 @@ WifiSettings::WifiSettings() : mWifiStaCapabilities(0), mWifiState(0), mScanAlwaysActive(false), - mHotspotState(static_cast(ApState::AP_STATE_CLOSED)), mP2pState(static_cast(P2pState::P2P_STATE_CLOSED)), mP2pDiscoverState(0), mP2pConnectState(0), mApMaxConnNum(0), mLastSelectedNetworkId(-1), mLastSelectedTimeVal(0), - mScreenState(1), + mScreenState(MODE_STATE_OPEN), mAirplaneModeState(MODE_STATE_CLOSE), - mAppRunningModeState(1), - mPowerSavingModeState(MODE_STATE_CLOSE) -{} + mAppRunningModeState(ScanMode::SYS_FOREGROUND_SCAN), + mPowerSavingModeState(MODE_STATE_CLOSE), + mFreezeModeState(MODE_STATE_CLOSE), + mNoChargerPlugModeState(MODE_STATE_CLOSE) +{ + mHotspotState[0] = static_cast(ApState::AP_STATE_CLOSED); + powerModel[0] = PowerModel::GENERAL; + mThermalLevel = static_cast(ThermalLevel::NORMAL); + mValidChannels.clear(); +} WifiSettings::~WifiSettings() { @@ -73,7 +83,9 @@ void WifiSettings::InitHotspotConfig() std::vector tmp; mSavedHotspotConfig.GetValue(tmp); if (tmp.size() > 0) { - mHotspotConfig = tmp[0]; + for (size_t i = 0; i < tmp.size(); i++) { + mHotspotConfig[i] = tmp[i]; + } } else { InitDefaultHotspotConfig(); } @@ -111,7 +123,7 @@ void WifiSettings::InitP2pVendorConfig() int WifiSettings::Init() { mCountryCode = "CN"; - InitGetApMaxConnNum(); + InitSettingsNum(); /* read ini config */ mSavedDeviceConfig.SetConfigFilePath(DEVICE_CONFIG_FILE_PATH); @@ -120,12 +132,21 @@ int WifiSettings::Init() mSavedWifiConfig.SetConfigFilePath(WIFI_CONFIG_FILE_PATH); mSavedWifiP2pGroupInfo.SetConfigFilePath(WIFI_P2P_GROUP_INFO_FILE_PATH); mSavedWifiP2pVendorConfig.SetConfigFilePath(WIFI_P2P_VENDOR_CONFIG_FILE_PATH); + mTrustListPolicies.SetConfigFilePath(WIFI_TRUST_LIST_POLICY_FILE_PATH); + mMovingFreezePolicy.SetConfigFilePath(WIFI_MOVING_FREEZE_POLICY_FILE_PATH); + mSavedWifiStoreRandomMac.SetConfigFilePath(WIFI_STA_RANDOM_MAC_FILE_PATH); InitWifiConfig(); ReloadDeviceConfig(); InitHotspotConfig(); - InitScanControlInfo(); InitP2pVendorConfig(); ReloadWifiP2pGroupInfoConfig(); + InitScanControlInfo(); + ReloadTrustListPolicies(); + ReloadMovingFreezePolicy(); +#ifdef FEATURE_ENCRYPTION_SUPPORT + SetUpHks(); +#endif + IncreaseNumRebootsSinceLastUse(); return 0; } @@ -192,17 +213,17 @@ int WifiSettings::GetScanControlInfo(ScanControlInfo &info) return 0; } -int WifiSettings::GetP2pInfo(WifiP2pInfo &connInfo) +int WifiSettings::GetP2pInfo(WifiP2pLinkedInfo &linkedInfo) { std::unique_lock lock(mInfoMutex); - connInfo = mWifiP2pInfo; + linkedInfo = mWifiP2pInfo; return 0; } -int WifiSettings::SaveP2pInfo(WifiP2pInfo &connInfo) +int WifiSettings::SaveP2pInfo(WifiP2pLinkedInfo &linkedInfo) { std::unique_lock lock(mInfoMutex); - mWifiP2pInfo = connInfo; + mWifiP2pInfo = linkedInfo; return 0; } @@ -244,6 +265,10 @@ void WifiSettings::ClearDeviceConfig(void) int WifiSettings::GetDeviceConfig(std::vector &results) { + if (!deviceConfigLoadFlag.test_and_set()) { + LOGE("Reload wifi config"); + ReloadDeviceConfig(); + } std::unique_lock lock(mConfigMutex); for (auto iter = mWifiDeviceConfig.begin(); iter != mWifiDeviceConfig.end(); iter++) { results.push_back(iter->second); @@ -253,6 +278,10 @@ int WifiSettings::GetDeviceConfig(std::vector &results) int WifiSettings::GetDeviceConfig(const int &networkId, WifiDeviceConfig &config) { + if (!deviceConfigLoadFlag.test_and_set()) { + LOGE("Reload wifi config"); + ReloadDeviceConfig(); + } std::unique_lock lock(mConfigMutex); for (auto iter = mWifiDeviceConfig.begin(); iter != mWifiDeviceConfig.end(); iter++) { if (iter->second.networkId == networkId) { @@ -265,6 +294,10 @@ int WifiSettings::GetDeviceConfig(const int &networkId, WifiDeviceConfig &config int WifiSettings::GetDeviceConfig(const std::string &index, const int &indexType, WifiDeviceConfig &config) { + if (!deviceConfigLoadFlag.test_and_set()) { + LOGE("Reload wifi config"); + ReloadDeviceConfig(); + } std::unique_lock lock(mConfigMutex); if (indexType == DEVICE_CONFIG_INDEX_SSID) { for (auto iter = mWifiDeviceConfig.begin(); iter != mWifiDeviceConfig.end(); iter++) { @@ -286,6 +319,10 @@ int WifiSettings::GetDeviceConfig(const std::string &index, const int &indexType int WifiSettings::GetDeviceConfig(const std::string &ssid, const std::string &keymgmt, WifiDeviceConfig &config) { + if (!deviceConfigLoadFlag.test_and_set()) { + LOGE("Reload wifi config"); + ReloadDeviceConfig(); + } std::unique_lock lock(mConfigMutex); for (auto iter = mWifiDeviceConfig.begin(); iter != mWifiDeviceConfig.end(); iter++) { if ((iter->second.ssid == ssid) && (iter->second.keyMgmt == keymgmt)) { @@ -298,6 +335,10 @@ int WifiSettings::GetDeviceConfig(const std::string &ssid, const std::string &ke int WifiSettings::GetHiddenDeviceConfig(std::vector &results) { + if (!deviceConfigLoadFlag.test_and_set()) { + LOGE("Reload wifi config"); + ReloadDeviceConfig(); + } std::unique_lock lock(mConfigMutex); for (auto iter = mWifiDeviceConfig.begin(); iter != mWifiDeviceConfig.end(); iter++) { if (iter->second.hiddenSSID) { @@ -328,6 +369,54 @@ int WifiSettings::SetDeviceState(int networkId, int state, bool bSetOther) return 0; } +int WifiSettings::SetDeviceAfterConnect(int networkId) +{ + std::unique_lock lock(mConfigMutex); + auto iter = mWifiDeviceConfig.find(networkId); + if (iter == mWifiDeviceConfig.end()) { + return -1; + } + LOGI("Set Device After Connect"); + iter->second.lastConnectTime = time(0); + iter->second.numRebootsSinceLastUse = 0; + iter->second.numAssociation++; + return 0; +} + +int WifiSettings::GetCandidateConfig(const int uid, const int &networkId, WifiDeviceConfig &config) +{ + std::vector configs; + if (GetAllCandidateConfig(uid, configs) != 0) { + return -1; + } + + for (const auto &it : configs) { + if (it.networkId == networkId) { + config = it; + return it.networkId; + } + } + return -1; +} + +int WifiSettings::GetAllCandidateConfig(const int uid, std::vector &configs) +{ + if (!deviceConfigLoadFlag.test_and_set()) { + LOGE("Reload wifi config"); + ReloadDeviceConfig(); + } + + std::unique_lock lock(mConfigMutex); + bool found = false; + for (auto iter = mWifiDeviceConfig.begin(); iter != mWifiDeviceConfig.end(); iter++) { + if (iter->second.uid == uid) { + configs.push_back(iter->second); + found = true; + } + } + return found ? 0 : -1; +} + int WifiSettings::SyncWifiP2pGroupInfoConfig() { std::unique_lock lock(mP2pMutex); @@ -366,14 +455,54 @@ int WifiSettings::GetWifiP2pGroupInfo(std::vector &groups) return 0; } +int WifiSettings::IncreaseNumRebootsSinceLastUse() +{ + std::unique_lock lock(mConfigMutex); + for (auto iter = mWifiDeviceConfig.begin(); iter != mWifiDeviceConfig.end(); iter++) { + iter->second.numRebootsSinceLastUse++; + } + return 0; +} + +int WifiSettings::RemoveExcessDeviceConfigs(std::vector &configs) +{ + int maxNumConfigs = mMaxNumConfigs; + if (maxNumConfigs < 0) { + return 1; + } + int numExcessNetworks = configs.size() - maxNumConfigs; + if (numExcessNetworks <= 0) { + return 1; + } + LOGI("Remove %d configs", numExcessNetworks); + sort(configs.begin(), configs.end(), [](WifiDeviceConfig a, WifiDeviceConfig b) { + if (a.status != b.status) { + return (a.status == 0) < (b.status == 0); + } else if (a.lastConnectTime != b.lastConnectTime) { + return a.lastConnectTime < b.lastConnectTime; + } else if (a.numRebootsSinceLastUse != b.numRebootsSinceLastUse) { + return a.numRebootsSinceLastUse > b.numRebootsSinceLastUse; + } else if (a.numAssociation != b.numAssociation) { + return a.numAssociation < b.numAssociation; + } else { + return a.networkId < b.networkId; + } + }); + configs.erase(configs.begin(), configs.begin() + numExcessNetworks); + return 0; +} + int WifiSettings::SyncDeviceConfig() { #ifndef CONFIG_NO_CONFIG_WRITE std::unique_lock lock(mConfigMutex); std::vector tmp; for (auto iter = mWifiDeviceConfig.begin(); iter != mWifiDeviceConfig.end(); ++iter) { - tmp.push_back(iter->second); + if (!iter->second.isEphemeral) { + tmp.push_back(iter->second); + } } + RemoveExcessDeviceConfigs(tmp); mSavedDeviceConfig.SetValue(tmp); return mSavedDeviceConfig.SaveConfig(); #else @@ -386,8 +515,11 @@ int WifiSettings::ReloadDeviceConfig() #ifndef CONFIG_NO_CONFIG_WRITE int ret = mSavedDeviceConfig.LoadConfig(); if (ret < 0) { + deviceConfigLoadFlag.clear(); + LOGE("Loading device config failed: %{public}d", ret); return -1; } + deviceConfigLoadFlag.test_and_set(); std::vector tmp; mSavedDeviceConfig.GetValue(tmp); std::unique_lock lock(mConfigMutex); @@ -409,6 +541,7 @@ int WifiSettings::AddWpsDeviceConfig(const WifiDeviceConfig &config) { int ret = mSavedDeviceConfig.LoadConfig(); if (ret < 0) { + LOGE("Add Wps config loading config failed: %{public}d", ret); return -1; } std::vector tmp; @@ -466,6 +599,50 @@ int WifiSettings::GetMacAddress(std::string &macAddress) return 0; } +int WifiSettings::ReloadStaRandomMac() +{ + if (mSavedWifiStoreRandomMac.LoadConfig()) { + return -1; + } + std::unique_lock lock(mStaMutex); + mWifiStoreRandomMac.clear(); + mSavedWifiStoreRandomMac.GetValue(mWifiStoreRandomMac); + return 0; +} + +bool WifiSettings::AddRandomMac(WifiStoreRandomMac &randomMacInfo) +{ + std::unique_lock lock(mStaMutex); + bool isConnected = false; + + for (auto &ele : mWifiStoreRandomMac) { + if ((randomMacInfo.ssid == ele.ssid) && (randomMacInfo.keyMgmt == ele.keyMgmt)) { + ele.peerBssid = randomMacInfo.peerBssid; + randomMacInfo.randomMac = ele.randomMac; + isConnected = true; + break; + } else if (randomMacInfo.peerBssid == ele.peerBssid && (randomMacInfo.keyMgmt == ele.keyMgmt) && + (randomMacInfo.keyMgmt == "NONE")) { + isConnected = false; + } else if (randomMacInfo.peerBssid == ele.peerBssid && (randomMacInfo.keyMgmt == ele.keyMgmt) && + (randomMacInfo.keyMgmt != "NONE")) { + ele.ssid = randomMacInfo.ssid; + randomMacInfo.randomMac = ele.randomMac; + isConnected = true; + } else { + isConnected = false; + } + } + + if (!isConnected) { + mWifiStoreRandomMac.push_back(randomMacInfo); + } + + mSavedWifiStoreRandomMac.SetValue(mWifiStoreRandomMac); + mSavedWifiStoreRandomMac.SaveConfig(); + return isConnected; +} + int WifiSettings::SetCountryCode(const std::string &countryCode) { std::unique_lock lock(mStaMutex); @@ -482,28 +659,36 @@ int WifiSettings::GetCountryCode(std::string &countryCode) return 0; } -int WifiSettings::GetHotspotState() +int WifiSettings::GetHotspotState(int id) { - return mHotspotState.load(); + auto iter = mHotspotState.find(id); + if (iter != mHotspotState.end()) { + return iter->second.load(); + } + mHotspotState[id] = static_cast(ApState::AP_STATE_CLOSED); + return mHotspotState[id].load(); } -int WifiSettings::SetHotspotState(int state) +int WifiSettings::SetHotspotState(int state, int id) { - mHotspotState = state; + mHotspotState[id] = state; return 0; } -int WifiSettings::SetHotspotConfig(const HotspotConfig &config) +int WifiSettings::SetHotspotConfig(const HotspotConfig &config, int id) { std::unique_lock lock(mApMutex); - mHotspotConfig = config; + mHotspotConfig[id] = config; return 0; } -int WifiSettings::GetHotspotConfig(HotspotConfig &config) +int WifiSettings::GetHotspotConfig(HotspotConfig &config, int id) { std::unique_lock lock(mApMutex); - config = mHotspotConfig; + auto iter = mHotspotConfig.find(id); + if (iter != mHotspotConfig.end()) { + config = iter->second; + } return 0; } @@ -511,9 +696,17 @@ int WifiSettings::SyncHotspotConfig() { std::unique_lock lock(mApMutex); std::vector tmp; - tmp.push_back(mHotspotConfig); + + for (int i = 0; i < AP_INSTANCE_MAX_NUM; i++) { + auto iter = mHotspotConfig.find(i); + if (iter != mHotspotConfig.end()) { + tmp.push_back(iter->second); + } + } mSavedHotspotConfig.SetValue(tmp); - return mSavedHotspotConfig.SaveConfig(); + mSavedHotspotConfig.SaveConfig(); + + return 0; } int WifiSettings::SetP2pVendorConfig(const P2pVendorConfig &config) @@ -539,7 +732,7 @@ int WifiSettings::SyncP2pVendorConfig() return mSavedWifiP2pVendorConfig.SaveConfig(); } -int WifiSettings::GetStationList(std::vector &results) +int WifiSettings::GetStationList(std::vector &results, int id) { std::unique_lock lock(mInfoMutex); for (auto iter = mConnectStationInfo.begin(); iter != mConnectStationInfo.end(); iter++) { @@ -548,7 +741,7 @@ int WifiSettings::GetStationList(std::vector &results) return 0; } -int WifiSettings::ManageStation(const StationInfo &info, int mode) +int WifiSettings::ManageStation(const StationInfo &info, int mode, int id) { std::unique_lock lock(mInfoMutex); auto iter = mConnectStationInfo.find(info.bssid); @@ -568,7 +761,7 @@ int WifiSettings::ManageStation(const StationInfo &info, int mode) return 0; } -int WifiSettings::FindConnStation(const StationInfo &info) +int WifiSettings::FindConnStation(const StationInfo &info, int id) { std::unique_lock lock(mInfoMutex); auto iter = mConnectStationInfo.find(info.bssid); @@ -578,14 +771,14 @@ int WifiSettings::FindConnStation(const StationInfo &info) return 0; } -int WifiSettings::ClearStationList() +int WifiSettings::ClearStationList(int id) { std::unique_lock lock(mInfoMutex); mConnectStationInfo.clear(); return 0; } -int WifiSettings::GetBlockList(std::vector &results) +int WifiSettings::GetBlockList(std::vector &results, int id) { std::unique_lock lock(mInfoMutex); for (auto iter = mBlockListInfo.begin(); iter != mBlockListInfo.end(); iter++) { @@ -594,7 +787,7 @@ int WifiSettings::GetBlockList(std::vector &results) return 0; } -int WifiSettings::ManageBlockList(const StationInfo &info, int mode) +int WifiSettings::ManageBlockList(const StationInfo &info, int mode, int id) { std::unique_lock lock(mInfoMutex); auto iter = mBlockListInfo.find(info.bssid); @@ -663,6 +856,29 @@ int WifiSettings::ClearValidChannels() return 0; } +int WifiSettings::SetPowerModel(const PowerModel& model, int id) +{ + std::unique_lock lock(mInfoMutex); + auto ret = powerModel.emplace(id, model); + if (!ret.second) { + powerModel[id] = model; + } + return 0; +} + +int WifiSettings::GetPowerModel(PowerModel& model, int id) +{ + std::unique_lock lock(mInfoMutex); + auto iter = powerModel.find(id); + if (iter != powerModel.end()) { + model = iter->second; + } else { + powerModel[id] = PowerModel::GENERAL; + model = powerModel[id]; + } + return 0; +} + int WifiSettings::SetP2pState(int state) { mP2pState = state; @@ -747,56 +963,74 @@ int WifiSettings::GetApMaxConnNum() void WifiSettings::InitDefaultHotspotConfig() { - mHotspotConfig.SetSecurityType(KeyMgmt::WPA_PSK); - mHotspotConfig.SetBand(BandType::BAND_2GHZ); - mHotspotConfig.SetChannel(AP_CHANNEL_DEFAULT); - mHotspotConfig.SetMaxConn(GetApMaxConnNum()); - mHotspotConfig.SetSsid("OHOS_" + GetRandomStr(RANDOM_STR_LEN)); - mHotspotConfig.SetPreSharedKey("12345678"); + HotspotConfig cfg; + cfg.SetSecurityType(KeyMgmt::WPA_PSK); + cfg.SetBand(BandType::BAND_2GHZ); + cfg.SetChannel(AP_CHANNEL_DEFAULT); + cfg.SetMaxConn(GetApMaxConnNum()); + cfg.SetSsid("OHOS_" + GetRandomStr(RANDOM_STR_LEN)); + cfg.SetPreSharedKey("12345678"); + auto ret = mHotspotConfig.emplace(0, cfg); + if (!ret.second) { + mHotspotConfig[0] = cfg; + } } void WifiSettings::InitDefaultP2pVendorConfig() { mP2pVendorConfig.SetRandomMacSupport(false); - mP2pVendorConfig.SetIsAutoListen(true); + mP2pVendorConfig.SetIsAutoListen(false); mP2pVendorConfig.SetDeviceName(""); mP2pVendorConfig.SetPrimaryDeviceType(""); mP2pVendorConfig.SetSecondaryDeviceType(""); } -void WifiSettings::InitGetApMaxConnNum() +void WifiSettings::InitSettingsNum() { /* query drivers capability, support max connection num. */ mApMaxConnNum = MAX_AP_CONN; + mMaxNumConfigs = MAX_CONFIGS_NUM; } void WifiSettings::InitScanControlForbidList(void) { /* Disable external scanning during scanning. */ - std::vector forbidModeList; ScanForbidMode forbidMode; forbidMode.scanMode = ScanMode::ALL_EXTERN_SCAN; - forbidModeList.push_back(forbidMode); - mScanControlInfo.scanForbidMap[SCAN_SCENE_SCANNING] = forbidModeList; + forbidMode.scanScene = SCAN_SCENE_SCANNING; + mScanControlInfo.scanForbidList.push_back(forbidMode); /* Disable external scanning when the screen is shut down. */ - mScanControlInfo.scanForbidMap[SCAN_SCENE_SCREEN_OFF] = forbidModeList; + forbidMode.scanMode = ScanMode::ALL_EXTERN_SCAN; + forbidMode.scanScene = SCAN_SCENE_SCREEN_OFF; + mScanControlInfo.scanForbidList.push_back(forbidMode); /* Disable all scans in connection */ + forbidMode.scanMode = ScanMode::ALL_EXTERN_SCAN; + forbidMode.scanScene = SCAN_SCENE_CONNECTING; + mScanControlInfo.scanForbidList.push_back(forbidMode); forbidMode.scanMode = ScanMode::PNO_SCAN; - forbidModeList.push_back(forbidMode); + forbidMode.scanScene = SCAN_SCENE_CONNECTING; + mScanControlInfo.scanForbidList.push_back(forbidMode); forbidMode.scanMode = ScanMode::SYSTEM_TIMER_SCAN; - forbidModeList.push_back(forbidMode); - mScanControlInfo.scanForbidMap[SCAN_SCENE_CONNECTING] = forbidModeList; + forbidMode.scanScene = SCAN_SCENE_CONNECTING; + mScanControlInfo.scanForbidList.push_back(forbidMode); /* Deep sleep disables all scans. */ - mScanControlInfo.scanForbidMap[SCAN_SCENE_DEEP_SLEEP] = forbidModeList; + forbidMode.scanMode = ScanMode::ALL_EXTERN_SCAN; + forbidMode.scanScene = SCAN_SCENE_DEEP_SLEEP; + mScanControlInfo.scanForbidList.push_back(forbidMode); + forbidMode.scanMode = ScanMode::PNO_SCAN; + forbidMode.scanScene = SCAN_SCENE_DEEP_SLEEP; + mScanControlInfo.scanForbidList.push_back(forbidMode); + forbidMode.scanMode = ScanMode::SYSTEM_TIMER_SCAN; + forbidMode.scanScene = SCAN_SCENE_DEEP_SLEEP; + mScanControlInfo.scanForbidList.push_back(forbidMode); /* PNO scanning disabled */ - forbidModeList.clear(); forbidMode.scanMode = ScanMode::PNO_SCAN; - forbidModeList.push_back(forbidMode); - mScanControlInfo.scanForbidMap[SCAN_SCENE_CONNECTED] = forbidModeList; + forbidMode.scanScene = SCAN_SCENE_CONNECTED; + mScanControlInfo.scanForbidList.push_back(forbidMode); return; } @@ -804,7 +1038,7 @@ void WifiSettings::InitScanControlIntervalList(void) { /* Foreground app: 4 times in 2 minutes for a single application */ ScanIntervalMode scanIntervalMode; - scanIntervalMode.scanScene = SCAN_SCENE_ALL; + scanIntervalMode.scanScene = SCAN_SCENE_FREQUENCY_ORIGIN; scanIntervalMode.scanMode = ScanMode::APP_FOREGROUND_SCAN; scanIntervalMode.isSingle = true; scanIntervalMode.intervalMode = IntervalMode::INTERVAL_FIXED; @@ -813,7 +1047,7 @@ void WifiSettings::InitScanControlIntervalList(void) mScanControlInfo.scanIntervalList.push_back(scanIntervalMode); /* Backend apps: once every 30 minutes */ - scanIntervalMode.scanScene = SCAN_SCENE_ALL; + scanIntervalMode.scanScene = SCAN_SCENE_FREQUENCY_ORIGIN; scanIntervalMode.scanMode = ScanMode::APP_BACKGROUND_SCAN; scanIntervalMode.isSingle = false; scanIntervalMode.intervalMode = IntervalMode::INTERVAL_FIXED; @@ -821,6 +1055,34 @@ void WifiSettings::InitScanControlIntervalList(void) scanIntervalMode.count = BACKGROUND_SCAN_CONTROL_TIMES; mScanControlInfo.scanIntervalList.push_back(scanIntervalMode); + /* no charger plug */ + /* All app: If the scanning interval is less than 5s for five */ + /* consecutive times, the scanning can be performed only after */ + /* the scanning interval is greater than 5s. */ + const int frequencyContinueInterval = 5; + const int frequencyContinueCount = 5; + scanIntervalMode.scanScene = SCAN_SCENE_FREQUENCY_CUSTOM; + scanIntervalMode.scanMode = ScanMode::ALL_EXTERN_SCAN; + scanIntervalMode.isSingle = false; + scanIntervalMode.intervalMode = IntervalMode::INTERVAL_CONTINUE; + scanIntervalMode.interval = frequencyContinueInterval; + scanIntervalMode.count = frequencyContinueCount; + mScanControlInfo.scanIntervalList.push_back(scanIntervalMode); + + /* no charger plug */ + /* Single app: If all scanning interval in 10 times is less than */ + /* the threshold (20s), the app is added to the blocklist and */ + /* cannot initiate scanning. */ + const int frequencyBlocklistInterval = 20; + const int frequencyBlocklistCount = 10; + scanIntervalMode.scanScene = SCAN_SCENE_FREQUENCY_CUSTOM; + scanIntervalMode.scanMode = ScanMode::ALL_EXTERN_SCAN; + scanIntervalMode.isSingle = true; + scanIntervalMode.intervalMode = IntervalMode::INTERVAL_BLOCKLIST; + scanIntervalMode.interval = frequencyBlocklistInterval; + scanIntervalMode.count = frequencyBlocklistCount; + mScanControlInfo.scanIntervalList.push_back(scanIntervalMode); + /* PNO scanning every 20 seconds */ scanIntervalMode.scanScene = SCAN_SCENE_ALL; scanIntervalMode.scanMode = ScanMode::PNO_SCAN; @@ -906,6 +1168,7 @@ bool WifiSettings::GetStaLastRunState() int WifiSettings::SetStaLastRunState(bool bRun) { mWifiConfig.staLastState = bRun; + SyncWifiConfig(); return 0; } @@ -930,7 +1193,7 @@ void WifiSettings::SetScreenState(const int &state) mScreenState = state; } -int WifiSettings::GetScreenState() +int WifiSettings::GetScreenState() const { return mScreenState; } @@ -940,17 +1203,21 @@ void WifiSettings::SetAirplaneModeState(const int &state) mAirplaneModeState = state; } -int WifiSettings::GetAirplaneModeState() +int WifiSettings::GetAirplaneModeState() const { return mAirplaneModeState; } -void WifiSettings::SetAppRunningState(const int &state) +void WifiSettings::SetAppRunningState(ScanMode appRunMode) { - mAppRunningModeState = state; + if (static_cast(appRunMode) < static_cast(ScanMode::APP_FOREGROUND_SCAN) || + static_cast(appRunMode) > static_cast(ScanMode::SYS_BACKGROUND_SCAN)) { + return; + } + mAppRunningModeState = appRunMode; } -int WifiSettings::GetAppRunningState() +ScanMode WifiSettings::GetAppRunningState() const { return mAppRunningModeState; } @@ -960,11 +1227,41 @@ void WifiSettings::SetPowerSavingModeState(const int &state) mPowerSavingModeState = state; } -int WifiSettings::GetPowerSavingModeState() +int WifiSettings::GetPowerSavingModeState() const { return mPowerSavingModeState; } +void WifiSettings::SetAppPackageName(const std::string &appPackageName) +{ + mAppPackageName = appPackageName; +} + +const std::string WifiSettings::GetAppPackageName() const +{ + return mAppPackageName; +} + +void WifiSettings::SetFreezeModeState(int state) +{ + mFreezeModeState = state; +} + +int WifiSettings::GetFreezeModeState() const +{ + return mFreezeModeState; +} + +void WifiSettings::SetNoChargerPlugModeState(int state) +{ + mNoChargerPlugModeState = state; +} + +int WifiSettings::GetNoChargerPlugModeState() const +{ + return mNoChargerPlugModeState; +} + int WifiSettings::SetWhetherToAllowNetworkSwitchover(bool bSwitch) { mWifiConfig.whetherToAllowNetworkSwitchover = bSwitch; @@ -1053,6 +1350,17 @@ int WifiSettings::GetScoretacticsSecurityScore() return mWifiConfig.scoretacticsSecurityScore; } +int WifiSettings::SetScoretacticsNormalScore(const int &score) +{ + mWifiConfig.scoretacticsNormalScore = score; + return 0; +} + +int WifiSettings::GetScoretacticsNormalScore() +{ + return mWifiConfig.scoretacticsNormalScore; +} + int WifiSettings::SetSavedDeviceAppraisalPriority(const int &priority) { mWifiConfig.savedDeviceAppraisalPriority = priority; @@ -1096,11 +1404,109 @@ int WifiSettings::GetMinRssi5Ghz() return mWifiConfig.minRssi5Ghz; } +std::string WifiSettings::GetStrDnsBak() const +{ + return mWifiConfig.strDnsBak; +} + +bool WifiSettings::IsLoadStabak() const +{ + return mWifiConfig.isLoadStabak; +} + int WifiSettings::SetP2pDeviceName(const std::string &deviceName) { std::unique_lock lock(mP2pMutex); mP2pVendorConfig.SetDeviceName(deviceName); return mSavedWifiP2pVendorConfig.SaveConfig(); } + +const std::vector WifiSettings::ReloadTrustListPolicies() +{ + std::unique_lock lock(mStaMutex); + mTrustListPolicies.LoadConfig(); + if (mTrustListPolicies.GetValue().size() <= 0) { + std::vector policies; + TrustListPolicy policy; + policies.push_back(policy); + mTrustListPolicies.SetValue(policies); + mTrustListPolicies.SaveConfig(); + mTrustListPolicies.LoadConfig(); + } + + return mTrustListPolicies.GetValue(); +} + +const MovingFreezePolicy WifiSettings::ReloadMovingFreezePolicy() +{ + std::unique_lock lock(mStaMutex); + mMovingFreezePolicy.LoadConfig(); + + if (mMovingFreezePolicy.GetValue().size() <= 0) { + std::vector policies; + MovingFreezePolicy policy; + policies.push_back(policy); + mMovingFreezePolicy.SetValue(policies); + mMovingFreezePolicy.SaveConfig(); + mMovingFreezePolicy.LoadConfig(); + } + + if (mMovingFreezePolicy.GetValue().size() <= 0) { + return mFPolicy; + } + return mMovingFreezePolicy.GetValue()[0]; +} + +std::string WifiSettings::GetConnectTimeoutBssid() +{ + std::unique_lock lock(mStaMutex); + const int timeout = 30; // 30s + if (mBssidToTimeoutTime.second - static_cast(time(0)) > timeout) { + return ""; + } + return mBssidToTimeoutTime.first; +} + +int WifiSettings::SetConnectTimeoutBssid(std::string &bssid) +{ + std::unique_lock lock(mStaMutex); + time_t now = time(0); + mBssidToTimeoutTime = std::make_pair(bssid, static_cast(now)); + return 0; +} + +void WifiSettings::SetDefaultFrequenciesByCountryBand(const BandType band, std::vector &frequencies) +{ + std::string countryCode; + if (GetCountryCode(countryCode)) { + return; + } + + for (auto& item : g_countryDefaultFreqs) { + if (item.countryCode == countryCode && item.band == band) { + frequencies = item.freqs; + } + } +} + +void WifiSettings::SetExplicitGroup(bool isExplicit) +{ + explicitGroup = isExplicit; +} + +bool WifiSettings::IsExplicitGroup(void) +{ + return explicitGroup; +} + +void WifiSettings::SetThermalLevel(const int &level) +{ + mThermalLevel = level; +} + +int WifiSettings::GetThermalLevel() const +{ + return mThermalLevel; +} } // namespace Wifi -} // namespace OHOS \ No newline at end of file +} // namespace OHOS diff --git a/services/wifi_standard/wifi_framework/common/config/wifi_settings.h b/wifi/services/wifi_standard/wifi_framework/wifi_toolkit/config/wifi_settings.h similarity index 73% rename from services/wifi_standard/wifi_framework/common/config/wifi_settings.h rename to wifi/services/wifi_standard/wifi_framework/wifi_toolkit/config/wifi_settings.h index 54a5015b319078e5328a132d8e5a89d182876948..8fa6dbee56d1a53ec213f24e5a2aea511634e76d 100644 --- a/services/wifi_standard/wifi_framework/common/config/wifi_settings.h +++ b/wifi/services/wifi_standard/wifi_framework/wifi_toolkit/config/wifi_settings.h @@ -1,5 +1,5 @@ /* - * Copyright (C) 2021 Huawei Device Co., Ltd. + * Copyright (C) 2021-2022 Huawei Device Co., Ltd. * 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 @@ -22,11 +22,8 @@ #include #include #include +#include "wifi_common_def.h" #include "wifi_config_file_impl.h" - -constexpr int MODE_STATE_OPEN = 1; -constexpr int MODE_STATE_CLOSE = 2; - constexpr int RANDOM_STR_LEN = 6; constexpr int MSEC = 1000; constexpr int FOREGROUND_SCAN_CONTROL_TIMES = 4; @@ -43,16 +40,30 @@ constexpr int MODE_UPDATE = 2; /* Obtain the scanning result that is valid within 180s. */ constexpr int WIFI_GET_SCAN_INFO_VALID_TIMESTAMP = 180; -constexpr char DEVICE_CONFIG_FILE_PATH[] = "/data/misc/wifi/device_config.conf"; -constexpr char HOTSPOT_CONFIG_FILE_PATH[] = "/data/misc/wifi/hotspot_config.conf"; -constexpr char BLOCK_LIST_FILE_PATH[] = "/data/misc/wifi/block_list.conf"; -constexpr char WIFI_CONFIG_FILE_PATH[] = "/data/misc/wifi/wifi_config.conf"; -constexpr char WIFI_P2P_GROUP_INFO_FILE_PATH[] = "/data/misc/wifi/p2p_groups.conf"; -constexpr char WIFI_P2P_VENDOR_CONFIG_FILE_PATH[] = "/data/misc/wifi/p2p_vendor_config.conf"; +constexpr char DEVICE_CONFIG_FILE_PATH[] = CONFIG_ROOR_DIR"/device_config.conf"; +constexpr char HOTSPOT_CONFIG_FILE_PATH[] = CONFIG_ROOR_DIR"/hotspot_config.conf"; +constexpr char BLOCK_LIST_FILE_PATH[] = CONFIG_ROOR_DIR"/block_list.conf"; +constexpr char WIFI_CONFIG_FILE_PATH[] = CONFIG_ROOR_DIR"/wifi_config.conf"; +constexpr char WIFI_P2P_GROUP_INFO_FILE_PATH[] = CONFIG_ROOR_DIR"/p2p_groups.conf"; +constexpr char WIFI_P2P_VENDOR_CONFIG_FILE_PATH[] = CONFIG_ROOR_DIR"/p2p_vendor_config.conf"; +const std::string WIFI_TRUST_LIST_POLICY_FILE_PATH = CONFIG_ROOR_DIR"/trust_list_polices.conf"; +const std::string WIFI_MOVING_FREEZE_POLICY_FILE_PATH = CONFIG_ROOR_DIR"/moving_freeze_policy.conf"; +constexpr char WIFI_STA_RANDOM_MAC_FILE_PATH[] = CONFIG_ROOR_DIR"/sta_randomMac.conf"; + namespace OHOS { namespace Wifi { using ChannelsTable = std::map>; +enum class ThermalLevel { + COOL = 0, + NORMAL = 1, + WARM = 2, + HOT = 3, + OVERHEATED = 4, + WARNING = 5, + EMERGENCY = 6, +}; + class WifiSettings { public: ~WifiSettings(); @@ -129,18 +140,18 @@ public: /** * @Description save the p2p connected info * - * @param connInfo - WifiP2pInfo object + * @param linkedInfo - WifiP2pLinkedInfo object * @return int - 0 success */ - int SaveP2pInfo(WifiP2pInfo &connInfo); + int SaveP2pInfo(WifiP2pLinkedInfo &linkedInfo); /** * @Description Get the p2p connected info * - * @param connInfo - output the p2p connected info + * @param linkedInfo - output the p2p connected info * @return int - 0 success */ - int GetP2pInfo(WifiP2pInfo &connInfo); + int GetP2pInfo(WifiP2pLinkedInfo &linkedInfo); /** * @Description Get the scan control policy info @@ -230,13 +241,41 @@ public: * when the param bSetOther is true and the state is ENABLED, that means we need * to set other wifi device DISABLED * @param networkId - the wifi device's id - * @param state - WifiDeviceConfigStatus INVALID/CURRENT/DISABLED/ENABLED/UNKNOWN + * @param state - WifiDeviceConfigStatus DISABLED/ENABLED/UNKNOWN * @param bSetOther - whether set other device config disabled * @return int - when 0 means success, other means some fails happened, * Input state invalid or not find the wifi device config */ int SetDeviceState(int networkId, int state, bool bSetOther = false); + /** + * @Description Set a wifi device's attributes who's networkId equals input networkId after connect; + * + * @param networkId - the wifi device's id + * @return int - when 0 means success, other means some fails happened, + * Input state invalid or not find the wifi device config + */ + int SetDeviceAfterConnect(int networkId); + + /** + * @Description Get the candidate device configuration + * + * @param uid - call app uid + * @param networkId - a networkId that is to be get + * @param config - WifiDeviceConfig object + * @return int - network id + */ + int GetCandidateConfig(const int uid, const int &networkId, WifiDeviceConfig &config); + + /** + * @Description Get all the Candidate Device Configurations set key uuid + * + * @param uid - call app uid + * @param configs - WifiDeviceConfig objects + * @return int - 0 success + */ + int GetAllCandidateConfig(const int uid, std::vector &configs); + /** * @Description Synchronizing saved the wifi device config into config file * @@ -244,6 +283,20 @@ public: */ int SyncDeviceConfig(); + /** + * @Description Increments the number of reboots since last use for each configuration + * + * @return int - 0 success; -1 save file failed + */ + int IncreaseNumRebootsSinceLastUse(); + /** + * @Description Remove excess networks in case the number of saved networks exceeds the mas limit + * + * @param configs - WifiDeviceConfig objects + * @return int - 0 if networks were removed, 1 otherwise. + */ + int RemoveExcessDeviceConfigs(std::vector &configs); + /** * @Description Reload wifi device config from config file * @@ -336,6 +389,21 @@ public: */ int GetMacAddress(std::string &macAddress); + /** + * @Description reload mac address + * + * @return int - 0 success + */ + int ReloadStaRandomMac(); + + /** + * @Description add random mac address + * + * @param randomMacInfo - randmon mac address info + * @return int - 0 success + */ + bool AddRandomMac(WifiStoreRandomMac &randomMacInfo); + /** * @Description Save the country code * @@ -357,7 +425,7 @@ public: * * @return int - the hotspot state, IDLE/STARTING/STARTED/CLOSING/CLOSED */ - int GetHotspotState(); + int GetHotspotState(int id = 0); /** * @Description Save current hotspot state @@ -365,7 +433,7 @@ public: * @param state - hotspot state * @return int - 0 success */ - int SetHotspotState(int state); + int SetHotspotState(int state, int id = 0); /** * @Description Set the hotspot config @@ -373,7 +441,7 @@ public: * @param config - input HotspotConfig struct * @return int - 0 success */ - int SetHotspotConfig(const HotspotConfig &config); + int SetHotspotConfig(const HotspotConfig &config, int id = 0); /** * @Description Get the hotspot config @@ -381,7 +449,7 @@ public: * @param config - output HotspotConfig struct * @return int - 0 success */ - int GetHotspotConfig(HotspotConfig &config); + int GetHotspotConfig(HotspotConfig &config, int id = 0); /** * @Description Synchronizing saved the Hotspot config into config file @@ -419,7 +487,7 @@ public: * @param results - output StationInfo results * @return int - 0 success */ - int GetStationList(std::vector &results); + int GetStationList(std::vector &results, int id = 0); /** * @Description Management (add/update/delete) connected station list @@ -428,14 +496,14 @@ public: * @param mode - mode of MODE_ADD MODE_UPDATE MODE_DEL * @return int - 0 success; -1 mode not correct */ - int ManageStation(const StationInfo &info, int mode); /* add / update / remove */ + int ManageStation(const StationInfo &info, int mode, int id = 0); /* add / update / remove */ /** * @Description Clear connected station list * * @return int - 0 success */ - int ClearStationList(); + int ClearStationList(int id = 0); /** * @Description Get the block list @@ -443,7 +511,7 @@ public: * @param results - output StationInfo results * @return int - 0 success */ - int GetBlockList(std::vector &results); + int GetBlockList(std::vector &results, int id = 0); /** * @Description Manager (add/update/delete) station connect Blocklist @@ -452,7 +520,7 @@ public: * @param mode - mode of MODE_ADD MODE_DEL MODE_UPDATE * @return int - 0 success; -1 mode not correct */ - int ManageBlockList(const StationInfo &info, int mode); /* add / remove */ + int ManageBlockList(const StationInfo &info, int mode, int id = 0); /* add / remove */ /** * @Description Judge whether the station is in current linked station list @@ -460,7 +528,7 @@ public: * @param info - input StationInfo struct * @return int - 0 find the station, exist; -1 not find, not exist */ - int FindConnStation(const StationInfo &info); + int FindConnStation(const StationInfo &info, int id = 0); /** * @Description Synchronizing saved the block list config into config file @@ -472,7 +540,7 @@ public: /** * @Description Get the Valid Bands object * - * @param bands - output vector fo BandType + * @param bands - output vector for BandType * @return int - 0 success */ int GetValidBands(std::vector &bands); @@ -500,6 +568,22 @@ public: */ int ClearValidChannels(); + /** + * @Description Get supported power model list + * + * @param model - the model to be set + * @return ErrCode - operation result + */ + int SetPowerModel(const PowerModel& model, int id = 0); + + /** + * @Description Get power model + * + * @param model - current power model + * @return ErrCode - operation result + */ + int GetPowerModel(PowerModel& model, int id = 0); + /** * @Description set the p2p state * @@ -673,7 +757,7 @@ public: * * @return int - 1 on; 2 off */ - int GetScreenState(); + int GetScreenState() const; /** * @Description Set the Airplane Mode State @@ -687,21 +771,21 @@ public: * * @return int - 1 open; 2 close */ - int GetAirplaneModeState(); + int GetAirplaneModeState() const; /** * @Description Set the App Running State * - * @param state - 1 front; 2 backend + * @param appRunMode - app run mode */ - void SetAppRunningState(const int &state); + void SetAppRunningState(ScanMode appRunMode); /** * @Description Get the App Running State * - * @return int - 1 front; 2 backend + * @return ScanMode */ - int GetAppRunningState(); + ScanMode GetAppRunningState() const; /** * @Description Set the Power Saving Mode State @@ -715,7 +799,49 @@ public: * * @return int - 1 open; 2 close */ - int GetPowerSavingModeState(); + int GetPowerSavingModeState() const; + + /** + * @Description Set app package name. + * + * @param appPackageName - app package name + */ + void SetAppPackageName(const std::string &appPackageName); + + /** + * @Description Get app package name. + * + * @return const std::string - app package name. + */ + const std::string GetAppPackageName() const; + + /** + * @Description Set freeze mode state. + * + * @param state - 1 freeze mode; 2 moving mode + */ + void SetFreezeModeState(int state); + + /** + * @Description Get freeze mode state. + * + * @return freeze mode. + */ + int GetFreezeModeState() const; + + /** + * @Description Set no charger plugged in mode. + * + * @param state - 1 no charger plugged in mode; 2 charger plugged in mode + */ + void SetNoChargerPlugModeState(int state); + + /** + * @Description Get no charger plugged in mode. + * + * @return no charger plugged in mode. + */ + int GetNoChargerPlugModeState() const; /** * @Description Set enable/disable Whether to allow network switchover @@ -838,6 +964,21 @@ public: */ int GetScoretacticsSecurityScore(); + /** + * @Description Setting the Score Policy Candidate Score + * + * @param score - score + * @return int - 0 success + */ + int SetScoretacticsNormalScore(const int &score); + + /** + * @Description Get the Score Policy Candidate Score + * + * @return int - score + */ + int GetScoretacticsNormalScore(); + /** * @Description Set the saved device appraisal priority * @@ -889,6 +1030,19 @@ public: */ int GetMinRssi5Ghz(); + /** + * @Description Get the Alternate dns. + * + * @return string - dns + */ + std::string GetStrDnsBak() const; + /** + * @Description Obtaining Whether to Load the Configuration of the Standby STA. + * + * @return bool - Indicates whether to load the configuration of the standby STA. + */ + bool IsLoadStabak() const; + /** * @Description set the device name * @@ -897,6 +1051,68 @@ public: */ int SetP2pDeviceName(const std::string &deviceName); + /** + * @Description get trustlist policies. + * + * @return const std::vector - trustlist policies. + */ + const std::vector ReloadTrustListPolicies(); + + /** + * @Description get moving freeze state trustlist. + * + * @return const MovingFreezePolicy - moving freeze policy. + */ + const MovingFreezePolicy ReloadMovingFreezePolicy(); + + /** + * @Description get bssid of connection timeout for last time. + * + * @return bssid. + */ + std::string GetConnectTimeoutBssid(); + + /** + * @Description set bssid of connection timeout for last time. + * + * @return int - result + */ + int SetConnectTimeoutBssid(std::string &bssid); + + /** + * @Description set default frequencies for specify country band. + * + */ + void SetDefaultFrequenciesByCountryBand(const BandType band, std::vector &frequencies); + + /** + * @Description set type of GO group + * + * @param isExplicit true: created by user; false: created by auto negotiation + */ + void SetExplicitGroup(bool isExplicit); + + /** + * @Description get type of Go group + * + * @return true: created by user; false: created by auto negotiation + */ + bool IsExplicitGroup(void); + + /** + * @Description Set the thermal level + * + * @param level 0 COOL, 1 NORMAL, 2 WARM, 3 HOT, 4 OVERHEATED, 5 WARNING, 6 EMERGENCY + */ + void SetThermalLevel(const int &level); + + /** + * @Description Get the thermal level + * + * @return int 0 COOL, 1 NORMAL, 2 WARM, 3 HOT, 4 OVERHEATED, 5 WARNING, 6 EMERGENCY + */ + int GetThermalLevel() const; + private: WifiSettings(); void InitWifiConfig(); @@ -904,7 +1120,7 @@ private: void InitHotspotConfig(); void InitDefaultP2pVendorConfig(); void InitP2pVendorConfig(); - void InitGetApMaxConnNum(); + void InitSettingsNum(); void InitScanControlForbidList(); void InitScanControlIntervalList(); void InitScanControlInfo(); @@ -915,15 +1131,16 @@ private: std::atomic mScanAlwaysActive; /* if scan always */ std::vector mWifiScanInfoList; std::vector mGroupInfoList; + std::vector mWifiStoreRandomMac; ScanControlInfo mScanControlInfo; - WifiP2pInfo mWifiP2pInfo; + WifiP2pLinkedInfo mWifiP2pInfo; std::map mWifiDeviceConfig; IpInfo mWifiIpInfo; WifiLinkedInfo mWifiLinkedInfo; std::string mMacAddress; std::string mCountryCode; - std::atomic mHotspotState; - HotspotConfig mHotspotConfig; + std::map > mHotspotState; + std::map mHotspotConfig; P2pVendorConfig mP2pVendorConfig; std::map mConnectStationInfo; std::map mBlockListInfo; @@ -932,13 +1149,20 @@ private: std::atomic mP2pDiscoverState; std::atomic mP2pConnectState; int mApMaxConnNum; /* ap support max sta numbers */ + int mMaxNumConfigs; /* max saved configs numbers */ int mLastSelectedNetworkId; /* last selected networkid */ time_t mLastSelectedTimeVal; /* last selected time */ - int mScreenState; /* 1 on 2 off */ + int mScreenState; /* 1 MODE_STATE_OPEN, 2 MODE_STATE_CLOSE */ + int mThermalLevel; /* 1 COOL, 2 NORMAL, 3 WARM, 4 HOT, 5 OVERHEATED, 6 WARNING, 7 EMERGENCY */ int mAirplaneModeState; /* 1 on 2 off */ - int mAppRunningModeState; /* 1 front 2 backend */ + ScanMode mAppRunningModeState; /* 0 app for 1 app back 2 sys for 3 sys back */ int mPowerSavingModeState; /* 1 on 2 off */ + std::string mAppPackageName; + int mFreezeModeState; /* 1 on 2 off */ + int mNoChargerPlugModeState; /* 1 on 2 off */ WifiConfig mWifiConfig; + std::pair mBssidToTimeoutTime; + std::map powerModel; std::mutex mStaMutex; std::mutex mApMutex; @@ -946,13 +1170,20 @@ private: std::mutex mInfoMutex; std::mutex mP2pMutex; + std::atomic_flag deviceConfigLoadFlag = ATOMIC_FLAG_INIT; + WifiConfigFileImpl mSavedDeviceConfig; /* Persistence device config */ WifiConfigFileImpl mSavedHotspotConfig; WifiConfigFileImpl mSavedBlockInfo; WifiConfigFileImpl mSavedWifiConfig; WifiConfigFileImpl mSavedWifiP2pGroupInfo; WifiConfigFileImpl mSavedWifiP2pVendorConfig; + WifiConfigFileImpl mTrustListPolicies; + WifiConfigFileImpl mMovingFreezePolicy; + MovingFreezePolicy mFPolicy; + WifiConfigFileImpl mSavedWifiStoreRandomMac; + bool explicitGroup; }; } // namespace Wifi } // namespace OHOS -#endif \ No newline at end of file +#endif diff --git a/services/wifi_standard/wifi_framework/common/include/permission_def.h b/wifi/services/wifi_standard/wifi_framework/wifi_toolkit/include/permission_def.h similarity index 95% rename from services/wifi_standard/wifi_framework/common/include/permission_def.h rename to wifi/services/wifi_standard/wifi_framework/wifi_toolkit/include/permission_def.h index 5706ee95573c7143a37dfcc6f357b1e53a607ec8..48d76e438af54d3f9b71d32cf9de4cf8f3940447 100644 --- a/services/wifi_standard/wifi_framework/common/include/permission_def.h +++ b/wifi/services/wifi_standard/wifi_framework/wifi_toolkit/include/permission_def.h @@ -29,7 +29,6 @@ enum IsRestricted { RESTRICTED = 0, NOT_RESTRICTED = 1 }; enum IsGranted { PERMISSION_DENIED = 0, /* Not granted */ PERMISSION_GRANTED = 1, /* Granted */ - PERMISSION_FAILED = 2 /* Failed to judge permission */ }; typedef struct { diff --git a/services/wifi_standard/wifi_framework/common/include/wifi_internal_msg.h b/wifi/services/wifi_standard/wifi_framework/wifi_toolkit/include/wifi_internal_msg.h old mode 100755 new mode 100644 similarity index 87% rename from services/wifi_standard/wifi_framework/common/include/wifi_internal_msg.h rename to wifi/services/wifi_standard/wifi_framework/wifi_toolkit/include/wifi_internal_msg.h index c1cda1edea735bfc264dd2c074d2a8c8adef732e..11387e499dfc6aaca66c183ecfc1b7c23bac94f4 --- a/services/wifi_standard/wifi_framework/common/include/wifi_internal_msg.h +++ b/wifi/services/wifi_standard/wifi_framework/wifi_toolkit/include/wifi_internal_msg.h @@ -1,5 +1,5 @@ /* - * Copyright (C) 2021 Huawei Device Co., Ltd. + * Copyright (C) 2021-2022 Huawei Device Co., Ltd. * 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 @@ -16,16 +16,17 @@ #ifndef OHOS_WIFI_INTERNAL_MSG_H #define OHOS_WIFI_INTERNAL_MSG_H +#include "wifi_ap_msg.h" +#include "wifi_hid2d_msg.h" #include "wifi_msg.h" #include "wifi_p2p_msg.h" +#include "wifi_scan_msg.h" namespace OHOS { namespace Wifi { constexpr int REOPEN_STA_INTERVAL = 500; /* when reopen sta, need over last close sta time then interval */ constexpr int DEVICE_CONFIG_INDEX_SSID = 0; constexpr int DEVICE_CONFIG_INDEX_BSSID = 1; -constexpr int STATE_OPEN = 1; -constexpr int STATE_CLOSE = 2; constexpr int PRIORITY_1 = 1; constexpr int PRIORITY_2 = 2; constexpr int PRIORITY_3 = 3; @@ -36,6 +37,7 @@ constexpr int SAME_NETWORK_SCORE = 5; constexpr int FREQUENCY_5_GHZ_SCORE = 10; constexpr int LAST_SELECTION_SCORE = 120; constexpr int SECURITY_SCORE = 20; +constexpr int NORMAL_SCORE = 10; constexpr int MIN_RSSI_24GHZ = -80; constexpr int MIN_RSSI_5GHZ = -77; constexpr int RSSI_LEVEL_1_2G = -88; @@ -88,6 +90,8 @@ enum class OperateResState { DISCONNECT_DISCONNECT_FAILED, /* disconnect failed */ DISCONNECT_DISCONNECTED, /* disconnect succeed */ CONNECT_PASSWORD_WRONG, /* wrong password */ + CONNECT_CONNECTION_FULL, /* connection full */ + CONNECT_CONNECTION_REJECT, /* connection reject */ CONNECT_OBTAINING_IP, /* obtain ip */ CONNECT_OBTAINING_IP_FAILED, /* obtain ip FAILED */ CONNECT_ASSOCIATING, @@ -183,7 +187,7 @@ struct InterScanInfo { struct SingleAppForbid { int appID; ScanIntervalMode scanIntervalMode; - int lessThanIntervalNum; + int lessThanIntervalCount; time_t continueScanTime; time_t blockListScanTime; int expScanCount; @@ -192,7 +196,7 @@ struct SingleAppForbid { SingleAppForbid() { appID = 0; - lessThanIntervalNum = 0; + lessThanIntervalCount = 0; continueScanTime = 0; blockListScanTime = 0; expScanCount = 0; @@ -201,22 +205,38 @@ struct SingleAppForbid { } }; +struct CfgInfo { + CfgType type; + char* data; + int dataLen; + CfgInfo() + { + type = CfgType::CFG_INVALID; + data = nullptr; + dataLen = 0; + } +}; + struct WifiEventCallbackMsg { int msgCode; int msgData; + int id; std::string pinCode; /* wps pin mode code */ WifiLinkedInfo linkInfo; StationInfo staInfo; std::vector device; std::vector serviceInfo; - WifiP2pInfo p2pInfo; + WifiP2pLinkedInfo p2pInfo; WifiP2pDevice p2pDevice; P2pActionCallback p2pAction; + CfgInfo* cfgInfo; WifiEventCallbackMsg() { msgCode = 0; msgData = 0; + id = 0; p2pAction = P2pActionCallback::UNKNOWN; + cfgInfo = nullptr; } }; @@ -247,6 +267,7 @@ struct WifiConfig { int scoretacticsFrequency5GHzScore; int scoretacticsLastSelectionScore; int scoretacticsSecurityScore; + int scoretacticsNormalScore; bool whetherToAllowNetworkSwitchover; int dhcpIpType; std::string defaultWifiInterface; @@ -266,6 +287,8 @@ struct WifiConfig { int secondRssiLevel5G; int thirdRssiLevel5G; int fourthRssiLevel5G; + std::string strDnsBak; + bool isLoadStabak; WifiConfig() { @@ -281,6 +304,7 @@ struct WifiConfig { scoretacticsFrequency5GHzScore = FREQUENCY_5_GHZ_SCORE; scoretacticsLastSelectionScore = LAST_SELECTION_SCORE; scoretacticsSecurityScore = SECURITY_SCORE; + scoretacticsNormalScore = NORMAL_SCORE; whetherToAllowNetworkSwitchover = true; dhcpIpType = static_cast(DhcpIpType::DHCP_IPTYPE_MIX); defaultWifiInterface = "wlan0"; @@ -300,8 +324,40 @@ struct WifiConfig { secondRssiLevel5G = RSSI_LEVEL_2_5G; thirdRssiLevel5G = RSSI_LEVEL_3_5G; fourthRssiLevel5G = RSSI_LEVEL_4_5G; + strDnsBak = "8.8.8.8"; + isLoadStabak = true; + } +}; + +struct TrustListPolicy { + int sceneId = 0; /* scene id */ + std::string sceneName; /* scene name, just to read. */ + std::string trustList; /* trust list, eg: for A,B,and C,the format is A|B|C */ + + TrustListPolicy() + { + sceneId = 0; + sceneName = ""; + trustList = ""; } }; + +struct MovingFreezePolicy { + std::string trustList; /* trust list */ + + MovingFreezePolicy() + { + trustList = ""; + } +}; + +/* wifi RandomMac store */ +struct WifiStoreRandomMac { + std::string ssid; + std::string keyMgmt; + std::string peerBssid; + std::string randomMac; +}; } // namespace Wifi } // namespace OHOS #endif diff --git a/services/wifi_standard/wifi_framework/common/log/log_helper.c b/wifi/services/wifi_standard/wifi_framework/wifi_toolkit/log/log_helper.c similarity index 93% rename from services/wifi_standard/wifi_framework/common/log/log_helper.c rename to wifi/services/wifi_standard/wifi_framework/wifi_toolkit/log/log_helper.c index 045ee1761100f1f1f65b330b8bb7930c1b5a3523..1cfb8416ca53862b938b013571c148435605fe54 100644 --- a/services/wifi_standard/wifi_framework/common/log/log_helper.c +++ b/wifi/services/wifi_standard/wifi_framework/wifi_toolkit/log/log_helper.c @@ -1,5 +1,5 @@ /* - * Copyright (C) 2021 Huawei Device Co., Ltd. + * Copyright (C) 2021-2022 Huawei Device Co., Ltd. * 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 @@ -13,8 +13,10 @@ * limitations under the License. */ -#include "securec.h" #include "log_helper.h" +#include +#include +#include const int MAX_REMAIN_CHARACTER_NUM = 3; @@ -60,4 +62,4 @@ void EncryptLogMsg(const char *srcMsg, char *desMsg, int desLen) } } return; -} \ No newline at end of file +} diff --git a/services/wifi_standard/wifi_framework/common/log/log_helper.h b/wifi/services/wifi_standard/wifi_framework/wifi_toolkit/log/log_helper.h similarity index 87% rename from services/wifi_standard/wifi_framework/common/log/log_helper.h rename to wifi/services/wifi_standard/wifi_framework/wifi_toolkit/log/log_helper.h index 7a2b191c37903047c1712368a67ca2917484a14c..0a34c687cc23839233fd7774760cd544948ea799 100644 --- a/services/wifi_standard/wifi_framework/common/log/log_helper.h +++ b/wifi/services/wifi_standard/wifi_framework/wifi_toolkit/log/log_helper.h @@ -1,5 +1,5 @@ /* - * Copyright (C) 2021 Huawei Device Co., Ltd. + * Copyright (C) 2021-2022 Huawei Device Co., Ltd. * 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 @@ -16,10 +16,6 @@ #ifndef LOG_HELPER_H #define LOG_HELPER_H -#include -#include -#include - #ifdef __cplusplus extern "C" { #endif @@ -35,4 +31,4 @@ void EncryptLogMsg(const char *srcMsg, char *desMsg, int desLen); #ifdef __cplusplus } #endif -#endif /* log_helper end */ \ No newline at end of file +#endif /* log_helper end */ diff --git a/services/wifi_standard/wifi_framework/common/log/wifi_log.h b/wifi/services/wifi_standard/wifi_framework/wifi_toolkit/log/wifi_log.h similarity index 79% rename from services/wifi_standard/wifi_framework/common/log/wifi_log.h rename to wifi/services/wifi_standard/wifi_framework/wifi_toolkit/log/wifi_log.h index f0d26695fcaf42625b59f6b371d6b2dc43bfd7ec..ac8516f3d5777f9083d087f25b7c97afcc20916f 100644 --- a/services/wifi_standard/wifi_framework/common/log/wifi_log.h +++ b/wifi/services/wifi_standard/wifi_framework/wifi_toolkit/log/wifi_log.h @@ -1,5 +1,5 @@ /* - * Copyright (C) 2021 Huawei Device Co., Ltd. + * Copyright (C) 2021-2022 Huawei Device Co., Ltd. * 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 @@ -16,7 +16,11 @@ #ifndef OHOS_WIFI_LOG_H #define OHOS_WIFI_LOG_H +#ifdef OHOS_ARCH_LITE +#include "hilog/log.h" +#else #include "hilog/log_c.h" +#endif #undef LOG_TAG #define LOG_TAG "WifiFrameWork" @@ -34,4 +38,11 @@ #define LOGF(...) ((void)HiLogPrint(LOG_CORE, LOG_FATAL, LOG_DOMAIN, LOG_TAG, __VA_ARGS__)) +#ifndef CHECK_NULL_AND_RETURN +#define CHECK_NULL_AND_RETURN(ptr, retValue) \ +if (!(ptr)) { \ + LOGI("Pointer %{public}s in %{public}s is NULL!", #ptr, __func__); \ + return retValue; \ +} +#endif #endif \ No newline at end of file diff --git a/services/wifi_standard/wifi_framework/common/log/wifi_log_tags.h b/wifi/services/wifi_standard/wifi_framework/wifi_toolkit/log/wifi_log_tags.h similarity index 100% rename from services/wifi_standard/wifi_framework/common/log/wifi_log_tags.h rename to wifi/services/wifi_standard/wifi_framework/wifi_toolkit/log/wifi_log_tags.h diff --git a/services/wifi_standard/wifi_framework/common/log/wifi_logger.h b/wifi/services/wifi_standard/wifi_framework/wifi_toolkit/log/wifi_logger.h similarity index 95% rename from services/wifi_standard/wifi_framework/common/log/wifi_logger.h rename to wifi/services/wifi_standard/wifi_framework/wifi_toolkit/log/wifi_logger.h index 92d8051e4956f87c0ce77684b21c80e9767c212d..69e4746b2f830f061418f8bb3aedbf0906500d64 100644 --- a/services/wifi_standard/wifi_framework/common/log/wifi_logger.h +++ b/wifi/services/wifi_standard/wifi_framework/wifi_toolkit/log/wifi_logger.h @@ -1,5 +1,5 @@ /* - * Copyright (C) 2021 Huawei Device Co., Ltd. + * Copyright (C) 2021-2022 Huawei Device Co., Ltd. * 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 @@ -15,8 +15,12 @@ #ifndef OHOS_WIFI_LOGGER_H #define OHOS_WIFI_LOGGER_H +#ifdef OHOS_ARCH_LITE +#include "hilog/log.h" +#else #include "hilog/log_c.h" #include "hilog/log_cpp.h" +#endif #include "wifi_log_tags.h" namespace OHOS { diff --git a/wifi/services/wifi_standard/wifi_framework/wifi_toolkit/net_helper/arp_checker.cpp b/wifi/services/wifi_standard/wifi_framework/wifi_toolkit/net_helper/arp_checker.cpp new file mode 100644 index 0000000000000000000000000000000000000000..b1379748612f07b707a3f80aa4b8970b449d2d69 --- /dev/null +++ b/wifi/services/wifi_standard/wifi_framework/wifi_toolkit/net_helper/arp_checker.cpp @@ -0,0 +1,121 @@ +/* + * Copyright (C) 2022 Huawei Device Co., Ltd. + * 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 "arp_checker.h" +#include +#include +#include + +#include "securec.h" +#include "wifi_log.h" + +#ifdef LOG_TAG +#undef LOG_TAG +#endif +#define LOG_TAG "ohwifi_arp_checker" + +namespace OHOS { +namespace Wifi { +constexpr int MAX_LENGTH = 1500; + +ArpChecker::ArpChecker(std::string& ifname, std::string& hwAddr, std::string& ipAddr) +{ + uint8_t mac[ETH_ALEN + sizeof(uint32_t)]; + if (sscanf_s(hwAddr.c_str(), "%02x:%02x:%02x:%02x:%02x:%02x", + &mac[0], &mac[1], &mac[2], &mac[3], &mac[4], &mac[5]) != ETH_ALEN) { + LOGE("invalid hwAddr:%{public}s", hwAddr.c_str()); + if (memset_s(mac, sizeof(mac), 0, sizeof(mac)) != EOK) { + LOGE("ArpChecker memset fail"); + } + } + rawSocket_.CreateSocket(ifname.c_str(), ETH_P_ARP); + inet_aton(ipAddr.c_str(), &localIpAddr_); + if (memcpy_s(localHwAddr_, ETH_ALEN, mac, ETH_ALEN) != EOK) { + LOGE("ArpChecker memcpy fail"); + } + if (memset_s(l2Broadcast_, ETH_ALEN, 0xFF, ETH_ALEN) != EOK) { + LOGE("ArpChecker memset fail"); + } +} + +ArpChecker::~ArpChecker() +{ + rawSocket_.Close(); +} + +bool ArpChecker::DoArp(int& timeoutMillis, std::string& targetIp, bool& isFillSenderIp) +{ + struct in_addr destIp; + struct ArpPacket arpPacket; + + inet_aton(targetIp.c_str(), &destIp); + arpPacket.ar_hrd = htons(ARPHRD_ETHER); + arpPacket.ar_pro = htons(ETH_P_IP); + arpPacket.ar_hln = ETH_ALEN; + arpPacket.ar_pln = IPV4_ALEN; + arpPacket.ar_op = htons(ARPOP_REQUEST); + if (memcpy_s(arpPacket.ar_sha, ETH_ALEN, localHwAddr_, ETH_ALEN) != EOK) { + LOGE("DoArp memcpy fail"); + } + if (isFillSenderIp) { + if (memcpy_s(arpPacket.ar_spa, IPV4_ALEN, &localIpAddr_, sizeof(localIpAddr_)) != EOK) { + LOGE("DoArp memcpy fail"); + } + } else { + if (memset_s(arpPacket.ar_spa, IPV4_ALEN, 0, IPV4_ALEN) != EOK) { + LOGE("DoArp memset fail"); + } + } + if (memset_s(arpPacket.ar_tha, ETH_ALEN, 0, ETH_ALEN) != EOK) { + LOGE("DoArp memset fail"); + } + if (memcpy_s(arpPacket.ar_tpa, IPV4_ALEN, &destIp, sizeof(destIp)) != EOK) { + LOGE("DoArp memcpy fail"); + } + + if (rawSocket_.Send(reinterpret_cast(&arpPacket), sizeof(arpPacket), l2Broadcast_) != 0) { + LOGE("send arp fail"); + return false; + } + + int readLen = 0; + uint64_t elapsed = 0; + int leftMillis = timeoutMillis; + uint8_t recvBuff[MAX_LENGTH]; + std::chrono::steady_clock::time_point startTime = std::chrono::steady_clock::now(); + while (leftMillis > 0) { + readLen = rawSocket_.Recv(recvBuff, sizeof(recvBuff), leftMillis); + if (readLen >= static_cast(sizeof(struct ArpPacket))) { + struct ArpPacket *respPacket = reinterpret_cast(recvBuff); + if (ntohs(respPacket->ar_hrd) == ARPHRD_ETHER && + ntohs(respPacket->ar_pro) == ETH_P_IP && + respPacket->ar_hln == ETH_ALEN && + respPacket->ar_pln == IPV4_ALEN && + ntohs(respPacket->ar_op) == ARPOP_REPLY && + memcmp(respPacket->ar_sha, localHwAddr_, ETH_ALEN) != 0 && + memcmp(respPacket->ar_spa, &destIp, IPV4_ALEN) == 0) { + LOGE("doArp() return true"); + return true; + } + } + std::chrono::steady_clock::time_point current = std::chrono::steady_clock::now(); + elapsed = std::chrono::duration_cast(current - startTime).count(); + leftMillis -= static_cast(elapsed); + } + LOGE("doArp() return false"); + return false; +} +} +} diff --git a/wifi/services/wifi_standard/wifi_framework/wifi_toolkit/net_helper/arp_checker.h b/wifi/services/wifi_standard/wifi_framework/wifi_toolkit/net_helper/arp_checker.h new file mode 100644 index 0000000000000000000000000000000000000000..c6f417604160451f7b0208a12d7061d5f668b2a4 --- /dev/null +++ b/wifi/services/wifi_standard/wifi_framework/wifi_toolkit/net_helper/arp_checker.h @@ -0,0 +1,54 @@ +/* + * Copyright (C) 2022 Huawei Device Co., Ltd. + * 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 OHOS_WIFI_ARP_CHECKER_H +#define OHOS_WIFI_ARP_CHECKER_H +#include +#include +#include + +#include "raw_socket.h" + +namespace OHOS { +namespace Wifi { +constexpr int IPV4_ALEN = 4; + +/* defined in RFC 826 */ +struct ArpPacket { + uint16_t ar_hrd; // hardware type + uint16_t ar_pro; // protocol type + uint8_t ar_hln; // length of hardware address + uint8_t ar_pln; // length of protocol address + uint16_t ar_op; // opcode + uint8_t ar_sha[ETH_ALEN]; // sender hardware address + uint8_t ar_spa[IPV4_ALEN]; // sender protocol address + uint8_t ar_tha[ETH_ALEN]; // target hardware address + uint8_t ar_tpa[IPV4_ALEN]; // target protocol address +} __attribute__ ((__packed__)); + +class ArpChecker { +public: + ArpChecker(std::string& ifname, std::string& hwAddr, std::string& ipAddr); + ~ArpChecker(); + bool DoArp(int& timeoutMillis, std::string& targetIp, bool& isFillSenderIp); +private: + RawSocket rawSocket_; + struct in_addr localIpAddr_; + uint8_t localHwAddr_[ETH_ALEN]; + uint8_t l2Broadcast_[ETH_ALEN]; +}; +} +} +#endif diff --git a/services/wifi_standard/wifi_framework/common/net_helper/base_address.cpp b/wifi/services/wifi_standard/wifi_framework/wifi_toolkit/net_helper/base_address.cpp similarity index 94% rename from services/wifi_standard/wifi_framework/common/net_helper/base_address.cpp rename to wifi/services/wifi_standard/wifi_framework/wifi_toolkit/net_helper/base_address.cpp index f7cb1e5ebbc4138caadc42425fa355bd61e1d452..469eca2972a9bf2d1a0aaff4d7f9e6e4089d8fa6 100644 --- a/services/wifi_standard/wifi_framework/common/net_helper/base_address.cpp +++ b/wifi/services/wifi_standard/wifi_framework/wifi_toolkit/net_helper/base_address.cpp @@ -1,5 +1,5 @@ /* - * Copyright (C) 2021 Huawei Device Co., Ltd. + * Copyright (C) 2021-2022 Huawei Device Co., Ltd. * 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 @@ -14,7 +14,7 @@ */ #include "base_address.h" -#include "log_helper.h" +#include #include "wifi_log.h" #undef LOG_TAG @@ -55,4 +55,4 @@ void BaseAddress::Dump() const LOGI("TYPE: [%{public}s] address [%s/%zu]", ipType.c_str(), ipAddress_.c_str(), prefixLength_); } } // namespace Wifi -} // namespace OHOS \ No newline at end of file +} // namespace OHOS diff --git a/services/wifi_standard/wifi_framework/common/net_helper/base_address.h b/wifi/services/wifi_standard/wifi_framework/wifi_toolkit/net_helper/base_address.h similarity index 96% rename from services/wifi_standard/wifi_framework/common/net_helper/base_address.h rename to wifi/services/wifi_standard/wifi_framework/wifi_toolkit/net_helper/base_address.h index 7fb44ee3132a7e20329c5bd63e0e460f58afbacf..b30f2357ea047fe8a8acafce28c7aec6a94441ee 100644 --- a/services/wifi_standard/wifi_framework/common/net_helper/base_address.h +++ b/wifi/services/wifi_standard/wifi_framework/wifi_toolkit/net_helper/base_address.h @@ -1,5 +1,5 @@ /* - * Copyright (C) 2021 Huawei Device Co., Ltd. + * Copyright (C) 2021-2022 Huawei Device Co., Ltd. * 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 @@ -16,8 +16,9 @@ #ifndef OHOS_BASE_ADDRESS_H #define OHOS_BASE_ADDRESS_H -#include +#include #include +#include namespace OHOS { namespace Wifi { @@ -128,4 +129,4 @@ private: } // namespace Wifi } // namespace OHOS -#endif /* OHOS_BASE_ADDRESS_H */ \ No newline at end of file +#endif /* OHOS_BASE_ADDRESS_H */ diff --git a/services/wifi_standard/wifi_framework/common/net_helper/dhcpd_interface.cpp b/wifi/services/wifi_standard/wifi_framework/wifi_toolkit/net_helper/dhcpd_interface.cpp similarity index 93% rename from services/wifi_standard/wifi_framework/common/net_helper/dhcpd_interface.cpp rename to wifi/services/wifi_standard/wifi_framework/wifi_toolkit/net_helper/dhcpd_interface.cpp index aeb51a5748099cefdb8a583ec083a8c48926d033..f7fa8f240aff8e1d0088d997f117ecb19fe67b3c 100644 --- a/services/wifi_standard/wifi_framework/common/net_helper/dhcpd_interface.cpp +++ b/wifi/services/wifi_standard/wifi_framework/wifi_toolkit/net_helper/dhcpd_interface.cpp @@ -1,5 +1,5 @@ /* - * Copyright (C) 2021 Huawei Device Co., Ltd. + * Copyright (C) 2021-2022 Huawei Device Co., Ltd. * 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 @@ -12,30 +12,28 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + #include "dhcpd_interface.h" -#include #include - +#include +#include "dhcp_define.h" +#include "dhcp_service.h" #include "network_interface.h" #include "wifi_global_func.h" -#include "dhcpd_interface.h" #include "wifi_logger.h" -#include "dhcp_service.h" DEFINE_WIFILOG_DHCP_LABEL("WifiDhcpdInterface"); namespace OHOS { namespace Wifi { -const std::string IP_V4_MASK("255.255.255.0"); -const std::string IP_V4_DEFAULT("192.168.1.2"); const int EU_I64_ADDR_LEN = 64; const int GENE_V6_ADDR_LEN = 64; /* Generally, the prefix length cannot exceed 64 characters. */ const int IP_V6_ADDR_LEN = 128; const int MAC_ADDR_MAX_LEN = 17; const int DHCP_LEASE_FORMAT_SIZE = 5; -const int DHCP_LEASE_MAC_ADDR_POS = 1; -const int DHCP_LEASE_IP_ADDR_POS = 2; -const int DHCP_LEASE_HOSTNAME_POS = 3; +const int DHCP_LEASE_MAC_ADDR_POS = 0; +const int DHCP_LEASE_IP_ADDR_POS = 1; +const int DHCP_LEASE_HOSTNAME_POS = 2; DhcpdInterface::DhcpdInterface() : mBindIpv4(Ipv4Address::INVALID_INET_ADDRESS), mBindIpv6(Ipv6Address::INVALID_INET6_ADDRESS) @@ -50,13 +48,15 @@ DhcpdInterface::~DhcpdInterface() bool DhcpdInterface::SetDhcpEventFunc(const std::string &ifaceName, IDhcpResultNotify* pResultNotify) { - if (ifaceName.empty() || pResultNotify == nullptr || mDhcpService == nullptr) { + if (pResultNotify == nullptr) { + WIFI_LOGE("pResultNotify == nullptr, don't register dhcp exit notify event!"); return false; } - if (!mDhcpService->GetDhcpSerProExit(ifaceName, pResultNotify)) { - return true; + if (ifaceName.empty() || mDhcpService == nullptr) { + WIFI_LOGE("SetDhcpEventFunc parameter error!"); + return false; } - return false; + return (mDhcpService->GetDhcpSerProExit(ifaceName, pResultNotify) == DHCP_OPT_SUCCESS); } bool DhcpdInterface::StartDhcpServer(const std::string &ifaceName, Ipv4Address &ipv4, Ipv6Address &ipv6, bool isIpV4) @@ -111,7 +111,7 @@ bool DhcpdInterface::SetDhcpIpRange(const std::string &ifaceName) std::string ipAddr = mBindIpv4.GetAddressWithString(); std::string::size_type pos = ipAddr.rfind("."); if (pos == std::string::npos) { - WIFI_LOGE("invalid ip address[%{public}s]!", ipAddr.c_str()); + WIFI_LOGE("invalid ip address[%{private}s]!", ipAddr.c_str()); return false; } std::string ipHead = ipAddr.substr(0, pos); @@ -210,7 +210,7 @@ bool DhcpdInterface::StopDhcpServer(const std::string &ifaceName) } if (mDhcpService->StopDhcpServer(ifaceName) != 0) { - WIFI_LOGE("Stop dhcp server failed!"); + WIFI_LOGE("Dhcp server stop failed or already stopped!"); return false; } if (!NetworkInterface::ClearAllIpAddress(ifaceName)) { @@ -270,7 +270,7 @@ bool DhcpdInterface::CompareSubNet( for (auto address : vecIpAddr) { struct in_addr tmpAddr = {INADDR_ANY}; if (inet_aton(address.GetAddressWithString().c_str(), &tmpAddr) == 0) { - WIFI_LOGE("convert ipaddress [%s] failed!", address.GetAddressWithString().c_str()); + WIFI_LOGE("convert ipaddress %{private}s failed!", address.GetAddressWithString().c_str()); return true; } if (CALC_SUBNET(tmpAddr.s_addr, mask.s_addr) == input.s_addr) { @@ -329,7 +329,7 @@ Ipv6Address DhcpdInterface::AssignIpAddrV6(const std::vector &vecIp WIFI_LOGI("IpAddr:bad ip:%s and inet_pton error.", address.GetAddressWithString().c_str()); continue; } - if (memcmp(&tmpAddr, &prefix, GENE_V6_ADDR_LEN) == 0) { + if (memcmp(&tmpAddr, &prefix, sizeof(in6_addr)) == 0) { bFlag = false; WIFI_LOGI("same IP: %x and %x.", tmpAddr.s6_addr32[0], tmpAddr.s6_addr32[1]); break; diff --git a/services/wifi_standard/wifi_framework/common/net_helper/dhcpd_interface.h b/wifi/services/wifi_standard/wifi_framework/wifi_toolkit/net_helper/dhcpd_interface.h similarity index 97% rename from services/wifi_standard/wifi_framework/common/net_helper/dhcpd_interface.h rename to wifi/services/wifi_standard/wifi_framework/wifi_toolkit/net_helper/dhcpd_interface.h index 4fd9cc7ae284142d155acd86720dd6b6e2314ba0..7dac1b3a100a23b560f46ceb82e25c307628f1a7 100644 --- a/services/wifi_standard/wifi_framework/common/net_helper/dhcpd_interface.h +++ b/wifi/services/wifi_standard/wifi_framework/wifi_toolkit/net_helper/dhcpd_interface.h @@ -1,5 +1,5 @@ /* - * Copyright (C) 2021 Huawei Device Co., Ltd. + * Copyright (C) 2021-2022 Huawei Device Co., Ltd. * 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 @@ -12,6 +12,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + #ifndef OHOS_DHCPD_INTERFACE_H #define OHOS_DHCPD_INTERFACE_H #include @@ -22,7 +23,7 @@ #include "ipv4_address.h" #include "ipv6_address.h" #include "mac_address.h" -#include "wifi_msg.h" +#include "wifi_ap_msg.h" #include "i_dhcp_service.h" #define IP_V4 0 diff --git a/services/wifi_standard/wifi_framework/common/net_helper/http_request.cpp b/wifi/services/wifi_standard/wifi_framework/wifi_toolkit/net_helper/http_request.cpp similarity index 69% rename from services/wifi_standard/wifi_framework/common/net_helper/http_request.cpp rename to wifi/services/wifi_standard/wifi_framework/wifi_toolkit/net_helper/http_request.cpp index 75f22636b1b3004d85d970d55d207feabe1dadbc..213495bd364a9e2ddff306d1b2baeb11d861a24c 100644 --- a/services/wifi_standard/wifi_framework/common/net_helper/http_request.cpp +++ b/wifi/services/wifi_standard/wifi_framework/wifi_toolkit/net_helper/http_request.cpp @@ -14,7 +14,12 @@ */ #include "http_request.h" +#include +#include +#include +#include "securec.h" #include "wifi_log.h" + #undef LOG_TAG #define LOG_TAG "OHWIFI_UTILS_HTTP_REQ" @@ -78,12 +83,16 @@ int HttpRequest::HttpRequestExec( GetPortFromUrl(); if (iPort < 0) { LOGE("HttpRequest::HttpRequestExec get port failed from URL!\n"); + close(mISocketFd); + mISocketFd = INVALID_SOCKET; return -1; } iRet = GetIPFromUrl(); if (iRet != 0) { LOGE("HttpRequest::HttpRequestExec get ip failed from URL!\n"); + close(mISocketFd); + mISocketFd = INVALID_SOCKET; return -1; } @@ -92,8 +101,13 @@ int HttpRequest::HttpRequestExec( iRet = HttpConnect(strResponse); if (iRet != 0) { LOGE("HttpRequest::HttpConnect failed!\n"); + close(mISocketFd); + mISocketFd = INVALID_SOCKET; return -1; } + close(mISocketFd); + mISocketFd = INVALID_SOCKET; + LOGD("HttpRequest::HttpConnect success!\n"); return 0; } @@ -188,24 +202,49 @@ int HttpRequest::HttpDataTransmit(const int &iSockFd) if (buf == nullptr) { return -1; } + constexpr int timeoutMs = 500; + constexpr int timeRate = 1000; + struct timeval tv; + struct timeval tvEnd; + gettimeofday(&tv, nullptr); + long long tvTime = tv.tv_sec * timeRate + tv.tv_usec / timeRate; + long long tvEndTime; + bool bDataRec = false; while (1) { + gettimeofday(&tvEnd, nullptr); + tvEndTime = tvEnd.tv_sec * timeRate + tvEnd.tv_usec / timeRate; + if (tvEndTime - tvTime > timeoutMs) { + LOGE("HttpRequest::HttpDataTransmit recv timeout\n"); + delete[] buf; + buf = nullptr; + return -1; + } + (void)memset_s(buf, BUFSIZE, 0, BUFSIZE); ret = recv(iSockFd, buf, BUFSIZE, 0); if (ret == 0) { /* The connection is closed. */ - LOGE("HttpRequest::HttpDataTransmit recv error! Error code: %{public}d", errno); - delete[] buf; - return -1; + if (!bDataRec) { + LOGE("HttpRequest::HttpDataTransmit recv error! Error code: %{public}d", errno); + delete[] buf; + buf = nullptr; + return -1; + } else { + LOGD("HttpRequest::HttpDataTransmit recv success\n"); + delete[] buf; + return 0; + } } else if (ret > 0) { - strRes = buf; - delete[] buf; - return 0; + bDataRec = true; + strRes += buf; } else if (ret < 0) { /* Error */ if (errno == EINTR || errno == EWOULDBLOCK || errno == EAGAIN) { + LOGE("HttpRequest::HttpDataTransmit recv not finish!\n"); continue; } else { LOGE("HttpRequest::HttpDataTransmit recv error! Error code: %{public}d", errno); delete[] buf; + buf = nullptr; return -1; } } @@ -246,6 +285,43 @@ void HttpRequest::GetPortFromUrl() } } +std::mutex gMutex; +std::unordered_set gHostDataSet; +void GetHostThread(HostData* pThreadData) +{ + std::string ipOrDomain; + { + std::unique_lock lck(gMutex); + if (gHostDataSet.find(pThreadData) == gHostDataSet.end()) { + LOGE("GetHostThread Error."); + return; + } + ipOrDomain = pThreadData->strIpOrDomain; + } + hostent *he = gethostbyname(ipOrDomain.c_str()); + if (he == nullptr) { + { + std::unique_lock lck(gMutex); + if (gHostDataSet.find(pThreadData) != gHostDataSet.end()) { + LOGD("GetHostThread delete."); + gHostDataSet.erase(pThreadData); + delete pThreadData; + pThreadData = nullptr; + } + } + LOGE("GetIPFromUrl Url is wrong. error message:[%s]\n", hstrerror(h_errno)); + } else { + std::unique_lock lck(gMutex); + in_addr **addr_list = (in_addr **)he->h_addr_list; + for (int i = 0; addr_list[i] != nullptr; i++) { + pThreadData->strIp = inet_ntoa(*addr_list[i]); + } + pThreadData->bIp = true; + pThreadData->mWait_timeout.notify_one(); + } + return; +} + int HttpRequest::GetIPFromUrl() { std::string strIpOrDomain; @@ -260,23 +336,52 @@ int HttpRequest::GetIPFromUrl() } if (inet_addr(strIpOrDomain.c_str()) == INADDR_NONE) { - /* Incorrect IP address format. */ - LOGI("GetIPFromUrl Url maybe contain Domain\n"); - struct hostent *he = gethostbyname(strIpOrDomain.c_str()); - if (he == nullptr) { - LOGE("GetIPFromUrl Url is wrong."); - return -1; - } else { - struct in_addr **addrList = reinterpret_cast(he->h_addr_list); - for (int i = 0; addrList[i] != nullptr; i++) { - char ipStr[MAX_IP_STRING_LENGTH] = {0}; - if (inet_ntop(AF_INET, addrList[i], ipStr, sizeof(ipStr)) == nullptr) { - continue; + LOGI("GetIPFromUrl Url maybe contain Domain."); + HostData* pData = nullptr; + { + std::unique_lock lck(gMutex); + pData = new HostData; + if (pData == nullptr) { + LOGE("GetIPFromUrl new HostData error.\n"); + return -1; + } + gHostDataSet.emplace(pData); + pData->strIpOrDomain = strIpOrDomain; + } + + int iRlt = -1; + std::thread getHost = std::thread(&GetHostThread, pData); + getHost.detach(); + + bool bTimeOut = false; + const int timeoutMs = 150; + { + std::unique_lock lck(gMutex); + if (pData->mWait_timeout.wait_for(lck, std::chrono::milliseconds(timeoutMs)) == std::cv_status::timeout) { + bTimeOut = true; + } + } + + if (!bTimeOut) { + std::unique_lock lck(gMutex); + if (gHostDataSet.find(pData) == gHostDataSet.end()) { + if (pData != nullptr) { + delete pData; + pData = nullptr; } - strIp = std::string(ipStr); + LOGD("GetHostThread None."); + return -1; + } + if (pData->bIp) { + iRlt = 0; + strIp = pData->strIp; + gHostDataSet.erase(pData); + delete pData; + pData = nullptr; + LOGD("Get ip ok."); } - return 0; } + return iRlt; } else { LOGI("GetIPFromUrl Url contain ip\n"); strIp = strIpOrDomain; diff --git a/services/wifi_standard/wifi_framework/common/net_helper/http_request.h b/wifi/services/wifi_standard/wifi_framework/wifi_toolkit/net_helper/http_request.h similarity index 90% rename from services/wifi_standard/wifi_framework/common/net_helper/http_request.h rename to wifi/services/wifi_standard/wifi_framework/wifi_toolkit/net_helper/http_request.h index 5e1a328b5bee3e413752e3d5d0a2197fa35c69e5..b18aef444e7d1fd4d7722ed443712fdfaebcc0b4 100644 --- a/services/wifi_standard/wifi_framework/common/net_helper/http_request.h +++ b/wifi/services/wifi_standard/wifi_framework/wifi_toolkit/net_helper/http_request.h @@ -21,22 +21,23 @@ #include #include #include -#include -#include #include #include #include #include #include +#include +#include +#include -constexpr int BUFSIZE = 41000; -constexpr int URLSIZE = 1024; -constexpr int INVALID_SOCKET = -1; -constexpr int HTTP_HEADER_LENGTH = 7; -constexpr int HTTPS_HEADER_LENGTH = 8; -constexpr int DEFAULT_PORT = 80; -constexpr int SEND_HTTP_DELAY_TIME = 6; -constexpr int MAX_IP_STRING_LENGTH = 64; +#define BUFSIZE 1024 +#define URLSIZE 1024 +#define INVALID_SOCKET (-1) + +const int HTTP_HEADER_LENGTH = 7; +const int HTTPS_HEADER_LENGTH = 8; +const int DEFAULT_PORT = 80; +const int SEND_HTTP_DELAY_TIME = 1; namespace OHOS { namespace Wifi { @@ -152,6 +153,12 @@ private: std::string strParam; std::string httpHead; }; -} // namespace Wifi -} // namespace OHOS +struct HostData { + bool bIp = false; + std::string strIp; + std::string strIpOrDomain; + std::condition_variable mWait_timeout; +}; +} +} /* namespace OHOS */ #endif \ No newline at end of file diff --git a/services/wifi_standard/wifi_framework/wifi_manage/wifi_sta/net_conf/if_config.cpp b/wifi/services/wifi_standard/wifi_framework/wifi_toolkit/net_helper/if_config.cpp old mode 100755 new mode 100644 similarity index 75% rename from services/wifi_standard/wifi_framework/wifi_manage/wifi_sta/net_conf/if_config.cpp rename to wifi/services/wifi_standard/wifi_framework/wifi_toolkit/net_helper/if_config.cpp index 69910b48516d389add4208079edf4c6c7208ff5f..a3d2589d99a08e79b04f61e4bb2c86917084d014 --- a/services/wifi_standard/wifi_framework/wifi_manage/wifi_sta/net_conf/if_config.cpp +++ b/wifi/services/wifi_standard/wifi_framework/wifi_toolkit/net_helper/if_config.cpp @@ -1,5 +1,5 @@ /* - * Copyright (C) 2021 Huawei Device Co., Ltd. + * Copyright (C) 2021-2022 Huawei Device Co., Ltd. * 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 @@ -26,16 +26,20 @@ #include "securec.h" #include "if_config.h" #include "ip_tools.h" +#include namespace OHOS { namespace Wifi { const std::string SYSTEM_COMMAND_IP = "/system/bin/ip"; +const int SYSTEM_COMMAND_ERR = -1; +const int SYSTEM_NOT_EXECUTED = 127; +const int RECEIVE_BUFFER_LEN = 64; +#ifdef OHOS_ARCH_LITE const std::string SYSTEM_COMMAND_NDC = "/system/bin/ndc"; const std::string IFNAME = "wlan0"; -const int SYSTEM_COMMAND_ERR_1 = -1; -const int SYSTEM_COMMAND_ERR_2 = 127; const int IPV6_SUFFIX_LEN = 3; const int MAX_IFNAME_LEN = 13; +#endif IfConfig &IfConfig::GetInstance() { @@ -49,66 +53,51 @@ IfConfig::IfConfig() IfConfig::~IfConfig() {} -/** - * @Description : Execute script commands - * @Return success:true failed:false - */ -bool IfConfig::ExecCommand(const std::vector &vecCommandArg) +bool IfConfig::SyncExecuteCommand(const std::string& cmd) { - std::string command; - for (auto iter : vecCommandArg) { - command += iter; - command += " "; - } - LOGI("exec cmd: [%s]", command.c_str()); - int ret = system(command.c_str()); - if (ret == SYSTEM_COMMAND_ERR_1 || ret == SYSTEM_COMMAND_ERR_2) { - LOGE("exec failed. cmd: %s, error:%{public}d", command.c_str(), errno); + int ret = system(cmd.c_str()); + if (ret == SYSTEM_COMMAND_ERR || ret == SYSTEM_NOT_EXECUTED) { + LOGE("exec failed. cmd: %s, error:%{public}d", cmd.c_str(), errno); return false; } - + LOGI("Exec cmd end - sync"); return true; } -/** - * @Description : Set the network card address, routing, DNS - * @Return success:0 failed:-1 - */ -int IfConfig::SetIfAddr(const DhcpResult &dhcpResult, int ipType) +bool IfConfig::AsyncExecuteCommand(const std::string& cmd) { - LOGD("ipType=%d, ip=%s, gateway=%s, subnet=%s, strDns1=%s, strDns2=%s", - dhcpResult.iptype, - dhcpResult.strYourCli.c_str(), - dhcpResult.strSubnet.c_str(), - dhcpResult.strRouter1.c_str(), - dhcpResult.strDns1.c_str(), - dhcpResult.strDns2.c_str()); - SetNetDns(IFNAME, dhcpResult.strDns1, dhcpResult.strDns2); - FlushIpAddr(IFNAME, ipType); - AddIpAddr(IFNAME, dhcpResult.strYourCli, dhcpResult.strSubnet, ipType); - AddIfRoute(IFNAME, dhcpResult.strYourCli, dhcpResult.strSubnet, dhcpResult.strRouter1, ipType); - LOGI("set addr succeed!"); - return 0; + std::thread t( + [cmd]() { + FILE *fp = nullptr; + char buffer[RECEIVE_BUFFER_LEN]; + if ((fp = popen(cmd.c_str(), "r")) != nullptr) { + while (fgets(buffer, sizeof(buffer), fp) != nullptr) { + LOGD("exec cmd receive: %{public}s", buffer); + } + pclose(fp); + } else { + LOGE("exec cmd popen error!"); + } + LOGI("Exec cmd end - async"); + } + ); + t.detach(); + return true; } /** - * @Description : Set DNS - * @Return None + * @Description : Execute script commands + * @Return success:true failed:false */ -void IfConfig::SetNetDns(const std::string& ifName, const std::string& dns1, const std::string& dns2) +bool IfConfig::ExecCommand(const std::vector &vecCommandArg) { - std::vector ipRouteCmd; - ipRouteCmd.clear(); - ipRouteCmd.push_back(SYSTEM_COMMAND_NDC); - ipRouteCmd.push_back("resolver"); - ipRouteCmd.push_back("setnetdns"); - ipRouteCmd.push_back(ifName); - ipRouteCmd.push_back(""); - ipRouteCmd.push_back(dns1); - ipRouteCmd.push_back(dns2); - ExecCommand(ipRouteCmd); - - return; + std::string command; + for (auto iter : vecCommandArg) { + command += iter; + command += " "; + } + LOGI("Exec cmd start: [%s]", command.c_str()); + return AsyncExecuteCommand(command); } /** @@ -117,13 +106,15 @@ void IfConfig::SetNetDns(const std::string& ifName, const std::string& dns1, con */ void IfConfig::FlushIpAddr(const std::string& ifName, const int& ipType) { - if (ipType != static_cast(StaIpType::IPTYPE_IPV4)) { + LOGI("Flush IP, ifName: %{public}s", ifName.c_str()); + + if (ipType != static_cast(IpType::IPTYPE_IPV4)) { return; } struct ifreq ifr; if (memset_s(&ifr, sizeof(ifr), 0, sizeof(ifr)) != EOK || strcpy_s(ifr.ifr_name, sizeof(ifr.ifr_name), ifName.c_str()) != EOK) { - LOGE("Init the ifreq stuct failed!"); + LOGE("Init the ifreq struct failed!"); return; } int fd = socket(AF_INET, SOCK_DGRAM, 0); @@ -155,7 +146,12 @@ void IfConfig::FlushIpAddr(const std::string& ifName, const int& ipType) void IfConfig::AddIpAddr( const std::string &ifName, const std::string &ipAddr, const std::string &mask, const int &ipType) { - if (ipType == static_cast(StaIpType::IPTYPE_IPV4)) { + LOGI("Add ip address, ifName = %{public}s", ifName.c_str()); + + if (!CheckIfaceValid(ifName)) { + return; + } + if (ipType == static_cast(IpType::IPTYPE_IPV4)) { struct ifreq ifr; if (memset_s(&ifr, sizeof(ifr), 0, sizeof(ifr)) != EOK || strcpy_s(ifr.ifr_name, sizeof(ifr.ifr_name), ifName.c_str()) != EOK) { @@ -213,6 +209,124 @@ void IfConfig::AddIpAddr( return; } +/** + * @Description : set proxy + * @param isAuto - whether to automatically proxy[in] + * @param proxy - proxy host name[in] + * @param port - port[in] + * @param noProxys - objects to bypass proxy[in] + * @Return None + */ +void IfConfig::SetProxy( + bool isAuto, const std::string &proxy, const std::string &port, const std::string &noProxys, const std::string &pac) +{ + LOGI("SetProxy pac=[%s]\n", pac.c_str()); + std::vector ipRouteCmd; + + if (!isAuto) { + // Add proxy + if (!proxy.empty()) { + ipRouteCmd.clear(); + ipRouteCmd.push_back("export"); + ipRouteCmd.push_back("http_proxy=" + proxy + ":" + port); + ExecCommand(ipRouteCmd); + } + + // Bypass proxy + if (!noProxys.empty()) { + ipRouteCmd.clear(); + ipRouteCmd.push_back("export"); + ipRouteCmd.push_back("no_proxy=" + noProxys); + ExecCommand(ipRouteCmd); + } + } + return; +} + +bool IfConfig::GetIpAddr(const std::string& ifName, std::string& ipAddr) +{ + struct ifreq ifr; + if (memset_s(&ifr, sizeof(ifr), 0, sizeof(ifr)) != EOK || + strcpy_s(ifr.ifr_name, sizeof(ifr.ifr_name), ifName.c_str()) != EOK) { + LOGE("set ifr info failed!"); + return false; + } + int fd = socket(AF_INET, SOCK_DGRAM, 0); + if (fd < 0) { + LOGE("socket error\n"); + return false; + } + if (ioctl(fd, SIOCGIFADDR, &ifr) < 0) { + perror("ioctl error!\n"); + close(fd); + return false; + } + struct sockaddr_in *sin = reinterpret_cast(&ifr.ifr_addr); + ipAddr = inet_ntoa(sin->sin_addr); + close(fd); + return true; +} + +bool IfConfig::CheckIfaceValid(const std::string& ifname) +{ + struct if_nameindex *ifidxs, *ifni; + + ifidxs = if_nameindex(); + if (ifidxs == nullptr) { + LOGE("can not get interfaces"); + return false; + } + for (ifni = ifidxs; !(ifni->if_index == 0 && ifni->if_name == nullptr); ifni++) { + if (strncmp(ifni->if_name, ifname.c_str(), strlen(ifni->if_name)) == 0) { + if_freenameindex(ifidxs); + return true; + } + } + if_freenameindex(ifidxs); + LOGE("invalid interface: %{public}s", ifname.c_str()); + return false; +} + +#ifdef OHOS_ARCH_LITE +/** + * @Description : Set the network card routing, DNS + * @Return success:0 failed:-1 + */ +int IfConfig::SetIfDnsAndRoute(const DhcpResult &dhcpResult, int ipType) +{ + LOGD("ipType=%d, ip=%s, gateway=%s, subnet=%s, strDns1=%s, strDns2=%s", + dhcpResult.iptype, + dhcpResult.strYourCli.c_str(), + dhcpResult.strSubnet.c_str(), + dhcpResult.strRouter1.c_str(), + dhcpResult.strDns1.c_str(), + dhcpResult.strDns2.c_str()); + SetNetDns(IFNAME, dhcpResult.strDns1, dhcpResult.strDns2); + AddIfRoute(IFNAME, dhcpResult.strYourCli, dhcpResult.strSubnet, dhcpResult.strRouter1, ipType); + LOGI("set dns and route finished!"); + return 0; +} + +/** + * @Description : Set DNS + * @Return None + */ +void IfConfig::SetNetDns(const std::string& ifName, const std::string& dns1, const std::string& dns2) +{ + std::vector ipRouteCmd; + ipRouteCmd.clear(); + ipRouteCmd.push_back(SYSTEM_COMMAND_NDC); + ipRouteCmd.push_back("resolver"); + ipRouteCmd.push_back("setnetdns"); + ipRouteCmd.push_back(ifName); + ipRouteCmd.push_back(""); + ipRouteCmd.push_back(dns1); + ipRouteCmd.push_back(dns2); + ExecCommand(ipRouteCmd); + + return; +} + /** * @Description : Add Route * @Return None @@ -220,7 +334,7 @@ void IfConfig::AddIpAddr( void IfConfig::AddIfRoute(const std::string &ifName, const std::string &ipAddr, const std::string &mask, const std::string &gateWay, const int &ipType) { - if (ipType == static_cast(StaIpType::IPTYPE_IPV4)) { + if (ipType == static_cast(IpType::IPTYPE_IPV4)) { AddIpv4Route(ifName, ipAddr, mask, gateWay); } else { AddIpv6Route(ifName, ipAddr, mask, gateWay); @@ -235,7 +349,7 @@ void IfConfig::AddIfRoute(const std::string &ifName, const std::string &ipAddr, void IfConfig::AddIpv4Route( const std::string &ifName, const std::string &ipAddr, const std::string &mask, const std::string &gateWay) { - LOGI("Enter AddIpv4Route, ifName is %s, ipAddr is %s, mask is %s, gateWay is %s", + LOGI("Enter AddIpv4Route, ifName is %{public}s, ipAddr is %{private}s, mask is %s, gateWay is %{private}s", ifName.c_str(), ipAddr.c_str(), mask.c_str(), @@ -334,40 +448,6 @@ void IfConfig::AddIpv6Route( ipRouteCmd.push_back("-6 route flush cache"); ExecCommand(ipRouteCmd); } - -/** - * @Description : set proxy - * @param isAuto - whether to automatically proxy[in] - * @param proxy - proxy host name[in] - * @param port - port[in] - * @param noProxys - objects to bypass proxy[in] - * @Return None - */ -void IfConfig::SetProxy( - bool isAuto, const std::string &proxy, const std::string &port, const std::string &noProxys, const std::string &pac) -{ - LOGI("SetProxy pac=[%s]\n", pac.c_str()); - std::vector ipRouteCmd; - - if (!isAuto) { - // Add proxy - if (!proxy.empty()) { - ipRouteCmd.clear(); - ipRouteCmd.push_back("export"); - ipRouteCmd.push_back("http_proxy=" + proxy + ":" + port); - ExecCommand(ipRouteCmd); - } - - // Bypass proxy - if (!noProxys.empty()) { - ipRouteCmd.clear(); - ipRouteCmd.push_back("export"); - ipRouteCmd.push_back("no_proxy=" + noProxys); - ExecCommand(ipRouteCmd); - } - } - - return; -} +#endif } // namespace Wifi -} // namespace OHOS \ No newline at end of file +} // namespace OHOS diff --git a/services/wifi_standard/wifi_framework/wifi_manage/wifi_sta/net_conf/if_config.h b/wifi/services/wifi_standard/wifi_framework/wifi_toolkit/net_helper/if_config.h old mode 100755 new mode 100644 similarity index 65% rename from services/wifi_standard/wifi_framework/wifi_manage/wifi_sta/net_conf/if_config.h rename to wifi/services/wifi_standard/wifi_framework/wifi_toolkit/net_helper/if_config.h index 7c3ecf5d69aa7424cbaa23b9947bf9adce576967..bcfd2779969e5d5e514529c2cf1a41968776ecd2 --- a/services/wifi_standard/wifi_framework/wifi_manage/wifi_sta/net_conf/if_config.h +++ b/wifi/services/wifi_standard/wifi_framework/wifi_toolkit/net_helper/if_config.h @@ -1,5 +1,5 @@ /* - * Copyright (C) 2021 Huawei Device Co., Ltd. + * Copyright (C) 2021-2022 Huawei Device Co., Ltd. * 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 @@ -17,11 +17,20 @@ #include #include "wifi_log.h" + +#ifdef OHOS_ARCH_LITE #include "dhcp_define.h" -#include "sta_define.h" +#endif namespace OHOS { namespace Wifi { +typedef enum IpType { + IPTYPE_IPV4, + IPTYPE_IPV6, + IPTYPE_MIX, + IPTYPE_BUTT, +} IpType; + class IfConfig { public: IfConfig(); @@ -29,6 +38,18 @@ public: static IfConfig &GetInstance(); + void FlushIpAddr(const std::string &ifName, const int &ipType); + + void AddIpAddr(const std::string &ifName, const std::string &ipAddr, const std::string &mask, const int &ipType); + + void SetProxy(bool isAuto, const std::string &proxy, const std::string &port, const std::string &noProxys, + const std::string &pac); + + bool ExecCommand(const std::vector &vecCommandArg); + + bool GetIpAddr(const std::string& ifName, std::string& ipAddr); + +#ifdef OHOS_ARCH_LITE /** * @Description : Set the If Addr object * @@ -36,14 +57,10 @@ public: * @param ipType - ip type[in] * @return int */ - int SetIfAddr(const DhcpResult &dhcpInfo, int ipType); + int SetIfDnsAndRoute(const DhcpResult &dhcpInfo, int ipType); void SetNetDns(const std::string &ifName, const std::string &dns1, const std::string &dns2); - void FlushIpAddr(const std::string &ifName, const int &ipType); - - void AddIpAddr(const std::string &ifName, const std::string &ipAddr, const std::string &mask, const int &ipType); - void AddIfRoute(const std::string &ifName, const std::string &ipAddr, const std::string &mask, const std::string &gateWay, const int &ipType); @@ -52,12 +69,31 @@ public: void AddIpv6Route( const std::string &ifName, const std::string &ipAddr, const std::string &mask, const std::string &gateWay); +#endif - void SetProxy(bool isAuto, const std::string &proxy, const std::string &port, const std::string &noProxys, - const std::string &pac); +private: + /** + * @Description : Use synchronous mode to execute the command, the current thread will be blocked + * until the command execution is complete. + * + * @param cmd - command + * @return bool - true: success, false: failed + */ + bool SyncExecuteCommand(const std::string& cmd); - bool ExecCommand(const std::vector &vecCommandArg); + /** + * @Description : Start a new thread to execute the command, the current thread will not be blocked + * + * @param cmd - command + * @return bool - true: success, false: failed + */ + bool AsyncExecuteCommand(const std::string& cmd); + + /** + * @Description : Check if the interface name is valid + */ + bool CheckIfaceValid(const std::string& ifname); }; } // namespace Wifi } // namespace OHOS -#endif \ No newline at end of file +#endif diff --git a/services/wifi_standard/wifi_framework/common/net_helper/ip_tools.cpp b/wifi/services/wifi_standard/wifi_framework/wifi_toolkit/net_helper/ip_tools.cpp similarity index 97% rename from services/wifi_standard/wifi_framework/common/net_helper/ip_tools.cpp rename to wifi/services/wifi_standard/wifi_framework/wifi_toolkit/net_helper/ip_tools.cpp index 84f342570bc46148d587a32c83a00e67c9af1481..b8c7af288a8229376688ca428815df7860884957 100644 --- a/services/wifi_standard/wifi_framework/common/net_helper/ip_tools.cpp +++ b/wifi/services/wifi_standard/wifi_framework/wifi_toolkit/net_helper/ip_tools.cpp @@ -35,7 +35,7 @@ std::string IpTools::ConvertIpv4Address(unsigned int addressIpv4) unsigned int IpTools::ConvertIpv4Address(const std::string &address) { std::string tmpAddress = address; - int addrInt = 0; + unsigned int addrInt = 0; unsigned int i = 0; for (i = 0; i < IPV4_DOT_NUM; i++) { std::string::size_type npos = tmpAddress.find("."); @@ -120,8 +120,9 @@ void IpTools::ConvertIpv6Address(const std::string &address, std::vector MAX_PREFIX_LEN) { - return netMask; + if (prefixLength <= MIN_PREFIX_LEN || prefixLength > MAX_PREFIX_LEN) { + const int defaultPrefix = 24; + prefixLength = defaultPrefix; } int mask[IPV4_BYTE_NUM] = {0, 0, 0, 0}; diff --git a/services/wifi_standard/wifi_framework/common/net_helper/ip_tools.h b/wifi/services/wifi_standard/wifi_framework/wifi_toolkit/net_helper/ip_tools.h similarity index 100% rename from services/wifi_standard/wifi_framework/common/net_helper/ip_tools.h rename to wifi/services/wifi_standard/wifi_framework/wifi_toolkit/net_helper/ip_tools.h diff --git a/services/wifi_standard/wifi_framework/common/net_helper/ipv4_address.cpp b/wifi/services/wifi_standard/wifi_framework/wifi_toolkit/net_helper/ipv4_address.cpp similarity index 95% rename from services/wifi_standard/wifi_framework/common/net_helper/ipv4_address.cpp rename to wifi/services/wifi_standard/wifi_framework/wifi_toolkit/net_helper/ipv4_address.cpp index 2b87117ce9c192ba0f437c3920aac16acb7a6fc9..5d5d9826a1ec9de5deaf7093703b4dc8558f766e 100644 --- a/services/wifi_standard/wifi_framework/common/net_helper/ipv4_address.cpp +++ b/wifi/services/wifi_standard/wifi_framework/wifi_toolkit/net_helper/ipv4_address.cpp @@ -1,5 +1,5 @@ /* - * Copyright (C) 2021 Huawei Device Co., Ltd. + * Copyright (C) 2021-2022 Huawei Device Co., Ltd. * 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 @@ -12,9 +12,12 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + #include "ipv4_address.h" -#include #include +#include +#include +#include #include "wifi_log.h" #undef LOG_TAG @@ -38,7 +41,7 @@ bool Ipv4Address::IsValidIPv4(const std::string &ipv4) Ipv4Address Ipv4Address::Create(const std::string &ipv4, size_t prefixLength) { - if (!IsValidIPv4(ipv4) || prefixLength < 0 || prefixLength > MAX_IPV4_PREFIX_LENGTH - 1) { + if (!IsValidIPv4(ipv4) || prefixLength > MAX_IPV4_PREFIX_LENGTH - 1) { return INVALID_INET_ADDRESS; } return Ipv4Address(ipv4, prefixLength); @@ -155,4 +158,4 @@ std::string Ipv4Address::GetNetwork() const return network; } } // namespace Wifi -} // namespace OHOS \ No newline at end of file +} // namespace OHOS diff --git a/services/wifi_standard/wifi_framework/common/net_helper/ipv4_address.h b/wifi/services/wifi_standard/wifi_framework/wifi_toolkit/net_helper/ipv4_address.h similarity index 97% rename from services/wifi_standard/wifi_framework/common/net_helper/ipv4_address.h rename to wifi/services/wifi_standard/wifi_framework/wifi_toolkit/net_helper/ipv4_address.h index ab90c70809d8760438808fc7a0f515b795689c47..2c313a2f7cbfaec794bef7d467e8e983eba81b6e 100644 --- a/services/wifi_standard/wifi_framework/common/net_helper/ipv4_address.h +++ b/wifi/services/wifi_standard/wifi_framework/wifi_toolkit/net_helper/ipv4_address.h @@ -1,5 +1,5 @@ /* - * Copyright (C) 2021 Huawei Device Co., Ltd. + * Copyright (C) 2021-2022 Huawei Device Co., Ltd. * 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 @@ -15,6 +15,9 @@ #ifndef OHOS_ADDRESS_IPV4_H #define OHOS_ADDRESS_IPV4_H +#include +#include +#include #include "base_address.h" constexpr int MAX_MASK_LENGTH = 32; @@ -164,4 +167,4 @@ private: } // namespace Wifi } // namespace OHOS -#endif /* OHOS_ADDRESS_IPV4_H */ \ No newline at end of file +#endif /* OHOS_ADDRESS_IPV4_H */ diff --git a/services/wifi_standard/wifi_framework/common/net_helper/ipv6_address.cpp b/wifi/services/wifi_standard/wifi_framework/wifi_toolkit/net_helper/ipv6_address.cpp similarity index 94% rename from services/wifi_standard/wifi_framework/common/net_helper/ipv6_address.cpp rename to wifi/services/wifi_standard/wifi_framework/wifi_toolkit/net_helper/ipv6_address.cpp index 3fadae955d6b3bc12ff9ea53607c9ac145d04914..ca6f507b48ddb9bfe1cbda8d39bde39563fe57f0 100644 --- a/services/wifi_standard/wifi_framework/common/net_helper/ipv6_address.cpp +++ b/wifi/services/wifi_standard/wifi_framework/wifi_toolkit/net_helper/ipv6_address.cpp @@ -1,5 +1,5 @@ /* - * Copyright (C) 2021 Huawei Device Co., Ltd. + * Copyright (C) 2021-2022 Huawei Device Co., Ltd. * 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 @@ -74,7 +74,7 @@ Ipv6Address Ipv6Address::Create(std::string ipv6) Ipv6Address Ipv6Address::Create(const std::string &ipv6Prefix, MacAddress &mac, const size_t prefixLength) { - if (prefixLength < 0 || prefixLength > HALF_PREFIX_LENGTH || !IsValidIPv6(ipv6Prefix)) { + if (prefixLength > HALF_PREFIX_LENGTH || !IsValidIPv6(ipv6Prefix)) { return INVALID_INET6_ADDRESS; } std::string eui64Addr = std::string("::") + MacToEui64addr(mac); @@ -94,7 +94,7 @@ Ipv6Address Ipv6Address::Create(const std::string &ipv6Prefix, MacAddress &mac, Ipv6Address Ipv6Address::Create(const std::string &ipv6Prefix, const size_t prefixLength, unsigned int rndSeed) { - if (prefixLength < 0 || prefixLength > MAX_IPV6_PREFIX_LENGTH || !IsValidIPv6(ipv6Prefix)) { + if (prefixLength > MAX_IPV6_PREFIX_LENGTH || !IsValidIPv6(ipv6Prefix)) { return INVALID_INET6_ADDRESS; } LOGD("Create use rand seed, %{public}u", rndSeed); @@ -104,7 +104,7 @@ Ipv6Address Ipv6Address::Create(const std::string &ipv6Prefix, const size_t pref Ipv6Address Ipv6Address::Create(const struct in6_addr &i6Addr, const size_t prefixLength) { - if ((prefixLength < 0) || (prefixLength > MAX_IPV6_PREFIX_LENGTH)) { + if (prefixLength > MAX_IPV6_PREFIX_LENGTH) { return INVALID_INET6_ADDRESS; } char ipv6Buf[INET6_ADDRSTRLEN] = {0}; @@ -116,7 +116,7 @@ Ipv6Address Ipv6Address::Create(const struct in6_addr &i6Addr, const size_t pref Ipv6Address Ipv6Address::Create(std::string ipv6, const size_t prefixLength) { - if ((prefixLength < 0) || (prefixLength > MAX_IPV6_PREFIX_LENGTH) || (!IsValidIPv6(ipv6))) { + if ((prefixLength > MAX_IPV6_PREFIX_LENGTH) || (!IsValidIPv6(ipv6))) { return INVALID_INET6_ADDRESS; } std::transform(ipv6.begin(), ipv6.end(), ipv6.begin(), ::tolower); @@ -185,7 +185,7 @@ std::string Ipv6Address::GetPrefix() const struct in6_addr Ipv6Address::GetIpv6Prefix(struct in6_addr &ip6Addr, size_t prefixLength) { struct in6_addr addr = IN6ADDR_ANY_INIT; - if (prefixLength < 0 || prefixLength > MAX_IPV6_PREFIX_LENGTH) { + if (prefixLength > MAX_IPV6_PREFIX_LENGTH) { return addr; } char buf[INET6_ADDRSTRLEN] = {0}; @@ -208,7 +208,7 @@ struct in6_addr Ipv6Address::GetIpv6Prefix(struct in6_addr &ip6Addr, size_t pref struct in6_addr Ipv6Address::GetIpv6Mask(size_t prefixLength) { struct in6_addr addr = IN6ADDR_ANY_INIT; - if (prefixLength < 0 || prefixLength > MAX_IPV6_PREFIX_LENGTH) { + if (prefixLength > MAX_IPV6_PREFIX_LENGTH) { return addr; } else if (prefixLength == MAX_IPV6_PREFIX_LENGTH) { for (unsigned int count = 0; count < prefixLength / CHAR_BIT; ++count) { @@ -268,6 +268,10 @@ std::string Ipv6Address::GetRandomAddr(const std::string &ipv6Prefix, int prefix inet_pton(AF_INET6, resHex.c_str(), &rndAddr); struct in6_addr ipv6Addr = IN6ADDR_ANY_INIT; inet_pton(AF_INET6, ipv6Prefix.c_str(), &ipv6Addr); + if (prefixLength < 0 || (prefixLength / CHAR_BIT) >= sizeof(rndAddr.s6_addr)) { + LOGE("Get random address error: prefix"); + return ""; + } ipv6Addr.s6_addr[prefixLength / CHAR_BIT] |= rndAddr.s6_addr[prefixLength / CHAR_BIT]; for (int n = prefixLength / CHAR_BIT + 1; n < MAX_IPV6_PREFIX_LENGTH / CHAR_BIT; ++n) { ipv6Addr.s6_addr[n] = rndAddr.s6_addr[n]; diff --git a/services/wifi_standard/wifi_framework/common/net_helper/ipv6_address.h b/wifi/services/wifi_standard/wifi_framework/wifi_toolkit/net_helper/ipv6_address.h similarity index 100% rename from services/wifi_standard/wifi_framework/common/net_helper/ipv6_address.h rename to wifi/services/wifi_standard/wifi_framework/wifi_toolkit/net_helper/ipv6_address.h diff --git a/services/wifi_standard/wifi_framework/common/net_helper/mac_address.cpp b/wifi/services/wifi_standard/wifi_framework/wifi_toolkit/net_helper/mac_address.cpp similarity index 74% rename from services/wifi_standard/wifi_framework/common/net_helper/mac_address.cpp rename to wifi/services/wifi_standard/wifi_framework/wifi_toolkit/net_helper/mac_address.cpp index c527ee2b086f1900be4afa5308eeb57c7fe57c26..6c7048047c3c03fa47d7adcbe94751116454607f 100644 --- a/services/wifi_standard/wifi_framework/common/net_helper/mac_address.cpp +++ b/wifi/services/wifi_standard/wifi_framework/wifi_toolkit/net_helper/mac_address.cpp @@ -1,5 +1,5 @@ /* - * Copyright (C) 2021 Huawei Device Co., Ltd. + * Copyright (C) 2021-2022 Huawei Device Co., Ltd. * 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 @@ -12,11 +12,18 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + #include "mac_address.h" -#include +#include #include -#include "securec.h" -#include "log_helper.h" +#include +#include +#include +#include +#include +#include +#include +#include #include "wifi_log.h" #undef LOG_TAG @@ -110,7 +117,7 @@ bool MacAddress::IsValid() const void MacAddress::Dump() const { - LOGI("MAC: [%s]", mac_.c_str()); + LOGI("MAC: [%{private}s]", mac_.c_str()); } const std::string &MacAddress::GetMacAddressWifiString() const @@ -129,5 +136,35 @@ struct sockaddr MacAddress::GetMacAddressWifiSockaddr() const } return hwAddr; } + +bool MacAddress::GetMacAddr(const std::string& ifName, unsigned char macAddr[MAC_LEN]) +{ + struct ifreq ifr; + if (memset_s(&ifr, sizeof(ifr), 0, sizeof(ifr)) != EOK || + strcpy_s(ifr.ifr_name, sizeof(ifr.ifr_name), ifName.c_str()) != EOK) { + LOGE("Init the ifreq struct failed!"); + return false; + } + int fd = socket(AF_INET, SOCK_DGRAM, 0); + if (fd < 0) { + LOGE("get mac addr socket error"); + return false; + } + + ifr.ifr_hwaddr.sa_family = ARPHRD_ETHER; + if (ioctl(fd, SIOCGIFHWADDR, &ifr) < 0) { + LOGE("get mac addr ioctl SIOCGIFHWADDR error"); + close(fd); + return false; + } + + if (memcpy_s(macAddr, ETH_ALEN, ifr.ifr_hwaddr.sa_data, ETH_ALEN) != EOK) { + LOGE("get mac addr memcpy_s error"); + close(fd); + return false; + } + close(fd); + return true; +} } // namespace WiFi -} // namespace OHOS \ No newline at end of file +} // namespace OHOS diff --git a/services/wifi_standard/wifi_framework/common/net_helper/mac_address.h b/wifi/services/wifi_standard/wifi_framework/wifi_toolkit/net_helper/mac_address.h similarity index 89% rename from services/wifi_standard/wifi_framework/common/net_helper/mac_address.h rename to wifi/services/wifi_standard/wifi_framework/wifi_toolkit/net_helper/mac_address.h index b3d18cf30e5fbafe36230629c8ec2ee2fbf00233..ad3fd56f5096d8ab24384a59bda9a2d75c99dbd9 100644 --- a/services/wifi_standard/wifi_framework/common/net_helper/mac_address.h +++ b/wifi/services/wifi_standard/wifi_framework/wifi_toolkit/net_helper/mac_address.h @@ -1,5 +1,5 @@ /* - * Copyright (C) 2021 Huawei Device Co., Ltd. + * Copyright (C) 2021-2022 Huawei Device Co., Ltd. * 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 @@ -12,12 +12,13 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + #ifndef OHOS_MAC_ADDRESS_H #define OHOS_MAC_ADDRESS_H -#include -#include +#include #include +#include constexpr int ZERO = 0; constexpr int ONE = 1; @@ -32,6 +33,10 @@ constexpr int ETH_ALEN = 6; /* ETH_ALEN Size of the MAC address binary data */ constexpr size_t MAC_STRING_LENGTH = ETH_ALEN * 2 + (ETH_ALEN - 1); /* length of the string of mac address */ +#ifndef MAC_LEN +#define MAC_LEN 6 +#endif + namespace OHOS { namespace Wifi { class MacAddress { @@ -52,6 +57,7 @@ public: Otherwise, the successful object is returned. */ static MacAddress Create(const std::string &mac); + /** * @Description factory method * @@ -61,10 +67,17 @@ public: */ static MacAddress Create(const sockaddr &hwAddr); -public: + /** + * @Description Obtaining the MAC address by interface name + * + * @param ifName - interface name + * @param macAddr - Array for storing returned mac data + * @return true - success false - fail + */ + static bool GetMacAddr(const std::string& ifName, unsigned char macAddr[MAC_LEN]); + static const MacAddress INVALID_MAC_ADDRESS; /* Invalid MAC Address Object Constant */ -public: /** * @Description The == operator is overloaded to determine whether two MAC addresses represent the same MAC address. @@ -145,4 +158,4 @@ private: } // namespace Wifi } // namespace OHOS -#endif /* OHOS_MAC_ADDRESS_H */ \ No newline at end of file +#endif /* OHOS_MAC_ADDRESS_H */ diff --git a/services/wifi_standard/wifi_framework/common/net_helper/network_interface.cpp b/wifi/services/wifi_standard/wifi_framework/wifi_toolkit/net_helper/network_interface.cpp old mode 100755 new mode 100644 similarity index 88% rename from services/wifi_standard/wifi_framework/common/net_helper/network_interface.cpp rename to wifi/services/wifi_standard/wifi_framework/wifi_toolkit/net_helper/network_interface.cpp index 9300a01e3c231fcbc7ce022d365cc79dfd9e457b..098942ec84594c2a8dbb666b08fc0e82742a5511 --- a/services/wifi_standard/wifi_framework/common/net_helper/network_interface.cpp +++ b/wifi/services/wifi_standard/wifi_framework/wifi_toolkit/net_helper/network_interface.cpp @@ -58,22 +58,22 @@ bool NetworkInterface::IsValidInterfaceName(const std::string &interfaceName) void NetworkInterface::Dump(const std::string &interfaceName) { - WIFI_LOGI("InterfaceName [%s]", interfaceName.c_str()); + WIFI_LOGI("InterfaceName [%{private}s]", interfaceName.c_str()); std::vector vecIPv4; std::vector vecIPv6; bool ret = FetchInterfaceConfig(interfaceName, vecIPv4, vecIPv6); if (!ret) { - WIFI_LOGI("Fetch Interface [%s] failed.", interfaceName.c_str()); + WIFI_LOGI("Fetch Interface [%{private}s] failed.", interfaceName.c_str()); } - WIFI_LOGI("\tIPv4 size [%zu]", vecIPv4.size()); + WIFI_LOGI("\tIPv4 size [%{private}zu]", vecIPv4.size()); for (const auto &item : vecIPv4) { item.Dump(); } - WIFI_LOGI("\tIPv6 size [%zu]", vecIPv6.size()); + WIFI_LOGI("\tIPv6 size [%{private}zu]", vecIPv6.size()); for (const auto &item : vecIPv6) { item.Dump(); } @@ -140,20 +140,20 @@ bool NetworkInterface::IsExistAddressForInterface(const std::string &interfaceNa bool NetworkInterface::AddIpAddress(const std::string &interfaceName, const BaseAddress &ipAddress) { if (!ipAddress.IsValid()) { - WIFI_LOGE("Add IP address [%{public}s] is not valid.", ipAddress.GetAddressWithString().c_str()); + WIFI_LOGE("Add IP address [%{private}s] is not valid.", ipAddress.GetAddressWithString().c_str()); return false; } /* Avoid repeated add. */ if (IsExistAddressForInterface(interfaceName, ipAddress)) { - WIFI_LOGI("In interface [%{public}s], the address [%s] is exist.", + WIFI_LOGI("In interface [%{public}s], the address [%{private}s] is exist.", interfaceName.c_str(), ipAddress.GetAddressWithString().c_str()); return true; } if (!IpAddressChange(interfaceName, ipAddress, true)) { - WIFI_LOGE("Interface [%{public}s] add address [%s] failed.", + WIFI_LOGE("Interface [%{public}s] add address [%{private}s] failed.", interfaceName.c_str(), ipAddress.GetAddressWithString().c_str()); return false; @@ -164,18 +164,18 @@ bool NetworkInterface::AddIpAddress(const std::string &interfaceName, const Base bool NetworkInterface::DelIpAddress(const std::string &interfaceName, const BaseAddress &ipAddress) { if (!ipAddress.IsValid()) { - WIFI_LOGE("Del IP address [%s] is not valid.", ipAddress.GetAddressWithString().c_str()); + WIFI_LOGE("Del IP address [%{private}s] is not valid.", ipAddress.GetAddressWithString().c_str()); return false; } if (!IsExistAddressForInterface(interfaceName, ipAddress)) { - WIFI_LOGI("In interface [%{public}s], the address [%s] is not exist.", + WIFI_LOGI("In interface [%{public}s], the address [%{private}s] is not exist.", interfaceName.c_str(), ipAddress.GetAddressWithString().c_str()); return true; } if (!IpAddressChange(interfaceName, ipAddress, false)) { - WIFI_LOGE("Interface [%{public}s] del address [%s] failed.", + WIFI_LOGE("Interface [%{public}s] del address [%{private}s] failed.", interfaceName.c_str(), ipAddress.GetAddressWithString().c_str()); return false; @@ -283,7 +283,7 @@ bool NetworkInterface::IpAddressChange( const std::string &interface, const BaseAddress &ipAddress, bool action, bool dad) { if (!ipAddress.IsValid() || ipAddress.GetFamilyType() == BaseAddress::FamilyType::FAMILY_INET6) { - WIFI_LOGE("bad input parameter [%{public}s][%s]/[%zu]to change ip.", interface.c_str(), + WIFI_LOGE("bad input parameter [%{public}s][%{private}s]/[%{private}zu]to change ip.", interface.c_str(), ipAddress.GetAddressWithString().c_str(), ipAddress.GetAddressPrefixLength()); return false; } @@ -317,7 +317,7 @@ bool NetworkInterface::IpAddressChange( } if (ioctl(fd, SIOCSIFADDR, &ifr) < 0) { close(fd); - WIFI_LOGE("ioctl set ip address failed, error is: %d.", errno); + WIFI_LOGE("ioctl set ip address failed, error is: %{public}d.", errno); return false; } if (inet_aton(Mask.c_str(), &(sin->sin_addr)) < 0) { @@ -326,7 +326,7 @@ bool NetworkInterface::IpAddressChange( } if (ioctl(fd, SIOCSIFNETMASK, &ifr) < 0) { close(fd); - WIFI_LOGE("ioctl set mask address failed, error is: %d.", errno); + WIFI_LOGE("ioctl set mask address failed, error is: %{public}d.", errno); return false; } close(fd); @@ -337,12 +337,12 @@ bool NetworkInterface::WriteDataToFile(const std::string &fileName, const std::s { int fd = open(fileName.c_str(), O_WRONLY | O_CLOEXEC); if (fd < 0) { - WIFI_LOGE("open %{public}s fail, error: %d", fileName.c_str(), errno); + WIFI_LOGE("open %{public}s fail, error: %{public}d", fileName.c_str(), errno); return false; } if (static_cast(write(fd, content.c_str(), content.length())) != content.length()) { - WIFI_LOGE("write content [%s] to file [%{public}s] failed. error: %{public}d.", + WIFI_LOGE("write content [%{public}s] to file [%{public}s] failed. error: %{public}d.", content.c_str(), fileName.c_str(), errno); close(fd); return false; diff --git a/services/wifi_standard/wifi_framework/common/net_helper/network_interface.h b/wifi/services/wifi_standard/wifi_framework/wifi_toolkit/net_helper/network_interface.h similarity index 100% rename from services/wifi_standard/wifi_framework/common/net_helper/network_interface.h rename to wifi/services/wifi_standard/wifi_framework/wifi_toolkit/net_helper/network_interface.h diff --git a/wifi/services/wifi_standard/wifi_framework/wifi_toolkit/net_helper/raw_socket.cpp b/wifi/services/wifi_standard/wifi_framework/wifi_toolkit/net_helper/raw_socket.cpp new file mode 100644 index 0000000000000000000000000000000000000000..91a23fd1516e81d192a4d22b6d3a900a954d9739 --- /dev/null +++ b/wifi/services/wifi_standard/wifi_framework/wifi_toolkit/net_helper/raw_socket.cpp @@ -0,0 +1,178 @@ +/* + * Copyright (C) 2022 Huawei Device Co., Ltd. + * 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 "raw_socket.h" +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "securec.h" +#include "wifi_log.h" + +#ifdef LOG_TAG +#undef LOG_TAG +#endif +#define LOG_TAG "ohwifi_raw_socket" + +namespace OHOS { +namespace Wifi { +constexpr int OPT_SUCC = 0; +constexpr int OPT_FAIL = -1; + +RawSocket::RawSocket() : socketFd_(-1), ifaceIndex_(0), protocol_(0) +{ +} + +RawSocket::~RawSocket() +{ + Close(); +} + +bool RawSocket::SetNonBlock(int fd) +{ + int ret = fcntl(fd, F_GETFL); + if (ret < 0) { + return false; + } + + uint32_t flags = (static_cast(ret) | O_NONBLOCK); + return fcntl(fd, F_SETFL, flags); +} + +int RawSocket::CreateSocket(const char *iface, uint16_t protocol) +{ + if (iface == nullptr) { + LOGW("iface is null"); + return OPT_FAIL; + } + + unsigned int ifaceIndex = if_nametoindex(iface); + if (ifaceIndex == 0) { + LOGE("get iface index fail: %{public}s", iface); + return OPT_FAIL; + } + + int socketFd = socket(PF_PACKET, SOCK_DGRAM, htons(protocol)); + if (socketFd < 0) { + LOGE("create socket fail"); + return OPT_FAIL; + } + + if (SetNonBlock(socketFd)) { + LOGE("set non block fail"); + (void)close(socketFd); + return OPT_FAIL; + } + + struct sockaddr_ll rawAddr; + rawAddr.sll_ifindex = ifaceIndex; + rawAddr.sll_protocol = htons(protocol); + rawAddr.sll_family = AF_PACKET; + + int ret = bind(socketFd, reinterpret_cast(&rawAddr), sizeof(rawAddr)); + if (ret != 0) { + LOGE("bind fail"); + (void)close(socketFd); + return OPT_FAIL; + } + socketFd_ = socketFd; + ifaceIndex_ = ifaceIndex; + protocol_ = protocol; + return OPT_SUCC; +} + +int RawSocket::Send(uint8_t *buff, int count, uint8_t *destHwaddr) +{ + if (buff == nullptr || destHwaddr == nullptr) { + LOGE("buff or dest hwaddr is null"); + return OPT_FAIL; + } + + if (socketFd_ < 0 || ifaceIndex_ == 0) { + LOGE("invalid socket fd"); + return OPT_FAIL; + } + + struct sockaddr_ll rawAddr; + (void)memset_s(&rawAddr, sizeof(rawAddr), 0, sizeof(rawAddr)); + rawAddr.sll_ifindex = ifaceIndex_; + rawAddr.sll_protocol = htons(protocol_); + rawAddr.sll_family = AF_PACKET; + if (memcpy_s(rawAddr.sll_addr, sizeof(rawAddr.sll_addr), destHwaddr, ETH_ALEN) != EOK) { + LOGE("Send: memcpy fail"); + return OPT_FAIL; + } + + int ret; + do { + ret = sendto(socketFd_, buff, count, 0, reinterpret_cast(&rawAddr), sizeof(rawAddr)); + if (ret == -1) { + LOGE("Send: sendto fail"); + if (errno != EINTR) { + break; + } + } + } while (ret == -1); + return ret > 0 ? OPT_SUCC : OPT_FAIL; +} + +int RawSocket::Recv(uint8_t *buff, int count, int timeoutMillis) +{ + if (socketFd_ < 0) { + LOGE("invalid socket fd"); + return 0; + } + + pollfd fds[1]; + fds[0].fd = socketFd_; + fds[0].events = POLLIN; + if (poll(fds, 1, timeoutMillis) <= 0) { + return 0; + } + + int nBytes; + do { + nBytes = read(socketFd_, buff, count); + if (nBytes == -1) { + if (errno != EINTR) { + break; + } + } + } while (nBytes == -1); + + return nBytes < 0 ? 0 : nBytes; +} + +int RawSocket::Close(void) +{ + int ret = OPT_FAIL; + + if (socketFd_ >= 0) { + ret = close(socketFd_); + } + socketFd_ = -1; + ifaceIndex_ = 0; + protocol_ = 0; + return OPT_FAIL; +} +} +} diff --git a/wifi/services/wifi_standard/wifi_framework/wifi_toolkit/net_helper/raw_socket.h b/wifi/services/wifi_standard/wifi_framework/wifi_toolkit/net_helper/raw_socket.h new file mode 100644 index 0000000000000000000000000000000000000000..edb5555c50e12f9f67b03fb90036269e7f6696d4 --- /dev/null +++ b/wifi/services/wifi_standard/wifi_framework/wifi_toolkit/net_helper/raw_socket.h @@ -0,0 +1,39 @@ +/* + * Copyright (C) 2022 Huawei Device Co., Ltd. + * 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 OHOS_WIFI_RAW_SOCKET_H +#define OHOS_WIFI_RAW_SOCKET_H +#include + +namespace OHOS { +namespace Wifi { +class RawSocket { +public: + RawSocket(); + ~RawSocket(); + int CreateSocket(const char *iface, uint16_t protocol); + int Send(uint8_t *buff, int count, uint8_t *destHwaddr); + int Recv(uint8_t *buff, int count, int timeoutMillis); + int Close(void); +private: + bool SetNonBlock(int fd); + int socketFd_; + uint16_t ifaceIndex_; + uint16_t protocol_; +}; +} +} + +#endif diff --git a/services/wifi_standard/wifi_framework/common/utils/wifi_common_event_helper.cpp b/wifi/services/wifi_standard/wifi_framework/wifi_toolkit/utils/wifi_common_event_helper.cpp old mode 100755 new mode 100644 similarity index 92% rename from services/wifi_standard/wifi_framework/common/utils/wifi_common_event_helper.cpp rename to wifi/services/wifi_standard/wifi_framework/wifi_toolkit/utils/wifi_common_event_helper.cpp index 655961862b841e0a9cbcb8110508e089ff98557a..34dfa68ae38510ba9c880ff8e69a7dce34317852 --- a/services/wifi_standard/wifi_framework/common/utils/wifi_common_event_helper.cpp +++ b/wifi/services/wifi_standard/wifi_framework/wifi_toolkit/utils/wifi_common_event_helper.cpp @@ -1,5 +1,5 @@ /* - * Copyright (C) 2021 Huawei Device Co., Ltd. + * Copyright (C) 2021-2022 Huawei Device Co., Ltd. * 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 @@ -14,12 +14,17 @@ */ #include "wifi_common_event_helper.h" +#ifndef OHOS_ARCH_LITE #include "common_event_manager.h" #include "common_event.h" #include "common_event_data.h" +#include "common_event_subscriber.h" +#endif #include "wifi_logger.h" +#ifndef OHOS_ARCH_LITE using namespace OHOS::EventFwk; +#endif DEFINE_WIFILOG_LABEL("WifiCommonEventHelper"); namespace OHOS { namespace Wifi { @@ -27,6 +32,7 @@ bool WifiCommonEventHelper::PublishEvent(const std::string &eventAction, const i const std::vector &permissions) { WIFI_LOGD("publish event[%{public}s], code:%{public}d", eventAction.c_str(), code); +#ifndef OHOS_ARCH_LITE Want want; want.SetAction(eventAction); CommonEventData commonData; @@ -37,7 +43,7 @@ bool WifiCommonEventHelper::PublishEvent(const std::string &eventAction, const i CommonEventPublishInfo publishInfo; publishInfo.SetSubscriberPermissions(permissions); if (!CommonEventManager::PublishCommonEvent(commonData, publishInfo)) { - WIFI_LOGE("failed to publish event[%s], code:%d", eventAction.c_str(), code); + WIFI_LOGE("failed to publish event[%{public}s], code:%{public}d", eventAction.c_str(), code); return false; } return true; @@ -46,12 +52,14 @@ bool WifiCommonEventHelper::PublishEvent(const std::string &eventAction, const i WIFI_LOGE("failed to publish event[%{public}s], code:%{public}d", eventAction.c_str(), code); return false; } +#endif return true; } bool WifiCommonEventHelper::PublishEvent(const std::string &eventAction, const int &code, const std::string &data) { WIFI_LOGD("publish event[%{public}s], code:%{public}d", eventAction.c_str(), code); +#ifndef OHOS_ARCH_LITE Want want; want.SetAction(eventAction); CommonEventData commonData; @@ -62,6 +70,7 @@ bool WifiCommonEventHelper::PublishEvent(const std::string &eventAction, const i WIFI_LOGE("failed to publish event[%{public}s], code:%{public}d", eventAction.c_str(), code); return false; } +#endif return true; } @@ -85,7 +94,7 @@ bool WifiCommonEventHelper::PublishRssiValueChangedEvent(const int &code, const return WifiCommonEventHelper::PublishEvent(COMMON_EVENT_WIFI_RSSI_VALUE, code, data); } -bool WifiCommonEventHelper::PublishConnectionStateChangedEvent(const int &code, const std::string &data) +bool WifiCommonEventHelper::PublishConnStateChangedEvent(const int &code, const std::string &data) { return WifiCommonEventHelper::PublishEvent(COMMON_EVENT_WIFI_CONN_STATE, code, data); } diff --git a/services/wifi_standard/wifi_framework/common/utils/wifi_common_event_helper.h b/wifi/services/wifi_standard/wifi_framework/wifi_toolkit/utils/wifi_common_event_helper.h similarity index 95% rename from services/wifi_standard/wifi_framework/common/utils/wifi_common_event_helper.h rename to wifi/services/wifi_standard/wifi_framework/wifi_toolkit/utils/wifi_common_event_helper.h index 028f25d1c7d31569fac0e0992e7b49f2dc0fffa5..e93a59fbc16607a58ab2b3d1e8052c0b9214466e 100644 --- a/services/wifi_standard/wifi_framework/common/utils/wifi_common_event_helper.h +++ b/wifi/services/wifi_standard/wifi_framework/wifi_toolkit/utils/wifi_common_event_helper.h @@ -1,5 +1,5 @@ /* - * Copyright (C) 2021 Huawei Device Co., Ltd. + * Copyright (C) 2021-2022 Huawei Device Co., Ltd. * 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 @@ -17,7 +17,6 @@ #define OHOS_WIFI_COMMON_EVENT_HELPER_H #include -#include "common_event_subscriber.h" namespace OHOS { namespace Wifi { @@ -47,7 +46,7 @@ public: static bool PublishScanFinishedEvent(const int &code, const std::string &data); static bool PublishScanStateChangedEvent(const int &code, const std::string &data); static bool PublishRssiValueChangedEvent(const int &code, const std::string &data); - static bool PublishConnectionStateChangedEvent(const int &code, const std::string &data); + static bool PublishConnStateChangedEvent(const int &code, const std::string &data); static bool PublishHotspotStateChangedEvent(const int &code, const std::string &data); static bool PublishApStaJoinEvent(const int &code, const std::string &data); static bool PublishApStaLeaveEvent(const int &code, const std::string &data); diff --git a/wifi/services/wifi_standard/wifi_framework/wifi_toolkit/utils/wifi_encryption_util.cpp b/wifi/services/wifi_standard/wifi_framework/wifi_toolkit/utils/wifi_encryption_util.cpp new file mode 100755 index 0000000000000000000000000000000000000000..3ec43658470f7d0c5a8b2d2a12abf65bb0781565 --- /dev/null +++ b/wifi/services/wifi_standard/wifi_framework/wifi_toolkit/utils/wifi_encryption_util.cpp @@ -0,0 +1,173 @@ +/* + * Copyright (C) 2022 Huawei Device Co., Ltd. + * 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 FEATURE_ENCRYPTION_SUPPORT +#include "wifi_encryption_util.h" +#include +#include +#include "wifi_logger.h" +#include "wifi_global_func.h" +DEFINE_WIFILOG_LABEL("WifiConfigEncryption"); +namespace OHOS { +namespace Wifi { + +struct HksParam g_genParam[] = { + { .tag = HKS_TAG_KEY_STORAGE_FLAG, .uint32Param = HKS_STORAGE_PERSISTENT }, + { .tag = HKS_TAG_ALGORITHM, .uint32Param = HKS_ALG_AES }, + { .tag = HKS_TAG_KEY_SIZE, .uint32Param = HKS_AES_KEY_SIZE_256 }, + { .tag = HKS_TAG_PURPOSE, .uint32Param = HKS_KEY_PURPOSE_ENCRYPT | HKS_KEY_PURPOSE_DECRYPT }, + { .tag = HKS_TAG_DIGEST, .uint32Param = HKS_DIGEST_NONE }, + { .tag = HKS_TAG_PADDING, .uint32Param = HKS_PADDING_NONE }, + { .tag = HKS_TAG_IS_KEY_ALIAS, .boolParam = true }, + { .tag = HKS_TAG_KEY_GENERATE_TYPE, .uint32Param = HKS_KEY_GENERATE_TYPE_DEFAULT }, + { .tag = HKS_TAG_BLOCK_MODE, .uint32Param = HKS_MODE_GCM }, + { .tag = HKS_TAG_ASSOCIATED_DATA, .blob = { .size = AAD_SIZE, .data = (uint8_t *)AAD } }, +}; + +int32_t SetUpHks() +{ + int32_t ret = HksInitialize(); + if (ret != HKS_SUCCESS) { + WIFI_LOGE("wifi encryption init failed"); + } + return ret; +} + +int32_t GetKey(const WifiEncryptionInfo &wifiEncryptionInfo, const struct HksParamSet *genParamSet) +{ + struct HksBlob authId = wifiEncryptionInfo.keyAlias; + int32_t keyExist = HksKeyExist(&authId, nullptr); + if (keyExist == HKS_ERROR_NOT_EXIST) { + int32_t ret = HksGenerateKey(&authId, genParamSet, nullptr); + if (ret != HKS_SUCCESS) { + WIFI_LOGE("generate key failed"); + return ret; + } else { + return ret; + } + } else if (keyExist != HKS_SUCCESS) { + WIFI_LOGE("search key failed"); + return keyExist; + } + return keyExist; +} + +int32_t WifiEncryption(const WifiEncryptionInfo &wifiEncryptionInfo, const std::string &inputString, + EncryptedData &encryptedData) +{ + if (inputString.length() == 0) { + return HKS_SUCCESS; + } + struct HksBlob authId = wifiEncryptionInfo.keyAlias; + struct HksBlob plainText = { inputString.length(), (uint8_t *)&inputString[0] }; + + uint8_t nonce[NONCE_SIZE] = {0}; + struct HksBlob randomIV = {NONCE_SIZE, nonce}; + int32_t ret = HksGenerateRandom(NULL, &randomIV); + if (ret != HKS_SUCCESS) { + WIFI_LOGE("wifi encryption generate IV failed"); + return ret; + } + struct HksParam IVParam[] = { + { .tag = HKS_TAG_NONCE, .blob = { .size = NONCE_SIZE, .data = nonce } }, + }; + + struct HksParamSet *encryParamSet = nullptr; + HksInitParamSet(&encryParamSet); + HksAddParams(encryParamSet, g_genParam, sizeof(g_genParam) / sizeof(HksParam)); + HksAddParams(encryParamSet, IVParam, sizeof(IVParam) / sizeof(HksParam)); + HksBuildParamSet(&encryParamSet); + + ret = GetKey(wifiEncryptionInfo, encryParamSet); + if (ret != HKS_SUCCESS) { + WIFI_LOGE("wifi encryption failed"); + return ret; + } + + uint8_t cipherBuf[AES_COMMON_SIZE] = {0}; + HksBlob cipherData = { + .size = AES_COMMON_SIZE, + .data = cipherBuf + }; + + ret = HksEncrypt(&authId, encryParamSet, &plainText, &cipherData); + if (ret != HKS_SUCCESS) { + WIFI_LOGE("Hks encryption failed"); + return ret; + } + + encryptedData.encryptedPassword = ConvertArrayToHex(cipherBuf, cipherData.size); + encryptedData.IV = ConvertArrayToHex(nonce, NONCE_SIZE); + HksFreeParamSet(&encryParamSet); + return ret; +} + +int32_t WifiDecryption(const WifiEncryptionInfo &wifiEncryptionInfo, const EncryptedData &encryptedData, + std::string &decryptedData) +{ + if (encryptedData.encryptedPassword.size() == 0) { + return HKS_SUCCESS; + } + struct HksBlob authId = wifiEncryptionInfo.keyAlias; + uint8_t cipherBuf[AES_COMMON_SIZE] = {0}; + uint32_t length = AES_COMMON_SIZE; + int32_t retStrToArrat = HexStringToVec(encryptedData.encryptedPassword, cipherBuf, AES_COMMON_SIZE, length); + if (retStrToArrat != 0) { + return HKS_FAILURE; + } + + uint8_t nonce[NONCE_SIZE] = {0}; + uint32_t lengthIV = NONCE_SIZE; + retStrToArrat = HexStringToVec(encryptedData.IV, nonce, NONCE_SIZE, lengthIV); + if (retStrToArrat != 0) { + return HKS_FAILURE; + } + struct HksParam IVParam[] = { + { .tag = HKS_TAG_NONCE, .blob = { .size = NONCE_SIZE, .data = nonce } }, + }; + + struct HksBlob cipherData = { length, cipherBuf }; + struct HksParamSet *decryParamSet = nullptr; + + HksInitParamSet(&decryParamSet); + HksAddParams(decryParamSet, g_genParam, sizeof(g_genParam) / sizeof(HksParam)); + HksAddParams(decryParamSet, IVParam, sizeof(IVParam) / sizeof(HksParam)); + HksBuildParamSet(&decryParamSet); + + int32_t ret = HksKeyExist(&authId, nullptr); + if (ret != HKS_SUCCESS) { + WIFI_LOGE("wifi decryption key not exist"); + return ret; + } + uint8_t plainBuff[AES_COMMON_SIZE] = {0}; + HksBlob plainText = { + .size = AES_COMMON_SIZE, + .data = plainBuff + }; + + ret = HksDecrypt(&authId, decryParamSet, &cipherData, &plainText); + if (ret != HKS_SUCCESS) { + WIFI_LOGE("Hks decryption failed"); + return ret; + } + + std::string temp(plainText.data, plainText.data + plainText.size); + decryptedData = temp; + HksFreeParamSet(&decryParamSet); + return ret; +} +} // namespace Wifi +} // namespace OHOS +#endif \ No newline at end of file diff --git a/wifi/services/wifi_standard/wifi_framework/wifi_toolkit/utils/wifi_encryption_util.h b/wifi/services/wifi_standard/wifi_framework/wifi_toolkit/utils/wifi_encryption_util.h new file mode 100755 index 0000000000000000000000000000000000000000..d0280bd070bc58b9022c6766f892d6bb1ab75ca0 --- /dev/null +++ b/wifi/services/wifi_standard/wifi_framework/wifi_toolkit/utils/wifi_encryption_util.h @@ -0,0 +1,99 @@ +/* + * Copyright (C) 2022 Huawei Device Co., Ltd. + * 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 FEATURE_ENCRYPTION_SUPPORT +#ifndef OHOS_WIFI_CONFIG_HKS_H +#define OHOS_WIFI_CONFIG_HKS_H +#include +#include +#include "hks_api.h" +#include "hks_type.h" +#include "hks_param.h" + +namespace OHOS { +namespace Wifi { +constexpr uint32_t AES_COMMON_SIZE = 256; +constexpr uint32_t AAD_SIZE = 16; +constexpr uint32_t NONCE_SIZE = 16; + +const uint8_t AAD[AAD_SIZE] = {0}; + +class EncryptedData final { +public: + std::string encryptedPassword = ""; + std::string IV = ""; + EncryptedData(const std::string password, const std::string inputIV) + { + encryptedPassword = password; + IV = inputIV; + } + EncryptedData() {} + ~EncryptedData() {} +}; + +class WifiEncryptionInfo { +public: + std::string fileName; + static constexpr char WIFI_ENCRY_KEY[] = "WifiEncryHksAes"; + struct HksBlob keyAlias; + void SetFile(const std::string file) + { + fileName = WIFI_ENCRY_KEY + file; + keyAlias = { fileName.length(), (uint8_t *)&fileName[0] }; + } + explicit WifiEncryptionInfo(const std::string file) + { + SetFile(file); + } + WifiEncryptionInfo() {} + ~WifiEncryptionInfo() {} +}; + +/** + * @Description Set up Huks service + */ +int32_t SetUpHks(); + +/** + * @Description Generate new or get existed GCM-AES key based on input encryptionInfo and genParamSet + * @param wifiEncryptionInfo - keyAlias info + * @param genParamSet - generate params + * @return HKS_SUCCESS - find key, others - find key failed + */ +int32_t GetKey(const WifiEncryptionInfo &wifiEncryptionInfo, const struct HksParamSet *genParamSet); + +/** + * @Description Encrypt inputString using GCM-AES based on input encryptionInfo + * @param wifiEncryptionInfo - keyAlias info + * @param inputString - plaint string that needs to be encrypted + * @param encryptedData - encrypted result with encrypted string and IV value + * @return HKS_SUCCESS - encryption success, others - encryption failed + */ +int32_t WifiEncryption(const WifiEncryptionInfo &wifiEncryptionInfo, const std::string &inputString, + EncryptedData &encryptedData); + + +/** + * @Description Decrypt encryptedData using GCM-AES based on input encryptionInfo + * @param wifiEncryptionInfo - keyAlias info + * @param encryptedData - encrypted result with encrypted string and IV value + * @param decryptedData - string after decryption + * @return HKS_SUCCESS - decryption success, others - decryption failed + */ +int32_t WifiDecryption(const WifiEncryptionInfo &wifiEncryptionInfo, const EncryptedData &encryptedData, + std::string &decryptedData); +} +} +#endif +#endif \ No newline at end of file diff --git a/services/wifi_standard/wifi_framework/common/utils/wifi_global_func.cpp b/wifi/services/wifi_standard/wifi_framework/wifi_toolkit/utils/wifi_global_func.cpp old mode 100755 new mode 100644 similarity index 70% rename from services/wifi_standard/wifi_framework/common/utils/wifi_global_func.cpp rename to wifi/services/wifi_standard/wifi_framework/wifi_toolkit/utils/wifi_global_func.cpp index afa317821c802999275a3b5c7247cec5a1cea1d1..7e86f27ae24d70a4528426cd26d9e086e1dfe2c5 --- a/services/wifi_standard/wifi_framework/common/utils/wifi_global_func.cpp +++ b/wifi/services/wifi_standard/wifi_framework/wifi_toolkit/utils/wifi_global_func.cpp @@ -1,5 +1,5 @@ /* - * Copyright (C) 2021 Huawei Device Co., Ltd. + * Copyright (C) 2021-2022 Huawei Device Co., Ltd. * 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 @@ -15,6 +15,7 @@ #include "wifi_global_func.h" #include #include "wifi_log.h" + #undef LOG_TAG #define LOG_TAG "WifiGlobalFunc" @@ -34,6 +35,7 @@ constexpr int CHANNEL_5G_MIN = 34; ErrCode CfgCheckSsid(const HotspotConfig &cfg) { if (cfg.GetSsid().length() < MIN_SSID_LEN || cfg.GetSsid().length() > MAX_SSID_LEN) { + LOGE("Config ssid length is invalid!"); return ErrCode::WIFI_OPT_INVALID_PARAM; } return ErrCode::WIFI_OPT_SUCCESS; @@ -41,7 +43,9 @@ ErrCode CfgCheckSsid(const HotspotConfig &cfg) ErrCode CfgCheckPsk(const HotspotConfig &cfg) { - if (cfg.GetPreSharedKey().length() < MIN_PSK_LEN || cfg.GetPreSharedKey().length() > MAX_PSK_LEN) { + size_t len = cfg.GetPreSharedKey().length(); + if (len < MIN_PSK_LEN || len > MAX_PSK_LEN) { + LOGE("PreSharedKey length error! invalid len: %{public}zu", len); return ErrCode::WIFI_OPT_INVALID_PARAM; } return ErrCode::WIFI_OPT_SUCCESS; @@ -54,6 +58,7 @@ ErrCode CfgCheckBand(const HotspotConfig &cfg, std::vector &bandsFromC return ErrCode::WIFI_OPT_SUCCESS; } } + LOGE("Hotspot config band is invalid!"); return ErrCode::WIFI_OPT_INVALID_PARAM; } @@ -73,6 +78,7 @@ ErrCode IsValidHotspotConfig(const HotspotConfig &cfg, const HotspotConfig &cfgF if (cfg.GetSecurityType() == KeyMgmt::NONE) { if (cfg.GetPreSharedKey().length() > 0) { + LOGE("Open hotspot PreSharedKey length is non-zero error!"); return ErrCode::WIFI_OPT_INVALID_PARAM; } } else if (cfg.GetSecurityType() == KeyMgmt::WPA_PSK || cfg.GetSecurityType() == KeyMgmt::WPA2_PSK) { @@ -80,6 +86,7 @@ ErrCode IsValidHotspotConfig(const HotspotConfig &cfg, const HotspotConfig &cfgF return ErrCode::WIFI_OPT_INVALID_PARAM; } } else { + LOGE("Hotspot securityType is not supported!"); return ErrCode::WIFI_OPT_INVALID_PARAM; } @@ -89,8 +96,10 @@ ErrCode IsValidHotspotConfig(const HotspotConfig &cfg, const HotspotConfig &cfgF } } + LOGD("Config channel is: %{public}d", cfg.GetChannel()); if (cfg.GetChannel() != cfgFromCenter.GetChannel()) { if (CfgCheckChannel(cfg, channInfoFromCenter) == ErrCode::WIFI_OPT_INVALID_PARAM) { + LOGE("Config channel is invalid!"); return ErrCode::WIFI_OPT_INVALID_PARAM; } } @@ -127,50 +136,62 @@ std::string GetRandomStr(int len) bool IsAllowScanAnyTime(const ScanControlInfo &info) { - auto forbidIter = info.scanForbidMap.find(SCAN_SCENE_ALL); - for (; forbidIter != info.scanForbidMap.end(); forbidIter++) { - for (auto iter = forbidIter->second.begin(); iter != forbidIter->second.end(); iter++) { - if (iter->scanMode == ScanMode::ANYTIME_SCAN) { - return false; - } + for (auto forbidIter = info.scanForbidList.begin(); forbidIter != info.scanForbidList.end(); forbidIter++) { + if (forbidIter->scanMode == ScanMode::ANYTIME_SCAN && forbidIter->scanScene == SCAN_SCENE_ALL) { + return false; } } return true; } -ConnectionState ConvertConnStateInternal(OperateResState resState) +ConnState ConvertConnStateInternal(OperateResState resState, bool &isReport) { switch (resState) { case OperateResState::CONNECT_CONNECTING: - return ConnectionState::CONNECT_CONNECTING; + isReport = true; + return ConnState::CONNECTING; case OperateResState::CONNECT_AP_CONNECTED: - return ConnectionState::CONNECT_AP_CONNECTED; - case OperateResState::CONNECT_CHECK_PORTAL: - return ConnectionState::CONNECT_CHECK_PORTAL; + isReport = true; + return ConnState::CONNECTED; case OperateResState::CONNECT_NETWORK_ENABLED: - return ConnectionState::CONNECT_NETWORK_ENABLED; + isReport = false; + return ConnState::UNKNOWN; case OperateResState::CONNECT_NETWORK_DISABLED: - return ConnectionState::CONNECT_NETWORK_DISABLED; + isReport = false; + return ConnState::UNKNOWN; case OperateResState::DISCONNECT_DISCONNECTING: - return ConnectionState::DISCONNECT_DISCONNECTING; - case OperateResState::DISCONNECT_DISCONNECT_FAILED: - return ConnectionState::DISCONNECT_DISCONNECT_FAILED; + isReport = true; + return ConnState::DISCONNECTING; case OperateResState::DISCONNECT_DISCONNECTED: - return ConnectionState::DISCONNECT_DISCONNECTED; + isReport = true; + return ConnState::DISCONNECTED; case OperateResState::CONNECT_PASSWORD_WRONG: - return ConnectionState::CONNECT_PASSWORD_WRONG; + isReport = false; + return ConnState::UNKNOWN; + case OperateResState::CONNECT_CONNECTION_FULL: + isReport = false; + return ConnState::UNKNOWN; + case OperateResState::CONNECT_CONNECTION_REJECT: + isReport = false; + return ConnState::UNKNOWN; case OperateResState::CONNECT_CONNECTING_TIMEOUT: - return ConnectionState::CONNECT_CONNECTING_TIMEOUT; + isReport = false; + return ConnState::UNKNOWN; case OperateResState::CONNECT_OBTAINING_IP: - return ConnectionState::CONNECT_OBTAINING_IP; + isReport = true; + return ConnState::OBTAINING_IPADDR; case OperateResState::CONNECT_OBTAINING_IP_FAILED: - return ConnectionState::CONNECT_OBTAINING_IP_FAILED; + isReport = false; + return ConnState::UNKNOWN; case OperateResState::CONNECT_ASSOCIATING: - return ConnectionState::CONNECT_ASSOCIATING; + isReport = false; + return ConnState::UNKNOWN; case OperateResState::CONNECT_ASSOCIATED: - return ConnectionState::CONNECT_ASSOCIATED; + isReport = false; + return ConnState::UNKNOWN; default: - return ConnectionState::UNKNOWN; + isReport = true; + return ConnState::UNKNOWN; } } @@ -267,6 +288,69 @@ int HexStringToVec(const std::string &str, std::vector &vec) return 0; } +int HexStringToVec(const std::string &str, uint8_t plainText[], uint32_t plainLength, uint32_t &resultLength) +{ + if (plainLength < 0) { + return false; + } + + std::vector result; + result.clear(); + int ret = HexStringToVec(str, result); + if (ret == -1 || result.size() > plainLength) { + return -1; + } + for (std::vector::size_type i = 0; i < result.size(); ++i) { + plainText[i] = result[i]; + } + resultLength = result.size(); + return 0; +} + +static char ConvertArrayChar(uint8_t ch) +{ + constexpr int maxDecNum = 9; + constexpr int numDiffForHexAlphabet = 10; + if (ch >= 0 && ch <= maxDecNum) { + return '0' + ch; + } + if (ch >= 0xa && ch <= 0xf) { + return ch + 'a' - numDiffForHexAlphabet; + } + return '0'; +} + +std::string ConvertArrayToHex(const uint8_t plainText[], uint32_t size) +{ + constexpr int bitWidth = 4; + std::stringstream ss; + for (uint32_t i = 0; i < size; i++) { + ss << ConvertArrayChar(plainText[i] >> bitWidth) << ConvertArrayChar (plainText[i] & 0xf); + } + return ss.str(); +} + +static bool ValidateChar(const char ch) +{ + if (ch == '\n' || ch == '\r') { + return false; + } + return true; +} + +std::string ValidateString(const std::string &str) +{ + std::stringstream ss; + ss << "\""; + for (char ch : str) { + if (ValidateChar(ch)) { + ss << ch; + } + } + ss << "\""; + return ss.str(); +} + void TransformFrequencyIntoChannel(const std::vector &freqVector, std::vector &chanVector) { int channel; @@ -294,24 +378,5 @@ bool IsValid5GHz(int freq) { return freq > 4900 && freq < 5900; } - -void CheckBandChannel(HotspotConfig &apConfig, const std::map> &validChanTable) -{ - bool cfgValid = false; - auto it = validChanTable.find(apConfig.GetBand()); - if (it != validChanTable.end() && it->second.size() != 0) { - for (auto vecIt = it->second.begin(); vecIt != it->second.end(); ++vecIt) { - if (*vecIt == apConfig.GetChannel()) { - cfgValid = true; - break; - } - } - } - if (!cfgValid) { - LOGW("Error band or error channels in band, use 2.4G band default channel."); - apConfig.SetBand(BandType::BAND_2GHZ); - apConfig.SetChannel(AP_CHANNEL_DEFAULT); - } -} } // namespace Wifi } // namespace OHOS diff --git a/services/wifi_standard/wifi_framework/common/utils/wifi_global_func.h b/wifi/services/wifi_standard/wifi_framework/wifi_toolkit/utils/wifi_global_func.h similarity index 84% rename from services/wifi_standard/wifi_framework/common/utils/wifi_global_func.h rename to wifi/services/wifi_standard/wifi_framework/wifi_toolkit/utils/wifi_global_func.h index 98e3812d735c7844a13d11a27dd284ac47dc81e3..8e59c732dbb5daac331a94d80b0ab8f98053b17c 100644 --- a/services/wifi_standard/wifi_framework/common/utils/wifi_global_func.h +++ b/wifi/services/wifi_standard/wifi_framework/wifi_toolkit/utils/wifi_global_func.h @@ -1,5 +1,5 @@ /* - * Copyright (C) 2021 Huawei Device Co., Ltd. + * Copyright (C) 2021-2022 Huawei Device Co., Ltd. * 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 @@ -33,6 +33,7 @@ constexpr int MIN_PSK_LEN = 8; constexpr int MAX_PSK_LEN = 63; constexpr int HEX_TYPE_LEN = 3; /* 3 hex type: 0 a A */ constexpr int MAX_AP_CONN = 32; +constexpr int MAX_CONFIGS_NUM = 1000; /** * @Description Check valid ssid config @@ -98,12 +99,13 @@ std::string GetRandomStr(int len); bool IsAllowScanAnyTime(const ScanControlInfo &info); /** - * @Description Internal transition from OperateResState struct to ConnectionState + * @Description Internal transition from OperateResState struct to ConnState * * @param resState - OperateResState state - * @return ConnectionState - convert output connection state + * @param isReport - true : need report; flase : not report + * @return ConnState - convert output connection state */ -ConnectionState ConvertConnStateInternal(OperateResState resState); +ConnState ConvertConnStateInternal(OperateResState resState, bool &isReport); /** * @Description Check whether the MAC address is valid @@ -224,6 +226,33 @@ std::string Vec2Stream(const std::string &prefix, const std::vector &vecCh */ int HexStringToVec(const std::string &str, std::vector &vec); +/** + * @Description Convert a hex type string to uint8_t*. + * + * @param str - input hex string, eg: 010203... + * @param plainText - output uint8_t* result, eg: [1,2,3,...] + * @param plainLength - input maxLength of uint8_t* result, eg: 256 + * @param resultLength - output Length of uint8_t* result, eg: 16 + * @return int - convert result, 0 success, -1 failed + */ +int HexStringToVec(const std::string &str, uint8_t plainText[], uint32_t plainLength, uint32_t &resultLength); + +/** + * @Description Convert a uint8_t* to Hex string. + * + * @param plainText - input uint8_t*, eg: [1,2,3,...] + * @param size - input uint8_t* size, eg: 16 + * @return string - convert Hex string, eg: 010203... + */ +std::string ConvertArrayToHex(const uint8_t plainText[], uint32_t size); + +/** + * @Description Convert a string to validate string for write. + * + * @param str - input string + * @return string - validate string wrapped by "" + */ +std::string ValidateString(const std::string &str); /** * @Description Check is a valid 5G frequency. * @@ -242,14 +271,6 @@ bool IsValid5GHz(int freq); */ bool IsValid24GHz(int freq); -/** - * @Description Obtain and report available channel information. - * - * @param apConfig - configuration input - * @param validChanTable - Valid channel tables. - */ -void CheckBandChannel(HotspotConfig &apConfig, const std::map> &validChanTable); - /** * @Description Convert the frequency in the container into a channel. * diff --git a/wifi/services/wifi_standard/wifi_hal/BUILD.gn b/wifi/services/wifi_standard/wifi_hal/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..78f2737ace5fdbbeb4bb604ad5548c52c9b214f2 --- /dev/null +++ b/wifi/services/wifi_standard/wifi_hal/BUILD.gn @@ -0,0 +1,140 @@ +# Copyright (C) 2021-2022 Huawei Device Co., Ltd. +# 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. + +if (defined(ohos_lite)) { + import("//build/lite/config/component/lite_component.gni") + import("//foundation/communication/wifi/wifi/wifi_lite.gni") +} else { + import("//build/ohos.gni") + import("//foundation/communication/wifi/wifi/wifi.gni") +} + +local_base_sources = [ + "common/wifi_hal_common_func.c", + "hdi/src/wifi_hdi_ap_impl.c", + "hdi/src/wifi_hdi_p2p_impl.c", + "hdi/src/wifi_hdi_proxy.c", + "hdi/src/wifi_hdi_sta_impl.c", + "main.c", + "wifi_hal_adapter.c", + "wifi_hal_ap_interface.c", + "wifi_hal_base_interface.c", + "wifi_hal_callback.c", + "wifi_hal_chip_interface.c", + "wifi_hal_crpc_ap.c", + "wifi_hal_crpc_base.c", + "wifi_hal_crpc_chip.c", + "wifi_hal_crpc_common.c", + "wifi_hal_crpc_p2p.c", + "wifi_hal_crpc_server.c", + "wifi_hal_crpc_sta.c", + "wifi_hal_crpc_supplicant.c", + "wifi_hal_module/hostapd_hal/wifi_hostapd_hal.c", + "wifi_hal_module/wpa_supplicant_hal/wifi_wpa_common.c", + "wifi_hal_module/wpa_supplicant_hal/wifi_wpa_hal.c", + "wifi_hal_module/wpa_supplicant_hal/wpa_p2p_hal/wifi_p2p_hal.c", + "wifi_hal_module/wpa_supplicant_hal/wpa_sta_hal/wifi_supplicant_hal.c", + "wifi_hal_module_manage.c", + "wifi_hal_p2p_interface.c", + "wifi_hal_sta_interface.c", + "wifi_hal_vendor_interface.c", +] + +local_base_include_dirs = [ + "$WIFI_ROOT_DIR/frameworks/native/interfaces", + "$WIFI_ROOT_DIR/services/wifi_standard/ipc_framework/cRPC/include", + "$WIFI_ROOT_DIR/services/wifi_standard/wifi_hal", + "$WIFI_ROOT_DIR/services/wifi_standard/wifi_hal/common", + "$WIFI_ROOT_DIR/services/wifi_standard/wifi_hal/wifi_hal_module/hostapd_hal", + "$WIFI_ROOT_DIR/services/wifi_standard/wifi_hal/wifi_hal_module/wpa_supplicant_hal", + "$WIFI_ROOT_DIR/services/wifi_standard/wifi_hal/wifi_hal_module/wpa_supplicant_hal/wpa_sta_hal", + "$WIFI_ROOT_DIR/services/wifi_standard/wifi_hal/wifi_hal_module/wpa_supplicant_hal/wpa_p2p_hal", + "$WIFI_ROOT_DIR/services/wifi_standard/wifi_hal/hdi/inc", + "$WIFI_ROOT_DIR/services/wifi_standard/include", +] + +if (defined(ohos_lite)) { + executable("wifi_hal_service") { + sources = local_base_sources + + include_dirs = local_base_include_dirs + include_dirs += [ + "//base/hiviewdfx/hilog_lite/interfaces/native/innerkits", + "//third_party/bounds_checking_function/include", + "//third_party/wpa_supplicant/wpa_supplicant-2.9/src", + ] + + deps = [ + "$WIFI_ROOT_DIR/services/wifi_standard/ipc_framework/cRPC:crpc_server", + "$WIFI_ROOT_DIR/services/wifi_standard/wifi_hal/etc/init:etc", + "//base/hiviewdfx/hilog_lite/frameworks/featured:hilog_shared", + "//third_party/bounds_checking_function:libsec_shared", + "//third_party/wpa_supplicant/wpa_supplicant-2.9:wpa_supplicant", + ] + + cflags_cc = [ "-fno-rtti" ] + defines = [ + "_GNU_SOURCE", + "OHOS_ARCH_LITE", + "AP_INTF=\"$wifi_feature_with_ap_intf\"", + "AP_NUM=$wifi_feature_with_ap_num", + ] + ldflags = [ "-lwpa_client" ] + } +} else { + ohos_executable("wifi_hal_service") { + install_enable = true + sources = local_base_sources + + include_dirs = local_base_include_dirs + include_dirs += [ + "//commonlibrary/c_utils/base/include", + "//base/hiviewdfx/hilog/interfaces/native/innerkits/include", + "//third_party/wpa_supplicant/wpa_supplicant-2.9_standard/src/", + "//third_party/bounds_checking_function/include/", + "//drivers/peripheral/wlan/interfaces/include/", + ] + + deps = [ + "$WIFI_ROOT_DIR/services/wifi_standard/ipc_framework/cRPC:crpc_server", + "$WIFI_ROOT_DIR/services/wifi_standard/wifi_hal/etc/init:etc", + "//base/hiviewdfx/hilog/interfaces/native/innerkits:libhilog", + "//third_party/wpa_supplicant/wpa_supplicant-2.9_standard:wpa_client", + ] + + external_deps = [ "c_utils:utils" ] + + defines = [ + "AP_INTF=\"$wifi_feature_with_ap_intf\"", + "AP_NUM=$wifi_feature_with_ap_num", + ] + + if (wifi_feature_is_hdi_supported) { + defines += [ "HDI_INTERFACE_SUPPORT" ] + external_deps += [ "drivers_interface_wlan:libwlan_proxy_1.0" ] + } + + if (product_name == "rk3568") { + defines += [ "NON_SEPERATE_P2P" ] + } + + cflags_cc = [ "-fno-rtti" ] + + part_name = "wifi" + subsystem_name = "communication" + } +} + +group("wifi_hal") { + deps = [ ":wifi_hal_service" ] +} diff --git a/services/wifi_standard/wifi_hal/common/wifi_hal_common_func.c b/wifi/services/wifi_standard/wifi_hal/common/wifi_hal_common_func.c similarity index 78% rename from services/wifi_standard/wifi_hal/common/wifi_hal_common_func.c rename to wifi/services/wifi_standard/wifi_hal/common/wifi_hal_common_func.c index 180d1337fba7868c68384c6b5025a552f1c6ceec..8d43302097013d322dfc386f3408f81f1069875a 100644 --- a/services/wifi_standard/wifi_hal/common/wifi_hal_common_func.c +++ b/wifi/services/wifi_standard/wifi_hal/common/wifi_hal_common_func.c @@ -14,9 +14,14 @@ */ #include "wifi_hal_common_func.h" +#include #include #include +#include +#include +#include #include "securec.h" +#include "wifi_log.h" #define MAC_UINT_SIZE 6 #define MAC_STRING_SIZE 17 @@ -122,3 +127,29 @@ int CheckMacIsValid(const char *macStr) } return 0; } + +int GetIfaceState(const char *ifaceName) +{ + int state = 0; + int sock = socket(AF_INET, SOCK_DGRAM, 0); + if (sock < 0) { + LOGE("GetIfaceState: create socket fail"); + return state; + } + + struct ifreq ifr; + (void)memset_s(&ifr, sizeof(ifr), 0, sizeof(ifr)); + if (strcpy_s(ifr.ifr_name, IFNAMSIZ, ifaceName) != EOK) { + LOGE("GetIfaceState: strcpy_s fail"); + close(sock); + return state; + } + if (ioctl(sock, SIOCGIFFLAGS, &ifr) < 0) { + LOGE("GetIfaceState: can not get interface state: %{public}s", ifaceName); + close(sock); + return state; + } + state = ((ifr.ifr_flags & IFF_UP) > 0 ? 1 : 0); + LOGD("GetIfaceState: current interface state: %{public}d", state); + return state; +} diff --git a/services/wifi_standard/wifi_hal/common/wifi_hal_common_func.h b/wifi/services/wifi_standard/wifi_hal/common/wifi_hal_common_func.h similarity index 91% rename from services/wifi_standard/wifi_hal/common/wifi_hal_common_func.h rename to wifi/services/wifi_standard/wifi_hal/common/wifi_hal_common_func.h index e41293d54c1404ee4bd55a2d91437fbc47ae1e53..cd2cac387f468597cce98e938865448d7ff59b04 100644 --- a/services/wifi_standard/wifi_hal/common/wifi_hal_common_func.h +++ b/wifi/services/wifi_standard/wifi_hal/common/wifi_hal_common_func.h @@ -58,7 +58,14 @@ int ConvertMacToArray(const char *macStr, unsigned char *mac, int macSize); */ int CheckMacIsValid(const char *macStr); +/** + * @Description Get the state of interface + * @param ifaceName - the name of interface + * @return int - 0: down 1: up + */ +int GetIfaceState(const char *ifaceName); + #ifdef __cplusplus } #endif -#endif \ No newline at end of file +#endif diff --git a/services/wifi_standard/wifi_hal/common/wifi_log.h b/wifi/services/wifi_standard/wifi_hal/common/wifi_log.h similarity index 91% rename from services/wifi_standard/wifi_hal/common/wifi_log.h rename to wifi/services/wifi_standard/wifi_hal/common/wifi_log.h index afa33ffcb7d80327d8903f38766d8a58d7de2952..f7fab4fc00dd6c648969cd892f21d40104c0c31d 100644 --- a/services/wifi_standard/wifi_hal/common/wifi_log.h +++ b/wifi/services/wifi_standard/wifi_hal/common/wifi_log.h @@ -1,5 +1,5 @@ /* - * Copyright (C) 2021 Huawei Device Co., Ltd. + * Copyright (C) 2021-2022 Huawei Device Co., Ltd. * 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 @@ -16,8 +16,11 @@ #ifndef OHOS_WIFI_LOG_H #define OHOS_WIFI_LOG_H - +#ifdef OHOS_ARCH_LITE +#include "hilog/log.h" +#else #include "hilog/log_c.h" +#endif #undef LOG_TAG #define LOG_TAG "WifiHalService" diff --git a/wifi/services/wifi_standard/wifi_hal/etc/init/BUILD.gn b/wifi/services/wifi_standard/wifi_hal/etc/init/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..93992fffe0a79f9a2d28c7d3d5124aa5c661778a --- /dev/null +++ b/wifi/services/wifi_standard/wifi_hal/etc/init/BUILD.gn @@ -0,0 +1,67 @@ +# Copyright (C) 2021-2022 Huawei Device Co., Ltd. +# 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. + +if (defined(ohos_lite)) { + import("//build/lite/config/component/lite_component.gni") +} else { + import("//build/ohos.gni") +} + +group("etc") { + deps = [ ":wpa_supplicant.conf" ] + if (!defined(ohos_lite)) { + deps += [ + ":hostapd.conf", + ":p2p_supplicant.conf", + ":wifi_hal_service.cfg", + ] + } +} + +if (defined(ohos_lite)) { + copy("wpa_supplicant.conf") { + sources = [ "wpa_supplicant.conf" ] + outputs = [ "$root_out_dir/system/etc/wifi/wpa_supplicant.conf" ] + } +} else { + ohos_prebuilt_etc("wifi_hal_service.cfg") { + source = "wifi_hal_service.cfg" + relative_install_dir = "init" + part_name = "wifi" + subsystem_name = "communication" + } + + ohos_prebuilt_etc("wpa_supplicant.conf") { + source = "wpa_supplicant.conf" + relative_install_dir = "wifi" + part_name = "wifi" + subsystem_name = "communication" + } + + ohos_prebuilt_etc("hostapd.conf") { + source = "hostapd.conf" + if (product_name == "rk3568") { + source = "default_conf/hostapd.conf" + } + relative_install_dir = "wifi" + part_name = "wifi" + subsystem_name = "communication" + } + + ohos_prebuilt_etc("p2p_supplicant.conf") { + source = "p2p_supplicant.conf" + relative_install_dir = "wifi" + part_name = "wifi" + subsystem_name = "communication" + } +} diff --git a/wifi/services/wifi_standard/wifi_hal/etc/init/default_conf/hostapd.conf b/wifi/services/wifi_standard/wifi_hal/etc/init/default_conf/hostapd.conf new file mode 100644 index 0000000000000000000000000000000000000000..14a8864138d55070185f46e0c6169967f7bbbd1b --- /dev/null +++ b/wifi/services/wifi_standard/wifi_hal/etc/init/default_conf/hostapd.conf @@ -0,0 +1,19 @@ +# Copyright (C) 2022 Huawei Device Co., Ltd. +# 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. + +interface=wlan0 +ctrl_interface=udp +ssid=testap +hw_mode=g +channel=1 +ignore_broadcast_ssid=0 \ No newline at end of file diff --git a/services/wifi_standard/wifi_hal/etc/init/hostapd.conf b/wifi/services/wifi_standard/wifi_hal/etc/init/hostapd.conf similarity index 100% rename from services/wifi_standard/wifi_hal/etc/init/hostapd.conf rename to wifi/services/wifi_standard/wifi_hal/etc/init/hostapd.conf diff --git a/wifi/services/wifi_standard/wifi_hal/etc/init/p2p_supplicant.conf b/wifi/services/wifi_standard/wifi_hal/etc/init/p2p_supplicant.conf new file mode 100644 index 0000000000000000000000000000000000000000..b6dd2826e67428559646b454203b4cf9bfc9530a --- /dev/null +++ b/wifi/services/wifi_standard/wifi_hal/etc/init/p2p_supplicant.conf @@ -0,0 +1,29 @@ +# Copyright (C) 2022 Huawei Device Co., Ltd. +# 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. + +ctrl_interface=udp +device_name=p2p_ohos +manufacturer=ohos +device_type=10-0050F204-5 +config_methods=virtual_push_button physical_display keypad +p2p_listen_reg_class=81 +p2p_listen_channel=1 +p2p_oper_reg_class=81 +p2p_oper_channel=1 +p2p_go_intent=0 +persistent_reconnect=1 +serial_number=0123456789ABCDEF +p2p_ssid_postfix=-ohos +p2p_go_ht40=1 +p2p_go_vht=1 +update_config=1 diff --git a/services/wifi_standard/wifi_hal/etc/init/wifi_hal_service.cfg b/wifi/services/wifi_standard/wifi_hal/etc/init/wifi_hal_service.cfg old mode 100755 new mode 100644 similarity index 36% rename from services/wifi_standard/wifi_hal/etc/init/wifi_hal_service.cfg rename to wifi/services/wifi_standard/wifi_hal/etc/init/wifi_hal_service.cfg index 80f6133974c9b40ad5f363d8ece7c5ba43b90d97..764b688c461abce377293d1abf44f4ef879a51fc --- a/services/wifi_standard/wifi_hal/etc/init/wifi_hal_service.cfg +++ b/wifi/services/wifi_standard/wifi_hal/etc/init/wifi_hal_service.cfg @@ -1,16 +1,19 @@ { "jobs" : [{ - "name" : "post-fs-data", + "name" : "early-boot", "cmds" : [ - "start wifi_hal_service" + "mkdir /data/service/el1/public/wifi 0770 wifi wifi", + "mkdir /data/service/el1/public/wifi/wpa_supplicant 0770 wifi wifi" ] } ], "services" : [{ "name" : "wifi_hal_service", "path" : ["/system/bin/wifi_hal_service"], - "uid" : "root", - "gid" : ["root", "shell"] + "caps" : ["CAP_NET_ADMIN", "CAP_NET_RAW"], + "uid" : "wifi", + "gid" : ["wifi", "shell"], + "secon" : "u:r:wifi_hal_service:s0" } ] } diff --git a/services/wifi_standard/wifi_hal/etc/init/wpa_supplicant.conf b/wifi/services/wifi_standard/wifi_hal/etc/init/wpa_supplicant.conf similarity index 100% rename from services/wifi_standard/wifi_hal/etc/init/wpa_supplicant.conf rename to wifi/services/wifi_standard/wifi_hal/etc/init/wpa_supplicant.conf diff --git a/tests/wifi_standard/wifi_framework/dhcp_manage/dhcp_client/dhcp_main_test.cpp b/wifi/services/wifi_standard/wifi_hal/hdi/inc/wifi_hdi_ap_impl.h similarity index 58% rename from tests/wifi_standard/wifi_framework/dhcp_manage/dhcp_client/dhcp_main_test.cpp rename to wifi/services/wifi_standard/wifi_hal/hdi/inc/wifi_hdi_ap_impl.h index 37c317ffda7540ab065a06ea4a22805cd6d4cc5a..67783effad51e1ce466f9b850f1a8202d97043f4 100644 --- a/tests/wifi_standard/wifi_framework/dhcp_manage/dhcp_client/dhcp_main_test.cpp +++ b/wifi/services/wifi_standard/wifi_hal/hdi/inc/wifi_hdi_ap_impl.h @@ -1,5 +1,5 @@ /* - * Copyright (C) 2021 Huawei Device Co., Ltd. + * Copyright (C) 2022 Huawei Device Co., Ltd. * 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 @@ -13,15 +13,18 @@ * limitations under the License. */ -#include -#include -#include "global_test.h" +#ifndef OHOS_HDI_AP_IMPL_H +#define OHOS_HDI_AP_IMPL_H -int main(int argc, char *argv[]) -{ - testing::InitGoogleTest(&argc, argv); - testing::InitGoogleMock(&argc, argv); - testing::Environment *env = new GlobalTest(); - testing::AddGlobalTestEnvironment(env); - return RUN_ALL_TESTS(); +#include "wifi_hal_define.h" + +#ifdef __cplusplus +extern "C" { +#endif +WifiErrorNo GetValidFrequenciesForBand(int32_t band, int *frequencies, int32_t *size, int id); +WifiErrorNo WifiSetPowerModel(const int mode, int id); +WifiErrorNo WifiGetPowerModel(int* mode, int id); +#ifdef __cplusplus } +#endif +#endif \ No newline at end of file diff --git a/tests/wifi_standard/wifi_framework/common/unittest/common_test.cpp b/wifi/services/wifi_standard/wifi_hal/hdi/inc/wifi_hdi_p2p_impl.h similarity index 76% rename from tests/wifi_standard/wifi_framework/common/unittest/common_test.cpp rename to wifi/services/wifi_standard/wifi_hal/hdi/inc/wifi_hdi_p2p_impl.h index 3319c142851de52541d1504d05038720a14c7861..df84dd683ef1bea1931baf311c36677cee3c3549 100644 --- a/tests/wifi_standard/wifi_framework/common/unittest/common_test.cpp +++ b/wifi/services/wifi_standard/wifi_hal/hdi/inc/wifi_hdi_p2p_impl.h @@ -1,5 +1,5 @@ /* - * Copyright (C) 2021 Huawei Device Co., Ltd. + * Copyright (C) 2022 Huawei Device Co., Ltd. * 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 @@ -13,10 +13,15 @@ * limitations under the License. */ -#include +#ifndef OHOS_HDI_P2P_IMPL_H +#define OHOS_HDI_P2P_IMPL_H -int main(int argc, char *argv[]) -{ - testing::InitGoogleTest(&argc, argv); - return RUN_ALL_TESTS(); +#ifdef __cplusplus +extern "C" { +#endif + + +#ifdef __cplusplus } +#endif +#endif \ No newline at end of file diff --git a/wifi/services/wifi_standard/wifi_hal/hdi/inc/wifi_hdi_proxy.h b/wifi/services/wifi_standard/wifi_hal/hdi/inc/wifi_hdi_proxy.h new file mode 100644 index 0000000000000000000000000000000000000000..4dfda8a3da12e53b79eabe177bd99f86dd4689c4 --- /dev/null +++ b/wifi/services/wifi_standard/wifi_hal/hdi/inc/wifi_hdi_proxy.h @@ -0,0 +1,81 @@ +/* + * Copyright (C) 2022 Huawei Device Co., Ltd. + * 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 OHOS_HDI_PROXY_H +#define OHOS_HDI_PROXY_H + +#include "wifi_hal_define.h" +#include "v1_0/iwlan_interface.h" +#include "wifi_hal_base_feature.h" + +#ifdef __cplusplus +extern "C" { +#endif + +typedef struct WifiHdiProxy { + struct IWlanInterface* wlanObj; + struct HdfFeatureInfo* feature; +} WifiHdiProxy; + +#ifndef CHECK_HDI_PROXY_AND_RETURN +#define CHECK_HDI_PROXY_AND_RETURN(proxy, retValue) \ +if (proxy.wlanObj == NULL || proxy.feature == NULL) { \ + LOGE("Hdi proxy: %{public}s in %{public}s is NULL!", #proxy, __func__); \ + return retValue; \ +} +#endif + +/** + * @Description Create a channel between the HAL and the driver. + * + * @return WifiErrorNo - operation result + */ +WifiErrorNo HdiStart(); + +/** + * @Description Stop the created channel. + * + * @return WifiErrorNo - operation result + */ +WifiErrorNo HdiStop(); + +/** + * @Description Create the WiFi object. + * + * @return WifiErrorNo - operation result + */ +struct IWlanInterface* GetWlanInterface(); + +/** + * @Description Get the hdi proxy by wlan type. + * + * @param wlanType - wlan type + * @return WifiHdiProxy - interface proxy object + */ +WifiHdiProxy GetHdiProxy(const int32_t wlanType); + +/** + * @Description Release hdi proxy by wlan type. + * This interface will be automatic called in the hid stop function, + * So you can use it without releasing. + * + * @param wlanType - wlan type + * @return WifiErrorNo - operation result + */ +WifiErrorNo ReleaseHdiProxy(const int32_t wlanType); +#ifdef __cplusplus +} +#endif +#endif \ No newline at end of file diff --git a/tests/wifi_standard/wifi_framework/wifi_manage/idl_client/unittest/idl_client_test_main.cpp b/wifi/services/wifi_standard/wifi_hal/hdi/inc/wifi_hdi_sta_impl.h similarity index 76% rename from tests/wifi_standard/wifi_framework/wifi_manage/idl_client/unittest/idl_client_test_main.cpp rename to wifi/services/wifi_standard/wifi_hal/hdi/inc/wifi_hdi_sta_impl.h index 2c2414a40d0208e5b682065dceeb59811e9baff0..aee195356742706733c59396888814e88f027125 100644 --- a/tests/wifi_standard/wifi_framework/wifi_manage/idl_client/unittest/idl_client_test_main.cpp +++ b/wifi/services/wifi_standard/wifi_hal/hdi/inc/wifi_hdi_sta_impl.h @@ -1,5 +1,5 @@ /* - * Copyright (C) 2021 Huawei Device Co., Ltd. + * Copyright (C) 2022 Huawei Device Co., Ltd. * 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 @@ -12,10 +12,16 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -#include -int main(int argc, char *argv[]) -{ - testing::InitGoogleTest(&argc, argv); - return RUN_ALL_TESTS(); +#ifndef OHOS_HDI_STA_IMPL_H +#define OHOS_HDI_STA_IMPL_H + +#ifdef __cplusplus +extern "C" { +#endif + + +#ifdef __cplusplus } +#endif +#endif \ No newline at end of file diff --git a/wifi/services/wifi_standard/wifi_hal/hdi/src/wifi_hdi_ap_impl.c b/wifi/services/wifi_standard/wifi_hal/hdi/src/wifi_hdi_ap_impl.c new file mode 100644 index 0000000000000000000000000000000000000000..b7061b9232fbe6e272260b569780172cde0ea593 --- /dev/null +++ b/wifi/services/wifi_standard/wifi_hal/hdi/src/wifi_hdi_ap_impl.c @@ -0,0 +1,78 @@ +/* + * Copyright (C) 2022 Huawei Device Co., Ltd. + * 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 HDI_INTERFACE_SUPPORT + +#include "wifi_hdi_ap_impl.h" +#include "wifi_hdi_proxy.h" +#include "wifi_log.h" + +#undef LOG_TAG +#define LOG_TAG "WifiHdiApImpl" + +#define NUMS_BAND 2 + +static int32_t ConvertToNl80211Band(int32_t band) +{ + return (band > 0 && band <= NUMS_BAND) ? (band - 1) : band; +} + +WifiErrorNo GetValidFrequenciesForBand(int32_t band, int *frequencies, int32_t *size, int id) +{ + if (frequencies == NULL || size == NULL) { + LOGE("%{public}s frequencies or size is null.", __func__); + return WIFI_HAL_FAILED; + } + WifiHdiProxy proxy = GetHdiProxy(PROTOCOL_80211_IFTYPE_AP); + CHECK_HDI_PROXY_AND_RETURN(proxy, WIFI_HAL_FAILED); + struct HdfWifiInfo wifiInfo; + wifiInfo.band = ConvertToNl80211Band(band); + wifiInfo.size = *size; + uint32_t count = 0xff; + LOGI("Get freqs parameters [band: %{public}d, alloc size: %{public}d]", wifiInfo.band, wifiInfo.size); + int32_t ret = proxy.wlanObj->GetFreqsWithBand(proxy.wlanObj, proxy.feature, &wifiInfo, frequencies, &count); + LOGI("Get freqs result, actual size: %{public}d", count); + *size = count; + if (ret != 0) { + LOGE("Get freqs with band failed: %{public}d", ret); + } + return (ret == 0) ? WIFI_HAL_SUCCESS : WIFI_HAL_FAILED; +} + +WifiErrorNo WifiSetPowerModel(const int mode, int id) +{ + LOGI("Instance %{public}d WifiSetPowerModel: %{public}d", id, mode); + WifiHdiProxy proxy = GetHdiProxy(PROTOCOL_80211_IFTYPE_AP); + CHECK_HDI_PROXY_AND_RETURN(proxy, WIFI_HAL_FAILED); + int32_t ret = proxy.wlanObj->SetPowerMode(proxy.wlanObj, proxy.feature, mode); + if (ret != 0) { + LOGE("Set power mode failed: %{public}d", ret); + } + return (ret == 0) ? WIFI_HAL_SUCCESS : WIFI_HAL_FAILED; +} + +WifiErrorNo WifiGetPowerModel(int* mode, int id) +{ + LOGI("Instance %{public}d WifiGetPowerModel", id); + WifiHdiProxy proxy = GetHdiProxy(PROTOCOL_80211_IFTYPE_AP); + CHECK_HDI_PROXY_AND_RETURN(proxy, WIFI_HAL_FAILED); + int32_t ret = proxy.wlanObj->GetPowerMode(proxy.wlanObj, proxy.feature, (uint8_t *)mode); + if (ret != 0) { + LOGE("Get power mode failed: %{public}d", ret); + } + LOGI("Get power mode: %{public}d", *mode); + return (ret == 0) ? WIFI_HAL_SUCCESS : WIFI_HAL_FAILED; +} +#endif diff --git a/interfaces/innerkits/native_cpp/napi/wifi_napi_p2p.cpp b/wifi/services/wifi_standard/wifi_hal/hdi/src/wifi_hdi_p2p_impl.c old mode 100755 new mode 100644 similarity index 72% rename from interfaces/innerkits/native_cpp/napi/wifi_napi_p2p.cpp rename to wifi/services/wifi_standard/wifi_hal/hdi/src/wifi_hdi_p2p_impl.c index 2f6b735bf6a7800fc1f89c39489c0f5f7e654a40..152fffa9a0b958bb39f3434395fb3d3c5fac1a61 --- a/interfaces/innerkits/native_cpp/napi/wifi_napi_p2p.cpp +++ b/wifi/services/wifi_standard/wifi_hal/hdi/src/wifi_hdi_p2p_impl.c @@ -1,23 +1,26 @@ -/* - * Copyright (C) 2021 Huawei Device Co., Ltd. - * 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 "wifi_napi_p2p.h" -#include "wifi_logger.h" - -namespace OHOS { -namespace Wifi { - -} // namespace Wifi -} // namespace OHOS +/* + * Copyright (C) 2022 Huawei Device Co., Ltd. + * 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 HDI_INTERFACE_SUPPORT + +#include "wifi_hdi_p2p_impl.h" +#include "wifi_hdi_proxy.h" +#include "wifi_log.h" + +#undef LOG_TAG +#define LOG_TAG "WifiHdiP2pImpl" + + +#endif diff --git a/wifi/services/wifi_standard/wifi_hal/hdi/src/wifi_hdi_proxy.c b/wifi/services/wifi_standard/wifi_hal/hdi/src/wifi_hdi_proxy.c new file mode 100644 index 0000000000000000000000000000000000000000..26af6978b00fac42d5008935d2d23f14c11cfabb --- /dev/null +++ b/wifi/services/wifi_standard/wifi_hal/hdi/src/wifi_hdi_proxy.c @@ -0,0 +1,224 @@ +/* + * Copyright (C) 2022 Huawei Device Co., Ltd. + * 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 HDI_INTERFACE_SUPPORT +#include "wifi_hdi_proxy.h" +#include +#include +#include "wifi_log.h" + +#undef LOG_TAG +#define LOG_TAG "WifiHdiProxy" + +#define MAX_FEATURE_NUMBER 16 + +const char *WLAN_SERVICE_NAME = "wlan_interface_service"; // Move the define to HDF module + +static pthread_mutex_t g_mutex; +static unsigned int g_wlanRefCount = 0; +static struct IWlanInterface *g_wlanObj = NULL; +static struct HdfFeatureInfo* g_featureArray[MAX_FEATURE_NUMBER] = {NULL}; + +static WifiErrorNo ReleaseFeatureInner(const int32_t wlanType) +{ + WifiErrorNo ret = WIFI_HAL_SUCCESS; + if (g_wlanObj == NULL) { + LOGE("%{public}s g_wlanObj is null", __func__); + return WIFI_HAL_FAILED; + } + for (int i = 0; i != MAX_FEATURE_NUMBER; ++i) { + if (g_featureArray[i] == NULL || g_featureArray[i]->type != wlanType) { + continue; + } + LOGI("%{public}s destory feature begin.", __func__); + ret = g_wlanObj->DestroyFeature(g_wlanObj, g_featureArray[i]); + if (ret != HDF_SUCCESS) { + LOGE("Destroy feature %{public}d failed: %{public}d", g_featureArray[i]->type, ret); + } + LOGI("%{public}s destory feature end.", __func__); + free(g_featureArray[i]); + g_featureArray[i] = NULL; + break; + } + return ret; +} + +static struct HdfFeatureInfo* GetFeatureInner(const int32_t wlanType) +{ + struct HdfFeatureInfo *feature = NULL; + if (g_wlanObj == NULL) { + LOGE("%{public}s g_wlanObj is null!", __func__); + return NULL; + } + for (int i = 0; i != MAX_FEATURE_NUMBER; ++i) { + if (g_featureArray[i] == NULL) { + continue; + } + if (g_featureArray[i]->type == wlanType) { + LOGI("%{public}s get an exist feature.", __func__); + feature = g_featureArray[i]; + return feature; + } + } + + /* allocate 1 struct */ + feature = (struct HdfFeatureInfo *)calloc(1, sizeof(struct HdfFeatureInfo)); + if (feature == NULL) { + LOGE("%{public}s calloc failed!", __func__); + return NULL; + } + LOGI("Create feature type: %{public}d", wlanType); + int32_t ret = g_wlanObj->CreateFeature(g_wlanObj, wlanType, feature); + if (ret != HDF_SUCCESS) { + LOGE("CreateFeature %{public}d failed: %{public}d", wlanType, ret); + goto FAILURE; + } + LOGI("Create feature end, ifname: %{public}s", feature->ifName); + bool isAdd = false; + for (int i = 0; i != MAX_FEATURE_NUMBER; ++i) { + if (g_featureArray[i] == NULL) { + g_featureArray[i] = feature; + isAdd = true; + break; + } + } + if (!isAdd) { + LOGE("%{public}s g_featureArray is full!", __func__); + goto FAILURE; + } + return feature; + +FAILURE: + if (feature != NULL) { + free(feature); + } + return NULL; +} + +static void ReleaseAllFeatures() +{ + if (g_wlanObj == NULL) { + return; + } + WifiErrorNo ret = WIFI_HAL_SUCCESS; + for (int i = 0; i != MAX_FEATURE_NUMBER; ++i) { + if (g_featureArray[i] == NULL) { + continue; + } + LOGI("%{public}s destory feature[all] begin.", __func__); + ret = g_wlanObj->DestroyFeature(g_wlanObj, g_featureArray[i]); + if (ret != HDF_SUCCESS) { + LOGE("Destroy feature %{public}d failed: %{public}d", g_featureArray[i]->type, ret); + } + LOGI("%{public}s destory feature[all] end.", __func__); + free(g_featureArray[i]); + g_featureArray[i] = NULL; + } +} + +WifiErrorNo HdiStart() +{ + LOGI("%{public}s start...", __func__); + pthread_mutex_lock(&g_mutex); + if (g_wlanRefCount != 0) { + ++g_wlanRefCount; + pthread_mutex_unlock(&g_mutex); + LOGI("%{public}s wlan ref count: %d", __func__, g_wlanRefCount); + return WIFI_HAL_SUCCESS; + } + g_wlanObj = IWlanInterfaceGetInstance(WLAN_SERVICE_NAME, false); + if (g_wlanObj == NULL) { + pthread_mutex_unlock(&g_mutex); + LOGE("%{public}s WlanInterfaceGetInstance failed", __func__); + return WIFI_HAL_FAILED; + } + int32_t ret = g_wlanObj->Start(g_wlanObj); + if (ret != HDF_SUCCESS) { + LOGE("%{public}s Start failed: %{public}d", __func__, ret); + IWlanInterfaceReleaseInstance(WLAN_SERVICE_NAME, g_wlanObj, false); + g_wlanObj = NULL; + pthread_mutex_unlock(&g_mutex); + return WIFI_HAL_FAILED; + } + ++g_wlanRefCount; + pthread_mutex_unlock(&g_mutex); + LOGI("%{public}s is started", __func__); + return WIFI_HAL_SUCCESS; +} + +WifiErrorNo HdiStop() +{ + LOGI("%{public}s stop...", __func__); + pthread_mutex_lock(&g_mutex); + if (g_wlanObj == NULL || g_wlanRefCount == 0) { + pthread_mutex_unlock(&g_mutex); + LOGE("%{public}s g_wlanObj is NULL or ref count is 0", __func__); + return WIFI_HAL_FAILED; + } + + const unsigned int ONE_REF_COUNT = 1; + if (g_wlanRefCount > ONE_REF_COUNT) { + --g_wlanRefCount; + pthread_mutex_unlock(&g_mutex); + LOGI("%{public}s wlan ref count: %d", __func__, g_wlanRefCount); + return WIFI_HAL_SUCCESS; + } + ReleaseAllFeatures(); + int32_t ret = g_wlanObj->Stop(g_wlanObj); + if (ret != HDF_SUCCESS) { + LOGE("%{public}s Stop failed: %{public}d", __func__, ret); + } + IWlanInterfaceReleaseInstance(WLAN_SERVICE_NAME, g_wlanObj, false); + --g_wlanRefCount; + g_wlanObj = NULL; + pthread_mutex_unlock(&g_mutex); + LOGI("%{public}s is stopped", __func__); + return (ret == HDF_SUCCESS) ? WIFI_HAL_SUCCESS : WIFI_HAL_FAILED; +} + +struct IWlanInterface* GetWlanInterface() +{ + struct IWlanInterface *wlanObj = NULL; + pthread_mutex_lock(&g_mutex); + wlanObj = g_wlanObj; + pthread_mutex_unlock(&g_mutex); + return wlanObj; +} + +WifiHdiProxy GetHdiProxy(const int32_t wlanType) +{ + WifiHdiProxy proxy = {.wlanObj = NULL, .feature = NULL}; + pthread_mutex_lock(&g_mutex); + struct HdfFeatureInfo* feature = GetFeatureInner(wlanType); + if (feature == NULL) { + pthread_mutex_unlock(&g_mutex); + LOGE("%{public}s GetFeature failed!", __func__); + return proxy; + } + proxy.wlanObj = g_wlanObj; + proxy.feature = feature; + pthread_mutex_unlock(&g_mutex); + return proxy; +} + +WifiErrorNo ReleaseHdiProxy(const int32_t wlanType) +{ + WifiErrorNo ret = WIFI_HAL_FAILED; + pthread_mutex_lock(&g_mutex); + ret = ReleaseFeatureInner(wlanType); + pthread_mutex_unlock(&g_mutex); + return ret; +} +#endif diff --git a/wifi/services/wifi_standard/wifi_hal/hdi/src/wifi_hdi_sta_impl.c b/wifi/services/wifi_standard/wifi_hal/hdi/src/wifi_hdi_sta_impl.c new file mode 100644 index 0000000000000000000000000000000000000000..3c1f218fbe23137e67af8f7271fb8a0efab15841 --- /dev/null +++ b/wifi/services/wifi_standard/wifi_hal/hdi/src/wifi_hdi_sta_impl.c @@ -0,0 +1,26 @@ +/* + * Copyright (C) 2022 Huawei Device Co., Ltd. + * 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 HDI_INTERFACE_SUPPORT + +#include "wifi_hdi_sta_impl.h" +#include "wifi_hdi_proxy.h" +#include "wifi_log.h" + +#undef LOG_TAG +#define LOG_TAG "WifiHdiStaImpl" + + +#endif diff --git a/services/wifi_standard/wifi_hal/main.c b/wifi/services/wifi_standard/wifi_hal/main.c similarity index 59% rename from services/wifi_standard/wifi_hal/main.c rename to wifi/services/wifi_standard/wifi_hal/main.c index a75b2018b1c4169779163e071027c8fa9a021ad8..3a4afc5c7b3e051f60e8c106f5a261bc9fe2a7a1 100644 --- a/services/wifi_standard/wifi_hal/main.c +++ b/wifi/services/wifi_standard/wifi_hal/main.c @@ -1,5 +1,5 @@ /* - * Copyright (C) 2021 Huawei Device Co., Ltd. + * Copyright (C) 2021-2022 Huawei Device Co., Ltd. * 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 @@ -13,18 +13,27 @@ * limitations under the License. */ +#include #include +#include +#include #include "server.h" -#include "wifi_log.h" +#include "wifi_common_def.h" #include "wifi_hal_adapter.h" #include "wifi_hal_ap_interface.h" #include "wifi_hal_crpc_server.h" -#include "wifi_hal_sta_interface.h" #include "wifi_hal_p2p_interface.h" +#include "wifi_hal_sta_interface.h" +#include "wifi_hostapd_hal.h" +#include "wifi_log.h" #undef LOG_TAG #define LOG_TAG "WifiHalService" +#define BUF_LEN 32 +#define INVALID_PID (-1) +#define WIFI_SERVICE_NAME "wifi_manager_se" + static void SignalExit(int sig) { LOGI("Caught signal %{public}d", sig); @@ -35,10 +44,45 @@ static void SignalExit(int sig) return; } -int main(void) +int GetWifiServicePid(void) { - char rpcSockPath[] = "/data/misc/wifi/unix_sock.sock"; + char cmd[BUF_LEN]; + if (snprintf_s(cmd, sizeof(cmd), sizeof(cmd) - 1, "pidof -s %s", WIFI_SERVICE_NAME) < 0) { + return INVALID_PID; + } + + FILE *p = popen(cmd, "r"); + if (!p) { + return INVALID_PID; + } + const int base = 10; + char buf[BUF_LEN]; + fgets(buf, BUF_LEN, p); + pclose(p); + return strtoul(buf, NULL, base); +} +static void SendStartNotify(void) +{ + int pid = GetWifiServicePid(); + if (pid <= 0) { + return; + } + LOGI("Send SIGUSR1/2 SIG to pid %{public}d", pid); + int ret = kill(pid, SIGUSR1); + if (ret != 0) { + LOGE("Send SIGUSR1 SIG to pid %{public}d failed: %{public}d", pid, ret); + } + ret = kill(pid, SIGUSR2); + if (ret != 0) { + LOGE("Send SIGUSR2 SIG to pid %{public}d failed: %{public}d", pid, ret); + } +} + +int main(void) +{ + LOGI("Wifi hal service starting..."); + char rpcSockPath[] = CONFIG_ROOR_DIR"/unix_sock.sock"; if (access(rpcSockPath, 0) == 0) { unlink(rpcSockPath); } @@ -57,10 +101,13 @@ int main(void) signal(SIGTERM, SignalExit); signal(SIGPIPE, SIG_IGN); + SendStartNotify(); RunRpcLoop(server); /* stop wpa_supplicant, hostapd, and other resources */ ForceStop(); - StopSoftAp(); + for (int id = 0; id < AP_MAX_INSTANCE; id++) { + StopSoftAp(id); + } P2pForceStop(); ReleaseWifiHalVendorInterface(); /* clear RPC Server */ diff --git a/services/wifi_standard/wifi_hal/wifi_hal_adapter.c b/wifi/services/wifi_standard/wifi_hal/wifi_hal_adapter.c similarity index 65% rename from services/wifi_standard/wifi_hal/wifi_hal_adapter.c rename to wifi/services/wifi_standard/wifi_hal/wifi_hal_adapter.c index 8208af6c02d789f7afbe3783b6d8aaa7e3d40161..c55d7456fa8f02a90e1a9c0570ed886f82dc3dde 100644 --- a/services/wifi_standard/wifi_hal/wifi_hal_adapter.c +++ b/wifi/services/wifi_standard/wifi_hal/wifi_hal_adapter.c @@ -1,5 +1,5 @@ /* - * Copyright (C) 2021 Huawei Device Co., Ltd. + * Copyright (C) 2021-2022 Huawei Device Co., Ltd. * 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 @@ -12,11 +12,15 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + #include "wifi_hal_adapter.h" #include #include #include #include +#include +#include "securec.h" +#include "wifi_common_def.h" #include "wifi_log.h" #undef LOG_TAG @@ -25,16 +29,19 @@ WifiHalVendorInterface *g_wifiHalVendorInterface = NULL; #define MODULE_NAME_MAX_LEN 256 -#define MODULE_CONFIG_FILE_PATH "/data/misc/wifi/wifi_hal_vendor.conf" +#define MODULE_CONFIG_FILE_PATH CONFIG_ROOR_DIR"/wifi_hal_vendor.conf" +#define PATH_NUM 2 +#define BUFF_SIZE 256 + static int ReadConfigModuleName(char *name, int size) { if (name == NULL) { - return -1; + return HAL_FAILURE; } FILE *fp = fopen(MODULE_CONFIG_FILE_PATH, "r"); if (fp == NULL) { LOGE("open module configuration file failed"); - return 0; /* file not exist, use default operators */ + return HAL_SUCCESS; /* file not exist, use default operators */ } int flag = 0; do { @@ -59,21 +66,21 @@ static int ReadConfigModuleName(char *name, int size) static int OpenHalVendorModule(WifiHalVendorInterface *pInterface) { if (pInterface == NULL) { - return -1; + return HAL_FAILURE; } char name[MODULE_NAME_MAX_LEN] = {0}; if (ReadConfigModuleName(name, MODULE_NAME_MAX_LEN) < 0) { - return -1; + return HAL_FAILURE; } if (strlen(name) <= 0) { LOGW("module name is null."); - return 0; + return HAL_SUCCESS; } void *handle = dlopen(name, RTLD_LAZY); if (handle == NULL) { LOGE("open config [%{public}s] so failed![%{public}s]", name, dlerror()); - return -1; + return HAL_FAILURE; } int flag = 0; do { @@ -97,9 +104,9 @@ static int OpenHalVendorModule(WifiHalVendorInterface *pInterface) } while (0); if (flag == 0) { dlclose(handle); - return -1; + return HAL_FAILURE; } - return 0; + return HAL_SUCCESS; } WifiHalVendorInterface *GetWifiHalVendorInterface(void) @@ -133,3 +140,49 @@ void ReleaseWifiHalVendorInterface(void) } return; } + +int ExcuteCmd(const char *szCmd) +{ + LOGI("Execute cmd: %{private}s", szCmd); + int ret = system(szCmd); + if (ret == -1) { + LOGE("Execute system cmd %{private}s failed!", szCmd); + return HAL_FAILURE; + } + if (WIFEXITED(ret) && (WEXITSTATUS(ret) == 0)) { + return HAL_SUCCESS; + } + LOGE("Execute system cmd %{private}s failed: %{private}d", szCmd, WEXITSTATUS(ret)); + return HAL_FAILURE; +} + +int CopyConfigFile(const char* configName) +{ + char buf[BUFF_SIZE] = {0}; + if (snprintf_s(buf, sizeof(buf), sizeof(buf) - 1, "%s/wpa_supplicant/%s", CONFIG_ROOR_DIR, configName) < 0) { + LOGE("snprintf_s dest dir failed."); + return HAL_FAILURE; + } + if (access(buf, F_OK) != -1) { + LOGI("Configure file %{public}s is exist.", buf); + return HAL_SUCCESS; + } + char path[PATH_NUM][BUFF_SIZE] = {"/vendor/etc/wifi/", "/system/etc/wifi/"}; + for (int i = 0; i != PATH_NUM; ++i) { + if (strcat_s(path[i], sizeof(path[i]), configName) != EOK) { + LOGE("strcat_s failed."); + return HAL_FAILURE; + } + if (access(path[i], F_OK) != -1) { + char cmd[BUFF_SIZE] = {0}; + if (snprintf_s(cmd, sizeof(cmd), sizeof(cmd) - 1, + "cp %s %s/wpa_supplicant/", path[i], CONFIG_ROOR_DIR) < 0) { + LOGE("snprintf_s cp cmd failed."); + return HAL_FAILURE; + } + return ExcuteCmd(cmd); + } + } + LOGE("Copy config file failed: %{public}s", configName); + return HAL_FAILURE; +} \ No newline at end of file diff --git a/services/wifi_standard/wifi_hal/wifi_hal_adapter.h b/wifi/services/wifi_standard/wifi_hal/wifi_hal_adapter.h similarity index 93% rename from services/wifi_standard/wifi_hal/wifi_hal_adapter.h rename to wifi/services/wifi_standard/wifi_hal/wifi_hal_adapter.h index caf12bf394555f0a3aecf8ccd64216fc41be5bef..d2229769f85e9ecb610c28fe27622bf7de3a5689 100644 --- a/services/wifi_standard/wifi_hal/wifi_hal_adapter.h +++ b/wifi/services/wifi_standard/wifi_hal/wifi_hal_adapter.h @@ -39,6 +39,9 @@ WifiHalVendorInterface *GetWifiHalVendorInterface(void); */ void ReleaseWifiHalVendorInterface(void); +int ExcuteCmd(const char *szCmd); + +int CopyConfigFile(const char* configName); #ifdef __cplusplus } #endif diff --git a/services/wifi_standard/wifi_hal/wifi_hal_ap_interface.c b/wifi/services/wifi_standard/wifi_hal/wifi_hal_ap_interface.c similarity index 54% rename from services/wifi_standard/wifi_hal/wifi_hal_ap_interface.c rename to wifi/services/wifi_standard/wifi_hal/wifi_hal_ap_interface.c index db75e53202d340580205c4f288688d729fe2d545..95663e1f0283c13176359b7e232dde24e7d81e89 100644 --- a/services/wifi_standard/wifi_hal/wifi_hal_ap_interface.c +++ b/wifi/services/wifi_standard/wifi_hal/wifi_hal_ap_interface.c @@ -1,5 +1,5 @@ /* - * Copyright (C) 2021 Huawei Device Co., Ltd. + * Copyright (C) 2021-2022 Huawei Device Co., Ltd. * 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 @@ -12,189 +12,226 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + #include "wifi_hal_ap_interface.h" #include #include +#include "wifi_hal_adapter.h" #include "wifi_hal_module_manage.h" #include "wifi_hal_common_func.h" +#ifdef HDI_INTERFACE_SUPPORT +#include "wifi_hdi_proxy.h" +#endif #include "wifi_log.h" +#include "wifi_wpa_hal.h" #include "wifi_hostapd_hal.h" #undef LOG_TAG #define LOG_TAG "WifiHalApInterface" -#define BUFF_SIZE 1024 +#define DISABLE_AP_WAIT_MS 50000 +#define ABLE_AP_WAIT_MS 50000 +#define WIFI_MULTI_CMD_MAX_LEN 1024 +#define IFCAE_NAME_LEN 256 static const char *g_serviceName = "hostapd"; -static const char *g_startCmd = "hostapd /data/misc/wifi/wpa_supplicant/hostapd.conf"; -static int ExcuteStaCmd(const char *szCmd) +WifiErrorNo StartSoftAp(int id) { - int ret = system(szCmd); - if (ret == -1) { - LOGE("system cmd %{public}s failed!", szCmd); - } else { - if (WIFEXITED(ret)) { - if (WEXITSTATUS(ret) == 0) { - return 0; - } - LOGE("system cmd %{public}s failed, return status %{public}d", szCmd, WEXITSTATUS(ret)); - } else { - LOGE("system cmd %{public}s failed", szCmd); - } - } - - return -1; -} - -WifiErrorNo StartSoftAp(void) -{ - LOGD("Ready to start hostapd"); + LOGI("Ready to start hostapd: %{public}d!", id); + char ifaceName[IFCAE_NAME_LEN] = {0}; if (StartHostapd() != WIFI_HAL_SUCCESS) { LOGE("hostapd start failed!"); return WIFI_HAL_OPEN_HOSTAPD_FAILED; } - - if (StartHostapdHal() != WIFI_HAL_SUCCESS) { + if (StartHostapdHal(id) != WIFI_HAL_SUCCESS) { LOGE("hostapd init failed!"); return WIFI_HAL_HOSTAPD_NOT_INIT; } - - LOGD("AP start successfully!"); + WifiHostapdHalDevice *hostapdHalDevice = GetWifiHostapdDev(id); + if (hostapdHalDevice == NULL) { + LOGE("hostapdHalDevice is NULL!"); + return WIFI_HAL_HOSTAPD_NOT_INIT; + } + int ret = sprintf_s(ifaceName, IFCAE_NAME_LEN, AP_INTF"%d", id); + if (ret == -1) { + LOGE("StartSoftAp failed! ret=%{public}d", ret); + return WIFI_HAL_FAILED; + } + if (GetIfaceState(ifaceName) == 0 || id > 0) { + ret = hostapdHalDevice->enableAp(id); + if (ret != 0) { + LOGE("enableAp failed! ret=%{public}d", ret); + return WIFI_HAL_FAILED; + } + } +#ifdef HDI_INTERFACE_SUPPORT + if (HdiStart() != WIFI_HAL_SUCCESS) { + LOGE("[Ap] Start hdi failed!"); + return WIFI_HAL_FAILED; + } +#endif + LOGI("AP start successfully, id:%{public}d!", id); return WIFI_HAL_SUCCESS; } WifiErrorNo StartHostapd(void) { - const char *pConf = "/data/misc/wifi/wpa_supplicant/hostapd.conf"; - if ((access(pConf, F_OK)) != -1) { - LOGD("wpa configure file %s is exist.", pConf); - } else { - char szCmd[BUFF_SIZE] = {0}; - const char *cpConfCmd = "cp /system/etc/wifi/hostapd.conf /data/misc/wifi/wpa_supplicant"; - int iRet = snprintf_s(szCmd, sizeof(szCmd), sizeof(szCmd) - 1, "%s", cpConfCmd); - if (iRet < 0) { - return -1; + char startCmd[WIFI_MULTI_CMD_MAX_LEN] = {0}; + char *p = startCmd; + int onceMove = 0; + int sumMove = 0; + onceMove = snprintf_s(p, WIFI_MULTI_CMD_MAX_LEN - sumMove, + WIFI_MULTI_CMD_MAX_LEN - sumMove -1, "%s", g_serviceName); + if (onceMove < 0) { + return WIFI_HAL_FAILED; + } + p = p + onceMove; + sumMove = sumMove + onceMove; + int num; + WifiHostapdHalDeviceInfo *cfg = GetWifiCfg(&num); + if (cfg == NULL) { + return WIFI_HAL_FAILED; + } + for (int i = 0; i < num; i++) { + if (CopyConfigFile(cfg[i].cfgName) != 0) { + return WIFI_HAL_FAILED; } - - ExcuteStaCmd(szCmd); + onceMove = snprintf_s(p, WIFI_MULTI_CMD_MAX_LEN - sumMove, + WIFI_MULTI_CMD_MAX_LEN - sumMove -1, " %s", cfg[i].config); + if (onceMove < 0) { + return WIFI_HAL_FAILED; + } + p = p + onceMove; + sumMove = sumMove + onceMove; } - ModuleManageRetCode ret = StartModule(g_serviceName, g_startCmd); + ModuleManageRetCode ret = StartModule(g_serviceName, startCmd); if (ret == MM_SUCCESS) { return WIFI_HAL_SUCCESS; } - + LOGE("start hostapd failed!"); return WIFI_HAL_FAILED; } -WifiErrorNo StartHostapdHal(void) +WifiErrorNo StartHostapdHal(int id) { LOGD("Ready to init hostapd"); - WifiHostapdHalDevice *hostapdHalDevice = GetWifiHostapdDev(); + WifiHostapdHalDevice *hostapdHalDevice = GetWifiHostapdDev(id); if (hostapdHalDevice == NULL) { return WIFI_HAL_FAILED; } return WIFI_HAL_SUCCESS; } -WifiErrorNo StopSoftAp(void) +WifiErrorNo StopSoftAp(int id) { +#ifdef HDI_INTERFACE_SUPPORT + if (HdiStop() != WIFI_HAL_SUCCESS) { + LOGE("[Ap] Stop hdi failed!"); + return WIFI_HAL_FAILED; + } +#endif + WifiHostapdHalDevice *hostapdHalDevice = GetWifiHostapdDev(id); + if (hostapdHalDevice != NULL) { + int ret = hostapdHalDevice->disableAp(id); + if (ret != 0) { + LOGE("disableAp failed! ret=%{public}d", ret); + } + } else { + LOGE("cant not get hostapd dev"); + } if (StopHostapd() != WIFI_HAL_SUCCESS) { LOGE("hostapd stop failed!"); return WIFI_HAL_FAILED; } - - if (StopHostapdHal() != WIFI_HAL_SUCCESS) { + if (StopHostapdHal(id) != WIFI_HAL_SUCCESS) { LOGE("hostapd_hal stop failed!"); return WIFI_HAL_FAILED; } - - LOGD("AP stop successfully!"); + LOGI("AP stop successfully!"); return WIFI_HAL_SUCCESS; } WifiErrorNo StopHostapd(void) { ModuleManageRetCode ret; - do { - ret = StopModule(g_serviceName); - if (ret == MM_FAILED) { - LOGE("stop hostapd failed!"); - return WIFI_HAL_FAILED; - } - } while (ret == MM_REDUCE_REFERENCE); + ret = StopModule(g_serviceName, true); + if (ret == MM_FAILED) { + LOGE("stop hostapd failed!"); + return WIFI_HAL_FAILED; + } return WIFI_HAL_SUCCESS; } -WifiErrorNo StopHostapdHal(void) +WifiErrorNo StopHostapdHal(int id) { - ReleaseHostapdDev(); + ReleaseHostapdDev(id); return WIFI_HAL_SUCCESS; } -WifiErrorNo GetStaInfos(char *infos, int32_t *size) +WifiErrorNo GetStaInfos(char *infos, int32_t *size, int id) { if (infos == NULL || size == NULL) { LOGE("GetStaInfos infos or size is NULL"); return WIFI_HAL_FAILED; } LOGD("GetStaInfos:Start"); - WifiHostapdHalDevice *hostapdHalDevice = GetWifiHostapdDev(); + WifiHostapdHalDevice *hostapdHalDevice = GetWifiHostapdDev(id); if (hostapdHalDevice == NULL) { return WIFI_HAL_HOSTAPD_NOT_INIT; } - if (hostapdHalDevice->showConnectedDevList(infos, *size) != 0) { + if (hostapdHalDevice->showConnectedDevList(infos, *size, id) != 0) { LOGE("ShowConnectedDevList failed!"); return WIFI_HAL_FAILED; } return WIFI_HAL_SUCCESS; } -WifiErrorNo SetCountryCode(const char *code) +WifiErrorNo SetCountryCode(const char *code, int id) { if (code == NULL || strlen(code) != WIFI_COUNTRY_CODE_MAXLEN) { LOGE("SetCountryCode code is invalid"); return WIFI_HAL_INVALID_PARAM; } LOGD("SetCountryCode() code: %{public}s", code); - WifiHostapdHalDevice *hostapdHalDevice = GetWifiHostapdDev(); + WifiHostapdHalDevice *hostapdHalDevice = GetWifiHostapdDev(id); if (hostapdHalDevice == NULL) { return WIFI_HAL_HOSTAPD_NOT_INIT; } - if (hostapdHalDevice->setCountryCode(code) != 0) { + if (hostapdHalDevice->setCountryCode(code, id) != 0) { LOGE("SetCountryCode failed!"); return WIFI_HAL_FAILED; } return WIFI_HAL_SUCCESS; } -WifiErrorNo SetHostapdConfig(HostapdConfig *config) +WifiErrorNo SetHostapdConfig(HostapdConfig *config, int id) { if (config == NULL) { LOGE("SetHostapdConfig config is NULL"); return WIFI_HAL_FAILED; } LOGD("SetHostapdConfig()"); - WifiHostapdHalDevice *hostapdHalDevice = GetWifiHostapdDev(); + WifiHostapdHalDevice *hostapdHalDevice = GetWifiHostapdDev(id); if (hostapdHalDevice == NULL) { return WIFI_HAL_HOSTAPD_NOT_INIT; } - int ret = hostapdHalDevice->setApInfo(config); + int ret = hostapdHalDevice->setApInfo(config, id); if (ret != 0) { LOGE("SetApInfo failed!"); return WIFI_HAL_FAILED; } - ret = hostapdHalDevice->reloadApConfigInfo(); + ret = hostapdHalDevice->reloadApConfigInfo(id); if (ret != 0) { LOGE("ReloadApConfigInfo failed!"); return WIFI_HAL_FAILED; } - ret = hostapdHalDevice->disableAp(); + ret = hostapdHalDevice->disableAp(id); if (ret != 0) { LOGE("DisableAp failed!"); return WIFI_HAL_FAILED; } - ret = hostapdHalDevice->enableAp(); + ret = hostapdHalDevice->enableAp(id); if (ret != 0) { LOGE("EnableAp failed!"); return WIFI_HAL_FAILED; @@ -203,7 +240,7 @@ WifiErrorNo SetHostapdConfig(HostapdConfig *config) return WIFI_HAL_SUCCESS; } -WifiErrorNo SetMacFilter(const unsigned char *mac, int lenMac) +WifiErrorNo SetMacFilter(const unsigned char *mac, int lenMac, int id) { if (mac == NULL) { LOGE("SetMacFilter is NULL"); @@ -217,18 +254,18 @@ WifiErrorNo SetMacFilter(const unsigned char *mac, int lenMac) if (CheckMacIsValid((const char *)mac) != 0) { return WIFI_HAL_INPUT_MAC_INVALID; } - WifiHostapdHalDevice *hostapdHalDevice = GetWifiHostapdDev(); + WifiHostapdHalDevice *hostapdHalDevice = GetWifiHostapdDev(id); if (hostapdHalDevice == NULL) { return WIFI_HAL_HOSTAPD_NOT_INIT; } - if (hostapdHalDevice->addBlocklist((const char *)mac) != 0) { + if (hostapdHalDevice->addBlocklist((const char *)mac, id) != 0) { LOGE("AddBlocklist failed!"); return WIFI_HAL_FAILED; } return WIFI_HAL_SUCCESS; } -WifiErrorNo DelMacFilter(const unsigned char *mac, int lenMac) +WifiErrorNo DelMacFilter(const unsigned char *mac, int lenMac, int id) { if (mac == NULL) { LOGE("DelMacFilter is NULL"); @@ -242,18 +279,18 @@ WifiErrorNo DelMacFilter(const unsigned char *mac, int lenMac) if (CheckMacIsValid((const char *)mac) != 0) { return WIFI_HAL_INPUT_MAC_INVALID; } - WifiHostapdHalDevice *hostapdHalDevice = GetWifiHostapdDev(); + WifiHostapdHalDevice *hostapdHalDevice = GetWifiHostapdDev(id); if (hostapdHalDevice == NULL) { return WIFI_HAL_HOSTAPD_NOT_INIT; } - if (hostapdHalDevice->delBlocklist((const char *)mac) != 0) { + if (hostapdHalDevice->delBlocklist((const char *)mac, id) != 0) { LOGE("DelBlocklist failed!"); return WIFI_HAL_FAILED; } return WIFI_HAL_SUCCESS; } -WifiErrorNo DisassociateSta(const unsigned char *mac, int lenMac) +WifiErrorNo DisassociateSta(const unsigned char *mac, int lenMac, int id) { if (mac == NULL) { LOGE("DisassociateSta is NULL"); @@ -267,23 +304,35 @@ WifiErrorNo DisassociateSta(const unsigned char *mac, int lenMac) if (CheckMacIsValid((const char *)mac) != 0) { return WIFI_HAL_INPUT_MAC_INVALID; } - WifiHostapdHalDevice *hostapdHalDevice = GetWifiHostapdDev(); + WifiHostapdHalDevice *hostapdHalDevice = GetWifiHostapdDev(id); if (hostapdHalDevice == NULL) { return WIFI_HAL_HOSTAPD_NOT_INIT; } - if (hostapdHalDevice->disConnectedDev((const char *)mac) != 0) { + if (hostapdHalDevice->disConnectedDev((const char *)mac, id) != 0) { LOGE("DisConnectedDev failed!"); return WIFI_HAL_FAILED; } return WIFI_HAL_SUCCESS; } -WifiErrorNo GetValidFrequenciesForBand(int32_t band, int *frequencies, int32_t *size) +WifiErrorNo GetValidFrequenciesForBand(int32_t band, int *frequencies, int32_t *size, int id) { if (frequencies == NULL || size == NULL) { - LOGE("GetValidFrequenciesForBand frequencies or size is NULL"); + LOGE("%{public}s frequencies or size is null.", __func__); return WIFI_HAL_FAILED; } - LOGD("GetValidFrequenciesForBand"); - return WIFI_HAL_NOT_SUPPORT; + LOGE("%{public}s func is not support!", __func__); + return WIFI_HAL_FAILED; +} + +WifiErrorNo WifiSetPowerModel(const int mode, int id) +{ + LOGE("%{public}s func is not support!", __func__); + return WIFI_HAL_FAILED; +} + +WifiErrorNo WifiGetPowerModel(int* mode, int id) +{ + LOGE("%{public}s func is not support!", __func__); + return WIFI_HAL_FAILED; } diff --git a/services/wifi_standard/wifi_hal/wifi_hal_ap_interface.h b/wifi/services/wifi_standard/wifi_hal/wifi_hal_ap_interface.h similarity index 70% rename from services/wifi_standard/wifi_hal/wifi_hal_ap_interface.h rename to wifi/services/wifi_standard/wifi_hal/wifi_hal_ap_interface.h index bb18367104fe4eeee3aa16f3b445dc0089d61ece..5613563d70b5fa9f69419943acc09756672263b4 100644 --- a/services/wifi_standard/wifi_hal/wifi_hal_ap_interface.h +++ b/wifi/services/wifi_standard/wifi_hal/wifi_hal_ap_interface.h @@ -1,5 +1,5 @@ /* - * Copyright (C) 2021 Huawei Device Co., Ltd. + * Copyright (C) 2021-2022 Huawei Device Co., Ltd. * 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 @@ -30,13 +30,15 @@ extern "C" { /** * @Description Start Ap. * + * @param id - ap id * @return WifiErrorNo */ -WifiErrorNo StartSoftAp(void); +WifiErrorNo StartSoftAp(int id); /** * @Description Start Hostapd. * + * @param id - ap id * @return WifiErrorNo */ WifiErrorNo StartHostapd(void); @@ -44,16 +46,17 @@ WifiErrorNo StartHostapd(void); /** * @Description Init hostapd hal module. * + * @param id - ap id * @return WifiErrorNo */ -WifiErrorNo StartHostapdHal(void); +WifiErrorNo StartHostapdHal(int id); /** * @Description Stop Ap. * * @return WifiErrorNo */ -WifiErrorNo StopSoftAp(void); +WifiErrorNo StopSoftAp(int id); /** * @Description Stop hostapd. @@ -65,9 +68,10 @@ WifiErrorNo StopHostapd(void); /** * @Description Release hostapd hal. * + * @param id - ap id * @return WifiErrorNo */ -WifiErrorNo StopHostapdHal(void); +WifiErrorNo StopHostapdHal(int id); /** * @Description Obtains information about all connected STAs. @@ -75,25 +79,28 @@ WifiErrorNo StopHostapdHal(void); * @param infos - Connected STA information array. * @param size - Obtains the size of all sta information arrays and Size of the * obtained sta information array. + * @param id - ap id * @return WifiErrorNo */ -WifiErrorNo GetStaInfos(char *infos, int32_t *size); +WifiErrorNo GetStaInfos(char *infos, int32_t *size, int id); /** * @Description Setting the AP Country Code. * * @param code - Country code. + * @param id - ap id * @return WifiErrorNo */ -WifiErrorNo SetCountryCode(const char *code); +WifiErrorNo SetCountryCode(const char *code, int id); /** * @Description Setting the startup configuration items of the hostapd. * * @param config - Hostapd startup configuration. + * @param id - ap id * @return WifiErrorNo */ -WifiErrorNo SetHostapdConfig(HostapdConfig *config); +WifiErrorNo SetHostapdConfig(HostapdConfig *config, int id); /** * @Description To set the blocklist filtering in AP mode to prohibit @@ -101,9 +108,10 @@ WifiErrorNo SetHostapdConfig(HostapdConfig *config); * * @param mac - Blocklisted MAC address. * @param lenMac - Blocklist MAC address length. + * @param id - ap id * @return WifiErrorNo */ -WifiErrorNo SetMacFilter(const unsigned char *mac, int lenMac); +WifiErrorNo SetMacFilter(const unsigned char *mac, int lenMac, int id); /** * @Description To set blocklist filtering in AP mode and delete a specified MAC @@ -111,18 +119,20 @@ WifiErrorNo SetMacFilter(const unsigned char *mac, int lenMac); * * @param mac - Blocklisted MAC address. * @param lenMac - Blocklist MAC address length. + * @param id - ap id * @return WifiErrorNo */ -WifiErrorNo DelMacFilter(const unsigned char *mac, int lenMac); +WifiErrorNo DelMacFilter(const unsigned char *mac, int lenMac, int id); /** * @Description Disconnect the STA with a specified MAC address. * * @param mac - Blocklisted MAC address. * @param lenMac - Blocklist MAC address length. + * @param id - ap id * @return WifiErrorNo */ -WifiErrorNo DisassociateSta(const unsigned char *mac, int lenMac); +WifiErrorNo DisassociateSta(const unsigned char *mac, int lenMac, int id); /** * @Description Obtains the hotspot frequency supported by a specified @@ -131,10 +141,28 @@ WifiErrorNo DisassociateSta(const unsigned char *mac, int lenMac); * @param band - Specified frequency band. * @param frequencies - Frequency array. * @param size - Frequency array memory size and Returns the size of the frequency array. + * @param id - ap id * @return WifiErrorNo */ -WifiErrorNo GetValidFrequenciesForBand(int32_t band, int *frequencies, int32_t *size); +WifiErrorNo WEAK_FUNC GetValidFrequenciesForBand(int32_t band, int *frequencies, int32_t *size, int id); +/** + * @Description Set the power mode. + * + * @param mode - power mode. + * @param id - ap id + * @return WifiErrorNo + */ +WifiErrorNo WEAK_FUNC WifiSetPowerModel(const int mode, int id); + +/** + * @Description Get the power mode. + * + * @param mode - power mode. + * @param id - ap id + * @return WifiErrorNo + */ +WifiErrorNo WEAK_FUNC WifiGetPowerModel(int* mode, int id); #ifdef __cplusplus } #endif diff --git a/services/wifi_standard/wifi_hal/wifi_hal_base_interface.c b/wifi/services/wifi_standard/wifi_hal/wifi_hal_base_interface.c similarity index 100% rename from services/wifi_standard/wifi_hal/wifi_hal_base_interface.c rename to wifi/services/wifi_standard/wifi_hal/wifi_hal_base_interface.c diff --git a/services/wifi_standard/wifi_hal/wifi_hal_base_interface.h b/wifi/services/wifi_standard/wifi_hal/wifi_hal_base_interface.h similarity index 100% rename from services/wifi_standard/wifi_hal/wifi_hal_base_interface.h rename to wifi/services/wifi_standard/wifi_hal/wifi_hal_base_interface.h diff --git a/services/wifi_standard/wifi_hal/wifi_hal_callback.c b/wifi/services/wifi_standard/wifi_hal/wifi_hal_callback.c similarity index 75% rename from services/wifi_standard/wifi_hal/wifi_hal_callback.c rename to wifi/services/wifi_standard/wifi_hal/wifi_hal_callback.c index ede9dfb310669ab125d55f503103931a171c9617..a7cbf79cb073c97c3c4f897262c38a0975fa9d1b 100644 --- a/services/wifi_standard/wifi_hal/wifi_hal_callback.c +++ b/wifi/services/wifi_standard/wifi_hal/wifi_hal_callback.c @@ -1,5 +1,5 @@ /* - * Copyright (C) 2021 Huawei Device Co., Ltd. + * Copyright (C) 2021-2022 Huawei Device Co., Ltd. * 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 @@ -14,6 +14,7 @@ */ #include "wifi_hal_callback.h" +#include #include "wifi_log.h" #include "wifi_hal_crpc_server.h" #include "wifi_hal_define.h" @@ -31,23 +32,25 @@ static void EmitEventCallbackMsg(WifiHalEventCallbackMsg *pCbkMsg, WifiHalEvent if (server == NULL) { LOGE("Rpc server not exists!"); free(pCbkMsg); + pCbkMsg = NULL; return; } if (PushBackCallbackMsg(event, pCbkMsg) != 0) { free(pCbkMsg); + pCbkMsg = NULL; return; } if (EmitEvent(server, event) < 0) { PopBackCallbackMsg(event); free(pCbkMsg); + pCbkMsg = NULL; } return; } - void WifiHalCbNotifyScanEnd(int status) { - LOGD("Get Scan status: %{public}d, and begin push notify message", status); + LOGI("Get Scan status: %{public}d, and begin push notify message", status); WifiHalEventCallbackMsg *pCbkMsg = (WifiHalEventCallbackMsg *)calloc(1, sizeof(WifiHalEventCallbackMsg)); if (pCbkMsg == NULL) { LOGE("create callback message failed!"); @@ -64,7 +67,7 @@ void WifiHalCbNotifyConnectChanged(int status, int networkId, const char *pos) LOGI("Get connect state changed, pos is NULL"); return; } - LOGD("Get connect state changed, state: %{public}d, networkid = %{public}d", status, networkId); + LOGI("Get connect state changed, state: %{public}d, networkid = %{public}d", status, networkId); WifiHalEventCallbackMsg *pCbkMsg = (WifiHalEventCallbackMsg *)calloc(1, sizeof(WifiHalEventCallbackMsg)); if (pCbkMsg == NULL) { LOGE("create callback message failed!"); @@ -77,9 +80,34 @@ void WifiHalCbNotifyConnectChanged(int status, int networkId, const char *pos) return; } +void WifiHalCbNotifyBssidChanged(const char *reasonPos, const char *bssidPos) +{ + char reason[WIFI_REASON_LENGTH] = {0}; + if (reasonPos == NULL || bssidPos == NULL) { + LOGE("reasonPos or bssidPos is NULL"); + return; + } + char *reasonEnd = strchr(reasonPos, ' '); + if (reasonEnd != NULL) { + int reasonLen = reasonEnd - reasonPos; + reasonLen = reasonLen > WIFI_REASON_LENGTH ? WIFI_REASON_LENGTH : reasonLen; + (void)memcpy_s(reason, sizeof(reason), reasonPos, reasonLen); + } + + LOGI("bssid changed event, reason: %{public}s, bssid = %{private}s", reason, bssidPos); + WifiHalEventCallbackMsg *pCbkMsg = (WifiHalEventCallbackMsg *)calloc(1, sizeof(WifiHalEventCallbackMsg)); + if (pCbkMsg == NULL) { + LOGE("create callback message failed!"); + return; + } + (void)memcpy_s(pCbkMsg->msg.bssidChangedMsg.reason, WIFI_REASON_LENGTH, reason, WIFI_REASON_LENGTH); + (void)memcpy_s(pCbkMsg->msg.bssidChangedMsg.bssid, WIFI_MAC_LENGTH + 1, bssidPos, WIFI_MAC_LENGTH + 1); + EmitEventCallbackMsg(pCbkMsg, WIFI_BSSID_CHANGED_NOTIFY_EVENT); +} + void WifiHalCbNotifyWpaStateChange(int status) { - LOGD("wpa state changed, state: %{public}d, and begin push notify message", status); + LOGI("wpa state changed, state: %{public}d, and begin push notify message", status); WifiHalEventCallbackMsg *pCbkMsg = (WifiHalEventCallbackMsg *)calloc(1, sizeof(WifiHalEventCallbackMsg)); if (pCbkMsg == NULL) { LOGE("create callback message failed!"); @@ -92,7 +120,7 @@ void WifiHalCbNotifyWpaStateChange(int status) void WifiHalCbNotifyWrongKey(int status) { - LOGD("wrong key, state: %{public}d, and begin push notify message", status); + LOGI("wrong key, state: %{public}d, and begin push notify message", status); WifiHalEventCallbackMsg *pCbkMsg = (WifiHalEventCallbackMsg *)calloc(1, sizeof(WifiHalEventCallbackMsg)); if (pCbkMsg == NULL) { LOGE("create callback message failed!"); @@ -103,9 +131,37 @@ void WifiHalCbNotifyWrongKey(int status) return; } +void WifiHalCbNotifyConnectionFull(int status) +{ + LOGI("connection is full, state: %{public}d, and begin push notify message", status); + WifiHalEventCallbackMsg *pCbkMsg = (WifiHalEventCallbackMsg *)calloc(1, sizeof(WifiHalEventCallbackMsg)); + if (pCbkMsg == NULL) { + LOGE("create callback message failed!"); + return; + } + + pCbkMsg->msg.connMsg.status = status; + EmitEventCallbackMsg(pCbkMsg, WIFI_CONNECTION_FULL_EVENT); + return; +} + +void WifiHalCbNotifyConnectionReject(int status) +{ + LOGI("connection is eeject, state: %{public}d, and begin push notify message", status); + WifiHalEventCallbackMsg *pCbkMsg = (WifiHalEventCallbackMsg *)calloc(1, sizeof(WifiHalEventCallbackMsg)); + if (pCbkMsg == NULL) { + LOGE("create callback message failed!"); + return; + } + + pCbkMsg->msg.connMsg.status = status; + EmitEventCallbackMsg(pCbkMsg, WIFI_CONNECTION_REJECT_EVENT); + return; +} + void WifiHalCbNotifyWpsOverlap(int event) { - LOGD("wps overlap, state: %{public}d, and begin push notify message", event); + LOGI("wps overlap, state: %{public}d, and begin push notify message", event); WifiHalEventCallbackMsg *pCbkMsg = (WifiHalEventCallbackMsg *)calloc(1, sizeof(WifiHalEventCallbackMsg)); if (pCbkMsg == NULL) { LOGE("create callback message failed!"); @@ -118,7 +174,7 @@ void WifiHalCbNotifyWpsOverlap(int event) void WifiHalCbNotifyWpsTimeOut(int event) { - LOGD("wps time out, state: %{public}d, and begin push notify message", event); + LOGI("wps time out, state: %{public}d, and begin push notify message", event); WifiHalEventCallbackMsg *pCbkMsg = (WifiHalEventCallbackMsg *)calloc(1, sizeof(WifiHalEventCallbackMsg)); if (pCbkMsg == NULL) { LOGE("create callback message failed!"); @@ -129,13 +185,13 @@ void WifiHalCbNotifyWpsTimeOut(int event) return; } -void WifiHalCbStaJoin(const char *content) +void WifiHalCbStaJoin(const char *content, int id) { if (content == NULL) { LOGD("Get hostapd Sta join content is NULL"); return; } - LOGD("Get hostapd Sta join"); + LOGD("Get hostapd Sta join, instance id:%{public}d", id); WifiHalEvent event; char tmpBuf[WIFI_BSSID_LENGTH] = {0}; if (strncmp("AP-STA-CONNECTED", content, strlen("AP-STA-CONNECTED")) == 0) { @@ -152,19 +208,20 @@ void WifiHalCbStaJoin(const char *content) LOGE("hostapd create callback message failed!"); return; } + pCbkMsg->msg.ifMsg.id = id; pCbkMsg->msg.ifMsg.type = event; StrSafeCopy(pCbkMsg->msg.ifMsg.ifname, sizeof(pCbkMsg->msg.ifMsg.ifname), tmpBuf); EmitEventCallbackMsg(pCbkMsg, event); return; } -void WifiHalCbApState(const char *content) +void WifiHalCbApState(const char *content, int id) { if (content == NULL) { LOGD("Get hostapd status changed content is NULL"); return; } - LOGD("Get hostapd status changed"); + LOGD("Get hostapd status changed, instance id:%{public}d", id); WifiHalEvent event; if (strncmp(content, "AP-ENABLED", strlen("AP-ENABLED")) == 0) { event = WIFI_AP_ENABLE_EVENT; @@ -174,18 +231,21 @@ void WifiHalCbApState(const char *content) } else { return; } - RpcServer *server = GetRpcServer(); - if (server == NULL) { - LOGE("Rpc server not exists!"); + + WifiHalEventCallbackMsg *pCbkMsg = (WifiHalEventCallbackMsg *)calloc(1, sizeof(WifiHalEventCallbackMsg)); + if (pCbkMsg == NULL) { + LOGE("hostapd create callback message failed!"); return; } - EmitEvent(server, event); + pCbkMsg->msg.ifMsg.type = event; + pCbkMsg->msg.ifMsg.id = id; + EmitEventCallbackMsg(pCbkMsg, event); return; } void WifiP2pHalCbNotifyConnectSupplicant(int state) { - LOGD("P2p supplicant connect even : %{public}d", state); + LOGI("P2p supplicant connect even : %{public}d", state); WifiHalEventCallbackMsg *pCbkMsg = (WifiHalEventCallbackMsg *)calloc(1, sizeof(WifiHalEventCallbackMsg)); if (pCbkMsg == NULL) { LOGE("create callback message failed!"); @@ -196,12 +256,12 @@ void WifiP2pHalCbNotifyConnectSupplicant(int state) return; } -void P2pHalCbDeviceFound(const HidlP2pDeviceInfo *device) +void P2pHalCbDeviceFound(const P2pDeviceInfo *device) { if (device == NULL) { return; } - LOGD("P2p device found event deviceName: %{public}s", device->deviceName); + LOGI("P2p device found event deviceName: %{public}s", device->deviceName); WifiHalEventCallbackMsg *pCbkMsg = (WifiHalEventCallbackMsg *)calloc(1, sizeof(WifiHalEventCallbackMsg)); if (pCbkMsg == NULL) { LOGE("create callback message failed!"); @@ -218,7 +278,7 @@ void P2pHalCbDeviceLost(const char *p2pDeviceAddress) LOGI("P2p device lost event p2pDeviceAddress is NULL"); return; } - LOGD("P2p device lost event p2pDeviceAddress: %{private}s", p2pDeviceAddress); + LOGI("P2p device lost event p2pDeviceAddress: %{private}s", p2pDeviceAddress); WifiHalEventCallbackMsg *pCbkMsg = (WifiHalEventCallbackMsg *)calloc(1, sizeof(WifiHalEventCallbackMsg)); if (pCbkMsg == NULL) { LOGE("create callback message failed!"); @@ -227,6 +287,7 @@ void P2pHalCbDeviceLost(const char *p2pDeviceAddress) if (strncpy_s(pCbkMsg->msg.connMsg.bssid, sizeof(pCbkMsg->msg.connMsg.bssid), p2pDeviceAddress, sizeof(pCbkMsg->msg.connMsg.bssid) - 1) != EOK) { free(pCbkMsg); + pCbkMsg = NULL; return; } EmitEventCallbackMsg(pCbkMsg, P2P_DEVICE_LOST_EVENT); @@ -239,7 +300,7 @@ void P2pHalCbGoNegotiationRequest(const char *srcAddress, short passwordId) LOGI("P2p go negotiation request event srcAddress is NULL"); return; } - LOGD("P2p go negotiation request event srcAddress: %{private}s, passwordId: %{private}d", srcAddress, passwordId); + LOGI("P2p go negotiation request event srcAddress: %{private}s, passwordId: %{private}d", srcAddress, passwordId); WifiHalEventCallbackMsg *pCbkMsg = (WifiHalEventCallbackMsg *)calloc(1, sizeof(WifiHalEventCallbackMsg)); if (pCbkMsg == NULL) { LOGE("create callback message failed!"); @@ -249,6 +310,7 @@ void P2pHalCbGoNegotiationRequest(const char *srcAddress, short passwordId) if (strncpy_s(pCbkMsg->msg.connMsg.bssid, sizeof(pCbkMsg->msg.connMsg.bssid), srcAddress, sizeof(pCbkMsg->msg.connMsg.bssid) - 1) != EOK) { free(pCbkMsg); + pCbkMsg = NULL; return; } EmitEventCallbackMsg(pCbkMsg, P2P_GO_NEGOTIATION_REQUEST_EVENT); @@ -257,7 +319,7 @@ void P2pHalCbGoNegotiationRequest(const char *srcAddress, short passwordId) void P2pHalCbGoNegotiationSuccess() { - LOGD("P2p go negotiation success event"); + LOGI("P2p go negotiation success event"); RpcServer *server = GetRpcServer(); if (server == NULL) { LOGE("Rpc server not exists!"); @@ -269,7 +331,7 @@ void P2pHalCbGoNegotiationSuccess() void P2pHalCbGoNegotiationFailure(int status) { - LOGD("P2p go negotiation failure event status: %{public}d", status); + LOGI("P2p go negotiation failure event status: %{public}d", status); WifiHalEventCallbackMsg *pCbkMsg = (WifiHalEventCallbackMsg *)calloc(1, sizeof(WifiHalEventCallbackMsg)); if (pCbkMsg == NULL) { LOGE("create callback message failed!"); @@ -280,12 +342,12 @@ void P2pHalCbGoNegotiationFailure(int status) return; } -void P2pHalCbInvitationReceived(const HidlP2pInvitationInfo *info) +void P2pHalCbInvitationReceived(const P2pInvitationInfo *info) { if (info == NULL) { return; } - LOGD("P2p invitation received event srcAddress: %{private}s", info->srcAddress); + LOGI("P2p invitation received event srcAddress: %{private}s", info->srcAddress); WifiHalEventCallbackMsg *pCbkMsg = (WifiHalEventCallbackMsg *)calloc(1, sizeof(WifiHalEventCallbackMsg)); if (pCbkMsg == NULL) { LOGE("create callback message failed!"); @@ -302,7 +364,7 @@ void P2pHalCbInvitationResult(const char *bssid, int status) LOGI("P2p invitation result event bssid is NULL"); return; } - LOGD("P2p invitation result event bssid: %{private}s, status: %{public}d", bssid, status); + LOGI("P2p invitation result event bssid: %{private}s, status: %{public}d", bssid, status); WifiHalEventCallbackMsg *pCbkMsg = (WifiHalEventCallbackMsg *)calloc(1, sizeof(WifiHalEventCallbackMsg)); if (pCbkMsg == NULL) { LOGE("create callback message failed!"); @@ -312,6 +374,7 @@ void P2pHalCbInvitationResult(const char *bssid, int status) if (strncpy_s(pCbkMsg->msg.invitaInfo.bssid, sizeof(pCbkMsg->msg.invitaInfo.bssid), bssid, sizeof(pCbkMsg->msg.invitaInfo.bssid) - 1) != EOK) { free(pCbkMsg); + pCbkMsg = NULL; return; } EmitEventCallbackMsg(pCbkMsg, P2P_INVITATION_RESULT_EVENT); @@ -320,7 +383,7 @@ void P2pHalCbInvitationResult(const char *bssid, int status) void P2pHalCbGroupFormationSuccess() { - LOGD("P2p group formation success event"); + LOGI("P2p group formation success event"); RpcServer *server = GetRpcServer(); if (server == NULL) { LOGE("Rpc server not exists!"); @@ -336,7 +399,7 @@ void P2pHalCbGroupFormationFailure(const char *reason) LOGI("P2p group formation failure event reason is NULL"); return; } - LOGD("P2p group formation failure event reason: %{public}s", reason); + LOGW("P2p group formation failure event reason: %{public}s", reason); WifiHalEventCallbackMsg *pCbkMsg = (WifiHalEventCallbackMsg *)calloc(1, sizeof(WifiHalEventCallbackMsg)); if (pCbkMsg == NULL) { LOGE("create callback message failed!"); @@ -345,18 +408,19 @@ void P2pHalCbGroupFormationFailure(const char *reason) if (strncpy_s(pCbkMsg->msg.invitaInfo.bssid, sizeof(pCbkMsg->msg.invitaInfo.bssid), reason, sizeof(pCbkMsg->msg.invitaInfo.bssid) - 1) != EOK) { free(pCbkMsg); + pCbkMsg = NULL; return; } EmitEventCallbackMsg(pCbkMsg, P2P_GROUP_FORMATION_FAILURE_EVENT); return; } -void P2pHalCbGroupStarted(const HidlP2pGroupInfo *info) +void P2pHalCbGroupStarted(const P2pGroupInfo *info) { if (info == NULL) { return; } - LOGD("P2p group started event groupIfName: %{public}s", info->groupIfName); + LOGI("P2p group started event groupIfName: %{public}s", info->groupIfName); WifiHalEventCallbackMsg *pCbkMsg = (WifiHalEventCallbackMsg *)calloc(1, sizeof(WifiHalEventCallbackMsg)); if (pCbkMsg == NULL) { LOGE("create callback message failed!"); @@ -373,7 +437,7 @@ void P2pHalCbGroupRemoved(const char *groupIfName, int isGo) LOGI("P2p group removed event groupIfName is NULL"); return; } - LOGD("P2p group removed event groupIfName: %{public}s, isGo: %{public}d", groupIfName, isGo); + LOGW("P2p group removed event groupIfName: %{public}s, isGo: %{public}d", groupIfName, isGo); WifiHalEventCallbackMsg *pCbkMsg = (WifiHalEventCallbackMsg *)calloc(1, sizeof(WifiHalEventCallbackMsg)); if (pCbkMsg == NULL) { LOGE("create callback message failed!"); @@ -383,6 +447,7 @@ void P2pHalCbGroupRemoved(const char *groupIfName, int isGo) if (strncpy_s(pCbkMsg->msg.groupInfo.groupIfName, sizeof(pCbkMsg->msg.groupInfo.groupIfName), groupIfName, sizeof(pCbkMsg->msg.groupInfo.groupIfName) - 1) != EOK) { free(pCbkMsg); + pCbkMsg = NULL; return; } EmitEventCallbackMsg(pCbkMsg, P2P_GROUP_REMOVED_EVENT); @@ -395,7 +460,7 @@ void P2pHalCbProvisionDiscoveryPbcRequest(const char *address) LOGI("P2p provision discovery pbc request event address is NULL"); return; } - LOGD("P2p provision discovery pbc request event address: %{private}s", address); + LOGI("P2p provision discovery pbc request event address: %{private}s", address); WifiHalEventCallbackMsg *pCbkMsg = (WifiHalEventCallbackMsg *)calloc(1, sizeof(WifiHalEventCallbackMsg)); if (pCbkMsg == NULL) { LOGE("create callback message failed!"); @@ -404,6 +469,7 @@ void P2pHalCbProvisionDiscoveryPbcRequest(const char *address) if (strncpy_s(pCbkMsg->msg.deviceInfo.srcAddress, sizeof(pCbkMsg->msg.deviceInfo.srcAddress), address, sizeof(pCbkMsg->msg.deviceInfo.srcAddress) - 1) != EOK) { free(pCbkMsg); + pCbkMsg = NULL; return; } EmitEventCallbackMsg(pCbkMsg, P2P_PROV_DISC_PBC_REQ_EVENT); @@ -416,7 +482,7 @@ void P2pHalCbProvisionDiscoveryPbcResponse(const char *address) LOGI("P2p provision discovery pbc response event address is NULL"); return; } - LOGD("P2p provision discovery pbc response event address: %{private}s", address); + LOGI("P2p provision discovery pbc response event address: %{private}s", address); WifiHalEventCallbackMsg *pCbkMsg = (WifiHalEventCallbackMsg *)calloc(1, sizeof(WifiHalEventCallbackMsg)); if (pCbkMsg == NULL) { LOGE("create callback message failed!"); @@ -425,6 +491,7 @@ void P2pHalCbProvisionDiscoveryPbcResponse(const char *address) if (strncpy_s(pCbkMsg->msg.deviceInfo.srcAddress, sizeof(pCbkMsg->msg.deviceInfo.srcAddress), address, sizeof(pCbkMsg->msg.deviceInfo.srcAddress) - 1) != EOK) { free(pCbkMsg); + pCbkMsg = NULL; return; } EmitEventCallbackMsg(pCbkMsg, P2P_PROV_DISC_PBC_RSP_EVENT); @@ -437,7 +504,7 @@ void P2pHalCbProvisionDiscoveryEnterPin(const char *address) LOGI("P2p provision discovery enter pin event address is NULL"); return; } - LOGD("P2p provision discovery enter pin event address: %{private}s", address); + LOGI("P2p provision discovery enter pin event address: %{private}s", address); WifiHalEventCallbackMsg *pCbkMsg = (WifiHalEventCallbackMsg *)calloc(1, sizeof(WifiHalEventCallbackMsg)); if (pCbkMsg == NULL) { LOGE("create callback message failed!"); @@ -446,6 +513,7 @@ void P2pHalCbProvisionDiscoveryEnterPin(const char *address) if (strncpy_s(pCbkMsg->msg.deviceInfo.srcAddress, sizeof(pCbkMsg->msg.deviceInfo.srcAddress), address, sizeof(pCbkMsg->msg.deviceInfo.srcAddress) - 1) != EOK) { free(pCbkMsg); + pCbkMsg = NULL; return; } EmitEventCallbackMsg(pCbkMsg, P2P_PROV_DISC_ENTER_PIN_EVENT); @@ -458,7 +526,7 @@ void P2pHalCbProvisionDiscoveryShowPin(const char *address, const char *pin) LOGI("P2p provision discovery show pin event address or pin is NULL"); return; } - LOGD("P2p provision discovery show pin event address: %{private}s, pin: %{private}s", address, pin); + LOGI("P2p provision discovery show pin event address: %{private}s, pin: %{private}s", address, pin); WifiHalEventCallbackMsg *pCbkMsg = (WifiHalEventCallbackMsg *)calloc(1, sizeof(WifiHalEventCallbackMsg)); if (pCbkMsg == NULL) { LOGE("create callback message failed!"); @@ -469,6 +537,7 @@ void P2pHalCbProvisionDiscoveryShowPin(const char *address, const char *pin) strncpy_s(pCbkMsg->msg.deviceInfo.deviceName, sizeof(pCbkMsg->msg.deviceInfo.deviceName), pin, sizeof(pCbkMsg->msg.deviceInfo.deviceName) - 1) != EOK) { free(pCbkMsg); + pCbkMsg = NULL; return; } EmitEventCallbackMsg(pCbkMsg, P2P_PROV_DISC_SHOW_PIN_EVENT); @@ -477,7 +546,7 @@ void P2pHalCbProvisionDiscoveryShowPin(const char *address, const char *pin) void P2pHalCbProvisionDiscoveryFailure() { - LOGD("P2p provision discovery failure event"); + LOGW("P2p provision discovery failure event"); RpcServer *server = GetRpcServer(); if (server == NULL) { LOGE("Rpc server not exists!"); @@ -489,7 +558,7 @@ void P2pHalCbProvisionDiscoveryFailure() void P2pHalCbFindStopped() { - LOGD("P2p find stoped event"); + LOGW("P2p find stopped event"); RpcServer *server = GetRpcServer(); if (server == NULL) { LOGE("Rpc server not exists!"); @@ -499,12 +568,12 @@ void P2pHalCbFindStopped() return; } -void P2pHalCbServiceDiscoveryResponse(const HidlP2pServDiscRespInfo *info) +void P2pHalCbServiceDiscoveryResponse(const P2pServDiscRespInfo *info) { if (info == NULL) { return; } - LOGD("P2p service discovery response event srcAddress: %{private}s", info->srcAddress); + LOGI("P2p service discovery response event srcAddress: %{private}s", info->srcAddress); WifiHalEventCallbackMsg *pCbkMsg = (WifiHalEventCallbackMsg *)calloc(1, sizeof(WifiHalEventCallbackMsg)); if (pCbkMsg == NULL) { LOGE("create callback message failed!"); @@ -515,6 +584,7 @@ void P2pHalCbServiceDiscoveryResponse(const HidlP2pServDiscRespInfo *info) unsigned len = strlen(info->tlvs) + 1; if (len == 0) { free(pCbkMsg); + pCbkMsg = NULL; return; } pCbkMsg->msg.serverInfo.tlvs = (char *)calloc(len, sizeof(char)); @@ -522,6 +592,7 @@ void P2pHalCbServiceDiscoveryResponse(const HidlP2pServDiscRespInfo *info) strncpy_s(pCbkMsg->msg.serverInfo.tlvs, len, info->tlvs, len - 1) != EOK) { free(pCbkMsg->msg.serverInfo.tlvs); free(pCbkMsg); + pCbkMsg = NULL; return; } } @@ -535,7 +606,7 @@ void P2pHalCbStaConnectState(const char *p2pDeviceAddress, int state) LOGI("P2p sta authorized/deauthorized event devAddress is NULL"); return; } - LOGD("P2p sta authorized/deauthorized event devAddress: %{private}s", p2pDeviceAddress); + LOGI("P2p sta authorized/deauthorized event devAddress: %{private}s", p2pDeviceAddress); WifiHalEventCallbackMsg *pCbkMsg = (WifiHalEventCallbackMsg *)calloc(1, sizeof(WifiHalEventCallbackMsg)); if (pCbkMsg == NULL) { LOGE("create callback message failed!"); @@ -544,6 +615,7 @@ void P2pHalCbStaConnectState(const char *p2pDeviceAddress, int state) if (strncpy_s(pCbkMsg->msg.deviceInfo.p2pDeviceAddress, sizeof(pCbkMsg->msg.deviceInfo.p2pDeviceAddress), p2pDeviceAddress, sizeof(pCbkMsg->msg.deviceInfo.p2pDeviceAddress) - 1) != EOK) { free(pCbkMsg); + pCbkMsg = NULL; return; } EmitEventCallbackMsg(pCbkMsg, ((state == 0) ? AP_STA_DISCONNECTED_EVENT : AP_STA_CONNECTED_EVENT)); @@ -552,7 +624,7 @@ void P2pHalCbStaConnectState(const char *p2pDeviceAddress, int state) void P2pHalCbConnectSupplicantFailed() { - LOGD("P2p supplicant connect Failed event"); + LOGW("P2p supplicant connect Failed event"); RpcServer *server = GetRpcServer(); if (server == NULL) { LOGE("Rpc server not exists!"); @@ -562,9 +634,9 @@ void P2pHalCbConnectSupplicantFailed() return; } -void P2pHalCbServDiscReq(const HidlP2pServDiscReqInfo *info) +void P2pHalCbServDiscReq(const P2pServDiscReqInfo *info) { - LOGD("P2p service discovery request event"); + LOGI("P2p service discovery request event"); if (info == NULL) { return; } @@ -578,6 +650,7 @@ void P2pHalCbServDiscReq(const HidlP2pServDiscReqInfo *info) unsigned len = strlen(info->tlvs) + 1; if (len == 0) { free(pCbkMsg); + pCbkMsg = NULL; return; } pCbkMsg->msg.serDiscReqInfo.tlvs = (char *)calloc(len, sizeof(char)); @@ -585,9 +658,32 @@ void P2pHalCbServDiscReq(const HidlP2pServDiscReqInfo *info) strncpy_s(pCbkMsg->msg.serDiscReqInfo.tlvs, len, info->tlvs, len - 1) != EOK) { free(pCbkMsg->msg.serDiscReqInfo.tlvs); free(pCbkMsg); + pCbkMsg = NULL; return; } } EmitEventCallbackMsg(pCbkMsg, P2P_SERV_DISC_REQ_EVENT); return; } + +void P2pHalCbP2pIfaceCreated(const char *ifName, int isGo) +{ + if (ifName == NULL) { + LOGE("P2p interface created event ifName is NULL"); + return; + } + LOGI("P2p interface created event ifName: %{public}s, isGo: %{public}d", ifName, isGo); + WifiHalEventCallbackMsg *pCbkMsg = (WifiHalEventCallbackMsg *)calloc(1, sizeof(WifiHalEventCallbackMsg)); + if (pCbkMsg == NULL) { + LOGE("create callback message failed!"); + return; + } + pCbkMsg->msg.ifMsg.type = isGo; + if (strncpy_s(pCbkMsg->msg.ifMsg.ifname, sizeof(pCbkMsg->msg.ifMsg.ifname), ifName, + sizeof(pCbkMsg->msg.ifMsg.ifname) - 1) != EOK) { + free(pCbkMsg); + pCbkMsg = NULL; + return; + } + EmitEventCallbackMsg(pCbkMsg, P2P_IFACE_CREATED_EVENT); +} diff --git a/services/wifi_standard/wifi_hal/wifi_hal_callback.h b/wifi/services/wifi_standard/wifi_hal/wifi_hal_callback.h similarity index 76% rename from services/wifi_standard/wifi_hal/wifi_hal_callback.h rename to wifi/services/wifi_standard/wifi_hal/wifi_hal_callback.h index 4f2d85df1688d1be183cef26253dcb161e6db828..bb7a99c7d1ae3ba3ef188bfd77525f9e0c5cf954 100644 --- a/services/wifi_standard/wifi_hal/wifi_hal_callback.h +++ b/wifi/services/wifi_standard/wifi_hal/wifi_hal_callback.h @@ -27,7 +27,6 @@ extern "C" { * @param status */ void WifiHalCbNotifyScanEnd(int status); - /** * @Description Wi-Fi Hal callback notification of the connection change. * @@ -37,17 +36,39 @@ void WifiHalCbNotifyScanEnd(int status); */ void WifiHalCbNotifyConnectChanged(int status, int networkId, const char *pos); /** - * @Description The Wi-Fi Hal module notifies the WPA module of the status change. + * @Description Wi-Fi Hal module notifies the WPA module of the status change. * * @param status */ void WifiHalCbNotifyWpaStateChange(int status); +/** + * @Description Wi-Fi Hal module notifies the bssid change. + * + * @param reasonPos: reason in the return string + * @param bssidPos: bssid in the return string + */ +void WifiHalCbNotifyBssidChanged(const char *reasonPos, const char *bssidPos); /** * @Description Wi-Fi Hal callback notification error key. * * @param status */ void WifiHalCbNotifyWrongKey(int status); + +/** + * @Description Wi-Fi Hal callback notification connection full + * + * @param status + */ +void WifiHalCbNotifyConnectionFull(int status); + +/** + * @Description Wi-Fi Hal callback notification connection reject + * + * @param status + */ +void WifiHalCbNotifyConnectionReject(int status); + /** * @Description Wi-Fi Hal callback notification WPS overlaps. * @@ -64,29 +85,31 @@ void WifiHalCbNotifyWpsTimeOut(int event); * @Description Wi-Fi Hal calls back the STA to join the AP. * * @param content + * @param id - ap id */ -void WifiHalCbStaJoin(const char *content); +void WifiHalCbStaJoin(const char *content, int id); /** * @Description Wi-Fi Hal callback AP status. * * @param content */ -void WifiHalCbApState(const char *content); +void WifiHalCbApState(const char *content, int id); /** * @Description wpa_supplicant client connection result event * - * @param status - event value + * @param state - event value + * @param id - ap id */ -void WifiP2pHalCbNotifyConnectSupplicant(int status); +void WifiP2pHalCbNotifyConnectSupplicant(int state); /** * @Description Indicates that a P2P device has been found * * @param device */ -void P2pHalCbDeviceFound(const HidlP2pDeviceInfo *device); +void P2pHalCbDeviceFound(const P2pDeviceInfo *device); /** * @Description Indicates that a P2P device is lost @@ -121,7 +144,7 @@ void P2pHalCbGoNegotiationFailure(int status); * * @param info */ -void P2pHalCbInvitationReceived(const HidlP2pInvitationInfo *info); +void P2pHalCbInvitationReceived(const P2pInvitationInfo *info); /** * @Description Indicates the result of a P2P invitation request @@ -149,7 +172,7 @@ void P2pHalCbGroupFormationFailure(const char *reason); * * @param info */ -void P2pHalCbGroupStarted(const HidlP2pGroupInfo *info); +void P2pHalCbGroupStarted(const P2pGroupInfo *info); /** * @Description Deletes a P2P group @@ -208,7 +231,7 @@ void P2pHalCbFindStopped(); * @param tlvs * @param tlvsLength */ -void P2pHalCbServiceDiscoveryResponse(const HidlP2pServDiscRespInfo *info); +void P2pHalCbServiceDiscoveryResponse(const P2pServDiscRespInfo *info); /** * @Description Indicates when a STA device is connected/disconnected to this device @@ -216,7 +239,7 @@ void P2pHalCbServiceDiscoveryResponse(const HidlP2pServDiscRespInfo *info); * @param p2pDeviceAddress * @param type - 0 disconnect, 1 connected */ -void P2pHalCbStaConnectState(const char *p2pDeviceAddress, int type); +void P2pHalCbStaConnectState(const char *p2pDeviceAddress, int state); /** * @Description Reporting Link Failure Events @@ -230,8 +253,16 @@ void P2pHalCbConnectSupplicantFailed(); * * @param info */ -void P2pHalCbServDiscReq(const HidlP2pServDiscReqInfo *info); +void P2pHalCbServDiscReq(const P2pServDiscReqInfo *info); + +/** + * @Description Indicates that a P2P interface is created + * + * @param ifName + * @param isGo + */ +void P2pHalCbP2pIfaceCreated(const char *ifName, int isGo); #ifdef __cplusplus } #endif -#endif \ No newline at end of file +#endif diff --git a/services/wifi_standard/wifi_hal/wifi_hal_chip_interface.c b/wifi/services/wifi_standard/wifi_hal/wifi_hal_chip_interface.c similarity index 78% rename from services/wifi_standard/wifi_hal/wifi_hal_chip_interface.c rename to wifi/services/wifi_standard/wifi_hal/wifi_hal_chip_interface.c index 6bf56734c92f058a30a62f31865a9184d2188baa..87b8a53267acd566fa9100e193c7e376d51c8b0d 100644 --- a/services/wifi_standard/wifi_hal/wifi_hal_chip_interface.c +++ b/wifi/services/wifi_standard/wifi_hal/wifi_hal_chip_interface.c @@ -1,5 +1,5 @@ /* - * Copyright (C) 2021 Huawei Device Co., Ltd. + * Copyright (C) 2021-2022 Huawei Device Co., Ltd. * 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 @@ -55,7 +55,8 @@ WifiErrorNo CreateIface(int32_t type, WifiIface *iface) return WIFI_HAL_FAILED; } const int bufferSize = 8; - char name[bufferSize] = {0}; + char name[bufferSize]; + (void)memset_s(name, bufferSize, 0, bufferSize); if (strcpy_s(iface->name, sizeof(iface->name), name) != EOK) { return WIFI_HAL_FAILED; } @@ -70,16 +71,7 @@ WifiErrorNo GetIface(const char *ifname, WifiIface *iface) return WIFI_HAL_FAILED; } LOGD("GetIface() ifname: %{public}s", ifname); - - WifiIface tmpIface; - tmpIface.index = 0; /* fixed compile error, -Werror,-Wunused-parameter */ - tmpIface.type = 0; - tmpIface.name[0] = '\0'; - if (strcpy_s(tmpIface.macAddr, sizeof(tmpIface.macAddr), "00:00:00:00:00:00") != EOK) { - return WIFI_HAL_FAILED; - } - - iface = &tmpIface; + /* Currently not supported */ return WIFI_HAL_SUCCESS; } @@ -158,8 +150,52 @@ WifiErrorNo RequestFirmwareDebugDump(unsigned char *bytes, int32_t *size) return ConvertErrorCode(err); } -WifiErrorNo SetPowerMode(uint8_t mode) +WifiErrorNo GetIsChipSupportDbdc(int *support) +{ + LOGD("GetIsChipSupportDbdc"); + if (support == NULL) { + return WIFI_HAL_FAILED; + } + *support = WIFI_HAL_TRUE; + return WIFI_HAL_SUCCESS; +} + +WifiErrorNo GetIsChipSupportCsa(int *support) { - LOGD("SetPowerMode() %{public}u", mode); + LOGD("GetIsChipSupportCsa"); + if (support == NULL) { + return WIFI_HAL_FAILED; + } + *support = WIFI_HAL_FALSE; return WIFI_HAL_SUCCESS; -} \ No newline at end of file +} + +WifiErrorNo GetIsChipSupportRadarDetect(int *support) +{ + LOGD("GetIsChipSupportRadarDetect"); + if (support == NULL) { + return WIFI_HAL_FAILED; + } + *support = WIFI_HAL_TRUE; + return WIFI_HAL_SUCCESS; +} + +WifiErrorNo GetIsChipSupportDfsChannel(int *support) +{ + LOGD("GetIsChipSupportDfsChannel"); + if (support == NULL) { + return WIFI_HAL_FAILED; + } + *support = WIFI_HAL_TRUE; + return WIFI_HAL_SUCCESS; +} + +WifiErrorNo GetIsChipSupportIndoorChannel(int *support) +{ + LOGD("GetIsChipSupportIndoorChannel"); + if (support == NULL) { + return WIFI_HAL_FAILED; + } + *support = WIFI_HAL_TRUE; + return WIFI_HAL_SUCCESS; +} diff --git a/services/wifi_standard/wifi_hal/wifi_hal_chip_interface.h b/wifi/services/wifi_standard/wifi_hal/wifi_hal_chip_interface.h similarity index 79% rename from services/wifi_standard/wifi_hal/wifi_hal_chip_interface.h rename to wifi/services/wifi_standard/wifi_hal/wifi_hal_chip_interface.h index 3bf4f8ceb4226ab24f7f6048ef7920e8d8185368..ff0fb5f57b0db225bc569c0611d59a596d1b6f01 100644 --- a/services/wifi_standard/wifi_hal/wifi_hal_chip_interface.h +++ b/wifi/services/wifi_standard/wifi_hal/wifi_hal_chip_interface.h @@ -1,5 +1,5 @@ /* - * Copyright (C) 2021 Huawei Device Co., Ltd. + * Copyright (C) 2021-2022 Huawei Device Co., Ltd. * 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 @@ -133,13 +133,44 @@ WifiErrorNo GetComboModes(int32_t *id); WifiErrorNo RequestFirmwareDebugDump(unsigned char *bytes, int32_t *size); /** - * @Description Setting the Low Latency Mode. + * @Description Get is chip support DBDC. * - * @param mode - Low-latency mode. + * @param support - Is support or not supported. * @return WifiErrorNo */ -WifiErrorNo SetPowerMode(uint8_t mode); +WifiErrorNo GetIsChipSupportDbdc(int *support); +/** + * @Description Get is chip support CSA. + * + * @param support - Is support or not supported. + * @return WifiErrorNo + */ +WifiErrorNo GetIsChipSupportCsa(int *support); + +/** + * @Description Get is chip support radar detection. + * + * @param support - Is support or not supported. + * @return WifiErrorNo + */ +WifiErrorNo GetIsChipSupportRadarDetect(int *support); + +/** + * @Description Get is chip support Dfs channel + * + * @param support - Is support or not supported. + * @return WifiErrorNo + */ +WifiErrorNo GetIsChipSupportDfsChannel(int *support); + +/** + * @Description Get is chip support indoor channel. + * + * @param support - Is support or not supported. + * @return WifiErrorNo + */ +WifiErrorNo GetIsChipSupportIndoorChannel(int *support); #ifdef __cplusplus } #endif diff --git a/services/wifi_standard/wifi_hal/wifi_hal_crpc_ap.c b/wifi/services/wifi_standard/wifi_hal/wifi_hal_crpc_ap.c similarity index 56% rename from services/wifi_standard/wifi_hal/wifi_hal_crpc_ap.c rename to wifi/services/wifi_standard/wifi_hal/wifi_hal_crpc_ap.c index 154de4158b7924a94dabbecee673dd65fb9b512c..4896602f204cb92b47a3ae3ed922dd69f6eb4255 100644 --- a/services/wifi_standard/wifi_hal/wifi_hal_crpc_ap.c +++ b/wifi/services/wifi_standard/wifi_hal/wifi_hal_crpc_ap.c @@ -1,5 +1,5 @@ /* - * Copyright (C) 2021 Huawei Device Co., Ltd. + * Copyright (C) 2021-2022 Huawei Device Co., Ltd. * 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 @@ -14,71 +14,86 @@ */ #include "wifi_hal_crpc_ap.h" +#include +#include "serial.h" +#include "wifi_hdi_ap_impl.h" #include "wifi_hal_ap_interface.h" #include "wifi_hal_define.h" int RpcStartSoftAp(RpcServer *server, Context *context) { if (server == NULL || context == NULL) { - return -1; + return HAL_FAILURE; } - WifiErrorNo err = StartSoftAp(); + int id = 0; + if (ReadInt(context, &id) < 0 || id < 0) { + return HAL_FAILURE; + } + + WifiErrorNo err = StartSoftAp(id); WriteBegin(context, 0); WriteInt(context, err); WriteEnd(context); - return 0; + return HAL_SUCCESS; } int RpcStopSoftAp(RpcServer *server, Context *context) { if (server == NULL || context == NULL) { - return -1; + return HAL_FAILURE; } - WifiErrorNo err = StopSoftAp(); + int id = 0; + if (ReadInt(context, &id) < 0 || id < 0) { + return HAL_FAILURE; + } + + WifiErrorNo err = StopSoftAp(id); WriteBegin(context, 0); WriteInt(context, err); WriteEnd(context); - return 0; + return HAL_SUCCESS; } int RpcSetHostapdConfig(RpcServer *server, Context *context) { if (server == NULL || context == NULL) { - return -1; + return HAL_FAILURE; } + int id = 0; HostapdConfig config; if (memset_s(&config, sizeof(config), 0, sizeof(config)) != EOK) { - return -1; + return HAL_FAILURE; } if (ReadStr(context, config.ssid, sizeof(config.ssid)) != 0 || ReadInt(context, &config.ssidLen) < 0 || ReadStr(context, config.preSharedKey, sizeof(config.preSharedKey)) != 0 || ReadInt(context, &config.preSharedKeyLen) < 0 || ReadInt(context, &config.securityType) < 0 || ReadInt(context, &config.band) < 0 || ReadInt(context, &config.channel) < 0 || - ReadInt(context, &config.maxConn) < 0) { - return -1; + ReadInt(context, &config.maxConn) < 0 || ReadInt(context, &id) < 0 || id < 0) { + return HAL_FAILURE; } - WifiErrorNo err = SetHostapdConfig(&config); + WifiErrorNo err = SetHostapdConfig(&config, id); WriteBegin(context, 0); WriteInt(context, err); WriteEnd(context); - return 0; + return HAL_SUCCESS; } int RpcGetStaInfos(RpcServer *server, Context *context) { if (server == NULL || context == NULL) { - return -1; + return HAL_FAILURE; } int maxSize = 0; - if (ReadInt(context, &maxSize) < 0 || maxSize <= 0) { - return -1; + int id = 0; + if (ReadInt(context, &maxSize) < 0 || maxSize <= 0 || ReadInt(context, &id) < 0 || id < 0) { + return HAL_FAILURE; } char *infos = (char *)calloc(maxSize, sizeof(char)); if (infos == NULL) { - return -1; + return HAL_FAILURE; } - WifiErrorNo err = GetStaInfos(infos, &maxSize); + WifiErrorNo err = GetStaInfos(infos, &maxSize, id); WriteBegin(context, 0); WriteInt(context, err); if (err == WIFI_HAL_SUCCESS) { @@ -87,122 +102,135 @@ int RpcGetStaInfos(RpcServer *server, Context *context) } WriteEnd(context); free(infos); - return 0; + infos = NULL; + return HAL_SUCCESS; } int RpcSetCountryCode(RpcServer *server, Context *context) { if (server == NULL || context == NULL) { - return -1; + return HAL_FAILURE; } char countryCode[WIFI_COUNTRY_CODE_MAXLEN + 1] = {0}; - if (ReadStr(context, countryCode, sizeof(countryCode)) != 0) { - return -1; + int id = 0; + if (ReadStr(context, countryCode, sizeof(countryCode)) != 0 || ReadInt(context, &id) < 0 || id < 0) { + return HAL_FAILURE; } - WifiErrorNo err = SetCountryCode(countryCode); + WifiErrorNo err = SetCountryCode(countryCode, id); WriteBegin(context, 0); WriteInt(context, err); WriteEnd(context); - return 0; + return HAL_SUCCESS; } int RpcSetMacFilter(RpcServer *server, Context *context) { if (server == NULL || context == NULL) { - return -1; + return HAL_FAILURE; } int lenMac = 0; + int id = 0; if (ReadInt(context, &lenMac) < 0 || lenMac <= 0) { - return -1; + return HAL_FAILURE; } int len = lenMac + 1; unsigned char *mac = (unsigned char *)calloc(len, sizeof(unsigned char)); if (mac == NULL) { - return -1; + return HAL_FAILURE; } - if (ReadUStr(context, mac, len) != 0) { + if (ReadUStr(context, mac, len) != 0 || ReadInt(context, &id) < 0 || id < 0) { free(mac); - return -1; + mac = NULL; + return HAL_FAILURE; } - WifiErrorNo err = SetMacFilter(mac, lenMac); + WifiErrorNo err = SetMacFilter(mac, lenMac, id); WriteBegin(context, 0); WriteInt(context, err); WriteEnd(context); free(mac); - return 0; + mac = NULL; + return HAL_SUCCESS; } int RpcDelMacFilter(RpcServer *server, Context *context) { if (server == NULL || context == NULL) { - return -1; + return HAL_FAILURE; } int lenMac = 0; + int id = 0; if (ReadInt(context, &lenMac) < 0 || lenMac <= 0) { - return -1; + return HAL_FAILURE; } int len = lenMac + 1; unsigned char *mac = (unsigned char *)calloc(len, sizeof(unsigned char)); if (mac == NULL) { - return -1; + return HAL_FAILURE; } - if (ReadUStr(context, mac, len) != 0) { + if (ReadUStr(context, mac, len) != 0 || ReadInt(context, &id) < 0 || id < 0) { free(mac); - return -1; + mac = NULL; + return HAL_FAILURE; } - WifiErrorNo err = DelMacFilter(mac, lenMac); + WifiErrorNo err = DelMacFilter(mac, lenMac, id); WriteBegin(context, 0); WriteInt(context, err); WriteEnd(context); free(mac); - return 0; + mac = NULL; + return HAL_SUCCESS; } int RpcDisassociateSta(RpcServer *server, Context *context) { if (server == NULL || context == NULL) { - return -1; + return HAL_FAILURE; } int lenMac = 0; + int id = 0; if (ReadInt(context, &lenMac) < 0 || lenMac <= 0) { - return -1; + return HAL_FAILURE; } int len = lenMac + 1; unsigned char *mac = (unsigned char *)calloc(len, sizeof(unsigned char)); if (mac == NULL) { - return -1; + return HAL_FAILURE; } - if (ReadUStr(context, mac, len) != 0) { + if (ReadUStr(context, mac, len) != 0 || ReadInt(context, &id) < 0 || id < 0) { free(mac); - return -1; + mac = NULL; + return HAL_FAILURE; } - WifiErrorNo err = DisassociateSta(mac, lenMac); + WifiErrorNo err = DisassociateSta(mac, lenMac, id); WriteBegin(context, 0); WriteInt(context, err); WriteEnd(context); free(mac); - return 0; + mac = NULL; + return HAL_SUCCESS; } int RpcGetValidFrequenciesForBand(RpcServer *server, Context *context) { if (server == NULL || context == NULL) { - return -1; + return HAL_FAILURE; } int band = 0; int size = 0; - if (ReadInt(context, &band) < 0 || ReadInt(context, &size) < 0) { - return -1; + int id = 0; + if (ReadInt(context, &band) < 0 || ReadInt(context, &size) < 0 || + ReadInt(context, &id) < 0 || id < 0) { + return HAL_FAILURE; } if (size <= 0) { - return -1; + return HAL_FAILURE; } int *frequencies = (int *)calloc(size, sizeof(int)); if (frequencies == NULL) { - return -1; + return HAL_FAILURE; } - WifiErrorNo err = GetValidFrequenciesForBand(band, frequencies, &size); + WifiErrorNo err = GetValidFrequenciesForBand(band, frequencies, &size, id); WriteBegin(context, 0); WriteInt(context, err); if (err == WIFI_HAL_SUCCESS) { @@ -213,5 +241,46 @@ int RpcGetValidFrequenciesForBand(RpcServer *server, Context *context) } WriteEnd(context); free(frequencies); - return 0; + frequencies = NULL; + return HAL_SUCCESS; +} + +int RpcSetPowerModel(RpcServer *server, Context *context) +{ + if (server == NULL || context == NULL) { + return HAL_FAILURE; + } + int mode = -1; + if (ReadInt(context, &mode) < 0) { + return HAL_FAILURE; + } + int id = 0; + if (ReadInt(context, &id) < 0) { + return HAL_FAILURE; + } + WifiErrorNo err = WifiSetPowerModel(mode, id); + WriteBegin(context, 0); + WriteInt(context, err); + WriteEnd(context); + return HAL_SUCCESS; +} + +int RpcGetPowerModel(RpcServer *server, Context *context) +{ + if (server == NULL || context == NULL) { + return HAL_FAILURE; + } + int mode = -1; + int id = 0; + if (ReadInt(context, &id) < 0) { + return HAL_FAILURE; + } + WifiErrorNo err = WifiGetPowerModel(&mode, id); + WriteBegin(context, 0); + WriteInt(context, err); + if (err == WIFI_HAL_SUCCESS) { + WriteInt(context, mode); + } + WriteEnd(context); + return HAL_SUCCESS; } diff --git a/services/wifi_standard/wifi_hal/wifi_hal_crpc_ap.h b/wifi/services/wifi_standard/wifi_hal/wifi_hal_crpc_ap.h similarity index 84% rename from services/wifi_standard/wifi_hal/wifi_hal_crpc_ap.h rename to wifi/services/wifi_standard/wifi_hal/wifi_hal_crpc_ap.h index b8027a98d6cb0b7b7bb5d5f5e6cfaeb2c914f71e..c3f8ac406c95e0e467bfa6b485f7fe4b2d44a42e 100644 --- a/services/wifi_standard/wifi_hal/wifi_hal_crpc_ap.h +++ b/wifi/services/wifi_standard/wifi_hal/wifi_hal_crpc_ap.h @@ -112,6 +112,25 @@ int RpcDisassociateSta(RpcServer *server, Context *context); */ int RpcGetValidFrequenciesForBand(RpcServer *server, Context *context); +/** + * @Description Parse the context to obtain data. Call the corresponding function + * SetPowerModel and assemble the function to obtain data. + * + * @param server - Pointer to the global structure of the communication server. + * @param context - Pointer to the global communication context structure of the server. + * @return int - 0 Success, -1 Failed. + */ +int RpcSetPowerModel(RpcServer *server, Context *context); + +/** + * @Description Parse the context to obtain data. Call the corresponding function + * GetPowerModel and assemble the function to obtain data. + * + * @param server - Pointer to the global structure of the communication server. + * @param context - Pointer to the global communication context structure of the server. + * @return int - 0 Success, -1 Failed. + */ +int RpcGetPowerModel(RpcServer *server, Context *context); #ifdef __cplusplus } #endif diff --git a/services/wifi_standard/wifi_hal/wifi_hal_crpc_base.c b/wifi/services/wifi_standard/wifi_hal/wifi_hal_crpc_base.c similarity index 88% rename from services/wifi_standard/wifi_hal/wifi_hal_crpc_base.c rename to wifi/services/wifi_standard/wifi_hal/wifi_hal_crpc_base.c index c7c5062baa93529eef18f278ba2b7fdfb43b2f54..d6e4025ab9772cda180cde82fba14a3cf87bb795 100644 --- a/services/wifi_standard/wifi_hal/wifi_hal_crpc_base.c +++ b/wifi/services/wifi_standard/wifi_hal/wifi_hal_crpc_base.c @@ -1,5 +1,5 @@ /* - * Copyright (C) 2021 Huawei Device Co., Ltd. + * Copyright (C) 2021-2022 Huawei Device Co., Ltd. * 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 @@ -14,6 +14,8 @@ */ #include "wifi_hal_crpc_base.h" +#include +#include "serial.h" #include "wifi_hal_base_interface.h" #include "wifi_hal_define.h" @@ -30,6 +32,7 @@ int *ReadIntArray(Context *context, int size) for (int i = 0; i < size; ++i) { if (ReadInt(context, pArray + i) < 0) { free(pArray); + pArray = NULL; return NULL; } } @@ -62,8 +65,10 @@ char **ReadCharArray(Context *context, int size) if (i < size) { for (int j = 0; j < size; ++j) { free(pArray[j]); + pArray[j] = NULL; } free(pArray); + pArray = NULL; return NULL; } return pArray; @@ -72,15 +77,15 @@ char **ReadCharArray(Context *context, int size) int RpcGetName(RpcServer *server, Context *context) { if (server == NULL || context == NULL) { - return -1; + return HAL_FAILURE; } int size = 0; if (ReadInt(context, &size) < 0 || size <= 0) { - return -1; + return HAL_FAILURE; } char *ifname = (char *)calloc(size, sizeof(char)); if (ifname == NULL) { - return -1; + return HAL_FAILURE; } WifiErrorNo err = GetName(ifname, size); WriteBegin(context, 0); @@ -90,13 +95,14 @@ int RpcGetName(RpcServer *server, Context *context) } WriteEnd(context); free(ifname); - return 0; + ifname = NULL; + return HAL_SUCCESS; } int RpcGetType(RpcServer *server, Context *context) { if (server == NULL || context == NULL) { - return -1; + return HAL_FAILURE; } int type = 0; WifiErrorNo err = GetType(&type); @@ -106,5 +112,5 @@ int RpcGetType(RpcServer *server, Context *context) WriteInt(context, type); } WriteEnd(context); - return 0; + return HAL_SUCCESS; } \ No newline at end of file diff --git a/services/wifi_standard/wifi_hal/wifi_hal_crpc_base.h b/wifi/services/wifi_standard/wifi_hal/wifi_hal_crpc_base.h similarity index 100% rename from services/wifi_standard/wifi_hal/wifi_hal_crpc_base.h rename to wifi/services/wifi_standard/wifi_hal/wifi_hal_crpc_base.h diff --git a/services/wifi_standard/wifi_hal/wifi_hal_crpc_chip.c b/wifi/services/wifi_standard/wifi_hal/wifi_hal_crpc_chip.c similarity index 68% rename from services/wifi_standard/wifi_hal/wifi_hal_crpc_chip.c rename to wifi/services/wifi_standard/wifi_hal/wifi_hal_crpc_chip.c index a5d6ea4c5d2c19cfe311ff74d3429b3d0d6f6328..358b4e18d0ca7abb3bf39c5bc356c0258a66cb7a 100644 --- a/services/wifi_standard/wifi_hal/wifi_hal_crpc_chip.c +++ b/wifi/services/wifi_standard/wifi_hal/wifi_hal_crpc_chip.c @@ -1,5 +1,5 @@ /* - * Copyright (C) 2021 Huawei Device Co., Ltd. + * Copyright (C) 2021-2022 Huawei Device Co., Ltd. * 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 @@ -14,21 +14,23 @@ */ #include "wifi_hal_crpc_chip.h" +#include +#include "serial.h" #include "wifi_hal_chip_interface.h" #include "wifi_hal_define.h" int RpcGetWifiChip(RpcServer *server, Context *context) { if (server == NULL || context == NULL) { - return -1; + return HAL_FAILURE; } int chipId = 0; if (ReadInt(context, &chipId) < 0) { - return -1; + return HAL_FAILURE; } WifiChip wifiChip; if (memset_s(&wifiChip, sizeof(wifiChip), 0, sizeof(wifiChip)) != EOK) { - return -1; + return HAL_FAILURE; } WifiErrorNo err = GetWifiChip(chipId, &wifiChip); WriteBegin(context, 0); @@ -37,24 +39,24 @@ int RpcGetWifiChip(RpcServer *server, Context *context) WriteInt(context, wifiChip.chip); } WriteEnd(context); - return 0; + return HAL_SUCCESS; } int RpcGetWifiChipIds(RpcServer *server, Context *context) { if (server == NULL || context == NULL) { - return -1; + return HAL_FAILURE; } int maxSize = 0; if (ReadInt(context, &maxSize) < 0) { - return -1; + return HAL_FAILURE; } if (maxSize <= 0) { - return -1; + return HAL_FAILURE; } - uint8_t *chipIds = (uint8_t *)calloc(maxSize, sizeof(int)); + uint8_t *chipIds = (uint8_t *)calloc(maxSize * sizeof(int), sizeof(uint8_t)); if (chipIds == NULL) { - return -1; + return HAL_FAILURE; } WifiErrorNo err = GetWifiChipIds(chipIds, &maxSize); WriteBegin(context, 0); @@ -67,13 +69,14 @@ int RpcGetWifiChipIds(RpcServer *server, Context *context) } WriteEnd(context); free(chipIds); - return 0; + chipIds = NULL; + return HAL_SUCCESS; } int RpcGetChipId(RpcServer *server, Context *context) { if (server == NULL || context == NULL) { - return -1; + return HAL_FAILURE; } int chipId = 0; WifiErrorNo err = GetChipId(&chipId); @@ -83,21 +86,21 @@ int RpcGetChipId(RpcServer *server, Context *context) WriteInt(context, chipId); } WriteEnd(context); - return 0; + return HAL_SUCCESS; } int RpcCreateIface(RpcServer *server, Context *context) { if (server == NULL || context == NULL) { - return -1; + return HAL_FAILURE; } int type = 0; if (ReadInt(context, &type) < 0) { - return -1; + return HAL_FAILURE; } WifiIface wifiIface; if (memset_s(&wifiIface, sizeof(wifiIface), 0, sizeof(wifiIface)) != EOK) { - return -1; + return HAL_FAILURE; } WifiErrorNo err = CreateIface(type, &wifiIface); WriteBegin(context, 0); @@ -109,28 +112,28 @@ int RpcCreateIface(RpcServer *server, Context *context) WriteStr(context, wifiIface.macAddr); } WriteEnd(context); - return 0; + return HAL_SUCCESS; } int RpcGetIface(RpcServer *server, Context *context) { if (server == NULL || context == NULL) { - return -1; + return HAL_FAILURE; } WifiIface wifiIface; if (memset_s(&wifiIface, sizeof(wifiIface), 0, sizeof(wifiIface)) != EOK) { - return -1; + return HAL_FAILURE; } char ifname[WIFI_IFACE_NAME_MAXLEN] = {0}; char *pstr = NULL; int ret = ReadStr(context, ifname, WIFI_IFACE_NAME_MAXLEN); if (ret < 0) { - return -1; + return HAL_FAILURE; } else if (ret > 0) { int len = ret + 1; pstr = (char *)calloc(len, sizeof(char)); if (pstr == NULL) { - return -1; + return HAL_FAILURE; } ReadStr(context, pstr, len); } @@ -146,23 +149,24 @@ int RpcGetIface(RpcServer *server, Context *context) WriteEnd(context); if (pstr != NULL) { free(pstr); + pstr = NULL; } - return 0; + return HAL_SUCCESS; } int RpcGetIfaceNames(RpcServer *server, Context *context) { if (server == NULL || context == NULL) { - return -1; + return HAL_FAILURE; } int type = 0; int size = 0; if (ReadInt(context, &type) < 0 || ReadInt(context, &size) < 0 || size <= 0) { - return -1; + return HAL_FAILURE; } char *ifname = (char *)calloc(size, sizeof(char)); if (ifname == NULL) { - return -1; + return HAL_FAILURE; } WifiErrorNo err = GetIfaceNames(type, ifname, size); WriteBegin(context, 0); @@ -172,24 +176,25 @@ int RpcGetIfaceNames(RpcServer *server, Context *context) } WriteEnd(context); free(ifname); - return 0; + ifname = NULL; + return HAL_SUCCESS; } int RpcRemoveIface(RpcServer *server, Context *context) { if (server == NULL || context == NULL) { - return -1; + return HAL_FAILURE; } char ifname[WIFI_IFACE_NAME_MAXLEN] = {0}; char *pstr = NULL; int ret = ReadStr(context, ifname, WIFI_IFACE_NAME_MAXLEN); if (ret < 0) { - return -1; + return HAL_FAILURE; } else if (ret > 0) { int len = ret + 1; pstr = (char *)calloc(len, sizeof(char)); if (pstr == NULL) { - return -1; + return HAL_FAILURE; } ReadStr(context, pstr, len); } @@ -199,14 +204,15 @@ int RpcRemoveIface(RpcServer *server, Context *context) WriteEnd(context); if (pstr != NULL) { free(pstr); + pstr = NULL; } - return 0; + return HAL_SUCCESS; } int RpcGetCapabilities(RpcServer *server, Context *context) { if (server == NULL || context == NULL) { - return -1; + return HAL_FAILURE; } uint32_t capabilities = 0; WifiErrorNo err = GetCapabilities(&capabilities); @@ -216,21 +222,21 @@ int RpcGetCapabilities(RpcServer *server, Context *context) WriteInt(context, capabilities); } WriteEnd(context); - return 0; + return HAL_SUCCESS; } int RpcGetSupportedComboModes(RpcServer *server, Context *context) { if (server == NULL || context == NULL) { - return -1; + return HAL_FAILURE; } int maxSize = 0; if (ReadInt(context, &maxSize) < 0 || maxSize <= 0) { - return -1; + return HAL_FAILURE; } int *modes = (int *)calloc(maxSize, sizeof(int)); if (modes == NULL) { - return -1; + return HAL_FAILURE; } WifiErrorNo err = GetSupportedComboModes(modes, &maxSize); WriteBegin(context, 0); @@ -243,29 +249,30 @@ int RpcGetSupportedComboModes(RpcServer *server, Context *context) } WriteEnd(context); free(modes); - return 0; + modes = NULL; + return HAL_SUCCESS; } int RpcConfigComboModes(RpcServer *server, Context *context) { if (server == NULL || context == NULL) { - return -1; + return HAL_FAILURE; } int mode = 0; if (ReadInt(context, &mode) < 0) { - return -1; + return HAL_FAILURE; } WifiErrorNo err = ConfigComboModes(mode); WriteBegin(context, 0); WriteInt(context, err); WriteEnd(context); - return 0; + return HAL_SUCCESS; } int RpcGetComboModes(RpcServer *server, Context *context) { if (server == NULL || context == NULL) { - return -1; + return HAL_FAILURE; } int mode = 0; WifiErrorNo err = GetComboModes(&mode); @@ -275,22 +282,22 @@ int RpcGetComboModes(RpcServer *server, Context *context) WriteInt(context, mode); } WriteEnd(context); - return 0; + return HAL_SUCCESS; } int RpcRequestFirmwareDebugDump(RpcServer *server, Context *context) { if (server == NULL || context == NULL) { - return -1; + return HAL_FAILURE; } int maxSize = 0; if (ReadInt(context, &maxSize) < 0 || maxSize <= 0) { - return -1; + return HAL_FAILURE; } unsigned char *bytes = (unsigned char *)calloc(maxSize + 1, sizeof(unsigned char)); if (bytes == NULL) { - return -1; + return HAL_FAILURE; } WifiErrorNo err = RequestFirmwareDebugDump(bytes, &maxSize); @@ -302,21 +309,86 @@ int RpcRequestFirmwareDebugDump(RpcServer *server, Context *context) } WriteEnd(context); free(bytes); - return 0; + bytes = NULL; + return HAL_SUCCESS; } -int RpcSetPowerMode(RpcServer *server, Context *context) +int RpcIsChipSupportDbdc(RpcServer *server, Context *context) { if (server == NULL || context == NULL) { - return -1; + return HAL_FAILURE; } - int mode = 0; - if (ReadInt(context, &mode) < 0) { - return -1; + int support = 0; + WifiErrorNo err = GetIsChipSupportDbdc(&support); + WriteBegin(context, 0); + WriteInt(context, err); + if (err == WIFI_HAL_SUCCESS) { + WriteInt(context, support); + } + WriteEnd(context); + return HAL_SUCCESS; +} + +int RpcIsChipSupportCsa(RpcServer *server, Context *context) +{ + if (server == NULL || context == NULL) { + return HAL_FAILURE; } - WifiErrorNo err = SetPowerMode(mode); + int support = 0; + WifiErrorNo err = GetIsChipSupportCsa(&support); WriteBegin(context, 0); WriteInt(context, err); + if (err == WIFI_HAL_SUCCESS) { + WriteInt(context, support); + } + WriteEnd(context); + return HAL_SUCCESS; +} + +int RpcIsChipSupportRadarDetect(RpcServer *server, Context *context) +{ + if (server == NULL || context == NULL) { + return HAL_FAILURE; + } + int support = 0; + WifiErrorNo err = GetIsChipSupportRadarDetect(&support); + WriteBegin(context, 0); + WriteInt(context, err); + if (err == WIFI_HAL_SUCCESS) { + WriteInt(context, support); + } + WriteEnd(context); + return HAL_SUCCESS; +} + +int RpcIsChipSupportDfsChannel(RpcServer *server, Context *context) +{ + if (server == NULL || context == NULL) { + return HAL_FAILURE; + } + int support = 0; + WifiErrorNo err = GetIsChipSupportDfsChannel(&support); + WriteBegin(context, 0); + WriteInt(context, err); + if (err == WIFI_HAL_SUCCESS) { + WriteInt(context, support); + } + WriteEnd(context); + return HAL_SUCCESS; +} + +int RpcIsChipSupportIndoorChannel(RpcServer *server, Context *context) +{ + if (server == NULL || context == NULL) { + return HAL_FAILURE; + } + int support = 0; + WifiErrorNo err = GetIsChipSupportIndoorChannel(&support); + WriteBegin(context, 0); + WriteInt(context, err); + if (err == WIFI_HAL_SUCCESS) { + WriteInt(context, support); + } WriteEnd(context); - return 0; + return HAL_SUCCESS; } \ No newline at end of file diff --git a/services/wifi_standard/wifi_hal/wifi_hal_crpc_chip.h b/wifi/services/wifi_standard/wifi_hal/wifi_hal_crpc_chip.h similarity index 76% rename from services/wifi_standard/wifi_hal/wifi_hal_crpc_chip.h rename to wifi/services/wifi_standard/wifi_hal/wifi_hal_crpc_chip.h index a8d4b2843d4186ddfea82218b79a93aed2e498a4..4d3a417c4218165ddebd901bb77334e5896493b1 100644 --- a/services/wifi_standard/wifi_hal/wifi_hal_crpc_chip.h +++ b/wifi/services/wifi_standard/wifi_hal/wifi_hal_crpc_chip.h @@ -144,14 +144,53 @@ int RpcRequestFirmwareDebugDump(RpcServer *server, Context *context); /** * @Description Parse the context to obtain data. Call the corresponding function - * SetPowerMode and assemble the function to obtain data. + * RpcIsChipSupportDbdc and assemble the function to obtain data. * * @param server - Pointer to the global structure of the communication server. * @param context - Pointer to the global communication context structure of the server. * @return int - 0 Success, -1 Failed. */ -int RpcSetPowerMode(RpcServer *server, Context *context); +int RpcIsChipSupportDbdc(RpcServer *server, Context *context); +/** + * @Description Parse the context to obtain data. Call the corresponding function + * RpcIsChipSupportCsa and assemble the function to obtain data. + * + * @param server - Pointer to the global structure of the communication server. + * @param context - Pointer to the global communication context structure of the server. + * @return int - 0 Success, -1 Failed. + */ +int RpcIsChipSupportCsa(RpcServer *server, Context *context); + +/** + * @Description Parse the context to obtain data. Call the corresponding function + * RpcIsChipSupportRadarDetect and assemble the function to obtain data. + * + * @param server - Pointer to the global structure of the communication server. + * @param context - Pointer to the global communication context structure of the server. + * @return int - 0 Success, -1 Failed. + */ +int RpcIsChipSupportRadarDetect(RpcServer *server, Context *context); + +/** + * @Description Parse the context to obtain data. Call the corresponding function + * RpcIsChipSupportDfsChannel and assemble the function to obtain data. + * + * @param server - Pointer to the global structure of the communication server. + * @param context - Pointer to the global communication context structure of the server. + * @return int - 0 Success, -1 Failed. + */ +int RpcIsChipSupportDfsChannel(RpcServer *server, Context *context); + +/** + * @Description Parse the context to obtain data. Call the corresponding function + * RpcIsChipSupportIndoorChannel and assemble the function to obtain data. + * + * @param server - Pointer to the global structure of the communication server. + * @param context - Pointer to the global communication context structure of the server. + * @return int - 0 Success, -1 Failed. + */ +int RpcIsChipSupportIndoorChannel(RpcServer *server, Context *context); #ifdef __cplusplus } #endif diff --git a/services/wifi_standard/wifi_hal/wifi_hal_crpc_common.c b/wifi/services/wifi_standard/wifi_hal/wifi_hal_crpc_common.c similarity index 79% rename from services/wifi_standard/wifi_hal/wifi_hal_crpc_common.c rename to wifi/services/wifi_standard/wifi_hal/wifi_hal_crpc_common.c index 77d619afa482aad75825ad09976bd3befd220165..c427c8e523721f4e8446c2cfac3b77aebd3d90fc 100644 --- a/services/wifi_standard/wifi_hal/wifi_hal_crpc_common.c +++ b/wifi/services/wifi_standard/wifi_hal/wifi_hal_crpc_common.c @@ -1,5 +1,5 @@ /* - * Copyright (C) 2021 Huawei Device Co., Ltd. + * Copyright (C) 2021-2022 Huawei Device Co., Ltd. * 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 @@ -14,24 +14,26 @@ */ #include "wifi_hal_crpc_common.h" +#include "serial.h" #include "wifi_hal_crpc_base.h" #include "wifi_hal_sta_interface.h" #include "wifi_hal_ap_interface.h" #include "wifi_hal_p2p_interface.h" #include "wifi_hal_define.h" +#include "wifi_hostapd_hal.h" int RpcRegisterEventCallback(RpcServer *server, Context *context) { if (server == NULL || context == NULL) { - return -1; + return HAL_FAILURE; } int num = 0; if (ReadInt(context, &num) < 0) { - return -1; + return HAL_FAILURE; } int *events = ReadIntArray(context, num); if (events == NULL) { - return -1; + return HAL_FAILURE; } for (int i = 0; i < num; ++i) { RegisterCallback(server, events[i], context); @@ -40,21 +42,22 @@ int RpcRegisterEventCallback(RpcServer *server, Context *context) WriteInt(context, WIFI_HAL_SUCCESS); WriteEnd(context); free(events); - return 0; + events = NULL; + return HAL_SUCCESS; } int RpcUnRegisterEventCallback(RpcServer *server, Context *context) { if (server == NULL || context == NULL) { - return -1; + return HAL_FAILURE; } int num = 0; if (ReadInt(context, &num) < 0) { - return -1; + return HAL_FAILURE; } int *events = ReadIntArray(context, num); if (events == NULL) { - return -1; + return HAL_FAILURE; } for (int i = 0; i < num; ++i) { UnRegisterCallback(server, events[i], context); @@ -63,19 +66,22 @@ int RpcUnRegisterEventCallback(RpcServer *server, Context *context) WriteInt(context, WIFI_HAL_SUCCESS); WriteEnd(context); free(events); - return 0; + events = NULL; + return HAL_SUCCESS; } int RpcNotifyClear(RpcServer *server, Context *context) { if (server == NULL || context == NULL) { - return -1; + return HAL_FAILURE; } ForceStop(); - StopSoftAp(); + for (int id = 0; id < AP_MAX_INSTANCE; id++) { + StopSoftAp(id); + } P2pForceStop(); WriteBegin(context, 0); WriteInt(context, 0); WriteEnd(context); - return 0; + return HAL_SUCCESS; } \ No newline at end of file diff --git a/services/wifi_standard/wifi_hal/wifi_hal_crpc_common.h b/wifi/services/wifi_standard/wifi_hal/wifi_hal_crpc_common.h similarity index 100% rename from services/wifi_standard/wifi_hal/wifi_hal_crpc_common.h rename to wifi/services/wifi_standard/wifi_hal/wifi_hal_crpc_common.h diff --git a/services/wifi_standard/wifi_hal/wifi_hal_crpc_p2p.c b/wifi/services/wifi_standard/wifi_hal/wifi_hal_crpc_p2p.c similarity index 79% rename from services/wifi_standard/wifi_hal/wifi_hal_crpc_p2p.c rename to wifi/services/wifi_standard/wifi_hal/wifi_hal_crpc_p2p.c index 3114818936e1c1b4c241bf64f1e95977a3ef99d5..e8b8962f50558572d12f4707720588493b07cc26 100644 --- a/services/wifi_standard/wifi_hal/wifi_hal_crpc_p2p.c +++ b/wifi/services/wifi_standard/wifi_hal/wifi_hal_crpc_p2p.c @@ -1,5 +1,5 @@ /* - * Copyright (C) 2021 Huawei Device Co., Ltd. + * Copyright (C) 2021-2022 Huawei Device Co., Ltd. * 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 @@ -14,142 +14,143 @@ */ #include "wifi_hal_crpc_p2p.h" +#include +#include "serial.h" #include "wifi_hal_p2p_interface.h" #include "wifi_hal_define.h" -#include "securec.h" int RpcP2pStart(RpcServer *server, Context *context) { if (server == NULL || context == NULL) { - return -1; + return HAL_FAILURE; } WifiErrorNo err = P2pStart(); WriteBegin(context, 0); WriteInt(context, err); WriteEnd(context); - return 0; + return HAL_SUCCESS; } int RpcP2pStop(RpcServer *server, Context *context) { if (server == NULL || context == NULL) { - return -1; + return HAL_FAILURE; } WifiErrorNo err = P2pStop(); WriteBegin(context, 0); WriteInt(context, err); WriteEnd(context); - return 0; + return HAL_SUCCESS; } int RpcP2pSetRandomMac(RpcServer *server, Context *context) { if (server == NULL || context == NULL) { - return -1; + return HAL_FAILURE; } int enable = 0; if (ReadInt(context, &enable) < 0) { - return -1; + return HAL_FAILURE; } WifiErrorNo err = P2pSetRandomMac(enable); WriteBegin(context, 0); WriteInt(context, err); WriteEnd(context); - return 0; + return HAL_SUCCESS; } int RpcP2pSetDeviceName(RpcServer *server, Context *context) { if (server == NULL || context == NULL) { - return -1; + return HAL_FAILURE; } char name[WIFI_P2P_WPS_NAME_LENGTH] = {0}; if (ReadStr(context, name, sizeof(name)) != 0) { - return -1; + return HAL_FAILURE; } WifiErrorNo err = P2pSetDeviceName(name); WriteBegin(context, 0); WriteInt(context, err); WriteEnd(context); - return 0; + return HAL_SUCCESS; } int RpcP2pSetSsidPostfixName(RpcServer *server, Context *context) { if (server == NULL || context == NULL) { - return -1; + return HAL_FAILURE; } char name[WIFI_P2P_WPS_NAME_LENGTH] = {0}; if (ReadStr(context, name, sizeof(name)) != 0) { - return -1; + return HAL_FAILURE; } WifiErrorNo err = P2pSetSsidPostfixName(name); WriteBegin(context, 0); WriteInt(context, err); WriteEnd(context); - return 0; + return HAL_SUCCESS; } int RpcP2pSetWpsDeviceType(RpcServer *server, Context *context) { if (server == NULL || context == NULL) { - return -1; + return HAL_FAILURE; } char type[WIFI_P2P_WPS_NAME_LENGTH] = {0}; if (ReadStr(context, type, sizeof(type)) != 0) { - return -1; + return HAL_FAILURE; } WifiErrorNo err = P2pSetWpsDeviceType(type); WriteBegin(context, 0); WriteInt(context, err); WriteEnd(context); - return 0; + return HAL_SUCCESS; } int RpcP2pSetWpsSecondaryDeviceType(RpcServer *server, Context *context) { if (server == NULL || context == NULL) { - return -1; + return HAL_FAILURE; } char type[WIFI_P2P_WPS_NAME_LENGTH] = {0}; if (ReadStr(context, type, sizeof(type)) != 0) { - return -1; + return HAL_FAILURE; } WifiErrorNo err = P2pSetWpsSecondaryDeviceType(type); WriteBegin(context, 0); WriteInt(context, err); WriteEnd(context); - return 0; + return HAL_SUCCESS; } int RpcP2pSetWpsConfigMethods(RpcServer *server, Context *context) { if (server == NULL || context == NULL) { - return -1; + return HAL_FAILURE; } char methods[WIFI_P2P_WPS_METHODS_LENGTH] = {0}; if (ReadStr(context, methods, sizeof(methods)) != 0) { - return -1; + return HAL_FAILURE; } WifiErrorNo err = P2pSetWpsConfigMethods(methods); WriteBegin(context, 0); WriteInt(context, err); WriteEnd(context); - return 0; + return HAL_SUCCESS; } int RpcP2pGetDeviceAddress(RpcServer *server, Context *context) { if (server == NULL || context == NULL) { - return -1; + return HAL_FAILURE; } int size = 0; if (ReadInt(context, &size) < 0 || size <= 0) { - return -1; + return HAL_FAILURE; } char *address = (char *)calloc(size, sizeof(char)); if (address == NULL) { - return -1; + return HAL_FAILURE; } WifiErrorNo err = P2pGetDeviceAddress(address, size); WriteBegin(context, 0); @@ -159,66 +160,67 @@ int RpcP2pGetDeviceAddress(RpcServer *server, Context *context) } WriteEnd(context); free(address); - return 0; + address = NULL; + return HAL_SUCCESS; } int RpcP2pFlush(RpcServer *server, Context *context) { if (server == NULL || context == NULL) { - return -1; + return HAL_FAILURE; } WifiErrorNo err = P2pFlush(); WriteBegin(context, 0); WriteInt(context, err); WriteEnd(context); - return 0; + return HAL_SUCCESS; } int RpcP2pFlushService(RpcServer *server, Context *context) { if (server == NULL || context == NULL) { - return -1; + return HAL_FAILURE; } WifiErrorNo err = P2pFlushService(); WriteBegin(context, 0); WriteInt(context, err); WriteEnd(context); - return 0; + return HAL_SUCCESS; } int RpcP2pSaveConfig(RpcServer *server, Context *context) { if (server == NULL || context == NULL) { - return -1; + return HAL_FAILURE; } WifiErrorNo err = P2pSaveConfig(); WriteBegin(context, 0); WriteInt(context, err); WriteEnd(context); - return 0; + return HAL_SUCCESS; } int RpcP2pSetupWpsPbc(RpcServer *server, Context *context) { if (server == NULL || context == NULL) { - return -1; + return HAL_FAILURE; } char interface[WIFI_P2P_GROUP_IFNAME_LENGTH] = {0}; char bssid[WIFI_BSSID_LENGTH] = {0}; if (ReadStr(context, interface, sizeof(interface)) != 0 || ReadStr(context, bssid, sizeof(bssid)) != 0) { - return -1; + return HAL_FAILURE; } WifiErrorNo err = P2pSetupWpsPbc(interface, bssid); WriteBegin(context, 0); WriteInt(context, err); WriteEnd(context); - return 0; + return HAL_SUCCESS; } int RpcP2pSetupWpsPin(RpcServer *server, Context *context) { if (server == NULL || context == NULL) { - return -1; + return HAL_FAILURE; } char interface[WIFI_P2P_GROUP_IFNAME_LENGTH] = {0}; char address[WIFI_BSSID_LENGTH] = {0}; @@ -226,14 +228,14 @@ int RpcP2pSetupWpsPin(RpcServer *server, Context *context) int resultLen = 0; if (ReadStr(context, interface, sizeof(interface)) != 0 || ReadStr(context, address, sizeof(address)) != 0 || ReadStr(context, pinCode, sizeof(pinCode)) != 0 || ReadInt(context, &resultLen) < 0) { - return -1; + return HAL_FAILURE; } if (resultLen <= 0) { - return -1; + return HAL_FAILURE; } char *pResult = (char *)calloc(resultLen, sizeof(char)); if (pResult == NULL) { - return -1; + return HAL_FAILURE; } WifiErrorNo err = P2pSetupWpsPin(interface, address, pinCode, pResult, resultLen); WriteBegin(context, 0); @@ -243,33 +245,34 @@ int RpcP2pSetupWpsPin(RpcServer *server, Context *context) } WriteEnd(context); free(pResult); - return 0; + pResult = NULL; + return HAL_SUCCESS; } int RpcP2pRemoveNetwork(RpcServer *server, Context *context) { if (server == NULL || context == NULL) { - return -1; + return HAL_FAILURE; } int networkId = 0; if (ReadInt(context, &networkId) < 0) { - return -1; + return HAL_FAILURE; } WifiErrorNo err = P2pRemoveNetwork(networkId); WriteBegin(context, 0); WriteInt(context, err); WriteEnd(context); - return 0; + return HAL_SUCCESS; } int RpcP2pListNetworks(RpcServer *server, Context *context) { if (server == NULL || context == NULL) { - return -1; + return HAL_FAILURE; } - HidlP2pNetworkList infoList; + P2pNetworkList infoList; if (memset_s(&infoList, sizeof(infoList), 0, sizeof(infoList)) != EOK) { - return -1; + return HAL_FAILURE; } WifiErrorNo err = P2pListNetworks(&infoList); WriteBegin(context, 0); @@ -285,152 +288,153 @@ int RpcP2pListNetworks(RpcServer *server, Context *context) } WriteEnd(context); free(infoList.infos); - return 0; + infoList.infos = NULL; + return HAL_SUCCESS; } int RpcP2pSetGroupMaxIdle(RpcServer *server, Context *context) { if (server == NULL || context == NULL) { - return -1; + return HAL_FAILURE; } char interface[WIFI_P2P_GROUP_IFNAME_LENGTH] = {0}; int maxtime = 0; if (ReadStr(context, interface, sizeof(interface)) != 0 || ReadInt(context, &maxtime) < 0) { - return -1; + return HAL_FAILURE; } WifiErrorNo err = P2pSetGroupMaxIdle(interface, maxtime); WriteBegin(context, 0); WriteInt(context, err); WriteEnd(context); - return 0; + return HAL_SUCCESS; } int RpcP2pSetPowerSave(RpcServer *server, Context *context) { if (server == NULL || context == NULL) { - return -1; + return HAL_FAILURE; } char interface[WIFI_P2P_GROUP_IFNAME_LENGTH] = {0}; int enable = 0; if (ReadStr(context, interface, sizeof(interface)) != 0 || ReadInt(context, &enable) < 0) { - return -1; + return HAL_FAILURE; } WifiErrorNo err = P2pSetPowerSave(interface, enable); WriteBegin(context, 0); WriteInt(context, err); WriteEnd(context); - return 0; + return HAL_SUCCESS; } int RpcP2pSetWfdEnable(RpcServer *server, Context *context) { if (server == NULL || context == NULL) { - return -1; + return HAL_FAILURE; } int enable = 0; if (ReadInt(context, &enable) < 0) { - return -1; + return HAL_FAILURE; } WifiErrorNo err = P2pSetWfdEnable(enable); WriteBegin(context, 0); WriteInt(context, err); WriteEnd(context); - return 0; + return HAL_SUCCESS; } int RpcP2pSetWfdDeviceConfig(RpcServer *server, Context *context) { if (server == NULL || context == NULL) { - return -1; + return HAL_FAILURE; } char conf[WIFI_P2P_WFD_DEVICE_CONF_LENGTH] = {0}; if (ReadStr(context, conf, sizeof(conf)) != 0) { - return -1; + return HAL_FAILURE; } WifiErrorNo err = P2pSetWfdDeviceConfig(conf); WriteBegin(context, 0); WriteInt(context, err); WriteEnd(context); - return 0; + return HAL_SUCCESS; } int RpcP2pStartFind(RpcServer *server, Context *context) { if (server == NULL || context == NULL) { - return -1; + return HAL_FAILURE; } int timeout = 0; if (ReadInt(context, &timeout) < 0) { - return -1; + return HAL_FAILURE; } WifiErrorNo err = P2pStartFind(timeout); WriteBegin(context, 0); WriteInt(context, err); WriteEnd(context); - return 0; + return HAL_SUCCESS; } int RpcP2pStopFind(RpcServer *server, Context *context) { if (server == NULL || context == NULL) { - return -1; + return HAL_FAILURE; } WifiErrorNo err = P2pStopFind(); WriteBegin(context, 0); WriteInt(context, err); WriteEnd(context); - return 0; + return HAL_SUCCESS; } int RpcP2pSetExtListen(RpcServer *server, Context *context) { if (server == NULL || context == NULL) { - return -1; + return HAL_FAILURE; } int enable = 0; int period = 0; int interval = 0; if (ReadInt(context, &enable) < 0 || ReadInt(context, &period) < 0 || ReadInt(context, &interval) < 0) { - return -1; + return HAL_FAILURE; } WifiErrorNo err = P2pSetExtListen(enable, period, interval); WriteBegin(context, 0); WriteInt(context, err); WriteEnd(context); - return 0; + return HAL_SUCCESS; } int RpcP2pSetListenChannel(RpcServer *server, Context *context) { if (server == NULL || context == NULL) { - return -1; + return HAL_FAILURE; } int channel = 0; int regClass = 0; if (ReadInt(context, &channel) < 0 || ReadInt(context, ®Class) < 0) { - return -1; + return HAL_FAILURE; } WifiErrorNo err = P2pSetListenChannel(channel, regClass); WriteBegin(context, 0); WriteInt(context, err); WriteEnd(context); - return 0; + return HAL_SUCCESS; } int RpcP2pConnect(RpcServer *server, Context *context) { if (server == NULL || context == NULL) { - return -1; + return HAL_FAILURE; } - HidlP2pConnectInfo info; + P2pConnectInfo info; if (memset_s(&info, sizeof(info), 0, sizeof(info)) != EOK) { - return -1; + return HAL_FAILURE; } if (ReadInt(context, &info.mode) < 0 || ReadInt(context, &info.provdisc) < 0 || ReadInt(context, &info.goIntent) < 0 || ReadInt(context, &info.persistent) < 0 || ReadStr(context, info.peerDevAddr, sizeof(info.peerDevAddr)) != 0 || ReadStr(context, info.pin, sizeof(info.pin)) != 0) { - return -1; + return HAL_FAILURE; } int flag = 0; if (info.provdisc == HAL_WPS_METHOD_DISPLAY && strcmp(info.pin, "pin") == 0) { @@ -443,76 +447,76 @@ int RpcP2pConnect(RpcServer *server, Context *context) WriteStr(context, info.pin); } WriteEnd(context); - return 0; + return HAL_SUCCESS; } int RpcP2pCancelConnect(RpcServer *server, Context *context) { if (server == NULL || context == NULL) { - return -1; + return HAL_FAILURE; } WifiErrorNo err = P2pCancelConnect(); WriteBegin(context, 0); WriteInt(context, err); WriteEnd(context); - return 0; + return HAL_SUCCESS; } int RpcP2pProvisionDiscovery(RpcServer *server, Context *context) { if (server == NULL || context == NULL) { - return -1; + return HAL_FAILURE; } char bssid[WIFI_BSSID_LENGTH] = {0}; int mode = 0; if (ReadStr(context, bssid, sizeof(bssid)) != 0 || ReadInt(context, &mode) < 0) { - return -1; + return HAL_FAILURE; } WifiErrorNo err = P2pProvisionDiscovery(bssid, mode); WriteBegin(context, 0); WriteInt(context, err); WriteEnd(context); - return 0; + return HAL_SUCCESS; } int RpcP2pAddGroup(RpcServer *server, Context *context) { if (server == NULL || context == NULL) { - return -1; + return HAL_FAILURE; } int isPersistent = 0; int networkId = 0; int freq = 0; if (ReadInt(context, &isPersistent) < 0 || ReadInt(context, &networkId) < 0 || ReadInt(context, &freq) < 0) { - return -1; + return HAL_FAILURE; } WifiErrorNo err = P2pAddGroup(isPersistent, networkId, freq); WriteBegin(context, 0); WriteInt(context, err); WriteEnd(context); - return 0; + return HAL_SUCCESS; } int RpcP2pRemoveGroup(RpcServer *server, Context *context) { if (server == NULL || context == NULL) { - return -1; + return HAL_FAILURE; } char interface[WIFI_P2P_GROUP_IFNAME_LENGTH] = {0}; if (ReadStr(context, interface, sizeof(interface)) != 0) { - return -1; + return HAL_FAILURE; } WifiErrorNo err = P2pRemoveGroup(interface); WriteBegin(context, 0); WriteInt(context, err); WriteEnd(context); - return 0; + return HAL_SUCCESS; } int RpcP2pInvite(RpcServer *server, Context *context) { if (server == NULL || context == NULL) { - return -1; + return HAL_FAILURE; } int persistent = 0; char peerBssid[WIFI_BSSID_LENGTH] = {0}; @@ -520,40 +524,40 @@ int RpcP2pInvite(RpcServer *server, Context *context) char ifName[WIFI_IFACE_NAME_MAXLEN] = {0}; if (ReadInt(context, &persistent) < 0 || ReadStr(context, peerBssid, sizeof(peerBssid)) != 0 || ReadStr(context, goBssid, sizeof(goBssid)) != 0 || ReadStr(context, ifName, sizeof(ifName)) != 0) { - return -1; + return HAL_FAILURE; } WifiErrorNo err = P2pInvite(persistent, peerBssid, goBssid, ifName); WriteBegin(context, 0); WriteInt(context, err); WriteEnd(context); - return 0; + return HAL_SUCCESS; } int RpcP2pReinvoke(RpcServer *server, Context *context) { if (server == NULL || context == NULL) { - return -1; + return HAL_FAILURE; } int networkId = 0; char bssid[WIFI_BSSID_LENGTH] = {0}; if (ReadInt(context, &networkId) < 0 || ReadStr(context, bssid, sizeof(bssid)) != 0) { - return -1; + return HAL_FAILURE; } WifiErrorNo err = P2pReinvoke(networkId, bssid); WriteBegin(context, 0); WriteInt(context, err); WriteEnd(context); - return 0; + return HAL_SUCCESS; } int RpcP2pGetGroupCapability(RpcServer *server, Context *context) { if (server == NULL || context == NULL) { - return -1; + return HAL_FAILURE; } char bssid[WIFI_BSSID_LENGTH] = {0}; if (ReadStr(context, bssid, sizeof(bssid)) != 0) { - return -1; + return HAL_FAILURE; } int capacity = 0; WifiErrorNo err = P2pGetGroupCapability(bssid, &capacity); @@ -563,96 +567,98 @@ int RpcP2pGetGroupCapability(RpcServer *server, Context *context) WriteInt(context, capacity); } WriteEnd(context); - return 0; + return HAL_SUCCESS; } int RpcP2pAddService(RpcServer *server, Context *context) { if (server == NULL || context == NULL) { - return -1; + return HAL_FAILURE; } - HidlP2pServiceInfo argv; + P2pServiceInfo argv; if (memset_s(&argv, sizeof(argv), 0, sizeof(argv)) != EOK) { - return -1; + return HAL_FAILURE; } if (ReadInt(context, &argv.mode) < 0) { - return -1; + return HAL_FAILURE; } if (!argv.mode) { if (ReadInt(context, &argv.version) < 0 || ReadStr(context, argv.name, sizeof(argv.name)) != 0) { - return -1; + return HAL_FAILURE; } } else { if (ReadStr(context, argv.query, sizeof(argv.query)) != 0 || ReadStr(context, argv.resp, sizeof(argv.resp)) != 0) { - return -1; + return HAL_FAILURE; } } WifiErrorNo err = P2pAddService(&argv); WriteBegin(context, 0); WriteInt(context, err); WriteEnd(context); - return 0; + return HAL_SUCCESS; } int RpcP2pRemoveService(RpcServer *server, Context *context) { if (server == NULL || context == NULL) { - return -1; + return HAL_FAILURE; } - HidlP2pServiceInfo argv; + P2pServiceInfo argv; if (memset_s(&argv, sizeof(argv), 0, sizeof(argv)) != EOK) { - return -1; + return HAL_FAILURE; } if (ReadInt(context, &argv.mode) < 0) { - return -1; + return HAL_FAILURE; } if (!argv.mode) { if (ReadInt(context, &argv.version) < 0 || ReadStr(context, argv.name, sizeof(argv.name)) != 0) { - return -1; + return HAL_FAILURE; } } else { if (ReadStr(context, argv.query, sizeof(argv.query)) != 0) { - return -1; + return HAL_FAILURE; } } WifiErrorNo err = P2pRemoveService(&argv); WriteBegin(context, 0); WriteInt(context, err); WriteEnd(context); - return 0; + return HAL_SUCCESS; } int RpcP2pReqServiceDiscovery(RpcServer *server, Context *context) { if (server == NULL || context == NULL) { - return -1; + return HAL_FAILURE; } char bssid[WIFI_BSSID_LENGTH] = {0}; if (ReadStr(context, bssid, sizeof(bssid)) != 0) { - return -1; + return HAL_FAILURE; } char discoverinfo[WIFI_P2P_SERVE_DISCOVER_MSG_LENGTH] = {0}; char *pDiscoverInfo = NULL; int len = ReadStr(context, discoverinfo, sizeof(discoverinfo)); if (len < 0) { - return -1; + return HAL_FAILURE; } else if (len > 0) { pDiscoverInfo = (char *)calloc(len + 1, sizeof(char)); if (pDiscoverInfo == NULL) { - return -1; + return HAL_FAILURE; } ReadStr(context, pDiscoverInfo, len + 1); } int retSize = 0; if (ReadInt(context, &retSize) < 0 || retSize <= 0) { free(pDiscoverInfo); - return -1; + pDiscoverInfo = NULL; + return HAL_FAILURE; } char *pRetBuf = (char *)calloc(retSize, sizeof(char)); if (pRetBuf == NULL) { free(pDiscoverInfo); /* free(NULL) is ok, so here no need to judge pDiscoverInfo != NULL */ - return -1; + pDiscoverInfo = NULL; + return HAL_FAILURE; } WifiErrorNo err = P2pReqServiceDiscovery(bssid, ((pDiscoverInfo == NULL) ? discoverinfo : pDiscoverInfo), pRetBuf, retSize); @@ -663,62 +669,64 @@ int RpcP2pReqServiceDiscovery(RpcServer *server, Context *context) } WriteEnd(context); free(pRetBuf); + pRetBuf = NULL; free(pDiscoverInfo); - return 0; + pDiscoverInfo = NULL; + return HAL_SUCCESS; } int RpcP2pCancelServiceDiscovery(RpcServer *server, Context *context) { if (server == NULL || context == NULL) { - return -1; + return HAL_FAILURE; } char id[WIFI_P2P_SERVER_DISCOVERY_SEQUENCE_LENGTH] = {0}; if (ReadStr(context, id, sizeof(id)) != 0) { - return -1; + return HAL_FAILURE; } WifiErrorNo err = P2pCancelServiceDiscovery(id); WriteBegin(context, 0); WriteInt(context, err); WriteEnd(context); - return 0; + return HAL_SUCCESS; } int RpcP2pSetMiracastType(RpcServer *server, Context *context) { if (server == NULL || context == NULL) { - return -1; + return HAL_FAILURE; } int type = 0; if (ReadInt(context, &type) < 0) { - return -1; + return HAL_FAILURE; } WifiErrorNo err = P2pSetMiracastType(type); WriteBegin(context, 0); WriteInt(context, err); WriteEnd(context); - return 0; + return HAL_SUCCESS; } int RpcP2pRespServerDiscovery(RpcServer *server, Context *context) { if (server == NULL || context == NULL) { - return -1; + return HAL_FAILURE; } - HidlP2pServDiscReqInfo info; + P2pServDiscReqInfo info; if (memset_s(&info, sizeof(info), 0, sizeof(info)) != EOK) { - return -1; + return HAL_FAILURE; } if (ReadInt(context, &info.freq) < 0 || ReadInt(context, &info.dialogToken) < 0 || ReadStr(context, info.mac, sizeof(info.mac)) != 0) { - return -1; + return HAL_FAILURE; } int tlvsLen = ReadStr(context, NULL, 0); if (tlvsLen <= 0) { - return -1; + return HAL_FAILURE; } info.tlvs = (char *)calloc(tlvsLen + 1, sizeof(char)); if (info.tlvs == NULL) { - return -1; + return HAL_FAILURE; } ReadStr(context, info.tlvs, tlvsLen + 1); WifiErrorNo err = P2pRespServerDiscovery(&info); @@ -726,51 +734,52 @@ int RpcP2pRespServerDiscovery(RpcServer *server, Context *context) WriteInt(context, err); WriteEnd(context); free(info.tlvs); - return 0; + info.tlvs = NULL; + return HAL_SUCCESS; } int RpcP2pSetServDiscExternal(RpcServer *server, Context *context) { if (server == NULL || context == NULL) { - return -1; + return HAL_FAILURE; } int mode = 0; if (ReadInt(context, &mode) < 0) { - return -1; + return HAL_FAILURE; } WifiErrorNo err = P2pSetServDiscExternal(mode); WriteBegin(context, 0); WriteInt(context, err); WriteEnd(context); - return 0; + return HAL_SUCCESS; } int RpcP2pSetPersistentReconnect(RpcServer *server, Context *context) { if (server == NULL || context == NULL) { - return -1; + return HAL_FAILURE; } int mode = 0; if (ReadInt(context, &mode) < 0) { - return -1; + return HAL_FAILURE; } WifiErrorNo err = P2pSetPersistentReconnect(mode); WriteBegin(context, 0); WriteInt(context, err); WriteEnd(context); - return 0; + return HAL_SUCCESS; } int RpcP2pGetPeer(RpcServer *server, Context *context) { if (server == NULL || context == NULL) { - return -1; + return HAL_FAILURE; } char bssid[WIFI_BSSID_LENGTH] = {0}; - HidlP2pDeviceInfo peerInfo; + P2pDeviceInfo peerInfo; if (memset_s(&peerInfo, sizeof(peerInfo), 0, sizeof(peerInfo)) != EOK || ReadStr(context, bssid, sizeof(bssid)) != 0) { - return -1; + return HAL_FAILURE; } WifiErrorNo err = P2pGetPeer(bssid, &peerInfo); WriteBegin(context, 0); @@ -782,24 +791,25 @@ int RpcP2pGetPeer(RpcServer *server, Context *context) WriteInt(context, peerInfo.configMethods); WriteInt(context, peerInfo.deviceCapabilities); WriteInt(context, peerInfo.groupCapabilities); + WriteStr(context, peerInfo.operSsid); } WriteEnd(context); - return 0; + return HAL_SUCCESS; } int RpcP2pGetFrequencies(RpcServer *server, Context *context) { if (server == NULL || context == NULL) { - return -1; + return HAL_FAILURE; } int band = 0; int maxSize = 0; if (ReadInt(context, &band) < 0 || ReadInt(context, &maxSize) < 0 || maxSize <= 0) { - return -1; + return HAL_FAILURE; } int *frequencies = (int *)calloc(maxSize, sizeof(int)); if (frequencies == NULL) { - return -1; + return HAL_FAILURE; } WifiErrorNo err = P2pGetFrequencies(band, frequencies, &maxSize); WriteBegin(context, 0); @@ -812,22 +822,23 @@ int RpcP2pGetFrequencies(RpcServer *server, Context *context) } WriteEnd(context); free(frequencies); - return 0; + frequencies = NULL; + return HAL_SUCCESS; } int RpcP2pSetGroupConfig(RpcServer *server, Context *context) { if (server == NULL || context == NULL) { - return -1; + return HAL_FAILURE; } int networkId = 0; int size = 0; if (ReadInt(context, &networkId) < 0 || ReadInt(context, &size) < 0 || size <= 0) { - return -1; + return HAL_FAILURE; } - HidlP2pGroupConfig *confs = (HidlP2pGroupConfig *)calloc(size, sizeof(HidlP2pGroupConfig)); + P2pGroupConfig *confs = (P2pGroupConfig *)calloc(size, sizeof(P2pGroupConfig)); if (confs == NULL) { - return -1; + return HAL_FAILURE; } int flag = 0; for (int i = 0; i < size; ++i) { @@ -845,22 +856,23 @@ int RpcP2pSetGroupConfig(RpcServer *server, Context *context) WriteInt(context, err); WriteEnd(context); free(confs); - return 0; + confs = NULL; + return HAL_SUCCESS; } int RpcP2pGetGroupConfig(RpcServer *server, Context *context) { if (server == NULL || context == NULL) { - return -1; + return HAL_FAILURE; } int networkId = 0; int size = 0; if (ReadInt(context, &networkId) < 0 || ReadInt(context, &size) < 0 || size <= 0) { - return -1; + return HAL_FAILURE; } - HidlP2pGroupConfig *confs = (HidlP2pGroupConfig *)calloc(size, sizeof(HidlP2pGroupConfig)); + P2pGroupConfig *confs = (P2pGroupConfig *)calloc(size, sizeof(P2pGroupConfig)); if (confs == NULL) { - return -1; + return HAL_FAILURE; } int flag = 0; for (int i = 0; i < size; ++i) { @@ -882,13 +894,14 @@ int RpcP2pGetGroupConfig(RpcServer *server, Context *context) } WriteEnd(context); free(confs); - return 0; + confs = NULL; + return HAL_SUCCESS; } int RpcP2pAddNetwork(RpcServer *server, Context *context) { if (server == NULL || context == NULL) { - return -1; + return HAL_FAILURE; } int networkId = 0; WifiErrorNo err = P2pAddNetwork(&networkId); @@ -898,5 +911,28 @@ int RpcP2pAddNetwork(RpcServer *server, Context *context) WriteInt(context, networkId); } WriteEnd(context); - return 0; -} \ No newline at end of file + return HAL_SUCCESS; +} + +int RpcP2pHid2dConnect(RpcServer *server, Context *context) +{ + if (server == NULL || context == NULL) { + return HAL_FAILURE; + } + + Hid2dConnectInfo info; + if (memset_s(&info, sizeof(info), 0, sizeof(info)) != EOK) { + return HAL_FAILURE; + } + if (ReadStr(context, info.ssid, sizeof(info.ssid)) != 0 || + ReadStr(context, info.bssid, sizeof(info.bssid)) != 0 || + ReadStr(context, info.passphrase, sizeof(info.passphrase)) != 0 || + ReadInt(context, &info.frequency) < 0) { + return HAL_FAILURE; + } + WifiErrorNo err = P2pHid2dConnect(&info); + WriteBegin(context, 0); + WriteInt(context, err); + WriteEnd(context); + return HAL_SUCCESS; +} diff --git a/services/wifi_standard/wifi_hal/wifi_hal_crpc_p2p.h b/wifi/services/wifi_standard/wifi_hal/wifi_hal_crpc_p2p.h similarity index 97% rename from services/wifi_standard/wifi_hal/wifi_hal_crpc_p2p.h rename to wifi/services/wifi_standard/wifi_hal/wifi_hal_crpc_p2p.h index da6cd33b6148cd5ec012726ed98a70642d6d36da..5da0ac61e250e1415df4ff5fbc96efd0751eabb1 100644 --- a/services/wifi_standard/wifi_hal/wifi_hal_crpc_p2p.h +++ b/wifi/services/wifi_standard/wifi_hal/wifi_hal_crpc_p2p.h @@ -1,5 +1,5 @@ /* - * Copyright (C) 2021 Huawei Device Co., Ltd. + * Copyright (C) 2021-2022 Huawei Device Co., Ltd. * 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 @@ -425,6 +425,15 @@ int RpcP2pGetGroupConfig(RpcServer *server, Context *context); */ int RpcP2pAddNetwork(RpcServer *server, Context *context); +/** + * @Description P2P Connect. + * + * @param server - Pointer to the global structure of the communication server. + * @param context - Pointer to the global communication context structure of the server. + * @return int - 0 Success, -1 Failed. + */ +int RpcP2pHid2dConnect(RpcServer *server, Context *context); + #ifdef __cplusplus } #endif diff --git a/services/wifi_standard/wifi_hal/wifi_hal_crpc_server.c b/wifi/services/wifi_standard/wifi_hal/wifi_hal_crpc_server.c similarity index 91% rename from services/wifi_standard/wifi_hal/wifi_hal_crpc_server.c rename to wifi/services/wifi_standard/wifi_hal/wifi_hal_crpc_server.c index 58bdbb87391c774f509424dc635f3ce626984666..bb481d99dc5f5cad75f3ebd06da1c09de6cac7cd 100644 --- a/services/wifi_standard/wifi_hal/wifi_hal_crpc_server.c +++ b/wifi/services/wifi_standard/wifi_hal/wifi_hal_crpc_server.c @@ -1,5 +1,5 @@ /* - * Copyright (C) 2021 Huawei Device Co., Ltd. + * Copyright (C) 2021-2022 Huawei Device Co., Ltd. * 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 @@ -12,7 +12,10 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + #include "wifi_hal_crpc_server.h" +#include +#include "serial.h" #include "wifi_hal_crpc_base.h" #include "wifi_hal_crpc_chip.h" #include "wifi_hal_crpc_supplicant.h" @@ -20,7 +23,6 @@ #include "wifi_hal_crpc_ap.h" #include "wifi_hal_crpc_common.h" #include "wifi_hal_crpc_p2p.h" -#include "securec.h" #include "wifi_log.h" #include "wifi_hal_common_func.h" @@ -58,7 +60,7 @@ static int GetPos(const char *name) static int PushRpcFunc(const char *name, Rpcfunc func) { if (g_rpcFuncHandle == NULL || name == NULL || func == NULL) { - return -1; + return HAL_FAILURE; } int pos = GetPos(name); if (g_rpcFuncHandle[pos].func == NULL) { @@ -71,14 +73,14 @@ static int PushRpcFunc(const char *name, Rpcfunc func) } WifiHalRpcFunc *q = (WifiHalRpcFunc *)calloc(1, sizeof(WifiHalRpcFunc)); if (q == NULL) { - return -1; + return HAL_FAILURE; } StrSafeCopy(q->funcname, sizeof(q->funcname), name); q->func = func; q->next = NULL; p->next = q; } - return 0; + return HAL_SUCCESS; } static int InitRpcFuncMapBase(void) @@ -104,7 +106,11 @@ static int InitRpcFuncMapChip(void) ret += PushRpcFunc("ConfigComboModes", RpcConfigComboModes); ret += PushRpcFunc("GetComboModes", RpcGetComboModes); ret += PushRpcFunc("RequestFirmwareDebugDump", RpcRequestFirmwareDebugDump); - ret += PushRpcFunc("SetPowerMode", RpcSetPowerMode); + ret += PushRpcFunc("IsChipSupportDbdc", RpcIsChipSupportDbdc); + ret += PushRpcFunc("IsChipSupportCsa", RpcIsChipSupportCsa); + ret += PushRpcFunc("IsChipSupportRadarDetect", RpcIsChipSupportRadarDetect); + ret += PushRpcFunc("IsChipSupportDfsChannel", RpcIsChipSupportDfsChannel); + ret += PushRpcFunc("IsChipSupportIndoorChannel", RpcIsChipSupportIndoorChannel); return ret; } @@ -160,6 +166,7 @@ static int InitRpcFuncMapSta(void) ret += PushRpcFunc("WpaBlocklistClear", RpcWpaBlocklistClear); ret += PushRpcFunc("GetNetworkList", RpcGetNetworkList); ret += PushRpcFunc("GetConnectSignalInfo", RpcGetConnectSignalInfo); + ret += PushRpcFunc("SetSuspendMode", RpcSetSuspendMode); return ret; } @@ -175,6 +182,8 @@ static int InitRpcFuncMapAp(void) ret += PushRpcFunc("DelMacFilter", RpcDelMacFilter); ret += PushRpcFunc("DisassociateSta", RpcDisassociateSta); ret += PushRpcFunc("GetValidFrequenciesForBand", RpcGetValidFrequenciesForBand); + ret += PushRpcFunc("WpaSetPowerModel", RpcSetPowerModel); + ret += PushRpcFunc("WpaGetPowerModel", RpcGetPowerModel); return ret; } @@ -235,17 +244,18 @@ static int InitRpcFuncMapP2p(void) ret += PushRpcFunc("P2pSetGroupConfig", RpcP2pSetGroupConfig); ret += PushRpcFunc("P2pGetGroupConfig", RpcP2pGetGroupConfig); ret += PushRpcFunc("P2pAddNetwork", RpcP2pAddNetwork); + ret += PushRpcFunc("P2pHid2dConnect", RpcP2pHid2dConnect); return ret; } int InitRpcFunc(void) { if (g_rpcFuncHandle != NULL) { - return 0; + return HAL_SUCCESS; } g_rpcFuncHandle = (WifiHalRpcFunc *)calloc(RPC_FUNC_NUM, sizeof(WifiHalRpcFunc)); if (g_rpcFuncHandle == NULL) { - return -1; + return HAL_FAILURE; } int ret = 0; @@ -257,13 +267,13 @@ int InitRpcFunc(void) ret += InitRpcFuncMapCommon(); ret += InitRpcFuncMapP2p(); if (ret < 0) { - return -1; + return HAL_FAILURE; } if (InitCallbackMsg() < 0) { - return -1; + return HAL_FAILURE; } - return 0; + return HAL_SUCCESS; } void ReleaseRpcFunc(void) @@ -302,21 +312,21 @@ Rpcfunc GetRpcFunc(const char *func) int OnTransact(RpcServer *server, Context *context) { if ((server == NULL) || (context == NULL)) { - return -1; + return HAL_FAILURE; } char func[RPC_FUNCNAME_MAX_LEN] = {0}; int ret = ReadFunc(context, func, RPC_FUNCNAME_MAX_LEN); if (ret < 0) { - return -1; + return HAL_FAILURE; } LOGI("run %{public}s", func); Rpcfunc pFunc = GetRpcFunc(func); if (pFunc == NULL) { - LOGD("unsupport function[%{public}s]", func); + LOGD("unsupported function[%{public}s]", func); WriteBegin(context, 0); WriteInt(context, WIFI_HAL_FAILED); - WriteStr(context, "unsupport function"); + WriteStr(context, "unsupported function"); WriteEnd(context); } else { ret = pFunc(server, context); @@ -327,7 +337,7 @@ int OnTransact(RpcServer *server, Context *context) WriteEnd(context); } } - return 0; + return HAL_SUCCESS; } /* Defines the bidirectional list of global callback event parameters. */ @@ -336,18 +346,18 @@ static WifiHalEventCallback *g_wifiHalEventCallback = NULL; int InitCallbackMsg(void) { if (g_wifiHalEventCallback != NULL) { - return 0; + return HAL_SUCCESS; } g_wifiHalEventCallback = (WifiHalEventCallback *)calloc(1, sizeof(WifiHalEventCallback)); if (g_wifiHalEventCallback == NULL) { - return -1; + return HAL_FAILURE; } pthread_mutex_init(&g_wifiHalEventCallback->mutex, NULL); for (int i = 0; i < WIFI_HAL_MAX_EVENT - WIFI_FAILURE_EVENT; ++i) { g_wifiHalEventCallback->cbmsgs[i].pre = g_wifiHalEventCallback->cbmsgs + i; g_wifiHalEventCallback->cbmsgs[i].next = g_wifiHalEventCallback->cbmsgs + i; } - return 0; + return HAL_SUCCESS; } void ReleaseCallbackMsg(void) @@ -373,7 +383,7 @@ void ReleaseCallbackMsg(void) int PushBackCallbackMsg(int event, WifiHalEventCallbackMsg *msg) { if (g_wifiHalEventCallback == NULL || event >= WIFI_HAL_MAX_EVENT || event < WIFI_FAILURE_EVENT || msg == NULL) { - return -1; + return HAL_FAILURE; } int pos = event - WIFI_FAILURE_EVENT; pthread_mutex_lock(&g_wifiHalEventCallback->mutex); @@ -390,13 +400,13 @@ int PushBackCallbackMsg(int event, WifiHalEventCallbackMsg *msg) head->pre = msg; } pthread_mutex_unlock(&g_wifiHalEventCallback->mutex); - return 0; + return HAL_SUCCESS; } int PopBackCallbackMsg(int event) { if (g_wifiHalEventCallback == NULL || event >= WIFI_HAL_MAX_EVENT || event < WIFI_FAILURE_EVENT) { - return -1; + return HAL_FAILURE; } int pos = event - WIFI_FAILURE_EVENT; pthread_mutex_lock(&g_wifiHalEventCallback->mutex); @@ -407,7 +417,7 @@ int PopBackCallbackMsg(int event) tail->pre->next = head; } pthread_mutex_unlock(&g_wifiHalEventCallback->mutex); - return 0; + return HAL_SUCCESS; } WifiHalEventCallbackMsg *FrontCallbackMsg(int event) @@ -427,7 +437,7 @@ WifiHalEventCallbackMsg *FrontCallbackMsg(int event) int PopFrontCallbackMsg(int event) { if (g_wifiHalEventCallback == NULL || event >= WIFI_HAL_MAX_EVENT || event < WIFI_FAILURE_EVENT) { - return -1; + return HAL_FAILURE; } int pos = event - WIFI_FAILURE_EVENT; pthread_mutex_lock(&g_wifiHalEventCallback->mutex); @@ -437,9 +447,10 @@ int PopFrontCallbackMsg(int event) head->next = p->next; p->next->pre = head; free(p); + p = NULL; } pthread_mutex_unlock(&g_wifiHalEventCallback->mutex); - return 0; + return HAL_SUCCESS; } /* Processing callback messages */ @@ -456,6 +467,7 @@ static void DealIfaceCbk(int event, Context *context) { WifiHalEventCallbackMsg *cbmsg = FrontCallbackMsg(event); if (cbmsg != NULL) { + WriteInt(context, cbmsg->msg.ifMsg.id); WriteInt(context, cbmsg->msg.ifMsg.type); WriteStr(context, cbmsg->msg.ifMsg.ifname); } @@ -473,6 +485,16 @@ static void DealConnectionChangedCbk(int event, Context *context) return; } +static void DealBssidChangedCbk(int event, Context *context) +{ + WifiHalEventCallbackMsg *cbmsg = FrontCallbackMsg(event); + if (cbmsg != NULL) { + WriteStr(context, cbmsg->msg.bssidChangedMsg.reason); + WriteStr(context, cbmsg->msg.bssidChangedMsg.bssid); + } + return; +} + static void DealConnectWpsResultCbk(int event, Context *context) { WifiHalEventCallbackMsg *cbmsg = FrontCallbackMsg(event); @@ -488,6 +510,8 @@ static void DealStaApCallback(int event, Context *context) case WIFI_ADD_IFACE_EVENT: case WIFI_STA_JOIN_EVENT: case WIFI_STA_LEAVE_EVENT: + case WIFI_AP_ENABLE_EVENT: + case WIFI_AP_DISABLE_EVENT: DealIfaceCbk(event, context); break; case WIFI_SCAN_INFO_NOTIFY_EVENT: @@ -497,12 +521,18 @@ static void DealStaApCallback(int event, Context *context) case WIFI_SSID_WRONG_KEY: case WIFI_WPS_OVERLAP: case WIFI_WPS_TIME_OUT: + case WIFI_CONNECTION_FULL_EVENT: + case WIFI_CONNECTION_REJECT_EVENT: DealConnectWpsResultCbk(event, context); break; case WIFI_CONNECT_CHANGED_NOTIFY_EVENT: DealConnectionChangedCbk(event, context); break; + case WIFI_BSSID_CHANGED_NOTIFY_EVENT: + DealBssidChangedCbk(event, context); + break; default: + LOGE("DealStaApCallback, Invalid event: %{public}d", event); break; } return; @@ -614,6 +644,7 @@ static void DealP2pServerInfoCbk(int event, Context *context) WriteInt(context, strlen(cbmsg->msg.serverInfo.tlvs)); WriteStr(context, cbmsg->msg.serverInfo.tlvs); free(cbmsg->msg.serverInfo.tlvs); + cbmsg->msg.serverInfo.tlvs = NULL; } else { WriteInt(context, 0); } @@ -633,6 +664,7 @@ static void DealP2pServerDiscReqCbk(int event, Context *context) WriteInt(context, strlen(cbmsg->msg.serDiscReqInfo.tlvs)); WriteStr(context, cbmsg->msg.serDiscReqInfo.tlvs); free(cbmsg->msg.serDiscReqInfo.tlvs); + cbmsg->msg.serDiscReqInfo.tlvs = NULL; } else { WriteInt(context, 0); } @@ -677,6 +709,8 @@ static void DealP2pCallback(int event, Context *context) case P2P_SERV_DISC_REQ_EVENT: DealP2pServerDiscReqCbk(event, context); break; + case P2P_IFACE_CREATED_EVENT: + DealIfaceCbk(event, context); default: break; } @@ -687,20 +721,20 @@ static void DealP2pCallback(int event, Context *context) int OnCallbackTransact(const RpcServer *server, int event, Context *context) { if (server == NULL || context == NULL) { - return -1; + return HAL_FAILURE; } WriteBegin(context, 1); WriteInt(context, event); DealStaApCallback(event, context); DealP2pCallback(event, context); WriteEnd(context); - return 0; + return HAL_SUCCESS; } int EndCallbackTransact(const RpcServer *server, int event) { if (server == NULL) { - return -1; + return HAL_FAILURE; } return PopFrontCallbackMsg(event); -} \ No newline at end of file +} diff --git a/services/wifi_standard/wifi_hal/wifi_hal_crpc_server.h b/wifi/services/wifi_standard/wifi_hal/wifi_hal_crpc_server.h similarity index 90% rename from services/wifi_standard/wifi_hal/wifi_hal_crpc_server.h rename to wifi/services/wifi_standard/wifi_hal/wifi_hal_crpc_server.h index 9cdf0a6027c3b75f6f31edd204c59eeca88bef00..ce95cc47c3331927c33df3778ce6b74feba6468d 100644 --- a/services/wifi_standard/wifi_hal/wifi_hal_crpc_server.h +++ b/wifi/services/wifi_standard/wifi_hal/wifi_hal_crpc_server.h @@ -70,6 +70,7 @@ void SetRpcServerInited(RpcServer *server); RpcServer *GetRpcServer(void); typedef struct WifiHalCbIFaceMsg { + int id; int type; char ifname[WIFI_IFACE_NAME_MAXLEN]; } WifiHalCbIFaceMsg; @@ -80,15 +81,21 @@ typedef struct WifiHalConnectMsg { char bssid[WIFI_MAC_LENGTH + 1]; } WifiHalConnectMsg; +typedef struct WifiHalBssidChangedMsg { + char reason[WIFI_REASON_LENGTH]; + char bssid[WIFI_MAC_LENGTH + 1]; +} WifiHalBssidChangedMsg; + typedef union WifiHalCallbackMsg { int scanStatus; WifiHalConnectMsg connMsg; WifiHalCbIFaceMsg ifMsg; - HidlP2pDeviceInfo deviceInfo; - HidlP2pGroupInfo groupInfo; - HidlP2pInvitationInfo invitaInfo; - HidlP2pServDiscRespInfo serverInfo; - HidlP2pServDiscReqInfo serDiscReqInfo; + P2pDeviceInfo deviceInfo; + P2pGroupInfo groupInfo; + P2pInvitationInfo invitaInfo; + P2pServDiscRespInfo serverInfo; + P2pServDiscReqInfo serDiscReqInfo; + WifiHalBssidChangedMsg bssidChangedMsg; } WifiHalCallbackMsg; typedef struct WifiHalEventCallbackMsg { @@ -117,7 +124,7 @@ void ReleaseCallbackMsg(void); /** * @Description Add an event node to the header of the corresponding event linked list. * - * @param event - Evnet id. + * @param event - Event id. * @param msg * @return int - 0 Success, -1 Failed. */ diff --git a/services/wifi_standard/wifi_hal/wifi_hal_crpc_sta.c b/wifi/services/wifi_standard/wifi_hal/wifi_hal_crpc_sta.c similarity index 79% rename from services/wifi_standard/wifi_hal/wifi_hal_crpc_sta.c rename to wifi/services/wifi_standard/wifi_hal/wifi_hal_crpc_sta.c index 0817570ad5fc9ce7705113ceed2d74d069e40cce..01ca3670dd456910843e1ff6ee6a62267cdc7451 100644 --- a/services/wifi_standard/wifi_hal/wifi_hal_crpc_sta.c +++ b/wifi/services/wifi_standard/wifi_hal/wifi_hal_crpc_sta.c @@ -1,5 +1,5 @@ /* - * Copyright (C) 2021 Huawei Device Co., Ltd. + * Copyright (C) 2021-2022 Huawei Device Co., Ltd. * 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 @@ -14,6 +14,7 @@ */ #include "wifi_hal_crpc_sta.h" +#include "serial.h" #include "wifi_hal_crpc_base.h" #include "wifi_hal_sta_interface.h" #include "wifi_hal_define.h" @@ -21,31 +22,31 @@ int RpcStart(RpcServer *server, Context *context) { if (server == NULL || context == NULL) { - return -1; + return HAL_FAILURE; } WifiErrorNo err = Start(); WriteBegin(context, 0); WriteInt(context, err); WriteEnd(context); - return 0; + return HAL_SUCCESS; } int RpcStop(RpcServer *server, Context *context) { if (server == NULL || context == NULL) { - return -1; + return HAL_FAILURE; } WifiErrorNo err = Stop(); WriteBegin(context, 0); WriteInt(context, err); WriteEnd(context); - return 0; + return HAL_SUCCESS; } int RpcStartScan(RpcServer *server, Context *context) { if (server == NULL || context == NULL) { - return -1; + return HAL_FAILURE; } ScanSettings setting = {0}; int ret = -1; @@ -83,11 +84,14 @@ int RpcStartScan(RpcServer *server, Context *context) if (setting.hiddenSsid != NULL) { for (int i = 0; i < setting.hiddenSsidSize; ++i) { free(setting.hiddenSsid[i]); + setting.hiddenSsid[i] = NULL; } free(setting.hiddenSsid); + setting.hiddenSsid = NULL; } if (setting.freqs != NULL) { free(setting.freqs); + setting.freqs = NULL; } return ret; } @@ -95,18 +99,18 @@ int RpcStartScan(RpcServer *server, Context *context) int RpcGetScanInfos(RpcServer *server, Context *context) { if (server == NULL || context == NULL) { - return -1; + return HAL_FAILURE; } int maxSize = 0; if (ReadInt(context, &maxSize) < 0) { - return -1; + return HAL_FAILURE; } ScanInfo *results = NULL; if (maxSize > 0) { results = (ScanInfo *)calloc(maxSize, sizeof(ScanInfo)); } if (results == NULL) { - return -1; + return HAL_FAILURE; } WifiErrorNo err = GetScanInfos(results, &maxSize); WriteBegin(context, 0); @@ -124,6 +128,17 @@ int RpcGetScanInfos(RpcServer *server, Context *context) WriteStr(context, results[i].ssid); int64_t currTime = (int64_t)clockTime.tv_sec * secComplex * secComplex + clockTime.tv_nsec / secComplex; WriteInt64(context, currTime); + WriteInt(context, results[i].channelWidth); + WriteInt(context, results[i].centerFrequency0); + WriteInt(context, results[i].centerFrequency1); + WriteInt(context, results[i].ieSize); + for (int j = 0; j < results[i].ieSize; ++j) { + WriteInt(context, results[i].infoElems[j].id); + WriteInt(context, results[i].infoElems[j].size); + WriteUStr(context, (unsigned char *)results[i].infoElems[j].content, results[i].infoElems[j].size); + free(results[i].infoElems[j].content); + results[i].infoElems[j].content = NULL; + } if (results[i].infoElems != NULL) { free(results[i].infoElems); results[i].infoElems = NULL; @@ -132,46 +147,47 @@ int RpcGetScanInfos(RpcServer *server, Context *context) } WriteEnd(context); free(results); - return 0; + results = NULL; + return HAL_SUCCESS; } static int ReadPnoScanSettings(Context *context, PnoScanSettings *pSetting) { if (ReadInt(context, &pSetting->scanInterval) < 0 || ReadInt(context, &pSetting->minRssi2Dot4Ghz) < 0 || ReadInt(context, &pSetting->minRssi5Ghz) < 0 || ReadInt(context, &pSetting->hiddenSsidSize) < 0) { - return -1; + return HAL_FAILURE; } if (pSetting->hiddenSsidSize > 0) { pSetting->hiddenSsid = ReadCharArray(context, pSetting->hiddenSsidSize); if (pSetting->hiddenSsid == NULL) { - return -1; + return HAL_FAILURE; } } if (ReadInt(context, &pSetting->savedSsidSize) < 0) { - return -1; + return HAL_FAILURE; } if (pSetting->savedSsidSize > 0) { pSetting->savedSsid = ReadCharArray(context, pSetting->savedSsidSize); if (pSetting->savedSsid == NULL) { - return -1; + return HAL_FAILURE; } } if (ReadInt(context, &pSetting->freqSize) < 0) { - return -1; + return HAL_FAILURE; } if (pSetting->freqSize > 0) { pSetting->freqs = ReadIntArray(context, pSetting->freqSize); if (pSetting->freqs == NULL) { - return -1; + return HAL_FAILURE; } } - return 0; + return HAL_SUCCESS; } int RpcStartPnoScan(RpcServer *server, Context *context) { if (server == NULL || context == NULL) { - return -1; + return HAL_FAILURE; } PnoScanSettings setting = {0}; int ret = ReadPnoScanSettings(context, &setting); @@ -184,17 +200,22 @@ int RpcStartPnoScan(RpcServer *server, Context *context) if (setting.hiddenSsid != NULL) { for (int i = 0; i < setting.hiddenSsidSize; ++i) { free(setting.hiddenSsid[i]); + setting.hiddenSsid[i] = NULL; } free(setting.hiddenSsid); + setting.hiddenSsid = NULL; } if (setting.savedSsid != NULL) { for (int i = 0; i < setting.savedSsidSize; ++i) { free(setting.savedSsid[i]); + setting.savedSsid[i] = NULL; } free(setting.savedSsid); + setting.savedSsid = NULL; } if (setting.freqs != NULL) { free(setting.freqs); + setting.freqs = NULL; } return ret; @@ -203,71 +224,71 @@ int RpcStartPnoScan(RpcServer *server, Context *context) int RpcStopPnoScan(RpcServer *server, Context *context) { if (server == NULL || context == NULL) { - return -1; + return HAL_FAILURE; } WifiErrorNo err = StopPnoScan(); WriteBegin(context, 0); WriteInt(context, err); WriteEnd(context); - return 0; + return HAL_SUCCESS; } int RpcConnect(RpcServer *server, Context *context) { if (server == NULL || context == NULL) { - return -1; + return HAL_FAILURE; } int networkId = 0; if (ReadInt(context, &networkId) < 0) { - return -1; + return HAL_FAILURE; } WifiErrorNo err = Connect(networkId); WriteBegin(context, 0); WriteInt(context, err); WriteEnd(context); - return 0; + return HAL_SUCCESS; } int RpcReconnect(RpcServer *server, Context *context) { if (server == NULL || context == NULL) { - return -1; + return HAL_FAILURE; } WifiErrorNo err = Reconnect(); WriteBegin(context, 0); WriteInt(context, err); WriteEnd(context); - return 0; + return HAL_SUCCESS; } int RpcReassociate(RpcServer *server, Context *context) { if (server == NULL || context == NULL) { - return -1; + return HAL_FAILURE; } WifiErrorNo err = Reassociate(); WriteBegin(context, 0); WriteInt(context, err); WriteEnd(context); - return 0; + return HAL_SUCCESS; } int RpcDisconnect(RpcServer *server, Context *context) { if (server == NULL || context == NULL) { - return -1; + return HAL_FAILURE; } WifiErrorNo err = Disconnect(); WriteBegin(context, 0); WriteInt(context, err); WriteEnd(context); - return 0; + return HAL_SUCCESS; } int RpcGetStaCapabilities(RpcServer *server, Context *context) { if (server == NULL || context == NULL) { - return -1; + return HAL_FAILURE; } int32_t capabilities = 0; WifiErrorNo err = GetStaCapabilities(&capabilities); @@ -277,24 +298,24 @@ int RpcGetStaCapabilities(RpcServer *server, Context *context) WriteInt(context, capabilities); } WriteEnd(context); - return 0; + return HAL_SUCCESS; } int RpcGetDeviceMacAddress(RpcServer *server, Context *context) { if (server == NULL || context == NULL) { - return -1; + return HAL_FAILURE; } int maxSize = 0; if (ReadInt(context, &maxSize) < 0 || maxSize <= 0) { - return -1; + return HAL_FAILURE; } unsigned char *mac = NULL; if (maxSize > 0) { mac = (unsigned char *)calloc(maxSize + 1, sizeof(unsigned char)); } if (mac == NULL) { - return -1; + return HAL_FAILURE; } WifiErrorNo err = GetDeviceMacAddress(mac, &maxSize); WriteBegin(context, 0); @@ -305,22 +326,23 @@ int RpcGetDeviceMacAddress(RpcServer *server, Context *context) } WriteEnd(context); free(mac); - return 0; + mac = NULL; + return HAL_SUCCESS; } int RpcGetFrequencies(RpcServer *server, Context *context) { if (server == NULL || context == NULL) { - return -1; + return HAL_FAILURE; } int band = 0; int maxSize = 0; if (ReadInt(context, &band) < 0 || ReadInt(context, &maxSize) < 0 || maxSize <= 0) { - return -1; + return HAL_FAILURE; } int *frequencies = (int *)calloc(maxSize, sizeof(int)); if (frequencies == NULL) { - return -1; + return HAL_FAILURE; } WifiErrorNo err = GetFrequencies(band, frequencies, &maxSize); WriteBegin(context, 0); @@ -333,91 +355,93 @@ int RpcGetFrequencies(RpcServer *server, Context *context) } WriteEnd(context); free(frequencies); - return 0; + frequencies = NULL; + return HAL_SUCCESS; } int RpcSetAssocMacAddr(RpcServer *server, Context *context) { if (server == NULL || context == NULL) { - return -1; + return HAL_FAILURE; } int maxSize = 0; if (ReadInt(context, &maxSize) < 0) { - return -1; + return HAL_FAILURE; } int len = maxSize + 1; unsigned char *mac = (unsigned char *)calloc(len, sizeof(unsigned char)); if (mac == NULL) { - return -1; + return HAL_FAILURE; } if (ReadUStr(context, mac, len) != 0) { free(mac); - return -1; + mac = NULL; + return HAL_FAILURE; } WifiErrorNo err = SetAssocMacAddr(mac, maxSize); WriteBegin(context, 0); WriteInt(context, err); WriteEnd(context); free(mac); - return 0; + return HAL_SUCCESS; } int RpcSetScanningMacAddress(RpcServer *server, Context *context) { if (server == NULL || context == NULL) { - return -1; + return HAL_FAILURE; } int maxSize = 0; if (ReadInt(context, &maxSize) < 0 || maxSize < 0) { - return -1; + return HAL_FAILURE; } int len = maxSize + 1; unsigned char *mac = (unsigned char *)calloc(len, sizeof(unsigned char)); if (mac == NULL) { - return -1; + return HAL_FAILURE; } if (ReadUStr(context, mac, len) != 0) { free(mac); - return -1; + return HAL_FAILURE; } WifiErrorNo err = SetScanningMacAddress(mac, maxSize); WriteBegin(context, 0); WriteInt(context, err); WriteEnd(context); free(mac); - return 0; + return HAL_SUCCESS; } int RpcDeauthLastRoamingBssid(RpcServer *server, Context *context) { if (server == NULL || context == NULL) { - return -1; + return HAL_FAILURE; } int maxSize = 0; if (ReadInt(context, &maxSize) < 0 || maxSize < 0) { - return -1; + return HAL_FAILURE; } int len = maxSize + 1; unsigned char *mac = (unsigned char *)calloc(len, sizeof(unsigned char)); if (mac == NULL) { - return -1; + return HAL_FAILURE; } if (ReadUStr(context, mac, len) != 0) { free(mac); - return -1; + return HAL_FAILURE; } WifiErrorNo err = DeauthLastRoamingBssid(mac, maxSize); WriteBegin(context, 0); WriteInt(context, err); WriteEnd(context); free(mac); - return 0; + return HAL_SUCCESS; } int RpcGetSupportFeature(RpcServer *server, Context *context) { if (server == NULL || context == NULL) { - return -1; + return HAL_FAILURE; } long feature = 0; WifiErrorNo err = GetSupportFeature(&feature); @@ -427,24 +451,24 @@ int RpcGetSupportFeature(RpcServer *server, Context *context) WriteLong(context, feature); } WriteEnd(context); - return 0; + return HAL_SUCCESS; } int RpcRunCmd(RpcServer *server, Context *context) { if (server == NULL || context == NULL) { - return -1; + return HAL_FAILURE; } char ifname[WIFI_IFACE_NAME_MAXLEN] = {0}; char *pIfName = NULL; int ret = ReadStr(context, ifname, WIFI_IFACE_NAME_MAXLEN); if (ret < 0) { - return -1; + return HAL_FAILURE; } else if (ret > 0) { int len = ret + 1; pIfName = (char *)calloc(len, sizeof(char)); if (pIfName == NULL) { - return -1; + return HAL_FAILURE; } ReadStr(context, pIfName, len); } @@ -452,18 +476,22 @@ int RpcRunCmd(RpcServer *server, Context *context) int bufsize = 0; if (ReadInt(context, &cmdid) < 0 || ReadInt(context, &bufsize) < 0 || bufsize < 0) { free(pIfName); - return -1; + pIfName = NULL; + return HAL_FAILURE; } int len = bufsize + 1; unsigned char *buf = (unsigned char *)calloc(len, sizeof(unsigned char)); if (buf == NULL) { free(pIfName); - return -1; + pIfName = NULL; + return HAL_FAILURE; } if (ReadUStr(context, buf, len) != 0) { free(pIfName); free(buf); - return -1; + pIfName = NULL; + buf = NULL; + return HAL_FAILURE; } WifiErrorNo err = RunCmd((pIfName == NULL) ? ifname : pIfName, cmdid, buf, bufsize); WriteBegin(context, 0); @@ -471,45 +499,47 @@ int RpcRunCmd(RpcServer *server, Context *context) WriteEnd(context); free(pIfName); free(buf); - return 0; + pIfName = NULL; + buf = NULL; + return HAL_SUCCESS; } int RpcSetWifiTxPower(RpcServer *server, Context *context) { if (server == NULL || context == NULL) { - return -1; + return HAL_FAILURE; } int32_t power = 0; if (ReadInt(context, &power) < 0) { - return -1; + return HAL_FAILURE; } WifiErrorNo err = SetWifiTxPower(power); WriteBegin(context, 0); WriteInt(context, err); WriteEnd(context); - return 0; + return HAL_SUCCESS; } int RpcRemoveNetwork(RpcServer *server, Context *context) { if (server == NULL || context == NULL) { - return -1; + return HAL_FAILURE; } int32_t networkId = 0; if (ReadInt(context, &networkId) < 0) { - return -1; + return HAL_FAILURE; } WifiErrorNo err = RemoveNetwork(networkId); WriteBegin(context, 0); WriteInt(context, err); WriteEnd(context); - return 0; + return HAL_SUCCESS; } int RpcAddNetwork(RpcServer *server, Context *context) { if (server == NULL || context == NULL) { - return -1; + return HAL_FAILURE; } int networkId = 0; WifiErrorNo err = AddNetwork(&networkId); @@ -519,61 +549,61 @@ int RpcAddNetwork(RpcServer *server, Context *context) WriteInt(context, networkId); } WriteEnd(context); - return 0; + return HAL_SUCCESS; } int RpcEnableNetwork(RpcServer *server, Context *context) { if (server == NULL || context == NULL) { - return -1; + return HAL_FAILURE; } int networkId = 0; if (ReadInt(context, &networkId) < 0) { - return -1; + return HAL_FAILURE; } WifiErrorNo err = EnableNetwork(networkId); WriteBegin(context, 0); WriteInt(context, err); WriteEnd(context); - return 0; + return HAL_SUCCESS; } int RpcDisableNetwork(RpcServer *server, Context *context) { if (server == NULL || context == NULL) { - return -1; + return HAL_FAILURE; } int networkId = 0; if (ReadInt(context, &networkId) < 0) { - return -1; + return HAL_FAILURE; } WifiErrorNo err = DisableNetwork(networkId); WriteBegin(context, 0); WriteInt(context, err); WriteEnd(context); - return 0; + return HAL_SUCCESS; } int RpcSetNetwork(RpcServer *server, Context *context) { if (server == NULL || context == NULL) { - return -1; + return HAL_FAILURE; } int networkId = 0; if (ReadInt(context, &networkId) < 0) { - return -1; + return HAL_FAILURE; } int size = 0; if (ReadInt(context, &size) < 0) { - return -1; + return HAL_FAILURE; } if (size <= 0) { - return -1; + return HAL_FAILURE; } - HidlSetNetworkConfig *confs = (HidlSetNetworkConfig *)calloc(size, sizeof(HidlSetNetworkConfig)); + SetNetworkConfig *confs = (SetNetworkConfig *)calloc(size, sizeof(SetNetworkConfig)); if (confs == NULL) { - return -1; + return HAL_FAILURE; } int flag = 0; @@ -592,57 +622,58 @@ int RpcSetNetwork(RpcServer *server, Context *context) WriteInt(context, err); WriteEnd(context); free(confs); - return 0; + confs = NULL; + return HAL_SUCCESS; } int RpcSaveNetworkConfig(RpcServer *server, Context *context) { if (server == NULL || context == NULL) { - return -1; + return HAL_FAILURE; } WifiErrorNo err = SaveNetworkConfig(); WriteBegin(context, 0); WriteInt(context, err); WriteEnd(context); - return 0; + return HAL_SUCCESS; } int RpcStartWpsPbcMode(RpcServer *server, Context *context) { if (server == NULL || context == NULL) { - return -1; + return HAL_FAILURE; } WifiWpsParam param = {0}; if (ReadInt(context, ¶m.anyFlag) < 0) { - return -1; + return HAL_FAILURE; } if (ReadInt(context, ¶m.multiAp) < 0) { - return -1; + return HAL_FAILURE; } if (ReadStr(context, param.bssid, sizeof(param.bssid)) != 0) { - return -1; + return HAL_FAILURE; } WifiErrorNo err = StartWpsPbcMode(¶m); WriteBegin(context, 0); WriteInt(context, err); WriteEnd(context); - return 0; + return HAL_SUCCESS; } int RpcStartWpsPinMode(RpcServer *server, Context *context) { if (server == NULL || context == NULL) { - return -1; + return HAL_FAILURE; } WifiWpsParam param = {0}; if (ReadInt(context, ¶m.anyFlag) < 0) { - return -1; + return HAL_FAILURE; } if (ReadInt(context, ¶m.multiAp) < 0) { - return -1; + return HAL_FAILURE; } if (ReadStr(context, param.bssid, sizeof(param.bssid)) != 0) { - return -1; + return HAL_FAILURE; } int pinCode = 0; WifiErrorNo err = StartWpsPinMode(¶m, &pinCode); @@ -652,25 +683,25 @@ int RpcStartWpsPinMode(RpcServer *server, Context *context) WriteInt(context, pinCode); } WriteEnd(context); - return 0; + return HAL_SUCCESS; } int RpcStopWps(RpcServer *server, Context *context) { if (server == NULL || context == NULL) { - return -1; + return HAL_FAILURE; } WifiErrorNo err = StopWps(); WriteBegin(context, 0); WriteInt(context, err); WriteEnd(context); - return 0; + return HAL_SUCCESS; } int RpcGetRoamingCapabilities(RpcServer *server, Context *context) { if (server == NULL || context == NULL) { - return -1; + return HAL_FAILURE; } WifiRoamCapability capability = {0}; WifiErrorNo err = GetRoamingCapabilities(&capability); @@ -681,7 +712,7 @@ int RpcGetRoamingCapabilities(RpcServer *server, Context *context) WriteInt(context, capability.maxTrustlistSize); } WriteEnd(context); - return 0; + return HAL_SUCCESS; } static char **ReadRoamBlockList(Context *context, int size) @@ -710,8 +741,10 @@ static char **ReadRoamBlockList(Context *context, int size) if (i < size) { for (int j = 0; j <= i; ++j) { free(list[j]); + list[j] = NULL; } free(list); + list = NULL; return NULL; } else { return list; @@ -721,7 +754,7 @@ static char **ReadRoamBlockList(Context *context, int size) int RpcSetRoamConfig(RpcServer *server, Context *context) { if (server == NULL || context == NULL) { - return -1; + return HAL_FAILURE; } int blocksize = 0; char **blocklist = NULL; @@ -758,14 +791,18 @@ int RpcSetRoamConfig(RpcServer *server, Context *context) if (blocklist != NULL) { for (int i = 0; i < blocksize; ++i) { free(blocklist[i]); + blocklist[i] = NULL; } free(blocklist); + blocklist = NULL; } if (trustlist != NULL) { for (int i = 0; i < size; ++i) { free(trustlist[i]); + trustlist[i] = NULL; } free(trustlist); + trustlist = NULL; } return ret; } @@ -773,11 +810,11 @@ int RpcSetRoamConfig(RpcServer *server, Context *context) int RpcWpaGetNetwork(RpcServer *server, Context *context) { if (server == NULL || context == NULL) { - return -1; + return HAL_FAILURE; } - HidlGetNetworkConfig conf = {0}; + GetNetworkConfig conf = {0}; if (ReadInt(context, &(conf.networkId)) < 0 || ReadStr(context, conf.param, sizeof(conf.param)) != 0) { - return -1; + return HAL_FAILURE; } WifiErrorNo err = WpaGetNetWork(&conf); WriteBegin(context, 0); @@ -786,53 +823,53 @@ int RpcWpaGetNetwork(RpcServer *server, Context *context) WriteStr(context, conf.value); } WriteEnd(context); - return 0; + return HAL_SUCCESS; } int RpcWpaAutoConnect(RpcServer *server, Context *context) { if (server == NULL || context == NULL) { - return -1; + return HAL_FAILURE; } int enable = 0; if (ReadInt(context, &enable) < 0) { - return -1; + return HAL_FAILURE; } WifiErrorNo err = WpaAutoConnect(enable); WriteBegin(context, 0); WriteInt(context, err); WriteEnd(context); - return 0; + return HAL_SUCCESS; } int RpcWpaBlocklistClear(RpcServer *server, Context *context) { if (server == NULL || context == NULL) { - return -1; + return HAL_FAILURE; } WifiErrorNo err = WpaBlocklistClear(); WriteBegin(context, 0); WriteInt(context, err); WriteEnd(context); - return 0; + return HAL_SUCCESS; } int RpcGetNetworkList(RpcServer *server, Context *context) { if (server == NULL || context == NULL) { - return -1; + return HAL_FAILURE; } int maxSize = 0; if (ReadInt(context, &maxSize) < 0) { - return -1; + return HAL_FAILURE; } if (maxSize <= 0) { - return -1; + return HAL_FAILURE; } - HidlNetworkInfo *infos = (HidlNetworkInfo *)calloc(maxSize, sizeof(HidlNetworkInfo)); + WifiNetworkInfo *infos = (WifiNetworkInfo *)calloc(maxSize, sizeof(WifiNetworkInfo)); if (infos == NULL) { - return -1; + return HAL_FAILURE; } WifiErrorNo err = GetNetworkList(infos, &maxSize); @@ -849,19 +886,20 @@ int RpcGetNetworkList(RpcServer *server, Context *context) } WriteEnd(context); free(infos); - return 0; + infos = NULL; + return HAL_SUCCESS; } int RpcGetConnectSignalInfo(RpcServer *server, Context *context) { if (server == NULL || context == NULL) { - return -1; + return HAL_FAILURE; } char endBssid[WIFI_BSSID_LENGTH] = {0}; if (ReadStr(context, endBssid, sizeof(endBssid)) != 0) { - return -1; + return HAL_FAILURE; } - HidlWpaSignalInfo info = {0}; + WpaSignalInfo info = {0}; WifiErrorNo err = GetConnectSignalInfo(endBssid, &info); WriteBegin(context, 0); WriteInt(context, err); @@ -873,5 +911,22 @@ int RpcGetConnectSignalInfo(RpcServer *server, Context *context) WriteInt(context, info.frequency); } WriteEnd(context); - return 0; -} \ No newline at end of file + return HAL_SUCCESS; +} + +int RpcSetSuspendMode(RpcServer *server, Context *context) +{ + if (server == NULL || context == NULL) { + return HAL_FAILURE; + } + int tmpMode = 0; + if (ReadInt(context, &tmpMode) < 0) { + return HAL_FAILURE; + } + bool mode = (tmpMode == 0) ? false : true; + WifiErrorNo err = SetSuspendMode(mode); + WriteBegin(context, 0); + WriteInt(context, err); + WriteEnd(context); + return HAL_SUCCESS; +} diff --git a/services/wifi_standard/wifi_hal/wifi_hal_crpc_sta.h b/wifi/services/wifi_standard/wifi_hal/wifi_hal_crpc_sta.h similarity index 98% rename from services/wifi_standard/wifi_hal/wifi_hal_crpc_sta.h rename to wifi/services/wifi_standard/wifi_hal/wifi_hal_crpc_sta.h index 31ad2ae26452e4f4c4e2e63294403a99e0650a49..632e2bf4a69be7093c5c7dae8df88fc5ab70baa2 100644 --- a/services/wifi_standard/wifi_hal/wifi_hal_crpc_sta.h +++ b/wifi/services/wifi_standard/wifi_hal/wifi_hal_crpc_sta.h @@ -372,6 +372,13 @@ int RpcGetNetworkList(RpcServer *server, Context *context); */ int RpcGetConnectSignalInfo(RpcServer *server, Context *context); +/** + * @Description Send suspend mode to wpa + * + * @param mode - true for suspend mode, false for resume mode. + * @return int - 0 Success, -1 Failed. + */ +int RpcSetSuspendMode(RpcServer *server, Context *context); #ifdef __cplusplus } #endif diff --git a/services/wifi_standard/wifi_hal/wifi_hal_crpc_supplicant.c b/wifi/services/wifi_standard/wifi_hal/wifi_hal_crpc_supplicant.c similarity index 83% rename from services/wifi_standard/wifi_hal/wifi_hal_crpc_supplicant.c rename to wifi/services/wifi_standard/wifi_hal/wifi_hal_crpc_supplicant.c index 382d04f017bf3fbdac950d656ff850103abeb57b..baaa24b2f2e726e63097bd3ddf26125198178934 100644 --- a/services/wifi_standard/wifi_hal/wifi_hal_crpc_supplicant.c +++ b/wifi/services/wifi_standard/wifi_hal/wifi_hal_crpc_supplicant.c @@ -1,5 +1,5 @@ /* - * Copyright (C) 2021 Huawei Device Co., Ltd. + * Copyright (C) 2021-2022 Huawei Device Co., Ltd. * 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 @@ -14,120 +14,123 @@ */ #include "wifi_hal_crpc_supplicant.h" +#include "serial.h" #include "wifi_hal_sta_interface.h" #include "wifi_hal_define.h" int RpcStartSupplicant(RpcServer *server, Context *context) { if (server == NULL || context == NULL) { - return -1; + return HAL_FAILURE; } WifiErrorNo err = StartSupplicant(); WriteBegin(context, 0); WriteInt(context, err); WriteEnd(context); - return 0; + return HAL_SUCCESS; } int RpcStopSupplicant(RpcServer *server, Context *context) { if (server == NULL || context == NULL) { - return -1; + return HAL_FAILURE; } WifiErrorNo err = StopSupplicant(); WriteBegin(context, 0); WriteInt(context, err); WriteEnd(context); - return 0; + return HAL_SUCCESS; } int RpcConnectSupplicant(RpcServer *server, Context *context) { if (server == NULL || context == NULL) { - return -1; + return HAL_FAILURE; } WifiErrorNo err = ConnectSupplicant(); WriteBegin(context, 0); WriteInt(context, err); WriteEnd(context); - return 0; + return HAL_SUCCESS; } int RpcDisconnectSupplicant(RpcServer *server, Context *context) { if (server == NULL || context == NULL) { - return -1; + return HAL_FAILURE; } WifiErrorNo err = DisconnectSupplicant(); WriteBegin(context, 0); WriteInt(context, err); WriteEnd(context); - return 0; + return HAL_SUCCESS; } int RpcRequestToSupplicant(RpcServer *server, Context *context) { if (server == NULL || context == NULL) { - return -1; + return HAL_FAILURE; } int maxSize = 0; if (ReadInt(context, &maxSize) < 0 || maxSize < 0) { - return -1; + return HAL_FAILURE; } int len = maxSize + 1; unsigned char *buf = (unsigned char *)calloc(len, sizeof(unsigned char)); if (buf == NULL) { - return -1; + return HAL_FAILURE; } if (ReadUStr(context, buf, len) != 0) { free(buf); - return -1; + buf = NULL; + return HAL_FAILURE; } WifiErrorNo err = RequestToSupplicant(buf, maxSize); WriteBegin(context, 0); WriteInt(context, err); WriteEnd(context); free(buf); - return 0; + buf = NULL; + return HAL_SUCCESS; } int RpcSetPowerSave(RpcServer *server, Context *context) { if (server == NULL || context == NULL) { - return -1; + return HAL_FAILURE; } int mode = 0; if (ReadInt(context, &mode) < 0) { - return -1; + return HAL_FAILURE; } WifiErrorNo err = SetPowerSave(mode); WriteBegin(context, 0); WriteInt(context, err); WriteEnd(context); - return 0; + return HAL_SUCCESS; } int RpcWpaSetCountryCode(RpcServer *server, Context *context) { if (server == NULL || context == NULL) { - return -1; + return HAL_FAILURE; } char countryCode[WIFI_COUNTRY_CODE_MAXLEN + 1] = {0}; if (ReadStr(context, countryCode, sizeof(countryCode)) != 0) { - return -1; + return HAL_FAILURE; } WifiErrorNo err = WpaSetCountryCode(countryCode); WriteBegin(context, 0); WriteInt(context, err); WriteEnd(context); - return 0; + return HAL_SUCCESS; } int RpcWpaGetCountryCode(RpcServer *server, Context *context) { if (server == NULL || context == NULL) { - return -1; + return HAL_FAILURE; } char countryCode[WIFI_COUNTRY_CODE_MAXLEN + 1] = {0}; WifiErrorNo err = WpaGetCountryCode(countryCode, WIFI_COUNTRY_CODE_MAXLEN + 1); @@ -137,5 +140,5 @@ int RpcWpaGetCountryCode(RpcServer *server, Context *context) WriteStr(context, countryCode); } WriteEnd(context); - return 0; + return HAL_SUCCESS; } diff --git a/services/wifi_standard/wifi_hal/wifi_hal_crpc_supplicant.h b/wifi/services/wifi_standard/wifi_hal/wifi_hal_crpc_supplicant.h similarity index 100% rename from services/wifi_standard/wifi_hal/wifi_hal_crpc_supplicant.h rename to wifi/services/wifi_standard/wifi_hal/wifi_hal_crpc_supplicant.h diff --git a/services/wifi_standard/wifi_hal/wifi_hal_define.h b/wifi/services/wifi_standard/wifi_hal/wifi_hal_define.h similarity index 93% rename from services/wifi_standard/wifi_hal/wifi_hal_define.h rename to wifi/services/wifi_standard/wifi_hal/wifi_hal_define.h index bc4d779e222b4210f0d521ffa95743d6a02ea60b..1e1471b2fce54c1ef4d15427dab2146bd4053a4a 100644 --- a/services/wifi_standard/wifi_hal/wifi_hal_define.h +++ b/wifi/services/wifi_standard/wifi_hal/wifi_hal_define.h @@ -1,5 +1,5 @@ /* - * Copyright (C) 2021 Huawei Device Co., Ltd. + * Copyright (C) 2021-2022 Huawei Device Co., Ltd. * 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 @@ -36,6 +36,15 @@ extern "C" { #define WIFI_P2P_SERVER_NAME_LENGTH 256 #define WIFI_NETWORK_PSK_MAXLEN 64 +#define WPA_SUPPLICANT_NAME "wpa_supplicant" + +#define HAL_SUCCESS 0 +#define HAL_FAILURE (-1) +#define WIFI_HAL_FALSE 0 +#define WIFI_HAL_TRUE 1 + +#define WEAK_FUNC __attribute__((weak)) + typedef enum WifiErrorNo { WIFI_HAL_SUCCESS = 0, /* Success. */ WIFI_HAL_FAILED = 1, /* Failed. */ @@ -76,10 +85,13 @@ typedef enum WifiHalEvent { WIFI_STA_LEAVE_EVENT, /* STA disconnection notification in AP mode. */ WIFI_SCAN_INFO_NOTIFY_EVENT, /* Scan info notification. */ WIFI_CONNECT_CHANGED_NOTIFY_EVENT, /* Connection status change notification. */ + WIFI_BSSID_CHANGED_NOTIFY_EVENT, /* Bssid change notification. */ WIFI_AP_ENABLE_EVENT, /* AP enabling notification. */ WIFI_AP_DISABLE_EVENT, /* AP closure notification. */ WIFI_WPA_STATE_EVENT, /* WPA status change. */ WIFI_SSID_WRONG_KEY, /* Incorrect password. */ + WIFI_CONNECTION_FULL_EVENT, /* connection is full */ + WIFI_CONNECTION_REJECT_EVENT, /* connection reject */ WIFI_WPS_OVERLAP, /* wps pbc overlap */ WIFI_WPS_TIME_OUT, /* wps connect time out */ WIFI_P2P_SUP_CONNECTION_EVENT, /* Connection result of the wpa_supplicant client */ @@ -105,6 +117,7 @@ typedef enum WifiHalEvent { AP_STA_DISCONNECTED_EVENT, /* STA Disconnected from AP */ AP_STA_CONNECTED_EVENT, /* STA and AP connected event */ P2P_SERV_DISC_REQ_EVENT, /* Service discovery request event */ + P2P_IFACE_CREATED_EVENT, /* P2P interface created event */ WIFI_HAL_MAX_EVENT, } WifiHalEvent; @@ -116,6 +129,7 @@ typedef enum WifiHalEvent { #define WIFI_NETWORK_CONFIG_VALUE_LENGTH 256 #define WIFI_P2P_GROUP_CONFIG_VALUE_LENGTH 256 #define WIFI_MAC_LENGTH 17 +#define WIFI_REASON_LENGTH 32 #define WIFI_AP_PASSWORD_LENGTH 64 #define WIFI_PIN_CODE_LENGTH 8 @@ -143,6 +157,9 @@ typedef enum DeviceConfigType { DEVICE_CONFIG_WEP_KEY_1 = 12, DEVICE_CONFIG_WEP_KEY_2 = 13, DEVICE_CONFIG_WEP_KEY_3 = 14, + DEVICE_CONFIG_EAP_CLIENT_CERT = 15, + DEVICE_CONFIG_EAP_PRIVATE_KEY = 16, + DEVICE_CONFIG_EAP_PHASE2METHOD = 17, /** * Number of network configuration parameters, which is used as the last * parameter. @@ -216,4 +233,4 @@ typedef enum HalWpsMethod { #ifdef __cplusplus } #endif -#endif \ No newline at end of file +#endif diff --git a/services/wifi_standard/wifi_hal/wifi_hal_module/hostapd_hal/wifi_hostapd_hal.c b/wifi/services/wifi_standard/wifi_hal/wifi_hal_module/hostapd_hal/wifi_hostapd_hal.c similarity index 54% rename from services/wifi_standard/wifi_hal/wifi_hal_module/hostapd_hal/wifi_hostapd_hal.c rename to wifi/services/wifi_standard/wifi_hal/wifi_hal_module/hostapd_hal/wifi_hostapd_hal.c index 7bdef1c8e9fed0660c89a8251a334ab93a8eacec..f5e97ff98884473f4b3acad9bb6891599ed68285 100644 --- a/services/wifi_standard/wifi_hal/wifi_hal_module/hostapd_hal/wifi_hostapd_hal.c +++ b/wifi/services/wifi_standard/wifi_hal/wifi_hal_module/hostapd_hal/wifi_hostapd_hal.c @@ -1,5 +1,5 @@ /* - * Copyright (C) 2021 Huawei Device Co., Ltd. + * Copyright (C) 2021-2022 Huawei Device Co., Ltd. * 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 @@ -23,23 +23,45 @@ #include #include "securec.h" #include "common/wpa_ctrl.h" +#include "wifi_common_def.h" #include "wifi_hal_callback.h" #include "wifi_log.h" #undef LOG_TAG #define LOG_TAG "WifiHostapdHal" -#define CONFIG_PATH_DIR "/data/misc/wifi/wpa_supplicant" - -#define CONFIG_CTRL_IFACE_NAME "127.0.0.1:9877" /** * Blocklist configuration file name. This parameter is used by hostapd in an earlier version. */ #define CONFIG_DENY_MAC_FILE_NAME "deny_mac.conf" #define SLEEP_TIME_100_MS (100 * 1000) - -WifiHostapdHalDevice *g_hostapdHalDev = NULL; /* Global Variable */ - +#define CONFIG_PATH_DIR CONFIG_ROOR_DIR"/wpa_supplicant" +#if (AP_NUM > 1) +#define WIFI_5G_CFG "hostapd_0.conf" +#define WIFI_2G_CFG "hostapd_1.conf" +#define HOSTAPD_5G_CFG CONFIG_ROOR_DIR"/wpa_supplicant/"WIFI_5G_CFG +#define HOSTAPD_2G_CFG CONFIG_ROOR_DIR"/wpa_supplicant/"WIFI_2G_CFG +#define HOSTAPD_5G_UDPPORT "127.0.0.1:9866" +#define HOSTAPD_2G_UDPPORT "127.0.0.1:9877" + +WifiHostapdHalDeviceInfo g_hostapdHalDevInfo[] = { + {AP_5G_MAIN_INSTANCE, NULL, WIFI_5G_CFG, HOSTAPD_5G_CFG, HOSTAPD_5G_UDPPORT}, + {AP_2G_MAIN_INSTANCE, NULL, WIFI_2G_CFG, HOSTAPD_2G_CFG, HOSTAPD_2G_UDPPORT}, +}; +#else +#define WIFI_DEFAULT_CFG "hostapd.conf" +#define HOSTAPD_DEFAULT_CFG CONFIG_ROOR_DIR"/wpa_supplicant/"WIFI_DEFAULT_CFG +#define HOSTAPD_DEFAULT_UDPPORT "127.0.0.1:9877" +WifiHostapdHalDeviceInfo g_hostapdHalDevInfo[] = { + {AP_2G_MAIN_INSTANCE, NULL, WIFI_DEFAULT_CFG, HOSTAPD_DEFAULT_CFG, HOSTAPD_DEFAULT_UDPPORT} +}; +#endif + +WifiHostapdHalDeviceInfo *GetWifiCfg(int *len) +{ + *len = sizeof(g_hostapdHalDevInfo) / sizeof(WifiHostapdHalDeviceInfo); + return g_hostapdHalDevInfo; +} /* * The wpa_ctrl_pending interface provided by the WPA does not wait for the response. * As a result, the CPU usage is high. Reconstructed @@ -66,24 +88,25 @@ static int MyWpaCtrlPending(struct wpa_ctrl *ctrl) } } -static void DelCallbackMessage(const char *msg) +static void DelCallbackMessage(const char *msg, int id) { if (msg == NULL) { return; } if (strncmp(msg, AP_STA_CONNECTED, strlen(AP_STA_CONNECTED)) == 0 || strncmp(msg, AP_STA_DISCONNECTED, strlen(AP_STA_DISCONNECTED)) == 0) { - WifiHalCbStaJoin(msg); + WifiHalCbStaJoin(msg, id); } else if (strncmp(msg, AP_EVENT_ENABLED, strlen(AP_EVENT_ENABLED)) == 0 || strncmp(msg, AP_EVENT_DISABLED, strlen(AP_EVENT_DISABLED)) == 0 || strncmp(msg, WPA_EVENT_TERMINATING, strlen(WPA_EVENT_TERMINATING)) == 0) { - if (strncmp(msg, AP_EVENT_DISABLED, strlen(AP_EVENT_DISABLED)) == 0 && g_hostapdHalDev->execDisable == 1) { - g_hostapdHalDev->execDisable = 0; + if (strncmp(msg, AP_EVENT_DISABLED, strlen(AP_EVENT_DISABLED)) == 0 && + g_hostapdHalDevInfo[id].hostapdHalDev->execDisable == 1) { + g_hostapdHalDevInfo[id].hostapdHalDev->execDisable = 0; return; } - WifiHalCbApState(msg); + WifiHalCbApState(msg, id); if (strncmp(msg, WPA_EVENT_TERMINATING, strlen(WPA_EVENT_TERMINATING)) == 0) { - g_hostapdHalDev->threadRunFlag = 0; + g_hostapdHalDevInfo[id].hostapdHalDev->threadRunFlag = 0; } } } @@ -91,15 +114,23 @@ static void DelCallbackMessage(const char *msg) static void *HostapdReceiveCallback(void *arg) { if (arg == NULL) { + LOGE("%{public}s arg is null", __func__); return NULL; } - struct wpa_ctrl *ctrl = arg; + WifiHostapdHalDeviceInfo *halDeviceInfo = arg; + int id = halDeviceInfo->id; + if (halDeviceInfo->hostapdHalDev == NULL || + halDeviceInfo->hostapdHalDev->ctrlRecv == NULL) { + LOGE("%{public}s invalid HalDev or ctrlRecv", __func__); + return NULL; + } + struct wpa_ctrl *ctrl = halDeviceInfo->hostapdHalDev->ctrlRecv; char *buf = (char *)calloc(BUFSIZE_RECV, sizeof(char)); if (buf == NULL) { LOGE("In hostapd deal receive message thread, failed to calloc buff!"); return NULL; } - while (g_hostapdHalDev->threadRunFlag) { + while (g_hostapdHalDevInfo[id].hostapdHalDev->threadRunFlag) { int ret = MyWpaCtrlPending(ctrl); if (ret < 0) { LOGE("hostapd thread get event message failed!"); @@ -125,82 +156,116 @@ static void *HostapdReceiveCallback(void *arg) p = strchr(p, '>'); (p == NULL) ? (p = buf) : (p++); } - DelCallbackMessage(p); + DelCallbackMessage(p, id); } free(buf); + buf = NULL; LOGI("=====================hostapd thread exist======================="); return NULL; } -static struct wpa_ctrl *HostapdCliOpenConnection(const char *ifname) +void ReleaseHostapdCtrl(int id) { - struct wpa_ctrl *ctrl = NULL; - if (ifname == NULL) { - return NULL; + if (g_hostapdHalDevInfo[id].hostapdHalDev == NULL) { + return; } - int count = 30; - while (count) { - ctrl = wpa_ctrl_open(ifname); - if (ctrl == NULL) { - usleep(SLEEP_TIME_100_MS); - count--; - } else { - break; - } + if (g_hostapdHalDevInfo[id].hostapdHalDev->ctrlConn != NULL) { + wpa_ctrl_close(g_hostapdHalDevInfo[id].hostapdHalDev->ctrlConn); + g_hostapdHalDevInfo[id].hostapdHalDev->ctrlConn = NULL; + } + if (g_hostapdHalDevInfo[id].hostapdHalDev->ctrlRecv != NULL) { + wpa_ctrl_close(g_hostapdHalDevInfo[id].hostapdHalDev->ctrlRecv); + g_hostapdHalDevInfo[id].hostapdHalDev->ctrlRecv = NULL; } - return ctrl; + return; } -static int HostapdCliConnect(void) +int InitHostapdCtrl(const char *ifname, int id) { - int retval = 0; + if (g_hostapdHalDevInfo[id].hostapdHalDev == NULL || ifname == NULL) { + return -1; + } + int flag = 0; do { - g_hostapdHalDev->ctrlConn = HostapdCliOpenConnection(CONFIG_CTRL_IFACE_NAME); - g_hostapdHalDev->ctrlRecv = HostapdCliOpenConnection(CONFIG_CTRL_IFACE_NAME); - if (g_hostapdHalDev->ctrlConn == NULL || g_hostapdHalDev->ctrlRecv == NULL) { - LOGE("open hostapd control interface failed!"); + g_hostapdHalDevInfo[id].hostapdHalDev->ctrlRecv = wpa_ctrl_open(ifname); + if (g_hostapdHalDevInfo[id].hostapdHalDev->ctrlRecv == NULL) { + LOGE("open hostapd control interface ctrlRecv failed!"); break; } - - if (wpa_ctrl_attach(g_hostapdHalDev->ctrlRecv) != 0) { - LOGE("hostapd attach failed!"); + if (wpa_ctrl_attach(g_hostapdHalDevInfo[id].hostapdHalDev->ctrlRecv) != 0) { + LOGE("attach hostapd monitor interface failed!"); break; } - g_hostapdHalDev->threadRunFlag = 1; - if (pthread_create(&g_hostapdHalDev->tid, NULL, HostapdReceiveCallback, g_hostapdHalDev->ctrlRecv) != 0) { - wpa_ctrl_detach(g_hostapdHalDev->ctrlRecv); - LOGE("hostapd Create monitor thread failed!"); + g_hostapdHalDevInfo[id].hostapdHalDev->ctrlConn = wpa_ctrl_open(ifname); + if (g_hostapdHalDevInfo[id].hostapdHalDev->ctrlConn == NULL) { + LOGE("open hostapd control interface ctrlConn failed!"); break; } - retval += 1; + flag += 1; } while (0); + if (!flag) { + ReleaseHostapdCtrl(id); + return -1; + } + return 0; +} - if (retval == 0) { - if (g_hostapdHalDev->ctrlConn != NULL) { - wpa_ctrl_close(g_hostapdHalDev->ctrlConn); - g_hostapdHalDev->ctrlConn = NULL; - } - if (g_hostapdHalDev->ctrlRecv != NULL) { - wpa_ctrl_close(g_hostapdHalDev->ctrlRecv); - g_hostapdHalDev->ctrlRecv = NULL; +void GetDestPort(char *destPort, size_t len, int id) +{ + strcpy_s(destPort, len, g_hostapdHalDevInfo[id].udpPort); +} + +static int HostapdCliConnect(int id) +{ + if (g_hostapdHalDevInfo[id].hostapdHalDev == NULL) { + LOGE("hostapdHalDev is NULL!"); + return -1; + } + if (g_hostapdHalDevInfo[id].hostapdHalDev->ctrlConn != NULL) { + LOGE("Hostapd already initialized!"); + return 0; + } + int retryCount = 20; + char ifname[BUFFER_SIZE_64] = {0}; + GetDestPort(ifname, sizeof(ifname), id); + while (retryCount-- > 0) { + int ret = InitHostapdCtrl(ifname, id); + if (ret == 0) { + LOGI("Global hostapd interface connect successfully!"); + break; + } else { + LOGD("Init hostapd ctrl failed: %{public}d", ret); } + usleep(SLEEP_TIME_100_MS); } - return retval; + if (retryCount <= 0) { + LOGD("Retry init hostapd ctrl failed, retryCount: %{public}d", retryCount); + return -1; + } + g_hostapdHalDevInfo[id].hostapdHalDev->threadRunFlag = 1; + if (pthread_create(&g_hostapdHalDevInfo[id].hostapdHalDev->tid, NULL, + HostapdReceiveCallback, &g_hostapdHalDevInfo[id]) != 0) { + g_hostapdHalDevInfo[id].hostapdHalDev->threadRunFlag = 0; + ReleaseHostapdCtrl(id); + LOGE("Create hostapd monitor thread failed!"); + return -1; + } + return 0; } -static int HostapdCliClose(void) +static int HostapdCliClose(int id) { - if (g_hostapdHalDev == NULL) { + if (g_hostapdHalDevInfo[id].hostapdHalDev == NULL) { return 0; } - if (g_hostapdHalDev->ctrlConn != NULL) { - g_hostapdHalDev->threadRunFlag = 0; - pthread_join(g_hostapdHalDev->tid, NULL); - g_hostapdHalDev->tid = 0; - wpa_ctrl_close(g_hostapdHalDev->ctrlRecv); - g_hostapdHalDev->ctrlRecv = NULL; - wpa_ctrl_close(g_hostapdHalDev->ctrlConn); - g_hostapdHalDev->ctrlConn = NULL; + if (g_hostapdHalDevInfo[id].hostapdHalDev->ctrlConn != NULL) { + g_hostapdHalDevInfo[id].hostapdHalDev->threadRunFlag = 0; + pthread_join(g_hostapdHalDevInfo[id].hostapdHalDev->tid, NULL); + g_hostapdHalDevInfo[id].hostapdHalDev->tid = 0; + wpa_ctrl_close(g_hostapdHalDevInfo[id].hostapdHalDev->ctrlRecv); + g_hostapdHalDevInfo[id].hostapdHalDev->ctrlRecv = NULL; + wpa_ctrl_close(g_hostapdHalDevInfo[id].hostapdHalDev->ctrlConn); + g_hostapdHalDevInfo[id].hostapdHalDev->ctrlConn = NULL; } return 0; } @@ -229,13 +294,13 @@ static int WpaCtrlCommand(struct wpa_ctrl *ctrl, const char *cmd, char *buf, siz return 0; } -static int EnableAp(void) +static int EnableAp(int id) { char buf[BUFSIZE_REQUEST_SMALL] = {0}; - return WpaCtrlCommand(g_hostapdHalDev->ctrlConn, "ENABLE", buf, sizeof(buf)); + return WpaCtrlCommand(g_hostapdHalDevInfo[id].hostapdHalDev->ctrlConn, "ENABLE", buf, sizeof(buf)); } -static int SetApName(const char *name) +static int SetApName(const char *name, int id) { if (name == NULL) { return -1; @@ -246,10 +311,10 @@ static int SetApName(const char *name) if (sprintf_s(cmd, sizeof(cmd), "SET ssid %s", name) < 0) { return -1; } - return WpaCtrlCommand(g_hostapdHalDev->ctrlConn, cmd, buf, sizeof(buf)); + return WpaCtrlCommand(g_hostapdHalDevInfo[id].hostapdHalDev->ctrlConn, cmd, buf, sizeof(buf)); } -static int SetApRsnPairwise(const char *type) +static int SetApRsnPairwise(const char *type, int id) { if (type == NULL) { return -1; @@ -261,10 +326,10 @@ static int SetApRsnPairwise(const char *type) if (sprintf_s(cmd, sizeof(cmd), "SET rsn_pairwise %s", type) < 0) { return -1; } - return WpaCtrlCommand(g_hostapdHalDev->ctrlConn, cmd, buf, sizeof(buf)); + return WpaCtrlCommand(g_hostapdHalDevInfo[id].hostapdHalDev->ctrlConn, cmd, buf, sizeof(buf)); } -static int SetApWpaPairwise(const char *type) +static int SetApWpaPairwise(const char *type, int id) { if (type == NULL) { return -1; @@ -275,10 +340,10 @@ static int SetApWpaPairwise(const char *type) if (sprintf_s(cmd, sizeof(cmd), "SET wpa_pairwise %s", type) < 0) { return -1; } - return WpaCtrlCommand(g_hostapdHalDev->ctrlConn, cmd, buf, sizeof(buf)); + return WpaCtrlCommand(g_hostapdHalDevInfo[id].hostapdHalDev->ctrlConn, cmd, buf, sizeof(buf)); } -static int SetApWpaKeyMgmt(const char *type) +static int SetApWpaKeyMgmt(const char *type, int id) { if (type == NULL) { return -1; @@ -289,10 +354,10 @@ static int SetApWpaKeyMgmt(const char *type) if (sprintf_s(cmd, sizeof(cmd), "SET wpa_key_mgmt %s", type) < 0) { return -1; } - return WpaCtrlCommand(g_hostapdHalDev->ctrlConn, cmd, buf, sizeof(buf)); + return WpaCtrlCommand(g_hostapdHalDevInfo[id].hostapdHalDev->ctrlConn, cmd, buf, sizeof(buf)); } -static int SetApWpaValue(int securityType) +static int SetApWpaValue(int securityType, int id) { int retval = -1; char cmd[BUFSIZE_CMD] = {0}; @@ -316,25 +381,25 @@ static int SetApWpaValue(int securityType) return -1; } - retval = WpaCtrlCommand(g_hostapdHalDev->ctrlConn, cmd, buf, sizeof(buf)); + retval = WpaCtrlCommand(g_hostapdHalDevInfo[id].hostapdHalDev->ctrlConn, cmd, buf, sizeof(buf)); if (retval == 0 && securityType != NONE) { /* * If the value of wpa is switched between 0, 1, and 2, the wpa_key_mgmt, * wpa_pairwise, and rsn_pairwise attributes must be set. Otherwise, the * enable or STA cannot be connected. */ - retval = SetApWpaKeyMgmt("WPA-PSK"); + retval = SetApWpaKeyMgmt("WPA-PSK", id); } if (retval == 0 && securityType == WPA_PSK) { - retval = SetApWpaPairwise("CCMP"); + retval = SetApWpaPairwise("CCMP", id); } if (retval == 0 && securityType == WPA2_PSK) { - retval = SetApRsnPairwise("CCMP"); + retval = SetApRsnPairwise("CCMP", id); } return retval; } -static int SetApPasswd(const char *pass) +static int SetApPasswd(const char *pass, int id) { if (pass == NULL) { return -1; @@ -345,10 +410,10 @@ static int SetApPasswd(const char *pass) if (sprintf_s(cmd, sizeof(cmd), "SET wpa_passphrase %s", pass) < 0) { return -1; } - return WpaCtrlCommand(g_hostapdHalDev->ctrlConn, cmd, buf, sizeof(buf)); + return WpaCtrlCommand(g_hostapdHalDevInfo[id].hostapdHalDev->ctrlConn, cmd, buf, sizeof(buf)); } -static int SetApChannel(int channel) +static int SetApChannel(int channel, int id) { char cmd[BUFSIZE_CMD] = {0}; char buf[BUFSIZE_REQUEST_SMALL] = {0}; @@ -356,10 +421,10 @@ static int SetApChannel(int channel) if (sprintf_s(cmd, sizeof(cmd), "SET channel %d", channel) < 0) { return -1; } - return WpaCtrlCommand(g_hostapdHalDev->ctrlConn, cmd, buf, sizeof(buf)); + return WpaCtrlCommand(g_hostapdHalDevInfo[id].hostapdHalDev->ctrlConn, cmd, buf, sizeof(buf)); } -static int SetApBand(int band) +static int SetApBand(int band, int id) { char cmd[BUFSIZE_CMD] = {0}; char buf[BUFSIZE_REQUEST_SMALL] = {0}; @@ -383,10 +448,10 @@ static int SetApBand(int band) if (sprintf_s(cmd, sizeof(cmd), "SET hw_mode %s", hwMode) < 0) { return -1; } - return WpaCtrlCommand(g_hostapdHalDev->ctrlConn, cmd, buf, sizeof(buf)); + return WpaCtrlCommand(g_hostapdHalDevInfo[id].hostapdHalDev->ctrlConn, cmd, buf, sizeof(buf)); } -static int SetApMaxConn(int maxConn) +static int SetApMaxConn(int maxConn, int id) { char cmd[BUFSIZE_CMD] = {0}; char buf[BUFSIZE_REQUEST_SMALL] = {0}; @@ -394,10 +459,10 @@ static int SetApMaxConn(int maxConn) if (sprintf_s(cmd, sizeof(cmd), "SET max_num_sta %d", maxConn) < 0) { return -1; } - return WpaCtrlCommand(g_hostapdHalDev->ctrlConn, cmd, buf, sizeof(buf)); + return WpaCtrlCommand(g_hostapdHalDevInfo[id].hostapdHalDev->ctrlConn, cmd, buf, sizeof(buf)); } -static int SetApInfo(HostapdConfig *info) +static int SetApInfo(HostapdConfig *info, int id) { if (info == NULL) { return -1; @@ -409,42 +474,42 @@ static int SetApInfo(HostapdConfig *info) LOGE("password is invalid!"); return retval; } - if ((retval = SetApPasswd((char *)info->preSharedKey)) != 0) { + if ((retval = SetApPasswd((char *)info->preSharedKey, id)) != 0) { LOGE("SetApPasswd failed. retval %{public}d", retval); return retval; } } - if ((retval = SetApName((char *)info->ssid)) != 0) { + if ((retval = SetApName((char *)info->ssid, id)) != 0) { LOGE("SetApName failed. retval %{public}d", retval); return retval; } - if ((retval = SetApWpaValue(info->securityType)) != 0) { + if ((retval = SetApWpaValue(info->securityType, id)) != 0) { LOGE("SetApWpaValue failed. retval %{public}d", retval); return retval; } - if ((retval = SetApBand(info->band)) != 0) { + if ((retval = SetApBand(info->band, id)) != 0) { LOGE("SetApBand failed. retval %{public}d", retval); return retval; } - if ((retval = SetApChannel(info->channel)) != 0) { + if ((retval = SetApChannel(info->channel, id)) != 0) { LOGE("SetApChannel failed. retval %{public}d", retval); return retval; } - if (info->maxConn >= 0 && (retval = SetApMaxConn(info->maxConn)) != 0) { + if (info->maxConn >= 0 && (retval = SetApMaxConn(info->maxConn, id)) != 0) { LOGE("SetApMaxConn failed. retval %{public}d", retval); return retval; } return 0; } -static int DisableAp(void) +static int DisableAp(int id) { char buf[BUFSIZE_REQUEST_SMALL] = {0}; - g_hostapdHalDev->execDisable = 1; - return WpaCtrlCommand(g_hostapdHalDev->ctrlConn, "DISABLE", buf, sizeof(buf)); + g_hostapdHalDevInfo[id].hostapdHalDev->execDisable = 1; + return WpaCtrlCommand(g_hostapdHalDevInfo[id].hostapdHalDev->ctrlConn, "DISABLE", buf, sizeof(buf)); } -static int ModBlockList(const char *mac) +static int ModBlockList(const char *mac, int id) { if (mac == NULL) { return -1; @@ -467,10 +532,10 @@ static int ModBlockList(const char *mac) if (sprintf_s(cmd, sizeof(cmd), "SET deny_mac_file %s/%s", CONFIG_PATH_DIR, CONFIG_DENY_MAC_FILE_NAME) < 0) { return -1; } - return WpaCtrlCommand(g_hostapdHalDev->ctrlConn, cmd, buf, sizeof(buf)); + return WpaCtrlCommand(g_hostapdHalDevInfo[id].hostapdHalDev->ctrlConn, cmd, buf, sizeof(buf)); } -static int AddBlocklist(const char *mac) +static int AddBlocklist(const char *mac, int id) { if (mac == NULL) { return -1; @@ -481,7 +546,7 @@ static int AddBlocklist(const char *mac) if (snprintf_s(cmd, sizeof(cmd), sizeof(cmd) - 1, "DENY_ACL ADD_MAC %s", mac) < 0) { return -1; } - if (WpaCtrlCommand(g_hostapdHalDev->ctrlConn, cmd, buf, sizeof(buf)) != 0) { + if (WpaCtrlCommand(g_hostapdHalDevInfo[id].hostapdHalDev->ctrlConn, cmd, buf, sizeof(buf)) != 0) { LOGE("AddBlocklist Failed"); return -1; } @@ -490,12 +555,12 @@ static int AddBlocklist(const char *mac) /** * The hostapd of an earlier version does not support the DENY_ACL command and uses the configuration file. */ - return ModBlockList(mac); + return ModBlockList(mac, id); } return 0; } -static int DelBlocklist(const char *mac) +static int DelBlocklist(const char *mac, int id) { if (mac == NULL) { return -1; @@ -506,7 +571,7 @@ static int DelBlocklist(const char *mac) if (sprintf_s(cmd, sizeof(cmd), "DENY_ACL DEL_MAC %s", mac) < 0) { return -1; } - if (WpaCtrlCommand(g_hostapdHalDev->ctrlConn, cmd, buf, sizeof(buf)) != 0) { + if (WpaCtrlCommand(g_hostapdHalDevInfo[id].hostapdHalDev->ctrlConn, cmd, buf, sizeof(buf)) != 0) { LOGE("DelBlocklist Failed"); return -1; } @@ -515,12 +580,12 @@ static int DelBlocklist(const char *mac) if (sprintf_s(cmd, sizeof(cmd), "-%s", mac) < 0) { return -1; } - return ModBlockList(cmd); + return ModBlockList(cmd, id); } return 0; } -static int GetApStatus(StatusInfo *info) +static int GetApStatus(StatusInfo *info, int id) { if (info == NULL) { return -1; @@ -530,9 +595,10 @@ static int GetApStatus(StatusInfo *info) return -1; } - if (WpaCtrlCommand(g_hostapdHalDev->ctrlConn, "STATUS", buf, BUFSIZE_RECV) != 0) { + if (WpaCtrlCommand(g_hostapdHalDevInfo[id].hostapdHalDev->ctrlConn, "STATUS", buf, BUFSIZE_RECV) != 0) { LOGE("Status WpaCtrlCommand failed"); free(buf); + buf = NULL; return -1; } @@ -540,6 +606,7 @@ static int GetApStatus(StatusInfo *info) if (p == NULL) { LOGD("Status not find state result!"); free(buf); + buf = NULL; return 0; } p += strlen("state="); // skip state= @@ -550,10 +617,11 @@ static int GetApStatus(StatusInfo *info) } info->state[pos] = 0; free(buf); + buf = NULL; return 0; } -static int ShowConnectedDevList(char *buf, int size) +static int ShowConnectedDevList(char *buf, int size, int id) { if (buf == NULL) { return -1; @@ -563,9 +631,11 @@ static int ShowConnectedDevList(char *buf, int size) if (reqBuf == NULL) { return -1; } - if (WpaCtrlCommand(g_hostapdHalDev->ctrlConn, "STA-FIRST", reqBuf, BUFSIZE_REQUEST) != 0) { + if (WpaCtrlCommand(g_hostapdHalDevInfo[id].hostapdHalDev->ctrlConn, "STA-FIRST", + reqBuf, BUFSIZE_REQUEST) != 0) { LOGE("HostapdCliCmdListSta Failed"); free(reqBuf); + reqBuf = NULL; return -1; } do { @@ -579,6 +649,7 @@ static int ShowConnectedDevList(char *buf, int size) int staLen = strlen(reqBuf); if (bufLen + staLen + 1 >= size) { free(reqBuf); + reqBuf = NULL; return 0; } buf[bufLen++] = ','; @@ -590,18 +661,19 @@ static int ShowConnectedDevList(char *buf, int size) if (snprintf_s(cmd, sizeof(cmd), sizeof(cmd) - 1, "STA-NEXT %s", reqBuf) < 0) { break; } - } while (WpaCtrlCommand(g_hostapdHalDev->ctrlConn, cmd, reqBuf, BUFSIZE_REQUEST) == 0); + } while (WpaCtrlCommand(g_hostapdHalDevInfo[id].hostapdHalDev->ctrlConn, cmd, reqBuf, BUFSIZE_REQUEST) == 0); free(reqBuf); + reqBuf = NULL; return 0; } -static int ReloadApConfigInfo(void) +static int ReloadApConfigInfo(int id) { char buf[BUFSIZE_REQUEST_SMALL] = {0}; - return WpaCtrlCommand(g_hostapdHalDev->ctrlConn, "RELOAD", buf, sizeof(buf)); + return WpaCtrlCommand(g_hostapdHalDevInfo[id].hostapdHalDev->ctrlConn, "RELOAD", buf, sizeof(buf)); } -static int DisConnectedDev(const char *mac) +static int DisConnectedDev(const char *mac, int id) { if (mac == NULL) { return -1; @@ -612,10 +684,10 @@ static int DisConnectedDev(const char *mac) if (sprintf_s(cmd, sizeof(cmd), "DISASSOCIATE %s", mac) < 0) { return -1; } - return WpaCtrlCommand(g_hostapdHalDev->ctrlConn, cmd, buf, sizeof(buf)); + return WpaCtrlCommand(g_hostapdHalDevInfo[id].hostapdHalDev->ctrlConn, cmd, buf, sizeof(buf)); } -static int SetCountryCode(const char *code) +static int SetCountryCode(const char *code, int id) { if (code == NULL) { return -1; @@ -626,55 +698,64 @@ static int SetCountryCode(const char *code) if (sprintf_s(cmd, sizeof(cmd), "SET country_code %s", code) < 0) { return -1; } - return WpaCtrlCommand(g_hostapdHalDev->ctrlConn, cmd, buf, sizeof(buf)); + return WpaCtrlCommand(g_hostapdHalDevInfo[id].hostapdHalDev->ctrlConn, cmd, buf, sizeof(buf)); } -static int InitHostapdHal(void) +static int InitHostapdHal(int id) { - if (g_hostapdHalDev == NULL) { + if (g_hostapdHalDevInfo[id].hostapdHalDev == NULL) { return -1; } - g_hostapdHalDev->threadRunFlag = 1; - if (HostapdCliConnect() == 0) { + g_hostapdHalDevInfo[id].hostapdHalDev->threadRunFlag = 1; + if (HostapdCliConnect(id) != 0) { return -1; } return 0; } -WifiHostapdHalDevice *GetWifiHostapdDev(void) +WifiHostapdHalDevice *GetWifiHostapdDev(int id) { - if (g_hostapdHalDev != NULL) { - return g_hostapdHalDev; + if (id < 0 || id >= AP_MAX_INSTANCE) { + LOGE("Invalid id: %{public}d!", id); + return NULL; } - g_hostapdHalDev = (WifiHostapdHalDevice *)calloc(1, sizeof(WifiHostapdHalDevice)); - if (g_hostapdHalDev == NULL) { - LOGE("NULL device on open"); + + if (g_hostapdHalDevInfo[id].hostapdHalDev != NULL) { + return g_hostapdHalDevInfo[id].hostapdHalDev; + } + + g_hostapdHalDevInfo[id].hostapdHalDev = (WifiHostapdHalDevice *)calloc(1, sizeof(WifiHostapdHalDevice)); + if (g_hostapdHalDevInfo[id].hostapdHalDev == NULL) { + LOGE("hostapdHalDev is NULL"); return NULL; } + /* ************ Register hostapd_cli Interface ************************* */ - g_hostapdHalDev->enableAp = EnableAp; - g_hostapdHalDev->disableAp = DisableAp; - g_hostapdHalDev->setApInfo = SetApInfo; - g_hostapdHalDev->addBlocklist = AddBlocklist; - g_hostapdHalDev->delBlocklist = DelBlocklist; - g_hostapdHalDev->status = GetApStatus; - g_hostapdHalDev->showConnectedDevList = ShowConnectedDevList; - g_hostapdHalDev->reloadApConfigInfo = ReloadApConfigInfo; - g_hostapdHalDev->disConnectedDev = DisConnectedDev; - g_hostapdHalDev->setCountryCode = SetCountryCode; - if (InitHostapdHal() != 0) { - free(g_hostapdHalDev); - g_hostapdHalDev = NULL; + g_hostapdHalDevInfo[id].hostapdHalDev->enableAp = EnableAp; + g_hostapdHalDevInfo[id].hostapdHalDev->disableAp = DisableAp; + g_hostapdHalDevInfo[id].hostapdHalDev->setApInfo = SetApInfo; + g_hostapdHalDevInfo[id].hostapdHalDev->addBlocklist = AddBlocklist; + g_hostapdHalDevInfo[id].hostapdHalDev->delBlocklist = DelBlocklist; + g_hostapdHalDevInfo[id].hostapdHalDev->status = GetApStatus; + g_hostapdHalDevInfo[id].hostapdHalDev->showConnectedDevList = ShowConnectedDevList; + g_hostapdHalDevInfo[id].hostapdHalDev->reloadApConfigInfo = ReloadApConfigInfo; + g_hostapdHalDevInfo[id].hostapdHalDev->disConnectedDev = DisConnectedDev; + g_hostapdHalDevInfo[id].hostapdHalDev->setCountryCode = SetCountryCode; + + if (InitHostapdHal(id) != 0) { + LOGE("InitHostapdHal return failed!!"); + free(g_hostapdHalDevInfo[id].hostapdHalDev); + g_hostapdHalDevInfo[id].hostapdHalDev = NULL; return NULL; } - return g_hostapdHalDev; + return g_hostapdHalDevInfo[id].hostapdHalDev; } -void ReleaseHostapdDev(void) +void ReleaseHostapdDev(int id) { - if (g_hostapdHalDev != NULL) { - HostapdCliClose(); - free(g_hostapdHalDev); - g_hostapdHalDev = NULL; + if (g_hostapdHalDevInfo[id].hostapdHalDev != NULL) { + HostapdCliClose(id); + free(g_hostapdHalDevInfo[id].hostapdHalDev); + g_hostapdHalDevInfo[id].hostapdHalDev = NULL; } -} \ No newline at end of file +} diff --git a/services/wifi_standard/wifi_hal/wifi_hal_module/hostapd_hal/wifi_hostapd_hal.h b/wifi/services/wifi_standard/wifi_hal/wifi_hal_module/hostapd_hal/wifi_hostapd_hal.h similarity index 62% rename from services/wifi_standard/wifi_hal/wifi_hal_module/hostapd_hal/wifi_hostapd_hal.h rename to wifi/services/wifi_standard/wifi_hal/wifi_hal_module/hostapd_hal/wifi_hostapd_hal.h index 408ce0ee31f3fe25af9fa0b425af1b7976d711ad..f92c44c08a77b4209bfef5713ced0d07a6d0e4b8 100644 --- a/services/wifi_standard/wifi_hal/wifi_hal_module/hostapd_hal/wifi_hostapd_hal.h +++ b/wifi/services/wifi_standard/wifi_hal/wifi_hal_module/hostapd_hal/wifi_hostapd_hal.h @@ -39,6 +39,19 @@ extern "C" { #define BUFFER_SIZE_32 32 #define BUFFER_SIZE_16 16 +#if (AP_NUM > 1) +typedef enum EnApInstance { + AP_5G_MAIN_INSTANCE, + AP_2G_MAIN_INSTANCE, + AP_MAX_INSTANCE +} ApInstance; +#else +typedef enum EnApInstance { + AP_2G_MAIN_INSTANCE, + AP_MAX_INSTANCE +} ApInstance; +#endif + typedef struct StStatusInfo { char state[BUFFER_SIZE_16]; char phy[BUFFER_SIZE_16]; @@ -57,30 +70,45 @@ typedef struct StWifiHostapdHalDevice { pthread_t tid; int threadRunFlag; int execDisable; - int (*setApInfo)(HostapdConfig *info); - int (*enableAp)(void); - int (*disableAp)(void); - int (*addBlocklist)(const char *mac); - int (*delBlocklist)(const char *mac); - int (*status)(StatusInfo *info); - int (*showConnectedDevList)(char *info, int size); - int (*reloadApConfigInfo)(void); - int (*disConnectedDev)(const char *mac); - int (*setCountryCode)(const char *code); + int (*setApInfo)(HostapdConfig *info, int id); + int (*enableAp)(int id); + int (*disableAp)(int id); + int (*addBlocklist)(const char *mac, int id); + int (*delBlocklist)(const char *mac, int id); + int (*status)(StatusInfo *info, int id); + int (*showConnectedDevList)(char *info, int size, int id); + int (*reloadApConfigInfo)(int id); + int (*disConnectedDev)(const char *mac, int id); + int (*setCountryCode)(const char *code, int id); } WifiHostapdHalDevice; +typedef struct StWifiHostapdHalDeviceInfo { + int id; + WifiHostapdHalDevice *hostapdHalDev; + char *cfgName; + char *config; + char *udpPort; +} WifiHostapdHalDeviceInfo; + +WifiHostapdHalDeviceInfo *GetWifiCfg(int *len); /** * @Description Get the Wifi Hostapd Dev object. * * @return WifiHostapdHalDevice* */ -WifiHostapdHalDevice *GetWifiHostapdDev(void); +WifiHostapdHalDevice *GetWifiHostapdDev(int id); /** * @Description Release the Wifi Hostapd Dev object. * */ -void ReleaseHostapdDev(void); +void ReleaseHostapdDev(int id); + +/** + * @Description Hostpad string concatenation. + * + */ +void GetDestPort(char *destPort, size_t len, int id); #ifdef __cplusplus } diff --git a/services/wifi_standard/wifi_hal/wifi_hal_module/wpa_supplicant_hal/wifi_wpa_common.c b/wifi/services/wifi_standard/wifi_hal/wifi_hal_module/wpa_supplicant_hal/wifi_wpa_common.c similarity index 88% rename from services/wifi_standard/wifi_hal/wifi_hal_module/wpa_supplicant_hal/wifi_wpa_common.c rename to wifi/services/wifi_standard/wifi_hal/wifi_hal_module/wpa_supplicant_hal/wifi_wpa_common.c index d8f84cf4ee5a356df63cb471a0b9fe46c6c24c65..33c81d630cb160f3e51c798f0d6243c50cd54721 100644 --- a/services/wifi_standard/wifi_hal/wifi_hal_module/wpa_supplicant_hal/wifi_wpa_common.c +++ b/wifi/services/wifi_standard/wifi_hal/wifi_hal_module/wpa_supplicant_hal/wifi_wpa_common.c @@ -110,16 +110,20 @@ int InitWpaCtrl(WpaCtrl *pCtrl, const char *ifname) } int flag = 0; do { - pCtrl->pSend = wpa_ctrl_open(ifname); - pCtrl->pRecv = wpa_ctrl_open(ifname); - if (pCtrl->pSend == NULL || pCtrl->pRecv == NULL) { - LOGE("open wpa control interface failed!"); + pCtrl->pRecv = wpa_ctrl_open("global"); + if (pCtrl->pRecv == NULL) { + LOGE("open wpa control recv interface failed!"); break; } if (wpa_ctrl_attach(pCtrl->pRecv) != 0) { LOGE("attach monitor interface failed!"); break; } + pCtrl->pSend = wpa_ctrl_open("global"); + if (pCtrl->pSend == NULL) { + LOGE("open wpa control send interface failed!"); + break; + } flag += 1; } while (0); if (!flag) { @@ -139,6 +143,7 @@ int WpaCliCmd(const char *cmd, char *buf, size_t bufLen) return -1; } size_t len = bufLen - 1; + LOGI("wpa_ctrl_request -> cmd: %{private}s", cmd); int ret = wpa_ctrl_request(ctrl->pSend, cmd, strlen(cmd), buf, &len, NULL); if (ret == WPA_CMD_RETURN_TIMEOUT) { LOGE("[%{private}s] command timed out.", cmd); @@ -148,9 +153,10 @@ int WpaCliCmd(const char *cmd, char *buf, size_t bufLen) return -1; } buf[len] = '\0'; + LOGI("wpa_ctrl_request -> buf: %{private}s", buf); if (strncmp(buf, "FAIL\n", strlen("FAIL\n")) == 0 || strncmp(buf, "UNKNOWN COMMAND\n", strlen("UNKNOWN COMMAND\n")) == 0) { - LOGE("%{private}s request sucess, but response %{public}s", cmd, buf); + LOGE("%{private}s request success, but response %{public}s", cmd, buf); return -1; } return 0; diff --git a/services/wifi_standard/wifi_hal/wifi_hal_module/wpa_supplicant_hal/wifi_wpa_common.h b/wifi/services/wifi_standard/wifi_hal/wifi_hal_module/wpa_supplicant_hal/wifi_wpa_common.h similarity index 100% rename from services/wifi_standard/wifi_hal/wifi_hal_module/wpa_supplicant_hal/wifi_wpa_common.h rename to wifi/services/wifi_standard/wifi_hal/wifi_hal_module/wpa_supplicant_hal/wifi_wpa_common.h diff --git a/services/wifi_standard/wifi_hal/wifi_hal_module/wpa_supplicant_hal/wifi_wpa_hal.c b/wifi/services/wifi_standard/wifi_hal/wifi_hal_module/wpa_supplicant_hal/wifi_wpa_hal.c similarity index 84% rename from services/wifi_standard/wifi_hal/wifi_hal_module/wpa_supplicant_hal/wifi_wpa_hal.c rename to wifi/services/wifi_standard/wifi_hal/wifi_hal_module/wpa_supplicant_hal/wifi_wpa_hal.c index bbe5158f8dc204fccdee7ec7c27ea8fc8b254ef6..cde0054a1cbe1d7d62d0d09d1778a3ab53dcf57e 100644 --- a/services/wifi_standard/wifi_hal/wifi_hal_module/wpa_supplicant_hal/wifi_wpa_hal.c +++ b/wifi/services/wifi_standard/wifi_hal/wifi_hal_module/wpa_supplicant_hal/wifi_wpa_hal.c @@ -1,5 +1,5 @@ /* - * Copyright (C) 2021 Huawei Device Co., Ltd. + * Copyright (C) 2021-2022 Huawei Device Co., Ltd. * 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 @@ -12,19 +12,21 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + #include "wifi_wpa_hal.h" -#include #include +#include #include "securec.h" -#include "wifi_wpa_common.h" #include "utils/common.h" /* request for printf_decode to decode wpa's returned ssid info */ -#include "wifi_hal_common_func.h" +#include "wifi_common_def.h" #include "wifi_hal_callback.h" -#include "wifi_hal_struct.h" +#include "wifi_hal_common_func.h" #include "wifi_hal_p2p_struct.h" +#include "wifi_hal_struct.h" +#include "wifi_log.h" #include "wifi_p2p_hal.h" +#include "wifi_wpa_common.h" -#include "wifi_log.h" #undef LOG_TAG #define LOG_TAG "WifiWpaHal" @@ -45,7 +47,10 @@ #define WPA_CB_CONNECTED 1 #define WPA_CB_DISCONNECTED 2 #define WPS_EVENT_PBC_OVERLAP "WPS-OVERLAP-DETECTED PBC session overlap" +#define WPA_EVENT_BSSID_CHANGED "WPA-EVENT-BSSID-CHANGED " #define REPLY_BUF_LENGTH 4096 +#define CONNECTION_FULL_STATUS 17 +#define CONNECTION_REJECT_STATUS 37 static WifiWpaInterface *g_wpaInterface = NULL; @@ -54,7 +59,7 @@ static void DealP2pFindInfo(char *buf) if (buf == NULL || strlen(buf) < WIFI_MAC_LENGTH) { return; } - HidlP2pDeviceInfo info = {0}; + P2pDeviceInfo info = {0}; if (strncpy_s(info.srcAddress, sizeof(info.srcAddress), buf, WIFI_MAC_LENGTH) != EOK) { return; } @@ -76,7 +81,7 @@ static void DealP2pFindInfo(char *buf) info.groupCapabilities = Hex2Dec(retMsg.value); } else if (strncmp(retMsg.key, "wfd_dev_info", strlen("wfd_dev_info")) == 0) { if (strlen(retMsg.value) != strlen("0x000000000000")) { - LOGD("Unexpect wfd device info, it's return 6 uint8 array convert to hex string!"); + LOGD("Unexpected wfd device info, it's return 6 uint8 array convert to hex string!"); } else { StrSafeCopy(info.wfdDeviceInfo, sizeof(info.wfdDeviceInfo), retMsg.value); info.wfdLength = strlen(info.wfdDeviceInfo); @@ -121,7 +126,7 @@ static void DealGroupStartInfo(char *buf) if (buf == NULL) { return; } - HidlP2pGroupInfo conf = {0}; + P2pGroupInfo conf = {0}; if (memset_s(&conf, sizeof(conf), 0, sizeof(conf)) != EOK) { return; } @@ -171,7 +176,7 @@ static void DealServiceDiscRespEvent(char *buf) if (buf == NULL) { return; } - HidlP2pServDiscRespInfo info = {0}; + P2pServDiscRespInfo info = {0}; if (memset_s(&info, sizeof(info), 0, sizeof(info)) != EOK) { return; } @@ -182,23 +187,21 @@ static void DealServiceDiscRespEvent(char *buf) if (index == P2P_SERVICE_INFO_FIRST_SECTION) { if (strncpy_s(info.srcAddress, sizeof(info.srcAddress), token, strlen(token)) != EOK) { free(info.tlvs); + info.tlvs = NULL; return; } } else if (index == P2P_SERVICE_INFO_SECOND_SECTION) { info.updateIndicator = atoi(token); } else if (index == P2P_SERVICE_INFO_THIRD_SECTION) { unsigned len = strlen(token) + 1; - if (len == 0) { - free(info.tlvs); - return; - } - if (info.tlvs != NULL) { + if (info.tlvs != NULL || len > WPA_CMD_BUF_LEN) { free(info.tlvs); info.tlvs = NULL; } info.tlvs = (char *)calloc(len, sizeof(char)); if (info.tlvs == NULL || strncpy_s(info.tlvs, len, token, len - 1) != EOK) { free(info.tlvs); + info.tlvs = NULL; return; } } @@ -207,6 +210,7 @@ static void DealServiceDiscRespEvent(char *buf) } P2pHalCbServiceDiscoveryResponse(&info); free(info.tlvs); + info.tlvs = NULL; return; } @@ -273,7 +277,7 @@ static void DealInvitationReceived(char *buf, int type) if (buf == NULL) { return; } - HidlP2pInvitationInfo info = {0}; + P2pInvitationInfo info = {0}; if (memset_s(&info, sizeof(info), 0, sizeof(info)) != EOK) { return; } @@ -418,7 +422,7 @@ static void DealP2pServDiscReqEvent(char *buf) if (buf == NULL) { return; } - HidlP2pServDiscReqInfo info; + P2pServDiscReqInfo info; if (memset_s(&info, sizeof(info), 0, sizeof(info)) != EOK) { return; } @@ -431,6 +435,7 @@ static void DealP2pServDiscReqEvent(char *buf) } else if (index == P2P_SERVICE_DISC_REQ_TWO) { if (strncpy_s(info.mac, sizeof(info.mac), token, strlen(token)) != EOK) { free(info.tlvs); + info.tlvs = NULL; return; } } else if (index == P2P_SERVICE_DISC_REQ_THREE) { @@ -439,17 +444,14 @@ static void DealP2pServDiscReqEvent(char *buf) info.updateIndic = atoi(token); } else if (index == P2P_SERVICE_DISC_REQ_FIVE) { unsigned len = strlen(token) + 1; - if (len == 0) { - free(info.tlvs); - return; - } - if (info.tlvs != NULL) { + if (info.tlvs != NULL || len > WPA_CMD_BUF_LEN) { free(info.tlvs); info.tlvs = NULL; } info.tlvs = (char *)calloc(len, sizeof(char)); if (info.tlvs == NULL || strncpy_s(info.tlvs, len, token, len - 1) != EOK) { free(info.tlvs); + info.tlvs = NULL; return; } } @@ -458,9 +460,34 @@ static void DealP2pServDiscReqEvent(char *buf) } P2pHalCbServDiscReq(&info); free(info.tlvs); + info.tlvs = NULL; return; } +static void DealP2pInterfaceCreated(const char *buf) +{ + int type; + char ifName[WIFI_IFACE_NAME_MAXLEN] = {0}; + if (strncmp(buf, "GO ", strlen("GO ")) == 0) { + type = 1; + } else if (strncmp(buf, "GC ", strlen("GC ")) == 0) { + type = 0; + } else { + LOGE("p2p interface created invalid msg %{public}s", buf); + return; + } + + const char *pos = buf + strlen("GO "); // GO and GC have same length + if (strlen(pos) >= WIFI_IFACE_NAME_MAXLEN || strlen(pos) == 0) { + LOGE("p2p interface created invalid ifname len %{public}zu", strlen(pos)); + return; + } + if (strncpy_s(ifName, sizeof(ifName), pos, strlen(pos)) != EOK) { + return; + } + P2pHalCbP2pIfaceCreated(ifName, type); +} + static int DealWpaP2pCallBackSubFun(char *p) { if (p == NULL) { @@ -490,6 +517,8 @@ static int DealWpaP2pCallBackSubFun(char *p) DealGroupStartInfo(p); } else if (strncmp(p, P2P_EVENT_GROUP_REMOVED, strlen(P2P_EVENT_GROUP_REMOVED)) == 0) { DealP2pGroupRemove(p + strlen(P2P_EVENT_GROUP_REMOVED)); + } else if (strncmp(p, P2P_INTERFACE_CREATED, strlen(P2P_INTERFACE_CREATED)) == 0) { + DealP2pInterfaceCreated(p + strlen(P2P_INTERFACE_CREATED)); } else { return 1; } @@ -550,6 +579,17 @@ static void WpaCallBackFuncTwo(const char *p) WifiHalCbNotifyWpsOverlap(1); } else if (strncmp(p, WPS_EVENT_TIMEOUT, strlen(WPS_EVENT_TIMEOUT)) == 0) { WifiHalCbNotifyWpsTimeOut(1); + } else if (strncmp(p, WPA_EVENT_AUTH_REJECT, strlen(WPA_EVENT_AUTH_REJECT)) == 0) { + char *connectionStatus = strstr(p, "status_code="); + if (connectionStatus != NULL) { + connectionStatus += strlen("status_code="); + int status = atoi(connectionStatus); + if (status == CONNECTION_FULL_STATUS) { + WifiHalCbNotifyConnectionFull(status); + } else if (status == CONNECTION_REJECT_STATUS) { + WifiHalCbNotifyConnectionReject(status); + } + } } return; } @@ -584,6 +624,22 @@ static void WpaCallBackFunc(const char *p) } pBssid += strlen("bssid="); WifiHalCbNotifyConnectChanged(WPA_CB_DISCONNECTED, -1, pBssid); + /* bssid changed event */ + } else if (strncmp(p, WPA_EVENT_BSSID_CHANGED, strlen(WPA_EVENT_BSSID_CHANGED)) == 0) { + LOGI("Reveive WPA_EVENT_BSSID_CHANGED notify event"); + char *pBssid = strstr(p, "BSSID="); + if (pBssid == NULL) { + LOGE("NO bssid find!"); + return; + } + pBssid += strlen("BSSID="); + char *pReason = strstr(p, "REASON="); + if (pReason == NULL) { + LOGE("NO reason find!"); + return; + } + pReason += strlen("REASON="); + WifiHalCbNotifyBssidChanged(pReason, pBssid); } else { WpaCallBackFuncTwo(p); } @@ -617,6 +673,8 @@ static void *WpaReceiveCallback(void *arg) if (arg == NULL) { return NULL; } + char staIface[] = "IFNAME=wlan"; + char p2pIface[] = "IFNAME=p2p"; WifiWpaInterface *pWpa = arg; char *buf = (char *)calloc(REPLY_BUF_LENGTH, sizeof(char)); if (buf == NULL) { @@ -644,6 +702,7 @@ static void *WpaReceiveCallback(void *arg) if (len <= 0) { continue; } + LOGD("wpa recv buf: %{public}s!", buf); /* Message format: IFACE=wlan0 EventType params... */ char *p = strchr(buf, '>'); if (p == NULL) { @@ -654,30 +713,49 @@ static void *WpaReceiveCallback(void *arg) if (strncmp(p, WPA_EVENT_TERMINATING, strlen(WPA_EVENT_TERMINATING)) == 0) { break; } - if (WpaP2pCallBackFunc(p) == 0) { + char *iface = strstr(buf, "IFNAME="); + if (iface == NULL) { + /* if 'IFACE=' is not reported */ + if (WpaP2pCallBackFunc(p) == 0) { + continue; + } + WpaCallBackFunc(p); continue; } - WpaCallBackFunc(p); + if (strncmp(iface, p2pIface, strlen(p2pIface)) == 0) { + if (WpaP2pCallBackFunc(p) == 0) { + continue; + } + } + if (strncmp(iface, staIface, strlen(staIface)) == 0) { + WpaCallBackFunc(p); + } } free(buf); + buf = NULL; LOGI("=====================thread exist======================="); return NULL; } static int WpaCliConnect(WifiWpaInterface *p) { + LOGI("Wpa connect start."); if (p == NULL) { + LOGE("Wpa connect parameter error."); return -1; } if (p->wpaCtrl.pSend != NULL) { + LOGE("Wpa is already connected."); return 0; } int count = WPA_TRY_CONNECT_TIMES; while (count-- > 0) { - int ret = InitWpaCtrl(&p->wpaCtrl, "127.0.0.1:9878"); + int ret = InitWpaCtrl(&p->wpaCtrl, CONFIG_ROOR_DIR"/sockets/wpa"); if (ret == 0) { - LOGD("Global wpa interface connect successfully!"); + LOGI("Global wpa interface connect successfully!"); break; + } else { + LOGE("Init wpaCtrl failed: %{public}d", ret); } usleep(WPA_TRY_CONNECT_SLEEP_TIME); } @@ -691,6 +769,7 @@ static int WpaCliConnect(WifiWpaInterface *p) LOGE("Create monitor thread failed!"); return -1; } + LOGI("Wpa connect finish."); return 0; } @@ -705,7 +784,7 @@ static void WpaCliClose(WifiWpaInterface *p) return; } -static int WpaCliAddIface(WifiWpaInterface *p, const AddInterfaceArgv *argv) +static int WpaCliAddIface(WifiWpaInterface *p, const AddInterfaceArgv *argv, bool isWpaAdd) { if (p == NULL || argv == NULL) { return -1; @@ -725,11 +804,15 @@ static int WpaCliAddIface(WifiWpaInterface *p, const AddInterfaceArgv *argv) StrSafeCopy(info->name, sizeof(info->name), argv->name); char cmd[WPA_CMD_BUF_LEN] = {0}; char buf[WPA_CMD_REPLY_BUF_SMALL_LEN] = {0}; - if (snprintf_s(cmd, sizeof(cmd), sizeof(cmd) - 1, "INTERFACE_ADD %s\t%s", argv->name, argv->confName) < 0 || - WpaCliCmd(cmd, buf, sizeof(buf)) != 0) { + LOGI("Add interface start."); + if (isWpaAdd && (snprintf_s(cmd, sizeof(cmd), sizeof(cmd) - 1, "INTERFACE_ADD %s\t%s", + argv->name, argv->confName) < 0 || WpaCliCmd(cmd, buf, sizeof(buf)) != 0)) { free(info); + info = NULL; + LOGI("WpaCliAddIface failed, cmd: %{public}s, buf: %{public}s", cmd, buf); return -1; } + LOGI("Add interface finish, cmd: %{public}s, buf: %{public}s", cmd, buf); info->num += 1; info->next = p->ifaces; p->ifaces = info; @@ -741,6 +824,7 @@ static int WpaCliRemoveIface(WifiWpaInterface *p, const char *name) if (p == NULL || name == NULL) { return -1; } + LOGI("Remove interface: %{public}s", name); WpaIfaceInfo *prev = NULL; WpaIfaceInfo *info = p->ifaces; while (info != NULL) { @@ -767,9 +851,22 @@ static int WpaCliRemoveIface(WifiWpaInterface *p, const char *name) prev->next = info->next; } free(info); + info = NULL; return 0; } +static int WpaCliWpaTerminate(void) +{ + LOGI("Enter WpaCliWpaTerminate"); + char cmd[WPA_CMD_BUF_LEN] = {0}; + char buf[WPA_CMD_REPLY_BUF_SMALL_LEN] = {0}; + if (snprintf_s(cmd, sizeof(cmd), sizeof(cmd) - 1, "TERMINATE") < 0) { + LOGE("WpaCliWpaTerminate, snprintf err"); + return -1; + } + return WpaCliCmd(cmd, buf, sizeof(buf)); +} + WifiWpaInterface *GetWifiWapGlobalInterface(void) { if (g_wpaInterface != NULL) { @@ -784,6 +881,7 @@ WifiWpaInterface *GetWifiWapGlobalInterface(void) g_wpaInterface->wpaCliClose = WpaCliClose; g_wpaInterface->wpaCliAddIface = WpaCliAddIface; g_wpaInterface->wpaCliRemoveIface = WpaCliRemoveIface; + g_wpaInterface->wpaCliTerminate = WpaCliWpaTerminate; return g_wpaInterface; } diff --git a/services/wifi_standard/wifi_hal/wifi_hal_module/wpa_supplicant_hal/wifi_wpa_hal.h b/wifi/services/wifi_standard/wifi_hal/wifi_hal_module/wpa_supplicant_hal/wifi_wpa_hal.h similarity index 92% rename from services/wifi_standard/wifi_hal/wifi_hal_module/wpa_supplicant_hal/wifi_wpa_hal.h rename to wifi/services/wifi_standard/wifi_hal/wifi_hal_module/wpa_supplicant_hal/wifi_wpa_hal.h index 73c6ab31e2c830af99f46781354effb313bcda77..e5ca7aac093074e1830aad3a313ea7808f3b79d6 100644 --- a/services/wifi_standard/wifi_hal/wifi_hal_module/wpa_supplicant_hal/wifi_wpa_hal.h +++ b/wifi/services/wifi_standard/wifi_hal/wifi_hal_module/wpa_supplicant_hal/wifi_wpa_hal.h @@ -1,5 +1,5 @@ /* - * Copyright (C) 2021 Huawei Device Co., Ltd. + * Copyright (C) 2021-2022 Huawei Device Co., Ltd. * 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 @@ -12,8 +12,11 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + #ifndef WIFI_WPA_HAL_H #define WIFI_WPA_HAL_H + +#include #include #include #include @@ -47,16 +50,15 @@ struct stWifiWpaInterface { int (*wpaCliConnect)(WifiWpaInterface *p); void (*wpaCliClose)(WifiWpaInterface *p); - - int (*wpaCliAddIface)(WifiWpaInterface *p, const AddInterfaceArgv *argv); + int (*wpaCliAddIface)(WifiWpaInterface *p, const AddInterfaceArgv *argv, bool isWpaAdd); int (*wpaCliRemoveIface)(WifiWpaInterface *p, const char *name); + int (*wpaCliTerminate)(); }; WifiWpaInterface *GetWifiWapGlobalInterface(void); void ReleaseWpaGlobalInterface(void); WpaCtrl *GetWpaCtrl(void); - #ifdef __cplusplus } #endif -#endif \ No newline at end of file +#endif diff --git a/services/wifi_standard/wifi_hal/wifi_hal_module/wpa_supplicant_hal/wpa_p2p_hal/wifi_p2p_hal.c b/wifi/services/wifi_standard/wifi_hal/wifi_hal_module/wpa_supplicant_hal/wpa_p2p_hal/wifi_p2p_hal.c similarity index 96% rename from services/wifi_standard/wifi_hal/wifi_hal_module/wpa_supplicant_hal/wpa_p2p_hal/wifi_p2p_hal.c rename to wifi/services/wifi_standard/wifi_hal/wifi_hal_module/wpa_supplicant_hal/wpa_p2p_hal/wifi_p2p_hal.c index 136d411b5af05b05d1404b4ae0602b16339f053f..eabf934a08b10d5ee07ad7dcc9fa37a9395f71ec 100644 --- a/services/wifi_standard/wifi_hal/wifi_hal_module/wpa_supplicant_hal/wpa_p2p_hal/wifi_p2p_hal.c +++ b/wifi/services/wifi_standard/wifi_hal/wifi_hal_module/wpa_supplicant_hal/wpa_p2p_hal/wifi_p2p_hal.c @@ -1,5 +1,5 @@ /* - * Copyright (C) 2021 Huawei Device Co., Ltd. + * Copyright (C) 2021-2022 Huawei Device Co., Ltd. * 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 @@ -82,7 +82,7 @@ static P2pSupplicantErrCode WpaP2pCliCmdWpsPbc(WifiWpaP2pGroupInterface *this, c return P2P_SUP_ERRCODE_FAILED; } if (strncmp(buf, "FAIL-PBC-OVERLAP", strlen("FAIL-PBC-OVERLAP")) == 0) { - LOGE("wps_pbc sucess, but result err: buf =%{public}s", buf); + LOGE("wps_pbc success, but result err: buf =%{public}s", buf); return P2P_SUP_ERRCODE_PBC_OVERLAP; } return P2P_SUP_ERRCODE_SUCCESS; @@ -191,6 +191,7 @@ static P2pSupplicantErrCode WpaP2pCliCmdSetWpsDeviceType(WifiWpaP2pInterface *th LOGE("snprintf err"); return P2P_SUP_ERRCODE_FAILED; } + LOGI("Set device type CMD: %{public}s", cmd); if (WpaCliCmd(cmd, buf, sizeof(buf)) != 0) { LOGE("set device_type command failed!"); return P2P_SUP_ERRCODE_FAILED; @@ -574,7 +575,7 @@ static P2pSupplicantErrCode WpaP2pCliCmdReInvite(WifiWpaP2pInterface *this, cons return P2P_SUP_ERRCODE_SUCCESS; } -static P2pSupplicantErrCode WpaP2pCliCmdServiceAdd(WifiWpaP2pInterface *this, const HidlP2pServiceInfo *argv) +static P2pSupplicantErrCode WpaP2pCliCmdServiceAdd(WifiWpaP2pInterface *this, const P2pServiceInfo *argv) { if (this == NULL || argv == NULL) { return P2P_SUP_ERRCODE_INVALID; @@ -619,7 +620,7 @@ static P2pSupplicantErrCode WpaP2pCliCmdServiceAdd(WifiWpaP2pInterface *this, co return P2P_SUP_ERRCODE_SUCCESS; } -static P2pSupplicantErrCode WpaP2pCliCmdServiceDel(WifiWpaP2pInterface *this, const HidlP2pServiceInfo *argv) +static P2pSupplicantErrCode WpaP2pCliCmdServiceDel(WifiWpaP2pInterface *this, const P2pServiceInfo *argv) { if (this == NULL || argv == NULL) { return P2P_SUP_ERRCODE_INVALID; @@ -797,7 +798,7 @@ static P2pSupplicantErrCode WpaP2pCliCmdStoreConfig(WifiWpaP2pInterface *this) return P2P_SUP_ERRCODE_SUCCESS; } -static void GetHalNetworkInfos(char *buf, HidlP2pNetworkInfo *info) +static void GetHalNetworkInfos(char *buf, P2pNetworkInfo *info) { if (buf == NULL || info == NULL) { return; @@ -836,7 +837,7 @@ static void GetHalNetworkInfos(char *buf, HidlP2pNetworkInfo *info) return; } -static P2pSupplicantErrCode WpaP2pCliCmdNetworkList(WifiWpaP2pInterface *this, HidlP2pNetworkList *infoList) +static P2pSupplicantErrCode WpaP2pCliCmdNetworkList(WifiWpaP2pInterface *this, P2pNetworkList *infoList) { if (this == NULL || infoList == NULL) { return P2P_SUP_ERRCODE_INVALID; @@ -869,7 +870,7 @@ static P2pSupplicantErrCode WpaP2pCliCmdNetworkList(WifiWpaP2pInterface *this, H free(buf); return P2P_SUP_ERRCODE_SUCCESS; } - infoList->infos = (HidlP2pNetworkInfo *)calloc(infoList->infoNum, sizeof(HidlP2pNetworkInfo)); + infoList->infos = (P2pNetworkInfo *)calloc(infoList->infoNum, sizeof(P2pNetworkInfo)); if (infoList->infos == NULL) { free(buf); return P2P_SUP_ERRCODE_FAILED; @@ -890,7 +891,7 @@ static P2pSupplicantErrCode WpaP2pCliCmdNetworkList(WifiWpaP2pInterface *this, H return P2P_SUP_ERRCODE_SUCCESS; } -static P2pSupplicantErrCode WpaP2pCliCmdConnect(WifiWpaP2pInterface *this, HidlP2pConnectInfo *info) +static P2pSupplicantErrCode WpaP2pCliCmdConnect(WifiWpaP2pInterface *this, P2pConnectInfo *info) { if (this == NULL || info == NULL) { return P2P_SUP_ERRCODE_INVALID; @@ -961,7 +962,7 @@ static P2pSupplicantErrCode WpaP2pCliCmdSetPersistentReconnect(WifiWpaP2pInterfa return P2P_SUP_ERRCODE_SUCCESS; } -static P2pSupplicantErrCode WpaP2pCliCmdRespServerDiscovery(WifiWpaP2pInterface *this, HidlP2pServDiscReqInfo *info) +static P2pSupplicantErrCode WpaP2pCliCmdRespServerDiscovery(WifiWpaP2pInterface *this, P2pServDiscReqInfo *info) { if (this == NULL || info == NULL || info->tlvs == NULL) { return P2P_SUP_ERRCODE_INVALID; @@ -1083,7 +1084,7 @@ static P2pSupplicantErrCode WpaP2pCliCmdSetRandomMac(WifiWpaP2pInterface *this, } static P2pSupplicantErrCode WpaP2pCliCmdP2pGetPeer( - WifiWpaP2pInterface *this, const char *bssid, HidlP2pDeviceInfo *peerInfo) + WifiWpaP2pInterface *this, const char *bssid, P2pDeviceInfo *peerInfo) { if (this == NULL || bssid == NULL || peerInfo == NULL) { return P2P_SUP_ERRCODE_INVALID; @@ -1121,6 +1122,8 @@ static P2pSupplicantErrCode WpaP2pCliCmdP2pGetPeer( peerInfo->deviceCapabilities = Hex2Dec(retMsg.value); } else if (strncmp(retMsg.key, "group_capab", strlen("group_capab")) == 0) { peerInfo->groupCapabilities = Hex2Dec(retMsg.value); + } else if (strncmp(retMsg.key, "oper_ssid", strlen("oper_ssid")) == 0) { + StrSafeCopy(peerInfo->operSsid, sizeof(peerInfo->operSsid), retMsg.value); } token = strtok_r(NULL, "\n", &savedPtr); @@ -1226,6 +1229,32 @@ static P2pSupplicantErrCode WpaP2pCliCmdAddNetwork(WifiWpaP2pInterface *this, in return P2P_SUP_ERRCODE_SUCCESS; } +static P2pSupplicantErrCode WpaP2pHid2dCliCmdConnect(WifiWpaP2pInterface *this, Hid2dConnectInfo *info) +{ + if (this == NULL || info == NULL) { + return P2P_SUP_ERRCODE_INVALID; + } + + char buf[P2P_REPLY_BUF_SMALL_LENGTH] = {0}; + char cmd[P2P_CMD_BUF_LENGTH] = {0}; + if (snprintf_s(cmd, sizeof(cmd), sizeof(cmd) - 1, "IFNAME=%s MAGICLINK \"%s\"\n%s\n\"%s\"\n%d", this->ifName, + info->ssid, info->bssid, info->passphrase, info->frequency) < 0) { + LOGE("hid2d connect snprintf err"); + return P2P_SUP_ERRCODE_FAILED; + } + + LOGI("hid2d_connect, frequency = %{public}d", info->frequency); + if (WpaCliCmd(cmd, buf, sizeof(buf)) != 0) { + LOGE("hid2d_connect command failed!"); + return P2P_SUP_ERRCODE_FAILED; + } + if (strncmp(buf, "FAIL", strlen("FAIL")) == 0) { + LOGE("P2p hid2d_connect return %{public}s", buf); + return P2P_SUP_ERRCODE_FAILED; + } + return P2P_SUP_ERRCODE_SUCCESS; +} + static void InitGlobalWpaP2pFunc(void) { g_wpaP2pInterface->wpaP2pCliCmdSetWpsName = WpaP2pCliCmdSetWpsName; @@ -1264,6 +1293,7 @@ static void InitGlobalWpaP2pFunc(void) g_wpaP2pInterface->wpaP2pCliCmdSetGroupConfig = WpaP2pCliCmdSetGroupConfig; g_wpaP2pInterface->wpaP2pCliCmdGetGroupConfig = WpaP2pCliCmdGetGroupConfig; g_wpaP2pInterface->wpaP2pCliCmdAddNetwork = WpaP2pCliCmdAddNetwork; + g_wpaP2pInterface->wpaP2pCliCmdHid2dConnect = WpaP2pHid2dCliCmdConnect; return; } @@ -1277,7 +1307,11 @@ WifiWpaP2pInterface *GetWifiWapP2pInterface() LOGE("alloc memory for p2p interface failed!"); return NULL; } +#ifdef NON_SEPERATE_P2P + StrSafeCopy(g_wpaP2pInterface->ifName, sizeof(g_wpaP2pInterface->ifName), "p2p-dev-wlan0"); +#else StrSafeCopy(g_wpaP2pInterface->ifName, sizeof(g_wpaP2pInterface->ifName), "p2p0"); +#endif InitGlobalWpaP2pFunc(); return g_wpaP2pInterface; } diff --git a/services/wifi_standard/wifi_hal/wifi_hal_module/wpa_supplicant_hal/wpa_p2p_hal/wifi_p2p_hal.h b/wifi/services/wifi_standard/wifi_hal/wifi_hal_module/wpa_supplicant_hal/wpa_p2p_hal/wifi_p2p_hal.h similarity index 91% rename from services/wifi_standard/wifi_hal/wifi_hal_module/wpa_supplicant_hal/wpa_p2p_hal/wifi_p2p_hal.h rename to wifi/services/wifi_standard/wifi_hal/wifi_hal_module/wpa_supplicant_hal/wpa_p2p_hal/wifi_p2p_hal.h index 8f02755900a8649abd5cdf53782f3884894fdea2..aca94f198415f47c60da73a37ae713c040a86fe5 100644 --- a/services/wifi_standard/wifi_hal/wifi_hal_module/wpa_supplicant_hal/wpa_p2p_hal/wifi_p2p_hal.h +++ b/wifi/services/wifi_standard/wifi_hal/wifi_hal_module/wpa_supplicant_hal/wpa_p2p_hal/wifi_p2p_hal.h @@ -1,5 +1,5 @@ /* - * Copyright (C) 2021 Huawei Device Co., Ltd. + * Copyright (C) 2021-2022 Huawei Device Co., Ltd. * 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 @@ -32,6 +32,7 @@ extern "C" { #define P2P_PIN_KEYPAD 1 #define P2P_PIN_DISPLAY 2 #define P2P_GROUP_IFACE_MAX_LENGTH 128 +#define P2P_INTERFACE_CREATED "P2P-INTERFACE-CREATED " typedef struct stWifiWpaP2pInterface WifiWpaP2pInterface; struct stWifiWpaP2pInterface { @@ -56,8 +57,8 @@ struct stWifiWpaP2pInterface { P2pSupplicantErrCode (*wpaP2pCliCmdCancelConnect)(WifiWpaP2pInterface *p); P2pSupplicantErrCode (*wpaP2pCliCmdInvite)(WifiWpaP2pInterface *p, const P2pHalInviteArgv *argv); P2pSupplicantErrCode (*wpaP2pCliCmdReInvite)(WifiWpaP2pInterface *p, const P2pHalReInviteArgv *argv); - P2pSupplicantErrCode (*wpaP2pCliCmdServiceAdd)(WifiWpaP2pInterface *p, const HidlP2pServiceInfo *argv); - P2pSupplicantErrCode (*wpaP2pCliCmdServiceDel)(WifiWpaP2pInterface *p, const HidlP2pServiceInfo *argv); + P2pSupplicantErrCode (*wpaP2pCliCmdServiceAdd)(WifiWpaP2pInterface *p, const P2pServiceInfo *argv); + P2pSupplicantErrCode (*wpaP2pCliCmdServiceDel)(WifiWpaP2pInterface *p, const P2pServiceInfo *argv); P2pSupplicantErrCode (*wpaP2pCliCmdServDiscReq)( WifiWpaP2pInterface *p, const char *peerBssid, const char *tlvs, char *retSeq, unsigned size); P2pSupplicantErrCode (*wpaP2pCliCmdServDiscCancelReq)(WifiWpaP2pInterface *p, const char *val); @@ -65,17 +66,18 @@ struct stWifiWpaP2pInterface { WifiWpaP2pInterface *p, const P2pProvisionDiscoveryArgv *argv); P2pSupplicantErrCode (*wpaP2pCliCmdGroupAdd)(WifiWpaP2pInterface *p, int isPersistent, int networkId, int freq); P2pSupplicantErrCode (*wpaP2pCliCmdStoreConfig)(WifiWpaP2pInterface *p); - P2pSupplicantErrCode (*wpaP2pCliCmdNetworkList)(WifiWpaP2pInterface *p, HidlP2pNetworkList *infoList); - P2pSupplicantErrCode (*wpaP2pCliCmdConnect)(WifiWpaP2pInterface *p, HidlP2pConnectInfo *info); + P2pSupplicantErrCode (*wpaP2pCliCmdNetworkList)(WifiWpaP2pInterface *p, P2pNetworkList *infoList); + P2pSupplicantErrCode (*wpaP2pCliCmdConnect)(WifiWpaP2pInterface *p, P2pConnectInfo *info); P2pSupplicantErrCode (*wpaP2pCliCmdSetPersistentReconnect)(WifiWpaP2pInterface *p, int status); - P2pSupplicantErrCode (*wpaP2pCliCmdRespServerDiscovery)(WifiWpaP2pInterface *p, HidlP2pServDiscReqInfo *info); + P2pSupplicantErrCode (*wpaP2pCliCmdRespServerDiscovery)(WifiWpaP2pInterface *p, P2pServDiscReqInfo *info); P2pSupplicantErrCode (*wpaP2pCliCmdSetServDiscExternal)(WifiWpaP2pInterface *p, int mode); P2pSupplicantErrCode (*wpaP2pCliCmdSetRandomMac)(WifiWpaP2pInterface *p, int mode); P2pSupplicantErrCode (*wpaP2pCliCmdP2pGetPeer)( - WifiWpaP2pInterface *p, const char *bssid, HidlP2pDeviceInfo *peerInfo); + WifiWpaP2pInterface *p, const char *bssid, P2pDeviceInfo *peerInfo); P2pSupplicantErrCode (*wpaP2pCliCmdSetGroupConfig)(WifiWpaP2pInterface *p, const P2pWpaGroupConfigArgv *argv); P2pSupplicantErrCode (*wpaP2pCliCmdGetGroupConfig)(WifiWpaP2pInterface *p, P2pWpaGroupConfigArgv *argv); P2pSupplicantErrCode (*wpaP2pCliCmdAddNetwork)(WifiWpaP2pInterface *p, int *networkId); + P2pSupplicantErrCode (*wpaP2pCliCmdHid2dConnect)(WifiWpaP2pInterface *p, Hid2dConnectInfo *info); }; typedef struct stWifiWpaP2pGroupInterface WifiWpaP2pGroupInterface; @@ -97,4 +99,4 @@ void ReleaseWpaP2pGroupInterface(const char *groupIfc); #ifdef __cplusplus } #endif -#endif \ No newline at end of file +#endif diff --git a/services/wifi_standard/wifi_hal/wifi_hal_module/wpa_supplicant_hal/wpa_sta_hal/wifi_supplicant_hal.c b/wifi/services/wifi_standard/wifi_hal/wifi_hal_module/wpa_supplicant_hal/wpa_sta_hal/wifi_supplicant_hal.c similarity index 58% rename from services/wifi_standard/wifi_hal/wifi_hal_module/wpa_supplicant_hal/wpa_sta_hal/wifi_supplicant_hal.c rename to wifi/services/wifi_standard/wifi_hal/wifi_hal_module/wpa_supplicant_hal/wpa_sta_hal/wifi_supplicant_hal.c index 26a90a625c03eadb9f6c2db9b846c81a1bb9965f..43b70dc11a4c8638a81f9efaa40e3f7bb7aaa950 100644 --- a/services/wifi_standard/wifi_hal/wifi_hal_module/wpa_supplicant_hal/wpa_sta_hal/wifi_supplicant_hal.c +++ b/wifi/services/wifi_standard/wifi_hal/wifi_hal_module/wpa_supplicant_hal/wpa_sta_hal/wifi_supplicant_hal.c @@ -16,6 +16,7 @@ #include "wifi_supplicant_hal.h" #include #include +#include #include "wifi_hal_callback.h" #include "securec.h" #include "wifi_log.h" @@ -27,34 +28,68 @@ #define LOG_TAG "WifiWpaStaHal" #define FAIL_BUSY 2 -#define SCAN_INFO_NONE 0 -#define SCAN_INFO_ONE 1 -#define SCAN_INFO_TWO 2 -#define SCAN_INFO_THREE 3 + +#define COLUMN_INDEX_ZERO 0 +#define COLUMN_INDEX_ONE 1 +#define COLUMN_INDEX_TWO 2 +#define COLUMN_INDEX_THREE 3 +#define COLUMN_INDEX_FOUR 4 +#define COLUMN_INDEX_FIVE 5 + #define FAIL_PBC_OVERLAP_RETUEN 3 -#define CMD_BUFFER_SIZE 256 -#define REPLY_BUF_LENGTH 4096 +#define CMD_BUFFER_SIZE 1024 +#define REPLY_BUF_LENGTH (4096 * 10) #define REPLY_BUF_SMALL_LENGTH 64 #define CMD_FREQ_MAX_LEN 8 +const int QUOTATION_MARKS_FLAG_YES = 0; +const int QUOTATION_MARKS_FLAG_NO = 1; + +const unsigned int HT_OPER_EID = 61; +const unsigned int VHT_OPER_EID = 192; +const unsigned int EXT_EXIST_EID = 255; +const unsigned int EXT_HE_OPER_EID = 36; +const unsigned int HE_OPER_BASIC_LEN = 6; +const unsigned int VHT_OPER_INFO_EXTST_MASK = 0x40; +const unsigned int GHZ_HE_INFO_EXIST_MASK_6 = 0x02; +const unsigned int GHZ_HE_WIDTH_MASK_6 = 0x03; +const unsigned int BSS_EXIST_MASK = 0x80; +const unsigned int VHT_OPER_INFO_BEGIN_INDEX = 6; +const unsigned int VHT_INFO_SIZE = 3; +const unsigned int HT_INFO_SIZE = 3; +const unsigned int UINT8_MASK = 0xFF; +const unsigned int UNSPECIFIED = -1; +const unsigned int MAX_INFO_ELEMS_SIZE = 256; + +const unsigned int BAND_5_GHZ = 2; +const unsigned int BAND_6_GHZ = 8; +const unsigned int CHAN_WIDTH_20MHZ = 0; +const unsigned int CHAN_WIDTH_40MHZ = 1; +const unsigned int CHAN_WIDTH_80MHZ = 2; +const unsigned int CHAN_WIDTH_160MHZ = 3; +const unsigned int CHAN_WIDTH_80MHZ_MHZ = 4; + WifiWpaStaInterface *g_wpaStaInterface = NULL; static WpaSsidField g_wpaSsidFields[] = { - {DEVICE_CONFIG_SSID, "ssid", 0}, - {DEVICE_CONFIG_PSK, "psk", 0}, - {DEVICE_CONFIG_KEYMGMT, "key_mgmt", 1}, - {DEVICE_CONFIG_PRIORITY, "priority", 1}, - {DEVICE_CONFIG_SCAN_SSID, "scan_ssid", 1}, - {DEVICE_CONFIG_EAP, "eap", 1}, - {DEVICE_CONFIG_IDENTITY, "identity", 0}, - {DEVICE_CONFIG_PASSWORD, "password", 0}, - {DEVICE_CONFIG_BSSID, "bssid", 1}, - {DEVICE_CONFIG_AUTH_ALGORITHMS, "auth_alg", 1}, - {DEVICE_CONFIG_WEP_KEY_IDX, "wep_tx_keyidx", 1}, - {DEVICE_CONFIG_WEP_KEY_0, "wep_key0", 1}, - {DEVICE_CONFIG_WEP_KEY_1, "wep_key1", 1}, - {DEVICE_CONFIG_WEP_KEY_2, "wep_key2", 1}, - {DEVICE_CONFIG_WEP_KEY_3, "wep_key3", 1} + {DEVICE_CONFIG_SSID, "ssid", QUOTATION_MARKS_FLAG_YES}, + {DEVICE_CONFIG_PSK, "psk", QUOTATION_MARKS_FLAG_YES}, + {DEVICE_CONFIG_KEYMGMT, "key_mgmt", QUOTATION_MARKS_FLAG_NO}, + {DEVICE_CONFIG_PRIORITY, "priority", QUOTATION_MARKS_FLAG_NO}, + {DEVICE_CONFIG_SCAN_SSID, "scan_ssid", QUOTATION_MARKS_FLAG_NO}, + {DEVICE_CONFIG_EAP, "eap", QUOTATION_MARKS_FLAG_NO}, + {DEVICE_CONFIG_IDENTITY, "identity", QUOTATION_MARKS_FLAG_YES}, + {DEVICE_CONFIG_PASSWORD, "password", QUOTATION_MARKS_FLAG_YES}, + {DEVICE_CONFIG_BSSID, "bssid", QUOTATION_MARKS_FLAG_NO}, + {DEVICE_CONFIG_AUTH_ALGORITHMS, "auth_alg", QUOTATION_MARKS_FLAG_NO}, + {DEVICE_CONFIG_WEP_KEY_IDX, "wep_tx_keyidx", QUOTATION_MARKS_FLAG_NO}, + {DEVICE_CONFIG_WEP_KEY_0, "wep_key0", QUOTATION_MARKS_FLAG_NO}, + {DEVICE_CONFIG_WEP_KEY_1, "wep_key1", QUOTATION_MARKS_FLAG_NO}, + {DEVICE_CONFIG_WEP_KEY_2, "wep_key2", QUOTATION_MARKS_FLAG_NO}, + {DEVICE_CONFIG_WEP_KEY_3, "wep_key3", QUOTATION_MARKS_FLAG_NO}, + {DEVICE_CONFIG_EAP_CLIENT_CERT, "client_cert", QUOTATION_MARKS_FLAG_YES}, + {DEVICE_CONFIG_EAP_PRIVATE_KEY, "private_key", QUOTATION_MARKS_FLAG_YES}, + {DEVICE_CONFIG_EAP_PHASE2METHOD, "phase2", QUOTATION_MARKS_FLAG_YES}, }; static int WpaCliCmdStatus(WifiWpaStaInterface *this, struct WpaHalCmdStatus *pcmd) @@ -179,6 +214,30 @@ static int WpaCliCmdSaveConfig(WifiWpaStaInterface *this) return WpaCliCmd(cmd, buf, sizeof(buf)); } +static int CalcQuotationMarksFlag(int pos, const char value[WIFI_NETWORK_CONFIG_VALUE_LENGTH]) +{ + int flag = g_wpaSsidFields[pos].flag; + const int HEX_PSK_MAX_LEN = 64; + int len = strlen(value); + /* if the psk length is 64, it's hex format and don't need quotation marks */ + if (pos == DEVICE_CONFIG_PSK && len >= HEX_PSK_MAX_LEN) { + flag = QUOTATION_MARKS_FLAG_NO; + } + if (pos == DEVICE_CONFIG_WEP_KEY_0 || + pos == DEVICE_CONFIG_WEP_KEY_1 || + pos == DEVICE_CONFIG_WEP_KEY_2 || + pos == DEVICE_CONFIG_WEP_KEY_3) { + const int WEP_KEY_LEN1 = 5; + const int WEP_KEY_LEN2 = 13; + const int WEP_KEY_LEN3 = 16; + /* For wep key, ASCII format need quotation marks, hex format is not required */ + if (len == WEP_KEY_LEN1 || len == WEP_KEY_LEN2 || len == WEP_KEY_LEN3) { + flag = QUOTATION_MARKS_FLAG_YES; + } + } + return flag; +} + static int WpaCliCmdSetNetwork(WifiWpaStaInterface *this, const struct WpaSetNetworkArgv *argv) { if (this == NULL || argv == NULL) { @@ -198,7 +257,7 @@ static int WpaCliCmdSetNetwork(WifiWpaStaInterface *this, const struct WpaSetNet char cmd[CMD_BUFFER_SIZE] = {0}; char buf[REPLY_BUF_SMALL_LENGTH] = {0}; int res; - if (g_wpaSsidFields[pos].flag == 0) { + if (CalcQuotationMarksFlag(pos, argv->value) == QUOTATION_MARKS_FLAG_YES) { res = snprintf_s(cmd, sizeof(cmd), sizeof(cmd) - 1, "IFNAME=%s SET_NETWORK %d %s \"%s\"", this->ifname, argv->id, g_wpaSsidFields[pos].fieldName, argv->value); } else { @@ -424,6 +483,20 @@ static int WpaCliCmdPowerSave(WifiWpaStaInterface *this, int enable) return WpaCliCmd(cmd, buf, sizeof(buf)); } +static int WpaCliCmdSetRoamConfig(WifiWpaStaInterface *this, const char *bssid) +{ + if (this == NULL || bssid == NULL) { + return -1; + } + char buf[REPLY_BUF_SMALL_LENGTH] = {0}; + char cmd[CMD_BUFFER_SIZE] = {0}; + if (snprintf_s(cmd, sizeof(cmd), sizeof(cmd) - 1, "IFNAME=%s SET bssid %s", this->ifname, bssid) < 0) { + LOGE("snprintf err"); + return -1; + } + return WpaCliCmd(cmd, buf, sizeof(buf)); +} + static int WpaCliCmdSetCountryCode(WifiWpaStaInterface *this, const char *countryCode) { if (this == NULL || countryCode == NULL) { @@ -488,7 +561,7 @@ static int WpaCliCmdWpaBlockListClear(WifiWpaStaInterface *this) return WpaCliCmd(cmd, buf, sizeof(buf)); } -static void ListNetworkProcess(HidlNetworkInfo *pcmd, char *tmpBuf, int bufLeng) +static void ListNetworkProcess(WifiNetworkInfo *pcmd, char *tmpBuf, int bufLeng) { int start = 0; /* start pos */ int end = 0; /* end pos */ @@ -499,14 +572,14 @@ static void ListNetworkProcess(HidlNetworkInfo *pcmd, char *tmpBuf, int bufLeng) continue; } tmpBuf[end] = '\0'; - if (i == SCAN_INFO_NONE) { + if (i == COLUMN_INDEX_ZERO) { pcmd->id = atoi(tmpBuf); - } else if (i == SCAN_INFO_ONE) { + } else if (i == COLUMN_INDEX_ONE) { if (strcpy_s(pcmd->ssid, sizeof(pcmd->ssid), tmpBuf + start) != EOK) { break; } printf_decode((u8 *)pcmd->ssid, sizeof(pcmd->ssid), pcmd->ssid); - } else if (i == SCAN_INFO_TWO) { + } else if (i == COLUMN_INDEX_TWO) { if (strcpy_s(pcmd->bssid, sizeof(pcmd->bssid), tmpBuf + start) != EOK) { break; } @@ -523,7 +596,7 @@ static void ListNetworkProcess(HidlNetworkInfo *pcmd, char *tmpBuf, int bufLeng) return; } -static int WpaCliCmdListNetworks(WifiWpaStaInterface *this, HidlNetworkInfo *pcmd, int *size) +static int WpaCliCmdListNetworks(WifiWpaStaInterface *this, WifiNetworkInfo *pcmd, int *size) { if (this == NULL || pcmd == NULL || size == NULL || *size <= 0) { return -1; @@ -542,8 +615,8 @@ static int WpaCliCmdListNetworks(WifiWpaStaInterface *this, HidlNetworkInfo *pcm return -1; } char *savedPtr = NULL; - char *token = strtok_r(buf, "\n", &savedPtr); /* skip first line */ - token = strtok_r(NULL, "\n", &savedPtr); + strtok_r(buf, "\n", &savedPtr); /* skip first line */ + char *token = strtok_r(NULL, "\n", &savedPtr); int j = 0; while (token != NULL) { @@ -618,14 +691,33 @@ static int ConcatScanSetting(const ScanSettings *settings, char *buff, int len) return 0; } +static int WpaCliCmdBssFlush(WifiWpaStaInterface *this) +{ + if (this == NULL) { + return -1; + } + char buf[REPLY_BUF_SMALL_LENGTH] = {0}; + char cmd[CMD_BUFFER_SIZE] = {0}; + if (snprintf_s(cmd, sizeof(cmd), sizeof(cmd) - 1, "IFNAME=%s BSS_FLUSH 0", this->ifname) < 0) { + LOGE("snprintf err"); + return -1; + } + return WpaCliCmd(cmd, buf, sizeof(buf)); +} + static int WpaCliCmdScan(WifiWpaStaInterface *this, const ScanSettings *settings) { if (this == NULL) { return -1; } + + /* Invalidate expired scan results */ + WpaCliCmdBssFlush(this); unsigned len = CMD_BUFFER_SIZE; if (settings != NULL) { unsigned expectLen = strlen("IFNAME=") + strlen(this->ifname) + 1 + strlen("SCAN"); + LOGI("WpaCliCmdScan, freqSize=%{public}d, hiddenSsidSize=%{public}d", + settings->freqSize, settings->hiddenSsidSize); if (settings->freqSize > 0) { expectLen += strlen(" freq=") + (CMD_FREQ_MAX_LEN + 1) * settings->freqSize; } @@ -666,9 +758,347 @@ static int WpaCliCmdScan(WifiWpaStaInterface *this, const ScanSettings *settings return 0; } +#ifndef OHOS_ARCH_LITE +static int ConvertChanToFreqMhz(int channel, int band) +{ + int BAND_FIRST_CH_NUM_24 = 1; + int BAND_LAST_CH_NUM_24 = 14; + int BAND_START_FREQ_MHZ_24 = 2412; + int BAND_FIRST_CH_NUM_5 = 32; + int BAND_LAST_CH_NUM_5 = 173; + int BAND_START_FREQ_MHZ_5 = 5160; + int BAND_FIRST_CH_NUM_6 = 1; + int BAND_LAST_CH_NUM_6 = 233; + int BAND_START_FREQ_MHZ_6 = 5955; + int BAND_CLA_2_FREQ_136_CH_MHZ_6 = 5935; + int BAND_24_GHZ = 1; + int BAND_SPECIAL = 2484; + int CHANNEL_SPECIAL = 14; + int CHANNEL_TIMES = 5; + int CHANNEL_TYPE = 2; + + if (band == BAND_24_GHZ) { + if (channel == CHANNEL_SPECIAL) { + return BAND_SPECIAL; + } else if (channel >= BAND_FIRST_CH_NUM_24 && channel <= BAND_LAST_CH_NUM_24) { + return ((channel - BAND_FIRST_CH_NUM_24) * CHANNEL_TIMES) + BAND_START_FREQ_MHZ_24; + } else { + return UNSPECIFIED; + } + } + if (band == BAND_5_GHZ) { + if (channel >= BAND_FIRST_CH_NUM_5 && channel <= BAND_LAST_CH_NUM_5) { + return ((channel - BAND_FIRST_CH_NUM_5) * CHANNEL_TIMES) + BAND_START_FREQ_MHZ_5; + } else { + return UNSPECIFIED; + } + } + if (band == BAND_6_GHZ) { + if (channel >= BAND_FIRST_CH_NUM_6 && channel <= BAND_LAST_CH_NUM_6) { + if (channel == CHANNEL_TYPE) { + return BAND_CLA_2_FREQ_136_CH_MHZ_6; + } + return ((channel - BAND_FIRST_CH_NUM_6) * CHANNEL_TIMES) + BAND_START_FREQ_MHZ_6; + } else { + return UNSPECIFIED; + } + } + return UNSPECIFIED; +} + +static int GetHeChanWidth(int heChannelWidth, int centerSegFreq0, int centerSegFreq1) +{ + int CHANNEL_WIDTH = 2; + int SEG_FREQ_VALUE = 8; + if (heChannelWidth == 0) { + return CHAN_WIDTH_20MHZ; + } else if (heChannelWidth == 1) { + return CHAN_WIDTH_40MHZ; + } else if (heChannelWidth == CHANNEL_WIDTH) { + return CHAN_WIDTH_80MHZ; + } else if (abs(centerSegFreq1 - centerSegFreq0) == SEG_FREQ_VALUE) { + return CHAN_WIDTH_160MHZ; + } else { + return CHAN_WIDTH_80MHZ_MHZ; + } +} + +static int GetHeCentFreq(int centerSegFreq) +{ + if (centerSegFreq == 0) { + return 0; + } + return ConvertChanToFreqMhz(centerSegFreq, BAND_6_GHZ); +} + +static int GetHtChanWidth(int secondOffsetChannel) +{ + if (secondOffsetChannel != 0) { + return CHAN_WIDTH_40MHZ; + } else { + return CHAN_WIDTH_20MHZ; + } +} + +static int GetHtCentFreq0(int primaryFrequency, int secondOffsetChannel) +{ + int freqValue = 10; + int offsetChannle = 3; + if (secondOffsetChannel != 0) { + if (secondOffsetChannel == 1) { + return primaryFrequency + freqValue; + } else if (secondOffsetChannel == offsetChannle) { + return primaryFrequency - freqValue; + } else { + LOGE("error on get centFreq0"); + return 0; + } + } else { + return primaryFrequency; + } +} + +static int GetVhtChanWidth(int channelType, int centerFrequencyIndex1, int centerFrequencyIndex2) +{ + int FREQ_VALUE = 8; + if (channelType == 0) { + return UNSPECIFIED; + } else if (centerFrequencyIndex2 == 0) { + return CHAN_WIDTH_80MHZ; + } else if (abs(centerFrequencyIndex1 - centerFrequencyIndex2) == FREQ_VALUE) { + return CHAN_WIDTH_160MHZ; + } else { + return CHAN_WIDTH_80MHZ_MHZ; + } +} + +static int GetVhtCentFreq(int channelType, int centerFrequencyIndex) +{ + if (centerFrequencyIndex == 0 || channelType == 0) { + return 0; + } else { + return ConvertChanToFreqMhz(centerFrequencyIndex, BAND_5_GHZ); + } +} + +static int8_t IsValidHexCharAndConvert(char c) +{ + if (c >= '0' && c <= '9') { + return c - '0'; + } + if (c >= 'a' && c <= 'f') { + return c - 'a' + ('9' - '0' + 1); + } + if (c >= 'A' && c <= 'F') { + return c - 'A' + ('9' - '0' + 1); + } + return -1; +} + +static int HexStringToString(const char *str, char *out) +{ + unsigned len = strlen(str); + if ((len & 1) != 0) { + return -1; + } + const int hexShiftNum = 4; + for (unsigned i = 0, j = 0; i + 1 < len; ++i) { + int8_t high = IsValidHexCharAndConvert(str[i]); + int8_t low = IsValidHexCharAndConvert(str[++i]); + if (high < 0 || low < 0) { + return -1; + } + char tmp = ((high << hexShiftNum) | (low & 0x0F)); + out[j] = tmp; + ++j; + } + return 0; +} + +static bool GetChanWidthCenterFreqVht(ScanInfo *pcmd, ScanInfoElem* infoElem) +{ + if ((pcmd == NULL) || (infoElem == NULL)) { + LOGE("pcmd or infoElem is NULL."); + return false; + } + if ((infoElem->content == NULL) || ((unsigned int)infoElem->size < VHT_INFO_SIZE)) { + return false; + } + int channelType = infoElem->content[COLUMN_INDEX_ZERO] & UINT8_MASK; + int centerFrequencyIndex1 = infoElem->content[COLUMN_INDEX_ONE] & UINT8_MASK; + int centerFrequencyIndex2 = infoElem->content[COLUMN_INDEX_TWO] & UINT8_MASK; + pcmd->channelWidth = GetVhtChanWidth(channelType, centerFrequencyIndex1, centerFrequencyIndex2); + if ((unsigned int)pcmd->channelWidth == UNSPECIFIED) { + return false; + } + pcmd->centerFrequency0 = GetVhtCentFreq(channelType, centerFrequencyIndex1); + pcmd->centerFrequency1 = GetVhtCentFreq(channelType, centerFrequencyIndex2); + return true; +} + +static bool GetChanWidthCenterFreqHe(ScanInfo *pcmd, ScanInfoElem* infoElem) +{ + if ((pcmd == NULL) || (infoElem == NULL)) { + LOGE("pcmd or iesNeedParse is NULL."); + return false; + } + if ((infoElem->content == NULL) || ((unsigned int)infoElem->size < (HE_OPER_BASIC_LEN + 1))) { + return false; + } + if (infoElem->content[0] != EXT_HE_OPER_EID) { + return false; + } + char* content = infoElem->content + 1; + bool isVhtInfoExist = (content[COLUMN_INDEX_ONE] & VHT_OPER_INFO_EXTST_MASK) != 0; + bool is6GhzInfoExist = (content[COLUMN_INDEX_TWO] & GHZ_HE_INFO_EXIST_MASK_6) != 0; + bool coHostedBssPresent = (content[COLUMN_INDEX_ONE] & BSS_EXIST_MASK) != 0; + int expectedLen = HE_OPER_BASIC_LEN + (isVhtInfoExist ? COLUMN_INDEX_THREE : 0) + + (coHostedBssPresent ? 1 : 0) + (is6GhzInfoExist ? COLUMN_INDEX_FIVE : 0); + if (infoElem->size < expectedLen) { + return false; + } + if (is6GhzInfoExist) { + int startIndx = VHT_OPER_INFO_BEGIN_INDEX + (isVhtInfoExist ? COLUMN_INDEX_THREE : 0) + + (coHostedBssPresent ? 1 : 0); + int heChannelWidth = content[startIndx + 1] & GHZ_HE_WIDTH_MASK_6; + int centerSegFreq0 = content[startIndx + COLUMN_INDEX_TWO] & UINT8_MASK; + int centerSegFreq1 = content[startIndx + COLUMN_INDEX_THREE] & UINT8_MASK; + pcmd->channelWidth = GetHeChanWidth(heChannelWidth, centerSegFreq0, centerSegFreq1); + pcmd->centerFrequency0 = GetHeCentFreq(centerSegFreq0); + pcmd->centerFrequency1 = GetHeCentFreq(centerSegFreq1); + return true; + } + if (isVhtInfoExist) { + struct ScanInfoElem vhtInformation = {0}; + vhtInformation.id = VHT_OPER_EID; + vhtInformation.size = VHT_INFO_SIZE; + vhtInformation.content = content + VHT_OPER_INFO_BEGIN_INDEX; + return GetChanWidthCenterFreqVht(pcmd, &vhtInformation); + } + return false; +} + +static bool GetChanWidthCenterFreqHt(ScanInfo *pcmd, ScanInfoElem* infoElem) +{ + const int offsetBit = 0x3; + if ((pcmd == NULL) || (infoElem == NULL)) { + LOGE("pcmd or infoElem is NULL."); + return false; + } + if ((infoElem->content == NULL) || ((unsigned int)infoElem->size < HT_INFO_SIZE)) { + return false; + } + int secondOffsetChannel = infoElem->content[1] & offsetBit; + pcmd->channelWidth = GetHtChanWidth(secondOffsetChannel); + pcmd->centerFrequency0 = GetHtCentFreq0(pcmd->freq, secondOffsetChannel); + return true; +} + +static void GetChanWidthCenterFreq(ScanInfo *pcmd, struct NeedParseIe* iesNeedParse) +{ + if ((pcmd == NULL) || (iesNeedParse == NULL)) { + LOGE("pcmd or iesNeedParse is NULL."); + return; + } + + if ((iesNeedParse->ieExtern != NULL) && GetChanWidthCenterFreqHe(pcmd, iesNeedParse->ieExtern)) { + return; + } + if ((iesNeedParse->ieVhtOper != NULL) && GetChanWidthCenterFreqVht(pcmd, iesNeedParse->ieVhtOper)) { + return; + } + if ((iesNeedParse->ieHtOper != NULL) && GetChanWidthCenterFreqHt(pcmd, iesNeedParse->ieHtOper)) { + return; + } + + LOGE("GetChanWidthCenterFreq fail."); + return; +} + +static void RecordIeNeedParse(unsigned int id, ScanInfoElem* ie, struct NeedParseIe* iesNeedParse) +{ + if (iesNeedParse == NULL) { + return; + } + switch (id) { + case EXT_EXIST_EID: + iesNeedParse->ieExtern = ie; + break; + case VHT_OPER_EID: + iesNeedParse->ieVhtOper = ie; + break; + case HT_OPER_EID: + iesNeedParse->ieHtOper = ie; + break; + default: + break; + } +} + +static void GetInfoElems(int length, int end, char *srcBuf, ScanInfo *pcmd) +{ + int len; + int start = end + 1; + int last = end + 1; + int lenValue = 2; + int lastLength = 3; + int remainingLength = length - start; + int infoElemsSize = 0; + struct NeedParseIe iesNeedParse = {NULL}; + ScanInfoElem* infoElemsTemp = (ScanInfoElem *)calloc(MAX_INFO_ELEMS_SIZE, sizeof(ScanInfoElem)); + if (infoElemsTemp == NULL) { + return; + } + while (remainingLength > 1) { + if (srcBuf[start] == '[') { + ++start; + infoElemsTemp[infoElemsSize].id = atoi(srcBuf + start); + } + if (srcBuf[start] != ' ') { + ++start; + } + if (srcBuf[last] != ']') { + ++last; + continue; + } + len = last - start - 1; + infoElemsTemp[infoElemsSize].size = len/lenValue; + infoElemsTemp[infoElemsSize].content = (char *)calloc(len/lenValue+1, sizeof(char)); + if (infoElemsTemp[infoElemsSize].content == NULL) { + break; + } + ++start; + srcBuf[last] = '\0'; + HexStringToString(srcBuf + start, infoElemsTemp[infoElemsSize].content); + if ((length - last) > lastLength) { // make sure there is no useless character + last = last + 1; + } + start = last; + remainingLength = length - last; + RecordIeNeedParse(infoElemsTemp[infoElemsSize].id, &infoElemsTemp[infoElemsSize], &iesNeedParse); + ++infoElemsSize; + } + GetChanWidthCenterFreq(pcmd, &iesNeedParse); + /* Do NOT report inforElement to up layer */ + if (infoElemsTemp != NULL) { + for (int i = 0; i < infoElemsSize; i++) { + if (infoElemsTemp[i].content != NULL) { + free(infoElemsTemp[i].content); + infoElemsTemp[i].content = NULL; + } + } + free(infoElemsTemp); + infoElemsTemp = NULL; + } + pcmd->infoElems = infoElemsTemp; + pcmd->ieSize = 0; + return; +} +#endif + static int DelScanInfoLine(ScanInfo *pcmd, char *srcBuf, int length) { - int i = 0; + int columnIndex = 0; int start = 0; int end = 0; int fail = 0; @@ -678,20 +1108,21 @@ static int DelScanInfoLine(ScanInfo *pcmd, char *srcBuf, int length) continue; } srcBuf[end] = '\0'; - if (i == 0) { + if (columnIndex == COLUMN_INDEX_ZERO) { if (strcpy_s(pcmd->bssid, sizeof(pcmd->bssid), srcBuf + start) != EOK) { fail = 1; break; } - } else if (i == 1) { + } else if (columnIndex == COLUMN_INDEX_ONE) { pcmd->freq = atoi(srcBuf + start); - } else if (i == SCAN_INFO_TWO) { + } else if (columnIndex == COLUMN_INDEX_TWO) { pcmd->siglv = atoi(srcBuf + start); - } else if (i == SCAN_INFO_THREE) { + } else if (columnIndex == COLUMN_INDEX_THREE) { if (strcpy_s(pcmd->flags, sizeof(pcmd->flags), srcBuf + start) != EOK) { fail = 1; break; } +#ifdef OHOS_ARCH_LITE // The wpa of arch lite don't return "informationElements". start = end + 1; if (strcpy_s(pcmd->ssid, sizeof(pcmd->ssid), srcBuf + start) != EOK) { fail = 1; @@ -700,8 +1131,19 @@ static int DelScanInfoLine(ScanInfo *pcmd, char *srcBuf, int length) printf_decode((u8 *)pcmd->ssid, sizeof(pcmd->ssid), pcmd->ssid); start = length; break; +#else + } else if (columnIndex == COLUMN_INDEX_FOUR) { + if (strcpy_s(pcmd->ssid, sizeof(pcmd->ssid), srcBuf + start) != EOK) { + fail = 1; + break; + } + printf_decode((u8 *)pcmd->ssid, sizeof(pcmd->ssid), pcmd->ssid); + GetInfoElems(length, end, srcBuf, pcmd); + start = length; + break; +#endif } - ++i; + ++columnIndex; ++end; start = end; } @@ -732,8 +1174,8 @@ static int WpaCliCmdScanInfo(WifiWpaStaInterface *this, ScanInfo *pcmd, int *siz return -1; } char *savedPtr = NULL; - char *token = strtok_r(buf, "\n", &savedPtr); /* skip first line */ - token = strtok_r(NULL, "\n", &savedPtr); + strtok_r(buf, "\n", &savedPtr); /* skip first line */ + char *token = strtok_r(NULL, "\n", &savedPtr); int j = 0; while (token != NULL) { if (j >= *size) { @@ -750,6 +1192,9 @@ static int WpaCliCmdScanInfo(WifiWpaStaInterface *this, ScanInfo *pcmd, int *siz LOGE("parse scan result line failed!"); break; } + LOGD("-->>%{public}2d %{public}s %{public}s %{public}d %{public}d %{public}d %{public}d %{public}d", + j, pcmd[j].ssid, pcmd[j].bssid, pcmd[j].freq, pcmd[j].siglv, + pcmd[j].centerFrequency0, pcmd[j].centerFrequency1, pcmd[j].channelWidth); token = strtok_r(NULL, "\n", &savedPtr); j++; } @@ -758,7 +1203,7 @@ static int WpaCliCmdScanInfo(WifiWpaStaInterface *this, ScanInfo *pcmd, int *siz return 0; } -static int WpaCliCmdGetSignalInfo(WifiWpaStaInterface *this, HidlWpaSignalInfo *info) +static int WpaCliCmdGetSignalInfo(WifiWpaStaInterface *this, WpaSignalInfo *info) { if (this == NULL || info == NULL) { return -1; @@ -792,7 +1237,7 @@ static int WpaCliCmdGetSignalInfo(WifiWpaStaInterface *this, HidlWpaSignalInfo * token = strtok_r(NULL, "\n", &savedPtr); info->frequency = atoi(token); } else { - token = strtok_r(NULL, "\n", &savedPtr); + strtok_r(NULL, "\n", &savedPtr); } token = strtok_r(NULL, "=", &savedPtr); } @@ -800,6 +1245,23 @@ static int WpaCliCmdGetSignalInfo(WifiWpaStaInterface *this, HidlWpaSignalInfo * return 0; } +static int WpaCliCmdWpaSetSuspendMode(WifiWpaStaInterface *this, bool mode) +{ + LOGI("Enter WpaCliCmdWpaSetSuspendMode, mode:%{public}d.", mode); + if (this == NULL) { + LOGE("WpaCliCmdWpaSetSuspendMode, this is NULL."); + return -1; + } + char cmd[CMD_BUFFER_SIZE] = {0}; + char buf[REPLY_BUF_SMALL_LENGTH] = {0}; + if (snprintf_s(cmd, sizeof(cmd), sizeof(cmd) - 1, "IFNAME=%s DRIVER SETSUSPENDMODE %d", + this->ifname, mode) < 0) { + LOGE("WpaCliCmdWpaSetSuspendMode, snprintf_s err"); + return -1; + } + return WpaCliCmd(cmd, buf, sizeof(buf)); +} + WifiWpaStaInterface *GetWifiStaInterface(int staNo) { char *name; @@ -837,6 +1299,7 @@ WifiWpaStaInterface *GetWifiStaInterface(int staNo) p->wpaCliCmdWpsPin = WpaCliCmdWpsPin; p->wpaCliCmdWpsCancel = WpaCliCmdWpsCancel; p->wpaCliCmdPowerSave = WpaCliCmdPowerSave; + p->wpaCliCmdSetRoamConfig = WpaCliCmdSetRoamConfig; p->wpaCliCmdSetCountryCode = WpaCliCmdSetCountryCode; p->wpaCliCmdGetCountryCode = WpaCliCmdGetCountryCode; p->wpaCliCmdSetAutoConnect = WpaCliCmdSetAutoConnect; @@ -845,6 +1308,7 @@ WifiWpaStaInterface *GetWifiStaInterface(int staNo) p->wpaCliCmdScan = WpaCliCmdScan; p->wpaCliCmdScanInfo = WpaCliCmdScanInfo; p->wpaCliCmdGetSignalInfo = WpaCliCmdGetSignalInfo; + p->wpaCliCmdWpaSetSuspendMode = WpaCliCmdWpaSetSuspendMode; p->next = g_wpaStaInterface; g_wpaStaInterface = p; diff --git a/services/wifi_standard/wifi_hal/wifi_hal_module/wpa_supplicant_hal/wpa_sta_hal/wifi_supplicant_hal.h b/wifi/services/wifi_standard/wifi_hal/wifi_hal_module/wpa_supplicant_hal/wpa_sta_hal/wifi_supplicant_hal.h similarity index 90% rename from services/wifi_standard/wifi_hal/wifi_hal_module/wpa_supplicant_hal/wpa_sta_hal/wifi_supplicant_hal.h rename to wifi/services/wifi_standard/wifi_hal/wifi_hal_module/wpa_supplicant_hal/wpa_sta_hal/wifi_supplicant_hal.h index 9941b657a9a82256ce9436d965509980644b1d75..0f8734160dc5414ea066789b21ef6ee9991f0935 100644 --- a/services/wifi_standard/wifi_hal/wifi_hal_module/wpa_supplicant_hal/wpa_sta_hal/wifi_supplicant_hal.h +++ b/wifi/services/wifi_standard/wifi_hal/wifi_hal_module/wpa_supplicant_hal/wpa_sta_hal/wifi_supplicant_hal.h @@ -20,6 +20,7 @@ #include #include #include +#include #include "wifi_hal_struct.h" #include "wifi_hal_define.h" @@ -64,6 +65,12 @@ struct WpaWpsPinArgv { char pinCode[WIFI_PIN_CODE_LENGTH + 1]; }; +struct NeedParseIe { + ScanInfoElem* ieExtern; + ScanInfoElem* ieVhtOper; + ScanInfoElem* ieHtOper; +}; + typedef struct WifiWpaStaInterface WifiWpaStaInterface; struct WifiWpaStaInterface { int staNo; @@ -86,14 +93,16 @@ struct WifiWpaStaInterface { int (*wpaCliCmdWpsPin)(WifiWpaStaInterface *p, const struct WpaWpsPinArgv *wpspin, int *pincode); int (*wpaCliCmdWpsCancel)(WifiWpaStaInterface *p); int (*wpaCliCmdPowerSave)(WifiWpaStaInterface *p, int enable); + int (*wpaCliCmdSetRoamConfig)(WifiWpaStaInterface *p, const char *bssid); int (*wpaCliCmdSetCountryCode)(WifiWpaStaInterface *p, const char *countryCode); int (*wpaCliCmdGetCountryCode)(WifiWpaStaInterface *p, char *countryCode, int codeSize); int (*wpaCliCmdSetAutoConnect)(WifiWpaStaInterface *p, int enable); int (*wpaCliCmdWpaBlockListClear)(WifiWpaStaInterface *p); - int (*wpaCliCmdListNetworks)(WifiWpaStaInterface *p, HidlNetworkInfo *pcmd, int *size); + int (*wpaCliCmdListNetworks)(WifiWpaStaInterface *p, WifiNetworkInfo *pcmd, int *size); int (*wpaCliCmdScan)(WifiWpaStaInterface *p, const ScanSettings *settings); int (*wpaCliCmdScanInfo)(WifiWpaStaInterface *p, ScanInfo *pcmd, int *size); - int (*wpaCliCmdGetSignalInfo)(WifiWpaStaInterface *p, HidlWpaSignalInfo *info); + int (*wpaCliCmdGetSignalInfo)(WifiWpaStaInterface *p, WpaSignalInfo *info); + int (*wpaCliCmdWpaSetSuspendMode)(WifiWpaStaInterface *p, bool mode); }; /** diff --git a/services/wifi_standard/wifi_hal/wifi_hal_module_manage.c b/wifi/services/wifi_standard/wifi_hal/wifi_hal_module_manage.c old mode 100755 new mode 100644 similarity index 69% rename from services/wifi_standard/wifi_hal/wifi_hal_module_manage.c rename to wifi/services/wifi_standard/wifi_hal/wifi_hal_module_manage.c index e7fcf3eefa6fc9b0f72d3f66b9ab1d2e86d8e7e9..5b2ddb29d6803a1f985c0015a6e6b5c73919c532 --- a/services/wifi_standard/wifi_hal/wifi_hal_module_manage.c +++ b/wifi/services/wifi_standard/wifi_hal/wifi_hal_module_manage.c @@ -1,5 +1,5 @@ /* - * Copyright (C) 2021 Huawei Device Co., Ltd. + * Copyright (C) 2021-2022 Huawei Device Co., Ltd. * 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 @@ -12,6 +12,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + #include "wifi_hal_module_manage.h" #include #include @@ -19,19 +20,21 @@ #include #include #include +#include #include #include -#include "wifi_log.h" #include "securec.h" +#include "wifi_hal_define.h" +#include "wifi_log.h" +#include "wifi_wpa_hal.h" #undef LOG_TAG #define LOG_TAG "WifiHalModuleManage" static ModuleInfo *g_halModuleList = NULL; -#define STOP_MODULE_TRY_TIMES 3 #define MAX_WPA_MAIN_ARGC_NUM 20 -#define MAX_WPA_MAIN_ARGV_LEN 64 +#define MAX_WPA_MAIN_ARGV_LEN 128 struct StWpaMainParam { int argc; @@ -86,7 +89,15 @@ static void *WpaThreadMain(void *p) const char *startCmd = (const char *)p; struct StWpaMainParam param = {0}; SplitCmdString(startCmd, ¶m); +#ifdef OHOS_ARCH_LITE + void *handleLibWpa = dlopen("libwpa.so", RTLD_NOW | RTLD_LOCAL); +#else +#ifdef __aarch64__ + void *handleLibWpa = dlopen("/system/lib64/libwpa.z.so", RTLD_NOW | RTLD_LOCAL); +#else void *handleLibWpa = dlopen("/system/lib/libwpa.z.so", RTLD_NOW | RTLD_LOCAL); +#endif +#endif if (handleLibWpa == NULL) { LOGE("dlopen libwpa failed."); return NULL; @@ -118,57 +129,93 @@ static void *WpaThreadMain(void *p) int StartModuleInternal(const char *moduleName, const char *startCmd, pid_t *pProcessId) { if (moduleName == NULL || startCmd == NULL || pProcessId == NULL) { - return -1; + return HAL_FAILURE; } pid_t pid = fork(); if (pid < 0) { LOGE("Create wpa process failed!"); - return -1; + return HAL_FAILURE; } if (pid == 0) { /* sub process */ + // The child process will receive the exit signal when the parent process exits. + prctl(PR_SET_PDEATHSIG, SIGKILL); pthread_t tid; int ret = pthread_create(&tid, NULL, WpaThreadMain, (void *)startCmd); if (ret != 0) { LOGE("Create wpa thread failed!"); - return -1; + return HAL_FAILURE; } pthread_join(tid, NULL); exit(0); } else { LOGE("Create wpa process id is [%{public}d]", pid); - sleep(1); *pProcessId = pid; } - return 0; + return HAL_SUCCESS; +} + +static int StopModuleInternalKillProcess(pid_t processId) +{ + LOGI("Stop module kill process: %{public}d", processId); + if (kill(processId, SIGTERM) == -1) { + if (ESRCH == errno) { + LOGI("kill [%{public}d] success, pid no exist", processId); + return HAL_SUCCESS; + } + LOGE("kill [%{public}d] failed", processId); + return HAL_FAILURE; + } + return HAL_SUCCESS; } -int StopModuleInternal(const char *moduleName, pid_t processId) +static int StopModuleInternalCheckProcess(const char *moduleName, pid_t processId) { if (moduleName == NULL) { - return 0; + return HAL_SUCCESS; } + LOGI("Stop module internal check wpa process: %{public}d", processId); + const int STOP_MODULE_TRY_TIMES = 30; + const int SLEEP_TIME_US = 1000 * 100; // 100ms int tryTimes = STOP_MODULE_TRY_TIMES; while (tryTimes-- >= 0) { - if (kill(processId, SIGTERM) == -1) { - if (ESRCH == errno) { - LOGI("kill [%{public}d] success, pid no exist", processId); - return 0; - } - LOGE("kill [%{public}d] failed", processId); - return -1; - } - sleep(1); int ret = waitpid(processId, NULL, WNOHANG); if (ret <= 0) { - LOGI("Waitpid %{public}d return %{public}d, and retry", processId, ret); + LOGI("Waitpid %{public}d ret %{public}d, tryTimes %{public}d and retry", processId, ret, tryTimes); + usleep(SLEEP_TIME_US); continue; } else { - LOGD("waitpid [%{public}d] success", processId); - return 0; + LOGI("Stop wpa process [%{public}d] success, tryTimes %{public}d", processId, tryTimes); + return HAL_SUCCESS; } } - LOGE("stop [%{public}d] failed, cannot send SIGTERM signal to stop process", processId); - return -1; + LOGE("Stop wpa process [%{public}d] failed for timeout, try to kill process", processId); + StopModuleInternalKillProcess(processId); + return HAL_SUCCESS; +} + +static int StopModuleInternalSendTerminate(void) +{ + WifiWpaInterface *pWpaInterface = GetWifiWapGlobalInterface(); + if (pWpaInterface == NULL) { + LOGE("Get wpa global interface failed!"); + return HAL_FAILURE; + } + int ret = pWpaInterface->wpaCliTerminate(pWpaInterface); + return (ret == 0 ? HAL_SUCCESS : HAL_FAILURE); +} + +int StopModuleInternal(const char *moduleName, pid_t processId, bool isHostapd) +{ + int ret; + if (isHostapd) { + ret = StopModuleInternalKillProcess(processId); + } else { + ret = StopModuleInternalSendTerminate(); + } + if (ret != HAL_SUCCESS) { + LOGE("Send stop module command failed!"); + } + return StopModuleInternalCheckProcess(moduleName, processId); } ModuleInfo *FindModule(const char *moduleName) @@ -204,11 +251,13 @@ ModuleManageRetCode StartModule(const char *moduleName, const char *startCmd) } if (strcpy_s(p->szModuleName, sizeof(p->szModuleName), moduleName) != EOK) { free(p); + p = NULL; return MM_FAILED; } int ret = StartModuleInternal(moduleName, startCmd, &(p->processId)); if (ret != 0) { /* start module failed! */ free(p); + p = NULL; return MM_FAILED; } p->referenceCount = 1; @@ -217,7 +266,7 @@ ModuleManageRetCode StartModule(const char *moduleName, const char *startCmd) return MM_SUCCESS; } -ModuleManageRetCode StopModule(const char *moduleName) +ModuleManageRetCode StopModule(const char *moduleName, bool isHostapd) { if (moduleName == NULL) { return MM_FAILED; @@ -231,7 +280,7 @@ ModuleManageRetCode StopModule(const char *moduleName) LOGD("module %{public}s reference left %{public}d, return ok", moduleName, p->referenceCount); return MM_REDUCE_REFERENCE; } - int ret = StopModuleInternal(p->szModuleName, p->processId); + int ret = StopModuleInternal(p->szModuleName, p->processId, isHostapd); if (ret != 0) { /* stop module failed! */ p->referenceCount += 1; return MM_FAILED; @@ -248,5 +297,6 @@ ModuleManageRetCode StopModule(const char *moduleName) } } free(p); + p = NULL; return MM_SUCCESS; } diff --git a/services/wifi_standard/wifi_hal/wifi_hal_module_manage.h b/wifi/services/wifi_standard/wifi_hal/wifi_hal_module_manage.h similarity index 93% rename from services/wifi_standard/wifi_hal/wifi_hal_module_manage.h rename to wifi/services/wifi_standard/wifi_hal/wifi_hal_module_manage.h index 2789213763982ec164744cbd22d5d2d0156d77f9..b3a7c18d4edbc009fd2fc3f4422116c6809c2c4e 100644 --- a/services/wifi_standard/wifi_hal/wifi_hal_module_manage.h +++ b/wifi/services/wifi_standard/wifi_hal/wifi_hal_module_manage.h @@ -17,6 +17,7 @@ #define OHOS_WIFI_HAL_MODULE_MANAGE_H #include +#include #ifdef __cplusplus extern "C" { @@ -58,10 +59,10 @@ ModuleManageRetCode StartModule(const char *moduleName, const char *startCmd); * @Description Stop a specified service. * * @param moduleName - * @param modulePropertyName + * @param isHostapd * @return ModuleManageRetCode */ -ModuleManageRetCode StopModule(const char *moduleName); +ModuleManageRetCode StopModule(const char *moduleName, bool isHostapd); #ifdef __cplusplus } diff --git a/services/wifi_standard/wifi_hal/wifi_hal_p2p_interface.c b/wifi/services/wifi_standard/wifi_hal/wifi_hal_p2p_interface.c similarity index 93% rename from services/wifi_standard/wifi_hal/wifi_hal_p2p_interface.c rename to wifi/services/wifi_standard/wifi_hal/wifi_hal_p2p_interface.c index 53f262358c0020b45e194f5ee1bb7e11e7791838..9c6281679375a91f55cbe5256486dd5d7b9a7a03 100644 --- a/services/wifi_standard/wifi_hal/wifi_hal_p2p_interface.c +++ b/wifi/services/wifi_standard/wifi_hal/wifi_hal_p2p_interface.c @@ -1,5 +1,5 @@ /* - * Copyright (C) 2021 Huawei Device Co., Ltd. + * Copyright (C) 2021-2022 Huawei Device Co., Ltd. * 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 @@ -14,26 +14,37 @@ */ #include "wifi_hal_p2p_interface.h" -#include "wifi_log.h" -#include "wifi_wpa_hal.h" -#include "wifi_p2p_hal.h" +#include "securec.h" +#include "wifi_common_def.h" +#include "wifi_hal_adapter.h" #include "wifi_hal_callback.h" -#include "wifi_hal_module_manage.h" #include "wifi_hal_common_func.h" -#include "wifi_hal_adapter.h" -#include "securec.h" +#include "wifi_hal_module_manage.h" +#include "wifi_log.h" +#include "wifi_p2p_hal.h" +#include "wifi_wpa_hal.h" #undef LOG_TAG #define LOG_TAG "WifiHalP2pInterface" const int P2P_CONNECT_DELAY_TIME = 100000; -const char *g_wpaSupplicantP2p = "wpa_supplicant"; -const char *g_systemCmdWpaP2pStart = "wpa_supplicant -iglan0 -g/data/misc/wifi/sockets"; + +#ifdef NON_SEPERATE_P2P +#define P2P_START_CMD "wpa_supplicant -iglan0 -g"CONFIG_ROOR_DIR"/sockets/wpa"\ + " -m "CONFIG_ROOR_DIR"/wpa_supplicant/p2p_supplicant.conf" +#else +#define P2P_START_CMD "wpa_supplicant -iglan0 -g"CONFIG_ROOR_DIR"/sockets/wpa" +#endif + static int g_p2pSupplicantConnectEvent = 0; static WifiErrorNo P2pStartSupplicant(void) { - ModuleManageRetCode ret = StartModule(g_wpaSupplicantP2p, g_systemCmdWpaP2pStart); + LOGD("Start p2p supplicant"); + if (CopyConfigFile("p2p_supplicant.conf") != 0) { + return WIFI_HAL_FAILED; + } + ModuleManageRetCode ret = StartModule(WPA_SUPPLICANT_NAME, P2P_START_CMD); if (ret == MM_SUCCESS) { return WIFI_HAL_SUCCESS; } @@ -53,7 +64,7 @@ static WifiErrorNo P2pConnectSupplicant(void) static WifiErrorNo P2pStopSupplicant(void) { - ModuleManageRetCode ret = StopModule(g_wpaSupplicantP2p); + ModuleManageRetCode ret = StopModule(WPA_SUPPLICANT_NAME, false); if (ret == MM_FAILED) { LOGE("stop p2p_wpa_supplicant failed!"); return WIFI_HAL_FAILED; @@ -82,7 +93,11 @@ static WifiErrorNo StopP2pWpaAndWpaHal(void) } WifiWpaInterface *pWpaInterface = GetWifiWapGlobalInterface(); if (pWpaInterface != NULL) { +#ifdef NON_SEPERATE_P2P + pWpaInterface->wpaCliRemoveIface(pWpaInterface, "p2p-dev-wlan0"); +#else pWpaInterface->wpaCliRemoveIface(pWpaInterface, "p2p0"); +#endif } if (P2pStopSupplicant() != WIFI_HAL_SUCCESS) { LOGE("p2p_wpa_supplicant stop failed!"); @@ -105,11 +120,19 @@ static WifiErrorNo AddP2pIface(void) return WIFI_HAL_FAILED; } AddInterfaceArgv argv; +#ifdef NON_SEPERATE_P2P + if (strcpy_s(argv.name, sizeof(argv.name), "p2p-dev-wlan0") != EOK || +#else if (strcpy_s(argv.name, sizeof(argv.name), "p2p0") != EOK || - strcpy_s(argv.confName, sizeof(argv.confName), "/data/misc/wifi/wpa_supplicant/p2p_supplicant.conf") != EOK) { +#endif + strcpy_s(argv.confName, sizeof(argv.confName), CONFIG_ROOR_DIR"/wpa_supplicant/p2p_supplicant.conf") != EOK) { return WIFI_HAL_FAILED; } - if (pWpaInterface->wpaCliAddIface(pWpaInterface, &argv) < 0) { +#ifdef NON_SEPERATE_P2P + if (pWpaInterface->wpaCliAddIface(pWpaInterface, &argv, false) < 0) { +#else + if (pWpaInterface->wpaCliAddIface(pWpaInterface, &argv, true) < 0) { +#endif LOGE("Failed to add wpa iface!"); return WIFI_HAL_FAILED; } @@ -418,7 +441,7 @@ WifiErrorNo P2pRemoveNetwork(int networkId) return WIFI_HAL_SUCCESS; } -WifiErrorNo P2pListNetworks(HidlP2pNetworkList *infoList) +WifiErrorNo P2pListNetworks(P2pNetworkList *infoList) { if (infoList == NULL) { LOGE("P2pListNetworks infoList is NULL"); @@ -577,7 +600,7 @@ WifiErrorNo P2pSetListenChannel(int channel, int regClass) return WIFI_HAL_SUCCESS; } -WifiErrorNo P2pConnect(HidlP2pConnectInfo *info) +WifiErrorNo P2pConnect(P2pConnectInfo *info) { if (info == NULL) { LOGE("P2pConnect, info is NULL"); @@ -731,7 +754,7 @@ WifiErrorNo P2pGetGroupCapability(const char *bssid, int *cap) LOGE("P2pReinvoke, bssid or cap is NULL"); return WIFI_HAL_FAILED; } - HidlP2pDeviceInfo info; + P2pDeviceInfo info; if (memset_s(&info, sizeof(info), 0, sizeof(info)) != EOK) { LOGE("Failed to init p2p device info"); return WIFI_HAL_FAILED; @@ -749,7 +772,7 @@ WifiErrorNo P2pGetGroupCapability(const char *bssid, int *cap) return WIFI_HAL_SUCCESS; } -WifiErrorNo P2pAddService(const HidlP2pServiceInfo *info) +WifiErrorNo P2pAddService(const P2pServiceInfo *info) { if (info == NULL) { LOGE("P2pAddService, input service info is NULL"); @@ -768,7 +791,7 @@ WifiErrorNo P2pAddService(const HidlP2pServiceInfo *info) return WIFI_HAL_SUCCESS; } -WifiErrorNo P2pRemoveService(const HidlP2pServiceInfo *info) +WifiErrorNo P2pRemoveService(const P2pServiceInfo *info) { if (info == NULL) { LOGE("P2pRemoveService, input service info is NULL"); @@ -842,7 +865,7 @@ WifiErrorNo P2pSetMiracastType(int type) return ConvertErrorCode(err); } -WifiErrorNo P2pRespServerDiscovery(HidlP2pServDiscReqInfo *info) +WifiErrorNo P2pRespServerDiscovery(P2pServDiscReqInfo *info) { if (info == NULL) { LOGE("P2pRespServerDiscovery, info is NULL"); @@ -891,7 +914,7 @@ WifiErrorNo P2pSetPersistentReconnect(int mode) return WIFI_HAL_SUCCESS; } -WifiErrorNo P2pGetPeer(const char *bssid, HidlP2pDeviceInfo *peerInfo) +WifiErrorNo P2pGetPeer(const char *bssid, P2pDeviceInfo *peerInfo) { if (bssid == NULL || peerInfo == NULL) { LOGE("P2pGetPeer, bssid, peer info struct have NULL"); @@ -919,7 +942,7 @@ WifiErrorNo P2pGetFrequencies(int band, int *frequencies, int *size) return WIFI_HAL_NOT_SUPPORT; } -WifiErrorNo P2pSetGroupConfig(int networkId, HidlP2pGroupConfig *pConfig, int size) +WifiErrorNo P2pSetGroupConfig(int networkId, P2pGroupConfig *pConfig, int size) { if (pConfig == NULL || size == 0) { LOGE("P2pSetGroupConfig() confs is NULL"); @@ -949,7 +972,7 @@ WifiErrorNo P2pSetGroupConfig(int networkId, HidlP2pGroupConfig *pConfig, int si return WIFI_HAL_SUCCESS; } -WifiErrorNo P2pGetGroupConfig(int networkId, HidlP2pGroupConfig *pConfig, int size) +WifiErrorNo P2pGetGroupConfig(int networkId, P2pGroupConfig *pConfig, int size) { if (pConfig == NULL || size == 0) { LOGE("P2pGetGroupConfig() confs is NULL"); @@ -995,3 +1018,22 @@ WifiErrorNo P2pAddNetwork(int *networkId) } return WIFI_HAL_SUCCESS; } + +WifiErrorNo P2pHid2dConnect(Hid2dConnectInfo *info) +{ + if (info == NULL) { + LOGE("P2pHid2dConnect, info is NULL"); + return WIFI_HAL_FAILED; + } + LOGD("P2pHid2dConnect"); + WifiWpaP2pInterface *pMainIfc = GetWifiWapP2pInterface(); + if (pMainIfc == NULL) { + return WIFI_HAL_SUPPLICANT_NOT_INIT; + } + P2pSupplicantErrCode ret = pMainIfc->wpaP2pCliCmdHid2dConnect(pMainIfc, info); + if (ret != P2P_SUP_ERRCODE_SUCCESS) { + LOGE("wpaP2pHid2dCliCmdConnect fail, ret = %{public}d", ret); + return ConvertP2pErrCode(ret); + } + return WIFI_HAL_SUCCESS; +} diff --git a/services/wifi_standard/wifi_hal/wifi_hal_p2p_interface.h b/wifi/services/wifi_standard/wifi_hal/wifi_hal_p2p_interface.h similarity index 90% rename from services/wifi_standard/wifi_hal/wifi_hal_p2p_interface.h rename to wifi/services/wifi_standard/wifi_hal/wifi_hal_p2p_interface.h index 38152393d3f1ac140aaf669a768bb3e62c86f3a3..865d38b5225f3e5da5d0cd4beefd739924eadec0 100644 --- a/services/wifi_standard/wifi_hal/wifi_hal_p2p_interface.h +++ b/wifi/services/wifi_standard/wifi_hal/wifi_hal_p2p_interface.h @@ -1,5 +1,5 @@ /* - * Copyright (C) 2021 Huawei Device Co., Ltd. + * Copyright (C) 2021-2022 Huawei Device Co., Ltd. * 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 @@ -165,7 +165,7 @@ WifiErrorNo P2pRemoveNetwork(int networkId); * * @return WifiErrorNo */ -WifiErrorNo P2pListNetworks(HidlP2pNetworkList *infoList); +WifiErrorNo P2pListNetworks(P2pNetworkList *infoList); /** * @Description Set the maximum idle time of a group. @@ -241,7 +241,7 @@ WifiErrorNo P2pSetListenChannel(int channel, int regClass); * @param info * @return WifiErrorNo */ -WifiErrorNo P2pConnect(HidlP2pConnectInfo *info); +WifiErrorNo P2pConnect(P2pConnectInfo *info); /** * @Description Cancel the ongoing P2P group and join the group. @@ -280,12 +280,13 @@ WifiErrorNo P2pRemoveGroup(const char *interface); /** * @Description Inviting a Device to Join a Persistent Group. * + * @param persistent * @param peerBssid * @param goBssid * @param ifname * @return WifiErrorNo */ -WifiErrorNo P2pInvite(int persisitent, const char *peerBssid, const char *goBssid, const char *ifname); +WifiErrorNo P2pInvite(int persistent, const char *peerBssid, const char *goBssid, const char *ifname); /** * @Description persistent group Reinvoke peer @@ -311,7 +312,7 @@ WifiErrorNo P2pGetGroupCapability(const char *bssid, int *cap); * @param info * @return WifiErrorNo */ -WifiErrorNo P2pAddService(const HidlP2pServiceInfo *info); +WifiErrorNo P2pAddService(const P2pServiceInfo *info); /** * @Description Deleting an UPNP/Bonjour Service @@ -319,7 +320,7 @@ WifiErrorNo P2pAddService(const HidlP2pServiceInfo *info); * @param info * @return WifiErrorNo */ -WifiErrorNo P2pRemoveService(const HidlP2pServiceInfo *info); +WifiErrorNo P2pRemoveService(const P2pServiceInfo *info); /** * @Description Initiate a ServiceDiscovery request. @@ -352,7 +353,7 @@ WifiErrorNo P2pSetMiracastType(int type); * @param info * @return WifiErrorNo */ -WifiErrorNo P2pRespServerDiscovery(HidlP2pServDiscReqInfo *info); +WifiErrorNo P2pRespServerDiscovery(P2pServDiscReqInfo *info); /** * @Description P2p Set Service Discovery External @@ -377,7 +378,7 @@ WifiErrorNo P2pSetPersistentReconnect(int mode); * @param device * @return WifiErrorNo */ -WifiErrorNo P2pGetPeer(const char *bssid, HidlP2pDeviceInfo *peerInfo); +WifiErrorNo P2pGetPeer(const char *bssid, P2pDeviceInfo *peerInfo); /** * @Description Obtains the frequencies supported by a specified frequency band. @@ -398,7 +399,7 @@ WifiErrorNo P2pGetFrequencies(int band, int *frequencies, int *size); * @param size * @return WifiErrorNo */ -WifiErrorNo P2pSetGroupConfig(int networkId, HidlP2pGroupConfig *pConfig, int size); +WifiErrorNo P2pSetGroupConfig(int networkId, P2pGroupConfig *pConfig, int size); /** * @Description Getting the P2P group config. @@ -408,7 +409,7 @@ WifiErrorNo P2pSetGroupConfig(int networkId, HidlP2pGroupConfig *pConfig, int si * @param size * @return WifiErrorNo */ -WifiErrorNo P2pGetGroupConfig(int networkId, HidlP2pGroupConfig *pConfig, int size); +WifiErrorNo P2pGetGroupConfig(int networkId, P2pGroupConfig *pConfig, int size); /** * @Description Add Network interface. @@ -418,6 +419,14 @@ WifiErrorNo P2pGetGroupConfig(int networkId, HidlP2pGroupConfig *pConfig, int si */ WifiErrorNo P2pAddNetwork(int *networkId); +/** + * @Description Connect + * + * @param info - connection information + * @return WifiErrorNo + */ +WifiErrorNo P2pHid2dConnect(Hid2dConnectInfo *info); + #ifdef __cplusplus } #endif diff --git a/services/wifi_standard/wifi_hal/wifi_hal_p2p_struct.h b/wifi/services/wifi_standard/wifi_hal/wifi_hal_p2p_struct.h similarity index 82% rename from services/wifi_standard/wifi_hal/wifi_hal_p2p_struct.h rename to wifi/services/wifi_standard/wifi_hal/wifi_hal_p2p_struct.h index 58ca3f44239f203f5933131542321f37e128e880..1114fe327ed518310caf20f64f181e1ffe374738 100644 --- a/services/wifi_standard/wifi_hal/wifi_hal_p2p_struct.h +++ b/wifi/services/wifi_standard/wifi_hal/wifi_hal_p2p_struct.h @@ -1,5 +1,5 @@ /* - * Copyright (C) 2021 Huawei Device Co., Ltd. + * Copyright (C) 2021-2022 Huawei Device Co., Ltd. * 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 @@ -36,7 +36,7 @@ typedef enum P2pSupplicantErrCode { #define WIFI_P2P_WFD_DEVICE_INFO_LENGTH 32 #define WIFI_P2P_PASSWORD_SIZE 128 -typedef struct HidlP2pDeviceInfo { +typedef struct P2pDeviceInfo { short configMethods; int deviceCapabilities; int groupCapabilities; @@ -46,9 +46,10 @@ typedef struct HidlP2pDeviceInfo { char primaryDeviceType[WIFI_P2P_DEVICE_TYPE_LENGTH]; char deviceName[WIFI_P2P_DEVICE_NAME_LENGTH]; char wfdDeviceInfo[WIFI_P2P_WFD_DEVICE_INFO_LENGTH]; -} HidlP2pDeviceInfo; + char operSsid[WIFI_P2P_DEVICE_NAME_LENGTH]; +} P2pDeviceInfo; -typedef struct HidlP2pGroupInfo { +typedef struct P2pGroupInfo { int isGo; int isPersistent; int frequency; @@ -57,64 +58,64 @@ typedef struct HidlP2pGroupInfo { char psk[WIFI_P2P_PASSWORD_SIZE]; char passphrase[WIFI_P2P_PASSWORD_SIZE]; char goDeviceAddress[WIFI_BSSID_LENGTH]; -} HidlP2pGroupInfo; +} P2pGroupInfo; -typedef struct HidlP2pInvitationInfo { +typedef struct P2pInvitationInfo { int type; int persistentNetworkId; int operatingFrequency; char srcAddress[WIFI_BSSID_LENGTH]; char goDeviceAddress[WIFI_BSSID_LENGTH]; char bssid[WIFI_BSSID_LENGTH]; -} HidlP2pInvitationInfo; +} P2pInvitationInfo; -typedef struct HidlP2pServDiscRespInfo { +typedef struct P2pServDiscRespInfo { short updateIndicator; char srcAddress[WIFI_BSSID_LENGTH]; char *tlvs; -} HidlP2pServDiscRespInfo; +} P2pServDiscRespInfo; -typedef struct HidlP2pConnectInfo { +typedef struct P2pConnectInfo { int persistent; // persistent=] int mode; // [join|auth] int goIntent; // [go_intent=<0..15>] int provdisc; // [provdisc] char peerDevAddr[WIFI_BSSID_LENGTH]; char pin[WIFI_PIN_CODE_LENGTH + 1]; // -} HidlP2pConnectInfo; +} P2pConnectInfo; -typedef struct HidlP2pNetworkInfo { +typedef struct P2pNetworkInfo { int id; char ssid[WIFI_SSID_LENGTH]; char bssid[WIFI_BSSID_LENGTH]; char flags[WIFI_NETWORK_FLAGS_LENGTH]; -} HidlP2pNetworkInfo; +} P2pNetworkInfo; -typedef struct HidlP2pNetworkList { +typedef struct P2pNetworkList { int infoNum; - HidlP2pNetworkInfo *infos; -} HidlP2pNetworkList; + P2pNetworkInfo *infos; +} P2pNetworkList; -typedef struct HidlP2pServDiscReqInfo { +typedef struct P2pServDiscReqInfo { int freq; int dialogToken; int updateIndic; char mac[WIFI_BSSID_LENGTH]; char *tlvs; -} HidlP2pServDiscReqInfo; +} P2pServDiscReqInfo; -typedef struct HidlP2pServiceInfo { +typedef struct P2pServiceInfo { int mode; /* 0/1, upnp/bonjour */ int version; char name[WIFI_P2P_SERVER_NAME_LENGTH]; char query[WIFI_P2P_SERVE_INFO_LENGTH]; char resp[WIFI_P2P_SERVE_INFO_LENGTH]; -} HidlP2pServiceInfo; +} P2pServiceInfo; -typedef struct HidlP2pGroupConfig { +typedef struct P2pGroupConfig { P2pGroupConfigType cfgParam; /* param */ char cfgValue[WIFI_P2P_GROUP_CONFIG_VALUE_LENGTH]; /* param value */ -} HidlP2pGroupConfig; +} P2pGroupConfig; typedef struct P2pWpsPinDisplayArgv { int mode; /* 0/1 : PIN_KEYPAD/PIN_DISPLAY */ @@ -145,7 +146,14 @@ typedef struct P2pWpaGroupConfigArgv { char value[WIFI_P2P_GROUP_CONFIG_VALUE_LENGTH]; /* set network value */ } P2pWpaGroupConfigArgv; +typedef struct Hid2dConnectInfo { + char ssid[WIFI_SSID_LENGTH]; + char bssid[WIFI_BSSID_LENGTH]; + char passphrase[WIFI_P2P_PASSWORD_SIZE]; + int frequency; +} Hid2dConnectInfo; + #ifdef __cplusplus } #endif -#endif \ No newline at end of file +#endif diff --git a/services/wifi_standard/wifi_hal/wifi_hal_sta_interface.c b/wifi/services/wifi_standard/wifi_hal/wifi_hal_sta_interface.c similarity index 86% rename from services/wifi_standard/wifi_hal/wifi_hal_sta_interface.c rename to wifi/services/wifi_standard/wifi_hal/wifi_hal_sta_interface.c index 5b9b6c44f1adc47df205367838582e14f038d62c..36a9a0c2607d20a6a94bd6cefb4e625ab9654379 100644 --- a/services/wifi_standard/wifi_hal/wifi_hal_sta_interface.c +++ b/wifi/services/wifi_standard/wifi_hal/wifi_hal_sta_interface.c @@ -1,5 +1,5 @@ /* - * Copyright (C) 2021 Huawei Device Co., Ltd. + * Copyright (C) 2021-2022 Huawei Device Co., Ltd. * 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 @@ -12,42 +12,28 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + #include "wifi_hal_sta_interface.h" #include "securec.h" +#include "wifi_common_def.h" #include "wifi_hal_adapter.h" #include "wifi_hal_module_manage.h" +#ifdef HDI_INTERFACE_SUPPORT +#include "wifi_hdi_proxy.h" +#endif #include "wifi_log.h" -#include "wifi_wpa_hal.h" #include "wifi_supplicant_hal.h" +#include "wifi_wpa_hal.h" #undef LOG_TAG -#define LOG_TAG "WifHalStaInterface" -#define BUFF_SIZE 1024 -#define WPA_CMD_STOP_LENG 64 -#define WPA_TRY_CONNECT_SLEEP_TIME (100 * 1000) /* 100ms */ - -static const char *g_serviceName = "wpa_supplicant"; -static const char *g_startCmd = "wpa_supplicant -iglan0 -g/data/misc/wifi/sockets"; - -static int ExcuteStaCmd(const char *szCmd) -{ - int ret = system(szCmd); - if (ret == -1) { - LOGE("system cmd %{public}s failed!", szCmd); - } else { - if (WIFEXITED(ret)) { - if (WEXITSTATUS(ret) == 0) { - return 0; - } - LOGE("system cmd %{public}s failed, return status %{public}d", szCmd, WEXITSTATUS(ret)); - } else { - LOGE("system cmd %{public}s failed", szCmd); - } - } - - return -1; -} +#define LOG_TAG "WifiHalStaInterface" +#ifdef NON_SEPERATE_P2P +#define START_CMD "wpa_supplicant -iglan0 -g"CONFIG_ROOR_DIR"/sockets/wpa"\ + " -m"CONFIG_ROOR_DIR"/wpa_supplicant/p2p_supplicant.conf" +#else +#define START_CMD "wpa_supplicant -iglan0 -g"CONFIG_ROOR_DIR"/sockets/wpa" +#endif static WifiErrorNo AddWpaIface(int staNo) { @@ -63,16 +49,16 @@ static WifiErrorNo AddWpaIface(int staNo) AddInterfaceArgv argv; if (staNo == 0) { if (strcpy_s(argv.name, sizeof(argv.name), "wlan0") != EOK || strcpy_s(argv.confName, sizeof(argv.confName), - "/data/misc/wifi/wpa_supplicant/wpa_supplicant.conf") != EOK) { + CONFIG_ROOR_DIR"/wpa_supplicant/wpa_supplicant.conf") != EOK) { return WIFI_HAL_FAILED; } } else { if (strcpy_s(argv.name, sizeof(argv.name), "wlan2") != EOK || strcpy_s(argv.confName, sizeof(argv.confName), - "/data/misc/wifi/wpa_supplicant/wpa_supplicant.conf") != EOK) { + CONFIG_ROOR_DIR"/wpa_supplicant/wpa_supplicant.conf") != EOK) { return WIFI_HAL_FAILED; } } - if (pWpaInterface->wpaCliAddIface(pWpaInterface, &argv) < 0) { + if (pWpaInterface->wpaCliAddIface(pWpaInterface, &argv, true) < 0) { LOGE("Failed to add wpa iface!"); return WIFI_HAL_FAILED; } @@ -81,17 +67,18 @@ static WifiErrorNo AddWpaIface(int staNo) static WifiErrorNo RemoveWpaIface(int staNo) { + int ret = -1; WifiWpaInterface *pWpaInterface = GetWifiWapGlobalInterface(); if (pWpaInterface == NULL) { LOGE("Get wpa interface failed!"); return WIFI_HAL_FAILED; } if (staNo == 0) { - pWpaInterface->wpaCliRemoveIface(pWpaInterface, "wlan0"); + ret = pWpaInterface->wpaCliRemoveIface(pWpaInterface, "wlan0"); } else { - pWpaInterface->wpaCliRemoveIface(pWpaInterface, "wlan2"); + ret = pWpaInterface->wpaCliRemoveIface(pWpaInterface, "wlan2"); } - return WIFI_HAL_SUCCESS; + return (ret == 0 ? WIFI_HAL_SUCCESS : WIFI_HAL_FAILED); } static WifiErrorNo StopWpaAndWpaHal(int staNo) @@ -99,26 +86,28 @@ static WifiErrorNo StopWpaAndWpaHal(int staNo) if (DisconnectSupplicant() != WIFI_HAL_SUCCESS) { LOGE("wpa_s hal already stop!"); } - RemoveWpaIface(staNo); + + if (RemoveWpaIface(staNo) != WIFI_HAL_SUCCESS) { + LOGE("RemoveWpaIface return fail!"); + } if (StopSupplicant() != WIFI_HAL_SUCCESS) { LOGE("wpa_supplicant stop failed!"); return WIFI_HAL_FAILED; } - LOGD("wpa_supplicant stop successfully"); ReleaseWifiStaInterface(staNo); + LOGI("wpa_supplicant stop successfully"); return WIFI_HAL_SUCCESS; } - WifiErrorNo Start(void) { - LOGD("Ready to start wifi"); + LOGI("Ready to start wifi"); if (StartSupplicant() != WIFI_HAL_SUCCESS) { LOGE("wpa_supplicant start failed!"); return WIFI_HAL_OPEN_SUPPLICANT_FAILED; } - LOGD("wpa_supplicant start successfully!"); + LOGI("wpa_supplicant start successfully!"); if (AddWpaIface(0) != WIFI_HAL_SUCCESS) { LOGE("Failed to add wpa interface!"); @@ -131,26 +120,43 @@ WifiErrorNo Start(void) StopWpaAndWpaHal(0); return WIFI_HAL_CONN_SUPPLICANT_FAILED; } - LOGD("SupplicantHal connect wpa_supplicant successfully!"); - LOGD("Start wifi successfully"); +#ifdef HDI_INTERFACE_SUPPORT + if (HdiStart() != WIFI_HAL_SUCCESS) { + LOGE("[STA] Start hdi failed!"); + return WIFI_HAL_FAILED; + } +#endif + LOGI("Start wifi successfully"); return WIFI_HAL_SUCCESS; } WifiErrorNo Stop(void) { - LOGD("Ready to Stop wifi"); + LOGI("Ready to Stop wifi"); +#ifdef HDI_INTERFACE_SUPPORT + if (HdiStop() != WIFI_HAL_SUCCESS) { + LOGE("[Ap] Stop hdi failed!"); + return WIFI_HAL_FAILED; + } +#endif WifiErrorNo err = StopWpaAndWpaHal(0); if (err == WIFI_HAL_FAILED) { - LOGD("Wifi stop failed!"); + LOGE("Wifi stop failed!"); return WIFI_HAL_FAILED; } - LOGD("Wifi stop successfully!"); + LOGI("Wifi stop successfully!"); return WIFI_HAL_SUCCESS; } WifiErrorNo ForceStop(void) { - LOGD("Ready force Stop wifi"); + LOGI("Ready force Stop wifi"); +#ifdef HDI_INTERFACE_SUPPORT + if (HdiStop() != WIFI_HAL_SUCCESS) { + LOGE("[Ap] Stop hdi failed!"); + return WIFI_HAL_FAILED; + } +#endif WifiWpaStaInterface *p = TraversalWifiStaInterface(); while (p != NULL) { StopWpaAndWpaHal(p->staNo); @@ -161,21 +167,16 @@ WifiErrorNo ForceStop(void) WifiErrorNo StartSupplicant(void) { - const char *wpaConf = "/data/misc/wifi/wpa_supplicant/wpa_supplicant.conf"; - if ((access(wpaConf, F_OK)) != -1) { - LOGD("wpa configure file %{private}s is exist.", wpaConf); - } else { - char szcpCmd[BUFF_SIZE] = {0}; - const char *cpWpaConfCmd = "cp /system/etc/wifi/wpa_supplicant.conf /data/misc/wifi/wpa_supplicant"; - int iRet = snprintf_s(szcpCmd, sizeof(szcpCmd), sizeof(szcpCmd) - 1, "%s", cpWpaConfCmd); - if (iRet < 0) { - return WIFI_HAL_FAILED; - } - - ExcuteStaCmd(szcpCmd); + LOGI("Start supplicant"); + if (CopyConfigFile("wpa_supplicant.conf") != 0) { + return WIFI_HAL_FAILED; } - - ModuleManageRetCode ret = StartModule(g_serviceName, g_startCmd); +#ifdef NON_SEPERATE_P2P + if (CopyConfigFile("p2p_supplicant.conf") != 0) { + return WIFI_HAL_FAILED; + } +#endif + ModuleManageRetCode ret = StartModule(WPA_SUPPLICANT_NAME, START_CMD); if (ret != MM_SUCCESS) { LOGE("start wpa_supplicant failed!"); return WIFI_HAL_FAILED; @@ -185,11 +186,13 @@ WifiErrorNo StartSupplicant(void) WifiErrorNo StopSupplicant(void) { - ModuleManageRetCode ret = StopModule(g_serviceName); + LOGI("Stop supplicant"); + ModuleManageRetCode ret = StopModule(WPA_SUPPLICANT_NAME, false); if (ret == MM_FAILED) { LOGE("stop wpa_supplicant failed!"); return WIFI_HAL_FAILED; } + if (ret == MM_SUCCESS) { ReleaseWpaGlobalInterface(); } @@ -266,7 +269,7 @@ WifiErrorNo GetScanInfos(ScanInfo *results, int *size) return WIFI_HAL_SUCCESS; } -WifiErrorNo GetNetworkList(HidlNetworkInfo *infos, int *size) +WifiErrorNo GetNetworkList(WifiNetworkInfo *infos, int *size) { LOGD("GetNetworkList()"); if (infos == NULL || size == NULL || *size == 0) { @@ -591,7 +594,7 @@ WifiErrorNo DisableNetwork(int networkId) return WIFI_HAL_SUCCESS; } -WifiErrorNo SetNetwork(int networkId, const HidlSetNetworkConfig *confs, int size) +WifiErrorNo SetNetwork(int networkId, const SetNetworkConfig *confs, int size) { if (confs == NULL) { LOGE("SetNetwork() confs is NULL"); @@ -703,7 +706,7 @@ WifiErrorNo StopWps(void) WifiErrorNo GetRoamingCapabilities(WifiRoamCapability *capability) { - LOGD("GetRoamingCapabilities"); + LOGI("GetRoamingCapabilities"); if (capability == NULL) { return WIFI_HAL_FAILED; } @@ -712,8 +715,22 @@ WifiErrorNo GetRoamingCapabilities(WifiRoamCapability *capability) WifiErrorNo SetRoamConfig(char **blocklist, int blocksize, char **trustlist, int trustsize) { - LOGD("SetRoamConfig block size %{public}d, trust size %{public}d", blocksize, trustsize); - if (blocklist == NULL || trustlist == NULL) { + LOGI("SetRoamConfig, blocksize:%{public}d, trustsize:%{public}d", blocksize, trustsize); + if (trustlist != NULL && trustsize > 0) { + WifiWpaStaInterface *pStaIfc = GetWifiStaInterface(0); + if (pStaIfc == NULL) { + return WIFI_HAL_SUPPLICANT_NOT_INIT; + } + for (int i = 0; i < trustsize; i++) { + int ret = pStaIfc->wpaCliCmdSetRoamConfig(pStaIfc, trustlist[i]); + if (ret < 0) { + LOGE("wpaCliCmdSetRoamConfig failed! ret=%{public}d", ret); + return WIFI_HAL_FAILED; + } + } + } + + if (blocklist == NULL || blocksize <= 0) { return WIFI_HAL_SUCCESS; } return WIFI_HAL_SUCCESS; @@ -755,7 +772,7 @@ WifiErrorNo WpaGetCountryCode(char *countryCode, int codeSize) } return WIFI_HAL_SUCCESS; } -WifiErrorNo WpaGetNetWork(HidlGetNetworkConfig *conf) +WifiErrorNo WpaGetNetWork(GetNetworkConfig *conf) { if (conf == NULL) { LOGE("WpaGetNetWork conf is NULL"); @@ -794,7 +811,7 @@ WifiErrorNo WpaBlocklistClear(void) return WIFI_HAL_SUCCESS; } -WifiErrorNo GetConnectSignalInfo(const char *endBssid, HidlWpaSignalInfo *info) +WifiErrorNo GetConnectSignalInfo(const char *endBssid, WpaSignalInfo *info) { if (endBssid == NULL || info == NULL) { LOGE("GetConnectSignalInfo endBssid or info is NULL"); @@ -812,3 +829,19 @@ WifiErrorNo GetConnectSignalInfo(const char *endBssid, HidlWpaSignalInfo *info) } return WIFI_HAL_SUCCESS; } + +WifiErrorNo SetSuspendMode(bool mode) +{ + LOGI("SetSuspendMode() mode: %{public}d", mode); + WifiWpaStaInterface *pStaIfc = GetWifiStaInterface(0); + if (pStaIfc == NULL) { + LOGE("GetWifiStaInterface return failed"); + return WIFI_HAL_SUPPLICANT_NOT_INIT; + } + int ret = pStaIfc->wpaCliCmdWpaSetSuspendMode(pStaIfc, mode); + if (ret != WIFI_HAL_SUCCESS) { + LOGE("wpaCliCmdWpaSetSuspendMode return failed! ret = %{public}d", ret); + return WIFI_HAL_FAILED; + } + return WIFI_HAL_SUCCESS; +} diff --git a/services/wifi_standard/wifi_hal/wifi_hal_sta_interface.h b/wifi/services/wifi_standard/wifi_hal/wifi_hal_sta_interface.h similarity index 93% rename from services/wifi_standard/wifi_hal/wifi_hal_sta_interface.h rename to wifi/services/wifi_standard/wifi_hal/wifi_hal_sta_interface.h index 743f9ed8cdf5b09231c4d8c18fe6c3e7c7837ba8..4577c5c910ec6cdb10b478dec0bc71d2b9fe5c32 100644 --- a/services/wifi_standard/wifi_hal/wifi_hal_sta_interface.h +++ b/wifi/services/wifi_standard/wifi_hal/wifi_hal_sta_interface.h @@ -21,6 +21,7 @@ #include #include #include +#include #include #include "wifi_hal_define.h" #include "wifi_hal_struct.h" @@ -224,7 +225,7 @@ WifiErrorNo GetSupportFeature(long *feature); * @Description Send instructions to the Wi-Fi driver or chip. * * @param ifname - * @param cmdid - Commond ID. + * @param cmdid - Command ID. * @param buf * @param bufSize * @return WifiErrorNo @@ -279,7 +280,7 @@ WifiErrorNo DisableNetwork(int networkId); * @param size - Size of the network configuration array to be set. * @return WifiErrorNo */ -WifiErrorNo SetNetwork(int networkId, const HidlSetNetworkConfig *confs, int size); +WifiErrorNo SetNetwork(int networkId, const SetNetworkConfig *confs, int size); /** * @Description Save the network. @@ -354,7 +355,7 @@ WifiErrorNo WpaGetCountryCode(char *countryCode, int codeSize); * @param conf * @return WifiErrorNo */ -WifiErrorNo WpaGetNetWork(HidlGetNetworkConfig *conf); +WifiErrorNo WpaGetNetWork(GetNetworkConfig *conf); /** * @Description Wpa_s disable/enable(0/1) automatic reconnection. @@ -374,12 +375,12 @@ WifiErrorNo WpaBlocklistClear(void); /** * @Description Obtaining the Network List. * - * @param HidlNetworkInfo - Array pointer of the network info structure type. + * @param WifiNetworkInfo - Array pointer of the network info structure type. * @param size - Number of infos that can be stored in the memory to which * the network info pointer points. * @return WifiErrorNo */ -WifiErrorNo GetNetworkList(HidlNetworkInfo *infos, int *size); +WifiErrorNo GetNetworkList(WifiNetworkInfo *infos, int *size); /** * @Description Get current connect signal info, rssi, linkspeed, noise ... @@ -388,8 +389,16 @@ WifiErrorNo GetNetworkList(HidlNetworkInfo *infos, int *size); * @param info - signal info * @return WifiErrorNo */ -WifiErrorNo GetConnectSignalInfo(const char *endBssid, HidlWpaSignalInfo *info); +WifiErrorNo GetConnectSignalInfo(const char *endBssid, WpaSignalInfo *info); + +/** + * @Description Send suspend mode to wpa + * + * @param mode - true for suspend mode, false for resume mode. + * @return WifiErrorNo + */ +WifiErrorNo SetSuspendMode(bool mode); #ifdef __cplusplus } #endif -#endif \ No newline at end of file +#endif diff --git a/services/wifi_standard/wifi_hal/wifi_hal_struct.h b/wifi/services/wifi_standard/wifi_hal/wifi_hal_struct.h similarity index 93% rename from services/wifi_standard/wifi_hal/wifi_hal_struct.h rename to wifi/services/wifi_standard/wifi_hal/wifi_hal_struct.h index 2ed5b65452a67167c1eddee3b94fdc5f69f058bd..32e38c7598e15f70bc2ea390573af14224baf2ed 100644 --- a/services/wifi_standard/wifi_hal/wifi_hal_struct.h +++ b/wifi/services/wifi_standard/wifi_hal/wifi_hal_struct.h @@ -89,12 +89,12 @@ typedef struct ScanInfo { Ant ant; } ScanInfo; -typedef struct HidlNetworkInfo { +typedef struct WifiNetworkInfo { int id; char ssid[WIFI_SSID_LENGTH]; char bssid[WIFI_BSSID_LENGTH]; char flags[WIFI_NETWORK_FLAGS_LENGTH]; -} HidlNetworkInfo; +} WifiNetworkInfo; typedef struct PnoScanSettings { int scanInterval; @@ -119,16 +119,16 @@ typedef struct HostapdConfig { int32_t maxConn; } HostapdConfig; -typedef struct HidlSetNetworkConfig { +typedef struct SetNetworkConfig { DeviceConfigType cfgParam; /* Setting parameters. */ char cfgValue[WIFI_NETWORK_CONFIG_VALUE_LENGTH]; /* Parameter value. */ -} HidlSetNetworkConfig; +} SetNetworkConfig; -typedef struct HidlGetNetworkConfig { +typedef struct GetNetworkConfig { int networkId; char param[WIFI_NETWORK_CONFIG_NAME_LENGTH]; char value[WIFI_NETWORK_CONFIG_VALUE_LENGTH]; -} HidlGetNetworkConfig; +} GetNetworkConfig; typedef struct WifiWpsParam { int anyFlag; @@ -142,13 +142,13 @@ typedef struct WifiRoamCapability { int maxTrustlistSize; } WifiRoamCapability; -typedef struct HidlWpaSignalInfo { +typedef struct WpaSignalInfo { int signal; /* RSSI */ int txrate; int rxrate; int noise; int frequency; -} HidlWpaSignalInfo; +} WpaSignalInfo; #ifdef __cplusplus } #endif diff --git a/services/wifi_standard/wifi_hal/wifi_hal_vendor_interface.c b/wifi/services/wifi_standard/wifi_hal/wifi_hal_vendor_interface.c similarity index 100% rename from services/wifi_standard/wifi_hal/wifi_hal_vendor_interface.c rename to wifi/services/wifi_standard/wifi_hal/wifi_hal_vendor_interface.c diff --git a/services/wifi_standard/wifi_hal/wifi_hal_vendor_interface.h b/wifi/services/wifi_standard/wifi_hal/wifi_hal_vendor_interface.h similarity index 100% rename from services/wifi_standard/wifi_hal/wifi_hal_vendor_interface.h rename to wifi/services/wifi_standard/wifi_hal/wifi_hal_vendor_interface.h diff --git a/wifi/test/fuzztest/fuzz_common_func/wifi_fuzz_common_func.h b/wifi/test/fuzztest/fuzz_common_func/wifi_fuzz_common_func.h new file mode 100644 index 0000000000000000000000000000000000000000..6af1bb7981934b9bbbbddc1ad3c3cf1aa0064a72 --- /dev/null +++ b/wifi/test/fuzztest/fuzz_common_func/wifi_fuzz_common_func.h @@ -0,0 +1,35 @@ +/* + * Copyright (C) 2022 Huawei Device Co., Ltd. + * 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 WIFI_FUZZ_COMMON_FUNC_H_ +#define WIFI_FUZZ_COMMON_FUNC_H_ + +#include + +namespace OHOS { +namespace Wifi { +inline uint16_t U16_AT(const uint8_t* data) +{ + return (data[0] << 8) | data[1]; +} + +inline uint32_t U32_AT(const uint8_t* data) +{ + return (data[0] << 24) | (data[1] << 16) | (data[2] << 8) | data[3]; +} +} // namespace Wifi +} // namespace OHOS +#endif + diff --git a/wifi/test/fuzztest/wifi_sta/BUILD.gn b/wifi/test/fuzztest/wifi_sta/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..2f851f6f5b6488c7ea84f8c6717061aa46f2af67 --- /dev/null +++ b/wifi/test/fuzztest/wifi_sta/BUILD.gn @@ -0,0 +1,23 @@ +# Copyright (C) 2022 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import("//build/test.gni") +group("fuzztest") { + testonly = true + deps = [] + + deps += [ + "adddeviceconfig_fuzzer:AddDeviceConfigFuzzTest", + "connecttodevice_fuzzer:ConnectToDeviceFuzzTest", + ] +} diff --git a/services/wifi_standard/wifi_framework/dhcp_manage/dhcp_server/BUILD.gn b/wifi/test/fuzztest/wifi_sta/adddeviceconfig_fuzzer/BUILD.gn similarity index 37% rename from services/wifi_standard/wifi_framework/dhcp_manage/dhcp_server/BUILD.gn rename to wifi/test/fuzztest/wifi_sta/adddeviceconfig_fuzzer/BUILD.gn index 111d95e4e6be08b3b4f3dc9595688e75b9009505..d2892ca4757382d3fb52dc0dbe11f018e3d775da 100644 --- a/services/wifi_standard/wifi_framework/dhcp_manage/dhcp_server/BUILD.gn +++ b/wifi/test/fuzztest/wifi_sta/adddeviceconfig_fuzzer/BUILD.gn @@ -1,4 +1,4 @@ -# Copyright (C) 2021 Huawei Device Co., Ltd. +# Copyright (C) 2022 Huawei Device Co., Ltd. # 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 @@ -11,40 +11,40 @@ # See the License for the specific language governing permissions and # limitations under the License. -import("//build/ohos.gni") -ohos_executable("dhcp_server") { - install_enable = true - dhcp_hilog_enable = true - sources = [ - "src/address_utils.c", - "src/common_util.c", - "src/dhcp_address_pool.c", - "src/dhcp_argument.c", - "src/dhcp_binding.c", - "src/dhcp_config.c", - "src/dhcp_dhcpd.c", - "src/dhcp_option.c", - "src/dhcp_server.c", - "src/hash_table.c", - ] +#####################hydra-fuzz################### +import("//build/config/features.gni") +import("//build/test.gni") +import("//foundation/communication/wifi/wifi/wifi.gni") +module_output_path = "wifi/wifi_sta" + +##############################fuzztest########################################## +ohos_fuzztest("AddDeviceConfigFuzzTest") { + module_out_path = module_output_path + fuzz_config_file = + "$WIFI_ROOT_DIR/test/fuzztest/wifi_sta/adddeviceconfig_fuzzer" include_dirs = [ - "include", - "include/common", - "//foundation/communication/wifi/services/wifi_standard/wifi_framework/dhcp_manage/dhcp_client/include", - "//utils/native/base/include", + "$WIFI_ROOT_DIR/frameworks/native/include", + "$WIFI_ROOT_DIR/frameworks/native/interfaces", + "$WIFI_ROOT_DIR/services/wifi_standard/wifi_framework/wifi_toolkit/net_helper", + "$WIFI_ROOT_DIR/test/fuzztest/fuzz_common_func", ] - deps = [ "//utils/native/base:utils" ] + cflags = [ + "-g", + "-O0", + "-Wno-unused-variable", + "-fno-omit-frame-pointer", + ] + sources = [ "adddeviceconfig_fuzzer.cpp" ] - cflags_cc = [ "-fno-rtti" ] + deps = [ "$WIFI_ROOT_DIR/frameworks/native:wifi_sdk" ] - defines = [ "__OHOS__" ] - if (dhcp_hilog_enable) { - external_deps = [ "hiviewdfx_hilog_native:libhilog" ] - defines += [ "DHCP_HILOG_ENABLE" ] - } + external_deps = [ + "c_utils:utils", + "ipc:ipc_core", + ] - part_name = "wifi_standard" + part_name = "wifi" subsystem_name = "communication" } diff --git a/wifi/test/fuzztest/wifi_sta/adddeviceconfig_fuzzer/adddeviceconfig_fuzzer.cpp b/wifi/test/fuzztest/wifi_sta/adddeviceconfig_fuzzer/adddeviceconfig_fuzzer.cpp new file mode 100644 index 0000000000000000000000000000000000000000..5ab9f0891cff720d58e4e2bf964378ec27bf6ae8 --- /dev/null +++ b/wifi/test/fuzztest/wifi_sta/adddeviceconfig_fuzzer/adddeviceconfig_fuzzer.cpp @@ -0,0 +1,46 @@ +/* + * Copyright (C) 2022 Huawei Device Co., Ltd. + * 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 "adddeviceconfig_fuzzer.h" +#include "wifi_device.h" + +namespace OHOS { +namespace Wifi { + std::unique_ptr devicePtr = WifiDevice::GetInstance(WIFI_DEVICE_ABILITY_ID); + bool AddDeviceConfigFuzzerTest(const uint8_t* data, size_t size) + { + if (devicePtr == nullptr) { + return false; + } + + WifiDeviceConfig config; + int addResult; + bool isCandidate = false; + config.ssid = std::string(reinterpret_cast(data), size); + config.bssid = std::string(reinterpret_cast(data), size); + config.preSharedKey = std::string(reinterpret_cast(data), size); + config.keyMgmt = std::string(reinterpret_cast(data), size); + devicePtr->AddDeviceConfig(config, addResult, isCandidate); + return true; + } +} // namespace Wifi +} // namespace OHOS + +/* Fuzzer entry point */ +extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) +{ + OHOS::Wifi::AddDeviceConfigFuzzerTest(data, size); + return 0; +} diff --git a/wifi/test/fuzztest/wifi_sta/adddeviceconfig_fuzzer/adddeviceconfig_fuzzer.h b/wifi/test/fuzztest/wifi_sta/adddeviceconfig_fuzzer/adddeviceconfig_fuzzer.h new file mode 100644 index 0000000000000000000000000000000000000000..9ca90ccf98d6279a82684031621681504f79b712 --- /dev/null +++ b/wifi/test/fuzztest/wifi_sta/adddeviceconfig_fuzzer/adddeviceconfig_fuzzer.h @@ -0,0 +1,21 @@ +/* + * Copyright (C) 2022 Huawei Device Co., Ltd. + * 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 WIFI_FUZZ_ADD_DEVICE_CONFIG_H_ +#define WIFI_FUZZ_ADD_DEVICE_CONFIG_H_ + +#define FUZZ_PROJECT_NAME "adddeviceconfig_fuzzer" + +#endif \ No newline at end of file diff --git a/tests/wifi_standard/wifi_framework/wifi_manage/unittest/wifi_manage_test.cpp b/wifi/test/fuzztest/wifi_sta/adddeviceconfig_fuzzer/corpus/init similarity index 76% rename from tests/wifi_standard/wifi_framework/wifi_manage/unittest/wifi_manage_test.cpp rename to wifi/test/fuzztest/wifi_sta/adddeviceconfig_fuzzer/corpus/init index e7867ae26bb2fef4b733b96479235a52fcd3662e..088eee3ee0668b9df51c4e3097d47d37d1913bbe 100644 --- a/tests/wifi_standard/wifi_framework/wifi_manage/unittest/wifi_manage_test.cpp +++ b/wifi/test/fuzztest/wifi_sta/adddeviceconfig_fuzzer/corpus/init @@ -1,21 +1,16 @@ -/* - * Copyright (C) 2021 Huawei Device Co., Ltd. - * 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 - -int main(int argc, char *argv[]) -{ - testing::InitGoogleTest(&argc, argv); - return RUN_ALL_TESTS(); -} \ No newline at end of file +/* + * Copyright (C) 2022 Huawei Device Co., Ltd. + * 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. + */ + +FUZZ \ No newline at end of file diff --git a/wifi/test/fuzztest/wifi_sta/adddeviceconfig_fuzzer/project.xml b/wifi/test/fuzztest/wifi_sta/adddeviceconfig_fuzzer/project.xml new file mode 100644 index 0000000000000000000000000000000000000000..5e3b584f39efcde7a43e48c9d95f03e55efb9985 --- /dev/null +++ b/wifi/test/fuzztest/wifi_sta/adddeviceconfig_fuzzer/project.xml @@ -0,0 +1,25 @@ + + + + + + 1000 + + 300 + + 4096 + + diff --git a/services/wifi_standard/wifi_hal/etc/init/BUILD.gn b/wifi/test/fuzztest/wifi_sta/connecttodevice_fuzzer/BUILD.gn old mode 100755 new mode 100644 similarity index 35% rename from services/wifi_standard/wifi_hal/etc/init/BUILD.gn rename to wifi/test/fuzztest/wifi_sta/connecttodevice_fuzzer/BUILD.gn index e2c07e859b9830c022b8ea524190b6dde0002f2c..8ba30e6639020f9e295340789a85b0063647a710 --- a/services/wifi_standard/wifi_hal/etc/init/BUILD.gn +++ b/wifi/test/fuzztest/wifi_sta/connecttodevice_fuzzer/BUILD.gn @@ -1,4 +1,4 @@ -# Copyright (C) 2021 Huawei Device Co., Ltd. +# Copyright (C) 2022 Huawei Device Co., Ltd. # 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 @@ -11,37 +11,40 @@ # See the License for the specific language governing permissions and # limitations under the License. -import("//build/ohos.gni") +#####################hydra-fuzz################### +import("//build/config/features.gni") +import("//build/test.gni") +import("//foundation/communication/wifi/wifi/wifi.gni") +module_output_path = "wifi/wifi_sta" -group("etc") { - deps = [ - ":wifi_hal_service.rc", - ":wpa_supplicant.conf", - ":hostapd.conf" +##############################fuzztest########################################## +ohos_fuzztest("ConnectToDeviceFuzzTest") { + module_out_path = module_output_path + fuzz_config_file = + "$WIFI_ROOT_DIR/test/fuzztest/wifi_sta/connecttodevice_fuzzer" + + include_dirs = [ + "$WIFI_ROOT_DIR/frameworks/native/include", + "$WIFI_ROOT_DIR/frameworks/native/interfaces", + "$WIFI_ROOT_DIR/services/wifi_standard/wifi_framework/wifi_toolkit/net_helper", + "$WIFI_ROOT_DIR/test/fuzztest/fuzz_common_func", ] -} -ohos_prebuilt_etc("wifi_hal_service.rc") { - if (use_musl) { - source = "wifi_hal_service.cfg" - } else { - source = "wifi_hal_service.rc" - } - relative_install_dir = "init" - part_name = "wifi_standard" - subsystem_name = "communication" -} + cflags = [ + "-g", + "-O0", + "-Wno-unused-variable", + "-fno-omit-frame-pointer", + ] + sources = [ "connecttodevice_fuzzer.cpp" ] -ohos_prebuilt_etc("wpa_supplicant.conf") { - source = "wpa_supplicant.conf" - relative_install_dir = "wifi" - part_name = "wifi_standard" - subsystem_name = "communication" -} + deps = [ "$WIFI_ROOT_DIR/frameworks/native:wifi_sdk" ] -ohos_prebuilt_etc("hostapd.conf") { - source = "hostapd.conf" - relative_install_dir = "wifi" - part_name = "wifi_standard" + external_deps = [ + "c_utils:utils", + "ipc:ipc_core", + ] + + part_name = "wifi" subsystem_name = "communication" -} \ No newline at end of file +} diff --git a/wifi/test/fuzztest/wifi_sta/connecttodevice_fuzzer/connecttodevice_fuzzer.cpp b/wifi/test/fuzztest/wifi_sta/connecttodevice_fuzzer/connecttodevice_fuzzer.cpp new file mode 100644 index 0000000000000000000000000000000000000000..79e8407c187a927b37650ce5fe24ef49fb8e2274 --- /dev/null +++ b/wifi/test/fuzztest/wifi_sta/connecttodevice_fuzzer/connecttodevice_fuzzer.cpp @@ -0,0 +1,45 @@ +/* + * Copyright (C) 2022 Huawei Device Co., Ltd. + * 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 "connecttodevice_fuzzer.h" +#include "wifi_device.h" + +namespace OHOS { +namespace Wifi { + std::unique_ptr devicePtr = WifiDevice::GetInstance(WIFI_DEVICE_ABILITY_ID); + bool ConnectToDeviceFuzzerTest(const uint8_t* data, size_t size) + { + if (devicePtr == nullptr) { + return false; + } + + WifiDeviceConfig config; + config.ssid = std::string(reinterpret_cast(data), size); + config.bssid = std::string(reinterpret_cast(data), size); + config.preSharedKey = std::string(reinterpret_cast(data), size); + config.keyMgmt = std::string(reinterpret_cast(data), size); + devicePtr->ConnectToDevice(config); + return true; + } +} // namespace Wifi +} // namespace OHOS + +/* Fuzzer entry point */ +extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) +{ + OHOS::Wifi::ConnectToDeviceFuzzerTest(data, size); + return 0; +} + diff --git a/wifi/test/fuzztest/wifi_sta/connecttodevice_fuzzer/connecttodevice_fuzzer.h b/wifi/test/fuzztest/wifi_sta/connecttodevice_fuzzer/connecttodevice_fuzzer.h new file mode 100644 index 0000000000000000000000000000000000000000..f1f7f20b47249d0c5ef611b15913beb33b63c4e0 --- /dev/null +++ b/wifi/test/fuzztest/wifi_sta/connecttodevice_fuzzer/connecttodevice_fuzzer.h @@ -0,0 +1,21 @@ +/* + * Copyright (C) 2022 Huawei Device Co., Ltd. + * 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 WIFI_FUZZ_CONNECT_TO_DEVICE_H_ +#define WIFI_FUZZ_CONNECT_TO_DEVICE_H_ + +#define FUZZ_PROJECT_NAME "connecttodevice_fuzzer" + +#endif diff --git a/tests/wifi_standard/wifi_hal/unittest/wifi_hal_test.cpp b/wifi/test/fuzztest/wifi_sta/connecttodevice_fuzzer/corpus/init similarity index 75% rename from tests/wifi_standard/wifi_hal/unittest/wifi_hal_test.cpp rename to wifi/test/fuzztest/wifi_sta/connecttodevice_fuzzer/corpus/init index 5d68c02374ab9e0269fe0d52caad4c14b2a1e27c..088eee3ee0668b9df51c4e3097d47d37d1913bbe 100644 --- a/tests/wifi_standard/wifi_hal/unittest/wifi_hal_test.cpp +++ b/wifi/test/fuzztest/wifi_sta/connecttodevice_fuzzer/corpus/init @@ -1,22 +1,16 @@ -/* - * Copyright (C) 2021 Huawei Device Co., Ltd. - * 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 - -int main(int argc, char *argv[]) -{ - testing::InitGoogleTest(&argc, argv); - return RUN_ALL_TESTS(); -} \ No newline at end of file +/* + * Copyright (C) 2022 Huawei Device Co., Ltd. + * 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. + */ + +FUZZ \ No newline at end of file diff --git a/wifi/test/fuzztest/wifi_sta/connecttodevice_fuzzer/project.xml b/wifi/test/fuzztest/wifi_sta/connecttodevice_fuzzer/project.xml new file mode 100644 index 0000000000000000000000000000000000000000..5e3b584f39efcde7a43e48c9d95f03e55efb9985 --- /dev/null +++ b/wifi/test/fuzztest/wifi_sta/connecttodevice_fuzzer/project.xml @@ -0,0 +1,25 @@ + + + + + + 1000 + + 300 + + 4096 + + diff --git a/wifi/test/wifi_client/BUILD.gn b/wifi/test/wifi_client/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..1146c2c8da257027ec5c012c0a2ad1070b80472d --- /dev/null +++ b/wifi/test/wifi_client/BUILD.gn @@ -0,0 +1,57 @@ +# Copyright (C) 2022 Huawei Device Co., Ltd. +# 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. + +if (defined(ohos_lite)) { + import("//build/lite/config/component/lite_component.gni") + import("//foundation/communication/wifi/wifi/wifi_lite.gni") +} else { + import("//build/ohos.gni") + import("//foundation/communication/wifi/wifi/wifi.gni") +} + +local_base_sources = [ "$WIFI_ROOT_DIR/test/wifi_client/wifi_client.cpp" ] + +local_base_include_dirs = [ + "$WIFI_ROOT_DIR/frameworks/native/include", + "$WIFI_ROOT_DIR/frameworks/native/interfaces", + "$WIFI_ROOT_DIR/services/wifi_standard/wifi_framework/wifi_toolkit/net_helper", +] + +if (defined(ohos_lite)) { + executable("wifi_client") { + sources = local_base_sources + include_dirs = local_base_include_dirs + include_dirs += [ "//third_party/bounds_checking_function/include" ] + deps = [ + "$WIFI_ROOT_DIR/frameworks/native:wifi_sdk", + "//third_party/bounds_checking_function:libsec_shared", + ] + defines = [ "OHOS_ARCH_LITE" ] + } +} else { + ohos_executable("wifi_client") { + install_enable = true + sources = local_base_sources + include_dirs = local_base_include_dirs + include_dirs += [ + "//foundation/communication/ipc/interfaces/innerkits/ipc_core/include", + "//commonlibrary/c_utils/base/include", + ] + deps = [ "$WIFI_ROOT_DIR/frameworks/native:wifi_sdk" ] + + external_deps = [ "c_utils:utils" ] + + part_name = "wifi" + subsystem_name = "communication" + } +} diff --git a/wifi/test/wifi_client/wifi_client.cpp b/wifi/test/wifi_client/wifi_client.cpp new file mode 100644 index 0000000000000000000000000000000000000000..19a0a9468ab37b363e31afb81f4e95287cebc1b5 --- /dev/null +++ b/wifi/test/wifi_client/wifi_client.cpp @@ -0,0 +1,839 @@ +/* + * Copyright (C) 2022 Huawei Device Co., Ltd. + * 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 "wifi_device.h" +#include "wifi_scan.h" + +#define ARRAY_SIZE(a) (sizeof(a) / sizeof((a)[0])) + +using namespace std; + +namespace OHOS { +namespace Wifi { +std::unique_ptr ptrWifiDevice = WifiDevice::GetInstance(WIFI_DEVICE_ABILITY_ID); +std::unique_ptr ptrWifiScan = WifiScan::GetInstance(WIFI_SCAN_ABILITY_ID); + +const int MAX_ARGS = 16; +const int BAND_2GHZ = 1; +const int BAND_5GHZ = 2; +const int CMD_IDX = 1; +const int ARG_IDX = 2; +const int MIN_WPA_LENGTH = 8; + +struct sta_cli_cmd { + const char *cmd; + void (*handler)(int argc, const char* argv[]); + const char *usage; +}; + +static void Log(const char *fmt, ...) +{ + va_list list; + va_start(list, fmt); + (void)vfprintf(stdout, fmt, list); + va_end(list); + fflush(stdout); +} + +#define Logd(fmt, ...) Log(fmt"\n", ##__VA_ARGS__) + +static void PrintLinkedInfo(const WifiLinkedInfo &linkedInfo) +{ + std::stringstream ss; + ss << "Linked info details:" << endl; + ss << " ssid:" << linkedInfo.ssid << endl; + ss << " bssid:" << linkedInfo.bssid << endl; + ss << " rssi:" << linkedInfo.rssi << endl; + ss << " band:" << linkedInfo.band << endl; + ss << " frequency:" << linkedInfo.frequency << endl; + ss << " linkSpeed:" << linkedInfo.linkSpeed << endl; + ss << " macAddress:" << linkedInfo.macAddress << endl; + ss << " ipAddress:" << linkedInfo.ipAddress << endl; + ss << " connState:" << static_cast(linkedInfo.connState) << endl; + ss << " ifHiddenSSID:" << linkedInfo.ifHiddenSSID << endl; + Logd("%s", ss.str().c_str()); +} + +static void PrintIpInfo(IpInfo &ipInfo) +{ + std::stringstream ss; + ss << "IP information:" << endl; + ss << " ipAddress:" << ipInfo.ipAddress << endl; + ss << " gateway:" << ipInfo.gateway << endl; + ss << " netmask:" << ipInfo.netmask << endl; + ss << " primaryDns:" << ipInfo.primaryDns << endl; + ss << " secondDns:" << ipInfo.secondDns << endl; + Logd("%s", ss.str().c_str()); +} + +static void PrintfDeviceConfigs(vector &configs) +{ + int idx = 0; + std::stringstream ss; + for (WifiDeviceConfig &config : configs) { + ss << "No. " << idx << " network id:" << config.networkId << endl; + ss << " ssid:" << config.ssid << endl; + ss << " bssid:" << config.bssid << endl; + ss << " keyMgmt:" << config.keyMgmt << endl; + ss << " status:" << config.status << endl; + idx++; + } + Logd("%s", ss.str().c_str()); +} + +static void PrintfScanResults(vector &scanInfos) +{ + Logd("%s total size:%u", __func__, scanInfos.size()); + int idx = 0; + std::stringstream ss; + for (WifiScanInfo &scanInfo : scanInfos) { + ss << "No. " << idx << " ssid:" << scanInfo.ssid << endl; + ss << " bssid:" << scanInfo.bssid << endl; + ss << " frequency:" << scanInfo.frequency << endl; + ss << " rssi:" << scanInfo.rssi << endl; + ss << " securityType:" << static_cast(scanInfo.securityType) << endl; + idx++; + } + Logd("%s", ss.str().c_str()); +} + +class WifiDeviceEventCallback : public IWifiDeviceCallBack { +public: + WifiDeviceEventCallback() + { + } + + virtual ~WifiDeviceEventCallback() + { + } + + void OnWifiStateChanged(int state) override + { + Logd("receive %s event, state:%d", __func__, state); + } + + void OnWifiConnectionChanged(int state, const WifiLinkedInfo &info) override + { + Logd("receive %s event, state:%d", __func__, state); + PrintLinkedInfo(info); + } + + void OnWifiRssiChanged(int rssi) override + { + Logd("receive %s event, rssi:%d", __func__, rssi); + } + + void OnWifiWpsStateChanged(int state, const std::string &pinCode) override + { + Logd("receive %s event, state:%d, pinCode:%s", __func__, state, pinCode.c_str()); + } + + void OnStreamChanged(int direction) override + { + Logd("receive %s event, direction:%d", __func__, direction); + } + + void OnDeviceConfigChanged(ConfigChange value) override + { + Logd("receive %s event:%d", __func__, static_cast(value)); + } + +#ifndef OHOS_ARCH_LITE + OHOS::sptr AsObject() override + { + return nullptr; + } +#endif +}; + +class WifiScanEventCallback : public IWifiScanCallback { +public: + WifiScanEventCallback() + { + } + + virtual ~WifiScanEventCallback() + { + } + + void OnWifiScanStateChanged(int state) override + { + Logd("receive %s event, state:%d", __func__, state); + } + +#ifndef OHOS_ARCH_LITE + OHOS::sptr AsObject() override + { + return nullptr; + } +#endif +}; + +#ifdef OHOS_ARCH_LITE +static std::shared_ptr deviceCallback = std::make_shared(); +static std::shared_ptr scanCallback = std::make_shared(); +#else +static sptr deviceCallback = + sptr(new (std::nothrow)WifiDeviceEventCallback()); +static sptr scanCallback = + sptr(new (std::nothrow)WifiScanEventCallback()); +#endif + +static void RegisterDeviceEvents(void) +{ + if (ptrWifiDevice != nullptr) { + ErrCode ret = ptrWifiDevice->RegisterCallBack(deviceCallback); + if (ret == WIFI_OPT_SUCCESS) { + Logd("%s success", __func__); + } else { + Logd("%s failed", __func__); + } + } +} + +static void RegisterScanEvents(void) +{ + if (ptrWifiScan != nullptr) { + ErrCode ret = ptrWifiScan->RegisterCallBack(scanCallback); + if (ret == WIFI_OPT_SUCCESS) { + Logd("%s success", __func__); + } else { + Logd("%s failed", __func__); + } + } +} + +static void HelpCommand(const char *command); +static bool GetNetworkId(int argc, const char *argv[], int &nid) +{ + nid = -1; + for (int i = ARG_IDX; i < argc; i++) { + if (strncmp(argv[i], "nid=", strlen("nid=")) == 0) { + (void)sscanf_s(argv[i], "nid=%d", &nid); + } + } + if (nid < 0) { + HelpCommand(argv[CMD_IDX]); + return false; + } + return true; +} + +static bool GetDeviceConfig(int argc, const char *argv[], WifiDeviceConfig &config) +{ + int phase2 = 0; + string keyMgmt = ""; + config.ssid = ""; + config.preSharedKey = ""; + config.wifiEapConfig.eap = ""; + config.wifiEapConfig.identity = ""; + + for (int i = ARG_IDX; i < argc; i++) { + if (strncmp(argv[i], "ssid=", strlen("ssid=")) == 0) { + config.ssid = argv[i] + strlen("ssid="); + } else if (strncmp(argv[i], "pwd=", strlen("pwd=")) == 0) { + config.preSharedKey = argv[i] + strlen("pwd="); + } else if (strncmp(argv[i], "key_mgmt=", strlen("key_mgmt=")) == 0) { + keyMgmt = argv[i] + strlen("key_mgmt="); + } else if (strncmp(argv[i], "id=", strlen("id=")) == 0) { + config.wifiEapConfig.identity = argv[i] + strlen("id="); + } else if (strncmp(argv[i], "phase2=", strlen("phase2=")) == 0) { + (void)sscanf_s(argv[i], "phase2=%d", &phase2); + } else if (strncmp(argv[i], "eapmethod=", strlen("eapmethod=")) == 0) { + config.wifiEapConfig.eap = argv[i] + strlen("eapmethod="); + } + } + if (config.ssid == "" || keyMgmt == "") { + HelpCommand(argv[CMD_IDX]); + return false; + } + if (keyMgmt != "open" && keyMgmt != "wpa" && keyMgmt != "wpa2" && keyMgmt != "eap") { + Logd("key_mgmt should be one of {open, wpa, wpa2, eap}"); + return false; + } + if ((keyMgmt != "open" && keyMgmt != "eap") && config.preSharedKey.length() < MIN_WPA_LENGTH) { + Logd("password length should be >= %d", MIN_WPA_LENGTH); + return false; + } + if (keyMgmt == "open") { + config.keyMgmt = KEY_MGMT_NONE; + } else if (keyMgmt == "eap") { + config.keyMgmt = KEY_MGMT_EAP; + if (config.wifiEapConfig.eap == EAP_METHOD_PEAP) { + config.wifiEapConfig.phase2Method = Phase2Method(phase2); + config.wifiEapConfig.password = config.preSharedKey; + config.preSharedKey = ""; + } else { + Logd("EapMethod %s unsupported", config.wifiEapConfig.eap.c_str()); + } + } else { + config.keyMgmt = KEY_MGMT_WPA_PSK; + } + return true; +} + +static void HandleEnable(int argc, const char* argv[]) +{ + Logd("enter command handler:%s", argv[CMD_IDX]); + if (ptrWifiDevice != nullptr) { + ErrCode ret = ptrWifiDevice->EnableWifi(); + if (ret == WIFI_OPT_SUCCESS) { + Logd("%s success", __func__); + } else { + Logd("%s failed", __func__); + } + } +} + +static void HandleDisable(int argc, const char* argv[]) +{ + Logd("enter command handler:%s", argv[CMD_IDX]); + if (ptrWifiDevice != nullptr) { + ErrCode ret = ptrWifiDevice->DisableWifi(); + if (ret == WIFI_OPT_SUCCESS) { + Logd("%s success", __func__); + } else { + Logd("%s failed", __func__); + } + } +} + +static void HandleScan(int argc, const char* argv[]) +{ + Logd("enter command handler:%s", argv[CMD_IDX]); + if (ptrWifiScan != nullptr) { + ErrCode ret = ptrWifiScan->Scan(); + if (ret == WIFI_OPT_SUCCESS) { + Logd("%s success", __func__); + } else { + Logd("%s failed", __func__); + } + } +} + +static void HandleDisconnect(int argc, const char* argv[]) +{ + Logd("enter command handler:%s", argv[CMD_IDX]); + if (ptrWifiDevice != nullptr) { + ErrCode ret = ptrWifiDevice->Disconnect(); + if (ret == WIFI_OPT_SUCCESS) { + Logd("%s success", __func__); + } else { + Logd("%s failed", __func__); + } + } +} + +static void HandleGetStatus(int argc, const char* argv[]) +{ + Logd("enter command handler:%s", argv[CMD_IDX]); + if (ptrWifiDevice == nullptr) { + return; + } + + bool active; + ErrCode ret = ptrWifiDevice->IsWifiActive(active); + if (ret != WIFI_OPT_SUCCESS) { + Logd("IsWifiActive failed"); + return; + } + if (!active) { + Logd("wifi is disabled"); + return; + } + Logd("wifi is enabled"); +#ifndef OHOS_ARCH_LITE + bool connected = ptrWifiDevice->IsConnected(); + if (!connected) { + Logd("wifi is disconnected"); + return; + } + Logd("wifi is connected"); +#endif + WifiLinkedInfo linkedInfo; + ret = ptrWifiDevice->GetLinkedInfo(linkedInfo); + if (ret != WIFI_OPT_SUCCESS) { + Logd("GetLinkedInfo failed"); + return; + } + PrintLinkedInfo(linkedInfo); + if (linkedInfo.connState != ConnState::CONNECTED) { + return; + } + + IpInfo ipInfo; + ret = ptrWifiDevice->GetIpInfo(ipInfo); + if (ret != WIFI_OPT_SUCCESS) { + Logd("GetIpInfo failed"); + return; + } + PrintIpInfo(ipInfo); +} + +static void HandleGetConfigList(int argc, const char* argv[]) +{ + Logd("enter command handler:%s", argv[CMD_IDX]); + if (ptrWifiDevice != nullptr) { + vector configs; + bool isCandidate = false; + ErrCode ret = ptrWifiDevice->GetDeviceConfigs(configs, isCandidate); + if (ret == WIFI_OPT_SUCCESS) { + Logd("%s success", __func__); + PrintfDeviceConfigs(configs); + } else { + Logd("%s failed", __func__); + } + } +} + +static void HandleGetScanResults(int argc, const char* argv[]) +{ + Logd("enter command handler:%s", argv[CMD_IDX]); + if (ptrWifiScan != nullptr) { + vector result; + ErrCode ret = ptrWifiScan->GetScanInfoList(result); + if (ret == WIFI_OPT_SUCCESS) { + Logd("%s success", __func__); + PrintfScanResults(result); + } else { + Logd("%s failed", __func__); + } + } +} + +static void HandleUpdateConfig(int argc, const char* argv[]) +{ + Logd("enter command handler:%s", argv[CMD_IDX]); + int nid; + WifiDeviceConfig config; + if (!GetDeviceConfig(argc, argv, config) || !GetNetworkId(argc, argv, nid)) { + return; + } + if (ptrWifiDevice != nullptr) { + int updatedId; + ErrCode ret = ptrWifiDevice->UpdateDeviceConfig(config, updatedId); + if (ret == WIFI_OPT_SUCCESS) { + Logd("%s success, nid=%d", __func__, updatedId); + } else { + Logd("%s failed", __func__); + } + } +} + +static void HandleAddConfig(int argc, const char* argv[]) +{ + Logd("enter command handler:%s", argv[CMD_IDX]); + WifiDeviceConfig config; + if (!GetDeviceConfig(argc, argv, config)) { + return; + } + if (ptrWifiDevice != nullptr) { + int nid; + bool isCandidate = false; + ErrCode ret = ptrWifiDevice->AddDeviceConfig(config, nid, isCandidate); + if (ret == WIFI_OPT_SUCCESS) { + Logd("%s success, nid=%d", __func__, nid); + } else { + Logd("%s failed", __func__); + } + } +} + +static void HandleRemoveConfigs(int argc, const char* argv[]) +{ + Logd("enter command handler:%s", argv[CMD_IDX]); + if (ptrWifiDevice != nullptr) { + ErrCode ret = ptrWifiDevice->RemoveAllDevice(); + if (ret == WIFI_OPT_SUCCESS) { + Logd("%s success", __func__); + } else { + Logd("%s failed", __func__); + } + } +} + +static void HandleRemoveConfig(int argc, const char* argv[]) +{ + Logd("enter command handler:%s", argv[CMD_IDX]); + int nid; + if (!GetNetworkId(argc, argv, nid)) { + return; + } + if (ptrWifiDevice != nullptr) { + ErrCode ret = ptrWifiDevice->RemoveDevice(nid); + if (ret == WIFI_OPT_SUCCESS) { + Logd("%s success, nid=%d", __func__, nid); + } else { + Logd("%s failed", __func__); + } + } +} + +static void HandleConnectNetwork(int argc, const char* argv[]) +{ + Logd("enter command handler:%s", argv[CMD_IDX]); + int nid; + if (!GetNetworkId(argc, argv, nid)) { + return; + } + if (ptrWifiDevice != nullptr) { + bool isCandidate = false; + ErrCode ret = ptrWifiDevice->ConnectToNetwork(nid, isCandidate); + if (ret == WIFI_OPT_SUCCESS) { + Logd("%s success, nid=%d", __func__, nid); + } else { + Logd("%s failed", __func__); + } + } +} + +static void HandleConnectDevice(int argc, const char* argv[]) +{ + Logd("enter command handler:%s", argv[CMD_IDX]); + WifiDeviceConfig config; + if (!GetDeviceConfig(argc, argv, config)) { + return; + } + if (ptrWifiDevice != nullptr) { + ErrCode ret = ptrWifiDevice->ConnectToDevice(config); + if (ret == WIFI_OPT_SUCCESS) { + Logd("%s success", __func__); + } else { + Logd("%s failed", __func__); + } + } +} + +static void HandleGetWifiState(int argc, const char* argv[]) +{ + Logd("enter command handler:%s", argv[CMD_IDX]); + if (ptrWifiDevice != nullptr) { + int state; + ErrCode ret = ptrWifiDevice->GetWifiState(state); + if (ret == WIFI_OPT_SUCCESS) { + Logd("%s success, wifi state:%d", __func__, state); + } else { + Logd("%s failed", __func__); + } + } +} + +static void HandleGetCountry(int argc, const char* argv[]) +{ + Logd("enter command handler:%s", argv[CMD_IDX]); + if (ptrWifiDevice != nullptr) { + string countryCode; + ErrCode ret = ptrWifiDevice->GetCountryCode(countryCode); + if (ret == WIFI_OPT_SUCCESS) { + Logd("%s success, countryCode: %s", __func__, countryCode.c_str()); + } else { + Logd("%s failed", __func__); + } + } +} + +static void HandleSetCountry(int argc, const char* argv[]) +{ + Logd("enter command handler:%s", argv[CMD_IDX]); + string code = ""; + for (int i = ARG_IDX; i < argc; i++) { + if (strncmp(argv[i], "code=", strlen("code=")) == 0) { + code = argv[i] + strlen("code="); + } + } + if (code == "") { + HelpCommand(argv[CMD_IDX]); + return; + } + if (ptrWifiDevice != nullptr) { + ErrCode ret = ptrWifiDevice->SetCountryCode(code); + if (ret == WIFI_OPT_SUCCESS) { + Logd("%s success, code=%s", __func__, code.c_str()); + } else { + Logd("%s failed", __func__); + } + } +} + +static void HandleGetSignalLevel(int argc, const char* argv[]) +{ + Logd("enter command handler:%s", argv[CMD_IDX]); + int rssi = 0; + string band = ""; + for (int i = ARG_IDX; i < argc; i++) { + if (strncmp(argv[i], "rssi=", strlen("rssi=")) == 0) { + (void)sscanf_s(argv[i], "rssi=%d", &rssi); + } else if (strncmp(argv[i], "band=", strlen("band=")) == 0) { + band = argv[i] + strlen("band="); + } + } + if (rssi >= 0 || (band != "2g" && band != "5g")) { + HelpCommand(argv[CMD_IDX]); + return; + } + if (ptrWifiDevice != nullptr) { + int level; + int bandType = (band == "2g" ? BAND_2GHZ : BAND_5GHZ); + ErrCode ret = ptrWifiDevice->GetSignalLevel(rssi, bandType, level); + if (ret == WIFI_OPT_SUCCESS) { + Logd("%s success, level=%d", __func__, level); + } else { + Logd("%s failed", __func__); + } + } +} + +static void HandleGetSupportedFeatures(int argc, const char* argv[]) +{ + Logd("enter command handler:%s", argv[CMD_IDX]); + if (ptrWifiDevice != nullptr) { + long features = 0L; + ErrCode ret = ptrWifiDevice->GetSupportedFeatures(features); + if (ret == WIFI_OPT_SUCCESS) { + Logd("%s success, features=0x%lx", __func__, features); + } else { + Logd("%s failed", __func__); + } + } +} + +static void HandleIsFeatureSupported(int argc, const char* argv[]) +{ + Logd("enter command handler:%s", argv[CMD_IDX]); + long feature = 0L; + for (int i = ARG_IDX; i < argc; i++) { + if (strncmp(argv[i], "feature=0x", strlen("feature=0x")) == 0) { + (void)sscanf_s(argv[i], "feature=0x%lx", &feature); + } + } + if (feature == 0) { + HelpCommand(argv[CMD_IDX]); + return; + } + if (ptrWifiDevice != nullptr) { + bool supported = ptrWifiDevice->IsFeatureSupported(feature); + Logd("%s feature:0x%lx, supported:%d", __func__, feature, supported); + } +} + +static void HandleEnableConfig(int argc, const char* argv[]) +{ + Logd("enter command handler:%s", argv[CMD_IDX]); + int nid = -1; + string disableOthers = ""; + for (int i = ARG_IDX; i < argc; i++) { + if (strncmp(argv[i], "nid=", strlen("nid=")) == 0) { + (void)sscanf_s(argv[i], "nid=%d", &nid); + } else if (strncmp(argv[i], "disableothers=", strlen("disableothers=")) == 0) { + disableOthers = argv[i] + strlen("disableothers="); + } + } + if (nid < 0 || (disableOthers != "true" && disableOthers != "false")) { + HelpCommand(argv[CMD_IDX]); + return; + } + if (ptrWifiDevice != nullptr) { + ErrCode ret = ptrWifiDevice->EnableDeviceConfig(nid, disableOthers == "true"); + if (ret == WIFI_OPT_SUCCESS) { + Logd("%s success, nid=%d", __func__, nid); + } else { + Logd("%s failed", __func__); + } + } +} + +static void HandleDisableConfig(int argc, const char* argv[]) +{ + Logd("enter command handler:%s", argv[CMD_IDX]); + int nid; + if (!GetNetworkId(argc, argv, nid)) { + return; + } + if (ptrWifiDevice != nullptr) { + ErrCode ret = ptrWifiDevice->DisableDeviceConfig(nid); + if (ret == WIFI_OPT_SUCCESS) { + Logd("%s success, nid=%d", __func__, nid); + } else { + Logd("%s failed", __func__); + } + } +} + +static void HandleReconnect(int argc, const char* argv[]) +{ + Logd("enter command handler:%s", argv[CMD_IDX]); + if (ptrWifiDevice != nullptr) { + ErrCode ret = ptrWifiDevice->ReConnect(); + if (ret == WIFI_OPT_SUCCESS) { + Logd("%s success", __func__); + } else { + Logd("%s failed", __func__); + } + } +} + +static void HandleReassociate(int argc, const char* argv[]) +{ + Logd("enter command handler:%s", argv[CMD_IDX]); + if (ptrWifiDevice != nullptr) { + ErrCode ret = ptrWifiDevice->ReAssociate(); + if (ret == WIFI_OPT_SUCCESS) { + Logd("%s success", __func__); + } else { + Logd("%s failed", __func__); + } + } +} + +static void HandleGetDeviceMac(int argc, const char* argv[]) +{ + Logd("enter command handler:%s", argv[CMD_IDX]); + if (ptrWifiDevice != nullptr) { + string mac; + ErrCode ret = ptrWifiDevice->GetDeviceMacAddress(mac); + if (ret == WIFI_OPT_SUCCESS) { + Logd("%s success, mac is %s:", __func__, mac.c_str()); + } else { + Logd("%s failed", __func__); + } + } +} + +static void ParseUserInput(std::string command); +static void HandleInteractive(int argc, const char* argv[]) +{ + string inputLine; + Logd("enter interactive mode! input quit to exit this mode"); + Logd("please input command:"); + RegisterDeviceEvents(); + RegisterScanEvents(); + + do { + getline(cin, inputLine); + if (inputLine == "quit") { + break; + } else { + ParseUserInput(inputLine); + Logd("please input command:"); + } + } while (true); +} + +static const struct sta_cli_cmd g_sta_cli_cmds[] = { + {"enable", HandleEnable, "enable"}, + {"disable", HandleDisable, "disable"}, + {"scan", HandleScan, "scan"}, + {"disconnect", HandleDisconnect, "disconnect nid=%d"}, + {"get_status", HandleGetStatus, "get_status"}, + {"get_config_list", HandleGetConfigList, "get_config_list"}, + {"get_scan_results", HandleGetScanResults, "get_scan_results"}, + {"update_config", HandleUpdateConfig, "update_config nid=%d ssid=%s pwd=%s key_mgmt=open/wpa/wpa2"}, + {"add_config", HandleAddConfig, "add_config ssid=%s pwd=%s key_mgmt=open/wpa/wpa2"}, + {"remove_configs", HandleRemoveConfigs, "remove_configs"}, + {"remove_config", HandleRemoveConfig, "remove_config nid=%d"}, + {"connect_network", HandleConnectNetwork, "connect_network nid=%d"}, + {"connect_device", HandleConnectDevice, "connect_device ssid=%s pwd=%s key_mgmt=open/wpa/wpa2"}, + {"get_wifi_state", HandleGetWifiState, "get_wifi_state"}, + {"set_country", HandleSetCountry, "set_country code=%s"}, + {"get_country", HandleGetCountry, "get_country"}, + {"get_signal_level", HandleGetSignalLevel, "get_signal_level rssi=%d band=2g/5g"}, + {"get_supported_features", HandleGetSupportedFeatures, "get_supported_features"}, + {"is_feature_supported", HandleIsFeatureSupported, "is_feature_supported feature=0x%x"}, + {"enable_config", HandleEnableConfig, "enable_config nid=%d disableothers=true/false"}, + {"disable_config", HandleDisableConfig, "disable_config nid=%d"}, + {"reconnect", HandleReconnect, "reconnect"}, + {"reassociate", HandleReassociate, "reassociate"}, + {"get_device_mac", HandleGetDeviceMac, "get_device_mac"}, + {"interactive", HandleInteractive, "interactive"} +}; + +static void HelpCommand(const char *command) +{ + int count = ARRAY_SIZE(g_sta_cli_cmds); + for (int i = 0; i < count; i++) { + if (strcmp(command, g_sta_cli_cmds[i].cmd) == 0) { + Logd("%s", g_sta_cli_cmds[i].usage); + return; + } + } + Logd("can not find command %s", command); +} + +static void Help(void) +{ + Logd("%s", "support command as follows:"); + int count = ARRAY_SIZE(g_sta_cli_cmds); + for (int i = 0; i < count; i++) { + Logd("%s", g_sta_cli_cmds[i].usage); + } +} + +static void HandleUserCommand(int argc, const char *argv[]) +{ + if (argc < ARG_IDX) { + Help(); + return; + } + + int count = ARRAY_SIZE(g_sta_cli_cmds); + for (int i = 0; i < count; i++) { + if (strcmp(g_sta_cli_cmds[i].cmd, argv[CMD_IDX]) == 0) { + if (g_sta_cli_cmds[i].handler != nullptr) { + g_sta_cli_cmds[i].handler(argc, argv); + } else { + Logd("no handler for command:%s", g_sta_cli_cmds[i].cmd); + } + return; + } + } + Help(); +} + +static void ParseUserInput(std::string command) +{ + int argc = 0; + const char* argv[MAX_ARGS] = { nullptr }; + vector cmdArgs; + + std::istringstream istr(command); + for (std::string s; istr >> s;) { + cmdArgs.push_back(s); + } + + argc = cmdArgs.size() + CMD_IDX; + if (argc > MAX_ARGS) { + argc = MAX_ARGS; + } + for (int i = CMD_IDX; i < argc; i++) { + argv[i] = cmdArgs[i - CMD_IDX].c_str(); + } + HandleUserCommand(argc, argv); + cmdArgs.clear(); +} +} +} + +int main(int argc, char *argv[]) +{ + OHOS::Wifi::HandleUserCommand(argc, const_cast(argv)); + return 0; +} diff --git a/tests/wifi_standard/ipc_framework/cRPC/unittest/BUILD.gn b/wifi/test/wifi_standard/ipc_framework/cRPC/unittest/BUILD.gn similarity index 62% rename from tests/wifi_standard/ipc_framework/cRPC/unittest/BUILD.gn rename to wifi/test/wifi_standard/ipc_framework/cRPC/unittest/BUILD.gn index 69672804358fabc8391e08f271390b174d7460c5..af450cd693cb9590ad67a9e53c26e6328b5dd027 100644 --- a/tests/wifi_standard/ipc_framework/cRPC/unittest/BUILD.gn +++ b/wifi/test/wifi_standard/ipc_framework/cRPC/unittest/BUILD.gn @@ -1,4 +1,4 @@ -# Copyright (C) 2021 Huawei Device Co., Ltd. +# Copyright (C) 2021-2022 Huawei Device Co., Ltd. # 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 @@ -12,24 +12,24 @@ # limitations under the License. import("//build/test.gni") -SUBSYSTEM_DIR = "//foundation/communication/wifi" -module_output_path = "wifi_standard/crpc_test" +import("//foundation/communication/wifi/wifi/wifi.gni") +module_output_path = "wifi/crpc_test" config("module_private_config") { visibility = [ ":*" ] include_dirs = [ - "//utils/native/base/include", - "$SUBSYSTEM_DIR/tests/wifi_standard/ipc_framework/cRPC/unittest", + "//commonlibrary/c_utils/base/include", + "$WIFI_ROOT_DIR/test/wifi_standard/ipc_framework/cRPC/unittest", ] } ohos_unittest("crpc_unittest") { module_out_path = module_output_path sources = [ - "$SUBSYSTEM_DIR/services/wifi_standard/ipc_framework/cRPC/src/context.c", - "$SUBSYSTEM_DIR/services/wifi_standard/ipc_framework/cRPC/src/hash_table.c", - "$SUBSYSTEM_DIR/services/wifi_standard/ipc_framework/cRPC/src/net.c", - "$SUBSYSTEM_DIR/services/wifi_standard/ipc_framework/cRPC/src/serial.c", + "$WIFI_ROOT_DIR/services/wifi_standard/ipc_framework/cRPC/src/context.c", + "$WIFI_ROOT_DIR/services/wifi_standard/ipc_framework/cRPC/src/hash_table.c", + "$WIFI_ROOT_DIR/services/wifi_standard/ipc_framework/cRPC/src/net.c", + "$WIFI_ROOT_DIR/services/wifi_standard/ipc_framework/cRPC/src/serial.c", "context_test.cpp", "hash_table_test.cpp", "net_test.cpp", @@ -38,12 +38,10 @@ ohos_unittest("crpc_unittest") { ] include_dirs = [ - "$SUBSYSTEM_DIR/services/wifi_standard/ipc_framework/cRPC/include", + "$WIFI_ROOT_DIR/services/wifi_standard/ipc_framework/cRPC/include", "//base/hiviewdfx/hilog/interfaces/native/innerkits/include", ] - deps = [ "//utils/native/base:utils" ] - ldflags = [ "-fPIC", "-Wl,--wrap=write", @@ -51,10 +49,18 @@ ohos_unittest("crpc_unittest") { "--coverage", ] - external_deps = [ "hiviewdfx_hilog_native:libhilog" ] + deps = [ + "//third_party/googletest:gmock_main", + "//third_party/googletest:gtest_main", + ] + + external_deps = [ + "c_utils:utils", + "hiviewdfx_hilog_native:libhilog", + ] configs = [ ":module_private_config" ] - part_name = "wifi_standard" + part_name = "wifi" subsystem_name = "communication" testonly = true } diff --git a/tests/wifi_standard/ipc_framework/cRPC/unittest/context_test.cpp b/wifi/test/wifi_standard/ipc_framework/cRPC/unittest/context_test.cpp similarity index 98% rename from tests/wifi_standard/ipc_framework/cRPC/unittest/context_test.cpp rename to wifi/test/wifi_standard/ipc_framework/cRPC/unittest/context_test.cpp index d7be628ed8d2896c7127272cf5c61677d42ba842..1f1717980378c68317b2c4a2dedc802b4c898e1c 100644 --- a/tests/wifi_standard/ipc_framework/cRPC/unittest/context_test.cpp +++ b/wifi/test/wifi_standard/ipc_framework/cRPC/unittest/context_test.cpp @@ -1,5 +1,5 @@ /* - * Copyright (C) 2021 Huawei Device Co., Ltd. + * Copyright (C) 2021-2022 Huawei Device Co., Ltd. * 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 @@ -14,7 +14,8 @@ */ #include "context_test.h" -#include "securec.h" +#include +#include "common.h" using namespace testing::ext; @@ -197,4 +198,4 @@ HWTEST_F(ContextTest, ContextWriteNetTest, TestSize.Level1) EXPECT_TRUE(ret == size - 1); } } // namespace Wifi -} // namespace OHOS \ No newline at end of file +} // namespace OHOS diff --git a/tests/wifi_standard/ipc_framework/cRPC/unittest/context_test.h b/wifi/test/wifi_standard/ipc_framework/cRPC/unittest/context_test.h similarity index 100% rename from tests/wifi_standard/ipc_framework/cRPC/unittest/context_test.h rename to wifi/test/wifi_standard/ipc_framework/cRPC/unittest/context_test.h diff --git a/tests/wifi_standard/ipc_framework/cRPC/unittest/hash_table_test.cpp b/wifi/test/wifi_standard/ipc_framework/cRPC/unittest/hash_table_test.cpp similarity index 100% rename from tests/wifi_standard/ipc_framework/cRPC/unittest/hash_table_test.cpp rename to wifi/test/wifi_standard/ipc_framework/cRPC/unittest/hash_table_test.cpp diff --git a/tests/wifi_standard/ipc_framework/cRPC/unittest/hash_table_test.h b/wifi/test/wifi_standard/ipc_framework/cRPC/unittest/hash_table_test.h similarity index 100% rename from tests/wifi_standard/ipc_framework/cRPC/unittest/hash_table_test.h rename to wifi/test/wifi_standard/ipc_framework/cRPC/unittest/hash_table_test.h diff --git a/tests/wifi_standard/ipc_framework/cRPC/unittest/net_test.cpp b/wifi/test/wifi_standard/ipc_framework/cRPC/unittest/net_test.cpp similarity index 96% rename from tests/wifi_standard/ipc_framework/cRPC/unittest/net_test.cpp rename to wifi/test/wifi_standard/ipc_framework/cRPC/unittest/net_test.cpp index 7b818f377efe72a2249d090a784196a6b991a2cf..211bd6c969b12330f763a338be372d2fa04e5c77 100644 --- a/tests/wifi_standard/ipc_framework/cRPC/unittest/net_test.cpp +++ b/wifi/test/wifi_standard/ipc_framework/cRPC/unittest/net_test.cpp @@ -1,5 +1,5 @@ /* - * Copyright (C) 2021 Huawei Device Co., Ltd. + * Copyright (C) 2021-2022 Huawei Device Co., Ltd. * 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 @@ -12,7 +12,10 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + #include "net_test.h" +#include +#include "common.h" #include "net.h" using namespace testing::ext; @@ -92,4 +95,4 @@ HWTEST_F(RpcNetTest, WaitFdEventTest, TestSize.Level1) } } } // namespace Wifi -} // namespace OHOS \ No newline at end of file +} // namespace OHOS diff --git a/tests/wifi_standard/ipc_framework/cRPC/unittest/net_test.h b/wifi/test/wifi_standard/ipc_framework/cRPC/unittest/net_test.h similarity index 100% rename from tests/wifi_standard/ipc_framework/cRPC/unittest/net_test.h rename to wifi/test/wifi_standard/ipc_framework/cRPC/unittest/net_test.h diff --git a/tests/wifi_standard/ipc_framework/cRPC/unittest/rpc_test_main.cpp b/wifi/test/wifi_standard/ipc_framework/cRPC/unittest/rpc_test_main.cpp similarity index 90% rename from tests/wifi_standard/ipc_framework/cRPC/unittest/rpc_test_main.cpp rename to wifi/test/wifi_standard/ipc_framework/cRPC/unittest/rpc_test_main.cpp index 6b29b2cf068d64bb2f54f45016421f6e3cf2d0f3..7de704f3cde92e18c76e1fd3518cfa089842154e 100644 --- a/tests/wifi_standard/ipc_framework/cRPC/unittest/rpc_test_main.cpp +++ b/wifi/test/wifi_standard/ipc_framework/cRPC/unittest/rpc_test_main.cpp @@ -1,5 +1,5 @@ /* - * Copyright (C) 2021 Huawei Device Co., Ltd. + * Copyright (C) 2021-2022 Huawei Device Co., Ltd. * 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 @@ -12,6 +12,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + #include static constexpr int MAX_SIZE = 10240; @@ -53,9 +54,3 @@ extern "C" int __wrap_write(int fd, const void *buf, unsigned int size) return size; } } - -int main(int argc, char *argv[]) -{ - testing::InitGoogleTest(&argc, argv); - return RUN_ALL_TESTS(); -} diff --git a/tests/wifi_standard/ipc_framework/cRPC/unittest/serial_test.cpp b/wifi/test/wifi_standard/ipc_framework/cRPC/unittest/serial_test.cpp similarity index 97% rename from tests/wifi_standard/ipc_framework/cRPC/unittest/serial_test.cpp rename to wifi/test/wifi_standard/ipc_framework/cRPC/unittest/serial_test.cpp index 45e9e45dc3bd78d55f3b94e21abfb4cc36912f27..ae67d3e81480156238db3cea207d36de50881cdd 100644 --- a/tests/wifi_standard/ipc_framework/cRPC/unittest/serial_test.cpp +++ b/wifi/test/wifi_standard/ipc_framework/cRPC/unittest/serial_test.cpp @@ -38,7 +38,7 @@ HWTEST_F(SerialTest, SerialTest, TestSize.Level1) ctx->oneProcess = ctx->szWrite; ctx->nSize = ctx->wEnd; - EXPECT_TRUE(strncmp(ctx->oneProcess, "N|", 2) == 0); + EXPECT_TRUE(strncmp(ctx->oneProcess, "N\t", 2) == 0); ctx->nPos = 2; char str[1024] = {0}; ASSERT_EQ(ReadFunc(ctx, str, 1024), 0); diff --git a/tests/wifi_standard/ipc_framework/cRPC/unittest/serial_test.h b/wifi/test/wifi_standard/ipc_framework/cRPC/unittest/serial_test.h similarity index 100% rename from tests/wifi_standard/ipc_framework/cRPC/unittest/serial_test.h rename to wifi/test/wifi_standard/ipc_framework/cRPC/unittest/serial_test.h diff --git a/tests/wifi_standard/wifi_framework/wifi_manage/idl_client/unittest/BUILD.gn b/wifi/test/wifi_standard/wifi_framework/wifi_manage/idl_client/unittest/BUILD.gn similarity index 41% rename from tests/wifi_standard/wifi_framework/wifi_manage/idl_client/unittest/BUILD.gn rename to wifi/test/wifi_standard/wifi_framework/wifi_manage/idl_client/unittest/BUILD.gn index 2144b2ce27393d4a41eafbb8bf79503f8f21c5fb..993b9686b8cd1d7441ab2ef4f2f9bbb92808c813 100644 --- a/tests/wifi_standard/wifi_framework/wifi_manage/idl_client/unittest/BUILD.gn +++ b/wifi/test/wifi_standard/wifi_framework/wifi_manage/idl_client/unittest/BUILD.gn @@ -1,4 +1,4 @@ -# Copyright (C) 2021 Huawei Device Co., Ltd. +# Copyright (C) 2021-2022 Huawei Device Co., Ltd. # 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 @@ -12,42 +12,37 @@ # limitations under the License. import("//build/test.gni") -SUBSYSTEM_DIR = "//foundation/communication/wifi" -module_output_path = "wifi_standard/idl_client_test" +import("//foundation/communication/wifi/wifi/wifi.gni") +module_output_path = "wifi/idl_client_test" config("module_private_config") { visibility = [ ":*" ] include_dirs = [ - "//utils/native/base/include", - "$SUBSYSTEM_DIR/tests/wifi_standard/wifi_framework/wifi_manage/idl_client/unittest", + "//commonlibrary/c_utils/base/include", + "$WIFI_ROOT_DIR/test/wifi_standard/wifi_framework/wifi_manage/idl_client/unittest", ] } ohos_unittest("idl_client_unittest") { module_out_path = module_output_path sources = [ - "$SUBSYSTEM_DIR/interfaces/innerkits/native_cpp/wifi_standard/src/wifi_p2p_msg.cpp", - "$SUBSYSTEM_DIR/services/wifi_standard/wifi_framework/common/net_helper/ip_tools.cpp", - "$SUBSYSTEM_DIR/services/wifi_standard/wifi_framework/common/utils/wifi_global_func.cpp", - "$SUBSYSTEM_DIR/services/wifi_standard/wifi_framework/wifi_manage/idl_client/idl_interface/i_wifi.c", - "$SUBSYSTEM_DIR/services/wifi_standard/wifi_framework/wifi_manage/idl_client/idl_interface/i_wifi_chip.c", - "$SUBSYSTEM_DIR/services/wifi_standard/wifi_framework/wifi_manage/idl_client/idl_interface/i_wifi_hotspot_iface.c", - "$SUBSYSTEM_DIR/services/wifi_standard/wifi_framework/wifi_manage/idl_client/idl_interface/i_wifi_iface.c", - "$SUBSYSTEM_DIR/services/wifi_standard/wifi_framework/wifi_manage/idl_client/idl_interface/i_wifi_p2p_iface.c", - "$SUBSYSTEM_DIR/services/wifi_standard/wifi_framework/wifi_manage/idl_client/idl_interface/i_wifi_public_func.c", - "$SUBSYSTEM_DIR/services/wifi_standard/wifi_framework/wifi_manage/idl_client/idl_interface/i_wifi_sta_iface.c", - "$SUBSYSTEM_DIR/services/wifi_standard/wifi_framework/wifi_manage/idl_client/idl_interface/i_wifi_supplicant_iface.c", - "$SUBSYSTEM_DIR/services/wifi_standard/wifi_framework/wifi_manage/idl_client/wifi_ap_hal_interface.cpp", - "$SUBSYSTEM_DIR/services/wifi_standard/wifi_framework/wifi_manage/idl_client/wifi_base_hal_interface.cpp", - "$SUBSYSTEM_DIR/services/wifi_standard/wifi_framework/wifi_manage/idl_client/wifi_chip_hal_interface.cpp", - "$SUBSYSTEM_DIR/services/wifi_standard/wifi_framework/wifi_manage/idl_client/wifi_idl_client.cpp", - "$SUBSYSTEM_DIR/services/wifi_standard/wifi_framework/wifi_manage/idl_client/wifi_idl_inner_interface.cpp", - "$SUBSYSTEM_DIR/services/wifi_standard/wifi_framework/wifi_manage/idl_client/wifi_p2p_hal_interface.cpp", - "$SUBSYSTEM_DIR/services/wifi_standard/wifi_framework/wifi_manage/idl_client/wifi_sta_hal_interface.cpp", - "$SUBSYSTEM_DIR/services/wifi_standard/wifi_framework/wifi_manage/idl_client/wifi_supplicant_hal_interface.cpp", - "idl_client_test_main.cpp", + "$WIFI_ROOT_DIR/frameworks/native/src/wifi_p2p_msg.cpp", + "$WIFI_ROOT_DIR/services/wifi_standard/wifi_framework/wifi_manage/idl_client/idl_interface/i_wifi.c", + "$WIFI_ROOT_DIR/services/wifi_standard/wifi_framework/wifi_manage/idl_client/idl_interface/i_wifi_chip.c", + "$WIFI_ROOT_DIR/services/wifi_standard/wifi_framework/wifi_manage/idl_client/idl_interface/i_wifi_hotspot_iface.c", + "$WIFI_ROOT_DIR/services/wifi_standard/wifi_framework/wifi_manage/idl_client/idl_interface/i_wifi_iface.c", + "$WIFI_ROOT_DIR/services/wifi_standard/wifi_framework/wifi_manage/idl_client/idl_interface/i_wifi_p2p_iface.c", + "$WIFI_ROOT_DIR/services/wifi_standard/wifi_framework/wifi_manage/idl_client/idl_interface/i_wifi_public_func.c", + "$WIFI_ROOT_DIR/services/wifi_standard/wifi_framework/wifi_manage/idl_client/idl_interface/i_wifi_sta_iface.c", + "$WIFI_ROOT_DIR/services/wifi_standard/wifi_framework/wifi_manage/idl_client/idl_interface/i_wifi_supplicant_iface.c", + "$WIFI_ROOT_DIR/services/wifi_standard/wifi_framework/wifi_manage/idl_client/wifi_ap_hal_interface.cpp", + "$WIFI_ROOT_DIR/services/wifi_standard/wifi_framework/wifi_manage/idl_client/wifi_chip_hal_interface.cpp", + "$WIFI_ROOT_DIR/services/wifi_standard/wifi_framework/wifi_manage/idl_client/wifi_idl_client.cpp", + "$WIFI_ROOT_DIR/services/wifi_standard/wifi_framework/wifi_manage/idl_client/wifi_idl_inner_interface.cpp", + "$WIFI_ROOT_DIR/services/wifi_standard/wifi_framework/wifi_manage/idl_client/wifi_p2p_hal_interface.cpp", + "$WIFI_ROOT_DIR/services/wifi_standard/wifi_framework/wifi_manage/idl_client/wifi_sta_hal_interface.cpp", + "$WIFI_ROOT_DIR/services/wifi_standard/wifi_framework/wifi_manage/idl_client/wifi_supplicant_hal_interface.cpp", "wifi_ap_hal_interface_test.cpp", - "wifi_base_hal_interface_test.cpp", "wifi_chip_hal_interface_test.cpp", "wifi_idl_client_test.cpp", "wifi_idl_interface_test.cpp", @@ -57,23 +52,25 @@ ohos_unittest("idl_client_unittest") { ] include_dirs = [ - "$SUBSYSTEM_DIR/interfaces/innerkits/native_cpp/wifi_standard/interfaces", - "$SUBSYSTEM_DIR/services/wifi_standard/ipc_framework/cRPC/include", - "$SUBSYSTEM_DIR/services/wifi_standard/wifi_framework/common/include", - "$SUBSYSTEM_DIR/services/wifi_standard/wifi_framework/common/config", - "$SUBSYSTEM_DIR/services/wifi_standard/wifi_framework/common/net_helper", - "$SUBSYSTEM_DIR/services/wifi_standard/wifi_framework/common/utils", - "$SUBSYSTEM_DIR/services/wifi_standard/wifi_framework/common/log", - "$SUBSYSTEM_DIR/services/wifi_standard/wifi_framework/wifi_manage/idl_client", - "$SUBSYSTEM_DIR/services/wifi_standard/wifi_framework/wifi_manage/idl_client/idl_interface", - "//utils/native/base/include", + "$WIFI_ROOT_DIR/frameworks/native/interfaces", + "$WIFI_ROOT_DIR/services/wifi_standard/ipc_framework/cRPC/include", + "$WIFI_ROOT_DIR/services/wifi_standard/wifi_framework/wifi_toolkit/include", + "$WIFI_ROOT_DIR/services/wifi_standard/wifi_framework/wifi_toolkit/config", + "$WIFI_ROOT_DIR/services/wifi_standard/wifi_framework/wifi_toolkit/net_helper", + "$WIFI_ROOT_DIR/services/wifi_standard/wifi_framework/wifi_toolkit/utils", + "$WIFI_ROOT_DIR/services/wifi_standard/wifi_framework/wifi_toolkit/log", + "$WIFI_ROOT_DIR/services/wifi_standard/wifi_framework/wifi_manage/idl_client", + "$WIFI_ROOT_DIR/services/wifi_standard/wifi_framework/wifi_manage/idl_client/idl_interface", + "//commonlibrary/c_utils/base/include", "//foundation/communication/ipc/interfaces/innerkits/ipc_core/include", "//base/hiviewdfx/hilog/interfaces/native/innerkits/include", ] deps = [ - "$SUBSYSTEM_DIR/services/wifi_standard/ipc_framework/cRPC:crpc_client", - "//utils/native/base:utils", + "$WIFI_ROOT_DIR/services/wifi_standard/ipc_framework/cRPC:crpc_client", + "$WIFI_ROOT_DIR/services/wifi_standard/wifi_framework/wifi_toolkit:wifi_toolkit", + "//third_party/googletest:gmock_main", + "//third_party/googletest:gtest_main", ] ldflags = [ @@ -81,10 +78,13 @@ ohos_unittest("idl_client_unittest") { "--coverage", ] - external_deps = [ "hiviewdfx_hilog_native:libhilog" ] + external_deps = [ + "c_utils:utils", + "hiviewdfx_hilog_native:libhilog", + ] configs = [ ":module_private_config" ] - part_name = "wifi_standard" + part_name = "wifi" subsystem_name = "communication" testonly = true } @@ -92,51 +92,49 @@ ohos_unittest("idl_client_unittest") { ohos_unittest("mock_wifi_hal_service") { module_out_path = module_output_path sources = [ - "$SUBSYSTEM_DIR/services/wifi_standard/wifi_framework/common/log/log_helper.c", - "$SUBSYSTEM_DIR/services/wifi_standard/wifi_hal/common/wifi_hal_common_func.c", - "$SUBSYSTEM_DIR/services/wifi_standard/wifi_hal/main.c", - "$SUBSYSTEM_DIR/services/wifi_standard/wifi_hal/wifi_hal_adapter.c", - "$SUBSYSTEM_DIR/services/wifi_standard/wifi_hal/wifi_hal_callback.c", - "$SUBSYSTEM_DIR/services/wifi_standard/wifi_hal/wifi_hal_crpc_ap.c", - "$SUBSYSTEM_DIR/services/wifi_standard/wifi_hal/wifi_hal_crpc_base.c", - "$SUBSYSTEM_DIR/services/wifi_standard/wifi_hal/wifi_hal_crpc_chip.c", - "$SUBSYSTEM_DIR/services/wifi_standard/wifi_hal/wifi_hal_crpc_common.c", - "$SUBSYSTEM_DIR/services/wifi_standard/wifi_hal/wifi_hal_crpc_p2p.c", - "$SUBSYSTEM_DIR/services/wifi_standard/wifi_hal/wifi_hal_crpc_server.c", - "$SUBSYSTEM_DIR/services/wifi_standard/wifi_hal/wifi_hal_crpc_sta.c", - "$SUBSYSTEM_DIR/services/wifi_standard/wifi_hal/wifi_hal_crpc_supplicant.c", + "$WIFI_ROOT_DIR/services/wifi_standard/wifi_hal/common/wifi_hal_common_func.c", + "$WIFI_ROOT_DIR/services/wifi_standard/wifi_hal/main.c", + "$WIFI_ROOT_DIR/services/wifi_standard/wifi_hal/wifi_hal_adapter.c", + "$WIFI_ROOT_DIR/services/wifi_standard/wifi_hal/wifi_hal_callback.c", + "$WIFI_ROOT_DIR/services/wifi_standard/wifi_hal/wifi_hal_crpc_ap.c", + "$WIFI_ROOT_DIR/services/wifi_standard/wifi_hal/wifi_hal_crpc_base.c", + "$WIFI_ROOT_DIR/services/wifi_standard/wifi_hal/wifi_hal_crpc_chip.c", + "$WIFI_ROOT_DIR/services/wifi_standard/wifi_hal/wifi_hal_crpc_common.c", + "$WIFI_ROOT_DIR/services/wifi_standard/wifi_hal/wifi_hal_crpc_p2p.c", + "$WIFI_ROOT_DIR/services/wifi_standard/wifi_hal/wifi_hal_crpc_server.c", + "$WIFI_ROOT_DIR/services/wifi_standard/wifi_hal/wifi_hal_crpc_sta.c", + "$WIFI_ROOT_DIR/services/wifi_standard/wifi_hal/wifi_hal_crpc_supplicant.c", "mock_wifi_hal_service.c", ] include_dirs = [ - "//utils/native/base/include", + "//commonlibrary/c_utils/base/include", "//base/hiviewdfx/hilog/interfaces/native/innerkits/include", - "$SUBSYSTEM_DIR/interfaces/innerkits/native_cpp/wifi_standard/interfaces", - "$SUBSYSTEM_DIR/services/wifi_standard/ipc_framework/cRPC/include", - "$SUBSYSTEM_DIR/services/wifi_standard/wifi_hal", - "$SUBSYSTEM_DIR/services/wifi_standard/wifi_hal/common", - "$SUBSYSTEM_DIR/services/wifi_standard/wifi_framework/common/log", + "$WIFI_ROOT_DIR/frameworks/native/interfaces", + "$WIFI_ROOT_DIR/services/wifi_standard/ipc_framework/cRPC/include", + "$WIFI_ROOT_DIR/services/wifi_standard/wifi_hal", + "$WIFI_ROOT_DIR/services/wifi_standard/wifi_hal/common", + "$WIFI_ROOT_DIR/services/wifi_standard/wifi_framework/wifi_toolkit/log", ] deps = [ - "$SUBSYSTEM_DIR/services/wifi_standard/ipc_framework/cRPC:crpc_server", + "$WIFI_ROOT_DIR/services/wifi_standard/ipc_framework/cRPC:crpc_server", + "$WIFI_ROOT_DIR/services/wifi_standard/wifi_framework/wifi_toolkit:wifi_toolkit", "//base/hiviewdfx/hilog/interfaces/native/innerkits:libhilog", - "//utils/native/base:utils", ] + external_deps = [ "c_utils:utils" ] + cflags_cc = [ "-fno-rtti" ] defines = [] - part_name = "wifi_standard" + part_name = "wifi" subsystem_name = "communication" testonly = true } group("unittest") { testonly = true - deps = [ - ":idl_client_unittest", - ":mock_wifi_hal_service", - ] + deps = [] } diff --git a/tests/wifi_standard/wifi_framework/wifi_manage/idl_client/unittest/mock_wifi_hal_service.c b/wifi/test/wifi_standard/wifi_framework/wifi_manage/idl_client/unittest/mock_wifi_hal_service.c similarity index 93% rename from tests/wifi_standard/wifi_framework/wifi_manage/idl_client/unittest/mock_wifi_hal_service.c rename to wifi/test/wifi_standard/wifi_framework/wifi_manage/idl_client/unittest/mock_wifi_hal_service.c index 741de69b1e683f93c8d577ca105b633dd6776c20..aa3642a67bcb330a4c6ee89d0a7c4429bc46524c 100644 --- a/tests/wifi_standard/wifi_framework/wifi_manage/idl_client/unittest/mock_wifi_hal_service.c +++ b/wifi/test/wifi_standard/wifi_framework/wifi_manage/idl_client/unittest/mock_wifi_hal_service.c @@ -1,5 +1,5 @@ /* - * Copyright (C) 2021 Huawei Device Co., Ltd. + * Copyright (C) 2021-2022 Huawei Device Co., Ltd. * 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 @@ -220,7 +220,7 @@ WifiErrorNo DisableNetwork(int networkId) return WIFI_HAL_SUCCESS; } -WifiErrorNo SetNetwork(int networkId, const HidlSetNetworkConfig *confs, int size) +WifiErrorNo SetNetwork(int networkId, const SetNetworkConfig *confs, int size) { return WIFI_HAL_SUCCESS; } @@ -274,7 +274,7 @@ WifiErrorNo WpaGetCountryCode(char *countryCode, int codeSize) return WIFI_HAL_SUCCESS; } -WifiErrorNo WpaGetNetWork(HidlGetNetworkConfig *conf) +WifiErrorNo WpaGetNetWork(GetNetworkConfig *conf) { return WIFI_HAL_SUCCESS; } @@ -289,12 +289,12 @@ WifiErrorNo WpaBlocklistClear(void) return WIFI_HAL_SUCCESS; } -WifiErrorNo GetNetworkList(HidlNetworkInfo *infos, int *size) +WifiErrorNo GetNetworkList(WifiNetworkInfo *infos, int *size) { return WIFI_HAL_SUCCESS; } -WifiErrorNo GetConnectSignalInfo(const char *endBssid, HidlWpaSignalInfo *info) +WifiErrorNo GetConnectSignalInfo(const char *endBssid, WpaSignalInfo *info) { return WIFI_HAL_SUCCESS; } @@ -373,12 +373,6 @@ WifiErrorNo DisassociateSta(const unsigned char *mac, int lenMac) WifiHalCbStaJoin(buff); return WIFI_HAL_SUCCESS; } - -WifiErrorNo GetValidFrequenciesForBand(int32_t band, int *frequencies, int32_t *size) -{ - return WIFI_HAL_SUCCESS; -} - /* --------- wifi_hal_ap_interface.h end -------------*/ /* --------- wifi_hal_chip_interface.h begin -------------*/ @@ -526,12 +520,12 @@ WifiErrorNo P2pRemoveNetwork(int networkId) return WIFI_HAL_SUCCESS; } -WifiErrorNo P2pListNetworks(HidlP2pNetworkList *infoList) +WifiErrorNo P2pListNetworks(P2pNetworkList *infoList) { if (infoList == NULL) { return WIFI_HAL_FAILED; } - infoList->infos = (HidlP2pNetworkInfo *)calloc(1, sizeof(HidlP2pNetworkInfo)); + infoList->infos = (P2pNetworkInfo *)calloc(1, sizeof(P2pNetworkInfo)); if (infoList->infos == NULL) { return WIFI_HAL_FAILED; } @@ -569,7 +563,7 @@ WifiErrorNo P2pSetWfdDeviceConfig(const char *config) WifiErrorNo P2pStartFind(int timeout) { - HidlP2pDeviceInfo device; + P2pDeviceInfo device; if (memset_s(&device, sizeof(device), 0, sizeof(device)) != EOK || strcpy_s(device.srcAddress, sizeof(device.srcAddress), "00:00:00:00:00:00") != EOK || strcpy_s(device.p2pDeviceAddress, sizeof(device.p2pDeviceAddress), "01:00:00:00:00:00") != EOK || @@ -599,7 +593,7 @@ WifiErrorNo P2pSetListenChannel(int channel, int regClass) return WIFI_HAL_SUCCESS; } -WifiErrorNo P2pConnect(const HidlP2pConnectInfo *info) +WifiErrorNo P2pConnect(const P2pConnectInfo *info) { P2pHalCbStaConnectState("00:00:00:00:00:00", 1); return WIFI_HAL_SUCCESS; @@ -628,7 +622,7 @@ WifiErrorNo P2pAddGroup(int isPersistent, int networkId) { P2pHalCbGroupFormationSuccess(); P2pHalCbGroupFormationFailure("unknown"); - HidlP2pGroupInfo info; + P2pGroupInfo info; if (memset_s(&info, sizeof(info), 0, sizeof(info)) != EOK || strcpy_s(info.groupIfName, sizeof(info.groupIfName), "p2p-dev-wlan1") != EOK || strcpy_s(info.ssid, sizeof(info.ssid), "p2p_honor_suffix") != EOK || @@ -648,7 +642,7 @@ WifiErrorNo P2pRemoveGroup(const char *interface) WifiErrorNo P2pInvite(int persisitent, const char *peerBssid, const char *goBssid, const char *ifname) { - HidlP2pInvitationInfo info; + P2pInvitationInfo info; if (memset_s(&info, sizeof(info), 0, sizeof(info)) != EOK || strcpy_s(info.srcAddress, sizeof(info.srcAddress), "00:00:00:00:00:00") != EOK || strcpy_s(info.goDeviceAddress, @@ -672,25 +666,25 @@ WifiErrorNo P2pGetGroupCapability(const char *bssid, int *cap) return WIFI_HAL_SUCCESS; } -WifiErrorNo P2pAddService(const HidlP2pServiceInfo *info) +WifiErrorNo P2pAddService(const P2pServiceInfo *info) { return WIFI_HAL_SUCCESS; } -WifiErrorNo P2pRemoveService(const HidlP2pServiceInfo *info) +WifiErrorNo P2pRemoveService(const P2pServiceInfo *info) { return WIFI_HAL_SUCCESS; } WifiErrorNo P2pReqServiceDiscovery(const char *bssid, const char *msg) { - HidlP2pServDiscReqInfo reqInfo; + P2pServDiscReqInfo reqInfo; if (memset_s(&reqInfo, sizeof(reqInfo), 0, sizeof(reqInfo)) != EOK || strcpy_s(reqInfo.mac, sizeof(reqInfo.mac), "00:00:00:00:00:00") != EOK) { return WIFI_HAL_FAILED; } P2pHalCbServDiscReq(&reqInfo); - HidlP2pServDiscRespInfo info; + P2pServDiscRespInfo info; if (memset_s(&info, sizeof(info), 0, sizeof(info)) != EOK || strcpy_s(info.srcAddress, sizeof(info.srcAddress), "00:00:00:00:00:00") != EOK) { return WIFI_HAL_FAILED; @@ -720,7 +714,7 @@ WifiErrorNo P2pSetPersistentReconnect(int mode) return WIFI_HAL_SUCCESS; } -WifiErrorNo P2pRespServerDiscovery(HidlP2pServDiscReqInfo *info) +WifiErrorNo P2pRespServerDiscovery(P2pServDiscReqInfo *info) { return WIFI_HAL_SUCCESS; } @@ -735,7 +729,7 @@ WifiErrorNo P2pSetWpsSecondaryDeviceType(const char *type) return WIFI_HAL_SUCCESS; } -WifiErrorNo P2pGetPeer(const char *bssid, HidlP2pDeviceInfo *peerInfo) +WifiErrorNo P2pGetPeer(const char *bssid, P2pDeviceInfo *peerInfo) { return WIFI_HAL_SUCCESS; } @@ -745,12 +739,12 @@ WifiErrorNo P2pGetFrequencies(int band, int *frequencies, int *size) return WIFI_HAL_SUCCESS; } -WifiErrorNo P2pSetGroupConfig(int networkId, HidlP2pGroupConfig *pConfig, int size) +WifiErrorNo P2pSetGroupConfig(int networkId, P2pGroupConfig *pConfig, int size) { return WIFI_HAL_SUCCESS; } -WifiErrorNo P2pGetGroupConfig(int networkId, HidlP2pGroupConfig *pConfig, int size) +WifiErrorNo P2pGetGroupConfig(int networkId, P2pGroupConfig *pConfig, int size) { return WIFI_HAL_SUCCESS; } @@ -760,4 +754,8 @@ WifiErrorNo P2pAddNetwork(int *networkId) return WIFI_HAL_SUCCESS; } +WifiErrorNo P2pHid2dConnect(Hid2dConnectInfo *info) +{ + return WIFI_HAL_SUCCESS; +} /*--------------- wifi_hal_p2p_interface.h end---------------------------*/ diff --git a/tests/wifi_standard/wifi_framework/wifi_manage/idl_client/unittest/wifi_ap_hal_interface_test.cpp b/wifi/test/wifi_standard/wifi_framework/wifi_manage/idl_client/unittest/wifi_ap_hal_interface_test.cpp similarity index 100% rename from tests/wifi_standard/wifi_framework/wifi_manage/idl_client/unittest/wifi_ap_hal_interface_test.cpp rename to wifi/test/wifi_standard/wifi_framework/wifi_manage/idl_client/unittest/wifi_ap_hal_interface_test.cpp diff --git a/tests/wifi_standard/wifi_framework/wifi_manage/idl_client/unittest/wifi_ap_hal_interface_test.h b/wifi/test/wifi_standard/wifi_framework/wifi_manage/idl_client/unittest/wifi_ap_hal_interface_test.h similarity index 100% rename from tests/wifi_standard/wifi_framework/wifi_manage/idl_client/unittest/wifi_ap_hal_interface_test.h rename to wifi/test/wifi_standard/wifi_framework/wifi_manage/idl_client/unittest/wifi_ap_hal_interface_test.h diff --git a/tests/wifi_standard/wifi_framework/wifi_manage/idl_client/unittest/wifi_base_hal_interface_test.cpp b/wifi/test/wifi_standard/wifi_framework/wifi_manage/idl_client/unittest/wifi_base_hal_interface_test.cpp similarity index 100% rename from tests/wifi_standard/wifi_framework/wifi_manage/idl_client/unittest/wifi_base_hal_interface_test.cpp rename to wifi/test/wifi_standard/wifi_framework/wifi_manage/idl_client/unittest/wifi_base_hal_interface_test.cpp diff --git a/tests/wifi_standard/wifi_framework/wifi_manage/idl_client/unittest/wifi_base_hal_interface_test.h b/wifi/test/wifi_standard/wifi_framework/wifi_manage/idl_client/unittest/wifi_base_hal_interface_test.h similarity index 100% rename from tests/wifi_standard/wifi_framework/wifi_manage/idl_client/unittest/wifi_base_hal_interface_test.h rename to wifi/test/wifi_standard/wifi_framework/wifi_manage/idl_client/unittest/wifi_base_hal_interface_test.h diff --git a/tests/wifi_standard/wifi_framework/wifi_manage/idl_client/unittest/wifi_chip_hal_interface_test.cpp b/wifi/test/wifi_standard/wifi_framework/wifi_manage/idl_client/unittest/wifi_chip_hal_interface_test.cpp similarity index 100% rename from tests/wifi_standard/wifi_framework/wifi_manage/idl_client/unittest/wifi_chip_hal_interface_test.cpp rename to wifi/test/wifi_standard/wifi_framework/wifi_manage/idl_client/unittest/wifi_chip_hal_interface_test.cpp diff --git a/tests/wifi_standard/wifi_framework/wifi_manage/idl_client/unittest/wifi_chip_hal_interface_test.h b/wifi/test/wifi_standard/wifi_framework/wifi_manage/idl_client/unittest/wifi_chip_hal_interface_test.h similarity index 100% rename from tests/wifi_standard/wifi_framework/wifi_manage/idl_client/unittest/wifi_chip_hal_interface_test.h rename to wifi/test/wifi_standard/wifi_framework/wifi_manage/idl_client/unittest/wifi_chip_hal_interface_test.h diff --git a/tests/wifi_standard/wifi_framework/wifi_manage/idl_client/unittest/wifi_idl_client_test.cpp b/wifi/test/wifi_standard/wifi_framework/wifi_manage/idl_client/unittest/wifi_idl_client_test.cpp similarity index 100% rename from tests/wifi_standard/wifi_framework/wifi_manage/idl_client/unittest/wifi_idl_client_test.cpp rename to wifi/test/wifi_standard/wifi_framework/wifi_manage/idl_client/unittest/wifi_idl_client_test.cpp diff --git a/tests/wifi_standard/wifi_framework/wifi_manage/idl_client/unittest/wifi_idl_client_test.h b/wifi/test/wifi_standard/wifi_framework/wifi_manage/idl_client/unittest/wifi_idl_client_test.h similarity index 100% rename from tests/wifi_standard/wifi_framework/wifi_manage/idl_client/unittest/wifi_idl_client_test.h rename to wifi/test/wifi_standard/wifi_framework/wifi_manage/idl_client/unittest/wifi_idl_client_test.h diff --git a/tests/wifi_standard/wifi_framework/wifi_manage/idl_client/unittest/wifi_idl_interface_test.cpp b/wifi/test/wifi_standard/wifi_framework/wifi_manage/idl_client/unittest/wifi_idl_interface_test.cpp similarity index 100% rename from tests/wifi_standard/wifi_framework/wifi_manage/idl_client/unittest/wifi_idl_interface_test.cpp rename to wifi/test/wifi_standard/wifi_framework/wifi_manage/idl_client/unittest/wifi_idl_interface_test.cpp diff --git a/tests/wifi_standard/wifi_framework/wifi_manage/idl_client/unittest/wifi_idl_interface_test.h b/wifi/test/wifi_standard/wifi_framework/wifi_manage/idl_client/unittest/wifi_idl_interface_test.h similarity index 100% rename from tests/wifi_standard/wifi_framework/wifi_manage/idl_client/unittest/wifi_idl_interface_test.h rename to wifi/test/wifi_standard/wifi_framework/wifi_manage/idl_client/unittest/wifi_idl_interface_test.h diff --git a/tests/wifi_standard/wifi_framework/wifi_manage/idl_client/unittest/wifi_p2p_hal_interface_test.cpp b/wifi/test/wifi_standard/wifi_framework/wifi_manage/idl_client/unittest/wifi_p2p_hal_interface_test.cpp similarity index 98% rename from tests/wifi_standard/wifi_framework/wifi_manage/idl_client/unittest/wifi_p2p_hal_interface_test.cpp rename to wifi/test/wifi_standard/wifi_framework/wifi_manage/idl_client/unittest/wifi_p2p_hal_interface_test.cpp index 07573407bf808d17e408e83792999252b631bef3..cb3ca151bf86f6a55e54eccf5d4d35bb9efbd173 100644 --- a/tests/wifi_standard/wifi_framework/wifi_manage/idl_client/unittest/wifi_p2p_hal_interface_test.cpp +++ b/wifi/test/wifi_standard/wifi_framework/wifi_manage/idl_client/unittest/wifi_p2p_hal_interface_test.cpp @@ -318,7 +318,7 @@ HWTEST_F(WifiP2pHalInterfaceTest, P2pFlush_SUCCESS, TestSize.Level1) HWTEST_F(WifiP2pHalInterfaceTest, Connect_SUCCESS, TestSize.Level1) { - WifiP2pConfig config; + WifiP2pConfigInternal config; bool isJoinExistingGroup = false; std::string pin; EXPECT_EQ(WifiErrorNo::WIFI_IDL_OPT_INVALID_PARAM, @@ -346,7 +346,7 @@ HWTEST_F(WifiP2pHalInterfaceTest, CancelConnect_SUCCESS, TestSize.Level1) HWTEST_F(WifiP2pHalInterfaceTest, ProvisionDiscovery_SUCCESS, TestSize.Level1) { - WifiP2pConfig config; + WifiP2pConfigInternal config; EXPECT_EQ(WifiErrorNo::WIFI_IDL_OPT_OK, WifiP2PHalInterface::GetInstance().ProvisionDiscovery(config)); } @@ -456,6 +456,12 @@ HWTEST_F(WifiP2pHalInterfaceTest, CancalReqServiceDiscovery_SUCCESS, TestSize.Le EXPECT_EQ(WifiErrorNo::WIFI_IDL_OPT_OK, WifiP2PHalInterface::GetInstance().CancelReqServiceDiscovery(id)); } +/** + * @tc.name: Save p2p config test + * @tc.desc: Save config of persistent group test function. + * @tc.type: FUNC + * @tc.require: issueI5EDUG + */ HWTEST_F(WifiP2pHalInterfaceTest, StoreConfig_SUCCESS, TestSize.Level1) { EXPECT_EQ(WifiErrorNo::WIFI_IDL_OPT_OK, WifiP2PHalInterface::GetInstance().SaveConfig()); diff --git a/tests/wifi_standard/wifi_framework/wifi_manage/idl_client/unittest/wifi_p2p_hal_interface_test.h b/wifi/test/wifi_standard/wifi_framework/wifi_manage/idl_client/unittest/wifi_p2p_hal_interface_test.h similarity index 100% rename from tests/wifi_standard/wifi_framework/wifi_manage/idl_client/unittest/wifi_p2p_hal_interface_test.h rename to wifi/test/wifi_standard/wifi_framework/wifi_manage/idl_client/unittest/wifi_p2p_hal_interface_test.h diff --git a/tests/wifi_standard/wifi_framework/wifi_manage/idl_client/unittest/wifi_sta_hal_interface_test.cpp b/wifi/test/wifi_standard/wifi_framework/wifi_manage/idl_client/unittest/wifi_sta_hal_interface_test.cpp similarity index 100% rename from tests/wifi_standard/wifi_framework/wifi_manage/idl_client/unittest/wifi_sta_hal_interface_test.cpp rename to wifi/test/wifi_standard/wifi_framework/wifi_manage/idl_client/unittest/wifi_sta_hal_interface_test.cpp diff --git a/tests/wifi_standard/wifi_framework/wifi_manage/idl_client/unittest/wifi_sta_hal_interface_test.h b/wifi/test/wifi_standard/wifi_framework/wifi_manage/idl_client/unittest/wifi_sta_hal_interface_test.h similarity index 100% rename from tests/wifi_standard/wifi_framework/wifi_manage/idl_client/unittest/wifi_sta_hal_interface_test.h rename to wifi/test/wifi_standard/wifi_framework/wifi_manage/idl_client/unittest/wifi_sta_hal_interface_test.h diff --git a/tests/wifi_standard/wifi_framework/wifi_manage/idl_client/unittest/wifi_supplicant_hal_interface_test.cpp b/wifi/test/wifi_standard/wifi_framework/wifi_manage/idl_client/unittest/wifi_supplicant_hal_interface_test.cpp similarity index 100% rename from tests/wifi_standard/wifi_framework/wifi_manage/idl_client/unittest/wifi_supplicant_hal_interface_test.cpp rename to wifi/test/wifi_standard/wifi_framework/wifi_manage/idl_client/unittest/wifi_supplicant_hal_interface_test.cpp diff --git a/tests/wifi_standard/wifi_framework/wifi_manage/idl_client/unittest/wifi_supplicant_hal_interface_test.h b/wifi/test/wifi_standard/wifi_framework/wifi_manage/idl_client/unittest/wifi_supplicant_hal_interface_test.h similarity index 100% rename from tests/wifi_standard/wifi_framework/wifi_manage/idl_client/unittest/wifi_supplicant_hal_interface_test.h rename to wifi/test/wifi_standard/wifi_framework/wifi_manage/idl_client/unittest/wifi_supplicant_hal_interface_test.h diff --git a/tests/wifi_standard/wifi_framework/wifi_manage/unittest/BUILD.gn b/wifi/test/wifi_standard/wifi_framework/wifi_manage/unittest/BUILD.gn similarity index 36% rename from tests/wifi_standard/wifi_framework/wifi_manage/unittest/BUILD.gn rename to wifi/test/wifi_standard/wifi_framework/wifi_manage/unittest/BUILD.gn index 6b020e7d1579d33f773a8a3b4c5a0928847f32b6..9f622074ea6a67cf4964d051c383fb177e1e28d3 100644 --- a/tests/wifi_standard/wifi_framework/wifi_manage/unittest/BUILD.gn +++ b/wifi/test/wifi_standard/wifi_framework/wifi_manage/unittest/BUILD.gn @@ -1,4 +1,4 @@ -# Copyright (C) 2021 Huawei Device Co., Ltd. +# Copyright (C) 2021-2022 Huawei Device Co., Ltd. # 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 @@ -12,80 +12,77 @@ # limitations under the License. import("//build/test.gni") -import("//foundation/appexecfwk/standard/appexecfwk.gni") +import("//foundation/communication/wifi/wifi/wifi.gni") ################################################################################ -SUBSYSTEM_DIR = "//foundation/communication/wifi" -module_output_path = "wifi_standard/manager_test" +module_output_path = "wifi/manager_test" config("module_private_config") { visibility = [ ":*" ] include_dirs = [ - "//utils/native/base/include", - "$SUBSYSTEM_DIR/tests/wifi_standard/wifi_framework/wifi_manage/unittest", + "//commonlibrary/c_utils/base/include", + "$WIFI_ROOT_DIR/test/wifi_standard/wifi_framework/wifi_manage/unittest", ] } ohos_unittest("manager_unittest") { module_out_path = module_output_path sources = [ - "$SUBSYSTEM_DIR/services/wifi_standard/wifi_framework/common/config/wifi_config_file_spec.cpp", - "$SUBSYSTEM_DIR/services/wifi_standard/wifi_framework/common/config/wifi_settings.cpp", - "$SUBSYSTEM_DIR/services/wifi_standard/wifi_framework/common/utils/wifi_common_event_helper.cpp", - "$SUBSYSTEM_DIR/services/wifi_standard/wifi_framework/wifi_manage/common/wifi_permission_helper.cpp", - "$SUBSYSTEM_DIR/services/wifi_standard/wifi_framework/wifi_manage/common/wifi_permission_utils.cpp", - "$SUBSYSTEM_DIR/services/wifi_standard/wifi_framework/wifi_manage/wifi_auth_center.cpp", - "$SUBSYSTEM_DIR/services/wifi_standard/wifi_framework/wifi_manage/wifi_config_center.cpp", - "$SUBSYSTEM_DIR/services/wifi_standard/wifi_framework/wifi_manage/wifi_internal_event_dispatcher.cpp", - "$SUBSYSTEM_DIR/services/wifi_standard/wifi_framework/wifi_manage/wifi_manager.cpp", - "$SUBSYSTEM_DIR/services/wifi_standard/wifi_framework/wifi_manage/wifi_service_manager.cpp", + "$WIFI_ROOT_DIR/services/wifi_standard/wifi_framework/wifi_manage/common/wifi_permission_helper.cpp", + "$WIFI_ROOT_DIR/services/wifi_standard/wifi_framework/wifi_manage/common/wifi_permission_utils.cpp", + "$WIFI_ROOT_DIR/services/wifi_standard/wifi_framework/wifi_manage/wifi_auth_center.cpp", + "$WIFI_ROOT_DIR/services/wifi_standard/wifi_framework/wifi_manage/wifi_config_center.cpp", + "$WIFI_ROOT_DIR/services/wifi_standard/wifi_framework/wifi_manage/wifi_internal_event_dispatcher.cpp", + "$WIFI_ROOT_DIR/services/wifi_standard/wifi_framework/wifi_manage/wifi_manager.cpp", + "$WIFI_ROOT_DIR/services/wifi_standard/wifi_framework/wifi_manage/wifi_net_agent.cpp", + "$WIFI_ROOT_DIR/services/wifi_standard/wifi_framework/wifi_manage/wifi_service_manager.cpp", "wifi_auth_center_test.cpp", "wifi_config_center_test.cpp", "wifi_internal_event_dispatcher_test.cpp", - "wifi_manage_test.cpp", "wifi_manager_service_test.cpp", "wifi_service_manager_test.cpp", ] include_dirs = [ - "$SUBSYSTEM_DIR/services/wifi_standard/wifi_framework/wifi_manage", - "$SUBSYSTEM_DIR/services/wifi_standard/wifi_framework/wifi_manage/common", - "$SUBSYSTEM_DIR/services/wifi_standard/wifi_framework/common/include", - "$SUBSYSTEM_DIR/services/wifi_standard/wifi_framework/common/net_helper", - "$SUBSYSTEM_DIR/services/wifi_standard/wifi_framework/common/utils", - "$SUBSYSTEM_DIR/services/wifi_standard/wifi_framework/common/log", - "$SUBSYSTEM_DIR/services/wifi_standard/wifi_framework/common/config", - "$SUBSYSTEM_DIR/services/wifi_standard/wifi_framework/wifi_manage/wifi_sta", - "$SUBSYSTEM_DIR/services/wifi_standard/wifi_framework/wifi_manage/wifi_scan", - "$SUBSYSTEM_DIR/services/wifi_standard/wifi_framework/wifi_manage/wifi_ap", - "$SUBSYSTEM_DIR/services/wifi_standard/wifi_framework/wifi_manage/wifi_p2p", - "$SUBSYSTEM_DIR/services/wifi_standard/wifi_framework/wifi_manage/wifi_aware", - "$SUBSYSTEM_DIR/interfaces/innerkits/native_cpp/wifi_standard/interfaces", - "$SUBSYSTEM_DIR/services/wifi_standard/wifi_framework/wifi_manage/idl_client", - "$SUBSYSTEM_DIR/services/wifi_standard/wifi_framework/wifi_manage/idl_client/idl_interface", - "$SUBSYSTEM_DIR/services/wifi_standard/ipc_framework/cRPC/include", - "//utils/native/base/include", + "$WIFI_ROOT_DIR/services/wifi_standard/wifi_framework/wifi_manage", + "$WIFI_ROOT_DIR/services/wifi_standard/wifi_framework/wifi_manage/common", + "$WIFI_ROOT_DIR/services/wifi_standard/wifi_framework/wifi_toolkit/include", + "$WIFI_ROOT_DIR/services/wifi_standard/wifi_framework/wifi_toolkit/net_helper", + "$WIFI_ROOT_DIR/services/wifi_standard/wifi_framework/wifi_toolkit/utils", + "$WIFI_ROOT_DIR/services/wifi_standard/wifi_framework/wifi_toolkit/log", + "$WIFI_ROOT_DIR/services/wifi_standard/wifi_framework/wifi_toolkit/config", + "$WIFI_ROOT_DIR/services/wifi_standard/wifi_framework/wifi_manage/wifi_sta", + "$WIFI_ROOT_DIR/services/wifi_standard/wifi_framework/wifi_manage/wifi_scan", + "$WIFI_ROOT_DIR/services/wifi_standard/wifi_framework/wifi_manage/wifi_ap", + "$WIFI_ROOT_DIR/services/wifi_standard/wifi_framework/wifi_manage/wifi_p2p", + "$WIFI_ROOT_DIR/frameworks/native/interfaces", + "$WIFI_ROOT_DIR/services/wifi_standard/wifi_framework/wifi_manage/idl_client", + "$WIFI_ROOT_DIR/services/wifi_standard/wifi_framework/wifi_manage/idl_client/idl_interface", + "$WIFI_ROOT_DIR/services/wifi_standard/ipc_framework/cRPC/include", + "//commonlibrary/c_utils/base/include", "//foundation/communication/ipc/interfaces/innerkits/ipc_core/include", "//base/hiviewdfx/hilog/interfaces/native/innerkits/include", - "//base/notification/ces_standard/cesfwk/innerkits/include", - "//base/notification/ces_standard/cesfwk/kits/native/include", - "//foundation/aafwk/standard/interfaces/innerkits/want/include/ohos/aafwk/content", - "//foundation/aafwk/standard/interfaces/innerkits/want/include", - "//foundation/distributedschedule/dmsfwk/services/dtbschedmgr/include", - "//foundation/aafwk/intent/interfaces/innerkits/base/include", + "//base/notification/common_event_service/cesfwk/innerkits/include", + "//base/notification/common_event_service/cesfwk/kits/native/include", "//foundation/appexecfwk/adapter/interfaces/innerkits/appexecfwk_base/include", - "//foundation/appexecfwk/standard/interfaces/innerkits/libeventhandler/include", - "//foundation/aafwk/standard/interfaces/innerkits/base/include", - "//foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_base/include", + "//base/security/access_token/interfaces/innerkits/accesstoken/include", + "//foundation/communication/netmanager_base/services/netmanagernative/include/netsys", + "$WIFI_ROOT_DIR/utils/inc", + "//foundation/systemabilitymgr/samgr/interfaces/innerkits/samgr_proxy/include", + "//foundation/communication/netmanager_base/frameworks/native/netmanagernative", + "//foundation/communication/netmanager_base/interfaces/innerkits/netmanagernative/include", + "$WIFI_ROOT_DIR/services/wifi_standard/include", ] deps = [ - "$SUBSYSTEM_DIR/services/wifi_standard/ipc_framework/cRPC:crpc_client", - "$SUBSYSTEM_DIR/services/wifi_standard/wifi_framework/wifi_manage/idl_client:wifi_idl_client", - "${aafwk_path}/interfaces/innerkits/base:base", - "${aafwk_path}/interfaces/innerkits/want:want", - "//utils/native/base:utils", + "$WIFI_ROOT_DIR/services/wifi_standard/ipc_framework/cRPC:crpc_client", + "$WIFI_ROOT_DIR/services/wifi_standard/wifi_framework/wifi_manage/idl_client:wifi_idl_client", + "$WIFI_ROOT_DIR/services/wifi_standard/wifi_framework/wifi_toolkit:wifi_toolkit", + "$WIFI_ROOT_DIR/utils:wifi_utils", + "//foundation/communication/netmanager_base/services/netmanagernative:netsys_native_manager", + "//third_party/googletest:gmock_main", + "//third_party/googletest:gtest_main", ] ldflags = [ @@ -94,12 +91,32 @@ ohos_unittest("manager_unittest") { ] external_deps = [ - "ces_standard:cesfwk_innerkits", + "ability_base:want", + "access_token:libaccesstoken_sdk", + "bundle_framework:appexecfwk_base", + "c_utils:utils", + "common_event_service:cesfwk_innerkits", + "eventhandler:libeventhandler", "hiviewdfx_hilog_native:libhilog", + "ipc:ipc_core", + "netmanager_base:net_conn_manager_if", + ] + + defines = [] + if (wifi_feature_with_p2p) { + defines += [ "FEATURE_P2P_SUPPORT" ] + } + + defines += [ + "FEATURE_AP_SUPPORT", + "AP_INSTANCE_MAX_NUM=$wifi_feature_with_ap_num", ] configs = [ ":module_private_config" ] - part_name = "wifi_standard" + # Do not modify the permission configuration of the unit test + defines += [ "PERMISSION_ALWAYS_GRANT" ] + + part_name = "wifi" subsystem_name = "communication" testonly = true } diff --git a/tests/wifi_standard/wifi_framework/wifi_manage/unittest/wifi_auth_center_test.cpp b/wifi/test/wifi_standard/wifi_framework/wifi_manage/unittest/wifi_auth_center_test.cpp similarity index 90% rename from tests/wifi_standard/wifi_framework/wifi_manage/unittest/wifi_auth_center_test.cpp rename to wifi/test/wifi_standard/wifi_framework/wifi_manage/unittest/wifi_auth_center_test.cpp index 29498a58a87bb348d4625085d5d60c263680d57c..241e5c07e30004606e7069b6fb2a1cd122b6132d 100644 --- a/tests/wifi_standard/wifi_framework/wifi_manage/unittest/wifi_auth_center_test.cpp +++ b/wifi/test/wifi_standard/wifi_framework/wifi_manage/unittest/wifi_auth_center_test.cpp @@ -43,7 +43,7 @@ HWTEST_F(WifiAuthCenterTest, ChangePermission_SUCCESS, TestSize.Level1) for (int i = 0; i < ARRAY_PERMISSION; i++) { permissions[g_wifiPermissions[i].name] = num[i]; } - EXPECT_EQ(0, WifiAuthCenter::GetInstance().ChangePermission(permissions, pid, uid)); + EXPECT_EQ(PERMISSION_GRANTED, WifiAuthCenter::GetInstance().ChangePermission(permissions, pid, uid)); } HWTEST_F(WifiAuthCenterTest, CheckChangePermission_GRANTED, TestSize.Level1) @@ -65,7 +65,7 @@ HWTEST_F(WifiAuthCenterTest, CheckChangePermission_DENIED, TestSize.Level1) permissions[g_wifiPermissions[i].name] = num[i]; } WifiAuthCenter::GetInstance().ChangePermission(permissions, pid, uid); - EXPECT_EQ(PERMISSION_DENIED, WifiAuthCenter::GetInstance().VerifySetWifiInfoPermission(pid, uid)); + EXPECT_EQ(PERMISSION_GRANTED, WifiAuthCenter::GetInstance().VerifySetWifiInfoPermission(pid, uid)); } HWTEST_F(WifiAuthCenterTest, CheckAccessPermission_GRANTED, TestSize.Level1) @@ -87,7 +87,7 @@ HWTEST_F(WifiAuthCenterTest, CheckAccessPermission_DENIED, TestSize.Level1) permissions[g_wifiPermissions[i].name] = num[i]; } WifiAuthCenter::GetInstance().ChangePermission(permissions, pid, uid); - EXPECT_EQ(PERMISSION_DENIED, WifiAuthCenter::GetInstance().VerifyGetWifiInfoPermission(pid, uid)); + EXPECT_EQ(PERMISSION_GRANTED, WifiAuthCenter::GetInstance().VerifyGetWifiInfoPermission(pid, uid)); } HWTEST_F(WifiAuthCenterTest, CheckAccessScanInfosPermission_GRANTED, TestSize.Level1) @@ -109,7 +109,7 @@ HWTEST_F(WifiAuthCenterTest, CheckAccessScanInfosPermission_DENIED, TestSize.Lev permissions[g_wifiPermissions[i].name] = num[i]; } WifiAuthCenter::GetInstance().ChangePermission(permissions, pid, uid); - EXPECT_EQ(PERMISSION_DENIED, WifiAuthCenter::GetInstance().VerifyGetScanInfosPermission(pid, uid)); + EXPECT_EQ(PERMISSION_GRANTED, WifiAuthCenter::GetInstance().VerifyGetScanInfosPermission(pid, uid)); } HWTEST_F(WifiAuthCenterTest, CheckGetLocalMacAddressPermission_GRANTED, TestSize.Level1) @@ -131,7 +131,7 @@ HWTEST_F(WifiAuthCenterTest, CheckGetLocalMacAddressPermission_DENIED, TestSize. permissions[g_wifiPermissions[i].name] = num[i]; } WifiAuthCenter::GetInstance().ChangePermission(permissions, pid, uid); - EXPECT_EQ(PERMISSION_DENIED, WifiAuthCenter::GetInstance().VerifyGetWifiLocalMacPermission(pid, uid)); + EXPECT_EQ(PERMISSION_GRANTED, WifiAuthCenter::GetInstance().VerifyGetWifiLocalMacPermission(pid, uid)); } HWTEST_F(WifiAuthCenterTest, CheckNetworkStackPermission_GRANTED, TestSize.Level1) @@ -153,7 +153,7 @@ HWTEST_F(WifiAuthCenterTest, CheckNetworkStackPermission_DENIED, TestSize.Level1 permissions[g_wifiPermissions[i].name] = num[i]; } WifiAuthCenter::GetInstance().ChangePermission(permissions, pid, uid); - EXPECT_EQ(PERMISSION_DENIED, WifiAuthCenter::GetInstance().VerifyWifiConnectionPermission(pid, uid)); + EXPECT_EQ(PERMISSION_GRANTED, WifiAuthCenter::GetInstance().VerifyWifiConnectionPermission(pid, uid)); } HWTEST_F(WifiAuthCenterTest, CheckNetworkStackOrSettingsPermission_GRANTED, TestSize.Level1) @@ -175,7 +175,7 @@ HWTEST_F(WifiAuthCenterTest, CheckNetworkStackOrSettingsPermission_DENIED, TestS permissions[g_wifiPermissions[i].name] = num[i]; } WifiAuthCenter::GetInstance().ChangePermission(permissions, pid, uid); - EXPECT_EQ(PERMISSION_DENIED, WifiAuthCenter::GetInstance().VerifyWifiConnectionPermission(pid, uid)); + EXPECT_EQ(PERMISSION_GRANTED, WifiAuthCenter::GetInstance().VerifyWifiConnectionPermission(pid, uid)); } HWTEST_F(WifiAuthCenterTest, CheckNetworkSettingsPermission_GRANTED, TestSize.Level1) @@ -197,7 +197,7 @@ HWTEST_F(WifiAuthCenterTest, CheckNetworkSettingsPermission_DENIED, TestSize.Lev permissions[g_wifiPermissions[i].name] = num[i]; } WifiAuthCenter::GetInstance().ChangePermission(permissions, pid, uid); - EXPECT_EQ(PERMISSION_DENIED, WifiAuthCenter::GetInstance().VerifyWifiConnectionPermission(pid, uid)); + EXPECT_EQ(PERMISSION_GRANTED, WifiAuthCenter::GetInstance().VerifyWifiConnectionPermission(pid, uid)); } } // namespace Wifi } // namespace OHOS \ No newline at end of file diff --git a/tests/wifi_standard/wifi_framework/wifi_manage/unittest/wifi_auth_center_test.h b/wifi/test/wifi_standard/wifi_framework/wifi_manage/unittest/wifi_auth_center_test.h similarity index 100% rename from tests/wifi_standard/wifi_framework/wifi_manage/unittest/wifi_auth_center_test.h rename to wifi/test/wifi_standard/wifi_framework/wifi_manage/unittest/wifi_auth_center_test.h diff --git a/tests/wifi_standard/wifi_framework/wifi_manage/unittest/wifi_config_center_test.cpp b/wifi/test/wifi_standard/wifi_framework/wifi_manage/unittest/wifi_config_center_test.cpp similarity index 97% rename from tests/wifi_standard/wifi_framework/wifi_manage/unittest/wifi_config_center_test.cpp rename to wifi/test/wifi_standard/wifi_framework/wifi_manage/unittest/wifi_config_center_test.cpp index 9ffa1fa6ad6e3c4b95b197a80015f60556b0a4ce..3b76986d28fd77d4950357ab8e2a126e4c7ba964 100644 --- a/tests/wifi_standard/wifi_framework/wifi_manage/unittest/wifi_config_center_test.cpp +++ b/wifi/test/wifi_standard/wifi_framework/wifi_manage/unittest/wifi_config_center_test.cpp @@ -1,5 +1,5 @@ /* - * Copyright (C) 2021 Huawei Device Co., Ltd. + * Copyright (C) 2021-2022 Huawei Device Co., Ltd. * 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 @@ -90,10 +90,13 @@ HWTEST_F(WifiConfigCenterTest, GetScanInfoList_SUCCESS, TestSize.Level1) WifiScanInfo info1, info2; info1.bssid = "asdfg"; info2.bssid = "adsgds"; + struct timespec clkTime = {0, 0}; + clock_gettime(CLOCK_MONOTONIC, &clkTime); + int64_t curr = static_cast(clkTime.tv_sec) * MSEC * MSEC + clkTime.tv_nsec / MSEC; /* us */ + info1.timestamp = curr; + info2.timestamp = curr; setInfo.push_back(info1); setInfo.push_back(info2); - getInfo.push_back(info1); - getInfo.push_back(info2); WifiSettings::GetInstance().SaveScanInfoList(setInfo); WifiConfigCenter::GetInstance().GetScanInfoList(getInfo); EXPECT_EQ(setInfo.size(), getInfo.size()); @@ -105,14 +108,17 @@ HWTEST_F(WifiConfigCenterTest, GetScanInfoList_FAILED, TestSize.Level1) { std::vector setInfo; std::vector getInfo; - WifiScanInfo info1, info2; + WifiScanInfo info1; + struct timespec clkTime = {0, 0}; + clock_gettime(CLOCK_MONOTONIC, &clkTime); + int64_t curr = static_cast(clkTime.tv_sec) * MSEC * MSEC + clkTime.tv_nsec / MSEC; /* us */ + info1.timestamp = curr; info1.bssid = "asdfg"; - info2.bssid = "adsgds"; setInfo.push_back(info1); - getInfo.push_back(info2); WifiSettings::GetInstance().SaveScanInfoList(setInfo); WifiConfigCenter::GetInstance().GetScanInfoList(getInfo); EXPECT_EQ(setInfo.size(), getInfo.size()); + setInfo.at(0).bssid = "adsgds"; EXPECT_NE(setInfo.at(0).bssid, getInfo.at(0).bssid); } @@ -357,7 +363,7 @@ HWTEST_F(WifiConfigCenterTest, SetGetAirplaneModeState_SUCCESS, TestSize.Level1) HWTEST_F(WifiConfigCenterTest, SetGetAppRunningState_SUCCESS, TestSize.Level1) { - int mode = 1; + ScanMode mode = ScanMode::APP_BACKGROUND_SCAN; WifiConfigCenter::GetInstance().SetAppRunningState(mode); EXPECT_EQ(mode, WifiConfigCenter::GetInstance().GetAppRunningState()); } diff --git a/tests/wifi_standard/wifi_framework/wifi_manage/unittest/wifi_config_center_test.h b/wifi/test/wifi_standard/wifi_framework/wifi_manage/unittest/wifi_config_center_test.h similarity index 100% rename from tests/wifi_standard/wifi_framework/wifi_manage/unittest/wifi_config_center_test.h rename to wifi/test/wifi_standard/wifi_framework/wifi_manage/unittest/wifi_config_center_test.h diff --git a/tests/wifi_standard/wifi_framework/wifi_manage/unittest/wifi_internal_event_dispatcher_test.cpp b/wifi/test/wifi_standard/wifi_framework/wifi_manage/unittest/wifi_internal_event_dispatcher_test.cpp similarity index 89% rename from tests/wifi_standard/wifi_framework/wifi_manage/unittest/wifi_internal_event_dispatcher_test.cpp rename to wifi/test/wifi_standard/wifi_framework/wifi_manage/unittest/wifi_internal_event_dispatcher_test.cpp index 77fa8d06a61993facc6aa01f85c22a450b7289ed..765e0f7cc2dfbec29a68682f0d2d68f72c561865 100644 --- a/tests/wifi_standard/wifi_framework/wifi_manage/unittest/wifi_internal_event_dispatcher_test.cpp +++ b/wifi/test/wifi_standard/wifi_framework/wifi_manage/unittest/wifi_internal_event_dispatcher_test.cpp @@ -20,6 +20,12 @@ using namespace testing::ext; namespace OHOS { namespace Wifi { +/** + * @tc.name: Events notify test + * @tc.desc: Events notify test function. + * @tc.type: FUNC + * @tc.require: issueI5LC60 + */ HWTEST_F(WifiInternalEventDispatcherTest, ThreadTest, TestSize.Level1) { WifiEventCallbackMsg msg; @@ -35,6 +41,9 @@ HWTEST_F(WifiInternalEventDispatcherTest, ThreadTest, TestSize.Level1) msg.msgCode = WIFI_CBK_MSG_RSSI_CHANGE; EXPECT_EQ(0, WifiInternalEventDispatcher::GetInstance().AddBroadCastMsg(msg)); sleep(1); + msg.msgCode = WIFI_CBK_MSG_DEVICE_CONFIG_CHANGE; + EXPECT_EQ(0, WifiInternalEventDispatcher::GetInstance().AddBroadCastMsg(msg)); + sleep(1); msg.msgCode = WIFI_CBK_MSG_HOTSPOT_STATE_CHANGE; EXPECT_EQ(0, WifiInternalEventDispatcher::GetInstance().AddBroadCastMsg(msg)); sleep(1); diff --git a/tests/wifi_standard/wifi_framework/wifi_manage/unittest/wifi_internal_event_dispatcher_test.h b/wifi/test/wifi_standard/wifi_framework/wifi_manage/unittest/wifi_internal_event_dispatcher_test.h similarity index 100% rename from tests/wifi_standard/wifi_framework/wifi_manage/unittest/wifi_internal_event_dispatcher_test.h rename to wifi/test/wifi_standard/wifi_framework/wifi_manage/unittest/wifi_internal_event_dispatcher_test.h diff --git a/tests/wifi_standard/wifi_framework/wifi_manage/unittest/wifi_manager_service_test.cpp b/wifi/test/wifi_standard/wifi_framework/wifi_manage/unittest/wifi_manager_service_test.cpp similarity index 93% rename from tests/wifi_standard/wifi_framework/wifi_manage/unittest/wifi_manager_service_test.cpp rename to wifi/test/wifi_standard/wifi_framework/wifi_manage/unittest/wifi_manager_service_test.cpp index 7afe40a4b86008df637d5467387bf2835953fe17..06b7ed84c7d76dbc0a92d6e28389270dfca05891 100644 --- a/tests/wifi_standard/wifi_framework/wifi_manage/unittest/wifi_manager_service_test.cpp +++ b/wifi/test/wifi_standard/wifi_framework/wifi_manage/unittest/wifi_manager_service_test.cpp @@ -38,7 +38,6 @@ HWTEST_F(WifiManagerServiceTest, StaCloseResTest, TestSize.Level1) ASSERT_TRUE(cbk.OnStaOpenRes != nullptr); ASSERT_TRUE(cbk.OnStaCloseRes != nullptr); cbk.OnStaOpenRes(OperateResState::OPEN_WIFI_SUCCEED); - cbk.OnStaCloseRes(OperateResState::CLOSE_WIFI_FAILED); cbk.OnStaCloseRes(OperateResState::CLOSE_WIFI_CLOSING); cbk.OnStaCloseRes(OperateResState::CLOSE_WIFI_SUCCEED); WifiSettings::GetInstance().SetAirplaneModeState(1); @@ -128,12 +127,12 @@ HWTEST_F(WifiManagerServiceTest, ApStateResTest, TestSize.Level1) IApServiceCallbacks cbk = WifiManager::GetInstance().GetApCallback(); ASSERT_TRUE(cbk.OnApStateChangedEvent != nullptr); - cbk.OnApStateChangedEvent(ApState::AP_STATE_STARTING); - cbk.OnApStateChangedEvent(ApState::AP_STATE_STARTED); - cbk.OnApStateChangedEvent(ApState::AP_STATE_CLOSING); - cbk.OnApStateChangedEvent(ApState::AP_STATE_CLOSED); - cbk.OnApStateChangedEvent(ApState::AP_STATE_IDLE); - cbk.OnApStateChangedEvent(ApState::AP_STATE_NONE); + cbk.OnApStateChangedEvent(ApState::AP_STATE_STARTING, 0); + cbk.OnApStateChangedEvent(ApState::AP_STATE_STARTED, 0); + cbk.OnApStateChangedEvent(ApState::AP_STATE_CLOSING, 0); + cbk.OnApStateChangedEvent(ApState::AP_STATE_CLOSED, 0); + cbk.OnApStateChangedEvent(ApState::AP_STATE_IDLE, 0); + cbk.OnApStateChangedEvent(ApState::AP_STATE_NONE, 0); sleep(2); } @@ -143,7 +142,7 @@ HWTEST_F(WifiManagerServiceTest, ApJoinResTest, TestSize.Level1) ASSERT_TRUE(cbk.OnHotspotStaJoinEvent != nullptr); StationInfo info; - cbk.OnHotspotStaJoinEvent(info); + cbk.OnHotspotStaJoinEvent(info, 0); sleep(1); } @@ -153,7 +152,7 @@ HWTEST_F(WifiManagerServiceTest, ApLeaveResTest, TestSize.Level1) ASSERT_TRUE(cbk.OnHotspotStaLeaveEvent != nullptr); StationInfo info; - cbk.OnHotspotStaLeaveEvent(info); + cbk.OnHotspotStaLeaveEvent(info, 0); sleep(1); } @@ -168,7 +167,7 @@ HWTEST_F(WifiManagerServiceTest, P2pStateChangeTest, TestSize.Level1) cbk.OnP2pStateChangedEvent(P2pState::P2P_STATE_CLOSED); cbk.OnP2pStateChangedEvent(P2pState::P2P_STATE_IDLE); cbk.OnP2pStateChangedEvent(P2pState::P2P_STATE_NONE); - sleep(2); + sleep(3); } HWTEST_F(WifiManagerServiceTest, P2pPeersChangeTest, TestSize.Level1) @@ -196,7 +195,7 @@ HWTEST_F(WifiManagerServiceTest, P2pConnectionChangeTest, TestSize.Level1) IP2pServiceCallbacks cbk = WifiManager::GetInstance().GetP2pCallback(); ASSERT_TRUE(cbk.OnP2pConnectionChangedEvent != nullptr); - WifiP2pInfo info; + WifiP2pLinkedInfo info; cbk.OnP2pConnectionChangedEvent(info); sleep(1); } diff --git a/tests/wifi_standard/wifi_framework/wifi_manage/unittest/wifi_manager_service_test.h b/wifi/test/wifi_standard/wifi_framework/wifi_manage/unittest/wifi_manager_service_test.h similarity index 92% rename from tests/wifi_standard/wifi_framework/wifi_manage/unittest/wifi_manager_service_test.h rename to wifi/test/wifi_standard/wifi_framework/wifi_manage/unittest/wifi_manager_service_test.h index 295bae0aff9cacdf4fb1521b05b3423a5b198fcd..3f518762ad56a66f954d5b7e8f5cf23f01d66d3b 100644 --- a/tests/wifi_standard/wifi_framework/wifi_manage/unittest/wifi_manager_service_test.h +++ b/wifi/test/wifi_standard/wifi_framework/wifi_manage/unittest/wifi_manager_service_test.h @@ -1,5 +1,5 @@ /* - * Copyright (C) 2021 Huawei Device Co., Ltd. + * Copyright (C) 2021-2022 Huawei Device Co., Ltd. * 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 @@ -12,6 +12,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + #ifndef OHOS_WIFI_MANAGER_SERVICE_TEST_H #define OHOS_WIFI_MANAGER_SERVICE_TEST_H @@ -28,7 +29,6 @@ public: } static void TearDownTestCase() { - WifiManager::GetInstance().Exit(); } virtual void SetUp() {} diff --git a/tests/wifi_standard/wifi_framework/wifi_manage/unittest/wifi_mock_p2p_service.cpp b/wifi/test/wifi_standard/wifi_framework/wifi_manage/unittest/wifi_mock_p2p_service.cpp similarity index 95% rename from tests/wifi_standard/wifi_framework/wifi_manage/unittest/wifi_mock_p2p_service.cpp rename to wifi/test/wifi_standard/wifi_framework/wifi_manage/unittest/wifi_mock_p2p_service.cpp index 6a54deee5550effb062746e22e15212c61e315aa..2f635ba57f56e54c57b4bd6c2196d82d03718d72 100644 --- a/tests/wifi_standard/wifi_framework/wifi_manage/unittest/wifi_mock_p2p_service.cpp +++ b/wifi/test/wifi_standard/wifi_framework/wifi_manage/unittest/wifi_mock_p2p_service.cpp @@ -1,5 +1,5 @@ /* - * Copyright (C) 2021 Huawei Device Co., Ltd. + * Copyright (C) 2021-2022 Huawei Device Co., Ltd. * 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 @@ -174,9 +174,9 @@ ErrCode WifiMockP2pService::StopP2pListen() return WIFI_OPT_SUCCESS; } -ErrCode WifiMockP2pService::FormGroup(const WifiP2pConfig &config) +ErrCode WifiMockP2pService::CreateGroup(const WifiP2pConfig &config) { - LOGI("Mock_p2p:FormGroup"); + LOGI("Mock_p2p:CreateGroup"); LOGI("config.GetDeviceAddress() = %s\n", config.GetDeviceAddress().c_str()); LOGI("config.GetGoBand() = %d\n", config.GetGoBand()); LOGI("config.GetNetId() = %d\n", config.GetNetId()); @@ -243,26 +243,26 @@ ErrCode WifiMockP2pService::P2pConnect(const WifiP2pConfig &config) LOGI("config.GetGroupOwnerIntent() = %d\n", config.GetGroupOwnerIntent()); LOGI("config.GetGroupName() = %s\n", config.GetGroupName().c_str()); - WifiP2pInfo connInfo; - connInfo.SetGroupFormed(true); - connInfo.SetIsGroupOwner(true); - connInfo.SetIsGroupOwnerAddress("IsGroupOwnerAddress"); - mCallback.OnP2pConnectionChangedEvent(connInfo); + WifiP2pLinkedInfo linkedInfo; + linkedInfo.SetGroupFormed(true); + linkedInfo.SetIsGroupOwner(true); + linkedInfo.SetIsGroupOwnerAddress("IsGroupOwnerAddress"); + mCallback.OnP2pConnectionChangedEvent(linkedInfo); return WIFI_OPT_SUCCESS; } -ErrCode WifiMockP2pService::P2pDisConnect() +ErrCode WifiMockP2pService::P2pCancelConnect() { - LOGI("Mock_p2p:P2pDisConnect"); + LOGI("Mock_p2p:P2pCancelConnect"); return WIFI_OPT_SUCCESS; } -ErrCode WifiMockP2pService::QueryP2pInfo(WifiP2pInfo &connInfo) +ErrCode WifiMockP2pService::QueryP2pLinkedInfo(WifiP2pLinkedInfo &linkedInfo) { - LOGI("Mock_p2p:QueryP2pInfo"); - connInfo.SetGroupFormed(true); - connInfo.SetIsGroupOwner(true); - connInfo.SetIsGroupOwnerAddress("IsGroupOwnerAddress"); + LOGI("Mock_p2p:QueryP2pLinkedInfo"); + linkedInfo.SetGroupFormed(true); + linkedInfo.SetIsGroupOwner(true); + linkedInfo.SetIsGroupOwnerAddress("IsGroupOwnerAddress"); return WIFI_OPT_SUCCESS; } @@ -323,7 +323,7 @@ ErrCode WifiMockP2pService::GetP2pConnectedStatus(int &status) return WIFI_OPT_SUCCESS; } -ErrCode WifiMockP2pService::QueryP2pDevices(std::vector &devives) +ErrCode WifiMockP2pService::QueryP2pDevices(std::vector &devices) { LOGI("Mock_p2p:QueryP2pDevices"); WifiP2pDevice device1; @@ -341,7 +341,7 @@ ErrCode WifiMockP2pService::QueryP2pDevices(std::vector &devives) device1.SetWpsConfigMethod(TEST_ONE_THOUSAND); device1.SetDeviceCapabilitys(TEST_ONE_THOUSAND); device1.SetGroupCapabilitys(TEST_ONE_THOUSAND); - devives.push_back(device1); + devices.push_back(device1); WifiP2pDevice device2; device2.SetDeviceName("DeviceName2"); device2.SetDeviceAddress("DeviceAddress2"); @@ -357,7 +357,7 @@ ErrCode WifiMockP2pService::QueryP2pDevices(std::vector &devives) device2.SetWpsConfigMethod(TEST_TWO_THOUSAND); device2.SetDeviceCapabilitys(TEST_TWO_THOUSAND); device2.SetGroupCapabilitys(TEST_TWO_THOUSAND); - devives.push_back(device2); + devices.push_back(device2); return WIFI_OPT_SUCCESS; } @@ -429,6 +429,7 @@ extern "C" IP2pService *Create(void) extern "C" void Destroy(IP2pService *p) { delete p; + p = nullptr; } } // namespace Wifi } // namespace OHOS \ No newline at end of file diff --git a/tests/wifi_standard/wifi_framework/wifi_manage/unittest/wifi_mock_p2p_service.h b/wifi/test/wifi_standard/wifi_framework/wifi_manage/unittest/wifi_mock_p2p_service.h similarity index 88% rename from tests/wifi_standard/wifi_framework/wifi_manage/unittest/wifi_mock_p2p_service.h rename to wifi/test/wifi_standard/wifi_framework/wifi_manage/unittest/wifi_mock_p2p_service.h index 23f096944eea5683fd986ab7ca1d28b802d34ed0..407c1fd9a71c676193f8a5b2b1588d869b16547a 100644 --- a/tests/wifi_standard/wifi_framework/wifi_manage/unittest/wifi_mock_p2p_service.h +++ b/wifi/test/wifi_standard/wifi_framework/wifi_manage/unittest/wifi_mock_p2p_service.h @@ -1,5 +1,5 @@ /* - * Copyright (C) 2021 Huawei Device Co., Ltd. + * Copyright (C) 2021-2022 Huawei Device Co., Ltd. * 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 @@ -37,17 +37,17 @@ public: ErrCode DeleteLocalP2pService(const WifiP2pServiceInfo &srvInfo); ErrCode StartP2pListen(int period, int interval); ErrCode StopP2pListen(); - ErrCode FormGroup(const WifiP2pConfig &config); + ErrCode CreateGroup(const WifiP2pConfig &config); ErrCode RemoveGroup(); ErrCode DeleteGroup(const WifiP2pGroupInfo &group); ErrCode P2pConnect(const WifiP2pConfig &config); - ErrCode P2pDisConnect(); - ErrCode QueryP2pInfo(WifiP2pInfo &connInfo); + ErrCode P2pCancelConnect(); + ErrCode QueryP2pLinkedInfo(WifiP2pLinkedInfo &linkedInfo); ErrCode GetCurrentGroup(WifiP2pGroupInfo &group); ErrCode GetP2pEnableStatus(int &status); ErrCode GetP2pDiscoverStatus(int &status); ErrCode GetP2pConnectedStatus(int &status); - ErrCode QueryP2pDevices(std::vector &devives); + ErrCode QueryP2pDevices(std::vector &devices); ErrCode QueryP2pGroups(std::vector &groups); ErrCode QueryP2pServices(std::vector &services); ErrCode RegisterP2pServiceCallbacks(const IP2pServiceCallbacks &callbacks); diff --git a/tests/wifi_standard/wifi_framework/wifi_manage/unittest/wifi_service_manager_test.cpp b/wifi/test/wifi_standard/wifi_framework/wifi_manage/unittest/wifi_service_manager_test.cpp similarity index 100% rename from tests/wifi_standard/wifi_framework/wifi_manage/unittest/wifi_service_manager_test.cpp rename to wifi/test/wifi_standard/wifi_framework/wifi_manage/unittest/wifi_service_manager_test.cpp diff --git a/tests/wifi_standard/wifi_framework/wifi_manage/unittest/wifi_service_manager_test.h b/wifi/test/wifi_standard/wifi_framework/wifi_manage/unittest/wifi_service_manager_test.h similarity index 100% rename from tests/wifi_standard/wifi_framework/wifi_manage/unittest/wifi_service_manager_test.h rename to wifi/test/wifi_standard/wifi_framework/wifi_manage/unittest/wifi_service_manager_test.h diff --git a/wifi/test/wifi_standard/wifi_framework/wifi_manage/wifi_ap/BUILD.gn b/wifi/test/wifi_standard/wifi_framework/wifi_manage/wifi_ap/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..73d676c7a2aa55564aa17ac7b3c6c16abaa6a377 --- /dev/null +++ b/wifi/test/wifi_standard/wifi_framework/wifi_manage/wifi_ap/BUILD.gn @@ -0,0 +1,120 @@ +# Copyright (C) 2021-2022 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import("//build/test.gni") +import("//foundation/communication/wifi/wifi/wifi.gni") +config("module_private_config") { + visibility = [ ":*" ] + include_dirs = [ + "//commonlibrary/c_utils/base/include", + "$WIFI_ROOT_DIR/services/wifi_standard/wifi_framework/wifi_manage/wifi_ap", + ] +} +ohos_unittest("WifiApServiceTest") { + module_out_path = "wifi/ap_test" + sources = [ + "$WIFI_ROOT_DIR/frameworks/native/src/wifi_p2p_msg.cpp", + "$WIFI_ROOT_DIR/services/wifi_standard/wifi_framework/wifi_manage/common/handler.cpp", + "$WIFI_ROOT_DIR/services/wifi_standard/wifi_framework/wifi_manage/common/internal_message.cpp", + "$WIFI_ROOT_DIR/services/wifi_standard/wifi_framework/wifi_manage/common/message_queue.cpp", + "$WIFI_ROOT_DIR/services/wifi_standard/wifi_framework/wifi_manage/common/state.cpp", + "$WIFI_ROOT_DIR/services/wifi_standard/wifi_framework/wifi_manage/common/state_machine.cpp", + "$WIFI_ROOT_DIR/services/wifi_standard/wifi_framework/wifi_manage/wifi_ap/ap_config_use.cpp", + "$WIFI_ROOT_DIR/services/wifi_standard/wifi_framework/wifi_manage/wifi_ap/ap_idle_state.cpp", + "$WIFI_ROOT_DIR/services/wifi_standard/wifi_framework/wifi_manage/wifi_ap/ap_monitor.cpp", + "$WIFI_ROOT_DIR/services/wifi_standard/wifi_framework/wifi_manage/wifi_ap/ap_root_state.cpp", + "$WIFI_ROOT_DIR/services/wifi_standard/wifi_framework/wifi_manage/wifi_ap/ap_service.cpp", + "$WIFI_ROOT_DIR/services/wifi_standard/wifi_framework/wifi_manage/wifi_ap/ap_started_state.cpp", + "$WIFI_ROOT_DIR/services/wifi_standard/wifi_framework/wifi_manage/wifi_ap/ap_state_machine.cpp", + "$WIFI_ROOT_DIR/services/wifi_standard/wifi_framework/wifi_manage/wifi_ap/ap_stations_manager.cpp", + "$WIFI_ROOT_DIR/services/wifi_standard/wifi_framework/wifi_manage/wifi_ap/wifi_ap_nat_manager.cpp", + "$WIFI_ROOT_DIR/services/wifi_standard/wifi_framework/wifi_manage/wifi_common/wifi_chip_capability.cpp", + "./Mock/mock_network_interface.cpp", + "./Mock/mock_system_interface.cpp", + "./Mock/mock_wifi_ap_hal_interface.cpp", + "./Mock/mock_wifi_settings.cpp", + "./Mock/operator_overload.cpp", + "ap_config_use_test.cpp", + "ap_idle_state_test.cpp", + "ap_monitor_test.cpp", + "ap_root_state_test.cpp", + "ap_service_test.cpp", + "ap_started_state_test.cpp", + "ap_state_machine_test.cpp", + "ap_stations_manager_test.cpp", + "global_test.cpp", + "wifi_ap_nat_manager_test.cpp", + ] + include_dirs = [ + "./", + "../", + "./Mock/", + "//commonlibrary/c_utils/base/include", + "//base/hiviewdfx/hilog/interfaces/native/innerkits/include", + "$WIFI_ROOT_DIR/frameworks/native/interfaces", + "$WIFI_ROOT_DIR/services/wifi_standard/ipc_framework/cRPC/include", + "$WIFI_ROOT_DIR/services/wifi_standard/wifi_framework/wifi_toolkit/include", + "$WIFI_ROOT_DIR/services/wifi_standard/wifi_framework/wifi_toolkit/net_helper", + "$WIFI_ROOT_DIR/services/wifi_standard/wifi_framework/wifi_toolkit/config", + "$WIFI_ROOT_DIR/services/wifi_standard/wifi_framework/wifi_toolkit/log", + "$WIFI_ROOT_DIR/services/wifi_standard/wifi_framework/wifi_toolkit/utils", + "$WIFI_ROOT_DIR/services/wifi_standard/wifi_framework/wifi_manage/common/include", + "$WIFI_ROOT_DIR/services/wifi_standard/wifi_framework/wifi_manage/wifi_ap", + "$WIFI_ROOT_DIR/services/wifi_standard/wifi_framework/wifi_manage/wifi_common", + "$WIFI_ROOT_DIR/services/wifi_standard/wifi_framework/wifi_manage", + "$WIFI_ROOT_DIR/services/wifi_standard/wifi_framework/wifi_manage/common", + "$WIFI_ROOT_DIR/services/wifi_standard/wifi_framework/wifi_manage/idl_client", + "$WIFI_ROOT_DIR/services/wifi_standard/wifi_framework/wifi_manage/idl_client/idl_interface", + "$WIFI_ROOT_DIR/utils/inc", + "$DHCP_ROOT_DIR/services/mgr_service/include", + "$DHCP_ROOT_DIR/interfaces/inner_api/include", + "$DHCP_ROOT_DIR/interfaces/inner_api/interfaces", + "//third_party/googletest/googlemock/include", + "//third_party/googletest/googletest/include", + "$WIFI_ROOT_DIR/services/wifi_standard/include", + ] + ldflags = [ + "-fPIC", + "-Wl,-E", + "-Wl,--wrap=system", + "--coverage", + ] + deps = [ + "$DHCP_ROOT_DIR/services/mgr_service:dhcp_manager_service", + "$WIFI_ROOT_DIR/services/wifi_standard/wifi_framework/wifi_manage/idl_client:wifi_idl_client", + "$WIFI_ROOT_DIR/services/wifi_standard/wifi_framework/wifi_toolkit:wifi_toolkit", + "$WIFI_ROOT_DIR/utils:wifi_utils", + "//third_party/googletest:gmock_main", + "//third_party/googletest:gtest_main", + ] + external_deps = [ + "c_utils:utils", + "hiviewdfx_hilog_native:libhilog", + ] + defines = [ + "AP_INTF=\"$wifi_feature_with_ap_intf\"", + "AP_INSTANCE_MAX_NUM=$wifi_feature_with_ap_num", + ] + + if (wifi_feature_with_dhcp_disable) { + defines += [ "WIFI_DHCP_DISABLED" ] + } + + part_name = "wifi" + subsystem_name = "communication" +} +group("unittest") { + testonly = true + deps = [] + deps += [ ":WifiApServiceTest" ] +} diff --git a/tests/wifi_standard/wifi_framework/wifi_manage/wifi_ap/Mock/mock_ap_config_use.h b/wifi/test/wifi_standard/wifi_framework/wifi_manage/wifi_ap/Mock/mock_ap_config_use.h similarity index 96% rename from tests/wifi_standard/wifi_framework/wifi_manage/wifi_ap/Mock/mock_ap_config_use.h rename to wifi/test/wifi_standard/wifi_framework/wifi_manage/wifi_ap/Mock/mock_ap_config_use.h index 5484ac37187be344cfe738f7f03674cc5bfe99fc..97c07dc4e8b51a517d2ba0850fa293e7ed0dc99e 100644 --- a/tests/wifi_standard/wifi_framework/wifi_manage/wifi_ap/Mock/mock_ap_config_use.h +++ b/wifi/test/wifi_standard/wifi_framework/wifi_manage/wifi_ap/Mock/mock_ap_config_use.h @@ -32,7 +32,9 @@ public: MOCK_CONST_METHOD1(IsValid5GHz, bool(int freq)); MOCK_CONST_METHOD2(CheckBandChannel, void(HotspotConfig &apConfig, const ChannelsTable &validChanTable)); MOCK_CONST_METHOD1(TransformFrequencyIntoChannel, int(int freq)); +private: + using ApConfigUse::CheckBandChannel; }; } // namespace Wifi } // namespace OHOS -#endif \ No newline at end of file +#endif diff --git a/tests/wifi_standard/wifi_framework/wifi_manage/wifi_ap/Mock/mock_ap_idle_state.h b/wifi/test/wifi_standard/wifi_framework/wifi_manage/wifi_ap/Mock/mock_ap_idle_state.h similarity index 100% rename from tests/wifi_standard/wifi_framework/wifi_manage/wifi_ap/Mock/mock_ap_idle_state.h rename to wifi/test/wifi_standard/wifi_framework/wifi_manage/wifi_ap/Mock/mock_ap_idle_state.h diff --git a/tests/wifi_standard/wifi_framework/wifi_manage/wifi_ap/Mock/mock_ap_monitor.h b/wifi/test/wifi_standard/wifi_framework/wifi_manage/wifi_ap/Mock/mock_ap_monitor.h similarity index 100% rename from tests/wifi_standard/wifi_framework/wifi_manage/wifi_ap/Mock/mock_ap_monitor.h rename to wifi/test/wifi_standard/wifi_framework/wifi_manage/wifi_ap/Mock/mock_ap_monitor.h diff --git a/tests/wifi_standard/wifi_framework/wifi_manage/wifi_ap/Mock/mock_ap_root_state.h b/wifi/test/wifi_standard/wifi_framework/wifi_manage/wifi_ap/Mock/mock_ap_root_state.h similarity index 100% rename from tests/wifi_standard/wifi_framework/wifi_manage/wifi_ap/Mock/mock_ap_root_state.h rename to wifi/test/wifi_standard/wifi_framework/wifi_manage/wifi_ap/Mock/mock_ap_root_state.h diff --git a/tests/wifi_standard/wifi_framework/wifi_manage/wifi_ap/Mock/mock_ap_service.h b/wifi/test/wifi_standard/wifi_framework/wifi_manage/wifi_ap/Mock/mock_ap_service.h similarity index 100% rename from tests/wifi_standard/wifi_framework/wifi_manage/wifi_ap/Mock/mock_ap_service.h rename to wifi/test/wifi_standard/wifi_framework/wifi_manage/wifi_ap/Mock/mock_ap_service.h diff --git a/tests/wifi_standard/wifi_framework/wifi_manage/wifi_ap/Mock/mock_ap_started_state.h b/wifi/test/wifi_standard/wifi_framework/wifi_manage/wifi_ap/Mock/mock_ap_started_state.h similarity index 93% rename from tests/wifi_standard/wifi_framework/wifi_manage/wifi_ap/Mock/mock_ap_started_state.h rename to wifi/test/wifi_standard/wifi_framework/wifi_manage/wifi_ap/Mock/mock_ap_started_state.h index c129c0d9effa63dc1d4cf8e29a4009c5501ba9a7..a8f20d845c8572b635420f48a0eb42023bf9ed16 100644 --- a/tests/wifi_standard/wifi_framework/wifi_manage/wifi_ap/Mock/mock_ap_started_state.h +++ b/wifi/test/wifi_standard/wifi_framework/wifi_manage/wifi_ap/Mock/mock_ap_started_state.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021 Huawei Device Co., Ltd. + * Copyright (c) 2021-2022 Huawei Device Co., Ltd. * 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 @@ -17,8 +17,9 @@ #define OHOS_MOCK_AP_STARTED_STATE_H #include -#include "wifi_msg.h" #include "ap_started_state.h" +#include "wifi_chip_capability.h" +#include "wifi_msg.h" namespace OHOS { namespace Wifi { @@ -31,7 +32,6 @@ public: MOCK_METHOD0(GoOutState, void()); MOCK_METHOD1(ExecuteStateMsg, bool(InternalMessage *msg)); }; - } // namespace OHOS } // namespace OHOS #endif \ No newline at end of file diff --git a/tests/wifi_standard/wifi_framework/wifi_manage/wifi_ap/Mock/mock_ap_state_machine.h b/wifi/test/wifi_standard/wifi_framework/wifi_manage/wifi_ap/Mock/mock_ap_state_machine.h similarity index 94% rename from tests/wifi_standard/wifi_framework/wifi_manage/wifi_ap/Mock/mock_ap_state_machine.h rename to wifi/test/wifi_standard/wifi_framework/wifi_manage/wifi_ap/Mock/mock_ap_state_machine.h index ce4ddd55f000f336622fb9ae308004224b0feec0..d9f7e36a32dbc1aa20f4ad4dc3384de9f8ed319a 100644 --- a/tests/wifi_standard/wifi_framework/wifi_manage/wifi_ap/Mock/mock_ap_state_machine.h +++ b/wifi/test/wifi_standard/wifi_framework/wifi_manage/wifi_ap/Mock/mock_ap_state_machine.h @@ -35,6 +35,7 @@ public: MOCK_METHOD1(RegisterApServiceCallbacks, ErrCode(const IApServiceCallbacks &callbacks)); MOCK_METHOD0(StartDhcpServer, bool()); MOCK_METHOD0(StopDhcpServer, bool()); + MOCK_METHOD1(GetConnectedStationInfo, bool(std::map &result)); }; } // namespace Wifi } // namespace OHOS diff --git a/tests/wifi_standard/wifi_framework/wifi_manage/wifi_ap/Mock/mock_ap_stations_manager.h b/wifi/test/wifi_standard/wifi_framework/wifi_manage/wifi_ap/Mock/mock_ap_stations_manager.h similarity index 100% rename from tests/wifi_standard/wifi_framework/wifi_manage/wifi_ap/Mock/mock_ap_stations_manager.h rename to wifi/test/wifi_standard/wifi_framework/wifi_manage/wifi_ap/Mock/mock_ap_stations_manager.h diff --git a/tests/wifi_standard/wifi_framework/wifi_manage/wifi_ap/Mock/mock_network_interface.cpp b/wifi/test/wifi_standard/wifi_framework/wifi_manage/wifi_ap/Mock/mock_network_interface.cpp similarity index 95% rename from tests/wifi_standard/wifi_framework/wifi_manage/wifi_ap/Mock/mock_network_interface.cpp rename to wifi/test/wifi_standard/wifi_framework/wifi_manage/wifi_ap/Mock/mock_network_interface.cpp index 1425a00e636b1a3e17e07d5aeee0765cf2692362..eb834c7f4dc082ae705fa9c893ce5f4834703c53 100644 --- a/tests/wifi_standard/wifi_framework/wifi_manage/wifi_ap/Mock/mock_network_interface.cpp +++ b/wifi/test/wifi_standard/wifi_framework/wifi_manage/wifi_ap/Mock/mock_network_interface.cpp @@ -23,6 +23,11 @@ bool IsValidInterfaceName(const std::string &interfaceName) return MockNetworkInterface::GetInstance().IsValidInterfaceName(interfaceName); } +bool IsInterfaceUp(const std::string &interfaceName) +{ + return MockNetworkInterface::GetInstance().IsInterfaceUp(interfaceName); +} + void Dump(const std::string &interfaceName) { MockNetworkInterface::GetInstance().Dump(interfaceName); diff --git a/tests/wifi_standard/wifi_framework/wifi_manage/wifi_ap/Mock/mock_network_interface.h b/wifi/test/wifi_standard/wifi_framework/wifi_manage/wifi_ap/Mock/mock_network_interface.h similarity index 94% rename from tests/wifi_standard/wifi_framework/wifi_manage/wifi_ap/Mock/mock_network_interface.h rename to wifi/test/wifi_standard/wifi_framework/wifi_manage/wifi_ap/Mock/mock_network_interface.h index 64fada9d18a816b5ebfda6b122d6b1b040d75a05..5d82c2c8b04a805d14a03c49b961a0a12ded189b 100644 --- a/tests/wifi_standard/wifi_framework/wifi_manage/wifi_ap/Mock/mock_network_interface.h +++ b/wifi/test/wifi_standard/wifi_framework/wifi_manage/wifi_ap/Mock/mock_network_interface.h @@ -29,6 +29,7 @@ namespace Wifi { class MockNetworkInterface { public: MOCK_METHOD1(IsValidInterfaceName, bool(const std::string &interfaceName)); + MOCK_METHOD1(IsInterfaceUp, bool(const std::string &interfaceName)); MOCK_METHOD1(Dump, void(const std::string &interfaceName)); MOCK_METHOD4(FetchInterfaceConfig, @@ -47,8 +48,8 @@ public: static MockNetworkInterface &GetInstance(void); private: - MockNetworkInterface(){} - ~MockNetworkInterface(){} + MockNetworkInterface() {} + ~MockNetworkInterface() {} }; } // namespace Wifi } // namespace OHOS diff --git a/tests/wifi_standard/wifi_framework/wifi_manage/wifi_ap/Mock/mock_pendant.h b/wifi/test/wifi_standard/wifi_framework/wifi_manage/wifi_ap/Mock/mock_pendant.h similarity index 100% rename from tests/wifi_standard/wifi_framework/wifi_manage/wifi_ap/Mock/mock_pendant.h rename to wifi/test/wifi_standard/wifi_framework/wifi_manage/wifi_ap/Mock/mock_pendant.h diff --git a/tests/wifi_standard/wifi_framework/wifi_manage/wifi_ap/Mock/mock_system_interface.cpp b/wifi/test/wifi_standard/wifi_framework/wifi_manage/wifi_ap/Mock/mock_system_interface.cpp similarity index 100% rename from tests/wifi_standard/wifi_framework/wifi_manage/wifi_ap/Mock/mock_system_interface.cpp rename to wifi/test/wifi_standard/wifi_framework/wifi_manage/wifi_ap/Mock/mock_system_interface.cpp diff --git a/tests/wifi_standard/wifi_framework/wifi_manage/wifi_ap/Mock/mock_system_interface.h b/wifi/test/wifi_standard/wifi_framework/wifi_manage/wifi_ap/Mock/mock_system_interface.h similarity index 100% rename from tests/wifi_standard/wifi_framework/wifi_manage/wifi_ap/Mock/mock_system_interface.h rename to wifi/test/wifi_standard/wifi_framework/wifi_manage/wifi_ap/Mock/mock_system_interface.h diff --git a/tests/wifi_standard/wifi_framework/wifi_manage/wifi_ap/Mock/mock_wifi_ap_hal_interface.cpp b/wifi/test/wifi_standard/wifi_framework/wifi_manage/wifi_ap/Mock/mock_wifi_ap_hal_interface.cpp similarity index 100% rename from tests/wifi_standard/wifi_framework/wifi_manage/wifi_ap/Mock/mock_wifi_ap_hal_interface.cpp rename to wifi/test/wifi_standard/wifi_framework/wifi_manage/wifi_ap/Mock/mock_wifi_ap_hal_interface.cpp diff --git a/tests/wifi_standard/wifi_framework/wifi_manage/wifi_ap/Mock/mock_wifi_ap_hal_interface.h b/wifi/test/wifi_standard/wifi_framework/wifi_manage/wifi_ap/Mock/mock_wifi_ap_hal_interface.h similarity index 46% rename from tests/wifi_standard/wifi_framework/wifi_manage/wifi_ap/Mock/mock_wifi_ap_hal_interface.h rename to wifi/test/wifi_standard/wifi_framework/wifi_manage/wifi_ap/Mock/mock_wifi_ap_hal_interface.h index 6cd3dbdb1cf484fcb5b6f8ab0e8739e40f025584..b2d14dab3c4a8b5bfae42bd8bfe42f7328737753 100644 --- a/tests/wifi_standard/wifi_framework/wifi_manage/wifi_ap/Mock/mock_wifi_ap_hal_interface.h +++ b/wifi/test/wifi_standard/wifi_framework/wifi_manage/wifi_ap/Mock/mock_wifi_ap_hal_interface.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021 Huawei Device Co., Ltd. + * Copyright (c) 2021-2022 Huawei Device Co., Ltd. * 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 @@ -15,7 +15,7 @@ #ifndef OHOS_MOCK_WIFI_AP_HAL_INTERFACE_H #define OHOS_MOCK_WIFI_AP_HAL_INTERFACE_H -#include "wifi_msg.h" + #include #include #include @@ -23,7 +23,7 @@ #include "i_wifi_struct.h" #include "wifi_error_no.h" -#include "wifi_msg.h" +#include "wifi_ap_msg.h" #include #include #include @@ -37,37 +37,39 @@ typedef struct IWifiApMonitorEventCallback { class MockWifiApHalInterface { public: virtual ~MockWifiApHalInterface() = default; - virtual WifiErrorNo StartAp(void) = 0; - virtual WifiErrorNo StopAp(void) = 0; - virtual WifiErrorNo StopAp1(void) = 0; - virtual WifiErrorNo SetSoftApConfig(const HotspotConfig &config) = 0; - virtual WifiErrorNo GetStationList(std::vector &result) = 0; - virtual WifiErrorNo SetHotspotConfig(const int &channel, const std::string &mscb) = 0; - virtual WifiErrorNo AddBlockByMac(const std::string &mac) = 0; - virtual WifiErrorNo DelBlockByMac(const std::string &mac) = 0; - virtual WifiErrorNo RemoveStation(const std::string &mac) = 0; - virtual WifiErrorNo GetFrequenciesByBand(int band, std::vector &frequencies) = 0; - virtual WifiErrorNo RegisterApEvent(IWifiApMonitorEventCallback callback) = 0; - virtual WifiErrorNo SetWifiCountryCode(const std::string &code) = 0; - virtual WifiErrorNo DisconnectStaByMac(const std::string &mac) = 0; + virtual WifiErrorNo StartAp(int id = 0) = 0; + virtual WifiErrorNo StopAp(int id = 0) = 0; + virtual WifiErrorNo SetSoftApConfig(const HotspotConfig &config, int id = 0) = 0; + virtual WifiErrorNo GetStationList(std::vector &result, int id = 0) = 0; + virtual WifiErrorNo AddBlockByMac(const std::string &mac, int id = 0) = 0; + virtual WifiErrorNo DelBlockByMac(const std::string &mac, int id = 0) = 0; + virtual WifiErrorNo RemoveStation(const std::string &mac, int id = 0) = 0; + virtual WifiErrorNo GetFrequenciesByBand(int band, std::vector &frequencies, int id = 0) = 0; + virtual WifiErrorNo RegisterApEvent(IWifiApMonitorEventCallback callback, int id = 0) = 0; + virtual WifiErrorNo SetWifiCountryCode(const std::string &code, int id = 0) = 0; + virtual WifiErrorNo DisconnectStaByMac(const std::string &mac, int id = 0) = 0; + virtual const IWifiApMonitorEventCallback &GetApCallbackInst(int id = 0) const = 0; + virtual WifiErrorNo GetPowerModel(int& model, int id = 0) const = 0; + virtual WifiErrorNo SetPowerModel(const int& model, int id = 0) const = 0; }; class WifiApHalInterface : public MockWifiApHalInterface { public: static WifiApHalInterface &GetInstance(void); - MOCK_METHOD0(StartAp, WifiErrorNo(void)); - MOCK_METHOD0(StopAp1, WifiErrorNo(void)); - MOCK_METHOD0(StopAp, WifiErrorNo(void)); - MOCK_METHOD1(SetSoftApConfig, WifiErrorNo(const HotspotConfig &config)); - MOCK_METHOD1(GetStationList, WifiErrorNo(std::vector &result)); - MOCK_METHOD2(SetHotspotConfig, WifiErrorNo(const int &channel, const std::string &mscb)); - MOCK_METHOD1(AddBlockByMac, WifiErrorNo(const std::string &mac)); - MOCK_METHOD1(DelBlockByMac, WifiErrorNo(const std::string &mac)); - MOCK_METHOD1(RemoveStation, WifiErrorNo(const std::string &mac)); - MOCK_METHOD2(GetFrequenciesByBand, WifiErrorNo(int band, std::vector &frequencies)); - MOCK_METHOD1(RegisterApEvent, WifiErrorNo(IWifiApMonitorEventCallback callback)); - MOCK_METHOD1(SetWifiCountryCode, WifiErrorNo(const std::string &code)); - MOCK_METHOD1(DisconnectStaByMac, WifiErrorNo(const std::string &mac)); + MOCK_METHOD1(StartAp, WifiErrorNo(int id)); + MOCK_METHOD1(StopAp, WifiErrorNo(int id)); + MOCK_METHOD2(SetSoftApConfig, WifiErrorNo(const HotspotConfig &config, int id)); + MOCK_METHOD2(GetStationList, WifiErrorNo(std::vector &result, int id)); + MOCK_METHOD2(AddBlockByMac, WifiErrorNo(const std::string &mac, int id)); + MOCK_METHOD2(DelBlockByMac, WifiErrorNo(const std::string &mac, int id)); + MOCK_METHOD2(RemoveStation, WifiErrorNo(const std::string &mac, int id)); + MOCK_METHOD3(GetFrequenciesByBand, WifiErrorNo(int band, std::vector &frequencies, int id)); + MOCK_METHOD2(RegisterApEvent, WifiErrorNo(IWifiApMonitorEventCallback callback, int id)); + MOCK_METHOD2(SetWifiCountryCode, WifiErrorNo(const std::string &code, int id)); + MOCK_METHOD2(DisconnectStaByMac, WifiErrorNo(const std::string &mac, int id)); + MOCK_CONST_METHOD1(GetApCallbackInst, IWifiApMonitorEventCallback &(int id)); + MOCK_CONST_METHOD2(GetPowerModel, WifiErrorNo(int& model, int id)); + MOCK_CONST_METHOD2(SetPowerModel, WifiErrorNo(const int& model, int id)); }; } // namespace Wifi } // namespace OHOS diff --git a/tests/wifi_standard/wifi_framework/wifi_manage/wifi_ap/Mock/mock_wifi_ap_nat_manager.h b/wifi/test/wifi_standard/wifi_framework/wifi_manage/wifi_ap/Mock/mock_wifi_ap_nat_manager.h similarity index 100% rename from tests/wifi_standard/wifi_framework/wifi_manage/wifi_ap/Mock/mock_wifi_ap_nat_manager.h rename to wifi/test/wifi_standard/wifi_framework/wifi_manage/wifi_ap/Mock/mock_wifi_ap_nat_manager.h diff --git a/tests/wifi_standard/wifi_framework/wifi_manage/wifi_ap/Mock/mock_wifi_settings.cpp b/wifi/test/wifi_standard/wifi_framework/wifi_manage/wifi_ap/Mock/mock_wifi_settings.cpp similarity index 100% rename from tests/wifi_standard/wifi_framework/wifi_manage/wifi_ap/Mock/mock_wifi_settings.cpp rename to wifi/test/wifi_standard/wifi_framework/wifi_manage/wifi_ap/Mock/mock_wifi_settings.cpp diff --git a/tests/wifi_standard/wifi_framework/wifi_manage/wifi_ap/Mock/mock_wifi_settings.h b/wifi/test/wifi_standard/wifi_framework/wifi_manage/wifi_ap/Mock/mock_wifi_settings.h similarity index 48% rename from tests/wifi_standard/wifi_framework/wifi_manage/wifi_ap/Mock/mock_wifi_settings.h rename to wifi/test/wifi_standard/wifi_framework/wifi_manage/wifi_ap/Mock/mock_wifi_settings.h index e86e8373300c374298d4ea3a21cb31f04e72129b..9e686d9af31291bbc136dfb8b2c7488801423e1f 100644 --- a/tests/wifi_standard/wifi_framework/wifi_manage/wifi_ap/Mock/mock_wifi_settings.h +++ b/wifi/test/wifi_standard/wifi_framework/wifi_manage/wifi_ap/Mock/mock_wifi_settings.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021 Huawei Device Co., Ltd. + * Copyright (c) 2021-2022 Huawei Device Co., Ltd. * 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 @@ -19,7 +19,7 @@ #include #include -#include "wifi_msg.h" +#include "wifi_ap_msg.h" #include namespace OHOS { @@ -36,21 +36,27 @@ public: virtual ~MockWifiSettings() = default; virtual int SetCountryCode(const std::string &countryCode) = 0; virtual int GetCountryCode(std::string &countryCode) = 0; - virtual int GetHotspotState() = 0; - virtual int SetHotspotState(int state) = 0; - virtual int SetHotspotConfig(const HotspotConfig &config) = 0; - virtual int GetHotspotConfig(HotspotConfig &config) = 0; - virtual int GetStationList(std::vector &results) = 0; - virtual int ManageStation(const StationInfo &info, int mode) = 0; /* add / update / remove */ - virtual int ClearStationList() = 0; - virtual int GetBlockList(std::vector &results) = 0; - virtual int ManageBlockList(const StationInfo &info, int mode) = 0; /* add / remove */ - virtual int FindConnStation(const StationInfo &info) = 0; + virtual int GetHotspotState(int id = 0) = 0; + virtual int SetHotspotState(int state, int id = 0) = 0; + virtual int SetHotspotConfig(const HotspotConfig &config, int id = 0) = 0; + virtual int GetHotspotConfig(HotspotConfig &config, int id = 0) = 0; + virtual int GetStationList(std::vector &results, int id = 0) = 0; + virtual int ManageStation(const StationInfo &info, int mode, int id = 0) = 0; /* add / update / remove */ + virtual int ClearStationList(int id = 0) = 0; + virtual int GetBlockList(std::vector &results, int id = 0) = 0; + virtual int ManageBlockList(const StationInfo &info, int mode, int id = 0) = 0; /* add / remove */ + virtual int FindConnStation(const StationInfo &info, int id = 0) = 0; virtual int GetValidBands(std::vector &bands) = 0; virtual int SetValidChannels(const ChannelsTable &channelsInfo) = 0; virtual int GetValidChannels(ChannelsTable &channelsInfo) = 0; virtual int ClearValidChannels() = 0; virtual int GetApMaxConnNum() = 0; + virtual void SetDefaultFrequenciesByCountryBand(const BandType band, std::vector &frequencies) = 0; + virtual std::string GetConnectTimeoutBssid() = 0; + virtual int SetConnectTimeoutBssid(std::string &bssid) = 0; + virtual int SyncHotspotConfig() = 0; + virtual int SetPowerModel(const PowerModel& model, int id = 0) = 0; + virtual int GetPowerModel(PowerModel& model, int id = 0) = 0; }; class WifiSettings : public MockWifiSettings { @@ -58,25 +64,30 @@ public: WifiSettings() = default; ~WifiSettings() = default; static WifiSettings &GetInstance(void); - MOCK_METHOD1(SetCountryCode, int(const std::string &countryCode)); MOCK_METHOD1(GetCountryCode, int(std::string &countryCode)); - MOCK_METHOD0(GetHotspotState, int()); - MOCK_METHOD1(SetHotspotState, int(int)); - MOCK_METHOD1(SetHotspotConfig, int(const HotspotConfig &config)); - MOCK_METHOD1(GetHotspotConfig, int(HotspotConfig &config)); - MOCK_METHOD1(GetStationList, int(std::vector &results)); - MOCK_METHOD2(ManageStation, int(const StationInfo &info, int mode)); - MOCK_METHOD0(ClearStationList, int()); - MOCK_METHOD1(GetBlockList, int(std::vector &results)); - MOCK_METHOD2(ManageBlockList, int(const StationInfo &info, int mode)); - MOCK_METHOD1(FindConnStation, int(const StationInfo &info)); + MOCK_METHOD1(GetHotspotState, int(int id)); + MOCK_METHOD2(SetHotspotState, int(int state, int id)); + MOCK_METHOD2(SetHotspotConfig, int(const HotspotConfig &config, int id)); + MOCK_METHOD2(GetHotspotConfig, int(HotspotConfig &config, int id)); + MOCK_METHOD2(GetStationList, int(std::vector &results, int id)); + MOCK_METHOD3(ManageStation, int(const StationInfo &info, int mode, int id)); + MOCK_METHOD1(ClearStationList, int(int id)); + MOCK_METHOD2(GetBlockList, int(std::vector &results, int id)); + MOCK_METHOD3(ManageBlockList, int(const StationInfo &info, int mode, int id)); + MOCK_METHOD2(FindConnStation, int(const StationInfo &info, int id)); MOCK_METHOD1(GetValidBands, int(std::vector &bands)); MOCK_METHOD1(SetValidChannels, int(const ChannelsTable &channelsInfo)); MOCK_METHOD1(GetValidChannels, int(ChannelsTable &channelsInfo)); MOCK_METHOD0(ClearValidChannels, int()); MOCK_METHOD0(GetApMaxConnNum, int()); + MOCK_METHOD2(SetDefaultFrequenciesByCountryBand, void(const BandType band, std::vector &frequencies)); + MOCK_METHOD0(GetConnectTimeoutBssid, std::string()); + MOCK_METHOD1(SetConnectTimeoutBssid, int(std::string &bssid)); + MOCK_METHOD0(SyncHotspotConfig, int()); + MOCK_METHOD2(SetPowerModel, int(const PowerModel& model, int id)); + MOCK_METHOD2(GetPowerModel, int(PowerModel& model, int id)); }; } /* namespace Wifi */ } /* namespace OHOS */ -#endif \ No newline at end of file +#endif diff --git a/tests/wifi_standard/wifi_framework/wifi_manage/wifi_ap/Mock/operator_overload.cpp b/wifi/test/wifi_standard/wifi_framework/wifi_manage/wifi_ap/Mock/operator_overload.cpp similarity index 100% rename from tests/wifi_standard/wifi_framework/wifi_manage/wifi_ap/Mock/operator_overload.cpp rename to wifi/test/wifi_standard/wifi_framework/wifi_manage/wifi_ap/Mock/operator_overload.cpp diff --git a/tests/wifi_standard/wifi_framework/wifi_manage/wifi_ap/Mock/operator_overload.h b/wifi/test/wifi_standard/wifi_framework/wifi_manage/wifi_ap/Mock/operator_overload.h similarity index 91% rename from tests/wifi_standard/wifi_framework/wifi_manage/wifi_ap/Mock/operator_overload.h rename to wifi/test/wifi_standard/wifi_framework/wifi_manage/wifi_ap/Mock/operator_overload.h index 3a63a5b10d4eba7ab904bde4340321a70aba3aab..9531d2ed73d21716e65a7886fc48331ec8e72f6e 100644 --- a/tests/wifi_standard/wifi_framework/wifi_manage/wifi_ap/Mock/operator_overload.h +++ b/wifi/test/wifi_standard/wifi_framework/wifi_manage/wifi_ap/Mock/operator_overload.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021 Huawei Device Co., Ltd. + * Copyright (c) 2021-2022 Huawei Device Co., Ltd. * 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 @@ -16,7 +16,7 @@ #ifndef OHOS_OPERATOR_OVERLOAD_H #define OHOS_OPERATOR_OVERLOAD_H -#include "wifi_msg.h" +#include "wifi_ap_msg.h" namespace OHOS { namespace Wifi { diff --git a/tests/wifi_standard/wifi_framework/wifi_manage/wifi_ap/wifi_hotspot_test/ap_config_use_test.cpp b/wifi/test/wifi_standard/wifi_framework/wifi_manage/wifi_ap/ap_config_use_test.cpp similarity index 81% rename from tests/wifi_standard/wifi_framework/wifi_manage/wifi_ap/wifi_hotspot_test/ap_config_use_test.cpp rename to wifi/test/wifi_standard/wifi_framework/wifi_manage/wifi_ap/ap_config_use_test.cpp index 5ef03b534a049329231624e3018126d37a0ccd26..65947eb2b67dbf86f1114001d87ed2d944ff4f10 100644 --- a/tests/wifi_standard/wifi_framework/wifi_manage/wifi_ap/wifi_hotspot_test/ap_config_use_test.cpp +++ b/wifi/test/wifi_standard/wifi_framework/wifi_manage/wifi_ap/ap_config_use_test.cpp @@ -25,6 +25,7 @@ using ::testing::DoAll; using ::testing::Eq; using ::testing::Return; using ::testing::StrEq; +using ::testing::ext::TestSize; namespace OHOS { namespace Wifi { @@ -35,12 +36,16 @@ std::map> ChanTbs; class ApConfigUse_Test : public testing::Test { public: - static void SetUpTestCase() - {} - static void TearDownTestCase() - {} + static void SetUpTestCase() {} + static void TearDownTestCase() {} virtual void SetUp() { + allowed5GFreq.clear(); + allowed2GFreq.clear(); + allowed2GChan.clear(); + allowed5GChan.clear(); + allowedFreqCom.clear(); + ChanTbs.clear(); const int testFreq1 = 2412; const int testFreq2 = 2417; const int testFreq3 = 2472; @@ -82,12 +87,14 @@ public: } virtual void TearDown() { - allowed2GFreq.clear(); allowed5GFreq.clear(); + allowed2GFreq.clear(); allowed2GChan.clear(); allowed5GChan.clear(); - + allowedFreqCom.clear(); + ChanTbs.clear(); delete pApConfigUse; + pApConfigUse = nullptr; } public: @@ -95,7 +102,7 @@ public: }; /* TransformFrequencyIntoChannel */ -TEST_F(ApConfigUse_Test, TransformFrequencyIntoChannel) +HWTEST_F(ApConfigUse_Test, TransformFrequencyIntoChannel, TestSize.Level1) { const int testFreq1 = 2412; const int testFreq2 = 2417; @@ -130,7 +137,7 @@ TEST_F(ApConfigUse_Test, TransformFrequencyIntoChannel) EXPECT_EQ(-1, pApConfigUse->TransformFrequencyIntoChannel(testFreq05)); } /* TransformFrequencyIntoChannel_overload */ -TEST_F(ApConfigUse_Test, TransformFrequencyIntoChannel_1) +HWTEST_F(ApConfigUse_Test, TransformFrequencyIntoChannel_1, TestSize.Level1) { const int testFreq1 = 2412; const int testFreq2 = 2417; @@ -160,7 +167,7 @@ TEST_F(ApConfigUse_Test, TransformFrequencyIntoChannel_1) EXPECT_EQ(FreqVector1, FreqVector); } /* SetConfig */ -TEST_F(ApConfigUse_Test, LogConfig_SUCCESS) +HWTEST_F(ApConfigUse_Test, LogConfig_SUCCESS, TestSize.Level1) { HotspotConfig apConfig; apConfig.SetBand(BandType::BAND_2GHZ); @@ -170,7 +177,7 @@ TEST_F(ApConfigUse_Test, LogConfig_SUCCESS) } /* IsValid24GHz */ -TEST_F(ApConfigUse_Test, IsValid24GHz) +HWTEST_F(ApConfigUse_Test, IsValid24GHz, TestSize.Level1) { EXPECT_FALSE(pApConfigUse->IsValid24GHz(2400)); EXPECT_FALSE(pApConfigUse->IsValid24GHz(2500)); @@ -179,7 +186,7 @@ TEST_F(ApConfigUse_Test, IsValid24GHz) EXPECT_FALSE(pApConfigUse->IsValid24GHz(2499)); } /* IsValid5GHz */ -TEST_F(ApConfigUse_Test, IsValid5GHz) +HWTEST_F(ApConfigUse_Test, IsValid5GHz, TestSize.Level1) { EXPECT_FALSE(pApConfigUse->IsValid5GHz(4900)); EXPECT_FALSE(pApConfigUse->IsValid5GHz(5169)); @@ -189,32 +196,32 @@ TEST_F(ApConfigUse_Test, IsValid5GHz) } /* CheckBandChannel */ -TEST_F(ApConfigUse_Test, CheckBandChannel_1) +HWTEST_F(ApConfigUse_Test, CheckBandChannel_1, TestSize.Level1) { HotspotConfig apConfig; apConfig.SetBand(BandType::BAND_2GHZ); apConfig.SetChannel(2); HotspotConfig apConfig1 = apConfig; - std::vector band_2G_channel = {1, 2, 3, 4, 5, 6, 7}; - std::vector band_5G_channel = {149, 168, 169}; - ChannelsTable ChannelsTb = {{BandType::BAND_2GHZ, band_2G_channel}, {BandType::BAND_5GHZ, band_5G_channel}}; + std::vector band_2G_channel = { 1, 2, 3, 4, 5, 6, 7 }; + std::vector band_5G_channel = { 149, 168, 169 }; + ChannelsTable ChannelsTb = { { BandType::BAND_2GHZ, band_2G_channel }, { BandType::BAND_5GHZ, band_5G_channel } }; pApConfigUse->CheckBandChannel(apConfig, ChannelsTb); EXPECT_EQ(apConfig1, apConfig); } -TEST_F(ApConfigUse_Test, CheckBandChannel_2) +HWTEST_F(ApConfigUse_Test, CheckBandChannel_2, TestSize.Level1) { HotspotConfig apConfig; apConfig.SetBand(BandType::BAND_2GHZ); apConfig.SetChannel(9); - std::vector band_2G_channel = {1, 2, 3, 4, 5, 6, 7}; - std::vector band_5G_channel = {149, 168, 169}; - ChannelsTable ChannelsTb = {{BandType::BAND_2GHZ, band_2G_channel}, {BandType::BAND_5GHZ, band_5G_channel}}; + std::vector band_2G_channel = { 1, 2, 3, 4, 5, 6, 7 }; + std::vector band_5G_channel = { 149, 168, 169 }; + ChannelsTable ChannelsTb = { { BandType::BAND_2GHZ, band_2G_channel }, { BandType::BAND_5GHZ, band_5G_channel } }; pApConfigUse->CheckBandChannel(apConfig, ChannelsTb); - EXPECT_EQ(apConfig.GetChannel(), 6); + EXPECT_EQ(apConfig.GetChannel(), 1); EXPECT_EQ(apConfig.GetBand(), BandType::BAND_2GHZ); } -TEST_F(ApConfigUse_Test, CheckBandChannel_3) +HWTEST_F(ApConfigUse_Test, CheckBandChannel_3, TestSize.Level1) { HotspotConfig apConfig; ChannelsTable ChannelsTb; @@ -222,5 +229,5 @@ TEST_F(ApConfigUse_Test, CheckBandChannel_3) EXPECT_EQ(apConfig.GetChannel(), 6); EXPECT_EQ(apConfig.GetBand(), BandType::BAND_2GHZ); } -} // namespace Wifi -} // namespace OHOS \ No newline at end of file +} // namespace Wifi +} // namespace OHOS \ No newline at end of file diff --git a/tests/wifi_standard/wifi_framework/wifi_manage/wifi_ap/wifi_hotspot_test/ap_idle_state_test.cpp b/wifi/test/wifi_standard/wifi_framework/wifi_manage/wifi_ap/ap_idle_state_test.cpp similarity index 72% rename from tests/wifi_standard/wifi_framework/wifi_manage/wifi_ap/wifi_hotspot_test/ap_idle_state_test.cpp rename to wifi/test/wifi_standard/wifi_framework/wifi_manage/wifi_ap/ap_idle_state_test.cpp index 73a20c24d40720919ff41a1f62283df6e814be70..0f1fb5e6ea5fbca23da539e942de01e44421a6f5 100644 --- a/tests/wifi_standard/wifi_framework/wifi_manage/wifi_ap/wifi_hotspot_test/ap_idle_state_test.cpp +++ b/wifi/test/wifi_standard/wifi_framework/wifi_manage/wifi_ap/ap_idle_state_test.cpp @@ -23,71 +23,83 @@ using namespace OHOS; using ::testing::_; using ::testing::Return; +using ::testing::ext::TestSize; namespace OHOS { namespace Wifi { class ApIdleState_test : public testing::Test { public: - static void SetUpTestCase() - {} - static void TearDownTestCase() - {} + static void SetUpTestCase() {} + static void TearDownTestCase() {} virtual void SetUp() { + const int SLEEP_TIEM = 20; pMockPendant = new MockPendant(); pMockPendant->GetMockApStateMachine().InitialStateMachine(); + pApIdleState = new ApIdleState(pMockPendant->GetMockApStateMachine()); + + msg = new InternalMessage(); + usleep(SLEEP_TIEM); } virtual void TearDown() { - EXPECT_CALL(WifiApHalInterface::GetInstance(), RegisterApEvent(_)) - .WillOnce(Return(WifiErrorNo::WIFI_IDL_OPT_OK)); delete pApIdleState; + pApIdleState = nullptr; + delete pMockPendant; + pMockPendant = nullptr; + + delete msg; + + msg = nullptr; } public: MockPendant *pMockPendant; + ApIdleState *pApIdleState; + + InternalMessage *msg; }; -TEST_F(ApIdleState_test, ExecuteStateMsg_SUCCESS) +HWTEST_F(ApIdleState_test, GoInState, TestSize.Level1) +{ + pApIdleState->GoInState(); +} +HWTEST_F(ApIdleState_test, GoOutState, TestSize.Level1) { - InternalMessage *msg = new InternalMessage(); + pApIdleState->GoOutState(); +} + +HWTEST_F(ApIdleState_test, ExecuteStateMsg_SUCCESS, TestSize.Level1) +{ + EXPECT_CALL(WifiApHalInterface::GetInstance(), RegisterApEvent(_, 0)) + .WillRepeatedly(Return(WifiErrorNo::WIFI_IDL_OPT_OK)); + msg->SetMessageName(static_cast(ApStatemachineEvent::CMD_UPDATE_HOTSPOTCONFIG_RESULT)); + EXPECT_TRUE(pApIdleState->ExecuteStateMsg(msg)); msg->SetMessageName(static_cast(ApStatemachineEvent::CMD_START_HOTSPOT)); + EXPECT_TRUE(pApIdleState->ExecuteStateMsg(msg)); - delete msg; } -TEST_F(ApIdleState_test, ExecuteStateMsg_FAILED) +HWTEST_F(ApIdleState_test, ExecuteStateMsg_FAILED, TestSize.Level1) { - InternalMessage *msg = new InternalMessage(); - msg->SetMessageName(static_cast(ApStatemachineEvent::CMD_SET_HOTSPOT_CONFIG)); + EXPECT_FALSE(pApIdleState->ExecuteStateMsg(msg)); msg->SetMessageName(static_cast(ApStatemachineEvent::CMD_DISCONNECT_STATION)); - EXPECT_FALSE(pApIdleState->ExecuteStateMsg(msg)); - msg = nullptr; EXPECT_FALSE(pApIdleState->ExecuteStateMsg(msg)); - delete msg; -} - -TEST_F(ApIdleState_test, GoInState) -{ - pApIdleState->GoInState(); -} -TEST_F(ApIdleState_test, GoOutState) -{ - pApIdleState->GoOutState(); + EXPECT_FALSE(pApIdleState->ExecuteStateMsg(nullptr)); } -} // namespace Wifi -} // namespace OHOS \ No newline at end of file +} // namespace Wifi +} // namespace OHOS \ No newline at end of file diff --git a/tests/wifi_standard/wifi_framework/wifi_manage/wifi_ap/wifi_hotspot_test/ap_monitor_test.cpp b/wifi/test/wifi_standard/wifi_framework/wifi_manage/wifi_ap/ap_monitor_test.cpp similarity index 57% rename from tests/wifi_standard/wifi_framework/wifi_manage/wifi_ap/wifi_hotspot_test/ap_monitor_test.cpp rename to wifi/test/wifi_standard/wifi_framework/wifi_manage/wifi_ap/ap_monitor_test.cpp index dcef929ccdf8fc196e2b8bd51857c5184b476783..01622800e1ed621762ed148865c0a2a0fc97a48b 100644 --- a/tests/wifi_standard/wifi_framework/wifi_manage/wifi_ap/wifi_hotspot_test/ap_monitor_test.cpp +++ b/wifi/test/wifi_standard/wifi_framework/wifi_manage/wifi_ap/ap_monitor_test.cpp @@ -25,6 +25,7 @@ using ::testing::DoAll; using ::testing::Eq; using ::testing::Return; using ::testing::TypedEq; +using ::testing::ext::TestSize; namespace OHOS { namespace Wifi { @@ -39,19 +40,16 @@ const int AP_DISABLE = 110; const int AP_FAILED = 111; class ApMonitor_Test : public testing::Test { public: - static void SetUpTestCase() - {} - static void TearDownTestCase() - {} + static void SetUpTestCase() {} + static void TearDownTestCase() {} virtual void SetUp() { pApMonitor = new ApMonitor(); } virtual void TearDown() { - EXPECT_CALL(WifiApHalInterface::GetInstance(), RegisterApEvent(_)) - .WillOnce(Return(WifiErrorNo::WIFI_IDL_OPT_OK)); delete pApMonitor; + pApMonitor = nullptr; } public: @@ -67,61 +65,80 @@ public: /* StationChangeEvent */ -TEST_F(ApMonitor_Test, StationChangeEvent_JOIN) +HWTEST_F(ApMonitor_Test, StationChangeEvent_JOIN, TestSize.Level1) { + EXPECT_CALL(WifiApHalInterface::GetInstance(), RegisterApEvent(_, 0)) + .WillRepeatedly(Return(WifiErrorNo::WIFI_IDL_OPT_OK)); const int type = 105; - EXPECT_CALL(WifiApHalInterface::GetInstance(), RegisterApEvent(_)).WillOnce(Return(WifiErrorNo::WIFI_IDL_OPT_OK)); pApMonitor->StartMonitor(); WifiApConnectionNofify cInfo; cInfo.type = type; cInfo.mac = "AA:BB:CC:DD:EE:FF"; pApMonitor->OnStaJoinOrLeave(cInfo); } -TEST_F(ApMonitor_Test, StationChangeEvent_LEAVE) +HWTEST_F(ApMonitor_Test, StationChangeEvent_LEAVE, TestSize.Level1) { + EXPECT_CALL(WifiApHalInterface::GetInstance(), RegisterApEvent(_, 0)) + .WillRepeatedly(Return(WifiErrorNo::WIFI_IDL_OPT_OK)); const int type = 106; + pApMonitor->StartMonitor(); WifiApConnectionNofify cInfo; cInfo.type = type; cInfo.mac = "AA:BB:CC:DD:EE:FF"; pApMonitor->OnStaJoinOrLeave(cInfo); } -TEST_F(ApMonitor_Test, StationChangeEvent_NULL) +HWTEST_F(ApMonitor_Test, StationChangeEvent_NULL, TestSize.Level1) { + EXPECT_CALL(WifiApHalInterface::GetInstance(), RegisterApEvent(_, 0)) + .WillRepeatedly(Return(WifiErrorNo::WIFI_IDL_OPT_OK)); + pApMonitor->StartMonitor(); WifiApConnectionNofify cInfo; pApMonitor->OnStaJoinOrLeave(cInfo); } /* OnHotspotStateEvent */ -TEST_F(ApMonitor_Test, OnHotspotStateEvent_ENABLE) +HWTEST_F(ApMonitor_Test, OnHotspotStateEvent_ENABLE, TestSize.Level1) { + EXPECT_CALL(WifiApHalInterface::GetInstance(), RegisterApEvent(_, 0)) + .WillRepeatedly(Return(WifiErrorNo::WIFI_IDL_OPT_OK)); + pApMonitor->StartMonitor(); pApMonitor->OnHotspotStateEvent(AP_ENABLE); } -TEST_F(ApMonitor_Test, OnHotspotStateEvent_DISABLE) +HWTEST_F(ApMonitor_Test, OnHotspotStateEvent_DISABLE, TestSize.Level1) { + EXPECT_CALL(WifiApHalInterface::GetInstance(), RegisterApEvent(_, 0)) + .WillRepeatedly(Return(WifiErrorNo::WIFI_IDL_OPT_OK)); + pApMonitor->StartMonitor(); pApMonitor->OnHotspotStateEvent(AP_DISABLE); } -TEST_F(ApMonitor_Test, OnHotspotStateEvent_FAILED) +HWTEST_F(ApMonitor_Test, OnHotspotStateEvent_FAILED, TestSize.Level1) { + EXPECT_CALL(WifiApHalInterface::GetInstance(), RegisterApEvent(_, 0)) + .WillRepeatedly(Return(WifiErrorNo::WIFI_IDL_OPT_OK)); + pApMonitor->StartMonitor(); pApMonitor->OnHotspotStateEvent(AP_FAILED); } /* StartMonitor */ -TEST_F(ApMonitor_Test, StartMonitor_SUCCESS) +HWTEST_F(ApMonitor_Test, StartMonitor_SUCCESS, TestSize.Level1) { - EXPECT_CALL(WifiApHalInterface::GetInstance(), RegisterApEvent(_)).WillOnce(Return(WifiErrorNo::WIFI_IDL_OPT_OK)); + EXPECT_CALL(WifiApHalInterface::GetInstance(), RegisterApEvent(_, 0)) + .WillRepeatedly(Return(WifiErrorNo::WIFI_IDL_OPT_OK)); pApMonitor->StartMonitor(); } /* StopMonitor */ -TEST_F(ApMonitor_Test, StopMonitor_SUCCESS) +HWTEST_F(ApMonitor_Test, StopMonitor_SUCCESS, TestSize.Level1) { - EXPECT_CALL(WifiApHalInterface::GetInstance(), RegisterApEvent(An())) - .WillOnce(Return(WifiErrorNo::WIFI_IDL_OPT_OK)); + EXPECT_CALL(WifiApHalInterface::GetInstance(), RegisterApEvent(_, 0)) + .WillRepeatedly(Return(WifiErrorNo::WIFI_IDL_OPT_OK)); pApMonitor->StopMonitor(); } /* UnregisterHandler */ -TEST_F(ApMonitor_Test, UnregisterHandler_SUCCESS) +HWTEST_F(ApMonitor_Test, UnregisterHandler_SUCCESS, TestSize.Level1) { + EXPECT_CALL(WifiApHalInterface::GetInstance(), RegisterApEvent(_, 0)) + .WillRepeatedly(Return(WifiErrorNo::WIFI_IDL_OPT_OK)); WraUnregisterHandler("wlan1"); } } // namespace Wifi diff --git a/tests/wifi_standard/wifi_framework/wifi_manage/wifi_ap/wifi_hotspot_test/ap_root_state_test.cpp b/wifi/test/wifi_standard/wifi_framework/wifi_manage/wifi_ap/ap_root_state_test.cpp similarity index 73% rename from tests/wifi_standard/wifi_framework/wifi_manage/wifi_ap/wifi_hotspot_test/ap_root_state_test.cpp rename to wifi/test/wifi_standard/wifi_framework/wifi_manage/wifi_ap/ap_root_state_test.cpp index 907b1744bc500673dd7527a939cfdb71c7d7e999..36301ed34bec4126468d2077a05dd0787d6d603a 100644 --- a/tests/wifi_standard/wifi_framework/wifi_manage/wifi_ap/wifi_hotspot_test/ap_root_state_test.cpp +++ b/wifi/test/wifi_standard/wifi_framework/wifi_manage/wifi_ap/ap_root_state_test.cpp @@ -21,15 +21,20 @@ #include "ap_root_state.h" using namespace OHOS; +using ::testing::_; +using ::testing::An; +using ::testing::DoAll; +using ::testing::Eq; +using ::testing::Return; +using ::testing::TypedEq; +using ::testing::ext::TestSize; namespace OHOS { namespace Wifi { class ApRootState_test : public testing::Test { public: - static void SetUpTestCase() - {} - static void TearDownTestCase() - {} + static void SetUpTestCase() {} + static void TearDownTestCase() {} virtual void SetUp() { pApRootState = new ApRootState(); @@ -37,13 +42,14 @@ public: virtual void TearDown() { delete pApRootState; + pApRootState = nullptr; } public: ApRootState *pApRootState; }; -TEST_F(ApRootState_test, ExecuteStateMsg_SUCCESS) +HWTEST_F(ApRootState_test, ExecuteStateMsg_SUCCESS, TestSize.Level1) { InternalMessage *msg = new InternalMessage(); @@ -55,21 +61,20 @@ TEST_F(ApRootState_test, ExecuteStateMsg_SUCCESS) msg->SetMessageName(static_cast(ApStatemachineEvent::CMD_SET_HOTSPOT_CONFIG)); EXPECT_TRUE(pApRootState->ExecuteStateMsg(msg)); - delete msg; + msg = nullptr; } -TEST_F(ApRootState_test, ExecuteStateMsg_FAILED) +HWTEST_F(ApRootState_test, ExecuteStateMsg_FAILED, TestSize.Level1) { - InternalMessage *msg = nullptr; - EXPECT_FALSE(pApRootState->ExecuteStateMsg(msg)); + EXPECT_FALSE(pApRootState->ExecuteStateMsg(nullptr)); } -TEST_F(ApRootState_test, GoInState) +HWTEST_F(ApRootState_test, GoInState, TestSize.Level1) { pApRootState->GoInState(); } -TEST_F(ApRootState_test, GoOutState) +HWTEST_F(ApRootState_test, GoOutState, TestSize.Level1) { pApRootState->GoOutState(); } diff --git a/tests/wifi_standard/wifi_framework/wifi_manage/wifi_ap/wifi_hotspot_test/ap_service_test.cpp b/wifi/test/wifi_standard/wifi_framework/wifi_manage/wifi_ap/ap_service_test.cpp similarity index 62% rename from tests/wifi_standard/wifi_framework/wifi_manage/wifi_ap/wifi_hotspot_test/ap_service_test.cpp rename to wifi/test/wifi_standard/wifi_framework/wifi_manage/wifi_ap/ap_service_test.cpp index 745f1eab2327e6226eddf267a11633184b809f5f..d30c4c5eb167427b9fb056f39404006c674a47d0 100644 --- a/tests/wifi_standard/wifi_framework/wifi_manage/wifi_ap/wifi_hotspot_test/ap_service_test.cpp +++ b/wifi/test/wifi_standard/wifi_framework/wifi_manage/wifi_ap/ap_service_test.cpp @@ -29,6 +29,7 @@ using ::testing::Return; using ::testing::SetArgReferee; using ::testing::StrEq; using ::testing::TypedEq; +using ::testing::ext::TestSize; namespace OHOS { namespace Wifi { @@ -39,30 +40,26 @@ const StationInfo staInfo = { }; class ApService_test : public testing::Test { public: - static void SetUpTestCase() - {} - static void TearDownTestCase() - {} + static void SetUpTestCase() {} + static void TearDownTestCase() {} virtual void SetUp() { + const int SLEEP_TIME = 20; pMockPendant = new MockPendant(); - pApStateMachine = &(pMockPendant->GetMockApStateMachine()); - pApStateMachine->InitialStateMachine(); - pApService = new ApService(*pApStateMachine); - - const int testMaxConn = 10; - const int channel = 6; + pMockPendant->GetMockApStateMachine().InitialStateMachine(); + pApService = new ApService(pMockPendant->GetMockApStateMachine()); + int testMaxConn = 10; + int channel = 6; apInfo.SetSsid(std::string("TEST")); apInfo.SetPreSharedKey(std::string("123456789")); apInfo.SetSecurityType(KeyMgmt::WPA2_PSK); apInfo.SetBand(BandType::BAND_2GHZ); apInfo.SetChannel(channel); apInfo.SetMaxConn(testMaxConn); + usleep(SLEEP_TIME); } virtual void TearDown() { - EXPECT_CALL(WifiApHalInterface::GetInstance(), RegisterApEvent(_)) - .WillOnce(Return(WifiErrorNo::WIFI_IDL_OPT_OK)); delete pApService; pApService = nullptr; delete pMockPendant; @@ -77,43 +74,54 @@ public: public: MockPendant *pMockPendant; - MockApStateMachine *pApStateMachine; ApService *pApService; HotspotConfig apInfo; }; /* EnableHotspot */ -TEST_F(ApService_test, EnableHotspot_SUCCESS) +HWTEST_F(ApService_test, EnableHotspot_SUCCESS, TestSize.Level1) { + EXPECT_CALL(WifiApHalInterface::GetInstance(), RegisterApEvent(_, 0)) + .WillRepeatedly(Return(WifiErrorNo::WIFI_IDL_OPT_OK)); EXPECT_EQ(ErrCode::WIFI_OPT_SUCCESS, pApService->EnableHotspot()); } /* DisableHotspot */ -TEST_F(ApService_test, DisableHotspotSUCCESS) +HWTEST_F(ApService_test, DisableHotspotSUCCESS, TestSize.Level1) { + EXPECT_CALL(WifiApHalInterface::GetInstance(), RegisterApEvent(_, 0)) + .WillRepeatedly(Return(WifiErrorNo::WIFI_IDL_OPT_OK)); EXPECT_EQ(ErrCode::WIFI_OPT_SUCCESS, pApService->DisableHotspot()); } /* SetHotspotConfig */ -TEST_F(ApService_test, SetHotspotConfig_SUCCESS) +HWTEST_F(ApService_test, SetHotspotConfig_SUCCESS, TestSize.Level1) { + EXPECT_CALL(WifiApHalInterface::GetInstance(), RegisterApEvent(_, 0)) + .WillRepeatedly(Return(WifiErrorNo::WIFI_IDL_OPT_OK)); EXPECT_EQ(ErrCode::WIFI_OPT_SUCCESS, pApService->SetHotspotConfig(apInfo)); } /* AddBlockList */ -TEST_F(ApService_test, AddBlockList_SUCCESS) +HWTEST_F(ApService_test, AddBlockList_SUCCESS, TestSize.Level1) { + EXPECT_CALL(WifiApHalInterface::GetInstance(), RegisterApEvent(_, 0)) + .WillRepeatedly(Return(WifiErrorNo::WIFI_IDL_OPT_OK)); EXPECT_EQ(ErrCode::WIFI_OPT_SUCCESS, pApService->AddBlockList(staInfo)); } /* DelBlockList */ -TEST_F(ApService_test, DelBlockList_SUCCESS) +HWTEST_F(ApService_test, DelBlockList_SUCCESS, TestSize.Level1) { + EXPECT_CALL(WifiApHalInterface::GetInstance(), RegisterApEvent(_, 0)) + .WillRepeatedly(Return(WifiErrorNo::WIFI_IDL_OPT_OK)); EXPECT_EQ(ErrCode::WIFI_OPT_SUCCESS, pApService->DelBlockList(staInfo)); } /* DisconnetStation */ -TEST_F(ApService_test, DisconnetStation_SUCCESS) +HWTEST_F(ApService_test, DisconnetStation_SUCCESS, TestSize.Level1) { + EXPECT_CALL(WifiApHalInterface::GetInstance(), RegisterApEvent(_, 0)) + .WillRepeatedly(Return(WifiErrorNo::WIFI_IDL_OPT_OK)); EXPECT_EQ(ErrCode::WIFI_OPT_SUCCESS, pApService->DisconnetStation(staInfo)); } /* GetValidBands */ -TEST_F(ApService_test, GetValidBands_SUCCESS) +HWTEST_F(ApService_test, GetValidBands_SUCCESS, TestSize.Level1) { std::vector vecSta; std::vector temp = { @@ -123,10 +131,12 @@ TEST_F(ApService_test, GetValidBands_SUCCESS) EXPECT_CALL(WifiSettings::GetInstance(), GetValidBands(Eq(vecSta))) .WillOnce(DoAll(SetArgReferee<0>(temp), Return(0))); + EXPECT_CALL(WifiApHalInterface::GetInstance(), RegisterApEvent(_, 0)) + .WillRepeatedly(Return(WifiErrorNo::WIFI_IDL_OPT_OK)); EXPECT_EQ(ErrCode::WIFI_OPT_SUCCESS, pApService->GetValidBands(vecSta)); EXPECT_EQ(temp, vecSta); } -TEST_F(ApService_test, GetValidBands_FAILED) +HWTEST_F(ApService_test, GetValidBands_FAILED, TestSize.Level1) { std::vector vecSta; std::vector temp = { @@ -136,17 +146,20 @@ TEST_F(ApService_test, GetValidBands_FAILED) EXPECT_CALL(WifiSettings::GetInstance(), GetValidBands(Eq(vecSta))) .WillOnce(DoAll(SetArgReferee<0>(temp), Return(-1))); + EXPECT_CALL(WifiApHalInterface::GetInstance(), RegisterApEvent(_, 0)) + .WillRepeatedly(Return(WifiErrorNo::WIFI_IDL_OPT_OK)); EXPECT_EQ(ErrCode::WIFI_OPT_FAILED, pApService->GetValidBands(vecSta)); } /* GetValidChannels */ -TEST_F(ApService_test, GetValidChannels_SUCCESS) +HWTEST_F(ApService_test, GetValidChannels_SUCCESS, TestSize.Level1) { std::vector vecChannels; - std::vector band_2G_channel = {1, 2, 3, 4, 5, 6, 7}; - std::vector band_5G_channel = {149, 168, 169}; - ChannelsTable temp = {{BandType::BAND_2GHZ, band_2G_channel}, {BandType::BAND_5GHZ, band_5G_channel}}; - + std::vector band_2G_channel = { 1, 2, 3, 4, 5, 6, 7 }; + std::vector band_5G_channel = { 149, 168, 169 }; + ChannelsTable temp = { { BandType::BAND_2GHZ, band_2G_channel }, { BandType::BAND_5GHZ, band_5G_channel } }; + EXPECT_CALL(WifiApHalInterface::GetInstance(), RegisterApEvent(_, 0)) + .WillRepeatedly(Return(WifiErrorNo::WIFI_IDL_OPT_OK)); EXPECT_CALL(WifiSettings::GetInstance(), GetValidChannels(_)).WillOnce(DoAll(SetArgReferee<0>(temp), Return(0))); EXPECT_EQ(ErrCode::WIFI_OPT_SUCCESS, pApService->GetValidChannels(BandType::BAND_2GHZ, vecChannels)); EXPECT_EQ(vecChannels, band_2G_channel); @@ -162,8 +175,10 @@ TEST_F(ApService_test, GetValidChannels_SUCCESS) } /* RegisterApServiceCallbacks */ -TEST_F(ApService_test, RegisterApServiceCallbacks_SUCCESS) +HWTEST_F(ApService_test, RegisterApServiceCallbacks_SUCCESS, TestSize.Level1) { + EXPECT_CALL(WifiApHalInterface::GetInstance(), RegisterApEvent(_, 0)) + .WillRepeatedly(Return(WifiErrorNo::WIFI_IDL_OPT_OK)); IApServiceCallbacks callbacks; EXPECT_EQ(ErrCode::WIFI_OPT_SUCCESS, WarpRegisterApServiceCallbacks(callbacks)); } diff --git a/tests/wifi_standard/wifi_framework/wifi_manage/wifi_ap/wifi_hotspot_test/ap_started_state_test.cpp b/wifi/test/wifi_standard/wifi_framework/wifi_manage/wifi_ap/ap_started_state_test.cpp similarity index 84% rename from tests/wifi_standard/wifi_framework/wifi_manage/wifi_ap/wifi_hotspot_test/ap_started_state_test.cpp rename to wifi/test/wifi_standard/wifi_framework/wifi_manage/wifi_ap/ap_started_state_test.cpp index 8412fe097600df29843fbe8c74393b9d32a856ab..77b67eb9cc01604dcd9c96d3fe44dbd0917cfd89 100644 --- a/tests/wifi_standard/wifi_framework/wifi_manage/wifi_ap/wifi_hotspot_test/ap_started_state_test.cpp +++ b/wifi/test/wifi_standard/wifi_framework/wifi_manage/wifi_ap/ap_started_state_test.cpp @@ -37,88 +37,107 @@ using ::testing::Eq; using ::testing::Return; using ::testing::SetArgReferee; using ::testing::StrEq; +using ::testing::ext::TestSize; namespace OHOS { namespace Wifi { -const std::string mac = "AA:BB:CC:DD:EE:FF"; -static StationInfo staInfo = { - "test_deviceName", - mac.c_str(), - "127.0.0.1", -}; - -HotspotConfig apcfg; -ChannelsTable channelTbs; -const int TEST_AP_CHANNEL = 6; -const int TEST_MAX_CONN = 10; - -std::vector valueList = { - { - "test_deviceName", - "DA:BB:CC:DD:EE:FF", - "127.0.0.3", - }, - { - "test_deviceName", - "DA:BB:CC:DD:EE:FF", - "127.0.0.3", - }, -}; - class ApStartedState_test : public testing::Test { public: - static void SetUpTestCase() - {} - static void TearDownTestCase() - {} + static void SetUpTestCase() {} + static void TearDownTestCase() {} virtual void SetUp() { - WifiSettings::GetInstance(); - WifiApHalInterface::GetInstance(); - + const int SLEEP_TIME = 20; pMockPendant = new MockPendant(); + + pMockApStateMachine = &(pMockPendant->GetMockApStateMachine()); + + pMockApStateMachine->InitialStateMachine(); + pMockApMonitor = &(pMockPendant->GetMockApMonitor()); + pMockApStationsManager = &(pMockPendant->GetMockApStationsManager()); - pMockApStateMachine = &(pMockPendant->GetMockApStateMachine()); + pMockApConfigUse = &(pMockPendant->GetMockApConfigUse()); - pMockApStateMachine->InitialStateMachine(); + pMockApNatManager = new MockWifiApNatManager(); pApStartedState = new ApStartedState(*pMockApStateMachine, *pMockApConfigUse, *pMockApMonitor); msg = new InternalMessage(); + apcfg.SetSsid(std::string("UnitTestAp")); + apcfg.SetPreSharedKey(std::string("123456789")); + apcfg.SetSecurityType(KeyMgmt::WPA2_PSK); + apcfg.SetBand(BandType::BAND_2GHZ); + apcfg.SetChannel(TEST_AP_CHANNEL); + apcfg.SetMaxConn(TEST_MAX_CONN); - WrapHotspotConfig() = apcfg; - std::vector band_2G_channel = {1, 2, 3, 4, 5, 6, 7}; - std::vector band_5G_channel = {149, 168, 169}; - channelTbs = {{BandType::BAND_2GHZ, band_2G_channel}, {BandType::BAND_5GHZ, band_5G_channel}}; + mac = "AA:BB:CC:DD:EE:FF"; + + staInfo = { + "test_deviceName", + mac.c_str(), + "127.0.0.1", + }; + + TEST_AP_CHANNEL = 6; + + TEST_MAX_CONN = 10; + + valueList = { + { + "test_deviceName", + "DA:BB:CC:DD:EE:FF", + "127.0.0.3", + }, + { + "test_deviceName", + "DA:BB:CC:DD:EE:FF", + "127.0.0.3", + }, + }; + + std::vector band_2G_channel = { 1, 2, 3, 4, 5, 6, 7 }; + + std::vector band_5G_channel = { 149, 168, 169 }; + + channelTbs = { { BandType::BAND_2GHZ, band_2G_channel }, { BandType::BAND_5GHZ, band_5G_channel } }; + + EXPECT_CALL(WifiApHalInterface::GetInstance(), RegisterApEvent(_, 0)) + .WillOnce(Return(WifiErrorNo::WIFI_IDL_OPT_OK)); + usleep(SLEEP_TIME); } virtual void TearDown() { - EXPECT_CALL(WifiApHalInterface::GetInstance(), RegisterApEvent(_)) - .WillOnce(Return(WifiErrorNo::WIFI_IDL_OPT_OK)); delete pApStartedState; - delete pMockPendant; - pApStartedState = nullptr; + delete pMockPendant; + pMockPendant = nullptr; + pMockApStateMachine = nullptr; + pMockApConfigUse = nullptr; + pMockApMonitor = nullptr; + pMockApStationsManager = nullptr; delete pMockApNatManager; + pMockApNatManager = nullptr; delete msg; + + msg = nullptr; } public: @@ -219,29 +238,48 @@ public: MockPendant *pMockPendant; MockApStationsManager *pMockApStationsManager; + MockApStateMachine *pMockApStateMachine; + MockApMonitor *pMockApMonitor; + MockApConfigUse *pMockApConfigUse; + MockWifiApNatManager *pMockApNatManager; + + std::string mac; + + StationInfo staInfo; + + ChannelsTable channelTbs; + + int TEST_AP_CHANNEL; + + int TEST_MAX_CONN; + + std::vector valueList; + + HotspotConfig apcfg; }; -TEST_F(ApStartedState_test, GoInState_SUCCESS) + +HWTEST_F(ApStartedState_test, GoInState_SUCCESS,TestSize.Level1) { std::vector results; EXPECT_CALL(MockNetworkInterface::GetInstance(), FetchIpAddress(_, _, _)).WillRepeatedly(Return(true)); EXPECT_CALL(MockNetworkInterface::GetInstance(), AddIpAddress(_, _)).WillRepeatedly(Return(true)); - EXPECT_CALL(WifiSettings::GetInstance(), SetHotspotState(A())).WillRepeatedly(Return(0)); - EXPECT_CALL(WifiApHalInterface::GetInstance(), StartAp()).WillRepeatedly(Return(WifiErrorNo::WIFI_IDL_OPT_OK)); + EXPECT_CALL(WifiSettings::GetInstance(), SetHotspotState(A(), 0)).WillRepeatedly(Return(0)); + EXPECT_CALL(WifiApHalInterface::GetInstance(), StartAp(0)).WillRepeatedly(Return(WifiErrorNo::WIFI_IDL_OPT_OK)); std::string countryCode = "CN"; EXPECT_CALL(WifiSettings::GetInstance(), GetCountryCode(Eq(""))) .WillRepeatedly(DoAll(testing::SetArgReferee<0>(countryCode), Return(0))); - EXPECT_CALL(WifiApHalInterface::GetInstance(), SetWifiCountryCode(Eq(countryCode))) + EXPECT_CALL(WifiApHalInterface::GetInstance(), SetWifiCountryCode(Eq(countryCode), 0)) .WillRepeatedly(Return(WifiErrorNo::WIFI_IDL_OPT_OK)); - EXPECT_CALL(WifiSettings::GetInstance(), GetHotspotConfig(A())) + EXPECT_CALL(WifiSettings::GetInstance(), GetHotspotConfig(A(), 0)) .WillRepeatedly(DoAll(SetArgReferee<0>(apcfg), Return(0))); - EXPECT_CALL(WifiApHalInterface::GetInstance(), GetFrequenciesByBand(_, _)) + EXPECT_CALL(WifiApHalInterface::GetInstance(), GetFrequenciesByBand(_, _, _)) .WillRepeatedly(Return(WifiErrorNo::WIFI_IDL_OPT_OK)); EXPECT_CALL(WifiSettings::GetInstance(), SetValidChannels(_)).WillRepeatedly(Return(0)); - EXPECT_CALL(WifiApHalInterface::GetInstance(), SetSoftApConfig(Eq(apcfg))) + EXPECT_CALL(WifiApHalInterface::GetInstance(), SetSoftApConfig(Eq(apcfg), 0)) .WillRepeatedly(Return(WifiErrorNo::WIFI_IDL_OPT_OK)); EXPECT_CALL(*pMockApStateMachine, StartDhcpServer()).WillRepeatedly(Return(true)); EXPECT_CALL(*pMockApNatManager, EnableInterfaceNat(Eq(true), StrEq(IN_INTERFACE), StrEq(OUT_INTERFACE))) @@ -250,38 +288,38 @@ TEST_F(ApStartedState_test, GoInState_SUCCESS) EXPECT_CALL(*pMockApMonitor, StartMonitor()).WillRepeatedly(Return()); EXPECT_CALL(*pMockApConfigUse, CheckBandChannel(Eq(apcfg), _)).WillRepeatedly(Return()); EXPECT_CALL(*pMockApConfigUse, LogConfig(Eq(apcfg))).WillRepeatedly(Return()); - EXPECT_CALL(WifiSettings::GetInstance(), GetBlockList(Eq(results))) + EXPECT_CALL(WifiSettings::GetInstance(), GetBlockList(Eq(results), 0)) .WillRepeatedly(DoAll(SetArgReferee<0>(valueList), Return(ErrCode::WIFI_OPT_SUCCESS))); - EXPECT_CALL(WifiApHalInterface::GetInstance(), AddBlockByMac(StrEq("DA:BB:CC:DD:EE:FF"))) + EXPECT_CALL(WifiApHalInterface::GetInstance(), AddBlockByMac(StrEq("DA:BB:CC:DD:EE:FF"), 0)) .WillRepeatedly(Return(WifiErrorNo::WIFI_IDL_OPT_OK)); pApStartedState->GoInState(); } -TEST_F(ApStartedState_test, GoInState_FAILED1) +HWTEST_F(ApStartedState_test, GoInState_FAILED1,TestSize.Level1) { std::vector results; - EXPECT_CALL(WifiSettings::GetInstance(), SetHotspotState(A())).WillRepeatedly(Return(0)); + EXPECT_CALL(WifiSettings::GetInstance(), SetHotspotState(A(), 0)).WillRepeatedly(Return(0)); EXPECT_CALL(*pMockApMonitor, StartMonitor()).WillRepeatedly(Return()); - EXPECT_CALL(WifiApHalInterface::GetInstance(), StartAp()).WillRepeatedly(Return(WifiErrorNo::WIFI_IDL_OPT_FAILED)); + EXPECT_CALL(WifiApHalInterface::GetInstance(), StartAp(0)).WillRepeatedly(Return(WifiErrorNo::WIFI_IDL_OPT_FAILED)); pApStartedState->GoInState(); - EXPECT_CALL(WifiApHalInterface::GetInstance(), StartAp()).WillRepeatedly(Return(WifiErrorNo::WIFI_IDL_OPT_OK)); + EXPECT_CALL(WifiApHalInterface::GetInstance(), StartAp(0)).WillRepeatedly(Return(WifiErrorNo::WIFI_IDL_OPT_OK)); EXPECT_CALL(WifiSettings::GetInstance(), GetCountryCode(StrEq(""))).WillRepeatedly(Return(1)); pApStartedState->GoInState(); EXPECT_CALL(WifiSettings::GetInstance(), GetCountryCode(StrEq(""))) .WillRepeatedly(DoAll(SetArgReferee<0>("CN"), Return(0))); - EXPECT_CALL(WifiApHalInterface::GetInstance(), SetWifiCountryCode(StrEq("CN"))) + EXPECT_CALL(WifiApHalInterface::GetInstance(), SetWifiCountryCode(StrEq("CN"), 0)) .WillRepeatedly(Return(WifiErrorNo::WIFI_IDL_OPT_FAILED)); pApStartedState->GoInState(); - EXPECT_CALL(WifiApHalInterface::GetInstance(), SetWifiCountryCode(StrEq("CN"))) + EXPECT_CALL(WifiApHalInterface::GetInstance(), SetWifiCountryCode(StrEq("CN"), 0)) .WillRepeatedly(Return(WifiErrorNo::WIFI_IDL_OPT_OK)); - EXPECT_CALL(WifiSettings::GetInstance(), GetHotspotConfig(A())).WillRepeatedly(Return(1)); + EXPECT_CALL(WifiSettings::GetInstance(), GetHotspotConfig(A(), 0)).WillRepeatedly(Return(1)); pApStartedState->GoInState(); - EXPECT_CALL(WifiSettings::GetInstance(), GetHotspotConfig(A())) + EXPECT_CALL(WifiSettings::GetInstance(), GetHotspotConfig(A(), 0)) .WillRepeatedly(DoAll(SetArgReferee<0>(apcfg), Return(0))); - EXPECT_CALL(WifiApHalInterface::GetInstance(), GetFrequenciesByBand(_, _)) + EXPECT_CALL(WifiApHalInterface::GetInstance(), GetFrequenciesByBand(_, _, _)) .WillRepeatedly(Return(WifiErrorNo::WIFI_IDL_OPT_FAILED)); EXPECT_CALL(*pMockApConfigUse, TransformFrequencyIntoChannel(_, _)).WillRepeatedly(Return()); EXPECT_CALL(WifiSettings::GetInstance(), SetValidChannels(_)).WillRepeatedly(Return(1)); @@ -289,64 +327,64 @@ TEST_F(ApStartedState_test, GoInState_FAILED1) EXPECT_CALL(WifiSettings::GetInstance(), SetValidChannels(_)).WillRepeatedly(Return(0)); EXPECT_CALL(*pMockApConfigUse, CheckBandChannel(_, _)).WillRepeatedly(Return()); - EXPECT_CALL(WifiApHalInterface::GetInstance(), SetSoftApConfig(Eq(apcfg))) + EXPECT_CALL(WifiApHalInterface::GetInstance(), SetSoftApConfig(Eq(apcfg), 0)) .WillRepeatedly(Return(WifiErrorNo::WIFI_IDL_OPT_FAILED)); pApStartedState->GoInState(); - EXPECT_CALL(WifiApHalInterface::GetInstance(), SetSoftApConfig(Eq(apcfg))) + EXPECT_CALL(WifiApHalInterface::GetInstance(), SetSoftApConfig(Eq(apcfg), 0)) .WillRepeatedly(Return(WifiErrorNo::WIFI_IDL_OPT_OK)); EXPECT_CALL(*pMockApConfigUse, LogConfig(Eq(apcfg))).WillRepeatedly(Return()); EXPECT_CALL(*pMockApStateMachine, StartDhcpServer()).WillRepeatedly(Return(false)); pApStartedState->GoInState(); - EXPECT_CALL(WifiSettings::GetInstance(), GetBlockList(Eq(results))) + EXPECT_CALL(WifiSettings::GetInstance(), GetBlockList(Eq(results), 0)) .WillRepeatedly(DoAll(SetArgReferee<0>(valueList), Return(ErrCode::WIFI_OPT_FAILED))); pApStartedState->GoInState(); - EXPECT_CALL(WifiSettings::GetInstance(), GetBlockList(Eq(results))) + EXPECT_CALL(WifiSettings::GetInstance(), GetBlockList(Eq(results), 0)) .WillRepeatedly(DoAll(SetArgReferee<0>(valueList), Return(ErrCode::WIFI_OPT_SUCCESS))); - EXPECT_CALL(WifiApHalInterface::GetInstance(), AddBlockByMac(StrEq("DA:BB:CC:DD:EE:FF"))) + EXPECT_CALL(WifiApHalInterface::GetInstance(), AddBlockByMac(StrEq("DA:BB:CC:DD:EE:FF"), 0)) .WillRepeatedly(Return(WifiErrorNo::WIFI_IDL_OPT_OK)); pApStartedState->GoInState(); - EXPECT_CALL(WifiSettings::GetInstance(), GetHotspotConfig(A())).WillRepeatedly(Return(1)); + EXPECT_CALL(WifiSettings::GetInstance(), GetHotspotConfig(A(), 0)).WillRepeatedly(Return(1)); EXPECT_CALL(*pMockApStateMachine, StartDhcpServer()).WillRepeatedly(Return(true)); EXPECT_CALL(*pMockApNatManager, EnableInterfaceNat(_, _, _)).WillRepeatedly(Return(false)); pApStartedState->GoInState(); } -TEST_F(ApStartedState_test, GoOutState_SUCCESS) +HWTEST_F(ApStartedState_test, GoOutState_SUCCESS, TestSize.Level1) { + pApStartedState->GoOutState(); EXPECT_CALL(MockSystemInterface::GetInstance(), system(_)).WillRepeatedly(Return(true)); EXPECT_CALL(MockNetworkInterface::GetInstance(), IsValidInterfaceName(_)).WillRepeatedly(Return(true)); EXPECT_CALL(MockNetworkInterface::GetInstance(), ClearAllIpAddress(_)).WillRepeatedly(Return(true)); - EXPECT_CALL(WifiSettings::GetInstance(), SetHotspotState(A())).WillRepeatedly(Return(0)); + EXPECT_CALL(WifiSettings::GetInstance(), SetHotspotState(A(), 0)).WillRepeatedly(Return(0)); EXPECT_CALL(*pMockApNatManager, EnableInterfaceNat(Eq(false), _, _)).WillRepeatedly(Return(true)); EXPECT_CALL(*pMockApStateMachine, StopDhcpServer()).WillRepeatedly(Return(true)); - EXPECT_CALL(WifiApHalInterface::GetInstance(), StopAp()).WillRepeatedly(Return(WifiErrorNo::WIFI_IDL_OPT_OK)); - EXPECT_CALL(WifiSettings::GetInstance(), ClearStationList()).WillRepeatedly(Return(0)); + EXPECT_CALL(WifiApHalInterface::GetInstance(), StopAp(0)).WillRepeatedly(Return(WifiErrorNo::WIFI_IDL_OPT_OK)); + EXPECT_CALL(WifiSettings::GetInstance(), ClearStationList(0)).WillRepeatedly(Return(0)); EXPECT_CALL(WifiSettings::GetInstance(), ClearValidChannels()).WillRepeatedly(Return(0)); EXPECT_CALL(*pMockApMonitor, StopMonitor()).WillRepeatedly(Return()); - pApStartedState->GoOutState(); } -TEST_F(ApStartedState_test, GoOutState_FAILED) +HWTEST_F(ApStartedState_test, GoOutState_FAILED, TestSize.Level1) { + pApStartedState->GoOutState(); EXPECT_CALL(MockSystemInterface::GetInstance(), system(_)).WillRepeatedly(Return(true)); - EXPECT_CALL(WifiSettings::GetInstance(), SetHotspotState(A())).WillRepeatedly(Return(0)); + EXPECT_CALL(WifiSettings::GetInstance(), SetHotspotState(A(), 0)).WillRepeatedly(Return(0)); EXPECT_CALL(*pMockApNatManager, EnableInterfaceNat(Eq(false), _, _)).WillRepeatedly(Return(false)); EXPECT_CALL(*pMockApStateMachine, StopDhcpServer()).WillRepeatedly(Return(false)); - EXPECT_CALL(WifiApHalInterface::GetInstance(), StopAp()).WillRepeatedly(Return(WifiErrorNo::WIFI_IDL_OPT_FAILED)); - EXPECT_CALL(WifiSettings::GetInstance(), ClearStationList()).WillRepeatedly(Return(0)); + EXPECT_CALL(WifiApHalInterface::GetInstance(), StopAp(0)).WillRepeatedly(Return(WifiErrorNo::WIFI_IDL_OPT_FAILED)); + EXPECT_CALL(WifiSettings::GetInstance(), ClearStationList(0)).WillRepeatedly(Return(0)); EXPECT_CALL(WifiSettings::GetInstance(), ClearValidChannels()).WillRepeatedly(Return(0)); EXPECT_CALL(*pMockApMonitor, StopMonitor()).WillRepeatedly(Return()); - pApStartedState->GoOutState(); } -TEST_F(ApStartedState_test, ExecuteStateMsg_SUCCESS) +HWTEST_F(ApStartedState_test, ExecuteStateMsg_SUCCESS, TestSize.Level1) { msg->SetMessageName(static_cast(ApStatemachineEvent::CMD_FAIL)); EXPECT_TRUE(pApStartedState->ExecuteStateMsg(msg)); - EXPECT_CALL(WifiSettings::GetInstance(), GetStationList(_)).WillRepeatedly(Return(ErrCode::WIFI_OPT_FAILED)); + EXPECT_CALL(WifiSettings::GetInstance(), GetStationList(_, 0)).WillRepeatedly(Return(ErrCode::WIFI_OPT_FAILED)); msg->ClearMessageBody(); StationInfo staInfo; msg->SetMessageObj(staInfo); @@ -373,11 +411,11 @@ TEST_F(ApStartedState_test, ExecuteStateMsg_SUCCESS) msg->AddIntMessageBody(apcfg.GetMaxConn()); EXPECT_CALL(*pMockApConfigUse, LogConfig(Eq(apcfg))).WillRepeatedly(Return()); - EXPECT_CALL(WifiApHalInterface::GetInstance(), GetFrequenciesByBand(_, _)) + EXPECT_CALL(WifiApHalInterface::GetInstance(), GetFrequenciesByBand(_, _, _)) .WillRepeatedly(Return(WifiErrorNo::WIFI_IDL_OPT_OK)); EXPECT_CALL(*pMockApConfigUse, TransformFrequencyIntoChannel(_, _)).WillRepeatedly(Return()); EXPECT_CALL(WifiSettings::GetInstance(), SetValidChannels(_)).WillRepeatedly(Return(0)); - EXPECT_CALL(WifiApHalInterface::GetInstance(), SetSoftApConfig(Eq(apcfg))) + EXPECT_CALL(WifiApHalInterface::GetInstance(), SetSoftApConfig(Eq(apcfg), 0)) .WillRepeatedly(Return(WifiErrorNo::WIFI_IDL_OPT_OK)); EXPECT_CALL(*pMockApConfigUse, CheckBandChannel(Eq(apcfg), _)).WillRepeatedly(Return()); EXPECT_TRUE(pApStartedState->ExecuteStateMsg(msg)); @@ -390,12 +428,12 @@ TEST_F(ApStartedState_test, ExecuteStateMsg_SUCCESS) msg->AddIntMessageBody(static_cast(apcfg.GetBand())); msg->AddIntMessageBody(apcfg.GetChannel()); msg->AddIntMessageBody(apcfg.GetMaxConn()); - EXPECT_CALL(WifiApHalInterface::GetInstance(), SetSoftApConfig(Eq(apcfg))) + EXPECT_CALL(WifiApHalInterface::GetInstance(), SetSoftApConfig(Eq(apcfg), 0)) .WillRepeatedly(Return(WifiErrorNo::WIFI_IDL_OPT_FAILED)); EXPECT_TRUE(pApStartedState->ExecuteStateMsg(msg)); } -TEST_F(ApStartedState_test, ExecuteStateMsg_SUCCESS2) +HWTEST_F(ApStartedState_test, ExecuteStateMsg_SUCCESS2, TestSize.Level1) { msg->ClearMessageBody(); msg->SetMessageName(static_cast(ApStatemachineEvent::CMD_UPDATE_HOTSPOTCONFIG_RESULT)); @@ -406,9 +444,7 @@ TEST_F(ApStartedState_test, ExecuteStateMsg_SUCCESS2) msg->AddIntMessageBody(apcfg.GetChannel()); msg->AddIntMessageBody(apcfg.GetMaxConn()); msg->SetParam1(1); - EXPECT_CALL(WifiSettings::GetInstance(), SetHotspotConfig(Eq(apcfg))).WillRepeatedly(Return(1)); msg->SetMessageName(static_cast(ApStatemachineEvent::CMD_UPDATE_HOTSPOTCONFIG_RESULT)); - EXPECT_TRUE(pApStartedState->ExecuteStateMsg(msg)); msg->SetParam1(0); msg->SetMessageName(static_cast(ApStatemachineEvent::CMD_UPDATE_HOTSPOTCONFIG_RESULT)); @@ -422,7 +458,7 @@ TEST_F(ApStartedState_test, ExecuteStateMsg_SUCCESS2) msg->AddIntMessageBody(static_cast(apcfg.GetBand())); msg->AddIntMessageBody(apcfg.GetChannel()); msg->AddIntMessageBody(apcfg.GetMaxConn()); - EXPECT_CALL(WifiApHalInterface::GetInstance(), AddBlockByMac(Eq(staInfo.bssid))) + EXPECT_CALL(WifiApHalInterface::GetInstance(), AddBlockByMac(Eq(staInfo.bssid), 0)) .WillRepeatedly(Return(WifiErrorNo::WIFI_IDL_OPT_OK)); msg->ClearMessageBody(); msg->SetMessageName(static_cast(ApStatemachineEvent::CMD_ADD_BLOCK_LIST)); @@ -435,7 +471,7 @@ TEST_F(ApStartedState_test, ExecuteStateMsg_SUCCESS2) msg->AddStringMessageBody(staInfo.deviceName); msg->AddStringMessageBody(staInfo.bssid); msg->AddStringMessageBody(staInfo.ipAddr); - EXPECT_CALL(WifiApHalInterface::GetInstance(), DelBlockByMac(Eq(staInfo.bssid))) + EXPECT_CALL(WifiApHalInterface::GetInstance(), DelBlockByMac(Eq(staInfo.bssid), 0)) .WillRepeatedly(Return(WifiErrorNo::WIFI_IDL_OPT_OK)); EXPECT_TRUE(pApStartedState->ExecuteStateMsg(msg)); msg->SetMessageName(static_cast(ApStatemachineEvent::CMD_STOP_HOTSPOT)); @@ -446,17 +482,15 @@ TEST_F(ApStartedState_test, ExecuteStateMsg_SUCCESS2) msg->AddStringMessageBody(staInfo.deviceName); msg->AddStringMessageBody(staInfo.bssid); msg->AddStringMessageBody(staInfo.ipAddr); - EXPECT_CALL(WifiApHalInterface::GetInstance(), DisconnectStaByMac(Eq(staInfo.bssid))) + EXPECT_CALL(WifiApHalInterface::GetInstance(), DisconnectStaByMac(Eq(staInfo.bssid), 0)) .WillRepeatedly(Return(WifiErrorNo::WIFI_IDL_OPT_OK)); EXPECT_TRUE(pApStartedState->ExecuteStateMsg(msg)); } -TEST_F(ApStartedState_test, ExecuteStateMsg_FAILED) +HWTEST_F(ApStartedState_test, ExecuteStateMsg_FAILED, TestSize.Level1) { msg->SetMessageName(static_cast(ApStatemachineEvent::CMD_START_HOTSPOT)); EXPECT_FALSE(pApStartedState->ExecuteStateMsg(msg)); - - msg = nullptr; - EXPECT_FALSE(pApStartedState->ExecuteStateMsg(msg)); + EXPECT_FALSE(pApStartedState->ExecuteStateMsg(nullptr)); } } // namespace Wifi -} // namespace OHOS \ No newline at end of file +} // namespace OHOS diff --git a/tests/wifi_standard/wifi_framework/wifi_manage/wifi_ap/wifi_hotspot_test/ap_state_machine_test.cpp b/wifi/test/wifi_standard/wifi_framework/wifi_manage/wifi_ap/ap_state_machine_test.cpp similarity index 87% rename from tests/wifi_standard/wifi_framework/wifi_manage/wifi_ap/wifi_hotspot_test/ap_state_machine_test.cpp rename to wifi/test/wifi_standard/wifi_framework/wifi_manage/wifi_ap/ap_state_machine_test.cpp index da1621e7c7ac40b8f91eb8f320905c063536d61d..546015fa0f4524e53ea6511115f27b2f3a3bc7eb 100644 --- a/tests/wifi_standard/wifi_framework/wifi_manage/wifi_ap/wifi_hotspot_test/ap_state_machine_test.cpp +++ b/wifi/test/wifi_standard/wifi_framework/wifi_manage/wifi_ap/ap_state_machine_test.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021 Huawei Device Co., Ltd. + * Copyright (c) 2021-2022 Huawei Device Co., Ltd. * 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 @@ -30,12 +30,11 @@ namespace OHOS { namespace Wifi { class ApStateMachine_test : public testing::Test { public: - static void SetUpTestCase() - {} - static void TearDownTestCase() - {} + static void SetUpTestCase() {} + static void TearDownTestCase() {} virtual void SetUp() { + const int SLEEP_TIME = 20; pMockPendant = new MockPendant(); pMockApStationsManager = &(pMockPendant->GetMockApStationsManager()); pMockApRootState = &(pMockPendant->GetMockApRootState()); @@ -45,18 +44,18 @@ public: pMockPendant->GetMockApStateMachine().InitialStateMachine(); - pApStateMachine = new ApStateMachine( - *pMockApStationsManager, *pMockApRootState, *pMockApIdleState, *pMockApStartedState, *pMockApMonitor); + pApStateMachine = new ApStateMachine(*pMockApStationsManager, *pMockApRootState, *pMockApIdleState, + *pMockApStartedState, *pMockApMonitor); pApStateMachine->InitialStateMachine(); RegisterApServiceCallbacks(); + EXPECT_CALL(WifiApHalInterface::GetInstance(), RegisterApEvent(_, 0)) + .WillOnce(Return(WifiErrorNo::WIFI_IDL_OPT_OK)); + usleep(SLEEP_TIME); } virtual void TearDown() { - EXPECT_CALL(WifiApHalInterface::GetInstance(), RegisterApEvent(_)) - .WillOnce(Return(WifiErrorNo::WIFI_IDL_OPT_OK)); delete pApStateMachine; - delete pMockPendant; pMockPendant = nullptr; pApStateMachine = nullptr; @@ -70,9 +69,11 @@ public: public: ErrCode RegisterApServiceCallbacks() { - std::function OnStationEvent = [&](const StationInfo &sta) { m_sta = sta; }; + std::function OnStationEvent = + [&](const StationInfo &sta, int id) { m_sta = sta; }; - IApServiceCallbacks callbacks = {[&](ApState state) { mBState = state; }, OnStationEvent, OnStationEvent}; + IApServiceCallbacks callbacks = {[&](ApState state, int id) { mBState = state; }, + OnStationEvent, OnStationEvent}; return pApStateMachine->RegisterApServiceCallbacks(callbacks); } ErrCode UnRegisterApServiceCallbacks() @@ -84,12 +85,12 @@ public: public: void WrapOnApStateChange(ApState state) { - EXPECT_CALL(WifiSettings::GetInstance(), SetHotspotState(Eq(static_cast(state)))).WillOnce(Return(0)); + EXPECT_CALL(WifiSettings::GetInstance(), SetHotspotState(Eq(static_cast(state)), 0)).WillOnce(Return(0)); pApStateMachine->OnApStateChange(state); } void WrapOnApStateChangeFail(ApState state) { - EXPECT_CALL(WifiSettings::GetInstance(), SetHotspotState(Eq(static_cast(state)))).WillOnce(Return(1)); + EXPECT_CALL(WifiSettings::GetInstance(), SetHotspotState(Eq(static_cast(state)), 0)).WillOnce(Return(1)); pApStateMachine->OnApStateChange(state); } diff --git a/tests/wifi_standard/wifi_framework/wifi_manage/wifi_ap/wifi_hotspot_test/ap_stations_manager_test.cpp b/wifi/test/wifi_standard/wifi_framework/wifi_manage/wifi_ap/ap_stations_manager_test.cpp similarity index 79% rename from tests/wifi_standard/wifi_framework/wifi_manage/wifi_ap/wifi_hotspot_test/ap_stations_manager_test.cpp rename to wifi/test/wifi_standard/wifi_framework/wifi_manage/wifi_ap/ap_stations_manager_test.cpp index 13e3ef82d62bd0dc0a8c4e36a31518b5d3b5d3d8..a60eed917826135679e39abf0ba55309f0d0884e 100644 --- a/tests/wifi_standard/wifi_framework/wifi_manage/wifi_ap/wifi_hotspot_test/ap_stations_manager_test.cpp +++ b/wifi/test/wifi_standard/wifi_framework/wifi_manage/wifi_ap/ap_stations_manager_test.cpp @@ -29,6 +29,7 @@ using ::testing::DoAll; using ::testing::Eq; using ::testing::Return; using ::testing::StrEq; +using ::testing::ext::TestSize; namespace OHOS { namespace Wifi { @@ -50,10 +51,8 @@ StationInfo value2 = { }; class ApStationsManager_test : public testing::Test { public: - static void SetUpTestCase() - {} - static void TearDownTestCase() - {} + static void SetUpTestCase() {} + static void TearDownTestCase() {} virtual void SetUp() { pApStaMgr = new ApStationsManager(); @@ -78,77 +77,76 @@ public: ApStationsManager *pApStaMgr; }; /* AddBlockList */ -TEST_F(ApStationsManager_test, AddBlockList_SUCCESS) +HWTEST_F(ApStationsManager_test, AddBlockList_SUCCESS, TestSize.Level1) { - EXPECT_CALL(WifiApHalInterface::GetInstance(), AddBlockByMac(StrEq(staInfo.bssid))) + EXPECT_CALL(WifiApHalInterface::GetInstance(), AddBlockByMac(StrEq(staInfo.bssid), 0)) .WillOnce(Return(WifiErrorNo::WIFI_IDL_OPT_OK)); EXPECT_TRUE(pApStaMgr->AddBlockList(staInfo)); } -TEST_F(ApStationsManager_test, AddBlockList_FAILED) +HWTEST_F(ApStationsManager_test, AddBlockList_FAILED, TestSize.Level1) { - EXPECT_CALL(WifiApHalInterface::GetInstance(), AddBlockByMac(StrEq(staInfo.bssid))) + EXPECT_CALL(WifiApHalInterface::GetInstance(), AddBlockByMac(StrEq(staInfo.bssid), 0)) .WillOnce(Return(WifiErrorNo::WIFI_IDL_OPT_FAILED)); EXPECT_FALSE(pApStaMgr->AddBlockList(staInfo)); } /* DelBlockList */ -TEST_F(ApStationsManager_test, DelBlockList_SUCCESS) +HWTEST_F(ApStationsManager_test, DelBlockList_SUCCESS, TestSize.Level1) { - EXPECT_CALL(WifiApHalInterface::GetInstance(), DelBlockByMac(StrEq(staInfo.bssid))) + EXPECT_CALL(WifiApHalInterface::GetInstance(), DelBlockByMac(StrEq(staInfo.bssid), 0)) .WillOnce(Return(WifiErrorNo::WIFI_IDL_OPT_OK)); EXPECT_TRUE(pApStaMgr->DelBlockList(staInfo)); } -TEST_F(ApStationsManager_test, DelBlockList_FAILED) +HWTEST_F(ApStationsManager_test, DelBlockList_FAILED, TestSize.Level1) { - EXPECT_CALL(WifiApHalInterface::GetInstance(), DelBlockByMac(StrEq(staInfo.bssid))) + EXPECT_CALL(WifiApHalInterface::GetInstance(), DelBlockByMac(StrEq(staInfo.bssid), 0)) .WillOnce(Return(WifiErrorNo::WIFI_IDL_OPT_FAILED)); EXPECT_FALSE(pApStaMgr->DelBlockList(staInfo)); } /* EnableAllBlockList */ -TEST_F(ApStationsManager_test, EnableAllBlockList_SUCCESS) +HWTEST_F(ApStationsManager_test, EnableAllBlockList_SUCCESS, TestSize.Level1) { std::vector value; std::vector valueCom; value.push_back(value1); value.push_back(value2); - EXPECT_CALL(WifiSettings::GetInstance(), GetBlockList(Eq(valueCom))) + EXPECT_CALL(WifiSettings::GetInstance(), GetBlockList(Eq(valueCom), 0)) .WillOnce(DoAll(testing::SetArgReferee<0>(value), Return(0))); - EXPECT_CALL(WifiApHalInterface::GetInstance(), AddBlockByMac(An())) - .WillOnce(Return(WifiErrorNo::WIFI_IDL_OPT_OK)) - .WillOnce(Return(WifiErrorNo::WIFI_IDL_OPT_OK)); + EXPECT_CALL(WifiApHalInterface::GetInstance(), AddBlockByMac(An(), 0)) + .WillRepeatedly(Return(WifiErrorNo::WIFI_IDL_OPT_OK)); EXPECT_TRUE(pApStaMgr->EnableAllBlockList()); } -TEST_F(ApStationsManager_test, EnableAllBlockList_FAILED0) +HWTEST_F(ApStationsManager_test, EnableAllBlockList_FAILED0, TestSize.Level1) { std::vector value; std::vector valueCom; value.push_back(value1); value.push_back(value2); - EXPECT_CALL(WifiSettings::GetInstance(), GetBlockList(Eq(valueCom))) + EXPECT_CALL(WifiSettings::GetInstance(), GetBlockList(Eq(valueCom), 0)) .WillOnce(DoAll(testing::SetArgReferee<0>(value), Return(-1))); EXPECT_FALSE(pApStaMgr->EnableAllBlockList()); } -TEST_F(ApStationsManager_test, EnableAllBlockList_FAILED1) +HWTEST_F(ApStationsManager_test, EnableAllBlockList_FAILED1, TestSize.Level1) { std::vector value; std::vector valueCom; value.push_back(value1); value.push_back(value2); - EXPECT_CALL(WifiSettings::GetInstance(), GetBlockList(valueCom)) + EXPECT_CALL(WifiSettings::GetInstance(), GetBlockList(valueCom, 0)) .WillOnce(DoAll(testing::SetArgReferee<0>(value), Return(0))); - EXPECT_CALL(WifiApHalInterface::GetInstance(), AddBlockByMac(An())) + EXPECT_CALL(WifiApHalInterface::GetInstance(), AddBlockByMac(An(), 0)) .WillOnce(Return(WifiErrorNo::WIFI_IDL_OPT_FAILED)) .WillOnce(Return(WifiErrorNo::WIFI_IDL_OPT_FAILED)); EXPECT_FALSE(pApStaMgr->EnableAllBlockList()); } /* StationLeave */ -TEST_F(ApStationsManager_test, StationLeave) +HWTEST_F(ApStationsManager_test, StationLeave, TestSize.Level1) { StationInfo value3 = { "test_deviceName", @@ -160,12 +158,12 @@ TEST_F(ApStationsManager_test, StationLeave) valueList.push_back(value2); valueList.push_back(value1); valueList.push_back(value3); - EXPECT_CALL(WifiSettings::GetInstance(), GetStationList(Eq(valueCom))) + EXPECT_CALL(WifiSettings::GetInstance(), GetStationList(Eq(valueCom), 0)) .WillOnce(DoAll(testing::SetArgReferee<0>(valueList), Return(0))); - EXPECT_CALL(WifiSettings::GetInstance(), ManageStation(Eq(value2), Eq(1))).WillOnce(Return(0)); + EXPECT_CALL(WifiSettings::GetInstance(), ManageStation(Eq(value2), Eq(1), 0)).WillOnce(Return(0)); pApStaMgr->StationLeave(value1.bssid); } -TEST_F(ApStationsManager_test, StationLeave1) +HWTEST_F(ApStationsManager_test, StationLeave1, TestSize.Level1) { std::vector valueList; std::vector valueCom; @@ -177,12 +175,12 @@ TEST_F(ApStationsManager_test, StationLeave1) valueList.push_back(value2); valueList.push_back(value1); valueList.push_back(value3); - EXPECT_CALL(WifiSettings::GetInstance(), GetStationList(Eq(valueCom))) + EXPECT_CALL(WifiSettings::GetInstance(), GetStationList(Eq(valueCom), 0)) .WillOnce(DoAll(testing::SetArgReferee<0>(valueList), Return(1))); pApStaMgr->StationLeave(value1.bssid); EXPECT_STREQ("AA:BB:CC:DD:EE:FF", Mac.c_str()); } -TEST_F(ApStationsManager_test, StationLeave2) +HWTEST_F(ApStationsManager_test, StationLeave2, TestSize.Level1) { std::vector valueList; std::vector valueCom; @@ -194,15 +192,15 @@ TEST_F(ApStationsManager_test, StationLeave2) valueList.push_back(value3); valueList.push_back(value1); valueList.push_back(value2); - EXPECT_CALL(WifiSettings::GetInstance(), GetStationList(Eq(valueCom))) + EXPECT_CALL(WifiSettings::GetInstance(), GetStationList(Eq(valueCom), 0)) .WillOnce(DoAll(testing::SetArgReferee<0>(valueList), Return(0))); - EXPECT_CALL(WifiSettings::GetInstance(), ManageStation(Eq(value1), Eq(1))).WillOnce(Return(1)); + EXPECT_CALL(WifiSettings::GetInstance(), ManageStation(Eq(value1), Eq(1), 0)).WillOnce(Return(1)); pApStaMgr->StationLeave(value1.bssid); EXPECT_STREQ("AA:BB:CC:DD:EE:FF", Mac.c_str()); } /* StationJoin */ -TEST_F(ApStationsManager_test, StationJoin1) +HWTEST_F(ApStationsManager_test, StationJoin1, TestSize.Level1) { std::vector valueCom; std::vector valueList; @@ -213,11 +211,11 @@ TEST_F(ApStationsManager_test, StationJoin1) }; valueList.push_back(value2); valueList.push_back(value1); - EXPECT_CALL(WifiSettings::GetInstance(), GetStationList(Eq(valueCom))) + EXPECT_CALL(WifiSettings::GetInstance(), GetStationList(Eq(valueCom), 0)) .WillOnce(DoAll(testing::SetArgReferee<0>(valueList), Return(1))); pApStaMgr->StationJoin(value3); } -TEST_F(ApStationsManager_test, StationJoin2) +HWTEST_F(ApStationsManager_test, StationJoin2, TestSize.Level1) { std::vector valueList; std::vector valueCom; @@ -228,12 +226,12 @@ TEST_F(ApStationsManager_test, StationJoin2) }; valueList.push_back(value1); valueList.push_back(value2); - EXPECT_CALL(WifiSettings::GetInstance(), GetStationList(Eq(valueCom))) + EXPECT_CALL(WifiSettings::GetInstance(), GetStationList(Eq(valueCom), 0)) .WillOnce(DoAll(testing::SetArgReferee<0>(valueList), Return(0))); - EXPECT_CALL(WifiSettings::GetInstance(), ManageStation(Eq(value3), 0)).WillOnce(Return(0)); + EXPECT_CALL(WifiSettings::GetInstance(), ManageStation(Eq(value3), MODE_ADD, 0)).WillOnce(Return(0)); pApStaMgr->StationJoin(value3); } -TEST_F(ApStationsManager_test, StationJoin3) +HWTEST_F(ApStationsManager_test, StationJoin3, TestSize.Level1) { std::vector valueList; std::vector valueCom; @@ -244,12 +242,12 @@ TEST_F(ApStationsManager_test, StationJoin3) }; valueList.push_back(value2); valueList.push_back(value1); - EXPECT_CALL(WifiSettings::GetInstance(), GetStationList(Eq(valueCom))) + EXPECT_CALL(WifiSettings::GetInstance(), GetStationList(Eq(valueCom), 0)) .WillOnce(DoAll(testing::SetArgReferee<0>(valueList), Return(0))); - EXPECT_CALL(WifiSettings::GetInstance(), ManageStation(Eq(value3), 0)).WillOnce(Return(1)); + EXPECT_CALL(WifiSettings::GetInstance(), ManageStation(Eq(value3), MODE_ADD, 0)).WillOnce(Return(1)); pApStaMgr->StationJoin(value3); } -TEST_F(ApStationsManager_test, StationJoin4) +HWTEST_F(ApStationsManager_test, StationJoin4, TestSize.Level1) { std::vector valueList; std::vector valueCom; @@ -260,12 +258,12 @@ TEST_F(ApStationsManager_test, StationJoin4) }; valueList.push_back(value1); valueList.push_back(value2); - EXPECT_CALL(WifiSettings::GetInstance(), GetStationList(Eq(valueCom))) + EXPECT_CALL(WifiSettings::GetInstance(), GetStationList(Eq(valueCom), 0)) .WillOnce(DoAll(testing::SetArgReferee<0>(valueList), Return(0))); - EXPECT_CALL(WifiSettings::GetInstance(), ManageStation(Eq(value3), 0)).WillOnce(Return(0)); + EXPECT_CALL(WifiSettings::GetInstance(), ManageStation(Eq(value3), MODE_ADD, 0)).WillOnce(Return(0)); pApStaMgr->StationJoin(value3); } -TEST_F(ApStationsManager_test, StationJoin5) +HWTEST_F(ApStationsManager_test, StationJoin5, TestSize.Level1) { std::vector valueList; std::vector valueCom; @@ -276,29 +274,29 @@ TEST_F(ApStationsManager_test, StationJoin5) }; valueList.push_back(value1); valueList.push_back(value2); - EXPECT_CALL(WifiSettings::GetInstance(), GetStationList(Eq(valueCom))) + EXPECT_CALL(WifiSettings::GetInstance(), GetStationList(Eq(valueCom), 0)) .WillOnce(DoAll(testing::SetArgReferee<0>(valueList), Return(0))); - EXPECT_CALL(WifiSettings::GetInstance(), ManageStation(Eq(value1), 0)).WillOnce(Return(0)); + EXPECT_CALL(WifiSettings::GetInstance(), ManageStation(Eq(value1), MODE_ADD, 0)).WillOnce(Return(0)); pApStaMgr->StationJoin(value3); } /* DisConnectStation */ -TEST_F(ApStationsManager_test, DisConnectStion_SUCCESS) +HWTEST_F(ApStationsManager_test, DisConnectStion_SUCCESS, TestSize.Level1) { - EXPECT_CALL(WifiApHalInterface::GetInstance(), DisconnectStaByMac(StrEq(Mac))) + EXPECT_CALL(WifiApHalInterface::GetInstance(), DisconnectStaByMac(StrEq(Mac), 0)) .WillOnce(Return(WifiErrorNo::WIFI_IDL_OPT_OK)); EXPECT_TRUE(pApStaMgr->DisConnectStation(staInfo)); } -TEST_F(ApStationsManager_test, DisConnectStion_FAILED) +HWTEST_F(ApStationsManager_test, DisConnectStion_FAILED, TestSize.Level1) { - EXPECT_CALL(WifiApHalInterface::GetInstance(), DisconnectStaByMac(StrEq(Mac))) + EXPECT_CALL(WifiApHalInterface::GetInstance(), DisconnectStaByMac(StrEq(Mac), 0)) .WillOnce(Return(WifiErrorNo::WIFI_IDL_OPT_FAILED)); EXPECT_FALSE(pApStaMgr->DisConnectStation(staInfo)); } /* GetAllConnectedStations */ -TEST_F(ApStationsManager_test, GetAllConnectedStations_SUCCESS) +HWTEST_F(ApStationsManager_test, GetAllConnectedStations_SUCCESS, TestSize.Level1) { std::vector staMacList; std::vector staMacListCom; @@ -306,12 +304,12 @@ TEST_F(ApStationsManager_test, GetAllConnectedStations_SUCCESS) std::string staMacList2 = "test_deviceName2"; staMacList.push_back(staMacList1); staMacList.push_back(staMacList2); - EXPECT_CALL(WifiApHalInterface::GetInstance(), GetStationList(Eq(staMacListCom))) + EXPECT_CALL(WifiApHalInterface::GetInstance(), GetStationList(Eq(staMacListCom), 0)) .WillOnce(DoAll(testing::SetArgReferee<0>(staMacList), Return(WifiErrorNo::WIFI_IDL_OPT_OK))); EXPECT_EQ(staMacList, pApStaMgr->GetAllConnectedStations()); } -TEST_F(ApStationsManager_test, GetAllConnectedStations_FAILED) +HWTEST_F(ApStationsManager_test, GetAllConnectedStations_FAILED, TestSize.Level1) { std::vector staMacList; std::vector staMacListCom; @@ -319,33 +317,33 @@ TEST_F(ApStationsManager_test, GetAllConnectedStations_FAILED) std::string staMacList2 = "test_deviceName2"; staMacList.push_back(staMacList1); staMacList.push_back(staMacList2); - EXPECT_CALL(WifiApHalInterface::GetInstance(), GetStationList(Eq(staMacListCom))) + EXPECT_CALL(WifiApHalInterface::GetInstance(), GetStationList(Eq(staMacListCom), 0)) .WillOnce(DoAll(testing::SetArgReferee<0>(staMacList), Return(WifiErrorNo::WIFI_IDL_OPT_FAILED))); staMacList.erase(staMacList.begin()); EXPECT_NE(staMacList, pApStaMgr->GetAllConnectedStations()); } /* AddAssociationStation */ -TEST_F(ApStationsManager_test, AddAssociationStation_SUCCESS) +HWTEST_F(ApStationsManager_test, AddAssociationStation_SUCCESS, TestSize.Level1) { - EXPECT_CALL(WifiSettings::GetInstance(), ManageStation(Eq(staInfo), Eq(0))).WillOnce(Return(0)); + EXPECT_CALL(WifiSettings::GetInstance(), ManageStation(Eq(staInfo), Eq(0), 0)).WillOnce(Return(0)); EXPECT_TRUE(WrapAddAssociationStation(staInfo)); } -TEST_F(ApStationsManager_test, AddAssociationStation_FAILED) +HWTEST_F(ApStationsManager_test, AddAssociationStation_FAILED, TestSize.Level1) { - EXPECT_CALL(WifiSettings::GetInstance(), ManageStation(Eq(staInfo), Eq(0))).WillOnce(Return(-1)); + EXPECT_CALL(WifiSettings::GetInstance(), ManageStation(Eq(staInfo), Eq(0), 0)).WillOnce(Return(-1)); EXPECT_FALSE(WrapAddAssociationStation(staInfo)); } /* DelAssociationStation */ -TEST_F(ApStationsManager_test, DelAssociationStation_SUCCESS) +HWTEST_F(ApStationsManager_test, DelAssociationStation_SUCCESS, TestSize.Level1) { - EXPECT_CALL(WifiSettings::GetInstance(), ManageStation(Eq(staInfo), Eq(1))).WillOnce(Return(0)); + EXPECT_CALL(WifiSettings::GetInstance(), ManageStation(Eq(staInfo), Eq(1), 0)).WillOnce(Return(0)); EXPECT_TRUE(WrapDelAssociationStation(staInfo)); } -TEST_F(ApStationsManager_test, DelAssociationStation_FAILED) +HWTEST_F(ApStationsManager_test, DelAssociationStation_FAILED, TestSize.Level1) { - EXPECT_CALL(WifiSettings::GetInstance(), ManageStation(Eq(staInfo), Eq(1))).WillOnce(Return(-1)); + EXPECT_CALL(WifiSettings::GetInstance(), ManageStation(Eq(staInfo), Eq(1), 0)).WillOnce(Return(-1)); EXPECT_FALSE(WrapDelAssociationStation(staInfo)); } } // namespace Wifi diff --git a/tests/wifi_standard/wifi_framework/wifi_manage/wifi_ap/global_test.cpp b/wifi/test/wifi_standard/wifi_framework/wifi_manage/wifi_ap/global_test.cpp similarity index 100% rename from tests/wifi_standard/wifi_framework/wifi_manage/wifi_ap/global_test.cpp rename to wifi/test/wifi_standard/wifi_framework/wifi_manage/wifi_ap/global_test.cpp diff --git a/tests/wifi_standard/wifi_framework/wifi_manage/wifi_ap/global_test.h b/wifi/test/wifi_standard/wifi_framework/wifi_manage/wifi_ap/global_test.h similarity index 100% rename from tests/wifi_standard/wifi_framework/wifi_manage/wifi_ap/global_test.h rename to wifi/test/wifi_standard/wifi_framework/wifi_manage/wifi_ap/global_test.h diff --git a/tests/wifi_standard/wifi_framework/wifi_manage/wifi_ap/wifi_ap_dhcp_nat/wifi_ap_nat_manager_test.cpp b/wifi/test/wifi_standard/wifi_framework/wifi_manage/wifi_ap/wifi_ap_nat_manager_test.cpp similarity index 68% rename from tests/wifi_standard/wifi_framework/wifi_manage/wifi_ap/wifi_ap_dhcp_nat/wifi_ap_nat_manager_test.cpp rename to wifi/test/wifi_standard/wifi_framework/wifi_manage/wifi_ap/wifi_ap_nat_manager_test.cpp index 79d18f41cccfc10d06b1c2ffaaab268b91bc62bc..08c1327fdb79e39219bf04d4207e5d77d6e052f6 100644 --- a/tests/wifi_standard/wifi_framework/wifi_manage/wifi_ap/wifi_ap_dhcp_nat/wifi_ap_nat_manager_test.cpp +++ b/wifi/test/wifi_standard/wifi_framework/wifi_manage/wifi_ap/wifi_ap_nat_manager_test.cpp @@ -24,19 +24,16 @@ using ::testing::_; using ::testing::Return; +using ::testing::ext::TestSize; namespace OHOS { namespace Wifi { class WifiApNatManager_test : public testing::Test { public: - static void SetUpTestCase() - {} - static void TearDownTestCase() - {} - virtual void SetUp() - {} - virtual void TearDown() - {} + static void SetUpTestCase() {} + static void TearDownTestCase() {} + virtual void SetUp() {} + virtual void TearDown() {} public: bool WrapSetForwarding(bool enable) @@ -55,10 +52,6 @@ public: { return mApNatManager.WriteDataToFile(fileName, content); } - bool WrapExecCommand(const std::vector &vecCommandArg) - { - return mApNatManager.ExecCommand(vecCommandArg); - } public: std::string ifc1 = "wlan1"; @@ -67,11 +60,11 @@ public: WifiApNatManager mApNatManager; }; -TEST_F(WifiApNatManager_test, EnableInterfaceNat_SUCCESS) +HWTEST_F(WifiApNatManager_test, EnableInterfaceNat_SUCCESS, TestSize.Level1) { int fd = 10; MockSystemInterface::SetMockFlag(true); - EXPECT_CALL(MockSystemInterface::GetInstance(), system(_)).WillOnce(Return(-1)).WillRepeatedly(Return(fd)); + ON_CALL(MockSystemInterface::GetInstance(), system(_)).WillByDefault(Return(fd)); EXPECT_CALL(MockNetworkInterface::GetInstance(), IsValidInterfaceName(_)).WillRepeatedly(Return(true)); EXPECT_TRUE(mApNatManager.EnableInterfaceNat(true, ifc1, ifc2)); EXPECT_FALSE(mApNatManager.EnableInterfaceNat(true, ifc1, ifc1)); @@ -84,11 +77,11 @@ TEST_F(WifiApNatManager_test, EnableInterfaceNat_SUCCESS) EXPECT_FALSE(mApNatManager.EnableInterfaceNat(true, std::string(""), ifc1)); } -TEST_F(WifiApNatManager_test, DisableInterfaceNat_SUCCESS) +HWTEST_F(WifiApNatManager_test, DisableInterfaceNat_SUCCESS, TestSize.Level1) { int fd = 10; MockSystemInterface::SetMockFlag(true); - EXPECT_CALL(MockSystemInterface::GetInstance(), system(_)).WillOnce(Return(-1)).WillRepeatedly(Return(fd)); + ON_CALL(MockSystemInterface::GetInstance(), system(_)).WillByDefault(Return(fd)); EXPECT_CALL(MockNetworkInterface::GetInstance(), IsValidInterfaceName(_)).WillRepeatedly(Return(true)); EXPECT_TRUE(mApNatManager.EnableInterfaceNat(false, ifc1, ifc2)); EXPECT_FALSE(mApNatManager.EnableInterfaceNat(false, ifc1, ifc1)); @@ -99,61 +92,47 @@ TEST_F(WifiApNatManager_test, DisableInterfaceNat_SUCCESS) EXPECT_FALSE(mApNatManager.EnableInterfaceNat(false, badifc, ifc1)); EXPECT_FALSE(mApNatManager.EnableInterfaceNat(false, std::string(""), ifc1)); + MockSystemInterface::SetMockFlag(false); } -TEST_F(WifiApNatManager_test, SetForwarding_SUCCESS) +HWTEST_F(WifiApNatManager_test, SetForwarding_SUCCESS, TestSize.Level1) { EXPECT_TRUE(WrapSetForwarding(true)); EXPECT_TRUE(WrapSetForwarding(false)); } -TEST_F(WifiApNatManager_test, SetInterfaceRoute_SUCCESS) +HWTEST_F(WifiApNatManager_test, SetInterfaceRoute_SUCCESS, TestSize.Level1) { int fd = 10; MockSystemInterface::SetMockFlag(true); - EXPECT_CALL(MockSystemInterface::GetInstance(), system(_)).WillOnce(Return(-1)).WillRepeatedly(Return(fd)); + ON_CALL(MockSystemInterface::GetInstance(), system(_)).WillByDefault(Return(fd)); EXPECT_TRUE(WrapSetInterfaceRoute(true)); EXPECT_TRUE(WrapSetInterfaceRoute(false)); + MockSystemInterface::SetMockFlag(false); } -TEST_F(WifiApNatManager_test, SetInterfaceNat_SUCCESS) +HWTEST_F(WifiApNatManager_test, SetInterfaceNat_SUCCESS, TestSize.Level1) { int fd = 10; MockSystemInterface::SetMockFlag(true); - EXPECT_CALL(MockSystemInterface::GetInstance(), system(_)).WillOnce(Return(-1)).WillRepeatedly(Return(fd)); + ON_CALL(MockSystemInterface::GetInstance(), system(_)).WillByDefault(Return(fd)); EXPECT_TRUE(WrapSetInterfaceNat(true, ifc2)); EXPECT_TRUE(WrapSetInterfaceNat(false, ifc2)); + MockSystemInterface::SetMockFlag(false); } -TEST_F(WifiApNatManager_test, WriteDataToFile_SUCCESS) +HWTEST_F(WifiApNatManager_test, WriteDataToFile_SUCCESS, TestSize.Level1) { std::string filename = "./test.txt"; std::string context = "1234567890"; MockSystemInterface::SetMockFlag(true); - /* EXPECT_CALL(MockSystemInterface::GetInstance(), write(_, _, _)) - .WillOnce(Return(-1)) - .WillRepeatedly(Return(context.size())); */ -// EXPECT_CALL(MockSystemInterface::GetInstance(), close(_)).WillRepeatedly(Return(1)); - EXPECT_TRUE(WrapWriteDataToFile(filename, context)); EXPECT_TRUE(WrapWriteDataToFile(filename, context)); EXPECT_TRUE(WrapWriteDataToFile(filename, context)); MockSystemInterface::SetMockFlag(false); } - -TEST_F(WifiApNatManager_test, ExecCommand_SUCCESS) -{ - MockSystemInterface::SetMockFlag(true); - std::vector str; - EXPECT_CALL(MockSystemInterface::GetInstance(), system(_)).WillOnce(Return(true)).WillRepeatedly(Return(-1)); - - EXPECT_TRUE(WrapExecCommand(str)); - EXPECT_FALSE(WrapExecCommand(str)); - - MockSystemInterface::SetMockFlag(false); -} -} // namespace Wifi -} // namespace OHOS \ No newline at end of file +} // namespace Wifi +} // namespace OHOS \ No newline at end of file diff --git a/tests/wifi_standard/wifi_framework/wifi_manage/wifi_ap/wifi_ap_service_test.cpp b/wifi/test/wifi_standard/wifi_framework/wifi_manage/wifi_ap/wifi_ap_service_test.cpp similarity index 100% rename from tests/wifi_standard/wifi_framework/wifi_manage/wifi_ap/wifi_ap_service_test.cpp rename to wifi/test/wifi_standard/wifi_framework/wifi_manage/wifi_ap/wifi_ap_service_test.cpp diff --git a/interfaces/innerkits/native_cpp/napi/wifi_napi_hotspot.cpp b/wifi/test/wifi_standard/wifi_framework/wifi_manage/wifi_common/Mock/mock_chip_capability.cpp old mode 100755 new mode 100644 similarity index 75% rename from interfaces/innerkits/native_cpp/napi/wifi_napi_hotspot.cpp rename to wifi/test/wifi_standard/wifi_framework/wifi_manage/wifi_common/Mock/mock_chip_capability.cpp index 905df40e1ca465629f85b59b5200272b96759487..b7e73a6d7802502580e3279cfa1dd6da4656638d --- a/interfaces/innerkits/native_cpp/napi/wifi_napi_hotspot.cpp +++ b/wifi/test/wifi_standard/wifi_framework/wifi_manage/wifi_common/Mock/mock_chip_capability.cpp @@ -1,23 +1,26 @@ -/* - * Copyright (C) 2021 Huawei Device Co., Ltd. - * 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 "wifi_napi_hotspot.h" -#include "wifi_logger.h" - -namespace OHOS { -namespace Wifi { - -} // namespace Wifi -} // namespace OHOS +/* + * Copyright (C) 2022 Huawei Device Co., Ltd. + * 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 "mock_chip_capability.h" + +namespace OHOS { +namespace Wifi { +ChipCapability &ChipCapability::GetInstance() +{ + static ChipCapability cp; + return cp; +} +} // namespace Wifi +} // namespace OHOS diff --git a/wifi/test/wifi_standard/wifi_framework/wifi_manage/wifi_common/Mock/mock_chip_capability.h b/wifi/test/wifi_standard/wifi_framework/wifi_manage/wifi_common/Mock/mock_chip_capability.h new file mode 100644 index 0000000000000000000000000000000000000000..d70463532e991100f8ddfb8ec84502b734b96f1f --- /dev/null +++ b/wifi/test/wifi_standard/wifi_framework/wifi_manage/wifi_common/Mock/mock_chip_capability.h @@ -0,0 +1,50 @@ +/* + * Copyright (C) 2022 Huawei Device Co., Ltd. + * 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 OHOS_MOCK_CHIP_CAPABILITY_H +#define OHOS_MOCK_CHIP_CAPABILITY_H + +#include + +namespace OHOS { +namespace Wifi { +class MockChipCapability { +public: + MockChipCapability() = default; + virtual ~MockChipCapability() = default; + + virtual bool InitializeChipCapability() = 0; + virtual bool IsSupportDbdc(void) = 0; + virtual bool IsSupportCsa(void) = 0; + virtual bool IsSupportRadarDetect(void) = 0; + virtual bool IsSupportDfsChannel(void) = 0; + virtual bool IsSupportIndoorChannel(void) = 0; +}; + +class ChipCapability : public MockChipCapability { +public: + ChipCapability() = default; + ~ChipCapability() = default; + static ChipCapability &GetInstance(void); + MOCK_METHOD0(InitializeChipCapability, bool()); + MOCK_METHOD0(IsSupportDbdc, bool()); + MOCK_METHOD0(IsSupportCsa, bool()); + MOCK_METHOD0(IsSupportRadarDetect, bool()); + MOCK_METHOD0(IsSupportDfsChannel, bool()); + MOCK_METHOD0(IsSupportIndoorChannel, bool()); +}; +} // namespace Wifi +} // namespace OHOS +#endif \ No newline at end of file diff --git a/wifi/test/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/test/BUILD.gn b/wifi/test/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/test/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..d4fb6575bd48074f35035028f0261b309ec5d22d --- /dev/null +++ b/wifi/test/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/test/BUILD.gn @@ -0,0 +1,159 @@ +# Copyright (C) 2021-2022 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import("//build/test.gni") +import("//foundation/communication/wifi/wifi/wifi.gni") +config("module_private_config") { + visibility = [ ":*" ] + include_dirs = [ + "//commonlibrary/c_utils/base/include", + "$WIFI_ROOT_DIR/services/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/test", + ] +} + +ohos_unittest("wifi_p2p_test") { + module_out_path = "wifi/p2p_test" + sources = [ + "$WIFI_ROOT_DIR/frameworks/native/src/wifi_hid2d_msg.cpp", + "$WIFI_ROOT_DIR/frameworks/native/src/wifi_p2p_msg.cpp", + "$WIFI_ROOT_DIR/services/wifi_standard/wifi_framework/wifi_manage/common/handler.cpp", + "$WIFI_ROOT_DIR/services/wifi_standard/wifi_framework/wifi_manage/common/internal_message.cpp", + "$WIFI_ROOT_DIR/services/wifi_standard/wifi_framework/wifi_manage/common/message_queue.cpp", + "$WIFI_ROOT_DIR/services/wifi_standard/wifi_framework/wifi_manage/common/state.cpp", + "$WIFI_ROOT_DIR/services/wifi_standard/wifi_framework/wifi_manage/common/state_machine.cpp", + "$WIFI_ROOT_DIR/services/wifi_standard/wifi_framework/wifi_manage/common/wifi_broadcast_helper.cpp", + "$WIFI_ROOT_DIR/services/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/authorizing_negotiation_request_state.cpp", + "$WIFI_ROOT_DIR/services/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/group_formed_state.cpp", + "$WIFI_ROOT_DIR/services/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/group_negotiation_state.cpp", + "$WIFI_ROOT_DIR/services/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/hid2d/wifi_hid2d_service_utils.cpp", + "$WIFI_ROOT_DIR/services/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/invitation_received_state.cpp", + "$WIFI_ROOT_DIR/services/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/invitation_request_state.cpp", + "$WIFI_ROOT_DIR/services/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/p2p_default_state.cpp", + "$WIFI_ROOT_DIR/services/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/p2p_disabled_state.cpp", + "$WIFI_ROOT_DIR/services/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/p2p_disabling_state.cpp", + "$WIFI_ROOT_DIR/services/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/p2p_enabled_state.cpp", + "$WIFI_ROOT_DIR/services/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/p2p_enabling_state.cpp", + "$WIFI_ROOT_DIR/services/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/p2p_group_formation_state.cpp", + "$WIFI_ROOT_DIR/services/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/p2p_group_join_state.cpp", + "$WIFI_ROOT_DIR/services/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/p2p_group_operating_state.cpp", + "$WIFI_ROOT_DIR/services/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/p2p_idle_state.cpp", + "$WIFI_ROOT_DIR/services/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/p2p_inviting_state.cpp", + "$WIFI_ROOT_DIR/services/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/p2p_monitor.cpp", + "$WIFI_ROOT_DIR/services/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/p2p_state_machine.cpp", + "$WIFI_ROOT_DIR/services/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/provision_discovery_state.cpp", + "$WIFI_ROOT_DIR/services/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/wifi_p2p_device_manager.cpp", + "$WIFI_ROOT_DIR/services/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/wifi_p2p_dns_sd_service_info.cpp", + "$WIFI_ROOT_DIR/services/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/wifi_p2p_dns_sd_service_request.cpp", + "$WIFI_ROOT_DIR/services/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/wifi_p2p_dns_sd_service_response.cpp", + "$WIFI_ROOT_DIR/services/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/wifi_p2p_dns_txt_record.cpp", + "$WIFI_ROOT_DIR/services/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/wifi_p2p_group_info_proxy.cpp", + "$WIFI_ROOT_DIR/services/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/wifi_p2p_group_manager.cpp", + "$WIFI_ROOT_DIR/services/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/wifi_p2p_service.cpp", + "$WIFI_ROOT_DIR/services/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/wifi_p2p_service_manager.cpp", + "$WIFI_ROOT_DIR/services/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/wifi_p2p_service_request_list.cpp", + "$WIFI_ROOT_DIR/services/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/wifi_p2p_service_response_list.cpp", + "$WIFI_ROOT_DIR/services/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/wifi_p2p_temp_disc_event.cpp", + "$WIFI_ROOT_DIR/services/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/wifi_p2p_upnp_service_info.cpp", + "$WIFI_ROOT_DIR/services/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/wifi_p2p_upnp_service_request.cpp", + "$WIFI_ROOT_DIR/services/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/wifi_p2p_upnp_service_response.cpp", + "./Mock/mock_wifi_p2p_hal_interface.cpp", + "authorizing_negotiation_request_state_test.cpp", + "global_test.cpp", + "group_formed_state_test.cpp", + "group_negotiation_state_test.cpp", + "invitation_recelved_state_test.cpp", + "invitation_request_state_test.cpp", + "p2p_default_state_test.cpp", + "p2p_disabled_state_test.cpp", + "p2p_disabling_state_test.cpp", + "p2p_enabled_state_test.cpp", + "p2p_enabling_state_test.cpp", + "p2p_group_formation_state_test.cpp", + "p2p_group_join_state_test.cpp", + "p2p_group_operating_state_test.cpp", + "p2p_idle_state_test.cpp", + "p2p_inviting_state_test.cpp", + "p2p_monitor_test.cpp", + "p2p_state_machine_test.cpp", + "provision_discovery_state_test.cpp", + "wifi_p2p_device_manager_test.cpp", + "wifi_p2p_dns_sd_service_info_test.cpp", + "wifi_p2p_dns_sd_service_request_test.cpp", + "wifi_p2p_dns_sd_service_response_test.cpp", + "wifi_p2p_group_info_proxy_test.cpp", + "wifi_p2p_group_manager_test.cpp", + "wifi_p2p_service_manager_test.cpp", + "wifi_p2p_service_request_list_test.cpp", + "wifi_p2p_service_response_list_test.cpp", + "wifi_p2p_service_test.cpp", + "wifi_p2p_upnp_service_info_test.cpp", + "wifi_p2p_upnp_service_request_test.cpp", + "wifi_p2p_upnp_service_response_test.cpp", + ] + + include_dirs = [ + "./", + "$WIFI_ROOT_DIR/services/wifi_standard/wifi_framework/wifi_manage/wifi_p2p", + "./Mock", + "//commonlibrary/c_utils/base/include", + "//base/hiviewdfx/hilog/interfaces/native/innerkits/include", + "$WIFI_ROOT_DIR/frameworks/native/interfaces", + "$WIFI_ROOT_DIR/services/wifi_standard/ipc_framework/cRPC/include", + "$WIFI_ROOT_DIR/services/wifi_standard/wifi_framework/wifi_toolkit/include", + "$WIFI_ROOT_DIR/services/wifi_standard/wifi_framework/wifi_toolkit/net_helper", + "$WIFI_ROOT_DIR/services/wifi_standard/wifi_framework/wifi_toolkit/config", + "$WIFI_ROOT_DIR/services/wifi_standard/wifi_framework/wifi_toolkit/log", + "$WIFI_ROOT_DIR/services/wifi_standard/wifi_framework/wifi_toolkit/utils", + "$WIFI_ROOT_DIR/services/wifi_standard/wifi_framework/wifi_manage/common/include", + "$WIFI_ROOT_DIR/services/wifi_standard/wifi_framework/wifi_manage/wifi_ap", + "$WIFI_ROOT_DIR/services/wifi_standard/wifi_framework/wifi_manage", + "$WIFI_ROOT_DIR/services/wifi_standard/wifi_framework/wifi_manage/common", + "$WIFI_ROOT_DIR/services/wifi_standard/wifi_framework/wifi_manage/idl_client", + "$WIFI_ROOT_DIR/services/wifi_standard/wifi_framework/wifi_manage/idl_client/idl_interface", + "$DHCP_ROOT_DIR/services/mgr_service/include", + "$DHCP_ROOT_DIR/interfaces/inner_api/include", + "$DHCP_ROOT_DIR/interfaces/inner_api/interfaces", + "//third_party/googletest/googlemock/include", + "//third_party/googletest/googletest/include", + "$WIFI_ROOT_DIR/services/wifi_standard/wifi_framework/wifi_manage/wifi_sta", + "$WIFI_ROOT_DIR/services/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/hid2d", + "$WIFI_ROOT_DIR/utils/inc", + "$WIFI_ROOT_DIR/services/wifi_standard/include", + ] + + deps = [ + "$DHCP_ROOT_DIR/services/mgr_service:dhcp_manager_service", + "$WIFI_ROOT_DIR/services/wifi_standard/wifi_framework/wifi_manage:wifi_manager_service", + "$WIFI_ROOT_DIR/services/wifi_standard/wifi_framework/wifi_manage/wifi_common:wifi_common_service", + "$WIFI_ROOT_DIR/services/wifi_standard/wifi_framework/wifi_toolkit:wifi_toolkit", + "$WIFI_ROOT_DIR/utils:wifi_utils", + "//third_party/googletest:gmock_main", + "//third_party/googletest:gtest_main", + ] + external_deps = [ + "c_utils:utils", + "hiviewdfx_hilog_native:libhilog", + "ipc:ipc_core", + "netmanager_base:net_conn_manager_if", + ] + + defines = [ "AP_INSTANCE_MAX_NUM=$wifi_feature_with_ap_num" ] + part_name = "wifi" + subsystem_name = "communication" +} + +group("unittest") { + testonly = true + deps = [] + deps += [ ":wifi_p2p_test" ] +} diff --git a/tests/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/test/Mock/mock_authorizing_negotiation_request_state.h b/wifi/test/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/test/Mock/mock_authorizing_negotiation_request_state.h similarity index 100% rename from tests/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/test/Mock/mock_authorizing_negotiation_request_state.h rename to wifi/test/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/test/Mock/mock_authorizing_negotiation_request_state.h diff --git a/tests/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/test/Mock/mock_group_formed_state.h b/wifi/test/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/test/Mock/mock_group_formed_state.h similarity index 100% rename from tests/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/test/Mock/mock_group_formed_state.h rename to wifi/test/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/test/Mock/mock_group_formed_state.h diff --git a/tests/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/test/Mock/mock_group_negotiation_state.h b/wifi/test/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/test/Mock/mock_group_negotiation_state.h similarity index 100% rename from tests/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/test/Mock/mock_group_negotiation_state.h rename to wifi/test/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/test/Mock/mock_group_negotiation_state.h diff --git a/tests/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/test/Mock/mock_invitation_recelved_state.h b/wifi/test/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/test/Mock/mock_invitation_recelved_state.h similarity index 100% rename from tests/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/test/Mock/mock_invitation_recelved_state.h rename to wifi/test/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/test/Mock/mock_invitation_recelved_state.h diff --git a/tests/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/test/Mock/mock_invitation_request_state.h b/wifi/test/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/test/Mock/mock_invitation_request_state.h similarity index 100% rename from tests/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/test/Mock/mock_invitation_request_state.h rename to wifi/test/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/test/Mock/mock_invitation_request_state.h diff --git a/tests/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/test/Mock/mock_p2p_default_state.h b/wifi/test/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/test/Mock/mock_p2p_default_state.h similarity index 100% rename from tests/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/test/Mock/mock_p2p_default_state.h rename to wifi/test/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/test/Mock/mock_p2p_default_state.h diff --git a/tests/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/test/Mock/mock_p2p_disabled_state.h b/wifi/test/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/test/Mock/mock_p2p_disabled_state.h similarity index 100% rename from tests/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/test/Mock/mock_p2p_disabled_state.h rename to wifi/test/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/test/Mock/mock_p2p_disabled_state.h diff --git a/tests/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/test/Mock/mock_p2p_disabling_state.h b/wifi/test/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/test/Mock/mock_p2p_disabling_state.h similarity index 100% rename from tests/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/test/Mock/mock_p2p_disabling_state.h rename to wifi/test/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/test/Mock/mock_p2p_disabling_state.h diff --git a/tests/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/test/Mock/mock_p2p_enabled_state.h b/wifi/test/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/test/Mock/mock_p2p_enabled_state.h similarity index 100% rename from tests/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/test/Mock/mock_p2p_enabled_state.h rename to wifi/test/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/test/Mock/mock_p2p_enabled_state.h diff --git a/tests/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/test/Mock/mock_p2p_enabling_state.h b/wifi/test/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/test/Mock/mock_p2p_enabling_state.h similarity index 100% rename from tests/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/test/Mock/mock_p2p_enabling_state.h rename to wifi/test/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/test/Mock/mock_p2p_enabling_state.h diff --git a/tests/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/test/Mock/mock_p2p_group_formation_state.h b/wifi/test/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/test/Mock/mock_p2p_group_formation_state.h similarity index 100% rename from tests/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/test/Mock/mock_p2p_group_formation_state.h rename to wifi/test/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/test/Mock/mock_p2p_group_formation_state.h diff --git a/tests/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/test/Mock/mock_p2p_group_join_state.h b/wifi/test/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/test/Mock/mock_p2p_group_join_state.h similarity index 100% rename from tests/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/test/Mock/mock_p2p_group_join_state.h rename to wifi/test/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/test/Mock/mock_p2p_group_join_state.h diff --git a/tests/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/test/Mock/mock_p2p_group_operating_state.h b/wifi/test/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/test/Mock/mock_p2p_group_operating_state.h similarity index 100% rename from tests/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/test/Mock/mock_p2p_group_operating_state.h rename to wifi/test/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/test/Mock/mock_p2p_group_operating_state.h diff --git a/tests/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/test/Mock/mock_p2p_idle_state.h b/wifi/test/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/test/Mock/mock_p2p_idle_state.h similarity index 100% rename from tests/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/test/Mock/mock_p2p_idle_state.h rename to wifi/test/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/test/Mock/mock_p2p_idle_state.h diff --git a/tests/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/test/Mock/mock_p2p_inviting_state.h b/wifi/test/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/test/Mock/mock_p2p_inviting_state.h similarity index 100% rename from tests/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/test/Mock/mock_p2p_inviting_state.h rename to wifi/test/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/test/Mock/mock_p2p_inviting_state.h diff --git a/tests/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/test/Mock/mock_p2p_monitor.h b/wifi/test/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/test/Mock/mock_p2p_monitor.h similarity index 100% rename from tests/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/test/Mock/mock_p2p_monitor.h rename to wifi/test/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/test/Mock/mock_p2p_monitor.h diff --git a/tests/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/test/Mock/mock_p2p_state_machine.h b/wifi/test/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/test/Mock/mock_p2p_state_machine.h similarity index 73% rename from tests/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/test/Mock/mock_p2p_state_machine.h rename to wifi/test/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/test/Mock/mock_p2p_state_machine.h index 84818765e51115de208a7822fb7d8f25e5c0ca54..8f02bd533c8ec7e4137e9bf69eb7e7f85e0a59e2 100644 --- a/tests/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/test/Mock/mock_p2p_state_machine.h +++ b/wifi/test/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/test/Mock/mock_p2p_state_machine.h @@ -36,7 +36,18 @@ public: {} ~MockP2pStateMachine() = default; MOCK_METHOD0(Initialize, void()); - MOCK_METHOD1(IsConfigUnusable, P2pConfigErrCode(const WifiP2pConfig &config)); + MOCK_METHOD1(IsConfigUnusable, P2pConfigErrCode(const WifiP2pConfigInternal &config)); + MOCK_METHOD0(DealGroupCreationFailed, void()); + MOCK_CONST_METHOD2(BroadcastActionResult, void(P2pActionCallback action, ErrCode result)); + MOCK_CONST_METHOD1(BroadcastP2pStatusChanged, void(P2pState state)); + MOCK_CONST_METHOD1(BroadcastThisDeviceChanaged, void(const WifiP2pDevice &device)); + MOCK_CONST_METHOD0(UpdateGroupInfoToWpa, void()); + MOCK_CONST_METHOD0(BroadcastP2pPeersChanged, void()); + MOCK_CONST_METHOD1(ReawakenPersistentGroup, bool(WifiP2pConfigInternal &config)); + MOCK_CONST_METHOD0(UpdatePersistentGroups, void()); + MOCK_METHOD0(StartDhcpServer, bool()); + MOCK_CONST_METHOD2(SetGroupConfig, bool(const WifiP2pConfigInternal &config, bool newGroup)); + MOCK_CONST_METHOD2(DealCreateNewGroupWithConfig, bool(const WifiP2pConfigInternal &config, int freq)); }; } // namespace Wifi } // namespace OHOS diff --git a/tests/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/test/Mock/mock_provision_discovery_state.h b/wifi/test/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/test/Mock/mock_provision_discovery_state.h similarity index 100% rename from tests/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/test/Mock/mock_provision_discovery_state.h rename to wifi/test/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/test/Mock/mock_provision_discovery_state.h diff --git a/tests/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/test/Mock/mock_wifi_p2p_device_manager.cpp b/wifi/test/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/test/Mock/mock_wifi_p2p_device_manager.cpp similarity index 100% rename from tests/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/test/Mock/mock_wifi_p2p_device_manager.cpp rename to wifi/test/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/test/Mock/mock_wifi_p2p_device_manager.cpp diff --git a/tests/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/test/Mock/mock_wifi_p2p_device_manager.h b/wifi/test/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/test/Mock/mock_wifi_p2p_device_manager.h similarity index 100% rename from tests/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/test/Mock/mock_wifi_p2p_device_manager.h rename to wifi/test/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/test/Mock/mock_wifi_p2p_device_manager.h diff --git a/tests/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/test/Mock/mock_wifi_p2p_hal_interface.cpp b/wifi/test/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/test/Mock/mock_wifi_p2p_hal_interface.cpp similarity index 100% rename from tests/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/test/Mock/mock_wifi_p2p_hal_interface.cpp rename to wifi/test/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/test/Mock/mock_wifi_p2p_hal_interface.cpp diff --git a/tests/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/test/Mock/mock_wifi_p2p_hal_interface.h b/wifi/test/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/test/Mock/mock_wifi_p2p_hal_interface.h similarity index 93% rename from tests/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/test/Mock/mock_wifi_p2p_hal_interface.h rename to wifi/test/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/test/Mock/mock_wifi_p2p_hal_interface.h index 50cb43ec593a8c60bc42968a4a60b37fc5c50001..2e050d4213f2265b408931436a13dbbc4772b915 100644 --- a/tests/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/test/Mock/mock_wifi_p2p_hal_interface.h +++ b/wifi/test/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/test/Mock/mock_wifi_p2p_hal_interface.h @@ -1,5 +1,5 @@ /* - * Copyright (C) 2021 Huawei Device Co., Ltd. + * Copyright (C) 2021-2022 Huawei Device Co., Ltd. * 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 @@ -19,10 +19,11 @@ #include #include #include -#include "wifi_msg.h" +#include "wifi_p2p_msg.h" #include "wifi_error_no.h" #include "wifi_idl_struct.h" #include "wifi_p2p_event_callback.h" +#include "wifi_hid2d_msg.h" namespace OHOS { namespace Wifi { @@ -49,9 +50,10 @@ public: virtual WifiErrorNo P2pConfigureListen(bool enable, size_t period, size_t interval) const = 0; virtual WifiErrorNo SetListenChannel(size_t channel, unsigned char regClass) const = 0; virtual WifiErrorNo P2pFlush() const = 0; - virtual WifiErrorNo Connect(const WifiP2pConfig &config, bool isJoinExistingGroup, std::string &pin) const = 0; + virtual WifiErrorNo Connect(const WifiP2pConfigInternal &config, bool isJoinExistingGroup, + std::string &pin) const = 0; virtual WifiErrorNo CancelConnect() const = 0; - virtual WifiErrorNo ProvisionDiscovery(const WifiP2pConfig &config) const = 0; + virtual WifiErrorNo ProvisionDiscovery(const WifiP2pConfigInternal &config) const = 0; virtual WifiErrorNo GroupAdd(bool isPersistent, int networkId, int freq) const = 0; virtual WifiErrorNo GroupRemove(const std::string &groupInterface) const = 0; virtual WifiErrorNo Invite(const WifiP2pGroupInfo &group, const std::string &deviceAddr) const = 0; @@ -78,6 +80,7 @@ public: virtual WifiErrorNo P2pAddNetwork(int &networkId) const = 0; virtual WifiErrorNo SetPersistentReconnect(int mode) const = 0; virtual WifiErrorNo SetP2pSecondaryDeviceType(const std::string &type) = 0; + virtual WifiErrorNo Hid2dConnect(const Hid2dConnectConfig &config) const = 0; }; class WifiP2PHalInterface : public MockWifiP2PHalInterface { @@ -105,9 +108,10 @@ public: MOCK_CONST_METHOD3(P2pConfigureListen, WifiErrorNo(bool enable, size_t period, size_t interval)); MOCK_CONST_METHOD2(SetListenChannel, WifiErrorNo(size_t channel, unsigned char regClass)); MOCK_CONST_METHOD0(P2pFlush, WifiErrorNo()); - MOCK_CONST_METHOD3(Connect, WifiErrorNo(const WifiP2pConfig &config, bool isJoinExistingGroup, std::string &pin)); + MOCK_CONST_METHOD3(Connect, + WifiErrorNo(const WifiP2pConfigInternal &config, bool isJoinExistingGroup, std::string &pin)); MOCK_CONST_METHOD0(CancelConnect, WifiErrorNo()); - MOCK_CONST_METHOD1(ProvisionDiscovery, WifiErrorNo(const WifiP2pConfig &)); + MOCK_CONST_METHOD1(ProvisionDiscovery, WifiErrorNo(const WifiP2pConfigInternal &)); MOCK_CONST_METHOD3(GroupAdd, WifiErrorNo(bool isPersistent, int networkId, int freq)); MOCK_CONST_METHOD1(GroupRemove, WifiErrorNo(const std::string &groupInterface)); MOCK_CONST_METHOD2(Invite, WifiErrorNo(const WifiP2pGroupInfo &group, const std::string &deviceAddr)); @@ -134,6 +138,7 @@ public: MOCK_CONST_METHOD1(P2pAddNetwork, WifiErrorNo(int &networkId)); MOCK_CONST_METHOD1(SetPersistentReconnect, WifiErrorNo(int mode)); MOCK_METHOD1(SetP2pSecondaryDeviceType, WifiErrorNo(const std::string &type)); + MOCK_CONST_METHOD1(Hid2dConnect, WifiErrorNo(const Hid2dConnectConfig &config)); }; } // namespace Wifi } // namespace OHOS diff --git a/tests/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/test/Mock/mock_wifi_settings.cpp b/wifi/test/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/test/Mock/mock_wifi_settings.cpp similarity index 100% rename from tests/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/test/Mock/mock_wifi_settings.cpp rename to wifi/test/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/test/Mock/mock_wifi_settings.cpp diff --git a/tests/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/test/Mock/mock_wifi_settings.h b/wifi/test/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/test/Mock/mock_wifi_settings.h similarity index 47% rename from tests/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/test/Mock/mock_wifi_settings.h rename to wifi/test/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/test/Mock/mock_wifi_settings.h index 7a49e52c6dd5538c7305cdf0718962abb48f3de1..b18373588ebbc31a5ed972499d6fe0fa062e9de4 100644 --- a/tests/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/test/Mock/mock_wifi_settings.h +++ b/wifi/test/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/test/Mock/mock_wifi_settings.h @@ -1,5 +1,5 @@ /* - * Copyright (C) 2021 Huawei Device Co., Ltd. + * Copyright (C) 2021-2022 Huawei Device Co., Ltd. * 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 @@ -19,7 +19,7 @@ #include #include #include -#include "wifi_msg.h" +#include "wifi_p2p_msg.h" #include namespace OHOS { @@ -28,33 +28,16 @@ const int MODE_ADD = 0; const int MODE_DEL = 1; const int MODE_UPDATE = 2; -using ChannelsTable = std::map>; - class MockWifiSettings { public: virtual ~MockWifiSettings() = default; virtual int SetCountryCode(const std::string &countryCode) = 0; virtual int GetCountryCode(std::string &countryCode) = 0; - virtual int GetHotspotState() = 0; - virtual int SetHotspotState(int state) = 0; - virtual int SetHotspotConfig(const HotspotConfig &config) = 0; - virtual int GetHotspotConfig(HotspotConfig &config) = 0; - virtual int GetStationList(std::vector &results) = 0; - virtual int ManageStation(const StationInfo &info, int mode) = 0; /* add / update / remove */ - virtual int ClearStationList() = 0; - virtual int GetBlockList(std::vector &results) = 0; - virtual int ManageBlockList(const StationInfo &info, int mode) = 0; /* add / remove */ - virtual int FindConnStation(const StationInfo &info) = 0; - virtual int GetValidBands(std::vector &bands) = 0; - virtual int SetValidChannels(const ChannelsTable &channelsInfo) = 0; - virtual int GetValidChannels(ChannelsTable &channelsInfo) = 0; - virtual int ClearValidChannels() = 0; - virtual int GetApMaxConnNum() = 0; virtual int SetWifiP2pGroupInfo(const std::vector &groups) = 0; virtual int SetP2pVendorConfig(const P2pVendorConfig &config) = 0; virtual int GetP2pVendorConfig(P2pVendorConfig &config) = 0; - virtual int GetP2pInfo(WifiP2pInfo &connInfo) = 0; - virtual int SaveP2pInfo(WifiP2pInfo &connInfo) = 0; + virtual int GetP2pInfo(WifiP2pLinkedInfo &linkedInfo) = 0; + virtual int SaveP2pInfo(WifiP2pLinkedInfo &linkedInfo) = 0; virtual int GetWifiP2pGroupInfo(std::vector &groups) = 0; }; @@ -64,28 +47,13 @@ public: ~WifiSettings() = default; static WifiSettings &GetInstance(void); MOCK_METHOD1(GetWifiP2pGroupInfo, int(std::vector &groups)); - MOCK_METHOD1(SaveP2pInfo, int(WifiP2pInfo &connInfo)); - MOCK_METHOD1(GetP2pInfo, int(WifiP2pInfo &connInfo)); + MOCK_METHOD1(SaveP2pInfo, int(WifiP2pLinkedInfo &linkedInfo)); + MOCK_METHOD1(GetP2pInfo, int(WifiP2pLinkedInfo &linkedInfo)); MOCK_METHOD1(SetP2pVendorConfig, int(const P2pVendorConfig &config)); MOCK_METHOD1(GetP2pVendorConfig, int(P2pVendorConfig &config)); MOCK_METHOD1(SetWifiP2pGroupInfo, int(const std::vector &groups)); MOCK_METHOD1(SetCountryCode, int(const std::string &countryCode)); MOCK_METHOD1(GetCountryCode, int(std::string &countryCode)); - MOCK_METHOD0(GetHotspotState, int()); - MOCK_METHOD1(SetHotspotState, int(int)); - MOCK_METHOD1(SetHotspotConfig, int(const HotspotConfig &config)); - MOCK_METHOD1(GetHotspotConfig, int(HotspotConfig &config)); - MOCK_METHOD1(GetStationList, int(std::vector &results)); - MOCK_METHOD2(ManageStation, int(const StationInfo &info, int mode)); - MOCK_METHOD0(ClearStationList, int()); - MOCK_METHOD1(GetBlockList, int(std::vector &results)); - MOCK_METHOD2(ManageBlockList, int(const StationInfo &info, int mode)); - MOCK_METHOD1(FindConnStation, int(const StationInfo &info)); - MOCK_METHOD1(GetValidBands, int(std::vector &bands)); - MOCK_METHOD1(SetValidChannels, int(const ChannelsTable &channelsInfo)); - MOCK_METHOD1(GetValidChannels, int(ChannelsTable &channelsInfo)); - MOCK_METHOD0(ClearValidChannels, int()); - MOCK_METHOD0(GetApMaxConnNum, int()); }; } // namespace Wifi } // namespace OHOS diff --git a/tests/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/test/authorizing_negotiation_request_state_test.cpp b/wifi/test/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/test/authorizing_negotiation_request_state_test.cpp similarity index 99% rename from tests/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/test/authorizing_negotiation_request_state_test.cpp rename to wifi/test/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/test/authorizing_negotiation_request_state_test.cpp index f3b7cbb6c350968bb35398a06b7f99c83211b69b..46e0bcecbb904adce35c86367bf88536f978a351 100644 --- a/tests/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/test/authorizing_negotiation_request_state_test.cpp +++ b/wifi/test/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/test/authorizing_negotiation_request_state_test.cpp @@ -73,10 +73,12 @@ HWTEST_F(AuthorizingNegotiationRequestStateTest, GoInState, TestSize.Level1) AddSaveP2pConfig(); pAuthorizingNegotlationRequestState->GoInState(); } + HWTEST_F(AuthorizingNegotiationRequestStateTest, GoOutState, TestSize.Level1) { pAuthorizingNegotlationRequestState->GoOutState(); } + HWTEST_F(AuthorizingNegotiationRequestStateTest, ExecuteStateMsg, TestSize.Level1) { AddSaveP2pConfig(); @@ -98,12 +100,14 @@ HWTEST_F(AuthorizingNegotiationRequestStateTest, ExecuteStateMsg1, TestSize.Leve EXPECT_CALL(WifiP2PHalInterface::GetInstance(), P2pStopFind()).WillOnce(Return(WifiErrorNo::WIFI_IDL_OPT_FAILED)); pAuthorizingNegotlationRequestState->ExecuteStateMsg(&msg); } + HWTEST_F(AuthorizingNegotiationRequestStateTest, ExecuteStateMsg2, TestSize.Level1) { InternalMessage msg; msg.SetMessageName(static_cast(P2P_STATE_MACHINE_CMD::PEER_CONNECTION_USER_REJECT)); pAuthorizingNegotlationRequestState->ExecuteStateMsg(&msg); } + HWTEST_F(AuthorizingNegotiationRequestStateTest, ExecuteStateMsg3, TestSize.Level1) { InternalMessage msg; @@ -112,6 +116,7 @@ HWTEST_F(AuthorizingNegotiationRequestStateTest, ExecuteStateMsg3, TestSize.Leve .WillOnce(Return(WifiErrorNo::WIFI_IDL_OPT_FAILED)); pAuthorizingNegotlationRequestState->ExecuteStateMsg(&msg); } + HWTEST_F(AuthorizingNegotiationRequestStateTest, ExecuteStateMsg4, TestSize.Level1) { InternalMessage msg; diff --git a/tests/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/test/global_test.cpp b/wifi/test/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/test/global_test.cpp similarity index 100% rename from tests/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/test/global_test.cpp rename to wifi/test/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/test/global_test.cpp diff --git a/tests/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/test/global_test.h b/wifi/test/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/test/global_test.h similarity index 100% rename from tests/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/test/global_test.h rename to wifi/test/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/test/global_test.h diff --git a/tests/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/test/group_formed_state_test.cpp b/wifi/test/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/test/group_formed_state_test.cpp similarity index 81% rename from tests/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/test/group_formed_state_test.cpp rename to wifi/test/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/test/group_formed_state_test.cpp index 848a9b4a4ae7340ba1df965e9dfdda88095729e3..4d4f74d11e4be4c2876de3568b57de976c2aacd0 100644 --- a/tests/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/test/group_formed_state_test.cpp +++ b/wifi/test/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/test/group_formed_state_test.cpp @@ -88,10 +88,12 @@ HWTEST_F(GroupFormedStateTest, GoInState, TestSize.Level1) AddGroupManager(); pGroupFormedState->GoInState(); } + HWTEST_F(GroupFormedStateTest, GoOutState, TestSize.Level1) { pGroupFormedState->GoOutState(); } + HWTEST_F(GroupFormedStateTest, ExecuteStateMsg1, TestSize.Level1) { InternalMessage msg; @@ -105,6 +107,7 @@ HWTEST_F(GroupFormedStateTest, ExecuteStateMsg1, TestSize.Level1) .WillRepeatedly(Return(WifiErrorNo::WIFI_IDL_OPT_FAILED)); EXPECT_TRUE(pGroupFormedState->ExecuteStateMsg(&msg)); } + HWTEST_F(GroupFormedStateTest, ExecuteStateMsg1break, TestSize.Level1) { InternalMessage msg; @@ -114,6 +117,7 @@ HWTEST_F(GroupFormedStateTest, ExecuteStateMsg1break, TestSize.Level1) msg.SetMessageName(static_cast(P2P_STATE_MACHINE_CMD::AP_STA_CONNECTED)); EXPECT_TRUE(pGroupFormedState->ExecuteStateMsg(&msg)); } + HWTEST_F(GroupFormedStateTest, ExecuteStateMsg2, TestSize.Level1) { InternalMessage msg; @@ -124,6 +128,7 @@ HWTEST_F(GroupFormedStateTest, ExecuteStateMsg2, TestSize.Level1) msg.SetMessageName(static_cast(P2P_STATE_MACHINE_CMD::AP_STA_DISCONNECTED)); EXPECT_TRUE(pGroupFormedState->ExecuteStateMsg(&msg)); } + HWTEST_F(GroupFormedStateTest, ExecuteStateMsg2break, TestSize.Level1) { InternalMessage msg; @@ -134,6 +139,7 @@ HWTEST_F(GroupFormedStateTest, ExecuteStateMsg2break, TestSize.Level1) msg.SetMessageName(static_cast(P2P_STATE_MACHINE_CMD::AP_STA_DISCONNECTED)); EXPECT_TRUE(pGroupFormedState->ExecuteStateMsg(&msg)); } + HWTEST_F(GroupFormedStateTest, ExecuteStateMsg3, TestSize.Level1) { InternalMessage msg; @@ -144,6 +150,7 @@ HWTEST_F(GroupFormedStateTest, ExecuteStateMsg3, TestSize.Level1) msg.SetMessageName(static_cast(P2P_STATE_MACHINE_CMD::P2P_EVENT_DEVICE_LOST)); EXPECT_TRUE(pGroupFormedState->ExecuteStateMsg(&msg)); } + HWTEST_F(GroupFormedStateTest, ExecuteStateMsg3break, TestSize.Level1) { InternalMessage msg; @@ -152,23 +159,26 @@ HWTEST_F(GroupFormedStateTest, ExecuteStateMsg3break, TestSize.Level1) msg.SetMessageName(static_cast(P2P_STATE_MACHINE_CMD::P2P_EVENT_DEVICE_LOST)); EXPECT_TRUE(pGroupFormedState->ExecuteStateMsg(&msg)); } + HWTEST_F(GroupFormedStateTest, ExecuteStateMsg4, TestSize.Level1) { InternalMessage msg; msg.SetMessageName(static_cast(P2P_STATE_MACHINE_CMD::CMD_P2P_DISABLE)); EXPECT_TRUE(pGroupFormedState->ExecuteStateMsg(&msg)); } -HWTEST_F(GroupFormedStateTest, ExecuteStateMsg5, TestSize.Level1) + +HWTEST_F(GroupFormedStateTest, ProcessCmdConnect1, TestSize.Level1) { - WifiP2pConfig config; + WifiP2pConfigInternal config; InternalMessage msg; msg.SetMessageObj(config); msg.SetMessageName(static_cast(P2P_STATE_MACHINE_CMD::CMD_CONNECT)); EXPECT_TRUE(pGroupFormedState->ExecuteStateMsg(&msg)); } -HWTEST_F(GroupFormedStateTest, ExecuteStateMsg6, TestSize.Level1) + +HWTEST_F(GroupFormedStateTest, ProcessCmdConnect2, TestSize.Level1) { - WifiP2pConfig config; + WifiP2pConfigInternal config; AddDeviceManager(); InternalMessage msg; config.SetDeviceAddress("AA:BB:CC:DD:EE:FF"); @@ -178,6 +188,43 @@ HWTEST_F(GroupFormedStateTest, ExecuteStateMsg6, TestSize.Level1) AddDeviceStateMachine(); EXPECT_TRUE(pGroupFormedState->ExecuteStateMsg(&msg)); } + +HWTEST_F(GroupFormedStateTest, ProcessCmdConnect3, TestSize.Level1) +{ + WifiP2pConfigInternal config; + InternalMessage msg; + msg.SetMessageObj(config); + msg.SetMessageName(static_cast(P2P_STATE_MACHINE_CMD::CMD_CONNECT)); + EXPECT_CALL(pMockP2pPendant->GetP2pStateMachine(), IsConfigUnusable(_)) + .WillOnce(Return(P2pConfigErrCode::MAC_EMPTY)); + EXPECT_CALL(pMockP2pPendant->GetP2pStateMachine(), BroadcastActionResult(_, _)).WillOnce(Return()); + EXPECT_TRUE(pGroupFormedState->ExecuteStateMsg(&msg)); +} + +HWTEST_F(GroupFormedStateTest, ProcessCmdConnect4, TestSize.Level1) +{ + WifiP2pConfigInternal config; + InternalMessage msg; + msg.SetMessageObj(config); + msg.SetMessageName(static_cast(P2P_STATE_MACHINE_CMD::CMD_CONNECT)); + EXPECT_CALL(pMockP2pPendant->GetP2pStateMachine(), IsConfigUnusable(_)) + .WillOnce(Return(P2pConfigErrCode::MAC_NOT_FOUND)); + EXPECT_CALL(pMockP2pPendant->GetP2pStateMachine(), BroadcastActionResult(_, _)).WillOnce(Return()); + EXPECT_TRUE(pGroupFormedState->ExecuteStateMsg(&msg)); +} + +HWTEST_F(GroupFormedStateTest, ProcessCmdConnect5, TestSize.Level1) +{ + WifiP2pConfigInternal config; + InternalMessage msg; + msg.SetMessageObj(config); + msg.SetMessageName(static_cast(P2P_STATE_MACHINE_CMD::CMD_CONNECT)); + EXPECT_CALL(pMockP2pPendant->GetP2pStateMachine(), IsConfigUnusable(_)) + .WillOnce(Return(P2pConfigErrCode::ERR_MAC_FORMAT)); + EXPECT_CALL(pMockP2pPendant->GetP2pStateMachine(), BroadcastActionResult(_, _)).WillOnce(Return()); + EXPECT_TRUE(pGroupFormedState->ExecuteStateMsg(&msg)); +} + HWTEST_F(GroupFormedStateTest, ExecuteStateMsg7, TestSize.Level1) { WifiP2pTempDiscEvent procDisc; @@ -189,6 +236,7 @@ HWTEST_F(GroupFormedStateTest, ExecuteStateMsg7, TestSize.Level1) msg.SetMessageName(static_cast(P2P_STATE_MACHINE_CMD::P2P_EVENT_PROV_DISC_PBC_REQ)); EXPECT_TRUE(pGroupFormedState->ExecuteStateMsg(&msg)); } + HWTEST_F(GroupFormedStateTest, ExecuteStateMsg8, TestSize.Level1) { WifiP2pTempDiscEvent procDisc; @@ -200,6 +248,7 @@ HWTEST_F(GroupFormedStateTest, ExecuteStateMsg8, TestSize.Level1) msg.SetMessageName(static_cast(P2P_STATE_MACHINE_CMD::P2P_EVENT_PROV_DISC_ENTER_PIN)); EXPECT_TRUE(pGroupFormedState->ExecuteStateMsg(&msg)); } + HWTEST_F(GroupFormedStateTest, ExecuteStateMsg9, TestSize.Level1) { WifiP2pTempDiscEvent procDisc; @@ -213,6 +262,7 @@ HWTEST_F(GroupFormedStateTest, ExecuteStateMsg9, TestSize.Level1) AddGroupManager(); EXPECT_TRUE(pGroupFormedState->ExecuteStateMsg(&msg)); } + HWTEST_F(GroupFormedStateTest, ExecuteStateMsg9break, TestSize.Level1) { InternalMessage msg; @@ -221,12 +271,14 @@ HWTEST_F(GroupFormedStateTest, ExecuteStateMsg9break, TestSize.Level1) msg.SetMessageName(static_cast(P2P_STATE_MACHINE_CMD::P2P_EVENT_PROV_DISC_SHOW_PIN)); EXPECT_TRUE(pGroupFormedState->ExecuteStateMsg(&msg)); } + HWTEST_F(GroupFormedStateTest, ExecuteStateMsg10, TestSize.Level1) { InternalMessage msg; msg.SetMessageName(static_cast(P2P_STATE_MACHINE_CMD::P2P_EVENT_GROUP_STARTED)); EXPECT_TRUE(pGroupFormedState->ExecuteStateMsg(&msg)); } + HWTEST_F(GroupFormedStateTest, ExecuteStateMsg11, TestSize.Level1) { InternalMessage msg; @@ -235,18 +287,21 @@ HWTEST_F(GroupFormedStateTest, ExecuteStateMsg11, TestSize.Level1) msg.SetMessageName(static_cast(P2P_STATE_MACHINE_CMD::CMD_DEVICE_DISCOVERS)); EXPECT_TRUE(pGroupFormedState->ExecuteStateMsg(&msg)); } + HWTEST_F(GroupFormedStateTest, ExecuteStateMsg12, TestSize.Level1) { InternalMessage msg; msg.SetMessageName(static_cast(P2P_STATE_MACHINE_CMD::P2P_EVENT_GROUP_REMOVED)); EXPECT_TRUE(pGroupFormedState->ExecuteStateMsg(&msg)); } + HWTEST_F(GroupFormedStateTest, ProcessCmdRemoveGroup1, TestSize.Level1) { InternalMessage msg; msg.SetMessageName(static_cast(P2P_STATE_MACHINE_CMD::CMD_REMOVE_GROUP)); EXPECT_TRUE(pGroupFormedState->ExecuteStateMsg(&msg)); } + HWTEST_F(GroupFormedStateTest, ProcessCmdRemoveGroup2, TestSize.Level1) { InternalMessage msg; @@ -256,5 +311,13 @@ HWTEST_F(GroupFormedStateTest, ProcessCmdRemoveGroup2, TestSize.Level1) EXPECT_FALSE(pGroupFormedState->ExecuteStateMsg(&msg)); EXPECT_FALSE(pGroupFormedState->ExecuteStateMsg(nullptr)); } + +HWTEST_F(GroupFormedStateTest, ProcessCmdCancelConnect, TestSize.Level1) +{ + InternalMessage msg; + EXPECT_CALL(pMockP2pPendant->GetP2pStateMachine(), BroadcastActionResult(_, _)).WillOnce(Return()); + msg.SetMessageName(static_cast(P2P_STATE_MACHINE_CMD::CMD_CANCEL_CONNECT)); + EXPECT_TRUE(pGroupFormedState->ExecuteStateMsg(&msg)); +} } // namespace Wifi } // namespace OHOS \ No newline at end of file diff --git a/tests/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/test/group_negotiation_state_test.cpp b/wifi/test/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/test/group_negotiation_state_test.cpp similarity index 80% rename from tests/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/test/group_negotiation_state_test.cpp rename to wifi/test/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/test/group_negotiation_state_test.cpp index 31a5ac84432198fd49e03781bb352f4a1478cba9..9e21ef0bc7fddf0402b9701398cfd59019b39e98 100644 --- a/tests/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/test/group_negotiation_state_test.cpp +++ b/wifi/test/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/test/group_negotiation_state_test.cpp @@ -90,7 +90,7 @@ HWTEST_F(GroupNegotiationStateTest, ExecuteStateMsg1, TestSize.Level1) EXPECT_TRUE(pGroupNegotiationState->ExecuteStateMsg(&msg)); } -HWTEST_F(GroupNegotiationStateTest, ExecuteStateMsg2, TestSize.Level1) +HWTEST_F(GroupNegotiationStateTest, ProcessGroupStartedEvt1, TestSize.Level1) { InternalMessage msg; WifiP2pGroupInfo group; @@ -101,18 +101,18 @@ HWTEST_F(GroupNegotiationStateTest, ExecuteStateMsg2, TestSize.Level1) EXPECT_TRUE(pGroupNegotiationState->ExecuteStateMsg(&msg)); } -HWTEST_F(GroupNegotiationStateTest, ExecuteStateMsg3, TestSize.Level1) +HWTEST_F(GroupNegotiationStateTest, ProcessGroupStartedEvt2, TestSize.Level1) { InternalMessage msg; WifiP2pGroupInfo group; WifiP2pDevice device; - group.SetIsGroupOwner(false); + group.SetIsGroupOwner(true); group.SetIsPersistent(true); device.SetDeviceName("device"); device.SetDeviceAddress("AA:BB:CC:DD:EE:FF"); group.SetOwner(device); msg.SetMessageObj(group); - EXPECT_CALL(WifiP2PHalInterface::GetInstance(), ListNetworks(_)).WillOnce(Return(WifiErrorNo::WIFI_IDL_OPT_FAILED)); + EXPECT_CALL(pMockP2pPendant->GetP2pStateMachine(), UpdatePersistentGroups()).WillOnce(Return()); EXPECT_CALL(WifiP2PHalInterface::GetInstance(), SetP2pGroupIdle(_, _)) .WillOnce(Return(WifiErrorNo::WIFI_IDL_OPT_FAILED)); AddDeviceManager(); @@ -120,7 +120,7 @@ HWTEST_F(GroupNegotiationStateTest, ExecuteStateMsg3, TestSize.Level1) EXPECT_TRUE(pGroupNegotiationState->ExecuteStateMsg(&msg)); } -HWTEST_F(GroupNegotiationStateTest, ExecuteStateMsg4, TestSize.Level1) +HWTEST_F(GroupNegotiationStateTest, ProcessGroupStartedEvt3, TestSize.Level1) { InternalMessage msg; WifiP2pGroupInfo group; @@ -129,7 +129,7 @@ HWTEST_F(GroupNegotiationStateTest, ExecuteStateMsg4, TestSize.Level1) msg.SetMessageObj(group); EXPECT_CALL(WifiP2PHalInterface::GetInstance(), SetP2pGroupIdle(_, _)) .WillOnce(Return(WifiErrorNo::WIFI_IDL_OPT_FAILED)); - EXPECT_CALL(WifiP2PHalInterface::GetInstance(), ListNetworks(_)).WillOnce(Return(WifiErrorNo::WIFI_IDL_OPT_FAILED)); + EXPECT_CALL(pMockP2pPendant->GetP2pStateMachine(), UpdatePersistentGroups()).WillOnce(Return()); AddDeviceManager(); msg.SetMessageName(static_cast(P2P_STATE_MACHINE_CMD::P2P_EVENT_GROUP_STARTED)); EXPECT_TRUE(pGroupNegotiationState->ExecuteStateMsg(&msg)); @@ -142,7 +142,7 @@ HWTEST_F(GroupNegotiationStateTest, ExecuteStateMsg5, TestSize.Level1) EXPECT_TRUE(pGroupNegotiationState->ExecuteStateMsg(&msg)); } -HWTEST_F(GroupNegotiationStateTest, ExecuteStateMsg6, TestSize.Level1) +HWTEST_F(GroupNegotiationStateTest, ProcessInvitationResultEvt1, TestSize.Level1) { InternalMessage msg; msg.SetParam1(1); @@ -150,7 +150,7 @@ HWTEST_F(GroupNegotiationStateTest, ExecuteStateMsg6, TestSize.Level1) EXPECT_TRUE(pGroupNegotiationState->ExecuteStateMsg(&msg)); } -HWTEST_F(GroupNegotiationStateTest, ExecuteStateMsg7, TestSize.Level1) +HWTEST_F(GroupNegotiationStateTest, ProcessInvitationResultEvt2, TestSize.Level1) { InternalMessage msg; msg.SetParam1(0); @@ -158,7 +158,7 @@ HWTEST_F(GroupNegotiationStateTest, ExecuteStateMsg7, TestSize.Level1) EXPECT_TRUE(pGroupNegotiationState->ExecuteStateMsg(&msg)); } -HWTEST_F(GroupNegotiationStateTest, ExecuteStateMsg8, TestSize.Level1) +HWTEST_F(GroupNegotiationStateTest, ProcessInvitationResultEvt3, TestSize.Level1) { InternalMessage msg; msg.SetParam1(8); @@ -166,7 +166,7 @@ HWTEST_F(GroupNegotiationStateTest, ExecuteStateMsg8, TestSize.Level1) EXPECT_TRUE(pGroupNegotiationState->ExecuteStateMsg(&msg)); } -HWTEST_F(GroupNegotiationStateTest, ExecuteStateMsg9, TestSize.Level1) +HWTEST_F(GroupNegotiationStateTest, ProcessInvitationResultEvt4, TestSize.Level1) { InternalMessage msg; msg.SetParam1(1); @@ -174,7 +174,7 @@ HWTEST_F(GroupNegotiationStateTest, ExecuteStateMsg9, TestSize.Level1) EXPECT_TRUE(pGroupNegotiationState->ExecuteStateMsg(&msg)); } -HWTEST_F(GroupNegotiationStateTest, ExecuteStateMsg10, TestSize.Level1) +HWTEST_F(GroupNegotiationStateTest, ProcessInvitationResultEvt5, TestSize.Level1) { InternalMessage msg; msg.SetParam1(7); @@ -182,6 +182,15 @@ HWTEST_F(GroupNegotiationStateTest, ExecuteStateMsg10, TestSize.Level1) EXPECT_TRUE(pGroupNegotiationState->ExecuteStateMsg(&msg)); } +HWTEST_F(GroupNegotiationStateTest, ProcessInvitationResultEvt6, TestSize.Level1) +{ + InternalMessage msg; + msg.SetParam1(3); + msg.SetMessageName(static_cast(P2P_STATE_MACHINE_CMD::P2P_EVENT_INVITATION_RESULT)); + EXPECT_CALL(pMockP2pPendant->GetP2pStateMachine(), DealGroupCreationFailed()).WillOnce(Return()); + EXPECT_TRUE(pGroupNegotiationState->ExecuteStateMsg(&msg)); +} + HWTEST_F(GroupNegotiationStateTest, ProcessNegotSucessEvt, TestSize.Level1) { InternalMessage msg; @@ -202,5 +211,13 @@ HWTEST_F(GroupNegotiationStateTest, ProcessGroupFormationFailEvt, TestSize.Level msg.SetMessageName(static_cast(P2P_STATE_MACHINE_CMD::P2P_EVENT_PROV_DISC_PBC_REQ)); EXPECT_FALSE(pGroupNegotiationState->ExecuteStateMsg(&msg)); } + +HWTEST_F(GroupNegotiationStateTest, ProcessGroupRemovedEvt, TestSize.Level1) +{ + InternalMessage msg; + msg.SetMessageName(static_cast(P2P_STATE_MACHINE_CMD::P2P_EVENT_GROUP_REMOVED)); + EXPECT_CALL(pMockP2pPendant->GetP2pStateMachine(), DealGroupCreationFailed()).WillOnce(Return()); + EXPECT_TRUE(pGroupNegotiationState->ExecuteStateMsg(&msg)); +} } // namespace Wifi } // namespace OHOS diff --git a/tests/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/test/invitation_recelved_state_test.cpp b/wifi/test/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/test/invitation_recelved_state_test.cpp similarity index 100% rename from tests/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/test/invitation_recelved_state_test.cpp rename to wifi/test/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/test/invitation_recelved_state_test.cpp diff --git a/tests/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/test/invitation_request_state_test.cpp b/wifi/test/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/test/invitation_request_state_test.cpp similarity index 72% rename from tests/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/test/invitation_request_state_test.cpp rename to wifi/test/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/test/invitation_request_state_test.cpp index 5d82a02e7f3ed35c88f59dc10a53ab6a6a861129..6eb214e00142d903698c9da37be5612010b20895 100644 --- a/tests/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/test/invitation_request_state_test.cpp +++ b/wifi/test/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/test/invitation_request_state_test.cpp @@ -71,16 +71,43 @@ HWTEST_F(InvitationRequestStateTest, GoOutState, TestSize.Level1) pInvitationRequestState->GoOutState(); } -HWTEST_F(InvitationRequestStateTest, ExecuteStateMsg1, TestSize.Level1) +HWTEST_F(InvitationRequestStateTest, ProcessInvitationResultEvt1, TestSize.Level1) { InternalMessage msg; msg.SetParam1(0); msg.SetMessageName(static_cast(P2P_STATE_MACHINE_CMD::P2P_EVENT_INVITATION_RESULT)); EXPECT_TRUE(pInvitationRequestState->ExecuteStateMsg(&msg)); +} +HWTEST_F(InvitationRequestStateTest, ProcessInvitationResultEvt2, TestSize.Level1) +{ + InternalMessage msg; + msg.SetMessageName(static_cast(P2P_STATE_MACHINE_CMD::P2P_EVENT_INVITATION_RESULT)); msg.SetParam1(8); EXPECT_TRUE(pInvitationRequestState->ExecuteStateMsg(&msg)); +} +HWTEST_F(InvitationRequestStateTest, ProcessInvitationResultEvt3, TestSize.Level1) +{ + WifiP2pGroupInfo group; + group.SetNetworkId(0); + groupManager.SetCurrentGroup(group); + InternalMessage msg; + msg.SetMessageName(static_cast(P2P_STATE_MACHINE_CMD::P2P_EVENT_INVITATION_RESULT)); + msg.SetParam1(8); + EXPECT_TRUE(pInvitationRequestState->ExecuteStateMsg(&msg)); +} + +HWTEST_F(InvitationRequestStateTest, ProcessCmdP2pDisable, TestSize.Level1) +{ + InternalMessage msg; + msg.SetMessageName(static_cast(P2P_STATE_MACHINE_CMD::CMD_P2P_DISABLE)); + EXPECT_TRUE(pInvitationRequestState->ExecuteStateMsg(&msg)); +} + +HWTEST_F(InvitationRequestStateTest, ExecuteStateMsgFailed, TestSize.Level1) +{ + InternalMessage msg; msg.SetMessageName(static_cast(P2P_STATE_MACHINE_CMD::P2P_EVENT_GROUP_FORMATION_SUCCESS)); EXPECT_FALSE(pInvitationRequestState->ExecuteStateMsg(&msg)); } diff --git a/tests/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/test/mock_p2p_pendant.h b/wifi/test/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/test/mock_p2p_pendant.h similarity index 100% rename from tests/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/test/mock_p2p_pendant.h rename to wifi/test/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/test/mock_p2p_pendant.h diff --git a/tests/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/test/p2p_default_state_test.cpp b/wifi/test/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/test/p2p_default_state_test.cpp similarity index 95% rename from tests/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/test/p2p_default_state_test.cpp rename to wifi/test/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/test/p2p_default_state_test.cpp index 3a38e4ba9f1d7a91b6a40158b0ca14a2b4349c7a..df7994968249a09527c58e83caf6dfe8dc2f047b 100644 --- a/tests/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/test/p2p_default_state_test.cpp +++ b/wifi/test/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/test/p2p_default_state_test.cpp @@ -66,14 +66,14 @@ HWTEST_F(P2pDefaultStateTest, ExecuteStateMsg1, TestSize.Level1) std::string deviceAddress; msg.SetMessageObj(deviceAddress); msg.SetMessageName(static_cast(P2P_STATE_MACHINE_CMD::REMOVE_SERVICE_REQUEST_RECORD)); - pDefaultState->ExecuteStateMsg(&msg); + EXPECT_TRUE(pDefaultState->ExecuteStateMsg(&msg)); } HWTEST_F(P2pDefaultStateTest, ExecuteStateMsg2, TestSize.Level1) { InternalMessage msg; msg.SetMessageName(static_cast(P2P_STATE_MACHINE_CMD::CREATE_GROUP_TIMED_OUT)); - pDefaultState->ExecuteStateMsg(&msg); + EXPECT_FALSE(pDefaultState->ExecuteStateMsg(&msg)); } } // namespace Wifi } // namespace OHOS \ No newline at end of file diff --git a/tests/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/test/p2p_disabled_state_test.cpp b/wifi/test/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/test/p2p_disabled_state_test.cpp similarity index 77% rename from tests/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/test/p2p_disabled_state_test.cpp rename to wifi/test/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/test/p2p_disabled_state_test.cpp index 0df0d35a037921fb893e9104f290f3dbfd8ddf98..aee880f54f7335d2efb2b3ef6ccb8ca6aed76e9c 100644 --- a/tests/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/test/p2p_disabled_state_test.cpp +++ b/wifi/test/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/test/p2p_disabled_state_test.cpp @@ -67,7 +67,7 @@ HWTEST_F(P2pDisabledStateTest, GoOutState, TestSize.Level1) pP2pDisabledState->GoOutState(); } -HWTEST_F(P2pDisabledStateTest, ExecuteStateMsg, TestSize.Level1) +HWTEST_F(P2pDisabledStateTest, ProcessCmdP2pEnable1, TestSize.Level1) { InternalMessage msg; EXPECT_CALL(*pMockMonitor, RegisterIfaceHandler(_, _)).WillOnce(Return()); @@ -76,9 +76,24 @@ HWTEST_F(P2pDisabledStateTest, ExecuteStateMsg, TestSize.Level1) EXPECT_CALL(WifiP2PHalInterface::GetInstance(), SetRandomMacAddr(_)).WillOnce(Return(WifiErrorNo::WIFI_IDL_OPT_OK)); msg.SetMessageName(static_cast(P2P_STATE_MACHINE_CMD::CMD_P2P_ENABLE)); - pP2pDisabledState->ExecuteStateMsg(&msg); + EXPECT_TRUE(pP2pDisabledState->ExecuteStateMsg(&msg)); +} + +HWTEST_F(P2pDisabledStateTest, ProcessCmdP2pEnable2, TestSize.Level1) +{ + InternalMessage msg; + EXPECT_CALL(*pMockMonitor, RegisterIfaceHandler(_, _)).WillOnce(Return()); + EXPECT_CALL(*pMockMonitor, MonitorBegins(_)).WillOnce(Return()); + EXPECT_CALL(WifiP2PHalInterface::GetInstance(), StartP2p()).WillOnce(Return(WifiErrorNo::WIFI_IDL_OPT_FAILED)); + msg.SetMessageName(static_cast(P2P_STATE_MACHINE_CMD::CMD_P2P_ENABLE)); + EXPECT_TRUE(pP2pDisabledState->ExecuteStateMsg(&msg)); +} + +HWTEST_F(P2pDisabledStateTest, ExecuteStateMsgFailed, TestSize.Level1) +{ + InternalMessage msg; msg.SetMessageName(static_cast(P2P_STATE_MACHINE_CMD::CMD_P2P_DISABLE)); - pP2pDisabledState->ExecuteStateMsg(&msg); + EXPECT_FALSE(pP2pDisabledState->ExecuteStateMsg(&msg)); } } // namespace Wifi } // namespace OHOS \ No newline at end of file diff --git a/tests/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/test/p2p_disabling_state_test.cpp b/wifi/test/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/test/p2p_disabling_state_test.cpp similarity index 82% rename from tests/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/test/p2p_disabling_state_test.cpp rename to wifi/test/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/test/p2p_disabling_state_test.cpp index d4ab353e3b6ab26d91f5e12908fddeec0f6d3bba..8e9999bc62524a1f210370147342f2efbe7e2e84 100644 --- a/tests/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/test/p2p_disabling_state_test.cpp +++ b/wifi/test/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/test/p2p_disabling_state_test.cpp @@ -72,7 +72,6 @@ HWTEST_F(P2pDisablingStateTest, ExecuteStateMsg, TestSize.Level1) msg.SetMessageName(static_cast(P2P_STATE_MACHINE_CMD::CMD_P2P_DISABLE)); pP2pDisablingState->ExecuteStateMsg(&msg); - msg.SetMessageName(static_cast(P2P_STATE_MACHINE_CMD::WPA_CONNECTED_EVENT)); } HWTEST_F(P2pDisablingStateTest, ExecuteStateMsg2, TestSize.Level1) @@ -81,7 +80,18 @@ HWTEST_F(P2pDisablingStateTest, ExecuteStateMsg2, TestSize.Level1) msg.SetMessageName(static_cast(P2P_STATE_MACHINE_CMD::WPA_CONNECTED_EVENT)); msg.SetParam1(0); EXPECT_CALL(pMockP2pPendant->GetMockP2pMonitor(), MonitorEnds(_)).WillOnce(Return()); + EXPECT_CALL(pMockP2pPendant->GetP2pStateMachine(), BroadcastP2pStatusChanged(_)).WillOnce(Return()); pP2pDisablingState->ExecuteStateMsg(&msg); } + +HWTEST_F(P2pDisablingStateTest, ProcessDisableP2pTimedOut, TestSize.Level1) +{ + InternalMessage msg; + msg.SetMessageName(static_cast(P2P_STATE_MACHINE_CMD::DISABLE_P2P_TIMED_OUT)); + msg.SetParam1(0); + EXPECT_CALL(pMockP2pPendant->GetMockP2pMonitor(), MonitorEnds(_)).WillOnce(Return()); + EXPECT_CALL(pMockP2pPendant->GetP2pStateMachine(), BroadcastP2pStatusChanged(_)).WillOnce(Return()); + EXPECT_TRUE(pP2pDisablingState->ExecuteStateMsg(&msg)); +} } // namespace Wifi } // namespace OHOS \ No newline at end of file diff --git a/tests/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/test/p2p_enabled_state_test.cpp b/wifi/test/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/test/p2p_enabled_state_test.cpp similarity index 77% rename from tests/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/test/p2p_enabled_state_test.cpp rename to wifi/test/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/test/p2p_enabled_state_test.cpp index 5ddc83242db247174f2c3b882d55e725f22a5a44..99639dc602f823834206e688eb906662971704fb 100644 --- a/tests/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/test/p2p_enabled_state_test.cpp +++ b/wifi/test/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/test/p2p_enabled_state_test.cpp @@ -64,6 +64,7 @@ public: std::unique_ptr pMockP2pPendant; WifiP2pGroupManager groupManager; WifiP2pDeviceManager deviceManager; + WifiP2pServiceManager serviceManager; }; HWTEST_F(P2pEnabledStateTest, GoInState, TestSize.Level1) @@ -74,9 +75,8 @@ HWTEST_F(P2pEnabledStateTest, GoInState, TestSize.Level1) EXPECT_CALL(WifiP2PHalInterface::GetInstance(), SetP2pSsidPostfix(_)) .WillOnce(Return(WifiErrorNo::WIFI_IDL_OPT_FAILED)) .WillOnce(Return(WifiErrorNo::WIFI_IDL_OPT_OK)); - EXPECT_CALL(WifiP2PHalInterface::GetInstance(), SetP2pDeviceType(_)) - .WillOnce(Return(WifiErrorNo::WIFI_IDL_OPT_FAILED)) - .WillOnce(Return(WifiErrorNo::WIFI_IDL_OPT_OK)); + ON_CALL(WifiP2PHalInterface::GetInstance(), SetP2pDeviceType(_)) + .WillByDefault(Return(WifiErrorNo::WIFI_IDL_OPT_OK)); EXPECT_CALL(WifiP2PHalInterface::GetInstance(), SetP2pConfigMethods(_)) .WillOnce(Return(WifiErrorNo::WIFI_IDL_OPT_FAILED)) .WillOnce(Return(WifiErrorNo::WIFI_IDL_OPT_OK)); @@ -93,16 +93,13 @@ HWTEST_F(P2pEnabledStateTest, GoInState, TestSize.Level1) .WillOnce(Return(WifiErrorNo::WIFI_IDL_OPT_FAILED)) .WillOnce(Return(WifiErrorNo::WIFI_IDL_OPT_OK)); EXPECT_CALL(WifiP2PHalInterface::GetInstance(), ListNetworks(_)) - .WillOnce(Return(WifiErrorNo::WIFI_IDL_OPT_FAILED)) - .WillOnce(Return(WifiErrorNo::WIFI_IDL_OPT_FAILED)) .WillOnce(Return(WifiErrorNo::WIFI_IDL_OPT_FAILED)) .WillOnce(Return(WifiErrorNo::WIFI_IDL_OPT_FAILED)); EXPECT_CALL(WifiP2PHalInterface::GetInstance(), SetPersistentReconnect(Eq(1))) .WillOnce(Return(WifiErrorNo::WIFI_IDL_OPT_FAILED)) .WillOnce(Return(WifiErrorNo::WIFI_IDL_OPT_OK)); - EXPECT_CALL(WifiP2PHalInterface::GetInstance(), RemoveNetwork(Eq(-1))) - .WillOnce(Return(WifiErrorNo::WIFI_IDL_OPT_FAILED)) - .WillOnce(Return(WifiErrorNo::WIFI_IDL_OPT_OK)); + EXPECT_CALL(pMockP2pPendant->GetP2pStateMachine(), UpdateGroupInfoToWpa()).WillOnce(Return()).WillOnce(Return()); + EXPECT_CALL(pMockP2pPendant->GetP2pStateMachine(), UpdatePersistentGroups()).WillOnce(Return()).WillOnce(Return()); pP2pEnabledState->GoInState(); pP2pEnabledState->GoInState(); } @@ -181,7 +178,7 @@ HWTEST_F(P2pEnabledStateTest, ExecuteStateMsg5, TestSize.Level1) pP2pEnabledState->ExecuteStateMsg(&msg); } -HWTEST_F(P2pEnabledStateTest, ExecuteStateMsg6, TestSize.Level1) +HWTEST_F(P2pEnabledStateTest, ProcessDeviceFoundEvt1, TestSize.Level1) { InternalMessage msg; WifiP2pDevice device; @@ -190,6 +187,17 @@ HWTEST_F(P2pEnabledStateTest, ExecuteStateMsg6, TestSize.Level1) pP2pEnabledState->ExecuteStateMsg(&msg); } +HWTEST_F(P2pEnabledStateTest, ProcessDeviceFoundEvt2, TestSize.Level1) +{ + InternalMessage msg; + WifiP2pDevice device; + device.SetDeviceAddress(std::string("aa:bb:cc:dd:ee:22")); + msg.SetMessageName(static_cast(P2P_STATE_MACHINE_CMD::P2P_EVENT_DEVICE_FOUND)); + msg.SetMessageObj(device); + EXPECT_CALL(pMockP2pPendant->GetP2pStateMachine(), BroadcastP2pPeersChanged()).WillOnce(Return()); + pP2pEnabledState->ExecuteStateMsg(&msg); +} + HWTEST_F(P2pEnabledStateTest, ExecuteStateMsg7, TestSize.Level1) { InternalMessage msg; @@ -218,6 +226,7 @@ HWTEST_F(P2pEnabledStateTest, ExecuteStateMsg9, TestSize.Level1) pP2pEnabledState->ExecuteStateMsg(&msg); } + HWTEST_F(P2pEnabledStateTest, ExecuteStateMsg10, TestSize.Level1) { InternalMessage msg; @@ -230,6 +239,7 @@ HWTEST_F(P2pEnabledStateTest, ExecuteStateMsg10, TestSize.Level1) pP2pEnabledState->ExecuteStateMsg(&msg); pP2pEnabledState->ExecuteStateMsg(&msg); } + HWTEST_F(P2pEnabledStateTest, ExecuteStateMsg11, TestSize.Level1) { InternalMessage msg; @@ -242,6 +252,7 @@ HWTEST_F(P2pEnabledStateTest, ExecuteStateMsg11, TestSize.Level1) pP2pEnabledState->ExecuteStateMsg(&msg); pP2pEnabledState->ExecuteStateMsg(&msg); } + HWTEST_F(P2pEnabledStateTest, ExecuteStateMsg12, TestSize.Level1) { InternalMessage msg; @@ -252,6 +263,7 @@ HWTEST_F(P2pEnabledStateTest, ExecuteStateMsg12, TestSize.Level1) pP2pEnabledState->ExecuteStateMsg(&msg); pP2pEnabledState->ExecuteStateMsg(&msg); } + HWTEST_F(P2pEnabledStateTest, ExecuteStateMsg13, TestSize.Level1) { InternalMessage msg; @@ -269,32 +281,45 @@ HWTEST_F(P2pEnabledStateTest, ExecuteStateMsg13, TestSize.Level1) pP2pEnabledState->ExecuteStateMsg(&msg); pP2pEnabledState->ExecuteStateMsg(&msg); } + HWTEST_F(P2pEnabledStateTest, ExecuteStateMsg14, TestSize.Level1) { InternalMessage msg; msg.SetMessageName(static_cast(P2P_STATE_MACHINE_CMD::P2P_EVENT_SERV_DISC_REQ)); WifiP2pServiceRequestList reqList; + const WifiP2pServiceRequest req; + reqList.AddServiceRequest(req); WifiP2pDevice device; device.SetDeviceAddress("AA:BB:CC:DD:EE:FF"); reqList.SetDevice(device); msg.SetMessageObj(reqList); + EXPECT_CALL(WifiP2PHalInterface::GetInstance(), RespServiceDiscovery(_, _, _, _)) + .WillOnce(Return(WifiErrorNo::WIFI_IDL_OPT_FAILED)); + pP2pEnabledState->ExecuteStateMsg(&msg); pP2pEnabledState->ExecuteStateMsg(&msg); } + HWTEST_F(P2pEnabledStateTest, ExecuteStateMsg15, TestSize.Level1) { InternalMessage msg; msg.SetMessageName(static_cast(P2P_STATE_MACHINE_CMD::P2P_EVENT_SERV_DISC_RESP)); WifiP2pServiceResponseList respList; + std::vector data; + WifiP2pServiceResponse resp( + P2pServicerProtocolType::SERVICE_TYPE_BONJOUR, P2pServiceStatus::PSRS_SERVICE_PROTOCOL_NOT_AVAILABLE, 0, data); + respList.AddServiceResponse(resp); msg.SetMessageObj(respList); pP2pEnabledState->ExecuteStateMsg(&msg); } + HWTEST_F(P2pEnabledStateTest, ExecuteStateMsg16, TestSize.Level1) { InternalMessage msg; msg.SetMessageName(static_cast(P2P_STATE_MACHINE_CMD::P2P_EVENT_PROV_DISC_FAILURE)); pP2pEnabledState->ExecuteStateMsg(&msg); } + HWTEST_F(P2pEnabledStateTest, ExecuteStateMsg17, TestSize.Level1) { InternalMessage msg; @@ -303,6 +328,7 @@ HWTEST_F(P2pEnabledStateTest, ExecuteStateMsg17, TestSize.Level1) msg.SetMessageName(static_cast(P2P_STATE_MACHINE_CMD::CMD_PUT_LOCAL_SERVICE)); pP2pEnabledState->ExecuteStateMsg(&msg); } + HWTEST_F(P2pEnabledStateTest, ExecuteStateMsg18, TestSize.Level1) { InternalMessage msg; @@ -334,6 +360,7 @@ HWTEST_F(P2pEnabledStateTest, ExecuteStateMsg19, TestSize.Level1) pP2pEnabledState->ExecuteStateMsg(&msg); pP2pEnabledState->ExecuteStateMsg(&msg); } + HWTEST_F(P2pEnabledStateTest, ExecuteStateMsg20, TestSize.Level1) { InternalMessage msg; @@ -351,6 +378,7 @@ HWTEST_F(P2pEnabledStateTest, ExecuteStateMsg20, TestSize.Level1) pP2pEnabledState->ExecuteStateMsg(&msg); pP2pEnabledState->ExecuteStateMsg(&msg); } + HWTEST_F(P2pEnabledStateTest, ExecuteStateMsg21, TestSize.Level1) { InternalMessage msg; @@ -359,6 +387,7 @@ HWTEST_F(P2pEnabledStateTest, ExecuteStateMsg21, TestSize.Level1) msg.SetMessageName(static_cast(P2P_STATE_MACHINE_CMD::P2P_EVENT_SERV_DISC_REQ)); pP2pEnabledState->ExecuteStateMsg(&msg); } + HWTEST_F(P2pEnabledStateTest, ExecuteStateMsg22, TestSize.Level1) { InternalMessage msg; @@ -370,11 +399,82 @@ HWTEST_F(P2pEnabledStateTest, ExecuteStateMsg22, TestSize.Level1) msg.SetMessageName(static_cast(P2P_STATE_MACHINE_CMD::P2P_EVENT_PROV_DISC_FAILURE)); pP2pEnabledState->ExecuteStateMsg(&msg); } + HWTEST_F(P2pEnabledStateTest, ExecuteStateMsg23, TestSize.Level1) { InternalMessage msg; msg.SetMessageName(static_cast(P2P_STATE_MACHINE_CMD::EXCEPTION_TIMED_OUT)); pP2pEnabledState->ExecuteStateMsg(&msg); } -} // namespace Wifi -} // namespace OHOS \ No newline at end of file + +HWTEST_F(P2pEnabledStateTest, ProcessCmdSetDeviceName1, TestSize.Level1) +{ + InternalMessage msg; + std::string devAddr; + msg.SetMessageObj(devAddr); + msg.SetMessageName(static_cast(P2P_STATE_MACHINE_CMD::CMD_SET_DEVICE_NAME)); + EXPECT_CALL(WifiP2PHalInterface::GetInstance(), SetP2pDeviceName(Eq(devAddr))) + .WillOnce(Return(WifiErrorNo::WIFI_IDL_OPT_FAILED)); + EXPECT_CALL(pMockP2pPendant->GetP2pStateMachine(), BroadcastActionResult(_, _)).WillOnce(Return()); + EXPECT_TRUE(pP2pEnabledState->ExecuteStateMsg(&msg)); +} + +HWTEST_F(P2pEnabledStateTest, ProcessCmdSetDeviceName2, TestSize.Level1) +{ + InternalMessage msg; + std::string devAddr; + msg.SetMessageObj(devAddr); + msg.SetMessageName(static_cast(P2P_STATE_MACHINE_CMD::CMD_SET_DEVICE_NAME)); + EXPECT_CALL(WifiP2PHalInterface::GetInstance(), SetP2pDeviceName(Eq(devAddr))) + .WillOnce(Return(WifiErrorNo::WIFI_IDL_OPT_OK)); + EXPECT_CALL(pMockP2pPendant->GetP2pStateMachine(), BroadcastThisDeviceChanaged(_)).WillOnce(Return()); + EXPECT_CALL(pMockP2pPendant->GetP2pStateMachine(), BroadcastActionResult(_, _)).WillOnce(Return()); + EXPECT_CALL(WifiP2PHalInterface::GetInstance(), SetP2pSsidPostfix(_)) + .WillOnce(Return(WifiErrorNo::WIFI_IDL_OPT_FAILED)); + EXPECT_TRUE(pP2pEnabledState->ExecuteStateMsg(&msg)); +} + +HWTEST_F(P2pEnabledStateTest, ProcessCmdSetWfdInfo1, TestSize.Level1) +{ + InternalMessage msg; + WifiP2pWfdInfo wfdInfo; + msg.SetMessageObj(wfdInfo); + msg.SetMessageName(static_cast(P2P_STATE_MACHINE_CMD::CMD_SET_WFD_INFO)); + EXPECT_CALL(WifiP2PHalInterface::GetInstance(), SetWfdDeviceConfig(_)) + .WillOnce(Return(WifiErrorNo::WIFI_IDL_OPT_FAILED)); + EXPECT_TRUE(pP2pEnabledState->ExecuteStateMsg(&msg)); +} + +HWTEST_F(P2pEnabledStateTest, ProcessCmdSetWfdInfo2, TestSize.Level1) +{ + InternalMessage msg; + WifiP2pWfdInfo wfdInfo; + msg.SetMessageObj(wfdInfo); + msg.SetMessageName(static_cast(P2P_STATE_MACHINE_CMD::CMD_SET_WFD_INFO)); + EXPECT_CALL(WifiP2PHalInterface::GetInstance(), SetWfdDeviceConfig(_)) + .WillOnce(Return(WifiErrorNo::WIFI_IDL_OPT_OK)); + EXPECT_CALL(WifiP2PHalInterface::GetInstance(), SetWfdEnable(_)).WillOnce(Return(WifiErrorNo::WIFI_IDL_OPT_FAILED)); + EXPECT_TRUE(pP2pEnabledState->ExecuteStateMsg(&msg)); +} + +HWTEST_F(P2pEnabledStateTest, ProcessCmdSetWfdInfo3, TestSize.Level1) +{ + InternalMessage msg; + WifiP2pWfdInfo wfdInfo; + msg.SetMessageObj(wfdInfo); + msg.SetMessageName(static_cast(P2P_STATE_MACHINE_CMD::CMD_SET_WFD_INFO)); + EXPECT_CALL(WifiP2PHalInterface::GetInstance(), SetWfdDeviceConfig(_)) + .WillOnce(Return(WifiErrorNo::WIFI_IDL_OPT_OK)); + EXPECT_CALL(WifiP2PHalInterface::GetInstance(), SetWfdEnable(_)).WillOnce(Return(WifiErrorNo::WIFI_IDL_OPT_OK)); + EXPECT_TRUE(pP2pEnabledState->ExecuteStateMsg(&msg)); +} + +HWTEST_F(P2pEnabledStateTest, ProcessCmdCancelConnect, TestSize.Level1) +{ + InternalMessage msg; + msg.SetMessageName(static_cast(P2P_STATE_MACHINE_CMD::CMD_CANCEL_CONNECT)); + EXPECT_CALL(pMockP2pPendant->GetP2pStateMachine(), BroadcastActionResult(_, _)).WillOnce(Return()); + EXPECT_TRUE(pP2pEnabledState->ExecuteStateMsg(&msg)); +} +} // namespace Wifi +} // namespace OHOS \ No newline at end of file diff --git a/tests/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/test/p2p_enabling_state_test.cpp b/wifi/test/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/test/p2p_enabling_state_test.cpp similarity index 100% rename from tests/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/test/p2p_enabling_state_test.cpp rename to wifi/test/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/test/p2p_enabling_state_test.cpp diff --git a/tests/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/test/p2p_group_formation_state_test.cpp b/wifi/test/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/test/p2p_group_formation_state_test.cpp similarity index 81% rename from tests/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/test/p2p_group_formation_state_test.cpp rename to wifi/test/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/test/p2p_group_formation_state_test.cpp index 674f817dcf98b8200e239f5a2d6c9b9760102147..b0f5e835f91f3a82b095c6d8c9bd93012bb92e6b 100644 --- a/tests/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/test/p2p_group_formation_state_test.cpp +++ b/wifi/test/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/test/p2p_group_formation_state_test.cpp @@ -66,12 +66,18 @@ HWTEST_F(P2pGroupFormationStateTest, GoOutState, TestSize.Level1) HWTEST_F(P2pGroupFormationStateTest, ExecuteStateMsg, TestSize.Level1) { InternalMessage msg; + EXPECT_CALL(pMockP2pPendant->GetP2pStateMachine(), BroadcastActionResult(_, _)).WillOnce(Return()); msg.SetMessageName(static_cast(P2P_STATE_MACHINE_CMD::CMD_DEVICE_DISCOVERS)); pP2pGroupFormationState->ExecuteStateMsg(&msg); msg.SetMessageName(static_cast(P2P_STATE_MACHINE_CMD::P2P_EVENT_DEVICE_LOST)); pP2pGroupFormationState->ExecuteStateMsg(&msg); msg.SetMessageName(static_cast(P2P_STATE_MACHINE_CMD::P2P_EVENT_INVITATION_RECEIVED)); pP2pGroupFormationState->ExecuteStateMsg(&msg); + EXPECT_CALL(WifiP2PHalInterface::GetInstance(), CancelConnect()).WillOnce(Return(WifiErrorNo::WIFI_IDL_OPT_OK)); + EXPECT_CALL(pMockP2pPendant->GetP2pStateMachine(), DealGroupCreationFailed()).WillOnce(Return()); + EXPECT_CALL(pMockP2pPendant->GetP2pStateMachine(), BroadcastActionResult(_, _)).WillOnce(Return()); + msg.SetMessageName(static_cast(P2P_STATE_MACHINE_CMD::CMD_CANCEL_CONNECT)); + pP2pGroupFormationState->ExecuteStateMsg(&msg); } } // namespace Wifi } // namespace OHOS \ No newline at end of file diff --git a/tests/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/test/p2p_group_join_state_test.cpp b/wifi/test/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/test/p2p_group_join_state_test.cpp similarity index 94% rename from tests/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/test/p2p_group_join_state_test.cpp rename to wifi/test/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/test/p2p_group_join_state_test.cpp index af65684bb5e22a058901e64b214a88e08d55defd..6bd2100570c3a6a4e23a102dff2121facedae1a5 100644 --- a/tests/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/test/p2p_group_join_state_test.cpp +++ b/wifi/test/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/test/p2p_group_join_state_test.cpp @@ -116,5 +116,12 @@ HWTEST_F(P2pGroupJoinStateTest, ExecuteStateMsg, TestSize.Level1) msg.SetMessageName(static_cast(P2P_STATE_MACHINE_CMD::PEER_CONNECTION_USER_REJECT)); pP2pGroupJoinState->ExecuteStateMsg(&msg); } + +HWTEST_F(P2pGroupJoinStateTest, ProcessCmdP2pDisable, TestSize.Level1) +{ + InternalMessage msg; + msg.SetMessageName(static_cast(P2P_STATE_MACHINE_CMD::CMD_P2P_DISABLE)); + pP2pGroupJoinState->ExecuteStateMsg(&msg); +} } // namespace Wifi } // namespace OHOS \ No newline at end of file diff --git a/tests/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/test/p2p_group_operating_state_test.cpp b/wifi/test/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/test/p2p_group_operating_state_test.cpp similarity index 69% rename from tests/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/test/p2p_group_operating_state_test.cpp rename to wifi/test/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/test/p2p_group_operating_state_test.cpp index c593cef8ef8cef014da6aba0ee6cb7a9407e176e..2b3bca5aa2dfc91d477491f5d38497865051f455 100644 --- a/tests/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/test/p2p_group_operating_state_test.cpp +++ b/wifi/test/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/test/p2p_group_operating_state_test.cpp @@ -58,6 +58,13 @@ public: pP2pGroupOperatingState->groupManager.AddGroup(group); pP2pGroupOperatingState->groupManager.SetCurrentGroup(group); } + void AddDeviceManager() + { + pP2pGroupOperatingState->deviceManager.ClearAll(); + WifiP2pDevice device; + device.SetDeviceAddress(std::string("11:22:33:44:55:66")); + pP2pGroupOperatingState->deviceManager.AddDevice(device); + } std::unique_ptr pP2pGroupOperatingState; std::unique_ptr pMockP2pPendant; WifiP2pGroupManager groupManager; @@ -74,43 +81,63 @@ HWTEST_F(P2pGroupOperatingStateTest, GoOutState, TestSize.Level1) pP2pGroupOperatingState->GoOutState(); } -HWTEST_F(P2pGroupOperatingStateTest, ExecuteStateMsg1, TestSize.Level1) +HWTEST_F(P2pGroupOperatingStateTest, ProcessCmdCreateGroup1, TestSize.Level1) { InternalMessage msg; msg.SetMessageName(static_cast(P2P_STATE_MACHINE_CMD::CMD_FORM_GROUP)); - WifiP2pConfig config; + WifiP2pConfigInternal config; config.SetNetId(0); + config.SetPassphrase(std::string("12345679")); msg.SetMessageObj(config); - EXPECT_CALL(WifiP2PHalInterface::GetInstance(), GroupAdd(_, _, _)).WillOnce(Return(WifiErrorNo::WIFI_IDL_OPT_FAILED)); + EXPECT_CALL(pMockP2pPendant->GetP2pStateMachine(), SetGroupConfig(_, _)).WillOnce(Return(false)); + EXPECT_CALL(WifiP2PHalInterface::GetInstance(), GroupAdd(_, _, _)) + .WillOnce(Return(WifiErrorNo::WIFI_IDL_OPT_FAILED)); + EXPECT_CALL(pMockP2pPendant->GetP2pStateMachine(), BroadcastActionResult(_, _)).WillOnce(Return()); EXPECT_TRUE(pP2pGroupOperatingState->ExecuteStateMsg(&msg)); +} - config.SetNetId(-2); +HWTEST_F(P2pGroupOperatingStateTest, ProcessCmdCreateGroup2, TestSize.Level1) +{ + InternalMessage msg; + msg.SetMessageName(static_cast(P2P_STATE_MACHINE_CMD::CMD_FORM_GROUP)); + WifiP2pConfigInternal config; + config.SetNetId(-1); msg.SetMessageObj(config); - EXPECT_CALL(WifiP2PHalInterface::GetInstance(), GroupAdd(_, _, _)).WillOnce(Return(WifiErrorNo::WIFI_IDL_OPT_OK)); + EXPECT_CALL(WifiP2PHalInterface::GetInstance(), GroupAdd(_, _, _)) + .WillOnce(Return(WifiErrorNo::WIFI_IDL_OPT_OK)); + EXPECT_CALL(pMockP2pPendant->GetP2pStateMachine(), BroadcastActionResult(_, _)).WillOnce(Return()); EXPECT_TRUE(pP2pGroupOperatingState->ExecuteStateMsg(&msg)); +} +HWTEST_F(P2pGroupOperatingStateTest, ProcessCmdCreateGroup3, TestSize.Level1) +{ + InternalMessage msg; + msg.SetMessageName(static_cast(P2P_STATE_MACHINE_CMD::CMD_FORM_GROUP)); + WifiP2pConfigInternal config; config.SetNetId(-1); + config.SetPassphrase(std::string("12345679")); + config.SetGroupName(std::string("groupName")); msg.SetMessageObj(config); - EXPECT_CALL(WifiP2PHalInterface::GetInstance(), GroupAdd(_, _, _)).WillOnce(Return(WifiErrorNo::WIFI_IDL_OPT_OK)); + EXPECT_CALL(pMockP2pPendant->GetP2pStateMachine(), DealCreateNewGroupWithConfig(_, _)).WillOnce(Return(true)); + EXPECT_CALL(pMockP2pPendant->GetP2pStateMachine(), BroadcastActionResult(_, _)).WillOnce(Return()); EXPECT_TRUE(pP2pGroupOperatingState->ExecuteStateMsg(&msg)); +} - config.SetNetId(-5); +HWTEST_F(P2pGroupOperatingStateTest, ProcessCmdCreateGroup4, TestSize.Level1) +{ + InternalMessage msg; + msg.SetMessageName(static_cast(P2P_STATE_MACHINE_CMD::CMD_FORM_GROUP)); + WifiP2pConfigInternal config; + const int invalidId = -999; + config.SetNetId(invalidId); msg.SetMessageObj(config); + EXPECT_CALL(pMockP2pPendant->GetP2pStateMachine(), BroadcastActionResult(_, _)).WillOnce(Return()); EXPECT_TRUE(pP2pGroupOperatingState->ExecuteStateMsg(&msg)); } HWTEST_F(P2pGroupOperatingStateTest, ExecuteStateMsg2, TestSize.Level1) { InternalMessage msg; - msg.SetMessageName(static_cast(P2P_STATE_MACHINE_CMD::P2P_EVENT_GROUP_STARTED)); - WifiP2pGroupInfo group; - group.SetIsPersistent(true); - msg.SetMessageObj(group); - EXPECT_CALL(WifiP2PHalInterface::GetInstance(), ListNetworks(_)).WillOnce(Return(WifiErrorNo::WIFI_IDL_OPT_FAILED)); - EXPECT_TRUE(pP2pGroupOperatingState->ExecuteStateMsg(&msg)); - group.SetIsPersistent(false); - msg.SetMessageObj(group); - EXPECT_TRUE(pP2pGroupOperatingState->ExecuteStateMsg(&msg)); msg.SetMessageName(static_cast(P2P_STATE_MACHINE_CMD::CREATE_GROUP_TIMED_OUT)); EXPECT_TRUE(pP2pGroupOperatingState->ExecuteStateMsg(&msg)); @@ -119,6 +146,33 @@ HWTEST_F(P2pGroupOperatingStateTest, ExecuteStateMsg2, TestSize.Level1) EXPECT_TRUE(pP2pGroupOperatingState->ExecuteStateMsg(&msg)); } +HWTEST_F(P2pGroupOperatingStateTest, ProcessGroupStartedEvt1, TestSize.Level1) +{ + InternalMessage msg; + msg.SetMessageName(static_cast(P2P_STATE_MACHINE_CMD::P2P_EVENT_GROUP_STARTED)); + WifiP2pGroupInfo groupInfo; + groupInfo.SetIsPersistent(true); + groupInfo.SetIsGroupOwner(true); + msg.SetMessageObj(groupInfo); + EXPECT_CALL(pMockP2pPendant->GetP2pStateMachine(), UpdatePersistentGroups()).WillOnce(Return()); + EXPECT_TRUE(pP2pGroupOperatingState->ExecuteStateMsg(&msg)); +} + +HWTEST_F(P2pGroupOperatingStateTest, ProcessGroupStartedEvt2, TestSize.Level1) +{ + InternalMessage msg; + msg.SetMessageName(static_cast(P2P_STATE_MACHINE_CMD::P2P_EVENT_GROUP_STARTED)); + WifiP2pGroupInfo groupInfo; + groupInfo.SetIsPersistent(false); + groupInfo.SetIsGroupOwner(false); + WifiP2pDevice device; + device.SetDeviceAddress(std::string("11:22:33:44:55:66")); + groupInfo.SetOwner(device); + msg.SetMessageObj(groupInfo); + AddDeviceManager(); + EXPECT_TRUE(pP2pGroupOperatingState->ExecuteStateMsg(&msg)); +} + HWTEST_F(P2pGroupOperatingStateTest, ExecuteStateMsg3, TestSize.Level1) { InternalMessage msg; @@ -140,7 +194,7 @@ HWTEST_F(P2pGroupOperatingStateTest, ExecuteStateMsg4, TestSize.Level1) msg.SetMessageName(static_cast(P2P_STATE_MACHINE_CMD::CMD_DELETE_GROUP)); AddGroupManager(); EXPECT_CALL(WifiP2PHalInterface::GetInstance(), RemoveNetwork(_)).WillOnce(Return(WifiErrorNo::WIFI_IDL_OPT_OK)); - EXPECT_CALL(WifiP2PHalInterface::GetInstance(), ListNetworks(_)).WillOnce(Return(WifiErrorNo::WIFI_IDL_OPT_FAILED)); + EXPECT_CALL(pMockP2pPendant->GetP2pStateMachine(), UpdatePersistentGroups()).WillOnce(Return()); EXPECT_CALL(WifiP2PHalInterface::GetInstance(), GroupRemove(_)).WillOnce(Return(WifiErrorNo::WIFI_IDL_OPT_FAILED)); WifiP2pGroupInfo group; group.SetNetworkId(1); diff --git a/tests/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/test/p2p_idle_state_test.cpp b/wifi/test/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/test/p2p_idle_state_test.cpp similarity index 57% rename from tests/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/test/p2p_idle_state_test.cpp rename to wifi/test/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/test/p2p_idle_state_test.cpp index 33e2b821c21ea4e4e02884aee72fec89580e78ef..3d0fbd4628e67598bbf4f9af95f357a5bcc40952 100644 --- a/tests/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/test/p2p_idle_state_test.cpp +++ b/wifi/test/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/test/p2p_idle_state_test.cpp @@ -137,11 +137,11 @@ HWTEST_F(P2pIdleStateTest, ExecuteStateMsg1, TestSize.Level1) EXPECT_TRUE(pP2pIdleState->ExecuteStateMsg(&msg)); } -HWTEST_F(P2pIdleStateTest, ExecuteStateMsg2, TestSize.Level1) +HWTEST_F(P2pIdleStateTest, ProcessCmdConnect1, TestSize.Level1) { InternalMessage msg; msg.SetMessageName(static_cast(P2P_STATE_MACHINE_CMD::CMD_CONNECT)); - WifiP2pConfig config; + WifiP2pConfigInternal config; msg.SetMessageObj(config); EXPECT_TRUE(pP2pIdleState->ExecuteStateMsg(&msg)); @@ -153,16 +153,91 @@ HWTEST_F(P2pIdleStateTest, ExecuteStateMsg2, TestSize.Level1) EXPECT_TRUE(pP2pIdleState->ExecuteStateMsg(&msg)); } -HWTEST_F(P2pIdleStateTest, ExecuteStateMsg, TestSize.Level1) +HWTEST_F(P2pIdleStateTest, ProcessCmdConnect2, TestSize.Level1) { InternalMessage msg; msg.SetMessageName(static_cast(P2P_STATE_MACHINE_CMD::CMD_CONNECT)); - WifiP2pConfig config; + WifiP2pConfigInternal config; AddDeviceManager(); config.SetDeviceAddress("AA:BB:CC:DD:EE:FF"); msg.SetMessageObj(config); EXPECT_CALL(pMockP2pPendant->GetP2pStateMachine(), IsConfigUnusable(_)).WillOnce(Return(P2pConfigErrCode::SUCCESS)); EXPECT_CALL(WifiP2PHalInterface::GetInstance(), P2pStopFind()).WillOnce(Return(WifiErrorNo::WIFI_IDL_OPT_OK)); + EXPECT_CALL(pMockP2pPendant->GetP2pStateMachine(), ReawakenPersistentGroup(_)).WillOnce(Return(false)); + EXPECT_TRUE(pP2pIdleState->ExecuteStateMsg(&msg)); +} + +HWTEST_F(P2pIdleStateTest, ProcessCmdConnect3, TestSize.Level1) +{ + InternalMessage msg; + msg.SetMessageName(static_cast(P2P_STATE_MACHINE_CMD::CMD_CONNECT)); + WifiP2pConfigInternal config; + AddDeviceManager(); + config.SetDeviceAddress("AA:BB:CC:DD:EE:FF"); + msg.SetMessageObj(config); + EXPECT_CALL(pMockP2pPendant->GetP2pStateMachine(), IsConfigUnusable(_)).WillOnce(Return(P2pConfigErrCode::SUCCESS)); + EXPECT_CALL(WifiP2PHalInterface::GetInstance(), P2pStopFind()).WillOnce(Return(WifiErrorNo::WIFI_IDL_OPT_OK)); + EXPECT_CALL(pMockP2pPendant->GetP2pStateMachine(), ReawakenPersistentGroup(_)).WillOnce(Return(true)); + EXPECT_TRUE(pP2pIdleState->ExecuteStateMsg(&msg)); +} + +HWTEST_F(P2pIdleStateTest, ProcessCmdConnect4, TestSize.Level1) +{ + WifiP2pConfigInternal config; + InternalMessage msg; + msg.SetMessageObj(config); + msg.SetMessageName(static_cast(P2P_STATE_MACHINE_CMD::CMD_CONNECT)); + EXPECT_CALL(pMockP2pPendant->GetP2pStateMachine(), IsConfigUnusable(_)) + .WillOnce(Return(P2pConfigErrCode::MAC_EMPTY)); + EXPECT_CALL(pMockP2pPendant->GetP2pStateMachine(), BroadcastActionResult(_, _)).WillOnce(Return()); + EXPECT_TRUE(pP2pIdleState->ExecuteStateMsg(&msg)); +} + +HWTEST_F(P2pIdleStateTest, ProcessCmdConnect5, TestSize.Level1) +{ + WifiP2pConfigInternal config; + InternalMessage msg; + msg.SetMessageObj(config); + msg.SetMessageName(static_cast(P2P_STATE_MACHINE_CMD::CMD_CONNECT)); + EXPECT_CALL(pMockP2pPendant->GetP2pStateMachine(), IsConfigUnusable(_)) + .WillOnce(Return(P2pConfigErrCode::MAC_NOT_FOUND)); + EXPECT_CALL(pMockP2pPendant->GetP2pStateMachine(), BroadcastActionResult(_, _)).WillOnce(Return()); + EXPECT_TRUE(pP2pIdleState->ExecuteStateMsg(&msg)); +} + +HWTEST_F(P2pIdleStateTest, ProcessCmdConnect6, TestSize.Level1) +{ + WifiP2pConfigInternal config; + InternalMessage msg; + msg.SetMessageObj(config); + msg.SetMessageName(static_cast(P2P_STATE_MACHINE_CMD::CMD_CONNECT)); + EXPECT_CALL(pMockP2pPendant->GetP2pStateMachine(), IsConfigUnusable(_)) + .WillOnce(Return(P2pConfigErrCode::ERR_MAC_FORMAT)); + EXPECT_CALL(pMockP2pPendant->GetP2pStateMachine(), BroadcastActionResult(_, _)).WillOnce(Return()); + EXPECT_TRUE(pP2pIdleState->ExecuteStateMsg(&msg)); +} + +HWTEST_F(P2pIdleStateTest, ProcessCmdConnect7, TestSize.Level1) +{ + WifiP2pConfigInternal config; + InternalMessage msg; + msg.SetMessageObj(config); + msg.SetMessageName(static_cast(P2P_STATE_MACHINE_CMD::CMD_CONNECT)); + EXPECT_CALL(pMockP2pPendant->GetP2pStateMachine(), IsConfigUnusable(_)) + .WillOnce(Return(P2pConfigErrCode::ERR_INTENT)); + EXPECT_CALL(pMockP2pPendant->GetP2pStateMachine(), BroadcastActionResult(_, _)).WillOnce(Return()); + EXPECT_TRUE(pP2pIdleState->ExecuteStateMsg(&msg)); +} + +HWTEST_F(P2pIdleStateTest, ProcessCmdConnect8, TestSize.Level1) +{ + WifiP2pConfigInternal config; + InternalMessage msg; + msg.SetMessageObj(config); + msg.SetMessageName(static_cast(P2P_STATE_MACHINE_CMD::CMD_CONNECT)); + EXPECT_CALL(pMockP2pPendant->GetP2pStateMachine(), IsConfigUnusable(_)) + .WillOnce(Return(P2pConfigErrCode::ERR_SIZE_NW_NAME)); + EXPECT_CALL(pMockP2pPendant->GetP2pStateMachine(), BroadcastActionResult(_, _)).WillOnce(Return()); EXPECT_TRUE(pP2pIdleState->ExecuteStateMsg(&msg)); } @@ -178,30 +253,60 @@ HWTEST_F(P2pIdleStateTest, ExecuteStateMsg3, TestSize.Level1) EXPECT_TRUE(pP2pIdleState->ExecuteStateMsg(&msg)); } -HWTEST_F(P2pIdleStateTest, ExecuteStateMsg4, TestSize.Level1) +HWTEST_F(P2pIdleStateTest, ProcessInvitationReceivedEvt1, TestSize.Level1) { InternalMessage msg; - msg.SetMessageName(static_cast(P2P_STATE_MACHINE_CMD::CMD_DISCONNECT)); - EXPECT_FALSE(pP2pIdleState->ExecuteStateMsg(&msg)); - msg.SetMessageName(static_cast(P2P_STATE_MACHINE_CMD::P2P_EVENT_INVITATION_RECEIVED)); WifiP2pGroupInfo group; WifiP2pDevice device; - + group.SetOwner(device); group.SetNetworkId(-1); msg.SetMessageObj(group); EXPECT_TRUE(pP2pIdleState->ExecuteStateMsg(&msg)); +} +HWTEST_F(P2pIdleStateTest, ProcessInvitationReceivedEvt2, TestSize.Level1) +{ + InternalMessage msg; + msg.SetMessageName(static_cast(P2P_STATE_MACHINE_CMD::P2P_EVENT_INVITATION_RECEIVED)); + WifiP2pGroupInfo group; + WifiP2pDevice device; + group.SetOwner(device); group.SetNetworkId(1); msg.SetMessageObj(group); EXPECT_TRUE(pP2pIdleState->ExecuteStateMsg(&msg)); +} - AddGroupManager(); - device.SetDeviceAddress(""); +HWTEST_F(P2pIdleStateTest, ProcessInvitationReceivedEvt3, TestSize.Level1) +{ + InternalMessage msg; + msg.SetMessageName(static_cast(P2P_STATE_MACHINE_CMD::P2P_EVENT_INVITATION_RECEIVED)); + WifiP2pGroupInfo group; + WifiP2pDevice device; group.SetOwner(device); + group.SetNetworkId(1); msg.SetMessageObj(group); + AddGroupManager(); + msg.SetMessageObj(group); + EXPECT_CALL(WifiP2PHalInterface::GetInstance(), GetP2pPeer(_, _)) + .WillOnce(Return(WifiErrorNo::WIFI_IDL_OPT_FAILED)); EXPECT_TRUE(pP2pIdleState->ExecuteStateMsg(&msg)); +} +HWTEST_F(P2pIdleStateTest, ProcessInvitationReceivedEvt4, TestSize.Level1) +{ + InternalMessage msg; + msg.SetMessageName(static_cast(P2P_STATE_MACHINE_CMD::P2P_EVENT_INVITATION_RECEIVED)); + WifiP2pGroupInfo group; + WifiP2pDevice device; + device.SetDeviceAddress(std::string("AA:BB:CC:DD:EE:FF")); + group.SetOwner(device); + group.SetNetworkId(1); + msg.SetMessageObj(group); + AddGroupManager(); + msg.SetMessageObj(group); + EXPECT_CALL(WifiP2PHalInterface::GetInstance(), GetP2pPeer(_, _)) + .WillRepeatedly(Return(WifiErrorNo::WIFI_IDL_OPT_OK)); AddDeviceManager1(); EXPECT_TRUE(pP2pIdleState->ExecuteStateMsg(&msg)); @@ -216,20 +321,54 @@ HWTEST_F(P2pIdleStateTest, ExecuteStateMsg5, TestSize.Level1) { InternalMessage msg; msg.SetMessageName(static_cast(P2P_STATE_MACHINE_CMD::P2P_EVENT_GO_NEG_REQUEST)); - WifiP2pConfig conf; + WifiP2pConfigInternal conf; msg.SetMessageObj(conf); EXPECT_TRUE(pP2pIdleState->ExecuteStateMsg(&msg)); } -HWTEST_F(P2pIdleStateTest, ExecuteStateMsg6, TestSize.Level1) +HWTEST_F(P2pIdleStateTest, ProcessGroupStartedEvt1, TestSize.Level1) +{ + InternalMessage msg; + WifiP2pGroupInfo group; + group.SetIsPersistent(true); + group.SetIsGroupOwner(false); + msg.SetMessageObj(group); + msg.SetMessageName(static_cast(P2P_STATE_MACHINE_CMD::P2P_EVENT_GROUP_STARTED)); + EXPECT_CALL(pMockP2pPendant->GetP2pStateMachine(), UpdatePersistentGroups()).WillOnce(Return()); + EXPECT_TRUE(pP2pIdleState->ExecuteStateMsg(&msg)); +} + +HWTEST_F(P2pIdleStateTest, ProcessGroupStartedEvt2, TestSize.Level1) +{ + InternalMessage msg; + WifiP2pGroupInfo group; + group.SetIsPersistent(false); + group.SetIsGroupOwner(false); + WifiP2pDevice device; + device.SetDeviceAddress(std::string("AA:BB:CC:DD:EE:FF")); + group.SetOwner(device); + AddDeviceManager(); + msg.SetMessageObj(group); + msg.SetMessageName(static_cast(P2P_STATE_MACHINE_CMD::P2P_EVENT_GROUP_STARTED)); + EXPECT_TRUE(pP2pIdleState->ExecuteStateMsg(&msg)); +} + +HWTEST_F(P2pIdleStateTest, ProcessGroupStartedEvt3, TestSize.Level1) { InternalMessage msg; WifiP2pGroupInfo group; group.SetIsPersistent(true); + group.SetIsGroupOwner(true); msg.SetMessageObj(group); msg.SetMessageName(static_cast(P2P_STATE_MACHINE_CMD::P2P_EVENT_GROUP_STARTED)); - EXPECT_CALL(WifiP2PHalInterface::GetInstance(), ListNetworks(_)).WillOnce(Return(WifiErrorNo::WIFI_IDL_OPT_FAILED)); + EXPECT_CALL(pMockP2pPendant->GetP2pStateMachine(), UpdatePersistentGroups()).WillOnce(Return()); + EXPECT_CALL(pMockP2pPendant->GetP2pStateMachine(), StartDhcpServer()).WillOnce(Return(false)); EXPECT_TRUE(pP2pIdleState->ExecuteStateMsg(&msg)); +} + +HWTEST_F(P2pIdleStateTest, ExecuteStateMsgFailed, TestSize.Level1) +{ + InternalMessage msg; msg.SetMessageName(static_cast(P2P_STATE_MACHINE_CMD::P2P_EVENT_GROUP_REMOVED)); EXPECT_FALSE(pP2pIdleState->ExecuteStateMsg(&msg)); EXPECT_FALSE(pP2pIdleState->ExecuteStateMsg(nullptr)); @@ -255,5 +394,12 @@ HWTEST_F(P2pIdleStateTest, ProcessCmdCreateGroup, TestSize.Level1) msg.SetMessageName(static_cast(P2P_STATE_MACHINE_CMD::CMD_FORM_GROUP)); EXPECT_TRUE(pP2pIdleState->ExecuteStateMsg(&msg)); } + +HWTEST_F(P2pIdleStateTest, ProcessProvDiscPbcReqEvt, TestSize.Level1) +{ + InternalMessage msg; + msg.SetMessageName(static_cast(P2P_STATE_MACHINE_CMD::P2P_EVENT_PROV_DISC_PBC_REQ)); + EXPECT_TRUE(pP2pIdleState->ExecuteStateMsg(&msg)); +} } // namespace Wifi } // namespace OHOS \ No newline at end of file diff --git a/tests/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/test/p2p_inviting_state_test.cpp b/wifi/test/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/test/p2p_inviting_state_test.cpp similarity index 84% rename from tests/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/test/p2p_inviting_state_test.cpp rename to wifi/test/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/test/p2p_inviting_state_test.cpp index de6f13838b5f029f78f7a014eb88bee6dc816015..b574e9a170e5e961277858db3e56aff58e26cd41 100644 --- a/tests/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/test/p2p_inviting_state_test.cpp +++ b/wifi/test/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/test/p2p_inviting_state_test.cpp @@ -74,6 +74,12 @@ HWTEST_F(P2pInvitingStateTest, ExecuteStateMsg, TestSize.Level1) msg.SetMessageName(static_cast(P2P_STATE_MACHINE_CMD::P2P_EVENT_DEVICE_FOUND)); pP2pInvitingState->ExecuteStateMsg(&msg); + + msg.SetMessageName(static_cast(P2P_STATE_MACHINE_CMD::CMD_CANCEL_CONNECT)); + EXPECT_CALL(WifiP2PHalInterface::GetInstance(), CancelConnect()).WillOnce(Return(WifiErrorNo::WIFI_IDL_OPT_OK)); + EXPECT_CALL(pMockP2pPendant->GetP2pStateMachine(), DealGroupCreationFailed()).WillOnce(Return()); + EXPECT_CALL(pMockP2pPendant->GetP2pStateMachine(), BroadcastActionResult(_, _)).WillOnce(Return()); + pP2pInvitingState->ExecuteStateMsg(&msg); } } // namespace Wifi } // namespace OHOS \ No newline at end of file diff --git a/tests/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/test/p2p_monitor_test.cpp b/wifi/test/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/test/p2p_monitor_test.cpp similarity index 70% rename from tests/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/test/p2p_monitor_test.cpp rename to wifi/test/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/test/p2p_monitor_test.cpp index 20e4a4c34341a42d846edf6b113b904d941a625a..939aa7e66e48341bf9ab9b5c2a9d12a7e4b103b1 100644 --- a/tests/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/test/p2p_monitor_test.cpp +++ b/wifi/test/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/test/p2p_monitor_test.cpp @@ -56,7 +56,7 @@ public: } public: - void WrapMethodSendMessage( + void WrapMethodMessageToStateMachine( const std::string &iface, P2P_STATE_MACHINE_CMD msgName, int param1, int param2, const std::any &anyObj) const { pP2pMonitor->MessageToStateMachine(iface, msgName, param1, param2, anyObj); @@ -82,7 +82,7 @@ public: pP2pMonitor->Broadcast2SmDeviceLost(iface, device); } - void WrapMethodBroadcast2SmGoNegRequest(const std::string &iface, const WifiP2pConfig &config) const + void WrapMethodBroadcast2SmGoNegRequest(const std::string &iface, const WifiP2pConfigInternal &config) const { pP2pMonitor->Broadcast2SmGoNegRequest(iface, config); } @@ -185,107 +185,107 @@ public: pP2pMonitor->OnConnectSupplicant(status); } - void WrapMethodOnDeviceFound(IdlP2pDeviceFound deviceInfo) + void WrapMethodWpaEventDeviceFound(IdlP2pDeviceFound deviceInfo) { pP2pMonitor->WpaEventDeviceFound(deviceInfo); } - void WrapMethodOnDeviceLost(const std::string &p2pDeviceAddress) + void WrapMethodWpaEventDeviceLost(const std::string &p2pDeviceAddress) { pP2pMonitor->WpaEventDeviceLost(p2pDeviceAddress); } - void WrapMethodOnGoNegRequest(const std::string &srcAddress, short passwordId) + void WrapMethodWpaEventGoNegRequest(const std::string &srcAddress, short passwordId) { pP2pMonitor->WpaEventGoNegRequest(srcAddress, passwordId); } - void WrapMethodOnGoNegSuccess() + void WrapMethodWpaEventGoNegSuccess() { pP2pMonitor->WpaEventGoNegSuccess(); } - void WrapMethodOnGoNegFailure(int status) + void WrapMethodWpaEventGoNegFailure(int status) { pP2pMonitor->WpaEventGoNegFailure(status); } - void WrapMethodOnInvitationReceived(IdlP2pInvitationInfo recvInfo) + void WrapMethodWpaEventInvitationReceived(IdlP2pInvitationInfo recvInfo) { pP2pMonitor->WpaEventInvitationReceived(recvInfo); } - void WrapMethodOnInvitationResult(const std::string &bssid, int status) + void WrapMethodWpaEventInvitationResult(const std::string &bssid, int status) { pP2pMonitor->WpaEventInvitationResult(bssid, status); } - void WrapMethodOnGroupFormationSuccess() + void WrapMethodWpaEventGroupFormationSuccess() { pP2pMonitor->WpaEventGroupFormationSuccess(); } - void WrapMethodOnGroupFormationFailure(const std::string &failureReason) + void WrapMethodWpaEventGroupFormationFailure(const std::string &failureReason) { pP2pMonitor->WpaEventGroupFormationFailure(failureReason); } - void WrapMethodOnGroupStarted(IdlP2pGroupInfo groupInfo) + void WrapMethodWpaEventGroupStarted(IdlP2pGroupInfo groupInfo) { pP2pMonitor->WpaEventGroupStarted(groupInfo); } - void WrapMethodOnGroupRemoved(const std::string &groupIfName, bool isGo) + void WrapMethodWpaEventGroupRemoved(const std::string &groupIfName, bool isGo) { pP2pMonitor->WpaEventGroupRemoved(groupIfName, isGo); } - void WrapMethodOnProvDiscPbcReq(const std::string &p2pDeviceAddress) + void WrapMethodWpaEventProvDiscPbcReq(const std::string &p2pDeviceAddress) { pP2pMonitor->WpaEventProvDiscPbcReq(p2pDeviceAddress); } - void WrapMethodOnProvDiscPbcResp(const std::string &p2pDeviceAddress) + void WrapMethodWpaEventProvDiscPbcResp(const std::string &p2pDeviceAddress) { pP2pMonitor->WpaEventProvDiscPbcResp(p2pDeviceAddress); } - void WrapMethodOnProvDiscEnterPin(const std::string &p2pDeviceAddress) + void WrapMethodWpaEventProvDiscEnterPin(const std::string &p2pDeviceAddress) { pP2pMonitor->WpaEventProvDiscEnterPin(p2pDeviceAddress); } - void WrapMethodOnProvDiscShowPin(const std::string &p2pDeviceAddress, const std::string &generatedPin) + void WrapMethodWpaEventProvDiscShowPin(const std::string &p2pDeviceAddress, const std::string &generatedPin) { pP2pMonitor->WpaEventProvDiscShowPin(p2pDeviceAddress, generatedPin); } - void WrapMethodOnProvDiscFailure() + void WrapMethodWpaEventProvDiscFailure() { pP2pMonitor->WpaEventProvDiscFailure(); } - void WrapMethodOnFindStopped() + void WrapMethodWpaEventFindStopped() { pP2pMonitor->WpaEventFindStopped(); } - void WrapMethodOnServDiscReq(IdlP2pServDiscReqInfo reqInfo) + void WrapMethodWpaEventServDiscReq(IdlP2pServDiscReqInfo reqInfo) { pP2pMonitor->WpaEventServDiscReq(reqInfo); } - void WrapMethodOnServDiscResp( + void WrapMethodWpaEventServDiscResp( const std::string &srcAddress, short updateIndicator, const std::vector &tlvs) { pP2pMonitor->WpaEventServDiscResp(srcAddress, updateIndicator, tlvs); } - void WrapMethodOnApStaDisconnected(const std::string &p2pDeviceAddress) + void WrapMethodWpaEventApStaDisconnected(const std::string &p2pDeviceAddress) { pP2pMonitor->WpaEventApStaDisconnected(p2pDeviceAddress); } - void WrapMethodOnApStaConnected(const std::string &p2pDeviceAddress) + void WrapMethodWpaEventApStaConnected(const std::string &p2pDeviceAddress) { pP2pMonitor->WpaEventApStaConnected(p2pDeviceAddress); } @@ -328,7 +328,7 @@ HWTEST_F(P2pMonitorTest, WrapMethod_test, TestSize.Level1) constexpr int param1 = 0; constexpr int param2 = 1; const std::any anyObj = std::string("test_any"); - WrapMethodSendMessage(iface, msgName, param1, param2, anyObj); + WrapMethodMessageToStateMachine(iface, msgName, param1, param2, anyObj); } HWTEST_F(P2pMonitorTest, WrapMethod_data, TestSize.Level1) @@ -377,7 +377,7 @@ HWTEST_F(P2pMonitorTest, Broadcast2SmDeviceLost, TestSize.Level1) HWTEST_F(P2pMonitorTest, Broadcast2SmGoNegRequest, TestSize.Level1) { const std::string iface = g_pIface; - WifiP2pConfig testConfig; + WifiP2pConfigInternal testConfig; WrapMethodBroadcast2SmGoNegRequest(iface, testConfig); } @@ -511,12 +511,12 @@ HWTEST_F(P2pMonitorTest, OnConnectSupplicant, TestSize.Level1) WrapMethodOnConnectSupplicant(status); } -HWTEST_F(P2pMonitorTest, WpaEventDeviceFound, TestSize.Level1) +HWTEST_F(P2pMonitorTest, WpaEventDeviceFound1, TestSize.Level1) { IdlP2pDeviceFound deviceInfo; deviceInfo.srcAddress = "ff:ff:ff:ff:ff:ff"; deviceInfo.p2pDeviceAddress = "ff:ff:ff:ff:ff:ff"; - deviceInfo.primaryDeviceType = "1-111111-1"; + deviceInfo.primaryDeviceType = "1-11111111-1"; deviceInfo.deviceName = "P2pUnitTest"; deviceInfo.configMethods = 10; deviceInfo.deviceCapabilities = 8; @@ -529,32 +529,83 @@ HWTEST_F(P2pMonitorTest, WpaEventDeviceFound, TestSize.Level1) deviceInfo.wfdDeviceInfo.push_back('e'); deviceInfo.wfdDeviceInfo.push_back('8'); deviceInfo.wfdDeviceInfo.push_back('8'); - WrapMethodOnDeviceFound(deviceInfo); + WrapMethodWpaEventDeviceFound(deviceInfo); } -HWTEST_F(P2pMonitorTest, WpaEventDeviceLost, TestSize.Level1) +HWTEST_F(P2pMonitorTest, WpaEventDeviceFound2, TestSize.Level1) { - WrapMethodOnDeviceLost("ff:ff:ff:ff:ff:ff"); + IdlP2pDeviceFound deviceInfo; + deviceInfo.srcAddress = "ff:ff:ff:ff:ff:ff"; + deviceInfo.p2pDeviceAddress = "ff:ff:ff:ff:ff:ff"; + deviceInfo.primaryDeviceType = "1-11111111-1"; + deviceInfo.deviceName = ""; + deviceInfo.configMethods = 10; + deviceInfo.deviceCapabilities = 8; + deviceInfo.groupCapabilities = 12; + deviceInfo.wfdDeviceInfo.push_back('1'); + deviceInfo.wfdDeviceInfo.push_back('5'); + deviceInfo.wfdDeviceInfo.push_back('a'); + deviceInfo.wfdDeviceInfo.push_back('3'); + deviceInfo.wfdDeviceInfo.push_back('6'); + deviceInfo.wfdDeviceInfo.push_back('e'); + deviceInfo.wfdDeviceInfo.push_back('8'); + deviceInfo.wfdDeviceInfo.push_back('8'); + WrapMethodWpaEventDeviceFound(deviceInfo); +} + +HWTEST_F(P2pMonitorTest, WpaEventDeviceLost1, TestSize.Level1) +{ + std::string p2pDeviceAddress("ff:ff:ff:ff:ff:ff"); + WrapMethodWpaEventDeviceLost(p2pDeviceAddress); } -HWTEST_F(P2pMonitorTest, WpaEventGoNegRequest, TestSize.Level1) +HWTEST_F(P2pMonitorTest, WpaEventDeviceLost2, TestSize.Level1) +{ + std::string p2pDeviceAddress(""); + WrapMethodWpaEventDeviceLost(p2pDeviceAddress); +} +HWTEST_F(P2pMonitorTest, WpaEventGoNegRequest1, TestSize.Level1) { short testPasswordId = 8; - WrapMethodOnGoNegRequest("ff:ff:ff:ff:ff:ff", testPasswordId); + WrapMethodWpaEventGoNegRequest("ff:ff:ff:ff:ff:ff", testPasswordId); +} + +HWTEST_F(P2pMonitorTest, WpaEventGoNegRequest2, TestSize.Level1) +{ + short testPasswordId = 1; + WrapMethodWpaEventGoNegRequest("ff:ff:ff:ff:ff:ff", testPasswordId); +} + +HWTEST_F(P2pMonitorTest, WpaEventGoNegRequest3, TestSize.Level1) +{ + short testPasswordId = 4; + WrapMethodWpaEventGoNegRequest("ff:ff:ff:ff:ff:ff", testPasswordId); } +HWTEST_F(P2pMonitorTest, WpaEventGoNegRequest4, TestSize.Level1) +{ + short testPasswordId = 5; + WrapMethodWpaEventGoNegRequest("ff:ff:ff:ff:ff:ff", testPasswordId); +} + +HWTEST_F(P2pMonitorTest, WpaEventGoNegRequest5, TestSize.Level1) +{ + short testPasswordId = 8; + std::string srcAddress(""); + WrapMethodWpaEventGoNegRequest(srcAddress, testPasswordId); +} HWTEST_F(P2pMonitorTest, WpaEventGoNegSuccess, TestSize.Level1) { - WrapMethodOnGoNegSuccess(); + WrapMethodWpaEventGoNegSuccess(); } HWTEST_F(P2pMonitorTest, WpaEventGoNegFailure, TestSize.Level1) { int testStatus = 1; - WrapMethodOnGoNegFailure(testStatus); + WrapMethodWpaEventGoNegFailure(testStatus); } -HWTEST_F(P2pMonitorTest, WpaEventInvitationReceived, TestSize.Level1) +HWTEST_F(P2pMonitorTest, WpaEventInvitationReceived1, TestSize.Level1) { IdlP2pInvitationInfo testRecvInfo; testRecvInfo.persistentNetworkId = 1; @@ -562,26 +613,47 @@ HWTEST_F(P2pMonitorTest, WpaEventInvitationReceived, TestSize.Level1) testRecvInfo.srcAddress = "ff:ff:ff:ff:ff:ff"; testRecvInfo.goDeviceAddress = "ff:ff:ff:ff:ff:fe"; testRecvInfo.bssid = "ff:ff:ff:ff:ff:ef"; - WrapMethodOnInvitationReceived(testRecvInfo); + WrapMethodWpaEventInvitationReceived(testRecvInfo); +} + +HWTEST_F(P2pMonitorTest, WpaEventInvitationReceived2, TestSize.Level1) +{ + IdlP2pInvitationInfo testRecvInfo; + testRecvInfo.persistentNetworkId = 1; + testRecvInfo.operatingFrequency = 6; + testRecvInfo.srcAddress = ""; + testRecvInfo.goDeviceAddress = "ff:ff:ff:ff:ff:fe"; + testRecvInfo.bssid = "ff:ff:ff:ff:ff:ef"; + WrapMethodWpaEventInvitationReceived(testRecvInfo); +} + +HWTEST_F(P2pMonitorTest, WpaEventInvitationReceived3, TestSize.Level1) +{ + IdlP2pInvitationInfo testRecvInfo; + testRecvInfo.persistentNetworkId = 1; + testRecvInfo.operatingFrequency = 6; + testRecvInfo.srcAddress = "ff:ff:ff:ff:ff:ff"; + testRecvInfo.bssid = "ff:ff:ff:ff:ff:ef"; + WrapMethodWpaEventInvitationReceived(testRecvInfo); } HWTEST_F(P2pMonitorTest, WpaEventInvitationResult, TestSize.Level1) { int testStatus = 1; - WrapMethodOnInvitationResult("ff:ff:ff:ff:ff:ff", testStatus); + WrapMethodWpaEventInvitationResult("ff:ff:ff:ff:ff:ff", testStatus); } HWTEST_F(P2pMonitorTest, WpaEventGroupFormationSuccess, TestSize.Level1) { - WrapMethodOnGroupFormationSuccess(); + WrapMethodWpaEventGroupFormationSuccess(); } HWTEST_F(P2pMonitorTest, WpaEventGroupFormationFailure, TestSize.Level1) { - WrapMethodOnGroupFormationFailure("P2pUnitTestReason"); + WrapMethodWpaEventGroupFormationFailure("P2pUnitTestReason"); } -HWTEST_F(P2pMonitorTest, WpaEventGroupStarted, TestSize.Level1) +HWTEST_F(P2pMonitorTest, WpaEventGroupStarted1, TestSize.Level1) { IdlP2pGroupInfo testGroupInfo; testGroupInfo.isGo = true; @@ -592,80 +664,116 @@ HWTEST_F(P2pMonitorTest, WpaEventGroupStarted, TestSize.Level1) testGroupInfo.psk = "123456789"; testGroupInfo.passphrase = "TestPassphrase"; testGroupInfo.goDeviceAddress = "ff:ff:ff:ff:ff:ff"; - WrapMethodOnGroupStarted(testGroupInfo); + WrapMethodWpaEventGroupStarted(testGroupInfo); +} + +HWTEST_F(P2pMonitorTest, WpaEventGroupStarted2, TestSize.Level1) +{ + IdlP2pGroupInfo testGroupInfo; + testGroupInfo.isGo = false; + testGroupInfo.isPersistent = true; + testGroupInfo.frequency = 6; + testGroupInfo.groupName = "P2pUnitTestWlan"; + testGroupInfo.ssid = "P2pUnitTestGroup"; + testGroupInfo.psk = "123456789"; + testGroupInfo.passphrase = "TestPassphrase"; + testGroupInfo.goDeviceAddress = "ff:ff:ff:ff:ff:ff"; + WrapMethodWpaEventGroupStarted(testGroupInfo); } -HWTEST_F(P2pMonitorTest, WpaEventGroupRemoved, TestSize.Level1) +HWTEST_F(P2pMonitorTest, WpaEventGroupStarted3, TestSize.Level1) +{ + IdlP2pGroupInfo testGroupInfo; + testGroupInfo.isGo = true; + testGroupInfo.isPersistent = true; + testGroupInfo.frequency = 6; + testGroupInfo.ssid = "P2pUnitTestGroup"; + testGroupInfo.psk = "123456789"; + testGroupInfo.passphrase = "TestPassphrase"; + testGroupInfo.goDeviceAddress = "ff:ff:ff:ff:ff:ff"; + WrapMethodWpaEventGroupStarted(testGroupInfo); +} + +HWTEST_F(P2pMonitorTest, WpaEventGroupRemoved1, TestSize.Level1) { bool isGo = true; - WrapMethodOnGroupRemoved("P2pUnitTestWlan", isGo); + WrapMethodWpaEventGroupRemoved("P2pUnitTestWlan", isGo); +} + +HWTEST_F(P2pMonitorTest, WpaEventGroupRemoved2, TestSize.Level1) +{ + bool isGo = true; + std::string groupIfName(""); + WrapMethodWpaEventGroupRemoved(groupIfName, isGo); } HWTEST_F(P2pMonitorTest, WpaEventProvDiscPbcReq, TestSize.Level1) { - WrapMethodOnProvDiscPbcReq("ff:ff:ff:ff:ff:ff"); + WrapMethodWpaEventProvDiscPbcReq("ff:ff:ff:ff:ff:ff"); } HWTEST_F(P2pMonitorTest, WpaEventProvDiscPbcResp, TestSize.Level1) { - WrapMethodOnProvDiscPbcResp("ff:ff:ff:ff:ff:ff"); + WrapMethodWpaEventProvDiscPbcResp("ff:ff:ff:ff:ff:ff"); } HWTEST_F(P2pMonitorTest, WpaEventProvDiscEnterPin, TestSize.Level1) { - WrapMethodOnProvDiscEnterPin("ff:ff:ff:ff:ff:ff"); + WrapMethodWpaEventProvDiscEnterPin("ff:ff:ff:ff:ff:ff"); } HWTEST_F(P2pMonitorTest, WpaEventProvDiscShowPin, TestSize.Level1) { - WrapMethodOnProvDiscShowPin("ff:ff:ff:ff:ff:ff", "TestGeneratedPin"); + WrapMethodWpaEventProvDiscShowPin("ff:ff:ff:ff:ff:ff", "TestGeneratedPin"); } HWTEST_F(P2pMonitorTest, WpaEventProvDiscFailure, TestSize.Level1) { - WrapMethodOnProvDiscFailure(); + WrapMethodWpaEventProvDiscFailure(); } HWTEST_F(P2pMonitorTest, WpaEventFindStopped, TestSize.Level1) { - WrapMethodOnFindStopped(); + WrapMethodWpaEventFindStopped(); } HWTEST_F(P2pMonitorTest, WpaEventServDiscReq, TestSize.Level1) { - EXPECT_CALL(WifiP2PHalInterface::GetInstance(), RegisterP2pCallback(_)); - const std::string iface = g_pIface; - pP2pMonitor->MonitorBegins(iface); IdlP2pServDiscReqInfo info; std::vector tList; + tList.push_back(0x02); + tList.push_back(0x00); + tList.push_back(0x01); + tList.push_back(0x00); info.tlvList = tList; - info.mac = "111"; - WrapMethodOnServDiscReq(info); + WrapMethodWpaEventServDiscReq(info); } HWTEST_F(P2pMonitorTest, WpaEventServDiscResp, TestSize.Level1) { - EXPECT_CALL(WifiP2PHalInterface::GetInstance(), RegisterP2pCallback(_)); - const std::string iface = g_pIface; - pP2pMonitor->MonitorBegins(iface); short testUpdateIndicator = 5; - const std::vector testTlvs; - WrapMethodOnServDiscResp("ff:ff:ff:ff:ff:ff", testUpdateIndicator, testTlvs); + std::vector testTlvs; + testTlvs.push_back(0x03); + testTlvs.push_back(0x00); + testTlvs.push_back(0x01); + testTlvs.push_back(0x00); + testTlvs.push_back(0x00); + WrapMethodWpaEventServDiscResp("ff:ff:ff:ff:ff:ff", testUpdateIndicator, testTlvs); } HWTEST_F(P2pMonitorTest, WpaEventApStaDisconnected, TestSize.Level1) { - WrapMethodOnApStaDisconnected("ff:ff:ff:ff:ff:ff"); + WrapMethodWpaEventApStaDisconnected("ff:ff:ff:ff:ff:ff"); } HWTEST_F(P2pMonitorTest, WpaEventApStaConnected, TestSize.Level1) { - WrapMethodOnApStaConnected("ff:ff:ff:ff:ff:ff"); + WrapMethodWpaEventApStaConnected("ff:ff:ff:ff:ff:ff"); } HWTEST_F(P2pMonitorTest, OnConnectSupplicantFailed, TestSize.Level1) { WrapMethodOnConnectSupplicantFailed(); } -} // namespace Wifi -} // namespace OHOS \ No newline at end of file +} // namespace Wifi +} // namespace OHOS \ No newline at end of file diff --git a/tests/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/test/p2p_state_machine_test.cpp b/wifi/test/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/test/p2p_state_machine_test.cpp similarity index 64% rename from tests/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/test/p2p_state_machine_test.cpp rename to wifi/test/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/test/p2p_state_machine_test.cpp index 8a927007cba9b177c23ed9f6db0ca74f1e12c96a..efa4b14fbdbeac2d1423abd3d83777b03baea1a6 100644 --- a/tests/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/test/p2p_state_machine_test.cpp +++ b/wifi/test/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/test/p2p_state_machine_test.cpp @@ -1,5 +1,5 @@ /* - * Copyright (C) 2021 Huawei Device Co., Ltd. + * Copyright (C) 2021-2022 Huawei Device Co., Ltd. * 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 @@ -105,7 +105,10 @@ public: { EXPECT_CALL(WifiP2PHalInterface::GetInstance(), RegisterP2pCallback(_)); pP2pStateMachine.reset(); - delete pMockP2pPendant; + if (pMockP2pPendant != nullptr) { + delete pMockP2pPendant; + pMockP2pPendant = nullptr; + } pMockAuthorizingNegotiationRequestState = nullptr; pMockGroupFormedState = nullptr; pMockGroupNegotiationState = nullptr; @@ -205,6 +208,16 @@ public: groupInfo.SetOwner(owner); pP2pStateMachine->groupManager.AddGroup(groupInfo); } + void AddGroupManager3() + { + WifiP2pGroupInfo groupInfo; + groupInfo.SetNetworkId(-1); + groupInfo.SetGroupName("AAA"); + groupInfo.SetIsGroupOwner(true); + WifiP2pDevice owner; + groupInfo.SetOwner(owner); + pP2pStateMachine->groupManager.AddGroup(groupInfo); + } void WarpHandlerDiscoverPeers() { pP2pStateMachine->HandlerDiscoverPeers(); @@ -223,7 +236,7 @@ public: pP2pStateMachine->UpdatePersistentGroups(); } - bool WarpReinvokePersistentGroup(WifiP2pConfig &config) const + bool WarpReinvokePersistentGroup(WifiP2pConfigInternal &config) const { return pP2pStateMachine->ReawakenPersistentGroup(config); } @@ -247,15 +260,15 @@ public: { pP2pStateMachine->InitializeThisDevice(); } - bool WarpIsUsableNetworkName(std::string nwName) + bool WarpIsUsableGroupName(std::string nwName) { - return pP2pStateMachine->IsUsableNetworkName(nwName); + return pP2pStateMachine->IsUsableGroupName(nwName); } - P2pConfigErrCode WarpIsConfigUnusable(const WifiP2pConfig &config) + P2pConfigErrCode WarpIsConfigUnusable(const WifiP2pConfigInternal &config) { return pP2pStateMachine->IsConfigUnusable(config); } - bool WarpIsConfigUsableAsGroup(WifiP2pConfig config) + bool WarpIsConfigUsableAsGroup(WifiP2pConfigInternal config) { return pP2pStateMachine->IsConfigUsableAsGroup(config); } @@ -305,7 +318,7 @@ public: { pP2pStateMachine->NotifyUserProvDiscShowPinRequestMessage(pin, peerAddress); } - void WarpP2pConnectWithPinDisplay(const WifiP2pConfig &config) const + void WarpP2pConnectWithPinDisplay(const WifiP2pConfigInternal &config) const { pP2pStateMachine->P2pConnectByShowingPin(config); } @@ -327,11 +340,46 @@ public: pP2pStateMachine->savedP2pConfig.SetWpsInfo(info); pP2pStateMachine->NotifyUserInvitationReceivedMessage(); } - void WarpClearWifiP2pInfo() { pP2pStateMachine->ClearWifiP2pInfo(); } + bool WarpStartDhcpServer() + { + return pP2pStateMachine->StartDhcpServer(); + } + void WarpDhcpResultNotifyOnSuccess(int status, const std::string &ifname, DhcpResult &result) + { + pP2pStateMachine->pDhcpResultNotify->OnSuccess(status, ifname, result); + } + void WarpDhcpResultNotifyOnFailed(int status, const std::string &ifname, const std::string &reason) + { + pP2pStateMachine->pDhcpResultNotify->OnFailed(status, ifname, reason); + } + void WarpDhcpResultNotifyOnSerExitNotify(const std::string& ifname) + { + pP2pStateMachine->pDhcpResultNotify->OnSerExitNotify(ifname); + } + int WarpGetAvailableFreqByBand(GroupOwnerBand band) const + { + return pP2pStateMachine->GetAvailableFreqByBand(band); + } + bool WarpSetGroupConfig(const WifiP2pConfigInternal &config, bool newGroup) const + { + return pP2pStateMachine->SetGroupConfig(config, newGroup); + } + bool WarpDealCreateNewGroupWithConfig(const WifiP2pConfigInternal &config, int freq) const + { + return pP2pStateMachine->DealCreateNewGroupWithConfig(config, freq); + } + void WarpUpdateGroupInfoToWpa() const + { + pP2pStateMachine->UpdateGroupInfoToWpa(); + } + void WarpHandleP2pServiceResp(const WifiP2pServiceResponse &resp, const WifiP2pDevice &dev) const + { + pP2pStateMachine->HandleP2pServiceResp(resp, dev); + } }; void ButtonTest(AlertDialog &dialog, std::any ctx) @@ -365,7 +413,7 @@ HWTEST_F(P2pStateMachineTest, RegisterEventHandler, TestSize.Level1) WarpRegisterEventHandler(); } -HWTEST_F(P2pStateMachineTest, UpdateOwnDevice, TestSize.Level1) +HWTEST_F(P2pStateMachineTest, UpdateThisDevice, TestSize.Level1) { WarpUpdateThisDevice(); } @@ -392,7 +440,7 @@ HWTEST_F(P2pStateMachineTest, UpdatePersistentGroups_FAILED, TestSize.Level1) HWTEST_F(P2pStateMachineTest, P2pConnectWithPinDisplay_SUCCESS, TestSize.Level1) { - WifiP2pConfig conf; + WifiP2pConfigInternal conf; WarpP2pConnectWithPinDisplay(conf); conf.SetDeviceAddress("AA:BB:CC:DD:EE:FF"); @@ -417,7 +465,7 @@ HWTEST_F(P2pStateMachineTest, RemoveGroupByNetworkId, TestSize.Level1) WarpRemoveGroupByNetworkId(1); } -HWTEST_F(P2pStateMachineTest, SetWifiP2pInfoWhenGroupFormed, TestSize.Level1) +HWTEST_F(P2pStateMachineTest, SetWifiP2pInfoOnGroupFormed, TestSize.Level1) { WarpSetWifiP2pInfoOnGroupFormed("AA:BB:CC:DD:EE:FF"); } @@ -440,40 +488,66 @@ HWTEST_F(P2pStateMachineTest, InitializeThisDevice2, TestSize.Level1) WarpInitializeThisDevice(); } -HWTEST_F(P2pStateMachineTest, IsUsableNetworkName, TestSize.Level1) +HWTEST_F(P2pStateMachineTest, IsUsableGroupName, TestSize.Level1) { - EXPECT_FALSE(WarpIsUsableNetworkName("")); - EXPECT_TRUE(WarpIsUsableNetworkName("12345678910")); - EXPECT_FALSE(WarpIsUsableNetworkName("1")); + EXPECT_FALSE(WarpIsUsableGroupName("")); + EXPECT_TRUE(WarpIsUsableGroupName("12345678910")); + EXPECT_FALSE(WarpIsUsableGroupName("1")); } -HWTEST_F(P2pStateMachineTest, IsConfigUnusable, TestSize.Level1) +HWTEST_F(P2pStateMachineTest, IsConfigUnusable1, TestSize.Level1) { - WifiP2pConfig config; + WifiP2pConfigInternal config; config.SetDeviceAddress(""); EXPECT_TRUE(WarpIsConfigUnusable(config) == P2pConfigErrCode::MAC_EMPTY); +} + +HWTEST_F(P2pStateMachineTest, IsConfigUnusable2, TestSize.Level1) +{ + WifiP2pConfigInternal config; AddDeviceManager(); config.SetDeviceAddress("AA:BB:CC:DD:EE:FF"); - EXPECT_FALSE(WarpIsConfigUnusable(config) == P2pConfigErrCode::SUCCESS); + config.SetGroupOwnerIntent(6); + EXPECT_TRUE(WarpIsConfigUnusable(config) == P2pConfigErrCode::SUCCESS); +} + +HWTEST_F(P2pStateMachineTest, IsConfigUnusable3, TestSize.Level1) +{ + WifiP2pConfigInternal config; + AddDeviceManager(); + config.SetDeviceAddress("AA:BB:CC:DD:EE:FF"); + config.SetGroupOwnerIntent(6); + config.SetGroupName(std::string("abcdefghijklnmopqrstuvwxyz1234567")); + EXPECT_TRUE(WarpIsConfigUnusable(config) == P2pConfigErrCode::ERR_SIZE_NW_NAME); +} + +HWTEST_F(P2pStateMachineTest, IsConfigUnusable4, TestSize.Level1) +{ + WifiP2pConfigInternal config; config.SetDeviceAddress("aa:cc:bb:dd:ee:ff"); EXPECT_TRUE(WarpIsConfigUnusable(config) == P2pConfigErrCode::MAC_NOT_FOUND); +} + +HWTEST_F(P2pStateMachineTest, IsConfigUnusable5, TestSize.Level1) +{ + WifiP2pConfigInternal config; config.SetDeviceAddress("aa:cc::bb:dd:ee:ff"); EXPECT_TRUE(WarpIsConfigUnusable(config) == P2pConfigErrCode::ERR_MAC_FORMAT); } HWTEST_F(P2pStateMachineTest, IsConfigUsableAsGroup, TestSize.Level1) { - WifiP2pConfig config; + WifiP2pConfigInternal config; config.SetDeviceAddress(""); EXPECT_FALSE(WarpIsConfigUsableAsGroup(config)); config.SetDeviceAddress("1"); EXPECT_FALSE(WarpIsConfigUsableAsGroup(config)); - config.SetNetworkName("12345678910"); + config.SetGroupName("12345678910"); config.SetPassphrase("12345678910"); EXPECT_TRUE(WarpIsConfigUsableAsGroup(config)); } -HWTEST_F(P2pStateMachineTest, CancelSupplicantSrvDiscReq, TestSize.Level1) +HWTEST_F(P2pStateMachineTest, CleanSupplicantServiceReq, TestSize.Level1) { WarpCleanSupplicantServiceReq(); Addsvr(); @@ -512,7 +586,7 @@ HWTEST_F(P2pStateMachineTest, BroadcastP2pServicesChanged, TestSize.Level1) HWTEST_F(P2pStateMachineTest, BroadcastP2pConnectionChanged, TestSize.Level1) { IP2pServiceCallbacks callback; - callback.OnP2pConnectionChangedEvent = [](const WifiP2pInfo &) { WIFI_LOGI("lamda"); }; + callback.OnP2pConnectionChangedEvent = [](const WifiP2pLinkedInfo &) { WIFI_LOGI("lamda"); }; pP2pStateMachine->RegisterP2pServiceCallbacks(callback); WarpBroadcastP2pConnectionChanged(); } @@ -557,7 +631,7 @@ HWTEST_F(P2pStateMachineTest, NotifyUserProvDiscShowPinRequestMessage, TestSize. WarpNotifyP2pProvDiscShowPinRequest(pin, peerAddress); } -HWTEST_F(P2pStateMachineTest, NotifyUserInvitationSentMessage, TestSize.Level1) +HWTEST_F(P2pStateMachineTest, NotifyInvitationSent, TestSize.Level1) { std::string pin; const std::string peerAddress; @@ -586,25 +660,24 @@ HWTEST_F(P2pStateMachineTest, ClearWifiP2pInfo, TestSize.Level1) HWTEST_F(P2pStateMachineTest, ReinvokePersistentGroup1, TestSize.Level1) { - WifiP2pConfig config; + WifiP2pConfigInternal config; EXPECT_FALSE(WarpReinvokePersistentGroup(config)); config.SetDeviceAddress("AA:BB:CC:DD:EE:FF"); - config.SetNetworkName("AAA"); + config.SetGroupName("AAA"); AddGroupManager(); AddDeviceManager(); EXPECT_CALL(WifiP2PHalInterface::GetInstance(), GroupAdd(_, _, _)) - .WillOnce(Return(WifiErrorNo::WIFI_IDL_OPT_OK)) - .WillOnce(Return(WifiErrorNo::WIFI_IDL_OPT_FAILED)); - EXPECT_TRUE(WarpReinvokePersistentGroup(config)); + .WillRepeatedly(Return(WifiErrorNo::WIFI_IDL_OPT_OK)); + EXPECT_FALSE(WarpReinvokePersistentGroup(config)); EXPECT_FALSE(WarpReinvokePersistentGroup(config)); } HWTEST_F(P2pStateMachineTest, ReinvokePersistentGroup2, TestSize.Level1) { - WifiP2pConfig config; + WifiP2pConfigInternal config; config.SetDeviceAddress("AA:BB:CC:DD:EE:FF"); - config.SetNetworkName("AAA"); + config.SetGroupName("AAA"); AddGroupManager(); AddDeviceManagerLimit(); EXPECT_FALSE(WarpReinvokePersistentGroup(config)); @@ -612,29 +685,218 @@ HWTEST_F(P2pStateMachineTest, ReinvokePersistentGroup2, TestSize.Level1) HWTEST_F(P2pStateMachineTest, ReinvokePersistentGroup3, TestSize.Level1) { - WifiP2pConfig config; + WifiP2pConfigInternal config; config.SetDeviceAddress("AA:BB:CC:DD:EE:FF"); - config.SetNetworkName("AAA"); + config.SetGroupName("AAA"); config.SetNetId(2); AddGroupManager(); AddDeviceManagerInViteable(); - EXPECT_CALL(WifiP2PHalInterface::GetInstance(), Reinvoke(_, _)) - .WillOnce(Return(WifiErrorNo::WIFI_IDL_OPT_OK)) - .WillOnce(Return(WifiErrorNo::WIFI_IDL_OPT_FAILED)); - EXPECT_CALL(WifiP2PHalInterface::GetInstance(), ListNetworks(_)).WillOnce(Return(WifiErrorNo::WIFI_IDL_OPT_FAILED)); - EXPECT_TRUE(WarpReinvokePersistentGroup(config)); + + ON_CALL(WifiP2PHalInterface::GetInstance(), Reinvoke(_, _)) + .WillByDefault(Return(WifiErrorNo::WIFI_IDL_OPT_OK)); + + ON_CALL(WifiP2PHalInterface::GetInstance(), ListNetworks(_)) + .WillByDefault(Return(WifiErrorNo::WIFI_IDL_OPT_OK)); + EXPECT_FALSE(WarpReinvokePersistentGroup(config)); EXPECT_FALSE(WarpReinvokePersistentGroup(config)); } HWTEST_F(P2pStateMachineTest, ReinvokePersistentGroup4, TestSize.Level1) { - WifiP2pConfig config; + WifiP2pConfigInternal config; config.SetDeviceAddress("AA:BB:CC:DD:EE:FF"); - config.SetNetworkName("AAA"); + config.SetGroupName("AAA"); config.SetNetId(3); AddGroupManager2(); AddDeviceManagerInViteable(); EXPECT_FALSE(WarpReinvokePersistentGroup(config)); } + +HWTEST_F(P2pStateMachineTest, StartDhcpServer, TestSize.Level1) +{ + WarpStartDhcpServer(); +} + +HWTEST_F(P2pStateMachineTest, DhcpResultNotifyOnSuccess, TestSize.Level1) +{ + int status = 1; + std::string ifName("ifName"); + DhcpResult result; + WarpDhcpResultNotifyOnSuccess(status, ifName, result); +} + +HWTEST_F(P2pStateMachineTest, DhcpResultNotifyOnFailed, TestSize.Level1) +{ + int status = 1; + std::string ifName("ifName"); + std::string reason("reason"); + EXPECT_CALL(WifiP2PHalInterface::GetInstance(), GroupRemove(_)).WillOnce(Return(WifiErrorNo::WIFI_IDL_OPT_OK)); + WarpDhcpResultNotifyOnFailed(status, ifName, reason); +} + +HWTEST_F(P2pStateMachineTest, DhcpResultNotifyOnSerExitNotify, TestSize.Level1) +{ + std::string ifName("ifName"); + WarpDhcpResultNotifyOnSerExitNotify(ifName); +} + +HWTEST_F(P2pStateMachineTest, GetAvailableFreqByBand1, TestSize.Level1) +{ + GroupOwnerBand band = GroupOwnerBand::GO_BAND_AUTO; + EXPECT_EQ(WarpGetAvailableFreqByBand(band), 0); +} + +HWTEST_F(P2pStateMachineTest, GetAvailableFreqByBand2, TestSize.Level1) +{ + GroupOwnerBand band = GroupOwnerBand::GO_BAND_2GHZ; + EXPECT_CALL(WifiP2PHalInterface::GetInstance(), P2pGetSupportFrequenciesByBand(_, _)) + .WillOnce(Return(WifiErrorNo::WIFI_IDL_OPT_FAILED)); + EXPECT_EQ(WarpGetAvailableFreqByBand(band), 0); +} + +HWTEST_F(P2pStateMachineTest, GetAvailableFreqByBand3, TestSize.Level1) +{ + GroupOwnerBand band = GroupOwnerBand::GO_BAND_2GHZ; + std::vector freqList; + freqList.push_back(2412); + EXPECT_CALL(WifiP2PHalInterface::GetInstance(), P2pGetSupportFrequenciesByBand(_, _)) + .WillOnce(DoAll(SetArgReferee<1>(freqList), Return(WifiErrorNo::WIFI_IDL_OPT_OK))); + WarpGetAvailableFreqByBand(band); +} + +HWTEST_F(P2pStateMachineTest, SetGroupConfig1, TestSize.Level1) +{ + WifiP2pConfigInternal config; + EXPECT_CALL(WifiP2PHalInterface::GetInstance(), P2pSetGroupConfig(_, _)) + .WillOnce(Return(WifiErrorNo::WIFI_IDL_OPT_FAILED)); + EXPECT_FALSE(WarpSetGroupConfig(config, true)); +} + +HWTEST_F(P2pStateMachineTest, SetGroupConfig2, TestSize.Level1) +{ + WifiP2pConfigInternal config; + EXPECT_CALL(WifiP2PHalInterface::GetInstance(), P2pGetGroupConfig(_, _)) + .WillOnce(Return(WifiErrorNo::WIFI_IDL_OPT_OK)); + EXPECT_CALL(WifiP2PHalInterface::GetInstance(), P2pSetGroupConfig(_, _)) + .WillOnce(Return(WifiErrorNo::WIFI_IDL_OPT_OK)); + EXPECT_TRUE(WarpSetGroupConfig(config, false)); +} + +HWTEST_F(P2pStateMachineTest, SetGroupConfig3, TestSize.Level1) +{ + WifiP2pConfigInternal config; + config.SetGroupName(std::string("GroupName")); + config.SetPassphrase(std::string("12345678")); + EXPECT_CALL(WifiP2PHalInterface::GetInstance(), P2pGetGroupConfig(_, _)) + .WillOnce(Return(WifiErrorNo::WIFI_IDL_OPT_FAILED)); + EXPECT_CALL(WifiP2PHalInterface::GetInstance(), P2pSetGroupConfig(_, _)) + .WillOnce(Return(WifiErrorNo::WIFI_IDL_OPT_OK)); + EXPECT_TRUE(WarpSetGroupConfig(config, false)); +} + +HWTEST_F(P2pStateMachineTest, DealCreateNewGroupWithConfig1, TestSize.Level1) +{ + WifiP2pConfigInternal config; + config.SetGroupName(std::string("AAA")); + int freq = 0; + AddGroupManager(); + EXPECT_FALSE(WarpDealCreateNewGroupWithConfig(config, freq)); +} + +HWTEST_F(P2pStateMachineTest, DealCreateNewGroupWithConfig2, TestSize.Level1) +{ + WifiP2pConfigInternal config; + int freq = 0; + EXPECT_CALL(WifiP2PHalInterface::GetInstance(), P2pAddNetwork(_)).WillOnce(Return(WifiErrorNo::WIFI_IDL_OPT_OK)); + EXPECT_CALL(WifiP2PHalInterface::GetInstance(), P2pSetGroupConfig(_, _)) + .WillOnce(Return(WifiErrorNo::WIFI_IDL_OPT_FAILED)); + EXPECT_CALL(WifiP2PHalInterface::GetInstance(), GroupAdd(_, _, _)) + .WillOnce(Return(WifiErrorNo::WIFI_IDL_OPT_FAILED)); + EXPECT_CALL(WifiP2PHalInterface::GetInstance(), RemoveNetwork(_)).WillOnce(Return(WifiErrorNo::WIFI_IDL_OPT_OK)); + EXPECT_FALSE(WarpDealCreateNewGroupWithConfig(config, freq)); +} + +HWTEST_F(P2pStateMachineTest, DealCreateNewGroupWithConfig3, TestSize.Level1) +{ + WifiP2pConfigInternal config; + config.SetNetId(-1); + int freq = 0; + EXPECT_CALL(WifiP2PHalInterface::GetInstance(), P2pAddNetwork(_)).WillOnce(Return(WifiErrorNo::WIFI_IDL_OPT_OK)); + EXPECT_CALL(WifiP2PHalInterface::GetInstance(), P2pSetGroupConfig(_, _)) + .WillOnce(Return(WifiErrorNo::WIFI_IDL_OPT_OK)); + EXPECT_CALL(WifiP2PHalInterface::GetInstance(), GroupAdd(_, _, _)).WillOnce(Return(WifiErrorNo::WIFI_IDL_OPT_OK)); + EXPECT_CALL(WifiP2PHalInterface::GetInstance(), RemoveNetwork(_)) + .WillOnce(Return(WifiErrorNo::WIFI_IDL_OPT_OK)) + .WillRepeatedly(Return(WifiErrorNo::WIFI_IDL_OPT_OK)); + EXPECT_TRUE(WarpDealCreateNewGroupWithConfig(config, freq)); +} + +HWTEST_F(P2pStateMachineTest, UpdateGroupInfoToWpa1, TestSize.Level1) +{ + AddGroupManager(); + EXPECT_CALL(WifiP2PHalInterface::GetInstance(), RemoveNetwork(_)) + .WillOnce(Return(WifiErrorNo::WIFI_IDL_OPT_FAILED)); + WarpUpdateGroupInfoToWpa(); +} + +HWTEST_F(P2pStateMachineTest, UpdateGroupInfoToWpa2, TestSize.Level1) +{ + AddGroupManager(); + EXPECT_CALL(WifiP2PHalInterface::GetInstance(), RemoveNetwork(_)) + .WillOnce(Return(WifiErrorNo::WIFI_IDL_OPT_OK)); + EXPECT_CALL(WifiP2PHalInterface::GetInstance(), P2pAddNetwork(_)) + .WillOnce(Return(WifiErrorNo::WIFI_IDL_OPT_FAILED)); + WarpUpdateGroupInfoToWpa(); +} + +HWTEST_F(P2pStateMachineTest, UpdateGroupInfoToWpa3, TestSize.Level1) +{ + AddGroupManager(); + AddGroupManager3(); + EXPECT_CALL(WifiP2PHalInterface::GetInstance(), RemoveNetwork(_)) + .WillOnce(Return(WifiErrorNo::WIFI_IDL_OPT_OK)); + EXPECT_CALL(WifiP2PHalInterface::GetInstance(), P2pAddNetwork(_)) + .WillOnce(Return(WifiErrorNo::WIFI_IDL_OPT_OK)) + .WillOnce(Return(WifiErrorNo::WIFI_IDL_OPT_OK)); + EXPECT_CALL(WifiP2PHalInterface::GetInstance(), P2pSetGroupConfig(_, _)) + .WillOnce(Return(WifiErrorNo::WIFI_IDL_OPT_OK)) + .WillOnce(Return(WifiErrorNo::WIFI_IDL_OPT_OK)); + WarpUpdateGroupInfoToWpa(); +} + +HWTEST_F(P2pStateMachineTest, HandleP2pServiceResp1, TestSize.Level1) +{ + WifiP2pServiceResponse resp; + resp.SetServiceStatus(P2pServiceStatus::PSRS_SERVICE_PROTOCOL_NOT_AVAILABLE); + WifiP2pDevice dev; + WarpHandleP2pServiceResp(resp, dev); +} + +HWTEST_F(P2pStateMachineTest, HandleP2pServiceResp2, TestSize.Level1) +{ + WifiP2pServiceResponse resp; + resp.SetServiceStatus(P2pServiceStatus::PSRS_SUCCESS); + resp.SetProtocolType(P2pServicerProtocolType::SERVICE_TYPE_BONJOUR); + WifiP2pDevice dev; + WarpHandleP2pServiceResp(resp, dev); +} + +HWTEST_F(P2pStateMachineTest, HandleP2pServiceResp3, TestSize.Level1) +{ + WifiP2pServiceResponse resp; + resp.SetServiceStatus(P2pServiceStatus::PSRS_SUCCESS); + resp.SetProtocolType(P2pServicerProtocolType::SERVICE_TYPE_UP_NP); + WifiP2pDevice dev; + WarpHandleP2pServiceResp(resp, dev); +} + +HWTEST_F(P2pStateMachineTest, HandleP2pServiceResp4, TestSize.Level1) +{ + WifiP2pServiceResponse resp; + resp.SetServiceStatus(P2pServiceStatus::PSRS_SUCCESS); + resp.SetProtocolType(P2pServicerProtocolType::SERVICE_TYPE_VENDOR_SPECIFIC); + WifiP2pDevice dev; + WarpHandleP2pServiceResp(resp, dev); +} } // namespace Wifi } // namespace OHOS \ No newline at end of file diff --git a/tests/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/test/provision_discovery_state_test.cpp b/wifi/test/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/test/provision_discovery_state_test.cpp similarity index 85% rename from tests/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/test/provision_discovery_state_test.cpp rename to wifi/test/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/test/provision_discovery_state_test.cpp index 365b3f4add706265cd3c5ca31ed2b65d486b94ac..2190600810a3335f784c8db01b4d2dbf57e527f8 100644 --- a/tests/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/test/provision_discovery_state_test.cpp +++ b/wifi/test/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/test/provision_discovery_state_test.cpp @@ -164,6 +164,10 @@ HWTEST_F(ProvisionDiscoveryStateTest, ExecuteStateMsg3, TestSize.Level1) AddSaveP2pConfig3(); EXPECT_TRUE(pProvisionDiscoveryState->ExecuteStateMsg(&msg)); + + provDisc.SetPin(std::string("12345678")); + msg.SetMessageObj(provDisc); + EXPECT_TRUE(pProvisionDiscoveryState->ExecuteStateMsg(&msg)); } HWTEST_F(ProvisionDiscoveryStateTest, ExecuteStateMsg4, TestSize.Level1) @@ -174,12 +178,29 @@ HWTEST_F(ProvisionDiscoveryStateTest, ExecuteStateMsg4, TestSize.Level1) EXPECT_FALSE(pProvisionDiscoveryState->ExecuteStateMsg(nullptr)); } -HWTEST_F(ProvisionDiscoveryStateTest, ProcessProvDiscFailEvt, TestSize.Level1) +HWTEST_F(ProvisionDiscoveryStateTest, ExecuteStateMsgFailed, TestSize.Level1) { InternalMessage msg; - msg.SetMessageName(static_cast(P2P_STATE_MACHINE_CMD::PEER_CONNECTION_USER_REJECT)); EXPECT_FALSE(pProvisionDiscoveryState->ExecuteStateMsg(&msg)); } + +HWTEST_F(ProvisionDiscoveryStateTest, ProcessProvDiscFailEvt, TestSize.Level1) +{ + InternalMessage msg; + msg.SetMessageName(static_cast(P2P_STATE_MACHINE_CMD::P2P_EVENT_PROV_DISC_FAILURE)); + EXPECT_CALL(pMockP2pPendant->GetP2pStateMachine(), DealGroupCreationFailed()).WillOnce(Return()); + EXPECT_TRUE(pProvisionDiscoveryState->ExecuteStateMsg(&msg)); +} + +HWTEST_F(ProvisionDiscoveryStateTest, ProcessCmdCancelConnect, TestSize.Level1) +{ + InternalMessage msg; + msg.SetMessageName(static_cast(P2P_STATE_MACHINE_CMD::CMD_CANCEL_CONNECT)); + EXPECT_CALL(WifiP2PHalInterface::GetInstance(), CancelConnect()).WillOnce(Return(WifiErrorNo::WIFI_IDL_OPT_OK)); + EXPECT_CALL(pMockP2pPendant->GetP2pStateMachine(), DealGroupCreationFailed()).WillOnce(Return()); + EXPECT_CALL(pMockP2pPendant->GetP2pStateMachine(), BroadcastActionResult(_, _)).WillOnce(Return()); + EXPECT_TRUE(pProvisionDiscoveryState->ExecuteStateMsg(&msg)); +} } // namespace Wifi } // namespace OHOS \ No newline at end of file diff --git a/tests/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/test/wifi_p2p_device_manager_test.cpp b/wifi/test/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/test/wifi_p2p_device_manager_test.cpp similarity index 100% rename from tests/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/test/wifi_p2p_device_manager_test.cpp rename to wifi/test/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/test/wifi_p2p_device_manager_test.cpp diff --git a/tests/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/test/wifi_p2p_dns_sd_service_info_test.cpp b/wifi/test/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/test/wifi_p2p_dns_sd_service_info_test.cpp similarity index 92% rename from tests/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/test/wifi_p2p_dns_sd_service_info_test.cpp rename to wifi/test/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/test/wifi_p2p_dns_sd_service_info_test.cpp index d4cad132ea45ba73b751b47b72b86f3cd6023667..a3a80dfb585af2bcff5b75ef8b8fc79dd71b800b 100644 --- a/tests/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/test/wifi_p2p_dns_sd_service_info_test.cpp +++ b/wifi/test/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/test/wifi_p2p_dns_sd_service_info_test.cpp @@ -37,7 +37,7 @@ public: public: std::unique_ptr pWifiP2pDnsSdServiceInfo; - void WarpCompressDnsName() + void WarpTurnDnsNameToStream() { std::string dnsName = "a.txt"; EXPECT_EQ("c00c", pWifiP2pDnsSdServiceInfo->TurnDnsNameToStream("_tcp.local.")); @@ -53,7 +53,8 @@ HWTEST_F(WifiP2pDnsSdServiceInfoTest, Create, TestSize.Level1) std::string instanceName; std::string serviceType; std::map txtMap; - std::string svrName; + txtMap.insert(std::make_pair(std::string("ip"), std::string("TestIp"))); + std::string svrName("TestSvrName"); WifiP2pDnsSdServiceInfo::Create(instanceName, serviceType, txtMap, svrName); } @@ -68,9 +69,10 @@ HWTEST_F(WifiP2pDnsSdServiceInfoTest, BuildRequest, TestSize.Level1) std::map txtMap; WifiP2pDnsSdServiceInfo::Create(instanceName, serviceType, txtMap, svrName).BuildRequest(dnsName, dnsType, version); } + HWTEST_F(WifiP2pDnsSdServiceInfoTest, TurnDnsNameToStream, TestSize.Level1) { - WarpCompressDnsName(); + WarpTurnDnsNameToStream(); } } // namespace Wifi } // namespace OHOS \ No newline at end of file diff --git a/tests/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/test/wifi_p2p_dns_sd_service_request_test.cpp b/wifi/test/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/test/wifi_p2p_dns_sd_service_request_test.cpp similarity index 100% rename from tests/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/test/wifi_p2p_dns_sd_service_request_test.cpp rename to wifi/test/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/test/wifi_p2p_dns_sd_service_request_test.cpp diff --git a/tests/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/test/wifi_p2p_dns_sd_service_response_test.cpp b/wifi/test/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/test/wifi_p2p_dns_sd_service_response_test.cpp similarity index 46% rename from tests/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/test/wifi_p2p_dns_sd_service_response_test.cpp rename to wifi/test/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/test/wifi_p2p_dns_sd_service_response_test.cpp index 9a96490ff9f3cc772ae0297fd89e23d495633253..b580069e8d6fb45a1df463a65cc035b1317ec578 100644 --- a/tests/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/test/wifi_p2p_dns_sd_service_response_test.cpp +++ b/wifi/test/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/test/wifi_p2p_dns_sd_service_response_test.cpp @@ -28,16 +28,20 @@ public: virtual void SetUp() { pWifiP2pDnsSdServiceResponse.reset(new WifiP2pDnsSdServiceResponse(resp)); + std::vector data; + pWifiP2pDnsSdServiceResponse2.reset(new WifiP2pDnsSdServiceResponse(P2pServiceStatus::PSRS_SUCCESS, 0, data)); } virtual void TearDown() { pWifiP2pDnsSdServiceResponse.reset(); + pWifiP2pDnsSdServiceResponse2.reset(); } public: WifiP2pServiceResponse resp; std::unique_ptr pWifiP2pDnsSdServiceResponse; - void WarpReadTxtData() + std::unique_ptr pWifiP2pDnsSdServiceResponse2; + void WarpFetchTxtData() { std::istringstream istream("name"); pWifiP2pDnsSdServiceResponse->FetchTxtData(istream); @@ -86,11 +90,120 @@ HWTEST_F(WifiP2pDnsSdServiceResponseTest, ParseData, TestSize.Level1) data.push_back(0xc0); pWifiP2pDnsSdServiceResponse->SetData(data); EXPECT_EQ(false, pWifiP2pDnsSdServiceResponse->ParseData()); + + data.clear(); + data.push_back(0x0b); + data.push_back(0x73); + data.push_back(0x65); + data.push_back(0x72); + data.push_back(0x76); + data.push_back(0x69); + data.push_back(0x63); + data.push_back(0x65); + data.push_back(0x54); + data.push_back(0x79); + data.push_back(0x70); + data.push_back(0x65); + data.push_back(0xc0); + data.push_back(0x11); + data.push_back(0x00); + data.push_back(0x0c); + data.push_back(0x01); + data.push_back(0x0c); + data.push_back(0x69); + data.push_back(0x6e); + data.push_back(0x73); + data.push_back(0x74); + data.push_back(0x61); + data.push_back(0x6e); + data.push_back(0x63); + data.push_back(0x65); + data.push_back(0x4e); + data.push_back(0x61); + data.push_back(0x6d); + data.push_back(0x65); + data.push_back(0xc0); + data.push_back(0x27); + data.push_back(0x3b); + data.push_back(0x04); + data.push_back(0x73); + data.push_back(0x65); + data.push_back(0x72); + data.push_back(0x76); + pWifiP2pDnsSdServiceResponse->SetData(data); + EXPECT_EQ(true, pWifiP2pDnsSdServiceResponse->ParseData()); + + data.clear(); + data.push_back(0x0c); + data.push_back(0x69); + data.push_back(0x6e); + data.push_back(0x73); + data.push_back(0x74); + data.push_back(0x61); + data.push_back(0x6e); + data.push_back(0x63); + data.push_back(0x65); + data.push_back(0x6e); + data.push_back(0x61); + data.push_back(0x6d); + data.push_back(0x65); + data.push_back(0x0b); + data.push_back(0x73); + data.push_back(0x65); + data.push_back(0x72); + data.push_back(0x76); + data.push_back(0x69); + data.push_back(0x63); + data.push_back(0x65); + data.push_back(0x74); + data.push_back(0x79); + data.push_back(0x70); + data.push_back(0x65); + data.push_back(0xc0); + data.push_back(0x11); + data.push_back(0x00); + data.push_back(0x10); + data.push_back(0x01); + data.push_back(0x0e); + data.push_back(0x69); + data.push_back(0x70); + data.push_back(0x3d); + data.push_back(0x58); + data.push_back(0x58); + data.push_back(0x58); + data.push_back(0x2e); + data.push_back(0x58); + data.push_back(0x58); + data.push_back(0x58); + data.push_back(0x2e); + data.push_back(0x58); + data.push_back(0x2e); + data.push_back(0x58); + data.push_back(0x0a); + data.push_back(0x70); + data.push_back(0x6f); + data.push_back(0x72); + data.push_back(0x74); + data.push_back(0x3d); + data.push_back(0x39); + data.push_back(0x39); + data.push_back(0x39); + data.push_back(0x39); + data.push_back(0x39); + data.push_back(0x00); + data.push_back(0x3b); + data.push_back(0x04); + data.push_back(0x73); + data.push_back(0x65); + data.push_back(0x72); + data.push_back(0x76); + pWifiP2pDnsSdServiceResponse->SetData(data); + EXPECT_EQ(true, pWifiP2pDnsSdServiceResponse->ParseData()); } HWTEST_F(WifiP2pDnsSdServiceResponseTest, FetchTxtData, TestSize.Level1) { - WarpReadTxtData(); + WarpFetchTxtData(); } } // namespace Wifi } // namespace OHOS \ No newline at end of file diff --git a/tests/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/test/wifi_p2p_group_info_proxy_test.cpp b/wifi/test/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/test/wifi_p2p_group_info_proxy_test.cpp similarity index 94% rename from tests/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/test/wifi_p2p_group_info_proxy_test.cpp rename to wifi/test/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/test/wifi_p2p_group_info_proxy_test.cpp index a752d217f1f2b5f55936593c473f7e57f1fe45ff..c5102bd2e872e29692331aa2230d4f4d44711932 100644 --- a/tests/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/test/wifi_p2p_group_info_proxy_test.cpp +++ b/wifi/test/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/test/wifi_p2p_group_info_proxy_test.cpp @@ -61,6 +61,8 @@ HWTEST_F(WifiP2pGroupInfoProxyTest, CompareSuccess, TestSize.Level1) EXPECT_EQ(pWifiP2pGroupInfoProxy->GetInterface(), "iface"); pWifiP2pGroupInfoProxy->SetGroupName("groupName"); EXPECT_EQ(pWifiP2pGroupInfoProxy->GetGroupName(), "groupName"); + pWifiP2pGroupInfoProxy->SetGoIpAddress("ip"); + EXPECT_EQ(pWifiP2pGroupInfoProxy->GetGoIpAddress(), "ip"); pWifiP2pGroupInfoProxy->SetFrequency(2020); EXPECT_EQ(pWifiP2pGroupInfoProxy->GetFrequency(), 2020); pWifiP2pGroupInfoProxy->SetIsPersistent(true); @@ -76,6 +78,7 @@ HWTEST_F(WifiP2pGroupInfoProxyTest, CompareSuccess, TestSize.Level1) devices.push_back(device1); devices.push_back(device2); pWifiP2pGroupInfoProxy->SetClientDevices(devices); + std::vector clientDevices = pWifiP2pGroupInfoProxy->GetClientDevices(); EXPECT_FALSE(pWifiP2pGroupInfoProxy->IsClientDevicesEmpty()); pWifiP2pGroupInfoProxy->ClearClientDevices(); EXPECT_TRUE(pWifiP2pGroupInfoProxy->IsClientDevicesEmpty()); diff --git a/tests/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/test/wifi_p2p_group_manager_test.cpp b/wifi/test/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/test/wifi_p2p_group_manager_test.cpp similarity index 97% rename from tests/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/test/wifi_p2p_group_manager_test.cpp rename to wifi/test/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/test/wifi_p2p_group_manager_test.cpp index 5856662b69418462b1bc5eaca45be0f370e45c3e..680903f1d63e14fae421a33bd623b199b3c9dba3 100644 --- a/tests/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/test/wifi_p2p_group_manager_test.cpp +++ b/wifi/test/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/test/wifi_p2p_group_manager_test.cpp @@ -49,7 +49,6 @@ public: groupInfo.SetIsPersistent(true); groupInfo.SetP2pGroupStatus(P2pGroupStatus::GS_INVALID); groupInfo.SetNetworkId(SET_NETWORKID); - groupInfo.SetGoIpAddress(std::string("111.111.111.111")); groupInfo.AddClientDevice(device); } virtual void TearDown() @@ -150,7 +149,7 @@ HWTEST_F(WifiP2pGroupManagerTest, GetOwnerAddr_SUCCESS, TestSize.Level1) HWTEST_F(WifiP2pGroupManagerTest, Contains_SUCCESS, TestSize.Level1) { - WifiP2pInfo connInfo; + WifiP2pLinkedInfo linkedInfo; EXPECT_FALSE(pWifiP2pGroupManager->IsInclude(10)); pWifiP2pGroupManager->AddGroup(groupInfo); EXPECT_TRUE(pWifiP2pGroupManager->IsInclude(10)); @@ -164,8 +163,8 @@ HWTEST_F(WifiP2pGroupManagerTest, RefreshGroupsFromCurrentGroup_SUCCESS, TestSiz HWTEST_F(WifiP2pGroupManagerTest, SaveP2pInfo_SUCCESS, TestSize.Level1) { - WifiP2pInfo connInfo; - pWifiP2pGroupManager->SaveP2pInfo(connInfo); + WifiP2pLinkedInfo linkedInfo; + pWifiP2pGroupManager->SaveP2pInfo(linkedInfo); pWifiP2pGroupManager->GetP2pInfo(); } diff --git a/tests/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/test/wifi_p2p_service_manager_test.cpp b/wifi/test/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/test/wifi_p2p_service_manager_test.cpp similarity index 86% rename from tests/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/test/wifi_p2p_service_manager_test.cpp rename to wifi/test/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/test/wifi_p2p_service_manager_test.cpp index 63e9eb0524abc16bad64367da05f3fa252e1a656..21a312f574cf286ebd7da4bd8c506a1d1ac7ebb8 100644 --- a/tests/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/test/wifi_p2p_service_manager_test.cpp +++ b/wifi/test/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/test/wifi_p2p_service_manager_test.cpp @@ -29,7 +29,6 @@ public: virtual void SetUp() { - WifiP2pDevice device; pWifiP2pServiceManager.reset(new WifiP2pServiceManager()); } virtual void TearDown() @@ -160,7 +159,6 @@ HWTEST_F(WifiP2pServiceManagerTest, AddServiceResponse_SUCCESS, TestSize.Level1) EXPECT_TRUE(pWifiP2pServiceManager->AddServiceResponse(p2pSvrReq1)); } - HWTEST_F(WifiP2pServiceManagerTest, RemoveServiceResponse_SUCCESS, TestSize.Level1) { WifiP2pDevice device; @@ -236,5 +234,36 @@ HWTEST_F(WifiP2pServiceManagerTest, ClearAllRequestRecord, TestSize.Level1) { pWifiP2pServiceManager->ClearAllRequestRecord(); } + +HWTEST_F(WifiP2pServiceManagerTest, UpdateServiceName1, TestSize.Level1) +{ + WifiP2pServiceResponse resp; + resp.SetServiceStatus(P2pServiceStatus::PSRS_SUCCESS); + WifiP2pDevice device; + device.SetDeviceAddress(std::string("aa:bb:cc:dd:ee:ff")); + EXPECT_FALSE(pWifiP2pServiceManager->UpdateServiceName(std::string("aa:bb:cc:dd:ee:ff"), resp)); +} + +HWTEST_F(WifiP2pServiceManagerTest, UpdateServiceName2, TestSize.Level1) +{ + WifiP2pServiceResponse resp; + resp.SetServiceStatus(P2pServiceStatus::PSRS_SUCCESS); + WifiP2pDevice device; + device.SetDeviceAddress(std::string("aa:bb:cc:dd:ee:ff")); + pWifiP2pServiceManager->AddDeviceService(resp, device); + EXPECT_TRUE(pWifiP2pServiceManager->UpdateServiceName(std::string("aa:bb:cc:dd:ee:ff"), resp)); +} + +HWTEST_F(WifiP2pServiceManagerTest, UpdateServiceName3, TestSize.Level1) +{ + WifiP2pServiceResponse resp; + resp.SetServiceStatus(P2pServiceStatus::PSRS_SUCCESS); + resp.SetProtocolType(P2pServicerProtocolType::SERVICE_TYPE_BONJOUR); + WifiP2pDevice device; + device.SetDeviceAddress(std::string("aa:bb:cc:dd:ee:ff")); + pWifiP2pServiceManager->AddDeviceService(resp, device); + resp.SetProtocolType(P2pServicerProtocolType::SERVICE_TYPE_UP_NP); + EXPECT_FALSE(pWifiP2pServiceManager->UpdateServiceName(std::string("aa:bb:cc:dd:ee:ff"), resp)); +} } // namespace Wifi } // namespace OHOS \ No newline at end of file diff --git a/tests/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/test/wifi_p2p_service_request_list_test.cpp b/wifi/test/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/test/wifi_p2p_service_request_list_test.cpp similarity index 76% rename from tests/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/test/wifi_p2p_service_request_list_test.cpp rename to wifi/test/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/test/wifi_p2p_service_request_list_test.cpp index 2fc9e8f398c8fc59ae2cb511699237baf9035db3..1ea1f87efef9e7a055305f5ab4649d4525951867 100644 --- a/tests/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/test/wifi_p2p_service_request_list_test.cpp +++ b/wifi/test/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/test/wifi_p2p_service_request_list_test.cpp @@ -94,17 +94,45 @@ HWTEST_F(WifiP2pServiceRequestListTest, SetDevice, TestSize.Level1) EXPECT_EQ(pWifiP2pServiceRequestList->GetDevice(), device); } -HWTEST_F(WifiP2pServiceRequestListTest, GetTlvs, TestSize.Level1) // +HWTEST_F(WifiP2pServiceRequestListTest, GetTlvs, TestSize.Level1) { WifiP2pServiceRequest resp; EXPECT_TRUE(pWifiP2pServiceRequestList->AddServiceRequest(resp)); pWifiP2pServiceRequestList->GetTlvs(); } -HWTEST_F(WifiP2pServiceRequestListTest, ParseTlvs2ReqList, TestSize.Level1) +HWTEST_F(WifiP2pServiceRequestListTest, ParseTlvs2ReqList1, TestSize.Level1) { - const std::vector tlvList; - pWifiP2pServiceRequestList->ParseTlvs2ReqList(tlvList); + std::vector tlvList; + tlvList.push_back(0x02); + tlvList.push_back(0x00); + tlvList.push_back(0x00); + tlvList.push_back(0x01); + EXPECT_TRUE(pWifiP2pServiceRequestList->ParseTlvs2ReqList(tlvList)); +} + +HWTEST_F(WifiP2pServiceRequestListTest, ParseTlvs2ReqList2, TestSize.Level1) +{ + std::vector tlvList; + tlvList.push_back(0x01); + tlvList.push_back(0x00); + tlvList.push_back(0x00); + tlvList.push_back(0x01); + EXPECT_FALSE(pWifiP2pServiceRequestList->ParseTlvs2ReqList(tlvList)); +} + +HWTEST_F(WifiP2pServiceRequestListTest, ParseTlvs2ReqList3, TestSize.Level1) +{ + std::vector tlvList; + tlvList.push_back(0x06); + tlvList.push_back(0x00); + tlvList.push_back(0x00); + tlvList.push_back(0x01); + tlvList.push_back(0x31); + tlvList.push_back(0x32); + tlvList.push_back(0x33); + tlvList.push_back(0x34); + EXPECT_TRUE(pWifiP2pServiceRequestList->ParseTlvs2ReqList(tlvList)); } } // namespace Wifi } // namespace OHOS \ No newline at end of file diff --git a/tests/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/test/wifi_p2p_service_response_list_test.cpp b/wifi/test/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/test/wifi_p2p_service_response_list_test.cpp similarity index 64% rename from tests/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/test/wifi_p2p_service_response_list_test.cpp rename to wifi/test/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/test/wifi_p2p_service_response_list_test.cpp index 2b7767c09b64efdbb7a23f5bc55524a036a55c23..39431067ccf8e332a4245d0f646ed3d287cec46b 100644 --- a/tests/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/test/wifi_p2p_service_response_list_test.cpp +++ b/wifi/test/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/test/wifi_p2p_service_response_list_test.cpp @@ -79,14 +79,13 @@ HWTEST_F(WifiP2pServiceResponseListTest, FilterSerivceResponse, TestSize.Level1) HWTEST_F(WifiP2pServiceResponseListTest, ReverseFilterSerivceResponse, TestSize.Level1) { - pWifiP2pServiceResponseList->ReverseFilterSerivceResponse(P2pServiceStatus::PSRS_BAD_REQUEST); WifiP2pServiceResponse resp; resp.SetServiceStatus(P2pServiceStatus::PSRS_SUCCESS); EXPECT_TRUE(pWifiP2pServiceResponseList->AddServiceResponse(resp)); - pWifiP2pServiceResponseList->ReverseFilterSerivceResponse(P2pServiceStatus::PSRS_SUCCESS); + pWifiP2pServiceResponseList->ReverseFilterSerivceResponse(P2pServiceStatus::PSRS_BAD_REQUEST); } -HWTEST_F(WifiP2pServiceResponseListTest, MergerAndDeduplicate, TestSize.Level1) +HWTEST_F(WifiP2pServiceResponseListTest, MergerAndDeduplicate1, TestSize.Level1) { WifiP2pDevice device; WifiP2pServiceResponseList responseList; @@ -94,14 +93,45 @@ HWTEST_F(WifiP2pServiceResponseListTest, MergerAndDeduplicate, TestSize.Level1) responseList.SetDevice(device); WifiP2pServiceResponse resp; pWifiP2pServiceResponseList->MergerAndDeduplicate(responseList); +} + +HWTEST_F(WifiP2pServiceResponseListTest, MergerAndDeduplicate2, TestSize.Level1) +{ + WifiP2pDevice device; + WifiP2pServiceResponseList responseList; + device.SetDeviceAddress("AA:BB:CC:DD:EE:FF"); + responseList.SetDevice(device); + WifiP2pServiceResponse resp; pWifiP2pServiceResponseList->SetDevice(device); pWifiP2pServiceResponseList->MergerAndDeduplicate(responseList); - EXPECT_TRUE(pWifiP2pServiceResponseList->AddServiceResponse(resp)); +} + +HWTEST_F(WifiP2pServiceResponseListTest, MergerAndDeduplicate3, TestSize.Level1) +{ + WifiP2pDevice device; + WifiP2pServiceResponseList responseList; + device.SetDeviceAddress("AA:BB:CC:DD:EE:FF"); + responseList.SetDevice(device); + WifiP2pServiceResponse resp; + pWifiP2pServiceResponseList->SetDevice(device); + responseList.AddServiceResponse(resp); + pWifiP2pServiceResponseList->MergerAndDeduplicate(responseList); +} + +HWTEST_F(WifiP2pServiceResponseListTest, MergerAndDeduplicate4, TestSize.Level1) +{ + WifiP2pDevice device; + WifiP2pServiceResponseList responseList; + device.SetDeviceAddress("AA:BB:CC:DD:EE:FF"); + responseList.SetDevice(device); + WifiP2pServiceResponse resp; + pWifiP2pServiceResponseList->SetDevice(device); responseList.AddServiceResponse(resp); + EXPECT_TRUE(pWifiP2pServiceResponseList->AddServiceResponse(resp)); pWifiP2pServiceResponseList->MergerAndDeduplicate(responseList); } -HWTEST_F(WifiP2pServiceResponseListTest, GetTlvs, TestSize.Level1) // +HWTEST_F(WifiP2pServiceResponseListTest, GetTlvs, TestSize.Level1) { WifiP2pServiceResponse resp; EXPECT_TRUE(pWifiP2pServiceResponseList->AddServiceResponse(resp)); @@ -136,10 +166,58 @@ HWTEST_F(WifiP2pServiceResponseListTest, SetDevice, TestSize.Level1) EXPECT_EQ(pWifiP2pServiceResponseList->GetDevice(), device); } -HWTEST_F(WifiP2pServiceResponseListTest, ParseTlvs2RespList, TestSize.Level1) +HWTEST_F(WifiP2pServiceResponseListTest, ParseTlvs2RespList1, TestSize.Level1) { - const std::vector tlvList; + std::vector tlvList; + tlvList.push_back(0x02); + tlvList.push_back(0x00); + tlvList.push_back(0x00); + tlvList.push_back(0x01); + tlvList.push_back(0x01); pWifiP2pServiceResponseList->ParseTlvs2RespList(tlvList); } + +HWTEST_F(WifiP2pServiceResponseListTest, ParseTlvs2RespList2, TestSize.Level1) +{ + std::vector tlvList; + EXPECT_FALSE(pWifiP2pServiceResponseList->ParseTlvs2RespList(tlvList)); +} + +HWTEST_F(WifiP2pServiceResponseListTest, ParseTlvs2RespList3, TestSize.Level1) +{ + std::vector tlvList; + tlvList.push_back(0x03); + tlvList.push_back(0x00); + tlvList.push_back(0x01); + tlvList.push_back(0x00); + tlvList.push_back(0x00); + EXPECT_TRUE(pWifiP2pServiceResponseList->ParseTlvs2RespList(tlvList)); +} + +HWTEST_F(WifiP2pServiceResponseListTest, ParseTlvs2RespList4, TestSize.Level1) +{ + std::vector tlvList; + tlvList.push_back(0x03); + tlvList.push_back(0x10); + tlvList.push_back(0x01); + tlvList.push_back(0x00); + tlvList.push_back(0x00); + EXPECT_FALSE(pWifiP2pServiceResponseList->ParseTlvs2RespList(tlvList)); +} + +HWTEST_F(WifiP2pServiceResponseListTest, ParseTlvs2RespList5, TestSize.Level1) +{ + std::vector tlvList; + tlvList.push_back(0x07); + tlvList.push_back(0x00); + tlvList.push_back(0x01); + tlvList.push_back(0x00); + tlvList.push_back(0x00); + tlvList.push_back(0x31); + tlvList.push_back(0x32); + tlvList.push_back(0x33); + tlvList.push_back(0x34); + EXPECT_TRUE(pWifiP2pServiceResponseList->ParseTlvs2RespList(tlvList)); +} } // namespace Wifi } // namespace OHOS \ No newline at end of file diff --git a/tests/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/test/wifi_p2p_service_test.cpp b/wifi/test/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/test/wifi_p2p_service_test.cpp similarity index 63% rename from tests/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/test/wifi_p2p_service_test.cpp rename to wifi/test/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/test/wifi_p2p_service_test.cpp index 340a61661797c4be1b02e7cd5a39eb554065d611..7207626e21396cf24b4a660986b7bc4d1ef4df53 100644 --- a/tests/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/test/wifi_p2p_service_test.cpp +++ b/wifi/test/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/test/wifi_p2p_service_test.cpp @@ -1,5 +1,5 @@ /* - * Copyright (C) 2021 Huawei Device Co., Ltd. + * Copyright (C) 2021-2022 Huawei Device Co., Ltd. * 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 @@ -12,12 +12,14 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -#include -#include "wifi_p2p_service.h" -#include "wifi_p2p_msg.h" +#include #include "mock_p2p_pendant.h" #include "mock_wifi_p2p_hal_interface.h" +#include "wifi_hid2d_msg.h" +#include "wifi_p2p_msg.h" +#include "wifi_p2p_service.h" +#include "wifi_settings.h" using ::testing::Return; using ::testing::ext::TestSize; @@ -28,8 +30,8 @@ class WifiP2pServiceTest : public testing::Test { public: WifiP2pServiceTest() : groupManager(), deviceManager(), svrManager() {} - static void SetUpTestCase(){} - static void TearDownTestCase(){} + static void SetUpTestCase() {} + static void TearDownTestCase() {} virtual void SetUp() { pMockP2pPendant.reset(new MockP2pPendant()); @@ -50,6 +52,10 @@ public: WifiP2pDeviceManager deviceManager; WifiP2pServiceManager svrManager; }; +HWTEST_F(WifiP2pServiceTest, EnableP2p, TestSize.Level1) +{ + EXPECT_EQ(pWifiP2pService->EnableP2p(), ErrCode::WIFI_OPT_SUCCESS); +} HWTEST_F(WifiP2pServiceTest, DisableP2p, TestSize.Level1) { @@ -100,15 +106,16 @@ HWTEST_F(WifiP2pServiceTest, StartP2pListen, TestSize.Level1) int interval = 0; EXPECT_EQ(pWifiP2pService->StartP2pListen(period, interval), ErrCode::WIFI_OPT_SUCCESS); } + HWTEST_F(WifiP2pServiceTest, StopP2pListen, TestSize.Level1) { EXPECT_EQ(pWifiP2pService->StopP2pListen(), ErrCode::WIFI_OPT_SUCCESS); } -HWTEST_F(WifiP2pServiceTest, FormGroup, TestSize.Level1) +HWTEST_F(WifiP2pServiceTest, CreateGroup, TestSize.Level1) { WifiP2pConfig config; - EXPECT_EQ(pWifiP2pService->FormGroup(config), ErrCode::WIFI_OPT_SUCCESS); + EXPECT_EQ(pWifiP2pService->CreateGroup(config), ErrCode::WIFI_OPT_SUCCESS); } HWTEST_F(WifiP2pServiceTest, RemoveGroup, TestSize.Level1) @@ -126,20 +133,24 @@ HWTEST_F(WifiP2pServiceTest, P2pConnect, TestSize.Level1) { WifiP2pConfig config; EXPECT_EQ(pWifiP2pService->P2pConnect(config), ErrCode::WIFI_OPT_SUCCESS); - EXPECT_EQ(pWifiP2pService->P2pDisConnect(), ErrCode::WIFI_OPT_SUCCESS); + EXPECT_EQ(pWifiP2pService->P2pCancelConnect(), ErrCode::WIFI_OPT_SUCCESS); } -HWTEST_F(WifiP2pServiceTest, QueryP2pInfo, TestSize.Level1) +HWTEST_F(WifiP2pServiceTest, QueryP2pLinkedInfo, TestSize.Level1) { - WifiP2pInfo connInfo; - EXPECT_EQ(pWifiP2pService->QueryP2pInfo(connInfo), ErrCode::WIFI_OPT_SUCCESS); + WifiP2pLinkedInfo linkedInfo; + EXPECT_EQ(pWifiP2pService->QueryP2pLinkedInfo(linkedInfo), ErrCode::WIFI_OPT_SUCCESS); } HWTEST_F(WifiP2pServiceTest, GetCurrentGroup, TestSize.Level1) { + WifiP2pLinkedInfo p2pInfo; + p2pInfo.SetConnectState(P2pConnectedState::P2P_DISCONNECTED); + WifiSettings::GetInstance().SaveP2pInfo(p2pInfo); WifiP2pGroupInfo group; - EXPECT_EQ(pWifiP2pService->GetCurrentGroup(group), ErrCode::WIFI_OPT_SUCCESS); + EXPECT_EQ(pWifiP2pService->GetCurrentGroup(group), ErrCode::WIFI_OPT_FAILED); } + HWTEST_F(WifiP2pServiceTest, GetP2pEnableStatus, TestSize.Level1) { int status; @@ -175,5 +186,66 @@ HWTEST_F(WifiP2pServiceTest, QueryP2pServices, TestSize.Level1) std::vector services; EXPECT_EQ(pWifiP2pService->QueryP2pServices(services), ErrCode::WIFI_OPT_SUCCESS); } + +HWTEST_F(WifiP2pServiceTest, SetP2pDeviceName, TestSize.Level1) +{ + std::string deviceName("TestName"); + EXPECT_EQ(pWifiP2pService->SetP2pDeviceName(deviceName), ErrCode::WIFI_OPT_SUCCESS); +} + +HWTEST_F(WifiP2pServiceTest, SetP2pWfdInfo, TestSize.Level1) +{ + WifiP2pWfdInfo wfd; + EXPECT_EQ(pWifiP2pService->SetP2pWfdInfo(wfd), ErrCode::WIFI_OPT_SUCCESS); +} + +/** + * @tc.name: Set upper scene test + * @tc.desc: Set upper scene test function. + * @tc.type: FUNC + * @tc.require: issueI5LC5N + */ +HWTEST_F(WifiP2pServiceTest, SetUpperScene, TestSize.Level1) +{ + Hid2dUpperScene upperScene; + upperScene.scene = 0; // 0: video, 1: audio, 2: file + EXPECT_EQ(pWifiP2pService->Hid2dSetUpperScene("p2p0", upperScene), ErrCode::WIFI_OPT_SUCCESS); + upperScene.scene = 1; + EXPECT_EQ(pWifiP2pService->Hid2dSetUpperScene("p2p0", upperScene), ErrCode::WIFI_OPT_SUCCESS); + upperScene.scene = 2; + EXPECT_EQ(pWifiP2pService->Hid2dSetUpperScene("p2p0", upperScene), ErrCode::WIFI_OPT_SUCCESS); +} + +/** + * @tc.name: Recommend channel test + * @tc.desc: Recommend channel test function. + * @tc.type: FUNC + * @tc.require: issueI5LC5N + */ +HWTEST_F(WifiP2pServiceTest, GetP2pRecommendChannel, TestSize.Level1) +{ + // recommendd channel is greater than 0 + EXPECT_GT(pWifiP2pService->GetP2pRecommendChannel(), 0); +} + +/** + * @tc.name: Hid2d shared link test + * @tc.desc: Hid2d shared link test function. + * @tc.type: FUNC + * @tc.require: issueI5LC5N + */ +HWTEST_F(WifiP2pServiceTest, HiD2dSharedLinkTest, TestSize.Level1) +{ + int count = pWifiP2pService->GetSharedLinkCount(); + pWifiP2pService->IncreaseSharedLink(); + EXPECT_EQ(pWifiP2pService->GetSharedLinkCount(), count + 1); + pWifiP2pService->IncreaseSharedLink(); + EXPECT_EQ(pWifiP2pService->GetSharedLinkCount(), count + 2); + + pWifiP2pService->DecreaseSharedLink(); + EXPECT_EQ(pWifiP2pService->GetSharedLinkCount(), count + 1); + pWifiP2pService->DecreaseSharedLink(); + EXPECT_EQ(pWifiP2pService->GetSharedLinkCount(), count); +} } // namespace Wifi } // namespace OHOS \ No newline at end of file diff --git a/tests/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/test/wifi_p2p_upnp_service_info_test.cpp b/wifi/test/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/test/wifi_p2p_upnp_service_info_test.cpp similarity index 94% rename from tests/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/test/wifi_p2p_upnp_service_info_test.cpp rename to wifi/test/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/test/wifi_p2p_upnp_service_info_test.cpp index c94b56eae7eeff75e39abde74c79fa531ea629de..52397ccf3f05a25021c918049b880b08d52a57b1 100644 --- a/tests/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/test/wifi_p2p_upnp_service_info_test.cpp +++ b/wifi/test/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/test/wifi_p2p_upnp_service_info_test.cpp @@ -37,7 +37,8 @@ public: std::string uuid; std::string device; std::vector services; - std::string svrName; + services.push_back(std::string("TestUpnpService")); + std::string svrName("TestSvrName"); WifiP2pUpnpServiceInfo::Create(uuid, device, services, svrName); } void WarpCreateSupQuery() diff --git a/tests/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/test/wifi_p2p_upnp_service_request_test.cpp b/wifi/test/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/test/wifi_p2p_upnp_service_request_test.cpp similarity index 95% rename from tests/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/test/wifi_p2p_upnp_service_request_test.cpp rename to wifi/test/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/test/wifi_p2p_upnp_service_request_test.cpp index fe3c9146077ff50d73220a084c452796b52ee646..4381f3242094bd99b3ee47d5a12eb72b7cd104f6 100644 --- a/tests/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/test/wifi_p2p_upnp_service_request_test.cpp +++ b/wifi/test/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/test/wifi_p2p_upnp_service_request_test.cpp @@ -36,6 +36,7 @@ public: { WifiP2pUpnpServiceRequest::Create(); WifiP2pUpnpServiceRequest::Create("searchTarget"); + WifiP2pUpnpServiceRequest::Create(std::string("")); } }; diff --git a/tests/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/test/wifi_p2p_upnp_service_response_test.cpp b/wifi/test/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/test/wifi_p2p_upnp_service_response_test.cpp similarity index 76% rename from tests/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/test/wifi_p2p_upnp_service_response_test.cpp rename to wifi/test/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/test/wifi_p2p_upnp_service_response_test.cpp index 87ed7a61d26d5d7a0933f4fd834418bd119d7b1f..b986fe77f65716bb1cd29cf30d1d8e0401abb0c4 100644 --- a/tests/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/test/wifi_p2p_upnp_service_response_test.cpp +++ b/wifi/test/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/test/wifi_p2p_upnp_service_response_test.cpp @@ -51,14 +51,25 @@ HWTEST_F(WifiP2pUpnpServiceResponseTest, GetVersion, TestSize.Level1) EXPECT_EQ(-1, WifiP2pUpnpServiceResponse::Create(status, tranId, data).GetVersion()); } -HWTEST_F(WifiP2pUpnpServiceResponseTest, ParseData, TestSize.Level1) +HWTEST_F(WifiP2pUpnpServiceResponseTest, ParseData1, TestSize.Level1) +{ + EXPECT_EQ(false, WifiP2pUpnpServiceResponse::Create(status, tranId, data).ParseData()); +} + +HWTEST_F(WifiP2pUpnpServiceResponseTest, ParseData2, TestSize.Level1) { - std::vector data; data.push_back(1); - data.push_back(2); - data.push_back(3); - EXPECT_EQ(true, WifiP2pUpnpServiceResponse::Create(status, tranId, data).ParseData()); - WifiP2pUpnpServiceResponse::Create(status, tranId, data).SetData(data); + data.push_back(0x31); + data.push_back(0x32); + data.push_back(0x2c); + data.push_back(0x33); + data.push_back(0x34); + data.push_back(0x3b); + data.push_back(0x04); + data.push_back(0x73); + data.push_back(0x76); + data.push_back(0x72); + data.push_back(0x4e); EXPECT_EQ(true, WifiP2pUpnpServiceResponse::Create(status, tranId, data).ParseData()); } } // namespace Wifi diff --git a/wifi/test/wifi_standard/wifi_framework/wifi_manage/wifi_scan/BUILD.gn b/wifi/test/wifi_standard/wifi_framework/wifi_manage/wifi_scan/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..abb6f02524246cb6a5b02fee60fc19f17e8755e4 --- /dev/null +++ b/wifi/test/wifi_standard/wifi_framework/wifi_manage/wifi_scan/BUILD.gn @@ -0,0 +1,102 @@ +# Copyright (C) 2021-2022 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import("//build/test.gni") +import("//foundation/communication/wifi/wifi/wifi.gni") +module_output_path = "wifi/scan_test" + +config("module_private_config") { + visibility = [ ":*" ] + include_dirs = [ + "//commonlibrary/c_utils/base/include", + "$WIFI_ROOT_DIR/test/wifi_standard/wifi_framework/wifi_manage/wifi_scan", + ] +} + +ohos_unittest("wifi_scan_unittest") { + module_out_path = module_output_path + sources = [ + "$WIFI_ROOT_DIR/services/wifi_standard/wifi_framework/wifi_manage/common/handler.cpp", + "$WIFI_ROOT_DIR/services/wifi_standard/wifi_framework/wifi_manage/common/internal_message.cpp", + "$WIFI_ROOT_DIR/services/wifi_standard/wifi_framework/wifi_manage/common/message_queue.cpp", + "$WIFI_ROOT_DIR/services/wifi_standard/wifi_framework/wifi_manage/common/state.cpp", + "$WIFI_ROOT_DIR/services/wifi_standard/wifi_framework/wifi_manage/common/state_machine.cpp", + "$WIFI_ROOT_DIR/services/wifi_standard/wifi_framework/wifi_manage/wifi_scan/scan_interface.cpp", + "$WIFI_ROOT_DIR/services/wifi_standard/wifi_framework/wifi_manage/wifi_scan/scan_monitor.cpp", + "$WIFI_ROOT_DIR/services/wifi_standard/wifi_framework/wifi_manage/wifi_scan/scan_service.cpp", + "$WIFI_ROOT_DIR/services/wifi_standard/wifi_framework/wifi_manage/wifi_scan/scan_state_machine.cpp", + "Mock/mock_scan_service.cpp", + "Mock/mock_scan_state_machine.cpp", + "Mock/mock_wifi_manager.cpp", + "Mock/mock_wifi_settings.cpp", + "Mock/mock_wifi_sta_hal_interface.cpp", + "Mock/mock_wifi_supplicant_hal_interface.cpp", + "global_test.cpp", + "scan_interface_test.cpp", + "scan_monitor_test.cpp", + "scan_service_test.cpp", + "scan_state_machine_test.cpp", + ] + + include_dirs = [ + "//commonlibrary/c_utils/base/include", + "$WIFI_ROOT_DIR/frameworks/native/interfaces", + "$WIFI_ROOT_DIR/services/wifi_standard/sdk/include", + "$WIFI_ROOT_DIR/services/wifi_standard/ipc_framework/cRPC/include", + "$WIFI_ROOT_DIR/services/wifi_standard/wifi_framework/wifi_toolkit/include", + "$WIFI_ROOT_DIR/services/wifi_standard/wifi_framework/wifi_toolkit/net_helper", + "$WIFI_ROOT_DIR/services/wifi_standard/wifi_framework/wifi_toolkit/log", + "$WIFI_ROOT_DIR/services/wifi_standard/wifi_framework/wifi_toolkit/config", + "$WIFI_ROOT_DIR/services/wifi_standard/wifi_framework/wifi_toolkit/utils", + "$WIFI_ROOT_DIR/services/wifi_standard/wifi_framework/wifi_manage/common", + "$WIFI_ROOT_DIR/services/wifi_standard/wifi_framework/wifi_manage/wifi_scan", + "$WIFI_ROOT_DIR/test/wifi_standard/wifi_framework/wifi_manage/wifi_scan/Mock", + "$WIFI_ROOT_DIR/services/wifi_standard/wifi_framework/wifi_manage/", + "$WIFI_ROOT_DIR/services/wifi_standard/wifi_framework/wifi_manage/idl_client", + "$WIFI_ROOT_DIR/services/wifi_standard/wifi_framework/wifi_manage/idl_client/idl_interface", + "$WIFI_ROOT_DIR/services/wifi_standard/wifi_framework/wifi_manage/wifi_sta/net_conf", + "$WIFI_ROOT_DIR/services/wifi_standard/wifi_framework/wifi_manage/wifi_sta", + "//base/hiviewdfx/hilog/interfaces/native/innerkits/include", + "$WIFI_ROOT_DIR/services/wifi_standard/depends/include/hardware/libhardware/include", + "$WIFI_ROOT_DIR/services/wifi_standard/depends/include/system/core/include", + "$WIFI_ROOT_DIR/services/wifi_standard/depends/include/frameworks/native/include", + "$WIFI_ROOT_DIR/services/wifi_standard/depends/include/system/core/libutils/include", + "$WIFI_ROOT_DIR/services/wifi_standard/depends/include/system/core/base/include", + "$WIFI_ROOT_DIR/services/wifi_standard/depends/include/system/libbase/include", + "$WIFI_ROOT_DIR/services/wifi_standard/depends/include/system/core/libnetutils/include/netutils", + "//third_party/googletest/googlemock/include", + "//third_party/googletest/googletest/include", + "$WIFI_ROOT_DIR/services/wifi_standard/include", + "$WIFI_ROOT_DIR/utils/inc", + ] + deps = [ + "$WIFI_ROOT_DIR/services/wifi_standard/wifi_framework/wifi_manage:wifi_manager_service", + "$WIFI_ROOT_DIR/services/wifi_standard/wifi_framework/wifi_manage/idl_client:wifi_idl_client", + "$WIFI_ROOT_DIR/services/wifi_standard/wifi_framework/wifi_toolkit:wifi_toolkit", + "$WIFI_ROOT_DIR/utils:wifi_utils", + "//third_party/googletest:gmock_main", + "//third_party/googletest:gtest_main", + ] + defines = [ "AP_INSTANCE_MAX_NUM=$wifi_feature_with_ap_num" ] + external_deps = [ + "c_utils:utils", + "hiviewdfx_hilog_native:libhilog", + ] + part_name = "wifi" + subsystem_name = "communication" +} + +group("unittest") { + testonly = true + deps = [ ":wifi_scan_unittest" ] +} diff --git a/tests/wifi_standard/wifi_framework/wifi_manage/wifi_scan/Mock/mock_scan_service.cpp b/wifi/test/wifi_standard/wifi_framework/wifi_manage/wifi_scan/Mock/mock_scan_service.cpp similarity index 92% rename from tests/wifi_standard/wifi_framework/wifi_manage/wifi_scan/Mock/mock_scan_service.cpp rename to wifi/test/wifi_standard/wifi_framework/wifi_manage/wifi_scan/Mock/mock_scan_service.cpp index 7abdfc5f062e88d5a3b1fdae196fbabe95876eed..1a001a5a6e8a66ceeab091b4bcd728f6709004b0 100644 --- a/tests/wifi_standard/wifi_framework/wifi_manage/wifi_scan/Mock/mock_scan_service.cpp +++ b/wifi/test/wifi_standard/wifi_framework/wifi_manage/wifi_scan/Mock/mock_scan_service.cpp @@ -57,9 +57,8 @@ void MockScanService::SystemScanProcess(bool scanAtOnce) WIFI_LOGI("Enter MockScanService::SystemScanProcess"); } -void MockScanService::HandleScreenStatusChanged(bool screenOn) +void MockScanService::HandleScreenStatusChanged() { - (void)screenOn; WIFI_LOGI("Enter MockScanService::HandleScreenStatusChanged"); } @@ -76,10 +75,10 @@ void MockScanService::HandleCustomStatusChanged(int customScene, int customScene WIFI_LOGI("Enter MockScanService::HandleCustomStatusChanged"); } -void MockScanService::SetOperateAppMode(int appMode) +void MockScanService::HandleGetCustomSceneState(std::map& sceneMap) const { - (void)appMode; - WIFI_LOGI("Enter MockScanService::SetOperateAppMode"); + (void)sceneMap; + WIFI_LOGI("Enter MockScanService::HandleGetCustomSceneState"); } void MockScanService::GetScanControlInfo() diff --git a/tests/wifi_standard/wifi_framework/wifi_manage/wifi_scan/Mock/mock_scan_service.h b/wifi/test/wifi_standard/wifi_framework/wifi_manage/wifi_scan/Mock/mock_scan_service.h similarity index 93% rename from tests/wifi_standard/wifi_framework/wifi_manage/wifi_scan/Mock/mock_scan_service.h rename to wifi/test/wifi_standard/wifi_framework/wifi_manage/wifi_scan/Mock/mock_scan_service.h index 03a6a481d0610af8457ac5593b1e1f13743c19f0..ea49c00291154c7e456db48a1adfd4303a610cfd 100644 --- a/tests/wifi_standard/wifi_framework/wifi_manage/wifi_scan/Mock/mock_scan_service.h +++ b/wifi/test/wifi_standard/wifi_framework/wifi_manage/wifi_scan/Mock/mock_scan_service.h @@ -30,10 +30,10 @@ public: ErrCode Scan(bool externFlag); ErrCode ScanWithParam(const WifiScanParams ¶ms); void SystemScanProcess(bool scanAtOnce); - void HandleScreenStatusChanged(bool screenOn); + void HandleScreenStatusChanged(); void HandleStaStatusChanged(int status); void HandleCustomStatusChanged(int customScene, int customSceneStatus); - void SetOperateAppMode(int appMode); + void HandleGetCustomSceneState(std::map& sceneMap) const; void GetScanControlInfo(); void ClearScanControlValue(); void SetStaCurrentTime(); diff --git a/tests/wifi_standard/wifi_framework/wifi_manage/wifi_scan/Mock/mock_scan_state_machine.cpp b/wifi/test/wifi_standard/wifi_framework/wifi_manage/wifi_scan/Mock/mock_scan_state_machine.cpp similarity index 100% rename from tests/wifi_standard/wifi_framework/wifi_manage/wifi_scan/Mock/mock_scan_state_machine.cpp rename to wifi/test/wifi_standard/wifi_framework/wifi_manage/wifi_scan/Mock/mock_scan_state_machine.cpp diff --git a/tests/wifi_standard/wifi_framework/wifi_manage/wifi_scan/Mock/mock_scan_state_machine.h b/wifi/test/wifi_standard/wifi_framework/wifi_manage/wifi_scan/Mock/mock_scan_state_machine.h similarity index 100% rename from tests/wifi_standard/wifi_framework/wifi_manage/wifi_scan/Mock/mock_scan_state_machine.h rename to wifi/test/wifi_standard/wifi_framework/wifi_manage/wifi_scan/Mock/mock_scan_state_machine.h diff --git a/tests/wifi_standard/wifi_framework/wifi_manage/wifi_scan/Mock/mock_wifi_manager.cpp b/wifi/test/wifi_standard/wifi_framework/wifi_manage/wifi_scan/Mock/mock_wifi_manager.cpp similarity index 93% rename from tests/wifi_standard/wifi_framework/wifi_manage/wifi_scan/Mock/mock_wifi_manager.cpp rename to wifi/test/wifi_standard/wifi_framework/wifi_manage/wifi_scan/Mock/mock_wifi_manager.cpp index 4011e31e2f052ad8e2316d0511823cadfbbb3a20..2a04619788c3ee54fad7251d405d724ed6286144 100644 --- a/tests/wifi_standard/wifi_framework/wifi_manage/wifi_scan/Mock/mock_wifi_manager.cpp +++ b/wifi/test/wifi_standard/wifi_framework/wifi_manage/wifi_scan/Mock/mock_wifi_manager.cpp @@ -39,6 +39,7 @@ void WifiManager::InitScanCallback(void) mScanCallback.OnScanStopEvent = std::bind(&WifiManager::DealScanCloseRes, this); mScanCallback.OnScanFinishEvent = std::bind(&WifiManager::DealScanFinished, this, _1); mScanCallback.OnScanInfoEvent = std::bind(&WifiManager::DealScanInfoNotify, this, _1); + mScanCallback.OnStoreScanInfoEvent = std::bind(&WifiManager::DealStoreScanInfoEvent, this, _1); return; } } // namespace Wifi diff --git a/tests/wifi_standard/wifi_framework/wifi_manage/wifi_scan/Mock/mock_wifi_manager.h b/wifi/test/wifi_standard/wifi_framework/wifi_manage/wifi_scan/Mock/mock_wifi_manager.h similarity index 90% rename from tests/wifi_standard/wifi_framework/wifi_manage/wifi_scan/Mock/mock_wifi_manager.h rename to wifi/test/wifi_standard/wifi_framework/wifi_manage/wifi_scan/Mock/mock_wifi_manager.h index bb8d74bbc975ee69c69252cc685e3609379c691a..d13b4c0c98d423e1f3c4be35f95c5a49adf79ea2 100644 --- a/tests/wifi_standard/wifi_framework/wifi_manage/wifi_scan/Mock/mock_wifi_manager.h +++ b/wifi/test/wifi_standard/wifi_framework/wifi_manage/wifi_scan/Mock/mock_wifi_manager.h @@ -27,6 +27,7 @@ public: virtual void DealScanCloseRes() = 0; virtual void DealScanFinished(int state) = 0; virtual void DealScanInfoNotify(std::vector &results) = 0; + virtual void DealStoreScanInfoEvent(std::vector &results) = 0; }; class WifiManager : public MockWifiManager { @@ -40,6 +41,7 @@ public: MOCK_METHOD0(DealScanCloseRes, void()); MOCK_METHOD1(DealScanFinished, void(int state)); MOCK_METHOD1(DealScanInfoNotify, void(std::vector &results)); + MOCK_METHOD1(DealStoreScanInfoEvent, void(std::vector &results)); private: IScanSerivceCallbacks mScanCallback; diff --git a/tests/wifi_standard/wifi_framework/wifi_manage/wifi_scan/Mock/mock_wifi_settings.cpp b/wifi/test/wifi_standard/wifi_framework/wifi_manage/wifi_scan/Mock/mock_wifi_settings.cpp similarity index 100% rename from tests/wifi_standard/wifi_framework/wifi_manage/wifi_scan/Mock/mock_wifi_settings.cpp rename to wifi/test/wifi_standard/wifi_framework/wifi_manage/wifi_scan/Mock/mock_wifi_settings.cpp diff --git a/tests/wifi_standard/wifi_framework/wifi_manage/wifi_scan/Mock/mock_wifi_settings.h b/wifi/test/wifi_standard/wifi_framework/wifi_manage/wifi_scan/Mock/mock_wifi_settings.h similarity index 66% rename from tests/wifi_standard/wifi_framework/wifi_manage/wifi_scan/Mock/mock_wifi_settings.h rename to wifi/test/wifi_standard/wifi_framework/wifi_manage/wifi_scan/Mock/mock_wifi_settings.h index 77eaedf81b8e7329ab681e4c000f0bb7b243d343..6884447fda5afa813bdc92199bde3efd0fe65508 100644 --- a/tests/wifi_standard/wifi_framework/wifi_manage/wifi_scan/Mock/mock_wifi_settings.h +++ b/wifi/test/wifi_standard/wifi_framework/wifi_manage/wifi_scan/Mock/mock_wifi_settings.h @@ -16,6 +16,7 @@ #define OHOS_MOCK_WIFI_SETTINGS_H #include "wifi_msg.h" +#include "wifi_internal_msg.h" #include namespace OHOS { @@ -28,12 +29,20 @@ public: virtual int GetScanControlInfo(ScanControlInfo &info) = 0; virtual int SetScanControlInfo(const ScanControlInfo &info) = 0; virtual void SetScreenState(const int &state) = 0; - virtual int GetScreenState() = 0; + virtual int GetScreenState() const = 0; + virtual ScanMode GetAppRunningState() const = 0; + virtual const std::string GetAppPackageName() const = 0; + virtual int GetFreezeModeState() const = 0; + virtual int GetNoChargerPlugModeState() const = 0; + virtual void SetSupportHwPnoFlag(bool supportHwPnoFlag) = 0; virtual bool GetSupportHwPnoFlag() = 0; virtual int GetMinRssi2Dot4Ghz() = 0; virtual int GetMinRssi5Ghz() = 0; virtual bool GetWhetherToAllowNetworkSwitchover() = 0; virtual int GetDeviceConfig(std::vector &results) = 0; + virtual const std::vector ReloadTrustListPolicies() = 0; + virtual const MovingFreezePolicy ReloadMovingFreezePolicy() = 0; + virtual int GetThermalLevel() const = 0; }; class WifiSettings : public MockWifiSettings { @@ -45,12 +54,20 @@ public: MOCK_METHOD1(GetScanControlInfo, int(ScanControlInfo &info)); MOCK_METHOD1(SetScanControlInfo, int(const ScanControlInfo &info)); MOCK_METHOD1(SetScreenState, void(const int &state)); - MOCK_METHOD0(GetScreenState, int()); + MOCK_CONST_METHOD0(GetScreenState, int()); + MOCK_CONST_METHOD0(GetAppRunningState, ScanMode()); + MOCK_CONST_METHOD0(GetAppPackageName, const std::string()); + MOCK_CONST_METHOD0(GetFreezeModeState, int()); + MOCK_CONST_METHOD0(GetNoChargerPlugModeState, int()); + MOCK_METHOD1(SetSupportHwPnoFlag, void(bool supportHwPnoFlag)); MOCK_METHOD0(GetSupportHwPnoFlag, bool()); MOCK_METHOD0(GetMinRssi2Dot4Ghz, int()); MOCK_METHOD0(GetMinRssi5Ghz, int()); MOCK_METHOD0(GetWhetherToAllowNetworkSwitchover, bool()); MOCK_METHOD1(GetDeviceConfig, int(std::vector &results)); + MOCK_METHOD0(ReloadTrustListPolicies, const std::vector()); + MOCK_METHOD0(ReloadMovingFreezePolicy, const MovingFreezePolicy()); + MOCK_CONST_METHOD0(GetThermalLevel, int()); }; } // namespace Wifi } // namespace OHOS diff --git a/tests/wifi_standard/wifi_framework/wifi_manage/wifi_scan/Mock/mock_wifi_sta_hal_interface.cpp b/wifi/test/wifi_standard/wifi_framework/wifi_manage/wifi_scan/Mock/mock_wifi_sta_hal_interface.cpp similarity index 100% rename from tests/wifi_standard/wifi_framework/wifi_manage/wifi_scan/Mock/mock_wifi_sta_hal_interface.cpp rename to wifi/test/wifi_standard/wifi_framework/wifi_manage/wifi_scan/Mock/mock_wifi_sta_hal_interface.cpp diff --git a/tests/wifi_standard/wifi_framework/wifi_manage/wifi_scan/Mock/mock_wifi_sta_hal_interface.h b/wifi/test/wifi_standard/wifi_framework/wifi_manage/wifi_scan/Mock/mock_wifi_sta_hal_interface.h similarity index 100% rename from tests/wifi_standard/wifi_framework/wifi_manage/wifi_scan/Mock/mock_wifi_sta_hal_interface.h rename to wifi/test/wifi_standard/wifi_framework/wifi_manage/wifi_scan/Mock/mock_wifi_sta_hal_interface.h diff --git a/tests/wifi_standard/wifi_framework/wifi_manage/wifi_scan/Mock/mock_wifi_supplicant_hal_interface.cpp b/wifi/test/wifi_standard/wifi_framework/wifi_manage/wifi_scan/Mock/mock_wifi_supplicant_hal_interface.cpp similarity index 100% rename from tests/wifi_standard/wifi_framework/wifi_manage/wifi_scan/Mock/mock_wifi_supplicant_hal_interface.cpp rename to wifi/test/wifi_standard/wifi_framework/wifi_manage/wifi_scan/Mock/mock_wifi_supplicant_hal_interface.cpp diff --git a/tests/wifi_standard/wifi_framework/wifi_manage/wifi_scan/Mock/mock_wifi_supplicant_hal_interface.h b/wifi/test/wifi_standard/wifi_framework/wifi_manage/wifi_scan/Mock/mock_wifi_supplicant_hal_interface.h similarity index 100% rename from tests/wifi_standard/wifi_framework/wifi_manage/wifi_scan/Mock/mock_wifi_supplicant_hal_interface.h rename to wifi/test/wifi_standard/wifi_framework/wifi_manage/wifi_scan/Mock/mock_wifi_supplicant_hal_interface.h diff --git a/tests/wifi_standard/wifi_framework/wifi_manage/wifi_scan/global_test.cpp b/wifi/test/wifi_standard/wifi_framework/wifi_manage/wifi_scan/global_test.cpp similarity index 100% rename from tests/wifi_standard/wifi_framework/wifi_manage/wifi_scan/global_test.cpp rename to wifi/test/wifi_standard/wifi_framework/wifi_manage/wifi_scan/global_test.cpp diff --git a/tests/wifi_standard/wifi_framework/wifi_manage/wifi_scan/global_test.h b/wifi/test/wifi_standard/wifi_framework/wifi_manage/wifi_scan/global_test.h similarity index 100% rename from tests/wifi_standard/wifi_framework/wifi_manage/wifi_scan/global_test.h rename to wifi/test/wifi_standard/wifi_framework/wifi_manage/wifi_scan/global_test.h diff --git a/tests/wifi_standard/wifi_framework/wifi_manage/wifi_scan/scan_interface_test.cpp b/wifi/test/wifi_standard/wifi_framework/wifi_manage/wifi_scan/scan_interface_test.cpp similarity index 88% rename from tests/wifi_standard/wifi_framework/wifi_manage/wifi_scan/scan_interface_test.cpp rename to wifi/test/wifi_standard/wifi_framework/wifi_manage/wifi_scan/scan_interface_test.cpp index 513d1b3873c746fd217d9d9adfbdf5fc2774d515..04bdc42ffc500f6d51a89cdcbc814ef5a79ac647 100644 --- a/tests/wifi_standard/wifi_framework/wifi_manage/wifi_scan/scan_interface_test.cpp +++ b/wifi/test/wifi_standard/wifi_framework/wifi_manage/wifi_scan/scan_interface_test.cpp @@ -1,5 +1,5 @@ /* - * Copyright (C) 2021 Huawei Device Co., Ltd. + * Copyright (C) 2021-2022 Huawei Device Co., Ltd. * 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 @@ -55,6 +55,9 @@ public: extern "C" IScanService *Create(void); extern "C" void Destroy(IScanService *pservice); + +std::vector refVecTrustList; +MovingFreezePolicy defaultValue; HWTEST_F(ScanInterfaceTest, GCreateDestroy, TestSize.Level1) { auto p = Create(); @@ -67,11 +70,15 @@ HWTEST_F(ScanInterfaceTest, InitTest, TestSize.Level1) EXPECT_CALL(WifiSupplicantHalInterface::GetInstance(), RegisterSupplicantEventCallback(_)).Times(AtLeast(1)); EXPECT_CALL(WifiStaHalInterface::GetInstance(), GetSupportFrequencies(_, _)).Times(AtLeast(1)); EXPECT_CALL(WifiSettings::GetInstance(), GetScanControlInfo(_)).Times(AtLeast(1)); - EXPECT_CALL(WifiSettings::GetInstance(), GetScreenState()).Times(AtLeast(1)); EXPECT_CALL(WifiManager::GetInstance(), DealScanOpenRes()).Times(AtLeast(0)); EXPECT_CALL(WifiSupplicantHalInterface::GetInstance(), UnRegisterSupplicantEventCallback()).Times(AtLeast(1)); EXPECT_CALL(WifiSettings::GetInstance(), GetWhetherToAllowNetworkSwitchover()).Times(AtLeast(0)); EXPECT_CALL(WifiSettings::GetInstance(), GetDeviceConfig(_)).Times(AtLeast(0)); + EXPECT_CALL(WifiSettings::GetInstance(), GetAppPackageName()).WillRepeatedly(Return("")); + EXPECT_CALL(WifiSettings::GetInstance(), ReloadTrustListPolicies()) + .WillRepeatedly(Return(refVecTrustList)); + EXPECT_CALL(WifiSettings::GetInstance(), ReloadMovingFreezePolicy()) + .WillRepeatedly(Return(defaultValue)); pScanInterface->Init(); } @@ -95,13 +102,13 @@ HWTEST_F(ScanInterfaceTest, ScanWithParamSuccess, TestSize.Level1) HWTEST_F(ScanInterfaceTest, OnScreenStateChangedSuccess1, TestSize.Level1) { - int screenState = STATE_OPEN; + int screenState = MODE_STATE_OPEN; EXPECT_EQ(WIFI_OPT_SUCCESS, pScanInterface->OnScreenStateChanged(screenState)); } HWTEST_F(ScanInterfaceTest, OnScreenStateChangedSuccess2, TestSize.Level1) { - int screenState = STATE_CLOSE; + int screenState = MODE_STATE_CLOSE; EXPECT_EQ(WIFI_OPT_SUCCESS, pScanInterface->OnScreenStateChanged(screenState)); } @@ -118,12 +125,12 @@ HWTEST_F(ScanInterfaceTest, OnClientModeStatusChangedSuccess, TestSize.Level1) HWTEST_F(ScanInterfaceTest, OnAppRunningModeChangedSuccess, TestSize.Level1) { - EXPECT_EQ(WIFI_OPT_SUCCESS, pScanInterface->OnAppRunningModeChanged(0)); + EXPECT_EQ(WIFI_OPT_SUCCESS, pScanInterface->OnAppRunningModeChanged(ScanMode::APP_FOREGROUND_SCAN)); } HWTEST_F(ScanInterfaceTest, OnCustomControlStateChangedSuccess, TestSize.Level1) { - int customSceneStatus = STATE_OPEN; + int customSceneStatus = MODE_STATE_OPEN; EXPECT_EQ(WIFI_OPT_SUCCESS, pScanInterface->OnCustomControlStateChanged(0, customSceneStatus)); } diff --git a/tests/wifi_standard/wifi_framework/wifi_manage/wifi_scan/scan_monitor_test.cpp b/wifi/test/wifi_standard/wifi_framework/wifi_manage/wifi_scan/scan_monitor_test.cpp similarity index 100% rename from tests/wifi_standard/wifi_framework/wifi_manage/wifi_scan/scan_monitor_test.cpp rename to wifi/test/wifi_standard/wifi_framework/wifi_manage/wifi_scan/scan_monitor_test.cpp diff --git a/tests/wifi_standard/wifi_framework/wifi_manage/wifi_scan/scan_service_test.cpp b/wifi/test/wifi_standard/wifi_framework/wifi_manage/wifi_scan/scan_service_test.cpp similarity index 80% rename from tests/wifi_standard/wifi_framework/wifi_manage/wifi_scan/scan_service_test.cpp rename to wifi/test/wifi_standard/wifi_framework/wifi_manage/wifi_scan/scan_service_test.cpp index 3914ad405df8dc68e217fbee00f6a2ae9cd30a7c..ae26a9ee9adf24d41fcb103051f00d0cc7f23e4b 100644 --- a/tests/wifi_standard/wifi_framework/wifi_manage/wifi_scan/scan_service_test.cpp +++ b/wifi/test/wifi_standard/wifi_framework/wifi_manage/wifi_scan/scan_service_test.cpp @@ -43,7 +43,7 @@ public: EXPECT_CALL(WifiStaHalInterface::GetInstance(), StopPnoScan()).Times(AtLeast(0)); pScanService = std::make_unique(); pScanService->pScanStateMachine = new MockScanStateMachine(); - pScanService->mScanSerivceCallbacks = WifiManager::GetInstance().GetScanCallback(); + pScanService->RegisterScanCallbacks(WifiManager::GetInstance().GetScanCallback()); } virtual void TearDown() { @@ -52,6 +52,8 @@ public: public: std::unique_ptr pScanService; + std::vector refVecTrustList; + MovingFreezePolicy defaultValue; void InitScanServiceSuccess1() { @@ -59,11 +61,12 @@ public: EXPECT_CALL(WifiSupplicantHalInterface::GetInstance(), RegisterSupplicantEventCallback(_)).Times(AtLeast(1)); EXPECT_CALL(WifiStaHalInterface::GetInstance(), GetSupportFrequencies(_, _)).Times(AtLeast(1)); EXPECT_CALL(WifiSettings::GetInstance(), GetScanControlInfo(_)).Times(AtLeast(1)); - EXPECT_CALL(WifiSettings::GetInstance(), GetScreenState()).Times(AtLeast(1)); EXPECT_CALL(WifiManager::GetInstance(), DealScanOpenRes()).Times(AtLeast(0)); EXPECT_CALL(WifiSupplicantHalInterface::GetInstance(), UnRegisterSupplicantEventCallback()).Times(AtLeast(1)); EXPECT_CALL(WifiSettings::GetInstance(), GetWhetherToAllowNetworkSwitchover()).Times(AtLeast(0)); EXPECT_CALL(WifiSettings::GetInstance(), GetDeviceConfig(_)).Times(AtLeast(0)); + EXPECT_CALL(WifiSettings::GetInstance(), ReloadMovingFreezePolicy()) + .WillRepeatedly(Return(defaultValue)); EXPECT_EQ(pScanService->InitScanService(WifiManager::GetInstance().GetScanCallback()), true); } @@ -79,6 +82,8 @@ public: EXPECT_CALL(WifiSupplicantHalInterface::GetInstance(), UnRegisterSupplicantEventCallback()).Times(AtLeast(1)); EXPECT_CALL(WifiSettings::GetInstance(), GetWhetherToAllowNetworkSwitchover()).Times(AtLeast(0)); EXPECT_CALL(WifiSettings::GetInstance(), GetDeviceConfig(_)).Times(AtLeast(0)); + EXPECT_CALL(WifiSettings::GetInstance(), ReloadTrustListPolicies()) + .WillRepeatedly(Return(refVecTrustList)); EXPECT_EQ(pScanService->InitScanService(WifiManager::GetInstance().GetScanCallback()), true); } @@ -90,9 +95,8 @@ public: void HandleScanStatusReportSuccess1() { - EXPECT_CALL(WifiSettings::GetInstance(), GetWhetherToAllowNetworkSwitchover()) - .Times(AtLeast(1)) - .WillRepeatedly(Return(true)); + ON_CALL(WifiSettings::GetInstance(), GetWhetherToAllowNetworkSwitchover()) + .WillByDefault(Return(true)); EXPECT_CALL(WifiManager::GetInstance(), DealScanOpenRes()).Times(AtLeast(1)); EXPECT_CALL(WifiSettings::GetInstance(), GetDeviceConfig(_)).Times(AtLeast(0)); EXPECT_CALL(WifiStaHalInterface::GetInstance(), StopPnoScan()).Times(AtLeast(0)); @@ -131,7 +135,7 @@ public: { EXPECT_CALL(WifiManager::GetInstance(), DealScanInfoNotify(_)).Times(AtLeast(1)); ScanStatusReport scanStatusReport; - scanStatusReport.status = PNO_SCAN_RESULT; + scanStatusReport.status = PNO_SCAN_INFO; pScanService->HandleScanStatusReport(scanStatusReport); } @@ -206,6 +210,7 @@ public: void ScanWithParamSuccess() { EXPECT_CALL(WifiSettings::GetInstance(), GetDeviceConfig(_)).WillRepeatedly(Return(true)); + EXPECT_CALL(WifiSettings::GetInstance(), GetThermalLevel()).WillRepeatedly(Return(1)); pScanService->scanStartedFlag = true; WifiScanParams params; params.band = SCAN_BAND_BOTH_WITH_DFS; @@ -268,7 +273,6 @@ public: { ScanConfig scanConfig; scanConfig.scanBand = SCAN_BAND_24_GHZ; - ; scanConfig.externFlag = true; scanConfig.scanStyle = SCAN_TYPE_HIGH_ACCURACY; EXPECT_EQ(true, pScanService->SingleScan(scanConfig)); @@ -405,7 +409,7 @@ public: void HandleCommonScanInfoSuccess2() { - EXPECT_CALL(WifiSettings::GetInstance(), SaveScanInfoList(_)).Times(AtLeast(1)); + ON_CALL(WifiSettings::GetInstance(), SaveScanInfoList(_)).WillByDefault(Return(0)); StoreScanConfig storeScanConfig0; storeScanConfig0.fullScanFlag = true; StoreScanConfig storeScanConfig1; @@ -554,20 +558,17 @@ public: void HandleScreenStatusChangedSuccess() { - pScanService->HandleScreenStatusChanged(false); - pScanService->HandleScreenStatusChanged(true); + pScanService->HandleScreenStatusChanged(); } void HandleStaStatusChangedSuccess1() { - EXPECT_CALL(WifiSettings::GetInstance(), GetWhetherToAllowNetworkSwitchover()); int status = static_cast(OperateResState::DISCONNECT_DISCONNECTED); pScanService->HandleStaStatusChanged(status); } void HandleStaStatusChangedSuccess2() { - EXPECT_CALL(WifiSettings::GetInstance(), GetWhetherToAllowNetworkSwitchover()); int status = static_cast(OperateResState::CONNECT_AP_CONNECTED); pScanService->HandleStaStatusChanged(status); } @@ -582,7 +583,7 @@ public: { EXPECT_CALL(WifiSettings::GetInstance(), GetWhetherToAllowNetworkSwitchover()).Times(AtLeast(0)); int customScene = 0; - int customSceneStatus = STATE_CLOSE; + int customSceneStatus = MODE_STATE_CLOSE; pScanService->HandleCustomStatusChanged(customScene, customSceneStatus); } @@ -590,15 +591,14 @@ public: { EXPECT_CALL(WifiSettings::GetInstance(), GetWhetherToAllowNetworkSwitchover()).Times(AtLeast(0)); int customScene = 0; - int customSceneStatus = STATE_OPEN; + int customSceneStatus = MODE_STATE_OPEN; pScanService->HandleCustomStatusChanged(customScene, customSceneStatus); } void SystemScanProcessSuccess1() { - EXPECT_CALL(WifiSettings::GetInstance(), GetWhetherToAllowNetworkSwitchover()); - pScanService->isScreenOn = true; ScanIntervalMode mode; + mode.scanScene = SCAN_SCENE_ALL; mode.scanMode = ScanMode::SYSTEM_TIMER_SCAN; mode.isSingle = false; pScanService->scanControlInfo.scanIntervalList.push_back(mode); @@ -610,7 +610,6 @@ public: EXPECT_CALL(WifiSettings::GetInstance(), GetWhetherToAllowNetworkSwitchover()); EXPECT_CALL(WifiSettings::GetInstance(), GetMinRssi2Dot4Ghz()).Times(AtLeast(0)); EXPECT_CALL(WifiSettings::GetInstance(), GetMinRssi5Ghz()).Times(AtLeast(0)); - pScanService->isScreenOn = false; pScanService->SystemScanProcess(true); } @@ -660,51 +659,10 @@ public: EXPECT_CALL(WifiSettings::GetInstance(), GetScanControlInfo(_)).WillRepeatedly(Return(-1)); pScanService->GetScanControlInfo(); } - - void GetScreenStateSuccess() - { - EXPECT_CALL(WifiSettings::GetInstance(), GetScreenState()).WillRepeatedly(Return(SCREEN_CLOSED)); - pScanService->GetScreenState(); - } - - void SetOperateAppModeSuccess() - { - pScanService->SetOperateAppMode(0); - } - - void GetOperateAppModeSuccess1() - { - pScanService->operateAppMode = APP_FOREGROUND_SCAN; - EXPECT_EQ(ScanMode::APP_FOREGROUND_SCAN, pScanService->GetOperateAppMode()); - } - - void GetOperateAppModeSuccess2() - { - pScanService->operateAppMode = APP_BACKGROUND_SCAN; - EXPECT_EQ(ScanMode::APP_BACKGROUND_SCAN, pScanService->GetOperateAppMode()); - } - - void GetOperateAppModeSuccess3() - { - pScanService->operateAppMode = SYS_FOREGROUND_SCAN; - EXPECT_EQ(ScanMode::SYS_FOREGROUND_SCAN, pScanService->GetOperateAppMode()); - } - - void GetOperateAppModeSuccess4() - { - pScanService->operateAppMode = SYS_BACKGROUND_SCAN; - EXPECT_EQ(ScanMode::SYS_BACKGROUND_SCAN, pScanService->GetOperateAppMode()); - } - - void GetOperateAppModeFail() - { - pScanService->operateAppMode = MAX_PNO_SCAN_FAILED_NUM; - EXPECT_EQ(ScanMode::SYS_FOREGROUND_SCAN, pScanService->GetOperateAppMode()); - } - + void AllowExternScanSuccess() { - pScanService->AllowExternScan(0); + pScanService->AllowExternScan(); } void AllowExternScanFail1() @@ -713,13 +671,21 @@ public: StoreScanConfig cfg; cfg.externFlag = true; pScanService->scanConfigMap.emplace(staScene, cfg); - pScanService->AllowExternScan(0); + + ScanMode scanMode = ScanMode::SYS_FOREGROUND_SCAN; + ScanForbidMode forbidMode; + forbidMode.scanScene = SCAN_SCENE_SCANNING; + forbidMode.scanMode = scanMode; + pScanService->scanControlInfo.scanForbidList.push_back(forbidMode); + + pScanService->AllowExternScan(); } void AllowSystemTimerScanSuccess() { EXPECT_CALL(WifiSettings::GetInstance(), GetWhetherToAllowNetworkSwitchover()); ScanIntervalMode mode; + mode.scanScene = SCAN_SCENE_ALL; mode.scanMode = ScanMode::SYSTEM_TIMER_SCAN; mode.isSingle = false; pScanService->scanControlInfo.scanIntervalList.push_back(mode); @@ -729,23 +695,144 @@ public: void AllowPnoScanSuccess() { ScanIntervalMode mode; + mode.scanScene = SCAN_SCENE_ALL; mode.scanMode = ScanMode::PNO_SCAN; mode.isSingle = false; pScanService->scanControlInfo.scanIntervalList.push_back(mode); pScanService->AllowPnoScan(); } + void AllowExternScanByThermal() + { + pScanService->AllowExternScanByThermal(); + } + void AllowExternScanByForbidSuccess1() { int staScene = 0; StoreScanConfig cfg; cfg.externFlag = true; pScanService->scanConfigMap.emplace(staScene, cfg); - pScanService->isScreenOn = false; ScanMode scanMode = ScanMode::SYS_FOREGROUND_SCAN; EXPECT_EQ(pScanService->AllowExternScanByForbid(staScene, scanMode), true); } + void AllowExternScanByForbidFail1() + { + int staScene = 0; + StoreScanConfig cfg; + cfg.externFlag = true; + pScanService->scanConfigMap.emplace(staScene, cfg); + + ScanMode scanMode = ScanMode::SYS_FOREGROUND_SCAN; + ScanForbidMode forbidMode; + forbidMode.scanScene = SCAN_SCENE_SCANNING; + forbidMode.scanMode = scanMode; + pScanService->scanControlInfo.scanForbidList.push_back(forbidMode); + + EXPECT_EQ(pScanService->AllowExternScanByForbid(staScene, scanMode), false); + } + + void AllowExternScanByForbidFail2() + { + int staScene = 0; + StoreScanConfig cfg; + cfg.externFlag = true; + pScanService->scanConfigMap.emplace(staScene, cfg); + + ScanMode scanMode = ScanMode::SYS_FOREGROUND_SCAN; + ScanForbidMode forbidMode; + forbidMode.scanScene = SCAN_SCENE_SCANNING; + forbidMode.scanMode = ScanMode::ALL_EXTERN_SCAN; + pScanService->scanControlInfo.scanForbidList.push_back(forbidMode); + + EXPECT_EQ(pScanService->AllowExternScanByForbid(staScene, scanMode), false); + } + + void AllowExternScanByForbidFail3() + { + int staScene = 0; + ScanMode scanMode = ScanMode::SYS_FOREGROUND_SCAN; + ScanForbidMode forbidMode; + forbidMode.scanScene = SCAN_SCENE_SCREEN_OFF; + forbidMode.scanMode = scanMode; + pScanService->scanControlInfo.scanForbidList.push_back(forbidMode); + EXPECT_EQ(pScanService->AllowExternScanByForbid(staScene, scanMode), false); + } + + void AllowExternScanByForbidFail4() + { + int staScene = 0; + ScanMode scanMode = ScanMode::SYS_FOREGROUND_SCAN; + ScanForbidMode forbidMode; + forbidMode.scanScene = SCAN_SCENE_SCREEN_OFF; + forbidMode.scanMode = ScanMode::ALL_EXTERN_SCAN; + pScanService->scanControlInfo.scanForbidList.push_back(forbidMode); + EXPECT_EQ(pScanService->AllowExternScanByForbid(staScene, scanMode), false); + } + + void AllowExternScanByForbidFail5() + { + int staScene = 0; + ScanMode scanMode = ScanMode::SYS_FOREGROUND_SCAN; + ScanForbidMode scanForbidMode; + scanForbidMode.scanScene = staScene; + scanForbidMode.scanMode = scanMode; + scanForbidMode.forbidTime = 0; + scanForbidMode.forbidCount = 0; + pScanService->scanControlInfo.scanForbidList.push_back(scanForbidMode); + EXPECT_EQ(pScanService->AllowExternScanByForbid(staScene, scanMode), false); + } + + void AllowExternScanByForbidFail6() + { + int staScene = 0; + ScanMode scanMode = ScanMode::SYS_FOREGROUND_SCAN; + ScanForbidMode scanForbidMode; + scanForbidMode.scanScene = staScene; + scanForbidMode.scanMode = ScanMode::ALL_EXTERN_SCAN; + scanForbidMode.forbidTime = 0; + scanForbidMode.forbidCount = 0; + pScanService->scanControlInfo.scanForbidList.push_back(scanForbidMode); + EXPECT_EQ(pScanService->AllowExternScanByForbid(staScene, scanMode), false); + } + + void AllowExternScanByForbidFail7() + { + int staScene = 0; + ScanMode scanMode = ScanMode::SYS_FOREGROUND_SCAN; + time_t now = time(nullptr); + if (now < 0) { + return; + } + pScanService->customSceneTimeMap.emplace(staScene, now); + ScanForbidMode scanForbidMode; + scanForbidMode.scanScene = staScene; + scanForbidMode.scanMode = scanMode; + scanForbidMode.forbidTime = 0; + scanForbidMode.forbidCount = 0; + pScanService->scanControlInfo.scanForbidList.push_back(scanForbidMode); + EXPECT_EQ(pScanService->AllowExternScanByForbid(staScene, scanMode), false); + } + + void AllowExternScanByForbidFail8() + { + int staScene = 0; + ScanMode scanMode = ScanMode::SYS_FOREGROUND_SCAN; + time_t now = time(nullptr); + if (now < 0) { + return; + } + pScanService->customSceneTimeMap.emplace(staScene, now); + ScanForbidMode scanForbidMode; + scanForbidMode.scanScene = staScene; + scanForbidMode.scanMode = ScanMode::ALL_EXTERN_SCAN; + scanForbidMode.forbidTime = 0; + scanForbidMode.forbidCount = 0; + pScanService->scanControlInfo.scanForbidList.push_back(scanForbidMode); + EXPECT_EQ(pScanService->AllowExternScanByForbid(staScene, scanMode), false); + } + void AllowExternScanByIntervaluccess() { pScanService->AllowExternScanByInterval(0, 0, ScanMode::SYS_FOREGROUND_SCAN); @@ -777,10 +864,14 @@ public: void GetStaSceneSuccess5() { + pScanService->staStatus = static_cast(OperateResState::CONNECT_ASSOCIATING); + EXPECT_EQ(SCAN_SCENE_ASSOCIATING, pScanService->GetStaScene()); } void GetStaSceneSuccess6() { + pScanService->staStatus = static_cast(OperateResState::CONNECT_ASSOCIATED); + EXPECT_EQ(SCAN_SCENE_ASSOCIATED, pScanService->GetStaScene()); } void GetStaSceneFail() @@ -925,28 +1016,159 @@ public: EXPECT_EQ(pScanService->AllowScanDuringScanning(scanMode), true); } + void AllowScanDuringScanningFail() + { + ScanMode scanMode = ScanMode::SYS_FOREGROUND_SCAN; + ScanForbidMode forbidMode; + forbidMode.scanScene = SCAN_SCENE_SCANNING; + forbidMode.scanMode = scanMode; + pScanService->scanControlInfo.scanForbidList.push_back(forbidMode); + EXPECT_EQ(pScanService->AllowScanDuringScanning(scanMode), false); + } + void AllowScanDuringScreenOffSuccess() { ScanMode scanMode = ScanMode::SYS_FOREGROUND_SCAN; EXPECT_EQ(pScanService->AllowScanDuringScreenOff(scanMode), true); } + void AllowScanDuringScreenOffFail1() + { + ScanMode scanMode = ScanMode::SYS_FOREGROUND_SCAN; + ScanForbidMode forbidMode; + forbidMode.scanScene = SCAN_SCENE_SCREEN_OFF; + forbidMode.scanMode = scanMode; + pScanService->scanControlInfo.scanForbidList.push_back(forbidMode); + + EXPECT_EQ(pScanService->AllowScanDuringScreenOff(scanMode), false); + } + void AllowScanDuringStaSceneSuccess1() { const int staScene = 0; ScanMode scanMode = ScanMode::SYS_FOREGROUND_SCAN; + ScanForbidMode scanForbidMode; + scanForbidMode.scanScene = staScene; + scanForbidMode.scanMode = scanMode; + scanForbidMode.forbidTime = 1; + scanForbidMode.forbidCount = 1; + pScanService->staSceneForbidCount = 1; time_t nowTime = time(nullptr); const int timeForTest = 2; pScanService->staCurrentTime = nowTime - timeForTest; + pScanService->scanControlInfo.scanForbidList.push_back(scanForbidMode); EXPECT_EQ(pScanService->AllowScanDuringStaScene(staScene, scanMode), true); } + void AllowScanDuringStaSceneFail1() + { + const int staScene = 0; + ScanMode scanMode = ScanMode::SYS_FOREGROUND_SCAN; + ScanForbidMode scanForbidMode; + scanForbidMode.scanScene = staScene; + scanForbidMode.scanMode = scanMode; + scanForbidMode.forbidTime = 0; + scanForbidMode.forbidCount = 0; + pScanService->scanControlInfo.scanForbidList.push_back(scanForbidMode); + EXPECT_EQ(pScanService->AllowScanDuringStaScene(staScene, scanMode), false); + } + + void AllowScanDuringStaSceneFail2() + { + const int staScene = 0; + ScanMode scanMode = ScanMode::SYS_FOREGROUND_SCAN; + ScanForbidMode scanForbidMode; + scanForbidMode.scanScene = staScene; + scanForbidMode.scanMode = scanMode; + scanForbidMode.forbidTime = 1; + scanForbidMode.forbidCount = 1; + pScanService->staSceneForbidCount = 0; + pScanService->scanControlInfo.scanForbidList.push_back(scanForbidMode); + EXPECT_EQ(pScanService->AllowScanDuringStaScene(staScene, scanMode), false); + } + + void AllowScanDuringStaSceneFail3() + { + const int staScene = 0; + ScanMode scanMode = ScanMode::SYS_FOREGROUND_SCAN; + ScanForbidMode scanForbidMode; + scanForbidMode.scanScene = staScene; + scanForbidMode.scanMode = scanMode; + scanForbidMode.forbidTime = 1; + scanForbidMode.forbidCount = 1; + pScanService->staSceneForbidCount = 1; + pScanService->staSceneForbidCount = 1; + time_t nowTime = time(nullptr); + const int timeForTest = 2; + pScanService->staCurrentTime = nowTime + timeForTest; + pScanService->scanControlInfo.scanForbidList.push_back(scanForbidMode); + EXPECT_EQ(pScanService->AllowScanDuringStaScene(staScene, scanMode), false); + } + void AllowScanDuringCustomSceneSuccess() { ScanMode scanMode = ScanMode::SYS_FOREGROUND_SCAN; EXPECT_EQ(pScanService->AllowScanDuringCustomScene(scanMode), true); } + void AllowScanDuringCustomSceneFail1() + { + const int staScene = 0; + ScanMode scanMode = ScanMode::SYS_FOREGROUND_SCAN; + time_t now = time(nullptr); + if (now < 0) { + return; + } + pScanService->customSceneTimeMap.emplace(staScene, now); + ScanForbidMode scanForbidMode; + scanForbidMode.scanScene = staScene; + scanForbidMode.scanMode = scanMode; + scanForbidMode.forbidTime = 0; + scanForbidMode.forbidCount = 0; + pScanService->scanControlInfo.scanForbidList.push_back(scanForbidMode); + EXPECT_EQ(pScanService->AllowScanDuringCustomScene(scanMode), false); + } + + void AllowScanDuringCustomSceneFail2() + { + const int staScene = 0; + ScanMode scanMode = ScanMode::SYS_FOREGROUND_SCAN; + time_t now = time(nullptr); + if (now < 0) { + return; + } + pScanService->customSceneTimeMap.emplace(staScene, now); + ScanForbidMode scanForbidMode; + scanForbidMode.scanScene = staScene; + scanForbidMode.scanMode = scanMode; + scanForbidMode.forbidTime = 1; + scanForbidMode.forbidCount = 1; + pScanService->staSceneForbidCount = 0; + pScanService->scanControlInfo.scanForbidList.push_back(scanForbidMode); + EXPECT_EQ(pScanService->AllowScanDuringCustomScene(scanMode), false); + } + + void AllowScanDuringCustomSceneFail3() + { + const int staScene = 0; + ScanMode scanMode = ScanMode::SYS_FOREGROUND_SCAN; + time_t now = time(nullptr); + if (now < 0) { + return; + } + pScanService->customSceneTimeMap.emplace(staScene, now); + ScanForbidMode scanForbidMode; + scanForbidMode.scanScene = staScene; + scanForbidMode.scanMode = scanMode; + scanForbidMode.forbidTime = 1; + scanForbidMode.forbidCount = 1; + time_t nowTime = time(nullptr); + const int timeForTest = 2; + pScanService->staCurrentTime = nowTime + timeForTest; + pScanService->scanControlInfo.scanForbidList.push_back(scanForbidMode); + EXPECT_EQ(pScanService->AllowScanDuringCustomScene(scanMode), false); + } + void AllowExternScanByIntervalMode() { pScanService->AllowExternScanByIntervalMode(0, 0, ScanMode::SYS_FOREGROUND_SCAN); @@ -1049,6 +1271,7 @@ public: int appId = 0; SingleAppForbid sAppForbid; sAppForbid.appID = appId; + sAppForbid.scanIntervalMode.scanScene = SCAN_SCENE_ALL; sAppForbid.scanIntervalMode.scanMode = ScanMode::SCAN_MODE_MAX; pScanService->appForbidList.push_back(sAppForbid); ScanIntervalMode scanIntervalMode = sAppForbid.scanIntervalMode; @@ -1060,6 +1283,7 @@ public: int appId = 0; SingleAppForbid sAppForbid; sAppForbid.appID = appId; + sAppForbid.scanIntervalMode.scanScene = SCAN_SCENE_ALL; sAppForbid.scanIntervalMode.scanMode = ScanMode::SCAN_MODE_MAX; sAppForbid.fixedScanCount = 1; @@ -1087,6 +1311,7 @@ public: int appId = 0; SingleAppForbid sAppForbid; sAppForbid.appID = appId; + sAppForbid.scanIntervalMode.scanScene = SCAN_SCENE_ALL; sAppForbid.scanIntervalMode.scanMode = ScanMode::SCAN_MODE_MAX; pScanService->fullAppForbidList.push_back(sAppForbid); ScanIntervalMode scanIntervalMode = sAppForbid.scanIntervalMode; @@ -1098,6 +1323,7 @@ public: int appId = 0; SingleAppForbid sAppForbid; sAppForbid.appID = appId; + sAppForbid.scanIntervalMode.scanScene = SCAN_SCENE_ALL; sAppForbid.scanIntervalMode.scanMode = ScanMode::SCAN_MODE_MAX; sAppForbid.fixedScanCount = 1; @@ -1215,7 +1441,6 @@ public: int lessThanIntervalCount = 0; const int countTest = 1; int count = countTest; - // lessThanIntervalCount = 0 branch. bool rlt = pScanService->AllowScanByIntervalContinue(continueScanTime, lessThanIntervalCount, interval, count); EXPECT_EQ(rlt, false); } @@ -1230,9 +1455,8 @@ public: int count = 0; pScanService->scanBlocklist.push_back(appId); pScanService->scanBlocklist.push_back(1); - // blockListScanTime now; branch. - bool rlt = pScanService->AllowScanByIntervalBlocklist(appId, blockListScanTime, lessThanIntervalCount, interval, - count); + bool rlt = pScanService->AllowScanByIntervalBlocklist( + appId, blockListScanTime, lessThanIntervalCount, interval, count); EXPECT_EQ(rlt, true); } @@ -1246,9 +1470,8 @@ public: int lessThanIntervalCount = 0; int interval = time(nullptr) + timeTest; int count = 0; - // if blockListScanTime 0 branch. - bool rlt = pScanService->AllowScanByIntervalBlocklist(appId, blockListScanTime, lessThanIntervalCount, interval, - count); + bool rlt = pScanService->AllowScanByIntervalBlocklist( + appId, blockListScanTime, lessThanIntervalCount, interval, count); EXPECT_EQ(rlt, true); } @@ -1262,9 +1485,8 @@ public: int interval = intervalTest; const int countTest = 2; int count = countTest; - // if lessThanIntervalCount count branch. - bool rlt = pScanService->AllowScanByIntervalBlocklist(appId, blockListScanTime, lessThanIntervalCount, interval, - count); + bool rlt = pScanService->AllowScanByIntervalBlocklist( + appId, blockListScanTime, lessThanIntervalCount, interval, count); EXPECT_EQ(rlt, true); } @@ -1278,9 +1500,8 @@ public: int interval = intervalTest; int count = 0; pScanService->scanBlocklist.push_back(appId); - // if find scanBlocklist.begin() branch. - bool rlt = pScanService->AllowScanByIntervalBlocklist(appId, blockListScanTime, lessThanIntervalCount, interval, - count); + bool rlt = pScanService->AllowScanByIntervalBlocklist( + appId, blockListScanTime, lessThanIntervalCount, interval, count); EXPECT_EQ(rlt, false); } @@ -1293,9 +1514,8 @@ public: const int intervalTest = 10; int interval = intervalTest; int count = 0; - // scanBlocklist (appId) branch. - bool rlt = pScanService->AllowScanByIntervalBlocklist(appId, blockListScanTime, lessThanIntervalCount, interval, - count); + bool rlt = pScanService->AllowScanByIntervalBlocklist( + appId, blockListScanTime, lessThanIntervalCount, interval, count); EXPECT_EQ(rlt, false); } }; @@ -1665,64 +1885,74 @@ HWTEST_F(ScanServiceTest, GetScanControlInfoFail, TestSize.Level1) GetScanControlInfoFail(); } -HWTEST_F(ScanServiceTest, GetScreenStateSuccess, TestSize.Level1) +HWTEST_F(ScanServiceTest, AllowExternScanSuccess, TestSize.Level1) +{ + AllowExternScanSuccess(); +} + +HWTEST_F(ScanServiceTest, AllowExternScanFail1, TestSize.Level1) +{ + AllowExternScanFail1(); +} + +HWTEST_F(ScanServiceTest, AllowSystemTimerScanSuccess, TestSize.Level1) { - GetScreenStateSuccess(); + AllowSystemTimerScanSuccess(); } -HWTEST_F(ScanServiceTest, SetOperateAppModeSuccess, TestSize.Level1) +HWTEST_F(ScanServiceTest, AllowPnoScanSuccess, TestSize.Level1) { - SetOperateAppModeSuccess(); + AllowPnoScanSuccess(); } -HWTEST_F(ScanServiceTest, GetOperateAppModeSuccess1, TestSize.Level1) +HWTEST_F(ScanServiceTest, AllowExternScanByThermal, TestSize.Level1) { - GetOperateAppModeSuccess1(); + AllowExternScanByThermal(); } -HWTEST_F(ScanServiceTest, GetOperateAppModeSuccess2, TestSize.Level1) +HWTEST_F(ScanServiceTest, AllowExternScanByForbidSuccess1, TestSize.Level1) { - GetOperateAppModeSuccess2(); + AllowExternScanByForbidSuccess1(); } -HWTEST_F(ScanServiceTest, GetOperateAppModeSuccess3, TestSize.Level1) +HWTEST_F(ScanServiceTest, AllowExternScanByForbidFail1, TestSize.Level1) { - GetOperateAppModeSuccess3(); + AllowExternScanByForbidFail1(); } -HWTEST_F(ScanServiceTest, GetOperateAppModeSuccess4, TestSize.Level1) +HWTEST_F(ScanServiceTest, AllowExternScanByForbidFail2, TestSize.Level1) { - GetOperateAppModeSuccess4(); + AllowExternScanByForbidFail2(); } -HWTEST_F(ScanServiceTest, GetOperateAppModeFail, TestSize.Level1) +HWTEST_F(ScanServiceTest, AllowExternScanByForbidFail3, TestSize.Level1) { - GetOperateAppModeFail(); + AllowExternScanByForbidFail3(); } -HWTEST_F(ScanServiceTest, AllowExternScanSuccess, TestSize.Level1) +HWTEST_F(ScanServiceTest, AllowExternScanByForbidFail4, TestSize.Level1) { - AllowExternScanSuccess(); + AllowExternScanByForbidFail4(); } -HWTEST_F(ScanServiceTest, AllowExternScanFail1, TestSize.Level1) +HWTEST_F(ScanServiceTest, AllowExternScanByForbidFail5, TestSize.Level1) { - AllowExternScanFail1(); + AllowExternScanByForbidFail5(); } -HWTEST_F(ScanServiceTest, AllowSystemTimerScanSuccess, TestSize.Level1) +HWTEST_F(ScanServiceTest, AllowExternScanByForbidFail6, TestSize.Level1) { - AllowSystemTimerScanSuccess(); + AllowExternScanByForbidFail6(); } -HWTEST_F(ScanServiceTest, AllowPnoScanSuccess, TestSize.Level1) +HWTEST_F(ScanServiceTest, AllowExternScanByForbidFail7, TestSize.Level1) { - AllowPnoScanSuccess(); + AllowExternScanByForbidFail7(); } -HWTEST_F(ScanServiceTest, AllowExternScanByForbidSuccess1, TestSize.Level1) +HWTEST_F(ScanServiceTest, AllowExternScanByForbidFail8, TestSize.Level1) { - AllowExternScanByForbidSuccess1(); + AllowExternScanByForbidFail8(); } HWTEST_F(ScanServiceTest, AllowExternScanByIntervaluccess, TestSize.Level1) @@ -1865,21 +2095,61 @@ HWTEST_F(ScanServiceTest, AllowScanDuringScanningSuccess, TestSize.Level1) AllowScanDuringScanningSuccess(); } +HWTEST_F(ScanServiceTest, AllowScanDuringScanningFail, TestSize.Level1) +{ + AllowScanDuringScanningFail(); +} + HWTEST_F(ScanServiceTest, AllowScanDuringScreenOffSuccess, TestSize.Level1) { AllowScanDuringScreenOffSuccess(); } +HWTEST_F(ScanServiceTest, AllowScanDuringScreenOffFail1, TestSize.Level1) +{ + AllowScanDuringScreenOffFail1(); +} + HWTEST_F(ScanServiceTest, AllowScanDuringStaSceneSuccess, TestSize.Level1) { AllowScanDuringStaSceneSuccess1(); } +HWTEST_F(ScanServiceTest, AllowScanDuringStaSceneFail1, TestSize.Level1) +{ + AllowScanDuringStaSceneFail1(); +} + +HWTEST_F(ScanServiceTest, AllowScanDuringStaSceneFail2, TestSize.Level1) +{ + AllowScanDuringStaSceneFail2(); +} + +HWTEST_F(ScanServiceTest, AllowScanDuringStaSceneFail3, TestSize.Level1) +{ + AllowScanDuringStaSceneFail3(); +} + HWTEST_F(ScanServiceTest, AllowScanDuringCustomSceneSuccess, TestSize.Level1) { AllowScanDuringCustomSceneSuccess(); } +HWTEST_F(ScanServiceTest, AllowScanDuringCustomSceneFail1, TestSize.Level1) +{ + AllowScanDuringCustomSceneFail1(); +} + +HWTEST_F(ScanServiceTest, AllowScanDuringCustomSceneFail2, TestSize.Level1) +{ + AllowScanDuringCustomSceneFail2(); +} + +HWTEST_F(ScanServiceTest, AllowScanDuringCustomSceneFail3, TestSize.Level1) +{ + AllowScanDuringCustomSceneFail3(); +} + HWTEST_F(ScanServiceTest, AllowExternScanByIntervalMode, TestSize.Level1) { AllowExternScanByIntervalMode(); @@ -2040,4 +2310,4 @@ HWTEST_F(ScanServiceTest, AllowScanByIntervalBlocklistFail2, TestSize.Level1) AllowScanByIntervalBlocklistFail2(); } } // namespace Wifi -} // namespace OHOS \ No newline at end of file +} // namespace OHOS diff --git a/tests/wifi_standard/wifi_framework/wifi_manage/wifi_scan/scan_state_machine_test.cpp b/wifi/test/wifi_standard/wifi_framework/wifi_manage/wifi_scan/scan_state_machine_test.cpp similarity index 99% rename from tests/wifi_standard/wifi_framework/wifi_manage/wifi_scan/scan_state_machine_test.cpp rename to wifi/test/wifi_standard/wifi_framework/wifi_manage/wifi_scan/scan_state_machine_test.cpp index bdaced736a010d5b1b158fa419d7049f70ebafde..ee9e3ad5c5ee7b7ca53c1c9eb8527b1560b59014 100644 --- a/tests/wifi_standard/wifi_framework/wifi_manage/wifi_scan/scan_state_machine_test.cpp +++ b/wifi/test/wifi_standard/wifi_framework/wifi_manage/wifi_scan/scan_state_machine_test.cpp @@ -655,7 +655,10 @@ public: { EXPECT_CALL(WifiStaHalInterface::GetInstance(), Scan(_)).WillRepeatedly(Return(WIFI_IDL_OPT_OK)); InterScanConfig interScanConfig; - pScanStateMachine->waitingScans.emplace(0, interScanConfig); + { + std::unique_lock guard(ScanStateMachine::lock); + pScanStateMachine->waitingScans.emplace(0, interScanConfig); + } pScanStateMachine->StartNewCommonScan(); } diff --git a/wifi/test/wifi_standard/wifi_framework/wifi_manage/wifi_sta/BUILD.gn b/wifi/test/wifi_standard/wifi_framework/wifi_manage/wifi_sta/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..861a1b181b3788300ce9c44c1879f55a5986368a --- /dev/null +++ b/wifi/test/wifi_standard/wifi_framework/wifi_manage/wifi_sta/BUILD.gn @@ -0,0 +1,131 @@ +# Copyright (C) 2021-2022 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import("//build/test.gni") +import("//foundation/communication/wifi/wifi/wifi.gni") +module_output_path = "wifi/sta_test" + +defines = [] +defines += [ "OHOS_WIFI_STA_TEST" ] + +config("module_private_config") { + visibility = [ ":*" ] + include_dirs = [ + "//commonlibrary/c_utils/base/include", + "$WIFI_ROOT_DIR/test/wifi_standard/wifi_framework/wifi_manage/wifi_sta", + ] +} + +ohos_unittest("wifi_sta_unittest") { + module_out_path = module_output_path + sources = [ + "$WIFI_ROOT_DIR/services/wifi_standard/wifi_framework/wifi_manage/common/handler.cpp", + "$WIFI_ROOT_DIR/services/wifi_standard/wifi_framework/wifi_manage/common/internal_message.cpp", + "$WIFI_ROOT_DIR/services/wifi_standard/wifi_framework/wifi_manage/common/message_queue.cpp", + "$WIFI_ROOT_DIR/services/wifi_standard/wifi_framework/wifi_manage/common/state.cpp", + "$WIFI_ROOT_DIR/services/wifi_standard/wifi_framework/wifi_manage/common/state_machine.cpp", + "$WIFI_ROOT_DIR/services/wifi_standard/wifi_framework/wifi_manage/wifi_sta/sta_auto_connect_service.cpp", + "$WIFI_ROOT_DIR/services/wifi_standard/wifi_framework/wifi_manage/wifi_sta/sta_interface.cpp", + "$WIFI_ROOT_DIR/services/wifi_standard/wifi_framework/wifi_manage/wifi_sta/sta_monitor.cpp", + "$WIFI_ROOT_DIR/services/wifi_standard/wifi_framework/wifi_manage/wifi_sta/sta_network_check.cpp", + "$WIFI_ROOT_DIR/services/wifi_standard/wifi_framework/wifi_manage/wifi_sta/sta_saved_device_appraisal.cpp", + "$WIFI_ROOT_DIR/services/wifi_standard/wifi_framework/wifi_manage/wifi_sta/sta_service.cpp", + "$WIFI_ROOT_DIR/services/wifi_standard/wifi_framework/wifi_manage/wifi_sta/sta_state_machine.cpp", + "$WIFI_ROOT_DIR/test/wifi_standard/wifi_framework/wifi_manage/wifi_common/Mock/mock_chip_capability.cpp", + "Mock/mock_dhcp_service.cpp", + "Mock/mock_if_config.cpp", + "Mock/mock_mac_address.cpp", + "Mock/mock_sta_auto_connect_service.cpp", + "Mock/mock_sta_network_check.cpp", + "Mock/mock_sta_state_machine.cpp", + "Mock/mock_wifi_chip_hal_interface.cpp", + "Mock/mock_wifi_manager.cpp", + "Mock/mock_wifi_settings.cpp", + "Mock/mock_wifi_sta_hal_interface.cpp", + "Mock/mock_wifi_supplicant_hal_interface.cpp", + "global_test.cpp", + "sta_auto_connect_service_test.cpp", + "sta_interface_test.cpp", + "sta_monitor_test.cpp", + "sta_network_check_test.cpp", + "sta_saved_device_appraisal_test.cpp", + "sta_service_test.cpp", + "sta_state_machine_test.cpp", + ] + + include_dirs = [ + "./", + "./Mock", + "$WIFI_ROOT_DIR/services/wifi_standard/wifi_framework/wifi_manage/wifi_sta/net_conf", + "$WIFI_ROOT_DIR/frameworks/native/include", + "$WIFI_ROOT_DIR/frameworks/native/interfaces", + "$WIFI_ROOT_DIR/services/wifi_standard/interface", + "$WIFI_ROOT_DIR/services/wifi_standard/ipc_framework/cRPC/include", + "$WIFI_ROOT_DIR/services/wifi_standard/wifi_framework/wifi_toolkit/include", + "$WIFI_ROOT_DIR/services/wifi_standard/wifi_framework/wifi_toolkit/net_helper", + "$WIFI_ROOT_DIR/services/wifi_standard/wifi_framework/wifi_toolkit/log", + "$WIFI_ROOT_DIR/services/wifi_standard/wifi_framework/wifi_toolkit/config", + "$WIFI_ROOT_DIR/services/wifi_standard/wifi_framework/wifi_toolkit/utils", + "$WIFI_ROOT_DIR/services/wifi_standard/wifi_framework/wifi_manage/common", + "$WIFI_ROOT_DIR/services/wifi_standard/wifi_framework/wifi_manage", + "$WIFI_ROOT_DIR/services/wifi_standard/wifi_framework/wifi_manage/idl_client", + "$WIFI_ROOT_DIR/services/wifi_standard/wifi_framework/wifi_manage/idl_client/idl_interface", + "$WIFI_ROOT_DIR/services/wifi_standard/wifi_framework/wifi_manage/wifi_ap", + "$WIFI_ROOT_DIR/test/wifi_standard/wifi_framework/wifi_manage/wifi_common/Mock", + "$WIFI_ROOT_DIR/services/wifi_standard/wifi_framework/wifi_manage/wifi_p2p", + "$WIFI_ROOT_DIR/services/wifi_standard/wifi_framework/wifi_manage/wifi_scan", + "$WIFI_ROOT_DIR/services/wifi_standard/wifi_framework/wifi_manage/wifi_sta", + "$WIFI_ROOT_DIR/services/wifi_standard/ipc_framework/cRPC/include", + "$DHCP_ROOT_DIR/services/mgr_service/include", + "$DHCP_ROOT_DIR/interfaces/inner_api/include", + "$DHCP_ROOT_DIR/interfaces/inner_api/interfaces", + "//third_party/googletest/googlemock/include", + "//third_party/googletest/googletest/include", + "//base/notification/ces_standard/cesfwk/kits/native/include", + "//commonlibrary/c_utils/base/include", + "//foundation/communication/ipc/interfaces/innerkits/ipc_core/include", + "//base/hiviewdfx/hilog/interfaces/native/innerkits/include", + "//foundation/arkui/ace_engine/frameworks/base/utils", + "//foundation/arkui/ace_engine/frameworks", + "//foundation/systemabilitymgr/safwk/interfaces/innerkits/safwk/", + "//foundation/ability/ability_lite/interfaces/kits/want_lite/", + "$WIFI_ROOT_DIR/utils/inc", + "$WIFI_ROOT_DIR/services/wifi_standard/wifi_framework/wifi_manage/wifi_common", + "$WIFI_ROOT_DIR/services/wifi_standard/include", + ] + + deps = [ + "$DHCP_ROOT_DIR/services/mgr_service:dhcp_manager_service", + "$WIFI_ROOT_DIR/services/wifi_standard/wifi_framework/wifi_manage:wifi_manager_service", + "$WIFI_ROOT_DIR/services/wifi_standard/wifi_framework/wifi_manage/idl_client:wifi_idl_client", + "$WIFI_ROOT_DIR/services/wifi_standard/wifi_framework/wifi_manage/wifi_common:wifi_common_service", + "$WIFI_ROOT_DIR/services/wifi_standard/wifi_framework/wifi_toolkit:wifi_toolkit", + "$WIFI_ROOT_DIR/utils:wifi_utils", + "//third_party/googletest:gmock_main", + "//third_party/googletest:gtest_main", + ] + external_deps = [ + "ability_base:want", + "c_utils:utils", + "hiviewdfx_hilog_native:libhilog", + "netmanager_base:net_conn_manager_if", + ] + defines += [ "AP_INSTANCE_MAX_NUM=$wifi_feature_with_ap_num" ] + part_name = "wifi" + subsystem_name = "communication" +} + +group("unittest") { + testonly = true + deps = [ ":wifi_sta_unittest" ] +} diff --git a/tests/wifi_standard/wifi_framework/wifi_manage/wifi_sta/Mock/mock_device_appraisal.h b/wifi/test/wifi_standard/wifi_framework/wifi_manage/wifi_sta/Mock/mock_device_appraisal.h similarity index 100% rename from tests/wifi_standard/wifi_framework/wifi_manage/wifi_sta/Mock/mock_device_appraisal.h rename to wifi/test/wifi_standard/wifi_framework/wifi_manage/wifi_sta/Mock/mock_device_appraisal.h diff --git a/tests/wifi_standard/wifi_framework/wifi_manage/wifi_sta/Mock/mock_dhcp_service.cpp b/wifi/test/wifi_standard/wifi_framework/wifi_manage/wifi_sta/Mock/mock_dhcp_service.cpp similarity index 100% rename from tests/wifi_standard/wifi_framework/wifi_manage/wifi_sta/Mock/mock_dhcp_service.cpp rename to wifi/test/wifi_standard/wifi_framework/wifi_manage/wifi_sta/Mock/mock_dhcp_service.cpp diff --git a/tests/wifi_standard/wifi_framework/wifi_manage/wifi_sta/Mock/mock_dhcp_service.h b/wifi/test/wifi_standard/wifi_framework/wifi_manage/wifi_sta/Mock/mock_dhcp_service.h similarity index 100% rename from tests/wifi_standard/wifi_framework/wifi_manage/wifi_sta/Mock/mock_dhcp_service.h rename to wifi/test/wifi_standard/wifi_framework/wifi_manage/wifi_sta/Mock/mock_dhcp_service.h diff --git a/tests/wifi_standard/wifi_framework/wifi_manage/wifi_sta/Mock/mock_if_config.cpp b/wifi/test/wifi_standard/wifi_framework/wifi_manage/wifi_sta/Mock/mock_if_config.cpp similarity index 100% rename from tests/wifi_standard/wifi_framework/wifi_manage/wifi_sta/Mock/mock_if_config.cpp rename to wifi/test/wifi_standard/wifi_framework/wifi_manage/wifi_sta/Mock/mock_if_config.cpp diff --git a/tests/wifi_standard/wifi_framework/wifi_manage/wifi_sta/Mock/mock_if_config.h b/wifi/test/wifi_standard/wifi_framework/wifi_manage/wifi_sta/Mock/mock_if_config.h similarity index 88% rename from tests/wifi_standard/wifi_framework/wifi_manage/wifi_sta/Mock/mock_if_config.h rename to wifi/test/wifi_standard/wifi_framework/wifi_manage/wifi_sta/Mock/mock_if_config.h index 0d27463493ef9199be6bdbfe5f3ee0a6603804f8..b6d3b1270ff84c142f88875ab87b291c41db64f0 100644 --- a/tests/wifi_standard/wifi_framework/wifi_manage/wifi_sta/Mock/mock_if_config.h +++ b/wifi/test/wifi_standard/wifi_framework/wifi_manage/wifi_sta/Mock/mock_if_config.h @@ -1,5 +1,5 @@ /* - * Copyright (C) 2021 Huawei Device Co., Ltd. + * Copyright (C) 2021-2022 Huawei Device Co., Ltd. * 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 @@ -20,10 +20,16 @@ namespace OHOS { namespace Wifi { +typedef enum IpType { + IPTYPE_IPV4, + IPTYPE_IPV6, + IPTYPE_MIX, + IPTYPE_BUTT, +} IpType; + class MockIfConfig { public: virtual ~MockIfConfig() = default; - virtual int SetIfAddr(const DhcpResult &dhcpInfo, int ipType) = 0; virtual void SetProxy(bool isAuto, const std::string &proxy, const std::string &port, const std::string &noProxys, const std::string &pac) = 0; virtual void FlushIpAddr(const std::string &ifName, const int &ipType) = 0; @@ -34,7 +40,6 @@ public: IfConfig() = default; ~IfConfig() = default; static IfConfig &GetInstance(void); - MOCK_METHOD2(SetIfAddr, int(const DhcpResult &dhcpInfo, int ipType)); MOCK_METHOD5(SetProxy, void(bool isAuto, const std::string &proxy, const std::string &port, const std::string &noProxys, const std::string &pac)); MOCK_METHOD2(FlushIpAddr, void(const std::string &ifName, const int &ipType)); diff --git a/tests/wifi_standard/wifi_framework/wifi_manage/wifi_sta/Mock/mock_mac_address.cpp b/wifi/test/wifi_standard/wifi_framework/wifi_manage/wifi_sta/Mock/mock_mac_address.cpp similarity index 100% rename from tests/wifi_standard/wifi_framework/wifi_manage/wifi_sta/Mock/mock_mac_address.cpp rename to wifi/test/wifi_standard/wifi_framework/wifi_manage/wifi_sta/Mock/mock_mac_address.cpp diff --git a/tests/wifi_standard/wifi_framework/wifi_manage/wifi_sta/Mock/mock_mac_address.h b/wifi/test/wifi_standard/wifi_framework/wifi_manage/wifi_sta/Mock/mock_mac_address.h similarity index 100% rename from tests/wifi_standard/wifi_framework/wifi_manage/wifi_sta/Mock/mock_mac_address.h rename to wifi/test/wifi_standard/wifi_framework/wifi_manage/wifi_sta/Mock/mock_mac_address.h diff --git a/tests/wifi_standard/wifi_framework/wifi_manage/wifi_sta/Mock/mock_sta_auto_connect_service.cpp b/wifi/test/wifi_standard/wifi_framework/wifi_manage/wifi_sta/Mock/mock_sta_auto_connect_service.cpp similarity index 100% rename from tests/wifi_standard/wifi_framework/wifi_manage/wifi_sta/Mock/mock_sta_auto_connect_service.cpp rename to wifi/test/wifi_standard/wifi_framework/wifi_manage/wifi_sta/Mock/mock_sta_auto_connect_service.cpp diff --git a/tests/wifi_standard/wifi_framework/wifi_manage/wifi_sta/Mock/mock_sta_auto_connect_service.h b/wifi/test/wifi_standard/wifi_framework/wifi_manage/wifi_sta/Mock/mock_sta_auto_connect_service.h similarity index 100% rename from tests/wifi_standard/wifi_framework/wifi_manage/wifi_sta/Mock/mock_sta_auto_connect_service.h rename to wifi/test/wifi_standard/wifi_framework/wifi_manage/wifi_sta/Mock/mock_sta_auto_connect_service.h diff --git a/tests/wifi_standard/wifi_framework/wifi_manage/wifi_sta/Mock/mock_sta_monitor.h b/wifi/test/wifi_standard/wifi_framework/wifi_manage/wifi_sta/Mock/mock_sta_monitor.h similarity index 100% rename from tests/wifi_standard/wifi_framework/wifi_manage/wifi_sta/Mock/mock_sta_monitor.h rename to wifi/test/wifi_standard/wifi_framework/wifi_manage/wifi_sta/Mock/mock_sta_monitor.h diff --git a/tests/wifi_standard/wifi_framework/wifi_manage/wifi_sta/Mock/mock_sta_network_check.cpp b/wifi/test/wifi_standard/wifi_framework/wifi_manage/wifi_sta/Mock/mock_sta_network_check.cpp similarity index 86% rename from tests/wifi_standard/wifi_framework/wifi_manage/wifi_sta/Mock/mock_sta_network_check.cpp rename to wifi/test/wifi_standard/wifi_framework/wifi_manage/wifi_sta/Mock/mock_sta_network_check.cpp index 621dd0be1030119c9910781a58d75302673b7a40..fbc155b3bc62bb1e49c308cee9daf518cd191d01 100644 --- a/tests/wifi_standard/wifi_framework/wifi_manage/wifi_sta/Mock/mock_sta_network_check.cpp +++ b/wifi/test/wifi_standard/wifi_framework/wifi_manage/wifi_sta/Mock/mock_sta_network_check.cpp @@ -1,5 +1,5 @@ /* - * Copyright (C) 2021 Huawei Device Co., Ltd. + * Copyright (C) 2021-2022 Huawei Device Co., Ltd. * 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 @@ -32,5 +32,9 @@ void MockStaNetworkCheck::StopNetCheckThread() { WIFI_LOGD("Enter MockDhcpService::[%{public}s].", __FUNCTION__); } +void MockStaNetworkCheck::ExitNetCheckThread() +{ + WIFI_LOGD("Enter ExitNetCheckThread::[%{public}s].", __FUNCTION__); +} } // namespace Wifi } // namespace OHOS \ No newline at end of file diff --git a/tests/wifi_standard/wifi_framework/wifi_manage/wifi_sta/Mock/mock_sta_network_check.h b/wifi/test/wifi_standard/wifi_framework/wifi_manage/wifi_sta/Mock/mock_sta_network_check.h similarity index 92% rename from tests/wifi_standard/wifi_framework/wifi_manage/wifi_sta/Mock/mock_sta_network_check.h rename to wifi/test/wifi_standard/wifi_framework/wifi_manage/wifi_sta/Mock/mock_sta_network_check.h index 81c1607b38f62bbecea2a47ccc9f58a3bbe2bd39..dbd290dafc3a16b23943b65c12fb64201d0394f4 100644 --- a/tests/wifi_standard/wifi_framework/wifi_manage/wifi_sta/Mock/mock_sta_network_check.h +++ b/wifi/test/wifi_standard/wifi_framework/wifi_manage/wifi_sta/Mock/mock_sta_network_check.h @@ -1,5 +1,5 @@ /* - * Copyright (C) 2021 Huawei Device Co., Ltd. + * Copyright (C) 2021-2022 Huawei Device Co., Ltd. * 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 @@ -12,6 +12,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + #ifndef OHOS_MOCK_STANETWORKCHECK_H #define OHOS_MOCK_STANETWORKCHECK_H #include @@ -27,6 +28,7 @@ public: ErrCode InitNetCheckThread() override; void SignalNetCheckThread() override; void StopNetCheckThread() override; + void ExitNetCheckThread() override; }; } // namespace OHOS } // namespace OHOS diff --git a/tests/wifi_standard/wifi_framework/wifi_manage/wifi_sta/Mock/mock_sta_service.h b/wifi/test/wifi_standard/wifi_framework/wifi_manage/wifi_sta/Mock/mock_sta_service.h similarity index 100% rename from tests/wifi_standard/wifi_framework/wifi_manage/wifi_sta/Mock/mock_sta_service.h rename to wifi/test/wifi_standard/wifi_framework/wifi_manage/wifi_sta/Mock/mock_sta_service.h diff --git a/tests/wifi_standard/wifi_framework/wifi_manage/wifi_sta/Mock/mock_sta_state_machine.cpp b/wifi/test/wifi_standard/wifi_framework/wifi_manage/wifi_sta/Mock/mock_sta_state_machine.cpp similarity index 100% rename from tests/wifi_standard/wifi_framework/wifi_manage/wifi_sta/Mock/mock_sta_state_machine.cpp rename to wifi/test/wifi_standard/wifi_framework/wifi_manage/wifi_sta/Mock/mock_sta_state_machine.cpp diff --git a/tests/wifi_standard/wifi_framework/wifi_manage/wifi_sta/Mock/mock_sta_state_machine.h b/wifi/test/wifi_standard/wifi_framework/wifi_manage/wifi_sta/Mock/mock_sta_state_machine.h similarity index 100% rename from tests/wifi_standard/wifi_framework/wifi_manage/wifi_sta/Mock/mock_sta_state_machine.h rename to wifi/test/wifi_standard/wifi_framework/wifi_manage/wifi_sta/Mock/mock_sta_state_machine.h diff --git a/tests/wifi_standard/wifi_framework/wifi_manage/wifi_sta/Mock/mock_wifi_chip_hal_interface.cpp b/wifi/test/wifi_standard/wifi_framework/wifi_manage/wifi_sta/Mock/mock_wifi_chip_hal_interface.cpp similarity index 100% rename from tests/wifi_standard/wifi_framework/wifi_manage/wifi_sta/Mock/mock_wifi_chip_hal_interface.cpp rename to wifi/test/wifi_standard/wifi_framework/wifi_manage/wifi_sta/Mock/mock_wifi_chip_hal_interface.cpp diff --git a/tests/wifi_standard/wifi_framework/wifi_manage/wifi_sta/Mock/mock_wifi_chip_hal_interface.h b/wifi/test/wifi_standard/wifi_framework/wifi_manage/wifi_sta/Mock/mock_wifi_chip_hal_interface.h similarity index 100% rename from tests/wifi_standard/wifi_framework/wifi_manage/wifi_sta/Mock/mock_wifi_chip_hal_interface.h rename to wifi/test/wifi_standard/wifi_framework/wifi_manage/wifi_sta/Mock/mock_wifi_chip_hal_interface.h diff --git a/tests/wifi_standard/wifi_framework/wifi_manage/wifi_sta/Mock/mock_wifi_manager.cpp b/wifi/test/wifi_standard/wifi_framework/wifi_manage/wifi_sta/Mock/mock_wifi_manager.cpp similarity index 100% rename from tests/wifi_standard/wifi_framework/wifi_manage/wifi_sta/Mock/mock_wifi_manager.cpp rename to wifi/test/wifi_standard/wifi_framework/wifi_manage/wifi_sta/Mock/mock_wifi_manager.cpp diff --git a/tests/wifi_standard/wifi_framework/wifi_manage/wifi_sta/Mock/mock_wifi_manager.h b/wifi/test/wifi_standard/wifi_framework/wifi_manage/wifi_sta/Mock/mock_wifi_manager.h similarity index 100% rename from tests/wifi_standard/wifi_framework/wifi_manage/wifi_sta/Mock/mock_wifi_manager.h rename to wifi/test/wifi_standard/wifi_framework/wifi_manage/wifi_sta/Mock/mock_wifi_manager.h diff --git a/tests/wifi_standard/wifi_framework/wifi_manage/wifi_sta/Mock/mock_wifi_settings.cpp b/wifi/test/wifi_standard/wifi_framework/wifi_manage/wifi_sta/Mock/mock_wifi_settings.cpp similarity index 100% rename from tests/wifi_standard/wifi_framework/wifi_manage/wifi_sta/Mock/mock_wifi_settings.cpp rename to wifi/test/wifi_standard/wifi_framework/wifi_manage/wifi_sta/Mock/mock_wifi_settings.cpp diff --git a/tests/wifi_standard/wifi_framework/wifi_manage/wifi_sta/Mock/mock_wifi_settings.h b/wifi/test/wifi_standard/wifi_framework/wifi_manage/wifi_sta/Mock/mock_wifi_settings.h similarity index 96% rename from tests/wifi_standard/wifi_framework/wifi_manage/wifi_sta/Mock/mock_wifi_settings.h rename to wifi/test/wifi_standard/wifi_framework/wifi_manage/wifi_sta/Mock/mock_wifi_settings.h index eb1aa29b2b20a8425eab075351a3bda633436315..c70b3a0fcc56930538086cbbac39163ade3076e7 100644 --- a/tests/wifi_standard/wifi_framework/wifi_manage/wifi_sta/Mock/mock_wifi_settings.h +++ b/wifi/test/wifi_standard/wifi_framework/wifi_manage/wifi_sta/Mock/mock_wifi_settings.h @@ -65,6 +65,8 @@ public: virtual int GetScoretacticsSecurityScore() = 0; virtual std::string GetStrDnsBak() const = 0; virtual int GetScanInfoList(std::vector &results) = 0; + virtual std::string GetConnectTimeoutBssid() = 0; + virtual int SetConnectTimeoutBssid(std::string &bssid) = 0; }; class WifiSettings : public MockWifiSettings { @@ -114,8 +116,10 @@ public: MOCK_METHOD0(GetScoretacticsSecurityScore, int()); MOCK_CONST_METHOD0(GetStrDnsBak, std::string()); MOCK_METHOD1(GetScanInfoList, int(std::vector &results)); + MOCK_METHOD0(GetConnectTimeoutBssid, std::string()); + MOCK_METHOD1(SetConnectTimeoutBssid, int(std::string &bssid)); }; } // namespace OHOS } // namespace Wifi -#endif \ No newline at end of file +#endif diff --git a/tests/wifi_standard/wifi_framework/wifi_manage/wifi_sta/Mock/mock_wifi_sta_hal_interface.cpp b/wifi/test/wifi_standard/wifi_framework/wifi_manage/wifi_sta/Mock/mock_wifi_sta_hal_interface.cpp similarity index 100% rename from tests/wifi_standard/wifi_framework/wifi_manage/wifi_sta/Mock/mock_wifi_sta_hal_interface.cpp rename to wifi/test/wifi_standard/wifi_framework/wifi_manage/wifi_sta/Mock/mock_wifi_sta_hal_interface.cpp diff --git a/tests/wifi_standard/wifi_framework/wifi_manage/wifi_sta/Mock/mock_wifi_sta_hal_interface.h b/wifi/test/wifi_standard/wifi_framework/wifi_manage/wifi_sta/Mock/mock_wifi_sta_hal_interface.h similarity index 100% rename from tests/wifi_standard/wifi_framework/wifi_manage/wifi_sta/Mock/mock_wifi_sta_hal_interface.h rename to wifi/test/wifi_standard/wifi_framework/wifi_manage/wifi_sta/Mock/mock_wifi_sta_hal_interface.h diff --git a/tests/wifi_standard/wifi_framework/wifi_manage/wifi_sta/Mock/mock_wifi_supplicant_hal_interface.cpp b/wifi/test/wifi_standard/wifi_framework/wifi_manage/wifi_sta/Mock/mock_wifi_supplicant_hal_interface.cpp similarity index 100% rename from tests/wifi_standard/wifi_framework/wifi_manage/wifi_sta/Mock/mock_wifi_supplicant_hal_interface.cpp rename to wifi/test/wifi_standard/wifi_framework/wifi_manage/wifi_sta/Mock/mock_wifi_supplicant_hal_interface.cpp diff --git a/tests/wifi_standard/wifi_framework/wifi_manage/wifi_sta/Mock/mock_wifi_supplicant_hal_interface.h b/wifi/test/wifi_standard/wifi_framework/wifi_manage/wifi_sta/Mock/mock_wifi_supplicant_hal_interface.h similarity index 88% rename from tests/wifi_standard/wifi_framework/wifi_manage/wifi_sta/Mock/mock_wifi_supplicant_hal_interface.h rename to wifi/test/wifi_standard/wifi_framework/wifi_manage/wifi_sta/Mock/mock_wifi_supplicant_hal_interface.h index 8b2f9ab6505949f738caffa3bffe7579d0f63469..35a9ab1919a0d72caf84974fa9d04e00ae980a84 100644 --- a/tests/wifi_standard/wifi_framework/wifi_manage/wifi_sta/Mock/mock_wifi_supplicant_hal_interface.h +++ b/wifi/test/wifi_standard/wifi_framework/wifi_manage/wifi_sta/Mock/mock_wifi_supplicant_hal_interface.h @@ -1,5 +1,5 @@ /* - * Copyright (C) 2021 Huawei Device Co., Ltd. + * Copyright (C) 2021-2022 Huawei Device Co., Ltd. * 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 @@ -27,7 +27,7 @@ public: virtual ~MockWifiSupplicantHalInterface() = default; virtual WifiErrorNo StartSupplicant(void) = 0; virtual WifiErrorNo WpaSetCountryCode(const std::string &countryCode) const = 0; - + virtual WifiErrorNo WpaSetSuspendMode(bool mode) const = 0; }; class WifiSupplicantHalInterface : public MockWifiSupplicantHalInterface { @@ -37,6 +37,7 @@ public: public: MOCK_METHOD0(StartSupplicant, WifiErrorNo()); MOCK_CONST_METHOD1(WpaSetCountryCode, WifiErrorNo(const std::string &countryCode)); + MOCK_CONST_METHOD1(WpaSetSuspendMode, WifiErrorNo(bool mode)); }; } // namespace OHOS } // namespace OHOS diff --git a/tests/wifi_standard/wifi_framework/wifi_manage/wifi_sta/global_test.cpp b/wifi/test/wifi_standard/wifi_framework/wifi_manage/wifi_sta/global_test.cpp similarity index 100% rename from tests/wifi_standard/wifi_framework/wifi_manage/wifi_sta/global_test.cpp rename to wifi/test/wifi_standard/wifi_framework/wifi_manage/wifi_sta/global_test.cpp diff --git a/tests/wifi_standard/wifi_framework/wifi_manage/wifi_sta/global_test.h b/wifi/test/wifi_standard/wifi_framework/wifi_manage/wifi_sta/global_test.h similarity index 100% rename from tests/wifi_standard/wifi_framework/wifi_manage/wifi_sta/global_test.h rename to wifi/test/wifi_standard/wifi_framework/wifi_manage/wifi_sta/global_test.h diff --git a/tests/wifi_standard/wifi_framework/wifi_manage/wifi_sta/sta_auto_connect_service_test.cpp b/wifi/test/wifi_standard/wifi_framework/wifi_manage/wifi_sta/sta_auto_connect_service_test.cpp similarity index 98% rename from tests/wifi_standard/wifi_framework/wifi_manage/wifi_sta/sta_auto_connect_service_test.cpp rename to wifi/test/wifi_standard/wifi_framework/wifi_manage/wifi_sta/sta_auto_connect_service_test.cpp index e0c4c8d808d4d4b28cfed160b67faaed0566abe6..b90aca44ed4a96d18ed5200c4e2449f06c42514a 100644 --- a/tests/wifi_standard/wifi_framework/wifi_manage/wifi_sta/sta_auto_connect_service_test.cpp +++ b/wifi/test/wifi_standard/wifi_framework/wifi_manage/wifi_sta/sta_auto_connect_service_test.cpp @@ -1,5 +1,5 @@ /* - * Copyright (C) 2021 Huawei Device Co., Ltd. + * Copyright (C) 2021-2022 Huawei Device Co., Ltd. * 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 @@ -154,7 +154,6 @@ public: void RoamingEncryptionModeCheckFail2(); void RoamingEncryptionModeCheckFail3(); void RoamingEncryptionModeCheckFail4(); - void RefreshConfigDeviceSuccess(); void RoamingSelectionSuccess1(); void RoamingSelectionFail1(); void RoamingSelectionFail2(); @@ -440,7 +439,6 @@ void StaAutoConnectServiceTest::OnScanResultsReadyHandlerFail6() EXPECT_CALL(WifiSettings::GetInstance(), GetWhetherToAllowNetworkSwitchover()) .Times(AtLeast(1)) .WillOnce(Return(true)); - EXPECT_CALL(WifiSettings::GetInstance(), GetDeviceConfig(_)).Times(AtLeast(1)); EXPECT_CALL(*(pMockDeviceAppraisal), DeviceAppraisals(_, _, _)).WillOnce(Return(WIFI_OPT_FAILED)); pStaAutoConnectService->OnScanInfosReadyHandler(scanInfos); @@ -764,7 +762,9 @@ void StaAutoConnectServiceTest::SetRoamBlockedBssidFirmwareSuccess() std::string bssid = "2a:76:93:47:e2:8a"; blockedBssids.push_back(bssid); - EXPECT_CALL(WifiStaHalInterface::GetInstance(), SetRoamConfig(_)).WillOnce(Return(WIFI_IDL_OPT_OK)); + EXPECT_CALL(WifiStaHalInterface::GetInstance(), SetRoamConfig(_)) + .WillOnce(Return(WIFI_IDL_OPT_OK)) + .WillRepeatedly(Return(WIFI_IDL_OPT_OK)); EXPECT_TRUE(pStaAutoConnectService->SetRoamBlockedBssidFirmware(blockedBssids) == true); } @@ -774,7 +774,8 @@ void StaAutoConnectServiceTest::SetRoamBlockedBssidFirmwareFail1() std::string bssid = "2a:76:93:47:e2:8a"; blockedBssids.push_back(bssid); - EXPECT_CALL(WifiStaHalInterface::GetInstance(), SetRoamConfig(_)).WillOnce(Return(WIFI_IDL_OPT_FAILED)); + ON_CALL(WifiStaHalInterface::GetInstance(), SetRoamConfig(_)) + .WillByDefault(Return(WIFI_IDL_OPT_FAILED)); EXPECT_TRUE(pStaAutoConnectService->SetRoamBlockedBssidFirmware(blockedBssids) == false); } @@ -843,8 +844,10 @@ void StaAutoConnectServiceTest::ConnectElectedDeviceFail1() GetWifiLinkedInfo(info); GetWifiDeviceConfig(deviceConfig); info.detailedState = DetailedState::INVALID; - - EXPECT_CALL(WifiSettings::GetInstance(), GetLinkedInfo(_)).WillOnce(DoAll(SetArgReferee<0>(info), Return(0))); + EXPECT_CALL(WifiSettings::GetInstance(), GetLinkedInfo(_)) + .Times(AtLeast(0)) + .WillOnce(DoAll(SetArgReferee<0>(info), Return(0))) + .WillRepeatedly(DoAll(SetArgReferee<0>(info), Return(0))); pStaAutoConnectService->ConnectElectedDevice(deviceConfig); } @@ -1183,11 +1186,6 @@ void StaAutoConnectServiceTest::RoamingEncryptionModeCheckFail4() EXPECT_TRUE(pStaAutoConnectService->RoamingEncryptionModeCheck(deviceConfig, scanInfo, info) == false); } -void StaAutoConnectServiceTest::RefreshConfigDeviceSuccess() -{ - pStaAutoConnectService->RefreshConfigDevice(); -} - void StaAutoConnectServiceTest::RoamingSelectionSuccess1() { WifiDeviceConfig deviceConfig; @@ -1201,9 +1199,9 @@ void StaAutoConnectServiceTest::RoamingSelectionSuccess1() info.connState = ConnState::CONNECTED; scanInfos[0].securityType = WifiSecurity::WEP; scanInfos[0].rssi = 8; - scanInfos[0].ssid = "huawei"; + scanInfos[0].ssid = "ohos"; scanInfos[0].bssid = "2a:76:93:47:e2:8e"; - info.ssid = "huawei"; + info.ssid = "ohos"; info.bssid = "2a:76:93:47:e2:8b"; info.rssi = 1; int indexType = DEVICE_CONFIG_INDEX_SSID; @@ -1667,11 +1665,6 @@ HWTEST_F(StaAutoConnectServiceTest, RoamingEncryptionModeCheckFail4, TestSize.Le RoamingEncryptionModeCheckFail4(); } -HWTEST_F(StaAutoConnectServiceTest, RefreshConfigDeviceSuccess, TestSize.Level1) -{ - RefreshConfigDeviceSuccess(); -} - HWTEST_F(StaAutoConnectServiceTest, RoamingSelectionSuccess1, TestSize.Level1) { RoamingSelectionSuccess1(); diff --git a/tests/wifi_standard/wifi_framework/wifi_manage/wifi_sta/sta_interface_test.cpp b/wifi/test/wifi_standard/wifi_framework/wifi_manage/wifi_sta/sta_interface_test.cpp similarity index 100% rename from tests/wifi_standard/wifi_framework/wifi_manage/wifi_sta/sta_interface_test.cpp rename to wifi/test/wifi_standard/wifi_framework/wifi_manage/wifi_sta/sta_interface_test.cpp diff --git a/tests/wifi_standard/wifi_framework/wifi_manage/wifi_sta/sta_monitor_test.cpp b/wifi/test/wifi_standard/wifi_framework/wifi_manage/wifi_sta/sta_monitor_test.cpp similarity index 100% rename from tests/wifi_standard/wifi_framework/wifi_manage/wifi_sta/sta_monitor_test.cpp rename to wifi/test/wifi_standard/wifi_framework/wifi_manage/wifi_sta/sta_monitor_test.cpp diff --git a/tests/wifi_standard/wifi_framework/wifi_manage/wifi_sta/sta_network_check_test.cpp b/wifi/test/wifi_standard/wifi_framework/wifi_manage/wifi_sta/sta_network_check_test.cpp similarity index 95% rename from tests/wifi_standard/wifi_framework/wifi_manage/wifi_sta/sta_network_check_test.cpp rename to wifi/test/wifi_standard/wifi_framework/wifi_manage/wifi_sta/sta_network_check_test.cpp index 1ee7a1ef87ebccfc47fe84d2841b05a0b1e4e75b..5bb12b3428009837a74656d7092ff2f3d95d97f4 100644 --- a/tests/wifi_standard/wifi_framework/wifi_manage/wifi_sta/sta_network_check_test.cpp +++ b/wifi/test/wifi_standard/wifi_framework/wifi_manage/wifi_sta/sta_network_check_test.cpp @@ -1,5 +1,5 @@ /* - * Copyright (C) 2021 Huawei Device Co., Ltd. + * Copyright (C) 2021-2022 Huawei Device Co., Ltd. * 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 @@ -12,10 +12,10 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -#include "sta_network_check.h" #include #include +#include "sta_network_check.h" using ::testing::ext::TestSize; @@ -43,7 +43,7 @@ public: public: std::unique_ptr pStaNetworkCheck; - NetStateHandler handle; + NetStateHandler handle = nullptr; }; void StaNetworkCheckTest::SignalNetCheckThreadSuccess() diff --git a/tests/wifi_standard/wifi_framework/wifi_manage/wifi_sta/sta_saved_device_appraisal_test.cpp b/wifi/test/wifi_standard/wifi_framework/wifi_manage/wifi_sta/sta_saved_device_appraisal_test.cpp similarity index 94% rename from tests/wifi_standard/wifi_framework/wifi_manage/wifi_sta/sta_saved_device_appraisal_test.cpp rename to wifi/test/wifi_standard/wifi_framework/wifi_manage/wifi_sta/sta_saved_device_appraisal_test.cpp index 8b99c6e29ac40c8e605c2974921a1d0265bb3447..d5660d21c2831f2342832bd74fd1a3a7e5b47c25 100644 --- a/tests/wifi_standard/wifi_framework/wifi_manage/wifi_sta/sta_saved_device_appraisal_test.cpp +++ b/wifi/test/wifi_standard/wifi_framework/wifi_manage/wifi_sta/sta_saved_device_appraisal_test.cpp @@ -28,6 +28,7 @@ using ::testing::AtLeast; using ::testing::DoAll; using ::testing::Eq; using ::testing::Return; +using ::testing::ReturnRef; using ::testing::SetArgReferee; using ::testing::StrEq; using ::testing::TypedEq; @@ -66,7 +67,6 @@ public: void AppraiseDeviceQualitySuccess1(); void AppraiseDeviceQualitySuccess2(); void WhetherSkipDeviceSuccess1(); - void WhetherSkipDeviceSuccess2(); void WhetherSkipDeviceFail1(); public: @@ -130,6 +130,10 @@ void StaSavedDeviceAppraisalTest::SaveNetworkEvaluatorSuccess1() .WillOnce(DoAll(SetArgReferee<2>(deviceConfig), Return(0))); EXPECT_CALL(WifiSettings::GetInstance(), GetSignalLevel(_, _)).Times(AtLeast(0)); EXPECT_CALL(WifiSettings::GetInstance(), GetUserLastSelectedNetworkId()).Times(AtLeast(1)).WillOnce(Return(0)); + EXPECT_CALL(WifiSettings::GetInstance(), GetConnectTimeoutBssid()) + .Times(AtLeast(1)) + .WillOnce(Return("")) + .WillRepeatedly(Return("")); EXPECT_TRUE(pStaSavedDeviceAppraisal->DeviceAppraisals(deviceConfig, scanInfos, info) == WIFI_OPT_SUCCESS); } @@ -222,18 +226,7 @@ void StaSavedDeviceAppraisalTest::WhetherSkipDeviceSuccess1() deviceConfig.isEphemeral = false; deviceConfig.status = static_cast(WifiDeviceConfigStatus::ENABLED); - EXPECT_TRUE(pStaSavedDeviceAppraisal->WhetherSkipDevice(deviceConfig) == true); -} - -void StaSavedDeviceAppraisalTest::WhetherSkipDeviceSuccess2() -{ - WifiDeviceConfig deviceConfig; - GetWifiDeviceConfig(deviceConfig); - - deviceConfig.isPasspoint = false; - deviceConfig.isEphemeral = false; - deviceConfig.status = static_cast(WifiDeviceConfigStatus::CURRENT); - EXPECT_TRUE(pStaSavedDeviceAppraisal->WhetherSkipDevice(deviceConfig) == true); + EXPECT_TRUE(pStaSavedDeviceAppraisal->WhetherSkipDevice(deviceConfig) == false); } void StaSavedDeviceAppraisalTest::WhetherSkipDeviceFail1() @@ -243,7 +236,7 @@ void StaSavedDeviceAppraisalTest::WhetherSkipDeviceFail1() deviceConfig.isPasspoint = true; deviceConfig.isEphemeral = true; deviceConfig.status = static_cast(WifiDeviceConfigStatus::ENABLED); - EXPECT_TRUE(pStaSavedDeviceAppraisal->WhetherSkipDevice(deviceConfig) == false); + EXPECT_TRUE(pStaSavedDeviceAppraisal->WhetherSkipDevice(deviceConfig) == true); } HWTEST_F(StaSavedDeviceAppraisalTest, SaveNetworkEvaluatorSuccess1, TestSize.Level1) @@ -276,11 +269,6 @@ HWTEST_F(StaSavedDeviceAppraisalTest, WhetherSkipDeviceSuccess1, TestSize.Level1 WhetherSkipDeviceSuccess1(); } -HWTEST_F(StaSavedDeviceAppraisalTest, WhetherSkipDeviceSuccess2, TestSize.Level1) -{ - WhetherSkipDeviceSuccess2(); -} - HWTEST_F(StaSavedDeviceAppraisalTest, WhetherSkipDeviceFail1, TestSize.Level1) { WhetherSkipDeviceFail1(); diff --git a/tests/wifi_standard/wifi_framework/wifi_manage/wifi_sta/sta_service_test.cpp b/wifi/test/wifi_standard/wifi_framework/wifi_manage/wifi_sta/sta_service_test.cpp similarity index 96% rename from tests/wifi_standard/wifi_framework/wifi_manage/wifi_sta/sta_service_test.cpp rename to wifi/test/wifi_standard/wifi_framework/wifi_manage/wifi_sta/sta_service_test.cpp index aaa3da5ba70dd547573064b07471914e8e40599b..56df15f3f753b8431deb0d1fc319271bc1227142 100644 --- a/tests/wifi_standard/wifi_framework/wifi_manage/wifi_sta/sta_service_test.cpp +++ b/wifi/test/wifi_standard/wifi_framework/wifi_manage/wifi_sta/sta_service_test.cpp @@ -1,5 +1,5 @@ /* - * Copyright (C) 2021 Huawei Device Co., Ltd. + * Copyright (C) 2021-2022 Huawei Device Co., Ltd. * 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 @@ -90,6 +90,8 @@ public: void StaServiceAutoConnectServiceSuccess(); void StaServiceRegisterStaServiceCallbackSuccess(); void StaServiceRegisterStaServiceCallbackFail(); + void StaServiceSetSuspendModeTest(); + public: std::unique_ptr pStaService; }; @@ -515,6 +517,23 @@ void StaServiceTest::StaServiceRegisterStaServiceCallbackFail() pStaService->RegisterStaServiceCallback(instance.GetStaCallback()); } +/** + * @tc.name: Set suspend mode test + * @tc.desc: Set suspend mode test function. + * @tc.type: FUNC + * @tc.require: issueI5JRBB + */ +void StaServiceTest::StaServiceSetSuspendModeTest() +{ + EXPECT_CALL(WifiSupplicantHalInterface::GetInstance(), WpaSetSuspendMode(_)) + .WillOnce(Return(WifiErrorNo::WIFI_IDL_OPT_FAILED)) + .WillRepeatedly(Return(WifiErrorNo::WIFI_IDL_OPT_OK)); + + EXPECT_TRUE(pStaService->SetSuspendMode(false) == WIFI_OPT_FAILED); + EXPECT_TRUE(pStaService->SetSuspendMode(false) == WIFI_OPT_SUCCESS); + EXPECT_TRUE(pStaService->SetSuspendMode(true) == WIFI_OPT_SUCCESS); +} + HWTEST_F(StaServiceTest, StaServiceInitStaServiceSuccess, TestSize.Level1) { StaServiceInitStaServiceSuccess(); @@ -674,5 +693,16 @@ HWTEST_F(StaServiceTest, StaServiceRegisterStaServiceCallbackFail, TestSize.Leve { StaServiceRegisterStaServiceCallbackFail(); } + +/** + * @tc.name: Set suspend mode test + * @tc.desc: Set suspend mode test function. + * @tc.type: FUNC + * @tc.require: issueI5JRBB + */ +HWTEST_F(StaServiceTest, StaServiceSetSuspendMode, TestSize.Level1) +{ + StaServiceSetSuspendModeTest(); +} } // namespace Wifi } // namespace OHOS \ No newline at end of file diff --git a/tests/wifi_standard/wifi_framework/wifi_manage/wifi_sta/sta_state_machine_test.cpp b/wifi/test/wifi_standard/wifi_framework/wifi_manage/wifi_sta/sta_state_machine_test.cpp similarity index 98% rename from tests/wifi_standard/wifi_framework/wifi_manage/wifi_sta/sta_state_machine_test.cpp rename to wifi/test/wifi_standard/wifi_framework/wifi_manage/wifi_sta/sta_state_machine_test.cpp index 0d5575883eab8455392d4b40d0cc2699b13678dc..632b8c270c6c4112ce852657a570ab7d4084aac1 100644 --- a/tests/wifi_standard/wifi_framework/wifi_manage/wifi_sta/sta_state_machine_test.cpp +++ b/wifi/test/wifi_standard/wifi_framework/wifi_manage/wifi_sta/sta_state_machine_test.cpp @@ -1,5 +1,5 @@ /* - * Copyright (C) 2021 Huawei Device Co., Ltd. + * Copyright (C) 2021-2022 Huawei Device Co., Ltd. * 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 @@ -12,18 +12,20 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -#include "sta_state_machine.h" -#include "sta_define.h" -#include "mock_wifi_settings.h" -#include "mock_wifi_supplicant_hal_interface.h" -#include "mock_wifi_sta_hal_interface.h" -#include "mock_wifi_manager.h" -#include "mock_dhcp_service.h" -#include "mock_wifi_chip_hal_interface.h" -#include "mock_sta_network_check.h" -#include "mock_if_config.h" + #include #include "internal_message.h" +#include "mock_chip_capability.h" +#include "mock_dhcp_service.h" +#include "mock_if_config.h" +#include "mock_sta_network_check.h" +#include "mock_wifi_chip_hal_interface.h" +#include "mock_wifi_manager.h" +#include "mock_wifi_settings.h" +#include "mock_wifi_sta_hal_interface.h" +#include "mock_wifi_supplicant_hal_interface.h" +#include "sta_define.h" +#include "sta_state_machine.h" using ::testing::_; using ::testing::AtLeast; @@ -46,7 +48,7 @@ public: pStaStateMachine.reset(new StaStateMachine()); pStaStateMachine->InitStaStateMachine(); - NetStateHandler handle; + NetStateHandler handle = nullptr; pStaStateMachine->pNetcheck = new MockStaNetworkCheck(handle); pStaStateMachine->RegisterStaServiceCallback(WifiManager::GetInstance().GetStaCallback()); } @@ -86,7 +88,7 @@ public: void DealConnectTimeOutCmd() { - EXPECT_CALL(WifiSettings::GetInstance(), SaveLinkedInfo(_)); + EXPECT_CALL(WifiSettings::GetInstance(), SaveLinkedInfo(_)).WillRepeatedly(Return(0)); EXPECT_CALL(WifiStaHalInterface::GetInstance(), DisableNetwork(_)).WillRepeatedly(Return(WIFI_IDL_OPT_FAILED)); EXPECT_CALL(WifiManager::GetInstance(), DealStaConnChanged(_, _)).Times(testing::AtLeast(1)); InternalMessage msg; @@ -452,7 +454,7 @@ public: EXPECT_CALL(WifiSettings::GetInstance(), SaveLinkedInfo(_)).Times(testing::AtLeast(0)); EXPECT_CALL(WifiManager::GetInstance(), DealStaConnChanged(_, _)).Times(testing::AtLeast(0)); InternalMessage msg; - pStaStateMachine->DealWpaWrongPskEvent(&msg); + pStaStateMachine->DealWpaLinkFailEvent(&msg); } void DealWpaWrongPskEventFail() @@ -460,12 +462,11 @@ public: EXPECT_CALL(WifiSettings::GetInstance(), SaveLinkedInfo(_)).Times(testing::AtLeast(0)); EXPECT_CALL(WifiManager::GetInstance(), DealStaConnChanged(_, _)).Times(testing::AtLeast(0)); InternalMessage msg; - pStaStateMachine->DealWpaWrongPskEvent(nullptr); + pStaStateMachine->DealWpaLinkFailEvent(nullptr); } void DealReassociateCmdSuccess() { - EXPECT_CALL(WifiSettings::GetInstance(), GetUserLastSelectedNetworkTimeVal()); EXPECT_CALL(WifiStaHalInterface::GetInstance(), Reassociate()).WillRepeatedly(Return(WIFI_IDL_OPT_OK)); EXPECT_CALL(WifiManager::GetInstance(), DealStaConnChanged(_, _)).Times(testing::AtLeast(0)); InternalMessage msg; @@ -474,7 +475,6 @@ public: void DealReassociateCmdFail1() { - EXPECT_CALL(WifiSettings::GetInstance(), GetUserLastSelectedNetworkTimeVal()); EXPECT_CALL(WifiStaHalInterface::GetInstance(), Reassociate()).WillRepeatedly(Return(WIFI_IDL_OPT_FAILED)); EXPECT_CALL(WifiManager::GetInstance(), DealStaConnChanged(_, _)).Times(testing::AtLeast(0)); pStaStateMachine->DealReassociateCmd(nullptr); @@ -482,7 +482,6 @@ public: void DealReassociateCmdFail2() { - EXPECT_CALL(WifiSettings::GetInstance(), GetUserLastSelectedNetworkTimeVal()); EXPECT_CALL(WifiStaHalInterface::GetInstance(), Reassociate()).WillRepeatedly(Return(WIFI_IDL_OPT_FAILED)); pStaStateMachine->DealReassociateCmd(nullptr); } @@ -917,7 +916,7 @@ public: void WpsStateExeMsgSuccess1() { EXPECT_CALL(WifiSettings::GetInstance(), SetWifiState(_)).Times(AtLeast(0)); - EXPECT_CALL(WifiSettings::GetInstance(), SaveLinkedInfo(_)); + EXPECT_CALL(WifiSettings::GetInstance(), SaveLinkedInfo(_)).Times(AtLeast(0)).WillRepeatedly(Return(0)); EXPECT_CALL(WifiSettings::GetInstance(), GetDeviceConfig(_)).Times(AtLeast(0)).WillRepeatedly(Return(0)); EXPECT_CALL(WifiSettings::GetInstance(), AddDeviceConfig(_)).Times(AtLeast(0)); EXPECT_CALL(WifiSettings::GetInstance(), SyncDeviceConfig()).Times(AtLeast(0)); @@ -1062,7 +1061,6 @@ public: EXPECT_CALL(WifiSettings::GetInstance(), SaveIpInfo(_)).Times(AtLeast(0)); ; EXPECT_CALL(WifiSettings::GetInstance(), SaveLinkedInfo(_)).Times(AtLeast(0)); - EXPECT_CALL(IfConfig::GetInstance(), SetIfAddr(_, _)).Times(AtLeast(0)); EXPECT_CALL(WifiManager::GetInstance(), DealStaConnChanged(_, _)).Times(AtLeast(0)); EXPECT_TRUE(pStaStateMachine->ConfigStaticIpAddress(staticIpAddress)); } @@ -1075,7 +1073,6 @@ public: pStaStateMachine->getIpSucNum = 1; pStaStateMachine->isRoam = false; StaticIpAddress staticIpAddress; - EXPECT_CALL(IfConfig::GetInstance(), SetIfAddr(_, _)).Times(AtLeast(0)); EXPECT_CALL(WifiSettings::GetInstance(), SaveIpInfo(_)).Times(AtLeast(0)); EXPECT_CALL(WifiSettings::GetInstance(), SaveLinkedInfo(_)).Times(AtLeast(0)); EXPECT_CALL(WifiManager::GetInstance(), DealStaConnChanged(_, _)).Times(AtLeast(0)); @@ -1092,7 +1089,6 @@ public: StaticIpAddress staticIpAddress; EXPECT_CALL(WifiSettings::GetInstance(), SaveIpInfo(_)).Times(AtLeast(0)); EXPECT_CALL(WifiSettings::GetInstance(), SaveLinkedInfo(_)).Times(AtLeast(0)); - EXPECT_CALL(IfConfig::GetInstance(), SetIfAddr(_, _)).Times(AtLeast(0)); EXPECT_CALL(WifiManager::GetInstance(), DealStaConnChanged(_, _)).Times(AtLeast(0)); EXPECT_TRUE(pStaStateMachine->ConfigStaticIpAddress(staticIpAddress)); } @@ -1105,7 +1101,6 @@ public: pStaStateMachine->isRoam = false; EXPECT_CALL(WifiSettings::GetInstance(), SaveIpInfo(_)).Times(AtLeast(0)); EXPECT_CALL(WifiSettings::GetInstance(), SaveLinkedInfo(_)).Times(AtLeast(0)); - EXPECT_CALL(IfConfig::GetInstance(), SetIfAddr(_, _)).Times(AtLeast(0)); EXPECT_FALSE(pStaStateMachine->ConfigStaticIpAddress(staticIpAddress)); } @@ -1113,20 +1108,20 @@ public: { EXPECT_CALL(WifiSettings::GetInstance(), SaveLinkedInfo(_)); pStaStateMachine->linkedInfo.connState = ConnState::CONNECTED; - pStaStateMachine->HandleNetCheckResult(StaNetState::NETWORK_STATE_WORKING); + pStaStateMachine->HandleNetCheckResult(StaNetState::NETWORK_STATE_WORKING, ""); } void HandleNetCheckResultSuccess3() { EXPECT_CALL(WifiSettings::GetInstance(), SaveLinkedInfo(_)); pStaStateMachine->linkedInfo.connState = ConnState::CONNECTED; - pStaStateMachine->HandleNetCheckResult(StaNetState::NETWORK_STATE_UNKNOW); + pStaStateMachine->HandleNetCheckResult(StaNetState::NETWORK_STATE_UNKNOWN, ""); } void HandleNetCheckResultFail() { pStaStateMachine->linkedInfo.connState = ConnState::DISCONNECTED; - pStaStateMachine->HandleNetCheckResult(StaNetState::NETWORK_STATE_UNKNOW); + pStaStateMachine->HandleNetCheckResult(StaNetState::NETWORK_STATE_UNKNOWN, ""); } void LinkedStateGoInStateSuccess() @@ -1222,6 +1217,7 @@ public: EXPECT_CALL(WifiSettings::GetInstance(), GetIpInfo(_)) .WillRepeatedly(DoAll(SetArgReferee<0>(ipInfo), Return(0))); EXPECT_CALL(WifiSettings::GetInstance(), SaveLinkedInfo(_)).Times(AtLeast(0)); + EXPECT_CALL(WifiSettings::GetInstance(), GetStrDnsBak()).Times(AtLeast(0)); std::string ifname = "wlan0"; DhcpResult result; diff --git a/tests/wifi_standard/wifi_framework/common/unittest/BUILD.gn b/wifi/test/wifi_standard/wifi_framework/wifi_toolkit/unittest/BUILD.gn similarity index 33% rename from tests/wifi_standard/wifi_framework/common/unittest/BUILD.gn rename to wifi/test/wifi_standard/wifi_framework/wifi_toolkit/unittest/BUILD.gn index 81d472a370482254ab7fed963c81e74ee42dae39..0712b7b68e172f35e99b8398446bfec59e968776 100644 --- a/tests/wifi_standard/wifi_framework/common/unittest/BUILD.gn +++ b/wifi/test/wifi_standard/wifi_framework/wifi_toolkit/unittest/BUILD.gn @@ -1,4 +1,4 @@ -# Copyright (C) 2021 Huawei Device Co., Ltd. +# Copyright (C) 2021-2022 Huawei Device Co., Ltd. # 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 @@ -12,32 +12,33 @@ # limitations under the License. import("//build/test.gni") -SUBSYSTEM_DIR = "//foundation/communication/wifi" -module_output_path = "wifi_standard/common_test" +import("//foundation/communication/wifi/wifi/wifi.gni") +module_output_path = "wifi/toolkit_test" config("module_private_config") { visibility = [ ":*" ] include_dirs = [ - "//utils/native/base/include", - "$SUBSYSTEM_DIR/tests/wifi_standard/wifi_framework/common/unittest", + "//commonlibrary/c_utils/base/include", + "$WIFI_ROOT_DIR/test/wifi_standard/wifi_framework/wifi_toolkit/unittest", ] } -ohos_unittest("common_unittest") { +ohos_unittest("toolkit_unittest") { module_out_path = module_output_path sources = [ - "$SUBSYSTEM_DIR/interfaces/innerkits/native_cpp/wifi_standard/src/wifi_p2p_msg.cpp", - "$SUBSYSTEM_DIR/services/wifi_standard/wifi_framework/common/config/wifi_config_file_spec.cpp", - "$SUBSYSTEM_DIR/services/wifi_standard/wifi_framework/common/log/log_helper.c", - "$SUBSYSTEM_DIR/services/wifi_standard/wifi_framework/common/net_helper/base_address.cpp", - "$SUBSYSTEM_DIR/services/wifi_standard/wifi_framework/common/net_helper/ip_tools.cpp", - "$SUBSYSTEM_DIR/services/wifi_standard/wifi_framework/common/net_helper/ipv4_address.cpp", - "$SUBSYSTEM_DIR/services/wifi_standard/wifi_framework/common/net_helper/ipv6_address.cpp", - "$SUBSYSTEM_DIR/services/wifi_standard/wifi_framework/common/net_helper/mac_address.cpp", - "$SUBSYSTEM_DIR/services/wifi_standard/wifi_framework/common/net_helper/network_interface.cpp", - "$SUBSYSTEM_DIR/services/wifi_standard/wifi_framework/common/utils/wifi_global_func.cpp", - "common_test.cpp", + "$WIFI_ROOT_DIR/frameworks/native/src/wifi_p2p_msg.cpp", + "$WIFI_ROOT_DIR/services/wifi_standard/wifi_framework/wifi_toolkit/config/wifi_config_file_spec.cpp", + "$WIFI_ROOT_DIR/services/wifi_standard/wifi_framework/wifi_toolkit/log/log_helper.c", + "$WIFI_ROOT_DIR/services/wifi_standard/wifi_framework/wifi_toolkit/net_helper/base_address.cpp", + "$WIFI_ROOT_DIR/services/wifi_standard/wifi_framework/wifi_toolkit/net_helper/ip_tools.cpp", + "$WIFI_ROOT_DIR/services/wifi_standard/wifi_framework/wifi_toolkit/net_helper/ipv4_address.cpp", + "$WIFI_ROOT_DIR/services/wifi_standard/wifi_framework/wifi_toolkit/net_helper/ipv6_address.cpp", + "$WIFI_ROOT_DIR/services/wifi_standard/wifi_framework/wifi_toolkit/net_helper/mac_address.cpp", + "$WIFI_ROOT_DIR/services/wifi_standard/wifi_framework/wifi_toolkit/net_helper/network_interface.cpp", + "$WIFI_ROOT_DIR/services/wifi_standard/wifi_framework/wifi_toolkit/utils/wifi_encryption_util.cpp", + "$WIFI_ROOT_DIR/services/wifi_standard/wifi_framework/wifi_toolkit/utils/wifi_global_func.cpp", "wifi_config_file_test.cpp", + "wifi_encryption_util_test.cpp", "wifi_global_func_test.cpp", "wifi_ip_tools_test.cpp", "wifi_log_helper_test.cpp", @@ -46,30 +47,41 @@ ohos_unittest("common_unittest") { include_dirs = [ "//base/hiviewdfx/hilog/interfaces/native/innerkits/include", - "$SUBSYSTEM_DIR/services/wifi_standard/wifi_framework/common/include", - "$SUBSYSTEM_DIR/services/wifi_standard/wifi_framework/common/net_helper", - "$SUBSYSTEM_DIR/services/wifi_standard/wifi_framework/common/utils", - "$SUBSYSTEM_DIR/services/wifi_standard/wifi_framework/common/log", - "$SUBSYSTEM_DIR/services/wifi_standard/wifi_framework/common/config", - "$SUBSYSTEM_DIR/interfaces/innerkits/native_cpp/wifi_standard/interfaces", + "$WIFI_ROOT_DIR/services/wifi_standard/wifi_framework/wifi_toolkit/include", + "$WIFI_ROOT_DIR/services/wifi_standard/wifi_framework/wifi_toolkit/net_helper", + "$WIFI_ROOT_DIR/services/wifi_standard/wifi_framework/wifi_toolkit/utils", + "$WIFI_ROOT_DIR/services/wifi_standard/wifi_framework/wifi_toolkit/log", + "$WIFI_ROOT_DIR/services/wifi_standard/wifi_framework/wifi_toolkit/config", + "$WIFI_ROOT_DIR/frameworks/native/interfaces", + "$WIFI_ROOT_DIR/services/wifi_standard/include", ] - deps = [ "//utils/native/base:utils" ] - ldflags = [ "-fPIC", "--coverage", ] - external_deps = [ "hiviewdfx_hilog_native:libhilog" ] + deps = [ + "//third_party/googletest:gmock_main", + "//third_party/googletest:gtest_main", + ] + defines = [] + external_deps = [ + "c_utils:utils", + "hiviewdfx_hilog_native:libhilog", + ] + if (wifi_feature_with_encryption) { + external_deps += [ "huks:libhukssdk" ] + defines += [ "FEATURE_ENCRYPTION_SUPPORT" ] + } configs = [ ":module_private_config" ] - part_name = "wifi_standard" + part_name = "wifi" subsystem_name = "communication" testonly = true } group("unittest") { testonly = true - deps = [ ":common_unittest" ] + deps = [ ":toolkit_unittest" ] } diff --git a/tests/wifi_standard/wifi_framework/common/unittest/wifi_config_file_test.cpp b/wifi/test/wifi_standard/wifi_framework/wifi_toolkit/unittest/wifi_config_file_test.cpp similarity index 97% rename from tests/wifi_standard/wifi_framework/common/unittest/wifi_config_file_test.cpp rename to wifi/test/wifi_standard/wifi_framework/wifi_toolkit/unittest/wifi_config_file_test.cpp index c08b5668a16a1cfaab9fd49507de4ec465215419..3bf4e99a0da233628d795157ffc3b0f38810f349 100644 --- a/tests/wifi_standard/wifi_framework/common/unittest/wifi_config_file_test.cpp +++ b/wifi/test/wifi_standard/wifi_framework/wifi_toolkit/unittest/wifi_config_file_test.cpp @@ -94,10 +94,7 @@ HWTEST_F(WifiConfigFileTest, SaveDeviceValueCheck, TestSize.Level1) tmp.status = static_cast(WifiDeviceConfigStatus::ENABLED); tmp.bssid = "01:xx:xx:xx:xx:06"; tmp.ssid = "my wifi"; - tmp.band = static_cast(BandType::BAND_2GHZ); - tmp.channel = 1; tmp.isPasspoint = true; - tmp.isEphemeral = true; tmp.preSharedKey = "12345678"; tmp.keyMgmt = "NONE"; tmp.wepKeys[0] = "12345678"; @@ -119,10 +116,7 @@ HWTEST_F(WifiConfigFileTest, SaveDeviceValueCheck, TestSize.Level1) EXPECT_TRUE(tmp.status == ldCfg.status); EXPECT_TRUE(tmp.bssid == ldCfg.bssid); EXPECT_TRUE(tmp.ssid == ldCfg.ssid); - EXPECT_TRUE(tmp.band == ldCfg.band); - EXPECT_TRUE(tmp.channel == ldCfg.channel); EXPECT_TRUE(tmp.isPasspoint == ldCfg.isPasspoint); - EXPECT_TRUE(tmp.isEphemeral == ldCfg.isEphemeral); EXPECT_TRUE(tmp.preSharedKey == ldCfg.preSharedKey); EXPECT_TRUE(tmp.keyMgmt == ldCfg.keyMgmt); EXPECT_TRUE(tmp.wepTxKeyIndex == ldCfg.wepTxKeyIndex); diff --git a/tests/wifi_standard/wifi_framework/common/unittest/wifi_config_file_test.h b/wifi/test/wifi_standard/wifi_framework/wifi_toolkit/unittest/wifi_config_file_test.h similarity index 100% rename from tests/wifi_standard/wifi_framework/common/unittest/wifi_config_file_test.h rename to wifi/test/wifi_standard/wifi_framework/wifi_toolkit/unittest/wifi_config_file_test.h diff --git a/wifi/test/wifi_standard/wifi_framework/wifi_toolkit/unittest/wifi_encryption_util_test.cpp b/wifi/test/wifi_standard/wifi_framework/wifi_toolkit/unittest/wifi_encryption_util_test.cpp new file mode 100755 index 0000000000000000000000000000000000000000..587c3710bb5d7330eeb073e2106964ddfc2857b3 --- /dev/null +++ b/wifi/test/wifi_standard/wifi_framework/wifi_toolkit/unittest/wifi_encryption_util_test.cpp @@ -0,0 +1,127 @@ +/* + * Copyright (C) 2022 Huawei Device Co., Ltd. + * 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 FEATURE_ENCRYPTION_SUPPORT +#include "wifi_encryption_util_test.h" +#include "wifi_encryption_util.h" + +using namespace testing::ext; + +namespace OHOS { +namespace Wifi { + +static struct HksParam g_genParam[] = { + { .tag = HKS_TAG_KEY_STORAGE_FLAG, .uint32Param = HKS_STORAGE_PERSISTENT }, + { .tag = HKS_TAG_ALGORITHM, .uint32Param = HKS_ALG_AES }, + { .tag = HKS_TAG_KEY_SIZE, .uint32Param = HKS_AES_KEY_SIZE_256 }, + { .tag = HKS_TAG_PURPOSE, .uint32Param = HKS_KEY_PURPOSE_ENCRYPT | HKS_KEY_PURPOSE_DECRYPT }, + { .tag = HKS_TAG_DIGEST, .uint32Param = HKS_DIGEST_NONE }, + { .tag = HKS_TAG_PADDING, .uint32Param = HKS_PADDING_NONE }, + { .tag = HKS_TAG_IS_KEY_ALIAS, .boolParam = true }, + { .tag = HKS_TAG_KEY_GENERATE_TYPE, .uint32Param = HKS_KEY_GENERATE_TYPE_DEFAULT }, + { .tag = HKS_TAG_BLOCK_MODE, .uint32Param = HKS_MODE_GCM }, + { .tag = HKS_TAG_ASSOCIATED_DATA, .blob = { .size = AAD_SIZE, .data = (uint8_t *)AAD } }, +}; + +HWTEST_F(WifiEncryptionUtilFuncTest, GetKey_001, TestSize.Level1) +{ + WifiEncryptionInfo testEncryptionInfo; + testEncryptionInfo.SetFile("TestKey"); + struct HksParamSet *testParamSet = nullptr; + EXPECT_TRUE(HksInitParamSet(&testParamSet) == HKS_SUCCESS); + EXPECT_TRUE(HksAddParams(testParamSet, g_genParam, sizeof(g_genParam) / sizeof(HksParam)) == HKS_SUCCESS); + EXPECT_TRUE(HksBuildParamSet(&testParamSet) == HKS_SUCCESS); + EXPECT_TRUE(GetKey(testEncryptionInfo, testParamSet) == HKS_SUCCESS); +} + +HWTEST_F(WifiEncryptionUtilFuncTest, WifiEncryption_002, TestSize.Level1) +{ + WifiEncryptionInfo testEncryptionInfo; + testEncryptionInfo.SetFile("TestEncryption"); + EncryptedData encryResult; + const std::string inputString = "12345678"; + EXPECT_TRUE(WifiEncryption(testEncryptionInfo, inputString, encryResult) == HKS_SUCCESS); +} + +HWTEST_F(WifiEncryptionUtilFuncTest, WifiEncryption_003, TestSize.Level1) +{ + WifiEncryptionInfo testEncryptionInfo; + testEncryptionInfo.SetFile("TestEncryption"); + EncryptedData encryResult; + const std::string inputString = ""; + EXPECT_TRUE(WifiEncryption(testEncryptionInfo, inputString, encryResult) == HKS_SUCCESS); + EXPECT_TRUE(inputString.compare(encryResult.encryptedPassword) == 0); +} + +HWTEST_F(WifiEncryptionUtilFuncTest, WifiDecryption_004, TestSize.Level1) +{ + WifiEncryptionInfo testEncryptionInfo; + testEncryptionInfo.SetFile("TestDecryption"); + EncryptedData encryResult; + const std::string inputString = "12345678"; + EXPECT_TRUE(WifiEncryption(testEncryptionInfo, inputString, encryResult) == HKS_SUCCESS); + std::string decryptedData = ""; + EXPECT_TRUE(WifiDecryption(testEncryptionInfo, encryResult, decryptedData) == HKS_SUCCESS); + EXPECT_TRUE(inputString.compare(decryptedData) == 0); +} + +HWTEST_F(WifiEncryptionUtilFuncTest, WifiDecryption_005, TestSize.Level1) +{ + WifiEncryptionInfo testEncryptionInfo; + testEncryptionInfo.SetFile("TestDecryption"); + EncryptedData encryResult; + encryResult.encryptedPassword = ""; + std::string decryptedData = ""; + EXPECT_TRUE(WifiDecryption(testEncryptionInfo, encryResult, decryptedData) == HKS_SUCCESS); + EXPECT_TRUE(decryptedData.compare("") == 0); +} + +HWTEST_F(WifiEncryptionUtilFuncTest, WifiDecryptionFailed_006, TestSize.Level1) +{ + WifiEncryptionInfo testEncryptionInfo; + testEncryptionInfo.SetFile("TestDecryption"); + EncryptedData encryResult; + encryResult.encryptedPassword = "1234567"; + std::string decryptedData = ""; + EXPECT_TRUE(WifiDecryption(testEncryptionInfo, encryResult, decryptedData) != HKS_SUCCESS); + EXPECT_TRUE(decryptedData.compare("") == 0); +} + +HWTEST_F(WifiEncryptionUtilFuncTest, WifiDecryptionFailed_007, TestSize.Level1) +{ + WifiEncryptionInfo testEncryptionInfo; + testEncryptionInfo.SetFile("TestDecryption"); + EncryptedData encryResult; + encryResult.encryptedPassword = "12345678"; + encryResult.encryptedPassword = "1234567"; + std::string decryptedData = ""; + EXPECT_TRUE(WifiDecryption(testEncryptionInfo, encryResult, decryptedData) != HKS_SUCCESS); + EXPECT_TRUE(decryptedData.compare("") == 0); +} + +HWTEST_F(WifiEncryptionUtilFuncTest, WifiDecryption_008, TestSize.Level1) +{ + WifiEncryptionInfo testEncryptionInfo; + testEncryptionInfo.SetFile("TestEncryption008"); + EncryptedData encryResult; + const std::string inputString = "12345678"; + EXPECT_TRUE(WifiEncryption(testEncryptionInfo, inputString, encryResult) == HKS_SUCCESS); + std::string decryptedData = ""; + WifiEncryptionInfo testDecryptionInfo; + testDecryptionInfo.SetFile("TestDecryption008"); + EXPECT_TRUE(WifiDecryption(testDecryptionInfo, encryResult, decryptedData) != HKS_SUCCESS); +} +} // namespace Wifi +} // namespace OHOS +#endif \ No newline at end of file diff --git a/wifi/test/wifi_standard/wifi_framework/wifi_toolkit/unittest/wifi_encryption_util_test.h b/wifi/test/wifi_standard/wifi_framework/wifi_toolkit/unittest/wifi_encryption_util_test.h new file mode 100755 index 0000000000000000000000000000000000000000..4b27d191dd7d24fbc1c9429c9d6da9a742522b6b --- /dev/null +++ b/wifi/test/wifi_standard/wifi_framework/wifi_toolkit/unittest/wifi_encryption_util_test.h @@ -0,0 +1,39 @@ +/* + * Copyright (C) 2022 Huawei Device Co., Ltd. + * 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 FEATURE_ENCRYPTION_SUPPORT +#ifndef OHOS_WIFI_ENCRYPTION_UTIL_TEST_H +#define OHOS_WIFI_ENCRYPTION_UTIL_TEST_H + +#include +#include "wifi_encryption_util.h" +namespace OHOS { +namespace Wifi { +class WifiEncryptionUtilFuncTest : public testing::Test { +public: + static void SetUpTestCase() + {} + static void TearDownTestCase() + {} + virtual void SetUp() + { + ASSERT_EQ(SetUpHks(), HKS_SUCCESS); + } + virtual void TearDown() + {} +}; +} // namespace Wifi +} // namespace OHOS +#endif +#endif \ No newline at end of file diff --git a/tests/wifi_standard/wifi_framework/common/unittest/wifi_global_func_test.cpp b/wifi/test/wifi_standard/wifi_framework/wifi_toolkit/unittest/wifi_global_func_test.cpp similarity index 79% rename from tests/wifi_standard/wifi_framework/common/unittest/wifi_global_func_test.cpp rename to wifi/test/wifi_standard/wifi_framework/wifi_toolkit/unittest/wifi_global_func_test.cpp index f5e715ae13faee3100e5778a1d7ff9ab8753c6e4..32b8b047a78e2b3e33dc93b7d92f25ff1688611d 100644 --- a/tests/wifi_standard/wifi_framework/common/unittest/wifi_global_func_test.cpp +++ b/wifi/test/wifi_standard/wifi_framework/wifi_toolkit/unittest/wifi_global_func_test.cpp @@ -133,33 +133,15 @@ HWTEST_F(WifiGlobalFuncTest, CheckMacIsValid, TestSize.Level1) HWTEST_F(WifiGlobalFuncTest, ConvertConnStateInternalTest, TestSize.Level1) { - EXPECT_TRUE(ConvertConnStateInternal(OperateResState::CONNECT_CONNECTING) == ConnectionState::CONNECT_CONNECTING); + bool isReport = true; + EXPECT_TRUE(ConvertConnStateInternal(OperateResState::CONNECT_CONNECTING, isReport) == ConnState::CONNECTING); EXPECT_TRUE( - ConvertConnStateInternal(OperateResState::CONNECT_AP_CONNECTED) == ConnectionState::CONNECT_AP_CONNECTED); - EXPECT_TRUE( - ConvertConnStateInternal(OperateResState::CONNECT_CHECK_PORTAL) == ConnectionState::CONNECT_CHECK_PORTAL); - EXPECT_TRUE( - ConvertConnStateInternal(OperateResState::CONNECT_NETWORK_ENABLED) == ConnectionState::CONNECT_NETWORK_ENABLED); - EXPECT_TRUE(ConvertConnStateInternal(OperateResState::CONNECT_NETWORK_DISABLED) == - ConnectionState::CONNECT_NETWORK_DISABLED); - EXPECT_TRUE(ConvertConnStateInternal(OperateResState::DISCONNECT_DISCONNECTING) == - ConnectionState::DISCONNECT_DISCONNECTING); - EXPECT_TRUE(ConvertConnStateInternal(OperateResState::DISCONNECT_DISCONNECT_FAILED) == - ConnectionState::DISCONNECT_DISCONNECT_FAILED); - EXPECT_TRUE( - ConvertConnStateInternal(OperateResState::DISCONNECT_DISCONNECTED) == ConnectionState::DISCONNECT_DISCONNECTED); - EXPECT_TRUE( - ConvertConnStateInternal(OperateResState::CONNECT_PASSWORD_WRONG) == ConnectionState::CONNECT_PASSWORD_WRONG); - EXPECT_TRUE(ConvertConnStateInternal(OperateResState::CONNECT_CONNECTING_TIMEOUT) == - ConnectionState::CONNECT_CONNECTING_TIMEOUT); - EXPECT_TRUE(ConvertConnStateInternal(OperateResState::CONNECT_OBTAINING_IP_FAILED) == - ConnectionState::CONNECT_OBTAINING_IP_FAILED); - EXPECT_TRUE(ConvertConnStateInternal(OperateResState::CONNECT_ASSOCIATING) == ConnectionState::CONNECT_ASSOCIATING); - EXPECT_TRUE(ConvertConnStateInternal(OperateResState::CONNECT_ASSOCIATED) == ConnectionState::CONNECT_ASSOCIATED); - EXPECT_TRUE(ConvertConnStateInternal(OperateResState::OPEN_WIFI_SUCCEED) == ConnectionState::UNKNOWN); + ConvertConnStateInternal(OperateResState::CONNECT_AP_CONNECTED, isReport) == ConnState::CONNECTED); + + EXPECT_TRUE(ConvertConnStateInternal(OperateResState::DISCONNECT_DISCONNECTING, isReport) == + ConnState::DISCONNECTING); EXPECT_TRUE( - ConvertConnStateInternal(OperateResState::CONNECT_OBTAINING_IP) == ConnectionState::CONNECT_OBTAINING_IP); - EXPECT_TRUE(ConvertConnStateInternal(OperateResState::CONNECT_SELECT_NETWORK_FAILED) == ConnectionState::UNKNOWN); + ConvertConnStateInternal(OperateResState::DISCONNECT_DISCONNECTED, isReport) == ConnState::DISCONNECTED); } HWTEST_F(WifiGlobalFuncTest, SplitStringTest, TestSize.Level1) diff --git a/tests/wifi_standard/wifi_framework/common/unittest/wifi_global_func_test.h b/wifi/test/wifi_standard/wifi_framework/wifi_toolkit/unittest/wifi_global_func_test.h similarity index 100% rename from tests/wifi_standard/wifi_framework/common/unittest/wifi_global_func_test.h rename to wifi/test/wifi_standard/wifi_framework/wifi_toolkit/unittest/wifi_global_func_test.h diff --git a/tests/wifi_standard/wifi_framework/common/unittest/wifi_ip_tools_test.cpp b/wifi/test/wifi_standard/wifi_framework/wifi_toolkit/unittest/wifi_ip_tools_test.cpp similarity index 94% rename from tests/wifi_standard/wifi_framework/common/unittest/wifi_ip_tools_test.cpp rename to wifi/test/wifi_standard/wifi_framework/wifi_toolkit/unittest/wifi_ip_tools_test.cpp index 8496eaad3a3038efc962ad66513a582c7fe6a46e..ddb6b24d917ee4a10b05eb2095701e86ac9e6a1f 100644 --- a/tests/wifi_standard/wifi_framework/common/unittest/wifi_ip_tools_test.cpp +++ b/wifi/test/wifi_standard/wifi_framework/wifi_toolkit/unittest/wifi_ip_tools_test.cpp @@ -75,9 +75,9 @@ HWTEST_F(WifiIpToolsTest, ConvertIpv6AddressTest, TestSize.Level1) HWTEST_F(WifiIpToolsTest, ConvertIpv4MaskTest, TestSize.Level1) { - EXPECT_TRUE(IpTools::ConvertIpv4Mask(-1) == ""); - EXPECT_TRUE(IpTools::ConvertIpv4Mask(33) == ""); - EXPECT_TRUE(IpTools::ConvertIpv4Mask(0) == "0.0.0.0"); + EXPECT_TRUE(IpTools::ConvertIpv4Mask(-1) == "255.255.255.0"); + EXPECT_TRUE(IpTools::ConvertIpv4Mask(33) == "255.255.255.0"); + EXPECT_TRUE(IpTools::ConvertIpv4Mask(0) == "255.255.255.0"); EXPECT_TRUE(IpTools::ConvertIpv4Mask(32) == "255.255.255.255"); EXPECT_TRUE(IpTools::ConvertIpv4Mask(11) == "255.224.0.0"); } diff --git a/tests/wifi_standard/wifi_framework/common/unittest/wifi_ip_tools_test.h b/wifi/test/wifi_standard/wifi_framework/wifi_toolkit/unittest/wifi_ip_tools_test.h similarity index 100% rename from tests/wifi_standard/wifi_framework/common/unittest/wifi_ip_tools_test.h rename to wifi/test/wifi_standard/wifi_framework/wifi_toolkit/unittest/wifi_ip_tools_test.h diff --git a/tests/wifi_standard/wifi_framework/common/unittest/wifi_log_helper_test.cpp b/wifi/test/wifi_standard/wifi_framework/wifi_toolkit/unittest/wifi_log_helper_test.cpp similarity index 100% rename from tests/wifi_standard/wifi_framework/common/unittest/wifi_log_helper_test.cpp rename to wifi/test/wifi_standard/wifi_framework/wifi_toolkit/unittest/wifi_log_helper_test.cpp diff --git a/tests/wifi_standard/wifi_framework/common/unittest/wifi_log_helper_test.h b/wifi/test/wifi_standard/wifi_framework/wifi_toolkit/unittest/wifi_log_helper_test.h similarity index 100% rename from tests/wifi_standard/wifi_framework/common/unittest/wifi_log_helper_test.h rename to wifi/test/wifi_standard/wifi_framework/wifi_toolkit/unittest/wifi_log_helper_test.h diff --git a/tests/wifi_standard/wifi_framework/common/unittest/wifi_network_interface_test.cpp b/wifi/test/wifi_standard/wifi_framework/wifi_toolkit/unittest/wifi_network_interface_test.cpp similarity index 100% rename from tests/wifi_standard/wifi_framework/common/unittest/wifi_network_interface_test.cpp rename to wifi/test/wifi_standard/wifi_framework/wifi_toolkit/unittest/wifi_network_interface_test.cpp diff --git a/tests/wifi_standard/wifi_framework/common/unittest/wifi_network_interface_test.h b/wifi/test/wifi_standard/wifi_framework/wifi_toolkit/unittest/wifi_network_interface_test.h similarity index 100% rename from tests/wifi_standard/wifi_framework/common/unittest/wifi_network_interface_test.h rename to wifi/test/wifi_standard/wifi_framework/wifi_toolkit/unittest/wifi_network_interface_test.h diff --git a/tests/wifi_standard/wifi_hal/unittest/BUILD.gn b/wifi/test/wifi_standard/wifi_hal/unittest/BUILD.gn similarity index 40% rename from tests/wifi_standard/wifi_hal/unittest/BUILD.gn rename to wifi/test/wifi_standard/wifi_hal/unittest/BUILD.gn index 20d7d37d2215a7300500f2c569a1662866d03011..d8303e594e64f84c8da6a66506f20b42b1566b67 100644 --- a/tests/wifi_standard/wifi_hal/unittest/BUILD.gn +++ b/wifi/test/wifi_standard/wifi_hal/unittest/BUILD.gn @@ -1,4 +1,4 @@ -# Copyright (C) 2021 Huawei Device Co., Ltd. +# Copyright (C) 2021-2022 Huawei Device Co., Ltd. # 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 @@ -12,43 +12,47 @@ # limitations under the License. import("//build/test.gni") -SUBSYSTEM_DIR = "//foundation/communication/wifi" -module_output_path = "wifi_standard/wifi_hal_test" +import("//foundation/communication/wifi/wifi/wifi.gni") +module_output_path = "wifi/wifi_hal_test" config("module_private_config") { visibility = [ ":*" ] include_dirs = [ - "//utils/native/base/include", - "$SUBSYSTEM_DIR/tests/wifi_standard/wifi_hal/unittest", + "//commonlibrary/c_utils/base/include", + "$WIFI_ROOT_DIR/test/wifi_standard/wifi_hal/unittest", ] } ohos_unittest("wifi_hal_unittest") { module_out_path = module_output_path sources = [ - "$SUBSYSTEM_DIR/services/wifi_standard/wifi_hal/common/wifi_hal_common_func.c", - "$SUBSYSTEM_DIR/services/wifi_standard/wifi_hal/wifi_hal_adapter.c", - "$SUBSYSTEM_DIR/services/wifi_standard/wifi_hal/wifi_hal_ap_interface.c", - "$SUBSYSTEM_DIR/services/wifi_standard/wifi_hal/wifi_hal_base_interface.c", - "$SUBSYSTEM_DIR/services/wifi_standard/wifi_hal/wifi_hal_callback.c", - "$SUBSYSTEM_DIR/services/wifi_standard/wifi_hal/wifi_hal_chip_interface.c", - "$SUBSYSTEM_DIR/services/wifi_standard/wifi_hal/wifi_hal_crpc_ap.c", - "$SUBSYSTEM_DIR/services/wifi_standard/wifi_hal/wifi_hal_crpc_base.c", - "$SUBSYSTEM_DIR/services/wifi_standard/wifi_hal/wifi_hal_crpc_chip.c", - "$SUBSYSTEM_DIR/services/wifi_standard/wifi_hal/wifi_hal_crpc_common.c", - "$SUBSYSTEM_DIR/services/wifi_standard/wifi_hal/wifi_hal_crpc_p2p.c", - "$SUBSYSTEM_DIR/services/wifi_standard/wifi_hal/wifi_hal_crpc_server.c", - "$SUBSYSTEM_DIR/services/wifi_standard/wifi_hal/wifi_hal_crpc_sta.c", - "$SUBSYSTEM_DIR/services/wifi_standard/wifi_hal/wifi_hal_crpc_supplicant.c", - "$SUBSYSTEM_DIR/services/wifi_standard/wifi_hal/wifi_hal_module/hostapd_hal/wifi_hostapd_hal.c", - "$SUBSYSTEM_DIR/services/wifi_standard/wifi_hal/wifi_hal_module/wpa_supplicant_hal/wifi_wpa_common.c", - "$SUBSYSTEM_DIR/services/wifi_standard/wifi_hal/wifi_hal_module/wpa_supplicant_hal/wifi_wpa_hal.c", - "$SUBSYSTEM_DIR/services/wifi_standard/wifi_hal/wifi_hal_module/wpa_supplicant_hal/wpa_p2p_hal/wifi_p2p_hal.c", - "$SUBSYSTEM_DIR/services/wifi_standard/wifi_hal/wifi_hal_module/wpa_supplicant_hal/wpa_sta_hal/wifi_supplicant_hal.c", - "$SUBSYSTEM_DIR/services/wifi_standard/wifi_hal/wifi_hal_module_manage.c", - "$SUBSYSTEM_DIR/services/wifi_standard/wifi_hal/wifi_hal_p2p_interface.c", - "$SUBSYSTEM_DIR/services/wifi_standard/wifi_hal/wifi_hal_sta_interface.c", - "$SUBSYSTEM_DIR/services/wifi_standard/wifi_hal/wifi_hal_vendor_interface.c", + "$WIFI_ROOT_DIR/services/wifi_standard/wifi_hal/common/wifi_hal_common_func.c", + "$WIFI_ROOT_DIR/services/wifi_standard/wifi_hal/hdi/src/wifi_hdi_ap_impl.c", + "$WIFI_ROOT_DIR/services/wifi_standard/wifi_hal/hdi/src/wifi_hdi_p2p_impl.c", + "$WIFI_ROOT_DIR/services/wifi_standard/wifi_hal/hdi/src/wifi_hdi_proxy.c", + "$WIFI_ROOT_DIR/services/wifi_standard/wifi_hal/hdi/src/wifi_hdi_sta_impl.c", + "$WIFI_ROOT_DIR/services/wifi_standard/wifi_hal/wifi_hal_adapter.c", + "$WIFI_ROOT_DIR/services/wifi_standard/wifi_hal/wifi_hal_ap_interface.c", + "$WIFI_ROOT_DIR/services/wifi_standard/wifi_hal/wifi_hal_base_interface.c", + "$WIFI_ROOT_DIR/services/wifi_standard/wifi_hal/wifi_hal_callback.c", + "$WIFI_ROOT_DIR/services/wifi_standard/wifi_hal/wifi_hal_chip_interface.c", + "$WIFI_ROOT_DIR/services/wifi_standard/wifi_hal/wifi_hal_crpc_ap.c", + "$WIFI_ROOT_DIR/services/wifi_standard/wifi_hal/wifi_hal_crpc_base.c", + "$WIFI_ROOT_DIR/services/wifi_standard/wifi_hal/wifi_hal_crpc_chip.c", + "$WIFI_ROOT_DIR/services/wifi_standard/wifi_hal/wifi_hal_crpc_common.c", + "$WIFI_ROOT_DIR/services/wifi_standard/wifi_hal/wifi_hal_crpc_p2p.c", + "$WIFI_ROOT_DIR/services/wifi_standard/wifi_hal/wifi_hal_crpc_server.c", + "$WIFI_ROOT_DIR/services/wifi_standard/wifi_hal/wifi_hal_crpc_sta.c", + "$WIFI_ROOT_DIR/services/wifi_standard/wifi_hal/wifi_hal_crpc_supplicant.c", + "$WIFI_ROOT_DIR/services/wifi_standard/wifi_hal/wifi_hal_module/hostapd_hal/wifi_hostapd_hal.c", + "$WIFI_ROOT_DIR/services/wifi_standard/wifi_hal/wifi_hal_module/wpa_supplicant_hal/wifi_wpa_common.c", + "$WIFI_ROOT_DIR/services/wifi_standard/wifi_hal/wifi_hal_module/wpa_supplicant_hal/wifi_wpa_hal.c", + "$WIFI_ROOT_DIR/services/wifi_standard/wifi_hal/wifi_hal_module/wpa_supplicant_hal/wpa_p2p_hal/wifi_p2p_hal.c", + "$WIFI_ROOT_DIR/services/wifi_standard/wifi_hal/wifi_hal_module/wpa_supplicant_hal/wpa_sta_hal/wifi_supplicant_hal.c", + "$WIFI_ROOT_DIR/services/wifi_standard/wifi_hal/wifi_hal_module_manage.c", + "$WIFI_ROOT_DIR/services/wifi_standard/wifi_hal/wifi_hal_p2p_interface.c", + "$WIFI_ROOT_DIR/services/wifi_standard/wifi_hal/wifi_hal_sta_interface.c", + "$WIFI_ROOT_DIR/services/wifi_standard/wifi_hal/wifi_hal_vendor_interface.c", "mock_wpa_ctrl.cpp", "wifi_hal_ap_interface_test.cpp", "wifi_hal_base_interface_test.cpp", @@ -58,29 +62,33 @@ ohos_unittest("wifi_hal_unittest") { "wifi_hal_hostapd_test.cpp", "wifi_hal_p2p_interface_test.cpp", "wifi_hal_sta_interface_test.cpp", - "wifi_hal_test.cpp", "wifi_hal_wpa_p2p_test.cpp", "wifi_hal_wpa_sta_test.cpp", ] include_dirs = [ - "//utils/native/base/include", - "$SUBSYSTEM_DIR/services/wifi_standard/ipc_framework/cRPC/include", - "$SUBSYSTEM_DIR/services/wifi_standard/wifi_hal", - "$SUBSYSTEM_DIR/services/wifi_standard/wifi_hal/common", - "$SUBSYSTEM_DIR/services/wifi_standard/wifi_hal/wifi_hal_module/hostapd_hal", - "$SUBSYSTEM_DIR/services/wifi_standard/wifi_hal/wifi_hal_module/wpa_supplicant_hal", - "$SUBSYSTEM_DIR/services/wifi_standard/wifi_hal/wifi_hal_module/wpa_supplicant_hal/wpa_sta_hal", - "$SUBSYSTEM_DIR/services/wifi_standard/wifi_hal/wifi_hal_module/wpa_supplicant_hal/wpa_p2p_hal", + "//commonlibrary/c_utils/base/include", + "$WIFI_ROOT_DIR/services/wifi_standard/ipc_framework/cRPC/include", + "$WIFI_ROOT_DIR/services/wifi_standard/wifi_hal", + "$WIFI_ROOT_DIR/services/wifi_standard/wifi_hal/common", + "$WIFI_ROOT_DIR/services/wifi_standard/wifi_hal/wifi_hal_module/hostapd_hal", + "$WIFI_ROOT_DIR/services/wifi_standard/wifi_hal/wifi_hal_module/wpa_supplicant_hal", + "$WIFI_ROOT_DIR/services/wifi_standard/wifi_hal/wifi_hal_module/wpa_supplicant_hal/wpa_sta_hal", + "$WIFI_ROOT_DIR/services/wifi_standard/wifi_hal/wifi_hal_module/wpa_supplicant_hal/wpa_p2p_hal", "//base/hiviewdfx/hilog/interfaces/native/innerkits/include", - "//third_party/wpa_supplicant/wpa_supplicant-2.9_standard/src/", - "//third_party/bounds_checking_function/include/", + "//third_party/wpa_supplicant/wpa_supplicant-2.9_standard/src", + "//third_party/bounds_checking_function/include", + "//drivers/peripheral/wlan/interfaces/include", + "//drivers/peripheral/wlan/client/include", + "$WIFI_ROOT_DIR/services/wifi_standard/wifi_hal/hdi/inc", + "$WIFI_ROOT_DIR/services/wifi_standard/include", ] deps = [ - "$SUBSYSTEM_DIR/services/wifi_standard/ipc_framework/cRPC:crpc_server", + "$WIFI_ROOT_DIR/services/wifi_standard/ipc_framework/cRPC:crpc_server", "//base/hiviewdfx/hilog/interfaces/native/innerkits:libhilog", - "//utils/native/base:utils", + "//third_party/googletest:gmock_main", + "//third_party/googletest:gtest_main", ] ldflags = [ @@ -88,10 +96,21 @@ ohos_unittest("wifi_hal_unittest") { "--coverage", ] - external_deps = [ "hiviewdfx_hilog_native:libhilog" ] + external_deps = [ + "c_utils:utils", + "hiviewdfx_hilog_native:libhilog", + ] + + defines = [ "AP_INTF=\"$wifi_feature_with_ap_intf\"" ] + + if (wifi_feature_is_hdi_supported) { + defines += [ "HDI_INTERFACE_SUPPORT" ] + external_deps += [ "drivers_interface_wlan:libwlan_proxy_1.0" ] + } + configs = [ ":module_private_config" ] - part_name = "wifi_standard" + part_name = "wifi" subsystem_name = "communication" testonly = true } @@ -104,15 +123,15 @@ group("unittest") { ohos_shared_library("WifiHalVendorTest") { sources = [ "wifi_hal_vendor_interface_test.c" ] include_dirs = [ - "//utils/native/base/include", + "//commonlibrary/c_utils/base/include", "//base/hiviewdfx/hilog/interfaces/native/innerkits/include", - "$SUBSYSTEM_DIR/services/wifi_standard/wifi_hal", - "$SUBSYSTEM_DIR/services/wifi_standard/wifi_hal/common", + "$WIFI_ROOT_DIR/services/wifi_standard/wifi_hal", + "$WIFI_ROOT_DIR/services/wifi_standard/wifi_hal/common", ] - deps = [ - "//base/hiviewdfx/hilog/interfaces/native/innerkits:libhilog", - "//utils/native/base:utils", - ] - part_name = "wifi_standard" + deps = [ "//base/hiviewdfx/hilog/interfaces/native/innerkits:libhilog" ] + + external_deps = [ "c_utils:utils" ] + + part_name = "wifi" subsystem_name = "communication" } diff --git a/tests/wifi_standard/wifi_hal/unittest/mock_wpa_ctrl.cpp b/wifi/test/wifi_standard/wifi_hal/unittest/mock_wpa_ctrl.cpp similarity index 100% rename from tests/wifi_standard/wifi_hal/unittest/mock_wpa_ctrl.cpp rename to wifi/test/wifi_standard/wifi_hal/unittest/mock_wpa_ctrl.cpp diff --git a/tests/wifi_standard/wifi_hal/unittest/mock_wpa_ctrl.h b/wifi/test/wifi_standard/wifi_hal/unittest/mock_wpa_ctrl.h similarity index 100% rename from tests/wifi_standard/wifi_hal/unittest/mock_wpa_ctrl.h rename to wifi/test/wifi_standard/wifi_hal/unittest/mock_wpa_ctrl.h diff --git a/tests/wifi_standard/wifi_hal/unittest/wifi_hal_adapter_test.h b/wifi/test/wifi_standard/wifi_hal/unittest/wifi_hal_adapter_test.h similarity index 100% rename from tests/wifi_standard/wifi_hal/unittest/wifi_hal_adapter_test.h rename to wifi/test/wifi_standard/wifi_hal/unittest/wifi_hal_adapter_test.h diff --git a/tests/wifi_standard/wifi_hal/unittest/wifi_hal_ap_interface_test.cpp b/wifi/test/wifi_standard/wifi_hal/unittest/wifi_hal_ap_interface_test.cpp similarity index 65% rename from tests/wifi_standard/wifi_hal/unittest/wifi_hal_ap_interface_test.cpp rename to wifi/test/wifi_standard/wifi_hal/unittest/wifi_hal_ap_interface_test.cpp index eea026af11df4343bf736bddaf88b006ceba8322..4735f3b589e1c4c7c1c6cf9e2aae015b622970d1 100644 --- a/tests/wifi_standard/wifi_hal/unittest/wifi_hal_ap_interface_test.cpp +++ b/wifi/test/wifi_standard/wifi_hal/unittest/wifi_hal_ap_interface_test.cpp @@ -30,31 +30,31 @@ void WifiHalApInterfaceTest::SetUpTestCase() HWTEST_F(WifiHalApInterfaceTest, StartSoftApTest, TestSize.Level1) { - EXPECT_TRUE(StartSoftAp() == WIFI_HAL_SUCCESS); + EXPECT_TRUE(StartSoftAp(0) == WIFI_HAL_SUCCESS); } HWTEST_F(WifiHalApInterfaceTest, GetStaInfosTest, TestSize.Level1) { char infos[4096] = {0}; int size = 4096; - EXPECT_TRUE(GetStaInfos(NULL, NULL) == WIFI_HAL_FAILED); - EXPECT_TRUE(GetStaInfos(infos, NULL) == WIFI_HAL_FAILED); - EXPECT_TRUE(GetStaInfos(NULL, &size) == WIFI_HAL_FAILED); - EXPECT_TRUE(GetStaInfos(infos, &size) == WIFI_HAL_SUCCESS); + EXPECT_TRUE(GetStaInfos(NULL, NULL, 0) == WIFI_HAL_FAILED); + EXPECT_TRUE(GetStaInfos(infos, NULL, 0) == WIFI_HAL_FAILED); + EXPECT_TRUE(GetStaInfos(NULL, &size, 0) == WIFI_HAL_FAILED); + EXPECT_TRUE(GetStaInfos(infos, &size, 0) == WIFI_HAL_SUCCESS); } HWTEST_F(WifiHalApInterfaceTest, SetCountryCodeTest, TestSize.Level1) { - EXPECT_TRUE(SetCountryCode(NULL) == WIFI_HAL_INVALID_PARAM); - EXPECT_TRUE(SetCountryCode("") == WIFI_HAL_INVALID_PARAM); - EXPECT_TRUE(SetCountryCode("C") == WIFI_HAL_INVALID_PARAM); - EXPECT_TRUE(SetCountryCode("CN") == WIFI_HAL_SUCCESS); - EXPECT_TRUE(SetCountryCode("CHINA") == WIFI_HAL_INVALID_PARAM); + EXPECT_TRUE(SetCountryCode(NULL, 0) == WIFI_HAL_INVALID_PARAM); + EXPECT_TRUE(SetCountryCode("", 0) == WIFI_HAL_INVALID_PARAM); + EXPECT_TRUE(SetCountryCode("C", 0) == WIFI_HAL_INVALID_PARAM); + EXPECT_TRUE(SetCountryCode("CN", 0) == WIFI_HAL_SUCCESS); + EXPECT_TRUE(SetCountryCode("CHINA", 0) == WIFI_HAL_INVALID_PARAM); } HWTEST_F(WifiHalApInterfaceTest, SetHostapdConfigTest, TestSize.Level1) { - EXPECT_TRUE(SetHostapdConfig(NULL) == WIFI_HAL_FAILED); + EXPECT_TRUE(SetHostapdConfig(NULL, 0) == WIFI_HAL_FAILED); HostapdConfig config; ASSERT_TRUE(memset_s(&config, sizeof(config), 0, sizeof(config)) == EOK); config.band = AP_2GHZ_BAND; @@ -65,40 +65,40 @@ HWTEST_F(WifiHalApInterfaceTest, SetHostapdConfigTest, TestSize.Level1) config.ssidLen = strlen(config.ssid); StrSafeCopy(config.preSharedKey, sizeof(config.preSharedKey), "adc123456"); config.preSharedKeyLen = strlen(config.preSharedKey); - EXPECT_TRUE(SetHostapdConfig(&config) == WIFI_HAL_SUCCESS); + EXPECT_TRUE(SetHostapdConfig(&config, 0) == WIFI_HAL_SUCCESS); } HWTEST_F(WifiHalApInterfaceTest, SetMacFilterTest, TestSize.Level1) { - EXPECT_TRUE(SetMacFilter(NULL, 0) == WIFI_HAL_FAILED); + EXPECT_TRUE(SetMacFilter(NULL, 0, 0) == WIFI_HAL_FAILED); unsigned char tmpMac[] = "00:00:00:00:00"; - EXPECT_TRUE(SetMacFilter(tmpMac, strlen((const char *)tmpMac)) == WIFI_HAL_FAILED); + EXPECT_TRUE(SetMacFilter(tmpMac, strlen((const char *)tmpMac), 0) == WIFI_HAL_FAILED); unsigned char tmpMac2[] = "00.00.00.00.00.00"; - EXPECT_TRUE(SetMacFilter(tmpMac2, strlen((const char *)tmpMac2)) == WIFI_HAL_INPUT_MAC_INVALID); + EXPECT_TRUE(SetMacFilter(tmpMac2, strlen((const char *)tmpMac2), 0) == WIFI_HAL_INPUT_MAC_INVALID); unsigned char mac[] = "00:00:00:00:00:00"; - EXPECT_TRUE(SetMacFilter(mac, strlen((const char *)mac)) == WIFI_HAL_SUCCESS); + EXPECT_TRUE(SetMacFilter(mac, strlen((const char *)mac), 0) == WIFI_HAL_SUCCESS); } HWTEST_F(WifiHalApInterfaceTest, DelMacFilterTest, TestSize.Level1) { - EXPECT_TRUE(DelMacFilter(NULL, 0) == WIFI_HAL_FAILED); + EXPECT_TRUE(DelMacFilter(NULL, 0, 0) == WIFI_HAL_FAILED); unsigned char tmpMac[] = "00:00:00:00:00"; - EXPECT_TRUE(DelMacFilter(tmpMac, strlen((const char *)tmpMac)) == WIFI_HAL_FAILED); + EXPECT_TRUE(DelMacFilter(tmpMac, strlen((const char *)tmpMac), 0) == WIFI_HAL_FAILED); unsigned char tmpMac2[] = "00.00.00.00.00.00"; - EXPECT_TRUE(DelMacFilter(tmpMac2, strlen((const char *)tmpMac2)) == WIFI_HAL_INPUT_MAC_INVALID); + EXPECT_TRUE(DelMacFilter(tmpMac2, strlen((const char *)tmpMac2), 0) == WIFI_HAL_INPUT_MAC_INVALID); unsigned char mac[] = "00:00:00:00:00:00"; - EXPECT_TRUE(DelMacFilter(mac, strlen((const char *)mac)) == WIFI_HAL_SUCCESS); + EXPECT_TRUE(DelMacFilter(mac, strlen((const char *)mac), 0) == WIFI_HAL_SUCCESS); } HWTEST_F(WifiHalApInterfaceTest, DisassociateStaTest, TestSize.Level1) { - EXPECT_TRUE(DisassociateSta(NULL, 0) == WIFI_HAL_FAILED); + EXPECT_TRUE(DisassociateSta(NULL, 0, 0) == WIFI_HAL_FAILED); unsigned char tmpMac[] = "00:00:00:00:00"; - EXPECT_TRUE(DisassociateSta(tmpMac, strlen((const char *)tmpMac)) == WIFI_HAL_FAILED); + EXPECT_TRUE(DisassociateSta(tmpMac, strlen((const char *)tmpMac), 0) == WIFI_HAL_FAILED); unsigned char tmpMac2[] = "00.00.00.00.00.00"; - EXPECT_TRUE(DisassociateSta(tmpMac2, strlen((const char *)tmpMac2)) == WIFI_HAL_INPUT_MAC_INVALID); + EXPECT_TRUE(DisassociateSta(tmpMac2, strlen((const char *)tmpMac2), 0) == WIFI_HAL_INPUT_MAC_INVALID); unsigned char mac[] = "00:00:00:00:00:00"; - EXPECT_TRUE(DisassociateSta(mac, strlen((const char *)mac)) == WIFI_HAL_SUCCESS); + EXPECT_TRUE(DisassociateSta(mac, strlen((const char *)mac), 0) == WIFI_HAL_SUCCESS); } HWTEST_F(WifiHalApInterfaceTest, GetValidFrequenciesForBandTest, TestSize.Level1) @@ -106,16 +106,17 @@ HWTEST_F(WifiHalApInterfaceTest, GetValidFrequenciesForBandTest, TestSize.Level1 int32_t band = AP_2GHZ_BAND; int frequencies[20] = {0}; int size = 20; - EXPECT_TRUE(GetValidFrequenciesForBand(band, NULL, NULL) == WIFI_HAL_FAILED); - EXPECT_TRUE(GetValidFrequenciesForBand(band, frequencies, NULL) == WIFI_HAL_FAILED); - EXPECT_TRUE(GetValidFrequenciesForBand(band, NULL, &size) == WIFI_HAL_FAILED); - WifiErrorNo err = GetValidFrequenciesForBand(band, frequencies, &size); - EXPECT_TRUE(err == WIFI_HAL_SUCCESS || err == WIFI_HAL_NOT_SUPPORT); + EXPECT_TRUE(GetValidFrequenciesForBand(band, NULL, NULL, 0) == WIFI_HAL_FAILED); + EXPECT_TRUE(GetValidFrequenciesForBand(band, frequencies, NULL, 0) == WIFI_HAL_FAILED); + EXPECT_TRUE(GetValidFrequenciesForBand(band, NULL, &size, 0) == WIFI_HAL_FAILED); + WifiErrorNo err = GetValidFrequenciesForBand(band, frequencies, &size, 0); + // WIFI_HAL_FAILED: Some devices do not support + EXPECT_TRUE(err == WIFI_HAL_SUCCESS || err == WIFI_HAL_NOT_SUPPORT || err == WIFI_HAL_FAILED); } HWTEST_F(WifiHalApInterfaceTest, StopSoftApTest, TestSize.Level1) { - EXPECT_TRUE(StopSoftAp() == WIFI_HAL_SUCCESS); + EXPECT_TRUE(StopSoftAp(0) == WIFI_HAL_SUCCESS); } } // namespace Wifi } // namespace OHOS \ No newline at end of file diff --git a/tests/wifi_standard/wifi_hal/unittest/wifi_hal_ap_interface_test.h b/wifi/test/wifi_standard/wifi_hal/unittest/wifi_hal_ap_interface_test.h similarity index 100% rename from tests/wifi_standard/wifi_hal/unittest/wifi_hal_ap_interface_test.h rename to wifi/test/wifi_standard/wifi_hal/unittest/wifi_hal_ap_interface_test.h diff --git a/tests/wifi_standard/wifi_hal/unittest/wifi_hal_base_interface_test.cpp b/wifi/test/wifi_standard/wifi_hal/unittest/wifi_hal_base_interface_test.cpp similarity index 100% rename from tests/wifi_standard/wifi_hal/unittest/wifi_hal_base_interface_test.cpp rename to wifi/test/wifi_standard/wifi_hal/unittest/wifi_hal_base_interface_test.cpp diff --git a/tests/wifi_standard/wifi_hal/unittest/wifi_hal_base_interface_test.h b/wifi/test/wifi_standard/wifi_hal/unittest/wifi_hal_base_interface_test.h similarity index 100% rename from tests/wifi_standard/wifi_hal/unittest/wifi_hal_base_interface_test.h rename to wifi/test/wifi_standard/wifi_hal/unittest/wifi_hal_base_interface_test.h diff --git a/tests/wifi_standard/wifi_hal/unittest/wifi_hal_chip_interface_test.cpp b/wifi/test/wifi_standard/wifi_hal/unittest/wifi_hal_chip_interface_test.cpp similarity index 96% rename from tests/wifi_standard/wifi_hal/unittest/wifi_hal_chip_interface_test.cpp rename to wifi/test/wifi_standard/wifi_hal/unittest/wifi_hal_chip_interface_test.cpp index 62bea0db4e27b2a96b7db57c87962c9cfb15cb29..54d6252a7b69d46d2a82750ac9e16e33f426fe38 100644 --- a/tests/wifi_standard/wifi_hal/unittest/wifi_hal_chip_interface_test.cpp +++ b/wifi/test/wifi_standard/wifi_hal/unittest/wifi_hal_chip_interface_test.cpp @@ -97,10 +97,5 @@ HWTEST_F(WifiHalChipInterfaceTest, RequestFirmwareDebugDumpTest, TestSize.Level1 int size = 32; EXPECT_TRUE(RequestFirmwareDebugDump(bytes, &size) == WIFI_HAL_NOT_SUPPORT); } - -HWTEST_F(WifiHalChipInterfaceTest, SetPowerModeTest, TestSize.Level1) -{ - EXPECT_TRUE(SetPowerMode(0) == WIFI_HAL_SUCCESS); -} } // namespace Wifi } // namespace OHOS \ No newline at end of file diff --git a/tests/wifi_standard/wifi_hal/unittest/wifi_hal_chip_interface_test.h b/wifi/test/wifi_standard/wifi_hal/unittest/wifi_hal_chip_interface_test.h similarity index 100% rename from tests/wifi_standard/wifi_hal/unittest/wifi_hal_chip_interface_test.h rename to wifi/test/wifi_standard/wifi_hal/unittest/wifi_hal_chip_interface_test.h diff --git a/tests/wifi_standard/wifi_hal/unittest/wifi_hal_crpc_server_add_test.cpp b/wifi/test/wifi_standard/wifi_hal/unittest/wifi_hal_crpc_server_add_test.cpp similarity index 67% rename from tests/wifi_standard/wifi_hal/unittest/wifi_hal_crpc_server_add_test.cpp rename to wifi/test/wifi_standard/wifi_hal/unittest/wifi_hal_crpc_server_add_test.cpp index 2d2f949cf7f8b4ed8f96bc6f5ab2c833d00e9ec5..6ef6a36a433a6f76f7bf399b7d719a405a0b5036 100644 --- a/tests/wifi_standard/wifi_hal/unittest/wifi_hal_crpc_server_add_test.cpp +++ b/wifi/test/wifi_standard/wifi_hal/unittest/wifi_hal_crpc_server_add_test.cpp @@ -1,5 +1,5 @@ /* - * Copyright (C) 2021 Huawei Device Co., Ltd. + * Copyright (C) 2021-2022 Huawei Device Co., Ltd. * 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 @@ -86,14 +86,14 @@ HWTEST_F(WifiHalCRpcServerAddTest, RpcP2pStopTest, TestSize.Level1) HWTEST_F(WifiHalCRpcServerAddTest, RpcP2pSetRandomMacTest, TestSize.Level1) { EXPECT_TRUE(RpcP2pSetRandomMac(nullptr, nullptr) < 0); - char buff[] = "N|P2pSetRandomMac|1"; + char buff[] = "N\tP2pSetRandomMac\t1"; mContext->oneProcess = buff; - mContext->nPos = strlen("N|P2pSetRandomMac|"); + mContext->nPos = strlen("N\tP2pSetRandomMac\t"); mContext->nSize = strlen(buff); EXPECT_TRUE(RpcP2pSetRandomMac(mServer, mContext) < 0); - char buff1[] = "N|P2pSetRandomMac|1|"; + char buff1[] = "N\tP2pSetRandomMac\t1\t"; mContext->oneProcess = buff1; - mContext->nPos = strlen("N|P2pSetRandomMac|"); + mContext->nPos = strlen("N\tP2pSetRandomMac\t"); mContext->nSize = strlen(buff1); EXPECT_TRUE(RpcP2pSetRandomMac(mServer, mContext) == 0); } @@ -101,14 +101,14 @@ HWTEST_F(WifiHalCRpcServerAddTest, RpcP2pSetRandomMacTest, TestSize.Level1) HWTEST_F(WifiHalCRpcServerAddTest, RpcP2pSetDeviceNameTest, TestSize.Level1) { EXPECT_TRUE(RpcP2pSetDeviceName(nullptr, nullptr) < 0); - char buff[] = "N|P2pSetDeviceName|p2p_device_name"; + char buff[] = "N\tP2pSetDeviceName\tp2p_device_name"; mContext->oneProcess = buff; - mContext->nPos = strlen("N|P2pSetDeviceName|"); + mContext->nPos = strlen("N\tP2pSetDeviceName\t"); mContext->nSize = strlen(buff); EXPECT_TRUE(RpcP2pSetDeviceName(mServer, mContext) < 0); - char buff1[] = "N|P2pSetDeviceName|p2p_device_name|"; + char buff1[] = "N\tP2pSetDeviceName\tp2p_device_name\t"; mContext->oneProcess = buff1; - mContext->nPos = strlen("N|P2pSetDeviceName|"); + mContext->nPos = strlen("N\tP2pSetDeviceName\t"); mContext->nSize = strlen(buff1); EXPECT_TRUE(RpcP2pSetDeviceName(mServer, mContext) == 0); } @@ -116,14 +116,14 @@ HWTEST_F(WifiHalCRpcServerAddTest, RpcP2pSetDeviceNameTest, TestSize.Level1) HWTEST_F(WifiHalCRpcServerAddTest, RpcP2pSetSsidPostfixNameTest, TestSize.Level1) { EXPECT_TRUE(RpcP2pSetSsidPostfixName(nullptr, nullptr) < 0); - char buff[] = "N|P2pSetSsidPostfixName|p2p_postfix_name"; + char buff[] = "N\tP2pSetSsidPostfixName\tp2p_postfix_name"; mContext->oneProcess = buff; - mContext->nPos = strlen("N|P2pSetSsidPostfixName|"); + mContext->nPos = strlen("N\tP2pSetSsidPostfixName\t"); mContext->nSize = strlen(buff); EXPECT_TRUE(RpcP2pSetSsidPostfixName(mServer, mContext) < 0); - char buff1[] = "N|P2pSetSsidPostfixName|p2p_postfix_name|"; + char buff1[] = "N\tP2pSetSsidPostfixName\tp2p_postfix_name\t"; mContext->oneProcess = buff1; - mContext->nPos = strlen("N|P2pSetSsidPostfixName|"); + mContext->nPos = strlen("N\tP2pSetSsidPostfixName\t"); mContext->nSize = strlen(buff1); EXPECT_TRUE(RpcP2pSetSsidPostfixName(mServer, mContext) == 0); } @@ -131,14 +131,14 @@ HWTEST_F(WifiHalCRpcServerAddTest, RpcP2pSetSsidPostfixNameTest, TestSize.Level1 HWTEST_F(WifiHalCRpcServerAddTest, RpcP2pSetWpsDeviceTypeTest, TestSize.Level1) { EXPECT_TRUE(RpcP2pSetWpsDeviceType(nullptr, nullptr) < 0); - char buff[] = "N|P2pSetWpsDeviceType|p2p_device_type"; + char buff[] = "N\tP2pSetWpsDeviceType\tp2p_device_type"; mContext->oneProcess = buff; - mContext->nPos = strlen("N|P2pSetWpsDeviceType|"); + mContext->nPos = strlen("N\tP2pSetWpsDeviceType\t"); mContext->nSize = strlen(buff); EXPECT_TRUE(RpcP2pSetWpsDeviceType(mServer, mContext) < 0); - char buff1[] = "N|P2pSetWpsDeviceType|p2p_device_type|"; + char buff1[] = "N\tP2pSetWpsDeviceType\tp2p_device_type\t"; mContext->oneProcess = buff1; - mContext->nPos = strlen("N|P2pSetWpsDeviceType|"); + mContext->nPos = strlen("N\tP2pSetWpsDeviceType\t"); mContext->nSize = strlen(buff1); EXPECT_TRUE(RpcP2pSetWpsDeviceType(mServer, mContext) == 0); } @@ -146,14 +146,14 @@ HWTEST_F(WifiHalCRpcServerAddTest, RpcP2pSetWpsDeviceTypeTest, TestSize.Level1) HWTEST_F(WifiHalCRpcServerAddTest, RpcP2pSetWpsConfigMethodsTest, TestSize.Level1) { EXPECT_TRUE(RpcP2pSetWpsConfigMethods(nullptr, nullptr) < 0); - char buff[] = "N|P2pSetWpsConfigMethods|p2p_config_methods"; + char buff[] = "N\tP2pSetWpsConfigMethods\tp2p_config_methods"; mContext->oneProcess = buff; - mContext->nPos = strlen("N|P2pSetWpsConfigMethods|"); + mContext->nPos = strlen("N\tP2pSetWpsConfigMethods\t"); mContext->nSize = strlen(buff); EXPECT_TRUE(RpcP2pSetWpsConfigMethods(mServer, mContext) < 0); - char buff1[] = "N|P2pSetWpsConfigMethods|p2p_config_methods|"; + char buff1[] = "N\tP2pSetWpsConfigMethods\tp2p_config_methods\t"; mContext->oneProcess = buff1; - mContext->nPos = strlen("N|P2pSetWpsConfigMethods|"); + mContext->nPos = strlen("N\tP2pSetWpsConfigMethods\t"); mContext->nSize = strlen(buff1); EXPECT_TRUE(RpcP2pSetWpsConfigMethods(mServer, mContext) == 0); } @@ -161,19 +161,19 @@ HWTEST_F(WifiHalCRpcServerAddTest, RpcP2pSetWpsConfigMethodsTest, TestSize.Level HWTEST_F(WifiHalCRpcServerAddTest, RpcP2pGetDeviceAddressTest, TestSize.Level1) { EXPECT_TRUE(RpcP2pGetDeviceAddress(nullptr, nullptr) < 0); - char buff[] = "N|P2pGetDeviceAddress|17"; + char buff[] = "N\tP2pGetDeviceAddress\t17"; mContext->oneProcess = buff; - mContext->nPos = strlen("N|P2pGetDeviceAddress|"); + mContext->nPos = strlen("N\tP2pGetDeviceAddress\t"); mContext->nSize = strlen(buff); EXPECT_TRUE(RpcP2pGetDeviceAddress(mServer, mContext) < 0); - char buff1[] = "N|P2pGetDeviceAddress|17|"; + char buff1[] = "N\tP2pGetDeviceAddress\t17\t"; mContext->oneProcess = buff1; - mContext->nPos = strlen("N|P2pGetDeviceAddress|"); + mContext->nPos = strlen("N\tP2pGetDeviceAddress\t"); mContext->nSize = strlen(buff1); EXPECT_TRUE(RpcP2pGetDeviceAddress(mServer, mContext) == 0); - char buff2[] = "N|P2pGetDeviceAddress|-1|"; + char buff2[] = "N\tP2pGetDeviceAddress\t-1\t"; mContext->oneProcess = buff2; - mContext->nPos = strlen("N|P2pGetDeviceAddress|"); + mContext->nPos = strlen("N\tP2pGetDeviceAddress\t"); mContext->nSize = strlen(buff2); EXPECT_TRUE(RpcP2pGetDeviceAddress(mServer, mContext) < 0); } @@ -199,14 +199,14 @@ HWTEST_F(WifiHalCRpcServerAddTest, RpcP2pSaveConfigTest, TestSize.Level1) HWTEST_F(WifiHalCRpcServerAddTest, RpcP2pSetupWpsPbcTest, TestSize.Level1) { EXPECT_TRUE(RpcP2pSetupWpsPbc(nullptr, nullptr) < 0); - char buff[] = "N|P2pSetupWpsPbc|p2p-dev-wlan0|00:00:00:00:00:00"; + char buff[] = "N\tP2pSetupWpsPbc\tp2p-dev-wlan0\t00:00:00:00:00:00"; mContext->oneProcess = buff; - mContext->nPos = strlen("N|P2pSetupWpsPbc|"); + mContext->nPos = strlen("N\tP2pSetupWpsPbc\t"); mContext->nSize = strlen(buff); EXPECT_TRUE(RpcP2pSetupWpsPbc(mServer, mContext) < 0); - char buff1[] = "N|P2pSetupWpsPbc|p2p-dev-wlan0|00:00:00:00:00:00|"; + char buff1[] = "N\tP2pSetupWpsPbc\tp2p-dev-wlan0\t00:00:00:00:00:00\t"; mContext->oneProcess = buff1; - mContext->nPos = strlen("N|P2pSetupWpsPbc|"); + mContext->nPos = strlen("N\tP2pSetupWpsPbc\t"); mContext->nSize = strlen(buff1); EXPECT_TRUE(RpcP2pSetupWpsPbc(mServer, mContext) == 0); } @@ -214,14 +214,14 @@ HWTEST_F(WifiHalCRpcServerAddTest, RpcP2pSetupWpsPbcTest, TestSize.Level1) HWTEST_F(WifiHalCRpcServerAddTest, RpcP2pSetupWpsPinTest, TestSize.Level1) { EXPECT_TRUE(RpcP2pSetupWpsPin(nullptr, nullptr) < 0); - char buff[] = "N|P2pSetupWpsPin|p2p-dev-wlan0|00:00:00:00:00:00|123456789|8|"; + char buff[] = "N\tP2pSetupWpsPiN\tp2p-dev-wlan0\t00:00:00:00:00:00\t123456789\t8\t"; mContext->oneProcess = buff; - mContext->nPos = strlen("N|P2pSetupWpsPin|"); + mContext->nPos = strlen("N\tP2pSetupWpsPiN\t"); mContext->nSize = strlen(buff); EXPECT_TRUE(RpcP2pSetupWpsPin(mServer, mContext) < 0); - char buff1[] = "N|P2pSetupWpsPin|p2p-dev-wlan0|00:00:00:00:00:00|12345678|8|"; + char buff1[] = "N\tP2pSetupWpsPiN\tp2p-dev-wlan0\t00:00:00:00:00:00\t12345678\t8\t"; mContext->oneProcess = buff1; - mContext->nPos = strlen("N|P2pSetupWpsPin|"); + mContext->nPos = strlen("N\tP2pSetupWpsPiN\t"); mContext->nSize = strlen(buff1); EXPECT_TRUE(RpcP2pSetupWpsPin(mServer, mContext) == 0); } @@ -229,14 +229,14 @@ HWTEST_F(WifiHalCRpcServerAddTest, RpcP2pSetupWpsPinTest, TestSize.Level1) HWTEST_F(WifiHalCRpcServerAddTest, RpcP2pRemoveNetworkTest, TestSize.Level1) { EXPECT_TRUE(RpcP2pRemoveNetwork(nullptr, nullptr) < 0); - char buff[] = "N|P2pRemoveNetwork|1"; + char buff[] = "N\tP2pRemoveNetwork\t1"; mContext->oneProcess = buff; - mContext->nPos = strlen("N|P2pRemoveNetwork|"); + mContext->nPos = strlen("N\tP2pRemoveNetwork\t"); mContext->nSize = strlen(buff); EXPECT_TRUE(RpcP2pRemoveNetwork(mServer, mContext) < 0); - char buff1[] = "N|P2pRemoveNetwork|1|"; + char buff1[] = "N\tP2pRemoveNetwork\t1\t"; mContext->oneProcess = buff1; - mContext->nPos = strlen("N|P2pRemoveNetwork|"); + mContext->nPos = strlen("N\tP2pRemoveNetwork\t"); mContext->nSize = strlen(buff1); EXPECT_TRUE(RpcP2pRemoveNetwork(mServer, mContext) == 0); } @@ -250,14 +250,14 @@ HWTEST_F(WifiHalCRpcServerAddTest, RpcP2pListNetworksTest, TestSize.Level1) HWTEST_F(WifiHalCRpcServerAddTest, RpcP2pSetGroupMaxIdleTest, TestSize.Level1) { EXPECT_TRUE(RpcP2pSetGroupMaxIdle(nullptr, nullptr) < 0); - char buff[] = "N|P2pSetGroupMaxIdle|p2p-dev-wlan0|1"; + char buff[] = "N\tP2pSetGroupMaxIdle\tp2p-dev-wlan0\t1"; mContext->oneProcess = buff; - mContext->nPos = strlen("N|P2pSetGroupMaxIdle|"); + mContext->nPos = strlen("N\tP2pSetGroupMaxIdle\t"); mContext->nSize = strlen(buff); EXPECT_TRUE(RpcP2pSetGroupMaxIdle(mServer, mContext) < 0); - char buff1[] = "N|P2pSetGroupMaxIdle|p2p-dev-wlan0|1|"; + char buff1[] = "N\tP2pSetGroupMaxIdle\tp2p-dev-wlan0\t1\t"; mContext->oneProcess = buff1; - mContext->nPos = strlen("N|P2pSetGroupMaxIdle|"); + mContext->nPos = strlen("N\tP2pSetGroupMaxIdle\t"); mContext->nSize = strlen(buff1); EXPECT_TRUE(RpcP2pSetGroupMaxIdle(mServer, mContext) == 0); } @@ -265,14 +265,14 @@ HWTEST_F(WifiHalCRpcServerAddTest, RpcP2pSetGroupMaxIdleTest, TestSize.Level1) HWTEST_F(WifiHalCRpcServerAddTest, RpcP2pSetPowerSaveTest, TestSize.Level1) { EXPECT_TRUE(RpcP2pSetPowerSave(nullptr, nullptr) < 0); - char buff[] = "N|P2pSetPowerSave|p2p-dev-wlan0|1"; + char buff[] = "N\tP2pSetPowerSave\tp2p-dev-wlan0\t1"; mContext->oneProcess = buff; - mContext->nPos = strlen("N|P2pSetPowerSave|"); + mContext->nPos = strlen("N\tP2pSetPowerSave\t"); mContext->nSize = strlen(buff); EXPECT_TRUE(RpcP2pSetPowerSave(mServer, mContext) < 0); - char buff1[] = "N|P2pSetPowerSave|p2p-dev-wlan0|1|"; + char buff1[] = "N\tP2pSetPowerSave\tp2p-dev-wlan0\t1\t"; mContext->oneProcess = buff1; - mContext->nPos = strlen("N|P2pSetPowerSave|"); + mContext->nPos = strlen("N\tP2pSetPowerSave\t"); mContext->nSize = strlen(buff1); EXPECT_TRUE(RpcP2pSetPowerSave(mServer, mContext) == 0); } @@ -280,14 +280,14 @@ HWTEST_F(WifiHalCRpcServerAddTest, RpcP2pSetPowerSaveTest, TestSize.Level1) HWTEST_F(WifiHalCRpcServerAddTest, RpcP2pSetWfdEnableTest, TestSize.Level1) { EXPECT_TRUE(RpcP2pSetWfdEnable(nullptr, nullptr) < 0); - char buff[] = "N|P2pSetWfdEnable|1"; + char buff[] = "N\tP2pSetWfdEnable\t1"; mContext->oneProcess = buff; - mContext->nPos = strlen("N|P2pSetWfdEnable|"); + mContext->nPos = strlen("N\tP2pSetWfdEnable\t"); mContext->nSize = strlen(buff); EXPECT_TRUE(RpcP2pSetWfdEnable(mServer, mContext) < 0); - char buff1[] = "N|P2pSetWfdEnable|1|"; + char buff1[] = "N\tP2pSetWfdEnable\t1\t"; mContext->oneProcess = buff1; - mContext->nPos = strlen("N|P2pSetWfdEnable|"); + mContext->nPos = strlen("N\tP2pSetWfdEnable\t"); mContext->nSize = strlen(buff1); EXPECT_TRUE(RpcP2pSetWfdEnable(mServer, mContext) == 0); } @@ -295,14 +295,14 @@ HWTEST_F(WifiHalCRpcServerAddTest, RpcP2pSetWfdEnableTest, TestSize.Level1) HWTEST_F(WifiHalCRpcServerAddTest, RpcP2pSetWfdDeviceConfigTest, TestSize.Level1) { EXPECT_TRUE(RpcP2pSetWfdDeviceConfig(nullptr, nullptr) < 0); - char buff[] = "N|P2pSetWfdDeviceConfig|p2p_device_config"; + char buff[] = "N\tP2pSetWfdDeviceConfig\tp2p_device_config"; mContext->oneProcess = buff; - mContext->nPos = strlen("N|P2pSetWfdDeviceConfig|"); + mContext->nPos = strlen("N\tP2pSetWfdDeviceConfig\t"); mContext->nSize = strlen(buff); EXPECT_TRUE(RpcP2pSetWfdDeviceConfig(mServer, mContext) < 0); - char buff1[] = "N|P2pSetWfdDeviceConfig|p2p_device_config|"; + char buff1[] = "N\tP2pSetWfdDeviceConfig\tp2p_device_config\t"; mContext->oneProcess = buff1; - mContext->nPos = strlen("N|P2pSetWfdDeviceConfig|"); + mContext->nPos = strlen("N\tP2pSetWfdDeviceConfig\t"); mContext->nSize = strlen(buff1); EXPECT_TRUE(RpcP2pSetWfdDeviceConfig(mServer, mContext) == 0); } @@ -310,14 +310,14 @@ HWTEST_F(WifiHalCRpcServerAddTest, RpcP2pSetWfdDeviceConfigTest, TestSize.Level1 HWTEST_F(WifiHalCRpcServerAddTest, RpcP2pStartFindTest, TestSize.Level1) { EXPECT_TRUE(RpcP2pStartFind(nullptr, nullptr) < 0); - char buff[] = "N|P2pStartFind|120"; + char buff[] = "N\tP2pStartFind\t120"; mContext->oneProcess = buff; - mContext->nPos = strlen("N|P2pStartFind|"); + mContext->nPos = strlen("N\tP2pStartFind\t"); mContext->nSize = strlen(buff); EXPECT_TRUE(RpcP2pStartFind(mServer, mContext) < 0); - char buff1[] = "N|P2pStartFind|120|"; + char buff1[] = "N\tP2pStartFind\t120\t"; mContext->oneProcess = buff1; - mContext->nPos = strlen("N|P2pStartFind|"); + mContext->nPos = strlen("N\tP2pStartFind\t"); mContext->nSize = strlen(buff1); EXPECT_TRUE(RpcP2pStartFind(mServer, mContext) == 0); } @@ -331,14 +331,14 @@ HWTEST_F(WifiHalCRpcServerAddTest, RpcP2pStopFindTest, TestSize.Level1) HWTEST_F(WifiHalCRpcServerAddTest, RpcP2pSetExtListenTest, TestSize.Level1) { EXPECT_TRUE(RpcP2pSetExtListen(nullptr, nullptr) < 0); - char buff[] = "N|P2pSetExtListen|0|0|0"; + char buff[] = "N\tP2pSetExtListeN\t0\t0\t0"; mContext->oneProcess = buff; - mContext->nPos = strlen("N|P2pSetExtListen|"); + mContext->nPos = strlen("N\tP2pSetExtListeN\t"); mContext->nSize = strlen(buff); EXPECT_TRUE(RpcP2pSetExtListen(mServer, mContext) < 0); - char buff1[] = "N|P2pSetExtListen|0|0|0|"; + char buff1[] = "N\tP2pSetExtListeN\t0\t0\t0\t"; mContext->oneProcess = buff1; - mContext->nPos = strlen("N|P2pSetExtListen|"); + mContext->nPos = strlen("N\tP2pSetExtListeN\t"); mContext->nSize = strlen(buff1); EXPECT_TRUE(RpcP2pSetExtListen(mServer, mContext) == 0); } @@ -346,14 +346,14 @@ HWTEST_F(WifiHalCRpcServerAddTest, RpcP2pSetExtListenTest, TestSize.Level1) HWTEST_F(WifiHalCRpcServerAddTest, RpcP2pSetListenChannelTest, TestSize.Level1) { EXPECT_TRUE(RpcP2pSetListenChannel(nullptr, nullptr) < 0); - char buff[] = "N|P2pSetListenChannel|0|0"; + char buff[] = "N\tP2pSetListenChannel\t0\t0"; mContext->oneProcess = buff; - mContext->nPos = strlen("N|P2pSetListenChannel|"); + mContext->nPos = strlen("N\tP2pSetListenChannel\t"); mContext->nSize = strlen(buff); EXPECT_TRUE(RpcP2pSetListenChannel(mServer, mContext) < 0); - char buff1[] = "N|P2pSetListenChannel|0|0|"; + char buff1[] = "N\tP2pSetListenChannel\t0\t0\t"; mContext->oneProcess = buff1; - mContext->nPos = strlen("N|P2pSetListenChannel|"); + mContext->nPos = strlen("N\tP2pSetListenChannel\t"); mContext->nSize = strlen(buff1); EXPECT_TRUE(RpcP2pSetListenChannel(mServer, mContext) == 0); } @@ -361,19 +361,19 @@ HWTEST_F(WifiHalCRpcServerAddTest, RpcP2pSetListenChannelTest, TestSize.Level1) HWTEST_F(WifiHalCRpcServerAddTest, RpcP2pConnectTest, TestSize.Level1) { EXPECT_TRUE(RpcP2pConnect(nullptr, nullptr) < 0); - char buff[] = "N|P2pConnect|0|0|0|0|00:00:00:00:00:00|12345678"; + char buff[] = "N\tP2pConnect\t0\t0\t0\t0\t00:00:00:00:00:00\t12345678"; mContext->oneProcess = buff; - mContext->nPos = strlen("N|P2pConnect|"); + mContext->nPos = strlen("N\tP2pConnect\t"); mContext->nSize = strlen(buff); EXPECT_TRUE(RpcP2pConnect(mServer, mContext) < 0); - char buff1[] = "N|P2pConnect|0|0|0|0|00:00:00:00:00:00|12345678|"; + char buff1[] = "N\tP2pConnect\t0\t0\t0\t0\t00:00:00:00:00:00\t12345678\t"; mContext->oneProcess = buff1; - mContext->nPos = strlen("N|P2pConnect|"); + mContext->nPos = strlen("N\tP2pConnect\t"); mContext->nSize = strlen(buff1); EXPECT_TRUE(RpcP2pConnect(mServer, mContext) == 0); - char buff2[] = "N|P2pConnect|0|1|0|0|00:00:00:00:00:00|pin|"; + char buff2[] = "N\tP2pConnect\t0\t1\t0\t0\t00:00:00:00:00:00\tpiN\t"; mContext->oneProcess = buff2; - mContext->nPos = strlen("N|P2pConnect|"); + mContext->nPos = strlen("N\tP2pConnect\t"); mContext->nSize = strlen(buff2); EXPECT_TRUE(RpcP2pConnect(mServer, mContext) == 0); } @@ -387,14 +387,14 @@ HWTEST_F(WifiHalCRpcServerAddTest, RpcP2pCancelConnectTest, TestSize.Level1) HWTEST_F(WifiHalCRpcServerAddTest, RpcP2pProvisionDiscoveryTest, TestSize.Level1) { EXPECT_TRUE(RpcP2pProvisionDiscovery(nullptr, nullptr) < 0); - char buff[] = "N|P2pProvisionDiscovery|00:00:00:00:00:00|1"; + char buff[] = "N\tP2pProvisionDiscovery\t00:00:00:00:00:00\t1"; mContext->oneProcess = buff; - mContext->nPos = strlen("N|P2pProvisionDiscovery|"); + mContext->nPos = strlen("N\tP2pProvisionDiscovery\t"); mContext->nSize = strlen(buff); EXPECT_TRUE(RpcP2pProvisionDiscovery(mServer, mContext) < 0); - char buff1[] = "N|P2pProvisionDiscovery|00:00:00:00:00:00|1|"; + char buff1[] = "N\tP2pProvisionDiscovery\t00:00:00:00:00:00\t1\t"; mContext->oneProcess = buff1; - mContext->nPos = strlen("N|P2pProvisionDiscovery|"); + mContext->nPos = strlen("N\tP2pProvisionDiscovery\t"); mContext->nSize = strlen(buff1); EXPECT_TRUE(RpcP2pProvisionDiscovery(mServer, mContext) == 0); } @@ -402,14 +402,14 @@ HWTEST_F(WifiHalCRpcServerAddTest, RpcP2pProvisionDiscoveryTest, TestSize.Level1 HWTEST_F(WifiHalCRpcServerAddTest, RpcP2pAddGroupTest, TestSize.Level1) { EXPECT_TRUE(RpcP2pAddGroup(nullptr, nullptr) < 0); - char buff[] = "N|P2pAddGroup|0|1|0"; + char buff[] = "N\tP2pAddGroup\t0\t1\t0"; mContext->oneProcess = buff; - mContext->nPos = strlen("N|P2pAddGroup|"); + mContext->nPos = strlen("N\tP2pAddGroup\t"); mContext->nSize = strlen(buff); EXPECT_TRUE(RpcP2pAddGroup(mServer, mContext) < 0); - char buff1[] = "N|P2pAddGroup|0|1|0|"; + char buff1[] = "N\tP2pAddGroup\t0\t1\t0\t"; mContext->oneProcess = buff1; - mContext->nPos = strlen("N|P2pAddGroup|"); + mContext->nPos = strlen("N\tP2pAddGroup\t"); mContext->nSize = strlen(buff1); EXPECT_TRUE(RpcP2pAddGroup(mServer, mContext) == 0); } @@ -417,14 +417,14 @@ HWTEST_F(WifiHalCRpcServerAddTest, RpcP2pAddGroupTest, TestSize.Level1) HWTEST_F(WifiHalCRpcServerAddTest, RpcP2pRemoveGroupTest, TestSize.Level1) { EXPECT_TRUE(RpcP2pRemoveGroup(nullptr, nullptr) < 0); - char buff[] = "N|P2pRemoveGroup|p2p-dev-wlan0"; + char buff[] = "N\tP2pRemoveGroup\tp2p-dev-wlan0"; mContext->oneProcess = buff; - mContext->nPos = strlen("N|P2pRemoveGroup|"); + mContext->nPos = strlen("N\tP2pRemoveGroup\t"); mContext->nSize = strlen(buff); EXPECT_TRUE(RpcP2pRemoveGroup(mServer, mContext) < 0); - char buff1[] = "N|P2pRemoveGroup|p2p-dev-wlan0|"; + char buff1[] = "N\tP2pRemoveGroup\tp2p-dev-wlan0\t"; mContext->oneProcess = buff1; - mContext->nPos = strlen("N|P2pRemoveGroup|"); + mContext->nPos = strlen("N\tP2pRemoveGroup\t"); mContext->nSize = strlen(buff1); EXPECT_TRUE(RpcP2pRemoveGroup(mServer, mContext) == 0); } @@ -432,29 +432,29 @@ HWTEST_F(WifiHalCRpcServerAddTest, RpcP2pRemoveGroupTest, TestSize.Level1) HWTEST_F(WifiHalCRpcServerAddTest, RpcP2pInviteTest, TestSize.Level1) { EXPECT_TRUE(RpcP2pInvite(nullptr, nullptr) < 0); - char buff[] = "N|P2pInvite|0|||p2p-dev-wlan0"; + char buff[] = "N\tP2pInvite\t0\tp2p-dev-wlan0"; mContext->oneProcess = buff; - mContext->nPos = strlen("N|P2pInvite|"); + mContext->nPos = strlen("N\tP2pInvite\t"); mContext->nSize = strlen(buff); EXPECT_TRUE(RpcP2pInvite(mServer, mContext) < 0); - char buff1[] = "N|P2pInvite|0|||p2p-dev-wlan0|"; + char buff1[] = "N\tP2pInvite\t0\tp2p-dev-wlan0\t"; mContext->oneProcess = buff1; - mContext->nPos = strlen("N|P2pInvite|"); + mContext->nPos = strlen("N\tP2pInvite\t"); mContext->nSize = strlen(buff1); - EXPECT_TRUE(RpcP2pInvite(mServer, mContext) == 0); + EXPECT_TRUE(RpcP2pInvite(mServer, mContext) < 0); } HWTEST_F(WifiHalCRpcServerAddTest, RpcP2pReinvokeTest, TestSize.Level1) { EXPECT_TRUE(RpcP2pReinvoke(nullptr, nullptr) < 0); - char buff[] = "N|P2pReinvoke|0|00:00:00:00:00:00"; + char buff[] = "N\tP2pReinvoke\t0\t00:00:00:00:00:00"; mContext->oneProcess = buff; - mContext->nPos = strlen("N|P2pReinvoke|"); + mContext->nPos = strlen("N\tP2pReinvoke\t"); mContext->nSize = strlen(buff); EXPECT_TRUE(RpcP2pReinvoke(mServer, mContext) < 0); - char buff1[] = "N|P2pReinvoke|0|00:00:00:00:00:00|"; + char buff1[] = "N\tP2pReinvoke\t0\t00:00:00:00:00:00\t"; mContext->oneProcess = buff1; - mContext->nPos = strlen("N|P2pReinvoke|"); + mContext->nPos = strlen("N\tP2pReinvoke\t"); mContext->nSize = strlen(buff1); EXPECT_TRUE(RpcP2pReinvoke(mServer, mContext) == 0); } @@ -462,14 +462,14 @@ HWTEST_F(WifiHalCRpcServerAddTest, RpcP2pReinvokeTest, TestSize.Level1) HWTEST_F(WifiHalCRpcServerAddTest, RpcP2pGetGroupCapabilityTest, TestSize.Level1) { EXPECT_TRUE(RpcP2pGetGroupCapability(nullptr, nullptr) < 0); - char buff[] = "N|P2pGetGroupCapability|00:00:00:00:00:00"; + char buff[] = "N\tP2pGetGroupCapability\t00:00:00:00:00:00"; mContext->oneProcess = buff; - mContext->nPos = strlen("N|P2pGetGroupCapability|"); + mContext->nPos = strlen("N\tP2pGetGroupCapability\t"); mContext->nSize = strlen(buff); EXPECT_TRUE(RpcP2pGetGroupCapability(mServer, mContext) < 0); - char buff1[] = "N|P2pGetGroupCapability|00:00:00:00:00:00|"; + char buff1[] = "N\tP2pGetGroupCapability\t00:00:00:00:00:00\t"; mContext->oneProcess = buff1; - mContext->nPos = strlen("N|P2pGetGroupCapability|"); + mContext->nPos = strlen("N\tP2pGetGroupCapability\t"); mContext->nSize = strlen(buff1); EXPECT_TRUE(RpcP2pGetGroupCapability(mServer, mContext) == 0); } @@ -477,29 +477,29 @@ HWTEST_F(WifiHalCRpcServerAddTest, RpcP2pGetGroupCapabilityTest, TestSize.Level1 HWTEST_F(WifiHalCRpcServerAddTest, RpcP2pAddServiceTest, TestSize.Level1) { EXPECT_TRUE(RpcP2pAddService(nullptr, nullptr) < 0); - char buff[] = "N|P2pAddService|x|0|service_name"; + char buff[] = "N\tP2pAddService\tx\t0\tservice_name"; mContext->oneProcess = buff; - mContext->nPos = strlen("N|P2pAddService|"); + mContext->nPos = strlen("N\tP2pAddService\t"); mContext->nSize = strlen(buff); EXPECT_TRUE(RpcP2pAddService(mServer, mContext) < 0); - char buff1[] = "N|P2pAddService|0|0|service_name"; + char buff1[] = "N\tP2pAddService\t0\t0\tservice_name"; mContext->oneProcess = buff1; - mContext->nPos = strlen("N|P2pAddService|"); + mContext->nPos = strlen("N\tP2pAddService\t"); mContext->nSize = strlen(buff1); EXPECT_TRUE(RpcP2pAddService(mServer, mContext) < 0); - char buff2[] = "N|P2pAddService|0|0|service_name|"; + char buff2[] = "N\tP2pAddService\t0\t0\tservice_name\t"; mContext->oneProcess = buff2; - mContext->nPos = strlen("N|P2pAddService|"); + mContext->nPos = strlen("N\tP2pAddService\t"); mContext->nSize = strlen(buff2); EXPECT_TRUE(RpcP2pAddService(mServer, mContext) == 0); - char buff3[] = "N|P2pAddService|1|query_message|resp_message"; + char buff3[] = "N\tP2pAddService\t1\tquery_message\tresp_message"; mContext->oneProcess = buff3; - mContext->nPos = strlen("N|P2pAddService|"); + mContext->nPos = strlen("N\tP2pAddService\t"); mContext->nSize = strlen(buff3); EXPECT_TRUE(RpcP2pAddService(mServer, mContext) < 0); - char buff4[] = "N|P2pAddService|1|query_message|resp_message|"; + char buff4[] = "N\tP2pAddService\t1\tquery_message\tresp_message\t"; mContext->oneProcess = buff4; - mContext->nPos = strlen("N|P2pAddService|"); + mContext->nPos = strlen("N\tP2pAddService\t"); mContext->nSize = strlen(buff4); EXPECT_TRUE(RpcP2pAddService(mServer, mContext) == 0); } @@ -507,29 +507,29 @@ HWTEST_F(WifiHalCRpcServerAddTest, RpcP2pAddServiceTest, TestSize.Level1) HWTEST_F(WifiHalCRpcServerAddTest, RpcP2pRemoveServiceTest, TestSize.Level1) { EXPECT_TRUE(RpcP2pRemoveService(nullptr, nullptr) < 0); - char buff[] = "N|P2pRemoveService|x|0|service_name"; + char buff[] = "N\tP2pRemoveService\tx\t0\tservice_name"; mContext->oneProcess = buff; - mContext->nPos = strlen("N|P2pRemoveService|"); + mContext->nPos = strlen("N\tP2pRemoveService\t"); mContext->nSize = strlen(buff); EXPECT_TRUE(RpcP2pRemoveService(mServer, mContext) < 0); - char buff1[] = "N|P2pRemoveService|0|0|service_name"; + char buff1[] = "N\tP2pRemoveService\t0\t0\tservice_name"; mContext->oneProcess = buff1; - mContext->nPos = strlen("N|P2pRemoveService|"); + mContext->nPos = strlen("N\tP2pRemoveService\t"); mContext->nSize = strlen(buff1); EXPECT_TRUE(RpcP2pRemoveService(mServer, mContext) < 0); - char buff2[] = "N|P2pRemoveService|0|0|service_name|"; + char buff2[] = "N\tP2pRemoveService\t0\t0\tservice_name\t"; mContext->oneProcess = buff2; - mContext->nPos = strlen("N|P2pRemoveService|"); + mContext->nPos = strlen("N\tP2pRemoveService\t"); mContext->nSize = strlen(buff2); EXPECT_TRUE(RpcP2pRemoveService(mServer, mContext) == 0); - char buff3[] = "N|P2pRemoveService|1|query_message"; + char buff3[] = "N\tP2pRemoveService\t1\tquery_message"; mContext->oneProcess = buff3; - mContext->nPos = strlen("N|P2pRemoveService|"); + mContext->nPos = strlen("N\tP2pRemoveService\t"); mContext->nSize = strlen(buff3); EXPECT_TRUE(RpcP2pRemoveService(mServer, mContext) < 0); - char buff4[] = "N|P2pRemoveService|1|query_message|"; + char buff4[] = "N\tP2pRemoveService\t1\tquery_message\t"; mContext->oneProcess = buff4; - mContext->nPos = strlen("N|P2pRemoveService|"); + mContext->nPos = strlen("N\tP2pRemoveService\t"); mContext->nSize = strlen(buff4); EXPECT_TRUE(RpcP2pRemoveService(mServer, mContext) == 0); } @@ -537,14 +537,14 @@ HWTEST_F(WifiHalCRpcServerAddTest, RpcP2pRemoveServiceTest, TestSize.Level1) HWTEST_F(WifiHalCRpcServerAddTest, RpcP2pReqServiceDiscoveryTest, TestSize.Level1) { EXPECT_TRUE(RpcP2pReqServiceDiscovery(nullptr, nullptr) < 0); - char buff[] = "N|P2pReqServiceDiscovery|00:00:00:00:00:00|discover message"; + char buff[] = "N\tP2pReqServiceDiscovery\t00:00:00:00:00:00\tdiscover message"; mContext->oneProcess = buff; - mContext->nPos = strlen("N|P2pReqServiceDiscovery|"); + mContext->nPos = strlen("N\tP2pReqServiceDiscovery\t"); mContext->nSize = strlen(buff); EXPECT_TRUE(RpcP2pReqServiceDiscovery(mServer, mContext) < 0); - char buff1[] = "N|P2pReqServiceDiscovery|00:00:00:00:00:00|discover message|32|"; + char buff1[] = "N\tP2pReqServiceDiscovery\t00:00:00:00:00:00\tdiscover message\t32\t"; mContext->oneProcess = buff1; - mContext->nPos = strlen("N|P2pReqServiceDiscovery|"); + mContext->nPos = strlen("N\tP2pReqServiceDiscovery\t"); mContext->nSize = strlen(buff1); EXPECT_TRUE(RpcP2pReqServiceDiscovery(mServer, mContext) == 0); } @@ -552,14 +552,14 @@ HWTEST_F(WifiHalCRpcServerAddTest, RpcP2pReqServiceDiscoveryTest, TestSize.Level HWTEST_F(WifiHalCRpcServerAddTest, RpcP2pCancelServiceDiscoveryTest, TestSize.Level1) { EXPECT_TRUE(RpcP2pCancelServiceDiscovery(nullptr, nullptr) < 0); - char buff[] = "N|P2pCancelServiceDiscovery|discover message"; + char buff[] = "N\tP2pCancelServiceDiscovery\tdiscover message"; mContext->oneProcess = buff; - mContext->nPos = strlen("N|P2pCancelServiceDiscovery|"); + mContext->nPos = strlen("N\tP2pCancelServiceDiscovery\t"); mContext->nSize = strlen(buff); EXPECT_TRUE(RpcP2pCancelServiceDiscovery(mServer, mContext) < 0); - char buff1[] = "N|P2pCancelServiceDiscovery|discover message|"; + char buff1[] = "N\tP2pCancelServiceDiscovery\tdiscover message\t"; mContext->oneProcess = buff1; - mContext->nPos = strlen("N|P2pCancelServiceDiscovery|"); + mContext->nPos = strlen("N\tP2pCancelServiceDiscovery\t"); mContext->nSize = strlen(buff1); EXPECT_TRUE(RpcP2pCancelServiceDiscovery(mServer, mContext) == 0); } @@ -567,14 +567,14 @@ HWTEST_F(WifiHalCRpcServerAddTest, RpcP2pCancelServiceDiscoveryTest, TestSize.Le HWTEST_F(WifiHalCRpcServerAddTest, RpcP2pSetMiracastTypeTest, TestSize.Level1) { EXPECT_TRUE(RpcP2pSetMiracastType(nullptr, nullptr) < 0); - char buff[] = "N|P2pSetMiracastType|x|"; + char buff[] = "N\tP2pSetMiracastType\tx\t"; mContext->oneProcess = buff; - mContext->nPos = strlen("N|P2pSetMiracastType|"); + mContext->nPos = strlen("N\tP2pSetMiracastType\t"); mContext->nSize = strlen(buff); EXPECT_TRUE(RpcP2pSetMiracastType(mServer, mContext) < 0); - char buff1[] = "N|P2pSetMiracastType|1|"; + char buff1[] = "N\tP2pSetMiracastType\t1\t"; mContext->oneProcess = buff1; - mContext->nPos = strlen("N|P2pSetMiracastType|"); + mContext->nPos = strlen("N\tP2pSetMiracastType\t"); mContext->nSize = strlen(buff1); EXPECT_TRUE(RpcP2pSetMiracastType(mServer, mContext) == 0); } @@ -582,14 +582,14 @@ HWTEST_F(WifiHalCRpcServerAddTest, RpcP2pSetMiracastTypeTest, TestSize.Level1) HWTEST_F(WifiHalCRpcServerAddTest, RpcP2pRespServerDiscoveryTest, TestSize.Level1) { EXPECT_TRUE(RpcP2pRespServerDiscovery(nullptr, nullptr) < 0); - char buff[] = "N|P2pRespServerDiscovery|0|0|00:00:00:00:00:00|tlvs message"; + char buff[] = "N\tP2pRespServerDiscovery\t0\t0\t00:00:00:00:00:00\ttlvs message"; mContext->oneProcess = buff; - mContext->nPos = strlen("N|P2pRespServerDiscovery|"); + mContext->nPos = strlen("N\tP2pRespServerDiscovery\t"); mContext->nSize = strlen(buff); EXPECT_TRUE(RpcP2pRespServerDiscovery(mServer, mContext) < 0); - char buff1[] = "N|P2pRespServerDiscovery|0|0|00:00:00:00:00:00|tlvs message|"; + char buff1[] = "N\tP2pRespServerDiscovery\t0\t0\t00:00:00:00:00:00\ttlvs message\t"; mContext->oneProcess = buff1; - mContext->nPos = strlen("N|P2pRespServerDiscovery|"); + mContext->nPos = strlen("N\tP2pRespServerDiscovery\t"); mContext->nSize = strlen(buff1); EXPECT_TRUE(RpcP2pRespServerDiscovery(mServer, mContext) == 0); } @@ -597,14 +597,14 @@ HWTEST_F(WifiHalCRpcServerAddTest, RpcP2pRespServerDiscoveryTest, TestSize.Level HWTEST_F(WifiHalCRpcServerAddTest, RpcP2pSetServDiscExternalTest, TestSize.Level1) { EXPECT_TRUE(RpcP2pSetServDiscExternal(nullptr, nullptr) < 0); - char buff[] = "N|P2pSetServDiscExternal|x|"; + char buff[] = "N\tP2pSetServDiscExternal\tx\t"; mContext->oneProcess = buff; - mContext->nPos = strlen("N|P2pSetServDiscExternal|"); + mContext->nPos = strlen("N\tP2pSetServDiscExternal\t"); mContext->nSize = strlen(buff); EXPECT_TRUE(RpcP2pSetServDiscExternal(mServer, mContext) < 0); - char buff1[] = "N|P2pSetServDiscExternal|1|"; + char buff1[] = "N\tP2pSetServDiscExternal\t1\t"; mContext->oneProcess = buff1; - mContext->nPos = strlen("N|P2pSetServDiscExternal|"); + mContext->nPos = strlen("N\tP2pSetServDiscExternal\t"); mContext->nSize = strlen(buff1); EXPECT_TRUE(RpcP2pSetServDiscExternal(mServer, mContext) == 0); } @@ -612,14 +612,14 @@ HWTEST_F(WifiHalCRpcServerAddTest, RpcP2pSetServDiscExternalTest, TestSize.Level HWTEST_F(WifiHalCRpcServerAddTest, RpcP2pSetPersistentReconnectTest, TestSize.Level1) { EXPECT_TRUE(RpcP2pSetPersistentReconnect(nullptr, nullptr) < 0); - char buff[] = "N|P2pSetPersistentReconnect|x|"; + char buff[] = "N\tP2pSetPersistentReconnect\tx\t"; mContext->oneProcess = buff; - mContext->nPos = strlen("N|P2pSetPersistentReconnect|"); + mContext->nPos = strlen("N\tP2pSetPersistentReconnect\t"); mContext->nSize = strlen(buff); EXPECT_TRUE(RpcP2pSetPersistentReconnect(mServer, mContext) < 0); - char buff1[] = "N|P2pSetPersistentReconnect|1|"; + char buff1[] = "N\tP2pSetPersistentReconnect\t1\t"; mContext->oneProcess = buff1; - mContext->nPos = strlen("N|P2pSetPersistentReconnect|"); + mContext->nPos = strlen("N\tP2pSetPersistentReconnect\t"); mContext->nSize = strlen(buff1); EXPECT_TRUE(RpcP2pSetPersistentReconnect(mServer, mContext) == 0); } diff --git a/tests/wifi_standard/wifi_hal/unittest/wifi_hal_crpc_server_add_test.h b/wifi/test/wifi_standard/wifi_hal/unittest/wifi_hal_crpc_server_add_test.h similarity index 100% rename from tests/wifi_standard/wifi_hal/unittest/wifi_hal_crpc_server_add_test.h rename to wifi/test/wifi_standard/wifi_hal/unittest/wifi_hal_crpc_server_add_test.h diff --git a/tests/wifi_standard/wifi_hal/unittest/wifi_hal_crpc_server_test.cpp b/wifi/test/wifi_standard/wifi_hal/unittest/wifi_hal_crpc_server_test.cpp similarity index 72% rename from tests/wifi_standard/wifi_hal/unittest/wifi_hal_crpc_server_test.cpp rename to wifi/test/wifi_standard/wifi_hal/unittest/wifi_hal_crpc_server_test.cpp index b95c984e082e25b2f66a0f7cd77b42ed5bd988ab..357dbb66762c9f2453ff5867dacd07b4adb863e5 100644 --- a/tests/wifi_standard/wifi_hal/unittest/wifi_hal_crpc_server_test.cpp +++ b/wifi/test/wifi_standard/wifi_hal/unittest/wifi_hal_crpc_server_test.cpp @@ -1,5 +1,5 @@ /* - * Copyright (C) 2021 Huawei Device Co., Ltd. + * Copyright (C) 2021-2022 Huawei Device Co., Ltd. * 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 @@ -94,18 +94,18 @@ HWTEST_F(WifiHalCRpcServerTest, GetRpcFuncTest, TestSize.Level1) HWTEST_F(WifiHalCRpcServerTest, OnTransactTest, TestSize.Level1) { - char buff[] = "N|IncorrectTypeInputMessage"; + char buff[] = "N\tIncorrectTypeInputMessage"; mContext->oneProcess = buff; mContext->nPos = 2; mContext->nSize = strlen(buff); EXPECT_TRUE(OnTransact(mServer, mContext) < 0); - char buff2[] = "N|UnsupportedCmd|"; + char buff2[] = "N\tUnsupportedCmd\t"; mContext->oneProcess = buff2; mContext->nPos = 2; mContext->nSize = strlen(buff2); EXPECT_TRUE(OnTransact(mServer, mContext) == 0); - EXPECT_TRUE(strstr(mContext->szWrite, "unsupport function") != nullptr); - char buff3[] = "N|SetCountryCode|"; + EXPECT_TRUE(strstr(mContext->szWrite, "unsupported function") != nullptr); + char buff3[] = "N\tSetCountryCode\t"; mContext->oneProcess = buff3; mContext->nPos = 2; mContext->nSize = strlen(buff3); @@ -161,18 +161,19 @@ HWTEST_F(WifiHalCRpcServerTest, DealCommonCbkTest, TestSize.Level1) cbmsg->msg.scanStatus = 100; EXPECT_TRUE(PushBackCallbackMsg(WIFI_SCAN_INFO_NOTIFY_EVENT, cbmsg) == 0); EXPECT_TRUE(OnCallbackTransact(mServer, WIFI_SCAN_INFO_NOTIFY_EVENT, mContext) == 0); - EXPECT_TRUE(StrcmpMathRight(mContext->szWrite, "C|107|100|$$$$$$") == 0); + EXPECT_TRUE(StrcmpMathRight(mContext->szWrite, "C\t107\t100\t$$$$$$") == 0); EXPECT_TRUE(EndCallbackTransact(mServer, WIFI_SCAN_INFO_NOTIFY_EVENT) == 0); } HWTEST_F(WifiHalCRpcServerTest, DealIfaceCbkTest, TestSize.Level1) { WifiHalEventCallbackMsg *cbmsg = (WifiHalEventCallbackMsg *)calloc(1, sizeof(WifiHalEventCallbackMsg)); + cbmsg->msg.ifMsg.id = 0; cbmsg->msg.ifMsg.type = 100; StrSafeCopy(cbmsg->msg.ifMsg.ifname, sizeof(cbmsg->msg.ifMsg.ifname), "wlan0"); EXPECT_TRUE(PushBackCallbackMsg(WIFI_ADD_IFACE_EVENT, cbmsg) == 0); EXPECT_TRUE(OnCallbackTransact(mServer, WIFI_ADD_IFACE_EVENT, mContext) == 0); - EXPECT_TRUE(StrcmpMathRight(mContext->szWrite, "C|103|100|wlan0|$$$$$$") == 0); + EXPECT_TRUE(StrcmpMathRight(mContext->szWrite, "C\t103\t0\t100\twlan0\t$$$$$$") == 0); EXPECT_TRUE(EndCallbackTransact(mServer, WIFI_ADD_IFACE_EVENT) == 0); } @@ -184,7 +185,7 @@ HWTEST_F(WifiHalCRpcServerTest, DealConnectionChangedCbkTest, TestSize.Level1) StrSafeCopy(cbmsg->msg.connMsg.bssid, sizeof(cbmsg->msg.connMsg.bssid), "00:00:00:00:00:00"); EXPECT_TRUE(PushBackCallbackMsg(WIFI_CONNECT_CHANGED_NOTIFY_EVENT, cbmsg) == 0); EXPECT_TRUE(OnCallbackTransact(mServer, WIFI_CONNECT_CHANGED_NOTIFY_EVENT, mContext) == 0); - EXPECT_TRUE(StrcmpMathRight(mContext->szWrite, "C|108|100|1|00:00:00:00:00:00|$$$$$$") == 0); + EXPECT_TRUE(StrcmpMathRight(mContext->szWrite, "C\t108\t100\t1\t00:00:00:00:00:00\t$$$$$$") == 0); EXPECT_TRUE(EndCallbackTransact(mServer, WIFI_CONNECT_CHANGED_NOTIFY_EVENT) == 0); } @@ -194,7 +195,7 @@ HWTEST_F(WifiHalCRpcServerTest, DealP2pDeviceFoundCbkTest, TestSize.Level1) StrSafeCopy(cbmsg->msg.deviceInfo.srcAddress, sizeof(cbmsg->msg.deviceInfo.srcAddress), "00:00:00:00:00:00"); EXPECT_TRUE(PushBackCallbackMsg(P2P_DEVICE_FOUND_EVENT, cbmsg) == 0); EXPECT_TRUE(OnCallbackTransact(mServer, P2P_DEVICE_FOUND_EVENT, mContext) == 0); - EXPECT_TRUE(StrcmpMathRight(mContext->szWrite, "C|117|0|0|0|0|00:00:00:00:00:00|||||$$$$$$") == 0); + EXPECT_TRUE(StrcmpMathRight(mContext->szWrite, "C\t120\t0\t0\t0\t0\t00:00:00:00:00:00\t\t\t\t\t$$$$$$") == 0); EXPECT_TRUE(EndCallbackTransact(mServer, P2P_DEVICE_FOUND_EVENT) == 0); } @@ -204,7 +205,7 @@ HWTEST_F(WifiHalCRpcServerTest, DealP2pNegoriationCbkLostTest, TestSize.Level1) StrSafeCopy(cbmsg->msg.connMsg.bssid, sizeof(cbmsg->msg.connMsg.bssid), "00:00:00:00:00:00"); EXPECT_TRUE(PushBackCallbackMsg(P2P_DEVICE_LOST_EVENT, cbmsg) == 0); EXPECT_TRUE(OnCallbackTransact(mServer, P2P_DEVICE_LOST_EVENT, mContext) == 0); - EXPECT_TRUE(StrcmpMathRight(mContext->szWrite, "C|118|00:00:00:00:00:00|$$$$$$") == 0); + EXPECT_TRUE(StrcmpMathRight(mContext->szWrite, "C\t121\t00:00:00:00:00:00\t$$$$$$") == 0); EXPECT_TRUE(EndCallbackTransact(mServer, P2P_DEVICE_LOST_EVENT) == 0); } @@ -214,7 +215,7 @@ HWTEST_F(WifiHalCRpcServerTest, DealP2pNegoriationCbkTest, TestSize.Level1) StrSafeCopy(cbmsg->msg.connMsg.bssid, sizeof(cbmsg->msg.connMsg.bssid), "00:00:00:00:00:00"); EXPECT_TRUE(PushBackCallbackMsg(P2P_GO_NEGOTIATION_REQUEST_EVENT, cbmsg) == 0); EXPECT_TRUE(OnCallbackTransact(mServer, P2P_GO_NEGOTIATION_REQUEST_EVENT, mContext) == 0); - EXPECT_TRUE(StrcmpMathRight(mContext->szWrite, "C|119|0|00:00:00:00:00:00|$$$$$$") == 0); + EXPECT_TRUE(StrcmpMathRight(mContext->szWrite, "C\t122\t0\t00:00:00:00:00:00\t$$$$$$") == 0); EXPECT_TRUE(EndCallbackTransact(mServer, P2P_GO_NEGOTIATION_REQUEST_EVENT) == 0); } @@ -225,7 +226,8 @@ HWTEST_F(WifiHalCRpcServerTest, DealP2pInviationCbkReceiveTest, TestSize.Level1) StrSafeCopy(cbmsg->msg.invitaInfo.bssid, sizeof(cbmsg->msg.invitaInfo.bssid), "00:00:00:00:00:00"); EXPECT_TRUE(PushBackCallbackMsg(P2P_INVITATION_RECEIVED_EVENT, cbmsg) == 0); EXPECT_TRUE(OnCallbackTransact(mServer, P2P_INVITATION_RECEIVED_EVENT, mContext) == 0); - EXPECT_TRUE(StrcmpMathRight(mContext->szWrite, "C|122|0|0|0|00:00:00:00:00:00||00:00:00:00:00:00|$$$$$$") == 0); + EXPECT_TRUE(StrcmpMathRight(mContext->szWrite, + "C\t125\t0\t0\t0\t00:00:00:00:00:00\t\t00:00:00:00:00:00\t$$$$$$") == 0); EXPECT_TRUE(EndCallbackTransact(mServer, P2P_INVITATION_RECEIVED_EVENT) == 0); } @@ -235,7 +237,7 @@ HWTEST_F(WifiHalCRpcServerTest, DealP2pInviationCbkResultTest, TestSize.Level1) StrSafeCopy(cbmsg->msg.invitaInfo.bssid, sizeof(cbmsg->msg.invitaInfo.bssid), "00:00:00:00:00:00"); EXPECT_TRUE(PushBackCallbackMsg(P2P_INVITATION_RESULT_EVENT, cbmsg) == 0); EXPECT_TRUE(OnCallbackTransact(mServer, P2P_INVITATION_RESULT_EVENT, mContext) == 0); - EXPECT_TRUE(StrcmpMathRight(mContext->szWrite, "C|123|0|00:00:00:00:00:00|$$$$$$") == 0); + EXPECT_TRUE(StrcmpMathRight(mContext->szWrite, "C\t126\t0\t00:00:00:00:00:00\t$$$$$$") == 0); EXPECT_TRUE(EndCallbackTransact(mServer, P2P_INVITATION_RESULT_EVENT) == 0); } @@ -245,7 +247,7 @@ HWTEST_F(WifiHalCRpcServerTest, DealP2pInviationCbkFailureTest, TestSize.Level1) StrSafeCopy(cbmsg->msg.invitaInfo.bssid, sizeof(cbmsg->msg.invitaInfo.bssid), "00:00:00:00:00:00"); EXPECT_TRUE(PushBackCallbackMsg(P2P_GROUP_FORMATION_FAILURE_EVENT, cbmsg) == 0); EXPECT_TRUE(OnCallbackTransact(mServer, P2P_GROUP_FORMATION_FAILURE_EVENT, mContext) == 0); - EXPECT_TRUE(StrcmpMathRight(mContext->szWrite, "C|125|00:00:00:00:00:00|$$$$$$") == 0); + EXPECT_TRUE(StrcmpMathRight(mContext->szWrite, "C\t128\t00:00:00:00:00:00\t$$$$$$") == 0); EXPECT_TRUE(EndCallbackTransact(mServer, P2P_GROUP_FORMATION_FAILURE_EVENT) == 0); } @@ -258,8 +260,8 @@ HWTEST_F(WifiHalCRpcServerTest, DealP2pGroupInfoCbkStartTest, TestSize.Level1) cbmsg->msg.groupInfo.goDeviceAddress, sizeof(cbmsg->msg.groupInfo.goDeviceAddress), "00:00:00:00:00:00"); EXPECT_TRUE(PushBackCallbackMsg(P2P_GROUP_STARTED_EVENT, cbmsg) == 0); EXPECT_TRUE(OnCallbackTransact(mServer, P2P_GROUP_STARTED_EVENT, mContext) == 0); - EXPECT_TRUE( - StrcmpMathRight(mContext->szWrite, "C|126|0|0|0|p2p-dev-wlan0|test_p2p|||00:00:00:00:00:00|$$$$$$") == 0); + EXPECT_TRUE(StrcmpMathRight(mContext->szWrite, + "C\t129\t0\t0\t0\tp2p-dev-wlan0\ttest_p2p\t\t\t00:00:00:00:00:00\t$$$$$$") == 0); EXPECT_TRUE(EndCallbackTransact(mServer, P2P_GROUP_STARTED_EVENT) == 0); } @@ -269,7 +271,7 @@ HWTEST_F(WifiHalCRpcServerTest, DealP2pGroupInfoCbkRemoveTest, TestSize.Level1) StrSafeCopy(cbmsg->msg.groupInfo.groupIfName, sizeof(cbmsg->msg.groupInfo.groupIfName), "p2p-dev-wlan0"); EXPECT_TRUE(PushBackCallbackMsg(P2P_GROUP_REMOVED_EVENT, cbmsg) == 0); EXPECT_TRUE(OnCallbackTransact(mServer, P2P_GROUP_REMOVED_EVENT, mContext) == 0); - EXPECT_TRUE(StrcmpMathRight(mContext->szWrite, "C|127|0|p2p-dev-wlan0|$$$$$$") == 0); + EXPECT_TRUE(StrcmpMathRight(mContext->szWrite, "C\t130\t0\tp2p-dev-wlan0\t$$$$$$") == 0); EXPECT_TRUE(EndCallbackTransact(mServer, P2P_GROUP_REMOVED_EVENT) == 0); } @@ -279,7 +281,7 @@ HWTEST_F(WifiHalCRpcServerTest, DealP2pDeviceInfoCbkPbcTest, TestSize.Level1) StrSafeCopy(cbmsg->msg.deviceInfo.srcAddress, sizeof(cbmsg->msg.deviceInfo.srcAddress), "00:00:00:00:00:00"); EXPECT_TRUE(PushBackCallbackMsg(P2P_PROV_DISC_PBC_REQ_EVENT, cbmsg) == 0); EXPECT_TRUE(OnCallbackTransact(mServer, P2P_PROV_DISC_PBC_REQ_EVENT, mContext) == 0); - EXPECT_TRUE(StrcmpMathRight(mContext->szWrite, "C|128|00:00:00:00:00:00|$$$$$$") == 0); + EXPECT_TRUE(StrcmpMathRight(mContext->szWrite, "C\t131\t00:00:00:00:00:00\t$$$$$$") == 0); EXPECT_TRUE(EndCallbackTransact(mServer, P2P_PROV_DISC_PBC_REQ_EVENT) == 0); } @@ -290,7 +292,7 @@ HWTEST_F(WifiHalCRpcServerTest, DealP2pDeviceInfoCbkPinTest, TestSize.Level1) StrSafeCopy(cbmsg->msg.deviceInfo.deviceName, sizeof(cbmsg->msg.deviceInfo.deviceName), "test_p2p"); EXPECT_TRUE(PushBackCallbackMsg(P2P_PROV_DISC_SHOW_PIN_EVENT, cbmsg) == 0); EXPECT_TRUE(OnCallbackTransact(mServer, P2P_PROV_DISC_SHOW_PIN_EVENT, mContext) == 0); - EXPECT_TRUE(StrcmpMathRight(mContext->szWrite, "C|131|00:00:00:00:00:00|test_p2p|$$$$$$") == 0); + EXPECT_TRUE(StrcmpMathRight(mContext->szWrite, "C\t134\t00:00:00:00:00:00\ttest_p2p\t$$$$$$") == 0); EXPECT_TRUE(EndCallbackTransact(mServer, P2P_PROV_DISC_SHOW_PIN_EVENT) == 0); } @@ -301,7 +303,7 @@ HWTEST_F(WifiHalCRpcServerTest, DealP2pDeviceInfoCbkConnectionTest, TestSize.Lev cbmsg->msg.deviceInfo.p2pDeviceAddress, sizeof(cbmsg->msg.deviceInfo.p2pDeviceAddress), "00:00:00:00:00:00"); EXPECT_TRUE(PushBackCallbackMsg(AP_STA_DISCONNECTED_EVENT, cbmsg) == 0); EXPECT_TRUE(OnCallbackTransact(mServer, AP_STA_DISCONNECTED_EVENT, mContext) == 0); - EXPECT_TRUE(StrcmpMathRight(mContext->szWrite, "C|135|00:00:00:00:00:00|$$$$$$") == 0); + EXPECT_TRUE(StrcmpMathRight(mContext->szWrite, "C\t138\t00:00:00:00:00:00\t$$$$$$") == 0); EXPECT_TRUE(EndCallbackTransact(mServer, AP_STA_DISCONNECTED_EVENT) == 0); } @@ -311,7 +313,7 @@ HWTEST_F(WifiHalCRpcServerTest, DealP2pServerInfoCbkTest, TestSize.Level1) StrSafeCopy(cbmsg->msg.serverInfo.srcAddress, sizeof(cbmsg->msg.serverInfo.srcAddress), "00:00:00:00:00:00"); EXPECT_TRUE(PushBackCallbackMsg(P2P_SERV_DISC_RESP_EVENT, cbmsg) == 0); EXPECT_TRUE(OnCallbackTransact(mServer, P2P_SERV_DISC_RESP_EVENT, mContext) == 0); - EXPECT_TRUE(StrcmpMathRight(mContext->szWrite, "C|133|0|00:00:00:00:00:00|0|$$$$$$") == 0); + EXPECT_TRUE(StrcmpMathRight(mContext->szWrite, "C\t136\t0\t00:00:00:00:00:00\t0\t$$$$$$") == 0); EXPECT_TRUE(EndCallbackTransact(mServer, P2P_SERV_DISC_RESP_EVENT) == 0); } @@ -321,21 +323,21 @@ HWTEST_F(WifiHalCRpcServerTest, DealP2pServerDiscReqCbkTest, TestSize.Level1) StrSafeCopy(cbmsg->msg.serDiscReqInfo.mac, sizeof(cbmsg->msg.serDiscReqInfo.mac), "00:00:00:00:00:00"); EXPECT_TRUE(PushBackCallbackMsg(P2P_SERV_DISC_REQ_EVENT, cbmsg) == 0); EXPECT_TRUE(OnCallbackTransact(mServer, P2P_SERV_DISC_REQ_EVENT, mContext) == 0); - EXPECT_TRUE(StrcmpMathRight(mContext->szWrite, "C|137|0|0|0|00:00:00:00:00:00|0|$$$$$$") == 0); + EXPECT_TRUE(StrcmpMathRight(mContext->szWrite, "C\t140\t0\t0\t0\t00:00:00:00:00:00\t0\t$$$$$$") == 0); EXPECT_TRUE(EndCallbackTransact(mServer, P2P_SERV_DISC_REQ_EVENT) == 0); } HWTEST_F(WifiHalCRpcServerTest, RpcGetNameTest, TestSize.Level1) { EXPECT_TRUE(RpcGetName(nullptr, nullptr) < 0); - char buff[] = "N|GetName|x|"; + char buff[] = "N\tGetName\tx\t"; mContext->oneProcess = buff; - mContext->nPos = strlen("N|GetName|"); + mContext->nPos = strlen("N\tGetName\t"); mContext->nSize = strlen(buff); EXPECT_TRUE(RpcGetName(mServer, mContext) < 0); - char buff2[] = "N|GetName|128|"; + char buff2[] = "N\tGetName\t128\t"; mContext->oneProcess = buff2; - mContext->nPos = strlen("N|GetName|"); + mContext->nPos = strlen("N\tGetName\t"); mContext->nSize = strlen(buff2); EXPECT_TRUE(RpcGetName(mServer, mContext) == 0); } @@ -349,19 +351,19 @@ HWTEST_F(WifiHalCRpcServerTest, RpcGetTypeTest, TestSize.Level1) HWTEST_F(WifiHalCRpcServerTest, RpcRegisterEventCallbackTest, TestSize.Level1) { EXPECT_TRUE(RpcRegisterEventCallback(nullptr, nullptr) < 0); - char buff[] = "N|RegisterEventCallback|asdgfd|"; + char buff[] = "N\tRegisterEventCallback\tasdgfd\t"; mContext->oneProcess = buff; - mContext->nPos = strlen("N|RegisterEventCallback|"); + mContext->nPos = strlen("N\tRegisterEventCallback\t"); mContext->nSize = strlen(buff); EXPECT_TRUE(RpcRegisterEventCallback(mServer, mContext) < 0); - char buff2[] = "N|RegisterEventCallback|2|101|asdf|"; + char buff2[] = "N\tRegisterEventCallback\t2\t101\tasdf\t"; mContext->oneProcess = buff2; - mContext->nPos = strlen("N|RegisterEventCallback|"); + mContext->nPos = strlen("N\tRegisterEventCallback\t"); mContext->nSize = strlen(buff2); EXPECT_TRUE(RpcRegisterEventCallback(mServer, mContext) < 0); - char buff3[] = "N|RegisterEventCallback|2|101|108|"; + char buff3[] = "N\tRegisterEventCallback\t2\t101\t108\t"; mContext->oneProcess = buff3; - mContext->nPos = strlen("N|RegisterEventCallback|"); + mContext->nPos = strlen("N\tRegisterEventCallback\t"); mContext->nSize = strlen(buff3); EXPECT_TRUE(RpcRegisterEventCallback(mServer, mContext) == 0); } @@ -369,19 +371,19 @@ HWTEST_F(WifiHalCRpcServerTest, RpcRegisterEventCallbackTest, TestSize.Level1) HWTEST_F(WifiHalCRpcServerTest, RpcUnRegisterEventCallbackTest, TestSize.Level1) { EXPECT_TRUE(RpcUnRegisterEventCallback(nullptr, nullptr) < 0); - char buff[] = "N|UnRegisterEventCallback|asdgfd|"; + char buff[] = "N\tUnRegisterEventCallback\tasdgfd\t"; mContext->oneProcess = buff; - mContext->nPos = strlen("N|UnRegisterEventCallback|"); + mContext->nPos = strlen("N\tUnRegisterEventCallback\t"); mContext->nSize = strlen(buff); EXPECT_TRUE(RpcUnRegisterEventCallback(mServer, mContext) < 0); - char buff2[] = "N|UnRegisterEventCallback|2|101|asdf|"; + char buff2[] = "N\tUnRegisterEventCallback\t2\t101\tasdf\t"; mContext->oneProcess = buff2; - mContext->nPos = strlen("N|UnRegisterEventCallback|"); + mContext->nPos = strlen("N\tUnRegisterEventCallback\t"); mContext->nSize = strlen(buff2); EXPECT_TRUE(RpcUnRegisterEventCallback(mServer, mContext) < 0); - char buff3[] = "N|UnRegisterEventCallback|2|101|108|"; + char buff3[] = "N\tUnRegisterEventCallback\t2\t101\t108\t"; mContext->oneProcess = buff3; - mContext->nPos = strlen("N|UnRegisterEventCallback|"); + mContext->nPos = strlen("N\tUnRegisterEventCallback\t"); mContext->nSize = strlen(buff3); EXPECT_TRUE(RpcUnRegisterEventCallback(mServer, mContext) == 0); } @@ -395,14 +397,14 @@ HWTEST_F(WifiHalCRpcServerTest, RpcNotifyClearTest, TestSize.Level1) HWTEST_F(WifiHalCRpcServerTest, RpcGetWifiChipTest, TestSize.Level1) { EXPECT_TRUE(RpcGetWifiChip(nullptr, nullptr) < 0); - char buff[] = "N|GetWifiChip|adsgfsd|"; + char buff[] = "N\tGetWifiChip\tadsgfsd\t"; mContext->oneProcess = buff; - mContext->nPos = strlen("N|GetWifiChip|"); + mContext->nPos = strlen("N\tGetWifiChip\t"); mContext->nSize = strlen(buff); EXPECT_TRUE(RpcGetWifiChip(mServer, mContext) < 0); - char buff1[] = "N|GetWifiChip|8|"; + char buff1[] = "N\tGetWifiChip\t8\t"; mContext->oneProcess = buff1; - mContext->nPos = strlen("N|GetWifiChip|"); + mContext->nPos = strlen("N\tGetWifiChip\t"); mContext->nSize = strlen(buff1); EXPECT_TRUE(RpcGetWifiChip(mServer, mContext) == 0); } @@ -410,14 +412,14 @@ HWTEST_F(WifiHalCRpcServerTest, RpcGetWifiChipTest, TestSize.Level1) HWTEST_F(WifiHalCRpcServerTest, RpcGetWifiChipIdsTest, TestSize.Level1) { EXPECT_TRUE(RpcGetWifiChipIds(nullptr, nullptr) < 0); - char buff[] = "N|GetWifiChipIds|x|"; + char buff[] = "N\tGetWifiChipIds\tx\t"; mContext->oneProcess = buff; - mContext->nPos = strlen("N|GetWifiChipIds|"); + mContext->nPos = strlen("N\tGetWifiChipIds\t"); mContext->nSize = strlen(buff); EXPECT_TRUE(RpcGetWifiChipIds(mServer, mContext) < 0); - char buff1[] = "N|GetWifiChipIds|8|"; + char buff1[] = "N\tGetWifiChipIds\t8\t"; mContext->oneProcess = buff1; - mContext->nPos = strlen("N|GetWifiChipIds|"); + mContext->nPos = strlen("N\tGetWifiChipIds\t"); mContext->nSize = strlen(buff1); EXPECT_TRUE(RpcGetWifiChipIds(mServer, mContext) == 0); } @@ -431,14 +433,14 @@ HWTEST_F(WifiHalCRpcServerTest, RpcGetChipIdTest, TestSize.Level1) HWTEST_F(WifiHalCRpcServerTest, RpcCreateIfaceTest, TestSize.Level1) { EXPECT_TRUE(RpcCreateIface(nullptr, nullptr) < 0); - char buff[] = "N|CreateIface|fdshajkdsghk|"; + char buff[] = "N\tCreateIface\tfdshajkdsghk\t"; mContext->oneProcess = buff; - mContext->nPos = strlen("N|CreateIface|"); + mContext->nPos = strlen("N\tCreateIface\t"); mContext->nSize = strlen(buff); EXPECT_TRUE(RpcCreateIface(mServer, mContext) < 0); - char buff1[] = "N|CreateIface|8|"; + char buff1[] = "N\tCreateIface\t8\t"; mContext->oneProcess = buff1; - mContext->nPos = strlen("N|CreateIface|"); + mContext->nPos = strlen("N\tCreateIface\t"); mContext->nSize = strlen(buff1); EXPECT_TRUE(RpcCreateIface(mServer, mContext) == 0); } @@ -446,19 +448,19 @@ HWTEST_F(WifiHalCRpcServerTest, RpcCreateIfaceTest, TestSize.Level1) HWTEST_F(WifiHalCRpcServerTest, RpcGetIfaceTest, TestSize.Level1) { EXPECT_TRUE(RpcGetIface(nullptr, nullptr) < 0); - char buff[] = "N|GetIface|wlan0"; + char buff[] = "N\tGetIface\twlan0"; mContext->oneProcess = buff; - mContext->nPos = strlen("N|GetIface|"); + mContext->nPos = strlen("N\tGetIface\t"); mContext->nSize = strlen(buff); EXPECT_TRUE(RpcGetIface(mServer, mContext) < 0); - char buff1[] = "N|GetIface|wlan0|"; + char buff1[] = "N\tGetIface\twlan0\t"; mContext->oneProcess = buff1; - mContext->nPos = strlen("N|GetIface|"); + mContext->nPos = strlen("N\tGetIface\t"); mContext->nSize = strlen(buff1); EXPECT_TRUE(RpcGetIface(mServer, mContext) == 0); - char buff2[] = "N|GetIface|01234567890123456789012345678901|"; + char buff2[] = "N\tGetIface\t01234567890123456789012345678901\t"; mContext->oneProcess = buff2; - mContext->nPos = strlen("N|GetIface|"); + mContext->nPos = strlen("N\tGetIface\t"); mContext->nSize = strlen(buff2); EXPECT_TRUE(RpcGetIface(mServer, mContext) == 0); } @@ -466,19 +468,19 @@ HWTEST_F(WifiHalCRpcServerTest, RpcGetIfaceTest, TestSize.Level1) HWTEST_F(WifiHalCRpcServerTest, RpcGetIfaceNamesTest, TestSize.Level1) { EXPECT_TRUE(RpcGetIfaceNames(nullptr, nullptr) < 0); - char buff[] = "N|GetIfaceNames|asdgf|asdgf|"; + char buff[] = "N\tGetIfaceNames\tasdgf\tasdgf\t"; mContext->oneProcess = buff; - mContext->nPos = strlen("N|GetIfaceNames|"); + mContext->nPos = strlen("N\tGetIfaceNames\t"); mContext->nSize = strlen(buff); EXPECT_TRUE(RpcGetIfaceNames(mServer, mContext) < 0); - char buff1[] = "N|GetIfaceNames|12|asdgf|"; + char buff1[] = "N\tGetIfaceNames\t12\tasdgf\t"; mContext->oneProcess = buff1; - mContext->nPos = strlen("N|GetIfaceNames|"); + mContext->nPos = strlen("N\tGetIfaceNames\t"); mContext->nSize = strlen(buff1); EXPECT_TRUE(RpcGetIfaceNames(mServer, mContext) < 0); - char buff2[] = "N|GetIfaceNames|12|128|"; + char buff2[] = "N\tGetIfaceNames\t12\t128\t"; mContext->oneProcess = buff2; - mContext->nPos = strlen("N|GetIfaceNames|"); + mContext->nPos = strlen("N\tGetIfaceNames\t"); mContext->nSize = strlen(buff2); EXPECT_TRUE(RpcGetIfaceNames(mServer, mContext) == 0); } @@ -486,19 +488,19 @@ HWTEST_F(WifiHalCRpcServerTest, RpcGetIfaceNamesTest, TestSize.Level1) HWTEST_F(WifiHalCRpcServerTest, RpcRemoveIfaceTest, TestSize.Level1) { EXPECT_TRUE(RpcRemoveIface(nullptr, nullptr) < 0); - char buff[] = "N|RemoveIface|wlan0"; + char buff[] = "N\tRemoveIface\twlan0"; mContext->oneProcess = buff; - mContext->nPos = strlen("N|RemoveIface|"); + mContext->nPos = strlen("N\tRemoveIface\t"); mContext->nSize = strlen(buff); EXPECT_TRUE(RpcRemoveIface(mServer, mContext) < 0); - char buff1[] = "N|RemoveIface|wlan0|"; + char buff1[] = "N\tRemoveIface\twlan0\t"; mContext->oneProcess = buff1; - mContext->nPos = strlen("N|RemoveIface|"); + mContext->nPos = strlen("N\tRemoveIface\t"); mContext->nSize = strlen(buff1); EXPECT_TRUE(RpcRemoveIface(mServer, mContext) == 0); - char buff2[] = "N|RemoveIface|01234567890123456789012345678901|"; + char buff2[] = "N\tRemoveIface\t01234567890123456789012345678901\t"; mContext->oneProcess = buff2; - mContext->nPos = strlen("N|RemoveIface|"); + mContext->nPos = strlen("N\tRemoveIface\t"); mContext->nSize = strlen(buff2); EXPECT_TRUE(RpcRemoveIface(mServer, mContext) == 0); } @@ -512,14 +514,14 @@ HWTEST_F(WifiHalCRpcServerTest, RpcGetCapabilitiesTest, TestSize.Level1) HWTEST_F(WifiHalCRpcServerTest, RpcGetSupportedComboModesTest, TestSize.Level1) { EXPECT_TRUE(RpcGetSupportedComboModes(nullptr, nullptr) < 0); - char buff[] = "N|GetSupportedComboModes|asdgds|"; + char buff[] = "N\tGetSupportedComboModes\tasdgds\t"; mContext->oneProcess = buff; - mContext->nPos = strlen("N|GetSupportedComboModes|"); + mContext->nPos = strlen("N\tGetSupportedComboModes\t"); mContext->nSize = strlen(buff); EXPECT_TRUE(RpcGetSupportedComboModes(mServer, mContext) < 0); - char buff1[] = "N|GetSupportedComboModes|134|"; + char buff1[] = "N\tGetSupportedComboModes\t134\t"; mContext->oneProcess = buff1; - mContext->nPos = strlen("N|GetSupportedComboModes|"); + mContext->nPos = strlen("N\tGetSupportedComboModes\t"); mContext->nSize = strlen(buff1); EXPECT_TRUE(RpcGetSupportedComboModes(mServer, mContext) == 0); } @@ -527,14 +529,14 @@ HWTEST_F(WifiHalCRpcServerTest, RpcGetSupportedComboModesTest, TestSize.Level1) HWTEST_F(WifiHalCRpcServerTest, RpcConfigComboModesTest, TestSize.Level1) { EXPECT_TRUE(RpcConfigComboModes(nullptr, nullptr) < 0); - char buff[] = "N|ConfigComboModes|asdgds|"; + char buff[] = "N\tConfigComboModes\tasdgds\t"; mContext->oneProcess = buff; - mContext->nPos = strlen("N|ConfigComboModes|"); + mContext->nPos = strlen("N\tConfigComboModes\t"); mContext->nSize = strlen(buff); EXPECT_TRUE(RpcConfigComboModes(mServer, mContext) < 0); - char buff1[] = "N|ConfigComboModes|134|"; + char buff1[] = "N\tConfigComboModes\t134\t"; mContext->oneProcess = buff1; - mContext->nPos = strlen("N|ConfigComboModes|"); + mContext->nPos = strlen("N\tConfigComboModes\t"); mContext->nSize = strlen(buff1); EXPECT_TRUE(RpcConfigComboModes(mServer, mContext) == 0); } @@ -548,33 +550,18 @@ HWTEST_F(WifiHalCRpcServerTest, RpcGetComboModesTest, TestSize.Level1) HWTEST_F(WifiHalCRpcServerTest, RpcRequestFirmwareDebugDumpTest, TestSize.Level1) { EXPECT_TRUE(RpcRequestFirmwareDebugDump(nullptr, nullptr) < 0); - char buff[] = "N|RequestFirmwareDebugDump|asdgds|"; + char buff[] = "N\tRequestFirmwareDebugDump\tasdgds\t"; mContext->oneProcess = buff; - mContext->nPos = strlen("N|RequestFirmwareDebugDump|"); + mContext->nPos = strlen("N\tRequestFirmwareDebugDump\t"); mContext->nSize = strlen(buff); EXPECT_TRUE(RpcRequestFirmwareDebugDump(mServer, mContext) < 0); - char buff1[] = "N|RequestFirmwareDebugDump|134|"; + char buff1[] = "N\tRequestFirmwareDebugDump\t134\t"; mContext->oneProcess = buff1; - mContext->nPos = strlen("N|RequestFirmwareDebugDump|"); + mContext->nPos = strlen("N\tRequestFirmwareDebugDump\t"); mContext->nSize = strlen(buff1); EXPECT_TRUE(RpcRequestFirmwareDebugDump(mServer, mContext) == 0); } -HWTEST_F(WifiHalCRpcServerTest, RpcSetPowerModeTest, TestSize.Level1) -{ - EXPECT_TRUE(RpcSetPowerMode(nullptr, nullptr) < 0); - char buff[] = "N|SetPowerMode|asdgds|"; - mContext->oneProcess = buff; - mContext->nPos = strlen("N|SetPowerMode|"); - mContext->nSize = strlen(buff); - EXPECT_TRUE(RpcSetPowerMode(mServer, mContext) < 0); - char buff1[] = "N|SetPowerMode|1|"; - mContext->oneProcess = buff1; - mContext->nPos = strlen("N|SetPowerMode|"); - mContext->nSize = strlen(buff1); - EXPECT_TRUE(RpcSetPowerMode(mServer, mContext) == 0); -} - HWTEST_F(WifiHalCRpcServerTest, RpcStartTest, TestSize.Level1) { EXPECT_TRUE(RpcStart(nullptr, nullptr) < 0); @@ -614,19 +601,19 @@ HWTEST_F(WifiHalCRpcServerTest, RpcDisconnectSupplicantTest, TestSize.Level1) HWTEST_F(WifiHalCRpcServerTest, RpcRequestToSupplicantTest, TestSize.Level1) { EXPECT_TRUE(RpcRequestToSupplicant(nullptr, nullptr) < 0); - char buff[] = "N|RequestToSupplicant|asdf|"; + char buff[] = "N\tRequestToSupplicant\tasdf\t"; mContext->oneProcess = buff; - mContext->nPos = strlen("N|RequestToSupplicant|"); + mContext->nPos = strlen("N\tRequestToSupplicant\t"); mContext->nSize = strlen(buff); EXPECT_TRUE(RpcRequestToSupplicant(mServer, mContext) < 0); - char buff1[] = "N|RequestToSupplicant|4|8c677c8d5a|"; + char buff1[] = "N\tRequestToSupplicant\t4\t8c677c8d5a\t"; mContext->oneProcess = buff1; - mContext->nPos = strlen("N|RequestToSupplicant|"); + mContext->nPos = strlen("N\tRequestToSupplicant\t"); mContext->nSize = strlen(buff1); EXPECT_TRUE(RpcRequestToSupplicant(mServer, mContext) < 0); - char buff2[] = "N|RequestToSupplicant|4|8c677c8a|"; + char buff2[] = "N\tRequestToSupplicant\t4\t8c677c8a\t"; mContext->oneProcess = buff2; - mContext->nPos = strlen("N|RequestToSupplicant|"); + mContext->nPos = strlen("N\tRequestToSupplicant\t"); mContext->nSize = strlen(buff2); EXPECT_TRUE(RpcRequestToSupplicant(mServer, mContext) == 0); } @@ -634,14 +621,14 @@ HWTEST_F(WifiHalCRpcServerTest, RpcRequestToSupplicantTest, TestSize.Level1) HWTEST_F(WifiHalCRpcServerTest, RpcSetPowerSaveTest, TestSize.Level1) { EXPECT_TRUE(RpcSetPowerSave(nullptr, nullptr) < 0); - char buff[] = "N|SetPowerSave|fds|"; + char buff[] = "N\tSetPowerSave\tfds\t"; mContext->oneProcess = buff; - mContext->nPos = strlen("N|SetPowerSave|"); + mContext->nPos = strlen("N\tSetPowerSave\t"); mContext->nSize = strlen(buff); EXPECT_TRUE(RpcSetPowerSave(mServer, mContext) < 0); - char buff1[] = "N|SetPowerSave|1|"; + char buff1[] = "N\tSetPowerSave\t1\t"; mContext->oneProcess = buff1; - mContext->nPos = strlen("N|SetPowerSave|"); + mContext->nPos = strlen("N\tSetPowerSave\t"); mContext->nSize = strlen(buff1); EXPECT_TRUE(RpcSetPowerSave(mServer, mContext) == 0); } @@ -649,14 +636,14 @@ HWTEST_F(WifiHalCRpcServerTest, RpcSetPowerSaveTest, TestSize.Level1) HWTEST_F(WifiHalCRpcServerTest, RpcWpaSetCountryCodeTest, TestSize.Level1) { EXPECT_TRUE(RpcWpaSetCountryCode(nullptr, nullptr) < 0); - char buff[] = "N|WpaSetCountryCode|CHINA|"; + char buff[] = "N\tWpaSetCountryCode\tCHINA\t"; mContext->oneProcess = buff; - mContext->nPos = strlen("N|WpaSetCountryCode|"); + mContext->nPos = strlen("N\tWpaSetCountryCode\t"); mContext->nSize = strlen(buff); EXPECT_TRUE(RpcWpaSetCountryCode(mServer, mContext) < 0); - char buff1[] = "N|WpaSetCountryCode|CN|"; + char buff1[] = "N\tWpaSetCountryCode\tCN\t"; mContext->oneProcess = buff1; - mContext->nPos = strlen("N|WpaSetCountryCode|"); + mContext->nPos = strlen("N\tWpaSetCountryCode\t"); mContext->nSize = strlen(buff1); EXPECT_TRUE(RpcWpaSetCountryCode(mServer, mContext) == 0); } @@ -670,34 +657,34 @@ HWTEST_F(WifiHalCRpcServerTest, RpcWpaGetCountryCodeTest, TestSize.Level1) HWTEST_F(WifiHalCRpcServerTest, RpcStartScanTest, TestSize.Level1) { EXPECT_TRUE(RpcStartScan(nullptr, nullptr) < 0); - char buff[] = "N|StartScan|x|10|scan_ssid1|10|scan_ssid2|2|2427|2442|2|"; + char buff[] = "N\tStartScan\tx\t10\tscan_ssid1\t10\tscan_ssid2\t2\t2427\t2442\t2\t"; mContext->oneProcess = buff; - mContext->nPos = strlen("N|StartScan|"); + mContext->nPos = strlen("N\tStartScan\t"); mContext->nSize = strlen(buff); EXPECT_TRUE(RpcStartScan(mServer, mContext) < 0); - char buff1[] = "N|StartScan|2|10|scan_ssid1|10|scan_ssid2"; + char buff1[] = "N\tStartScan\t2\t10\tscan_ssid1\t10\tscan_ssid2"; mContext->oneProcess = buff1; - mContext->nPos = strlen("N|StartScan|"); + mContext->nPos = strlen("N\tStartScan\t"); mContext->nSize = strlen(buff1); EXPECT_TRUE(RpcStartScan(mServer, mContext) < 0); - char buff2[] = "N|StartScan|2|10|scan_ssid1|10|scan_ssid2|x|"; + char buff2[] = "N\tStartScan\t2\t10\tscan_ssid1\t10\tscan_ssid2\tx\t"; mContext->oneProcess = buff2; - mContext->nPos = strlen("N|StartScan|"); + mContext->nPos = strlen("N\tStartScan\t"); mContext->nSize = strlen(buff2); EXPECT_TRUE(RpcStartScan(mServer, mContext) < 0); - char buff3[] = "N|StartScan|2|10|scan_ssid1|10|scan_ssid2|2|2427|x|x|"; + char buff3[] = "N\tStartScan\t2\t10\tscan_ssid1\t10\tscan_ssid2\t2\t2427\tx\tx\t"; mContext->oneProcess = buff3; - mContext->nPos = strlen("N|StartScan|"); + mContext->nPos = strlen("N\tStartScan\t"); mContext->nSize = strlen(buff3); EXPECT_TRUE(RpcStartScan(mServer, mContext) < 0); - char buff4[] = "N|StartScan|2|10|scan_ssid1|10|scan_ssid2|2|2427|2442|x|"; + char buff4[] = "N\tStartScan\t2\t10\tscan_ssid1\t10\tscan_ssid2\t2\t2427\t2442\tx\t"; mContext->oneProcess = buff4; - mContext->nPos = strlen("N|StartScan|"); + mContext->nPos = strlen("N\tStartScan\t"); mContext->nSize = strlen(buff4); EXPECT_TRUE(RpcStartScan(mServer, mContext) < 0); - char buff5[] = "N|StartScan|2|10|scan_ssid1|10|scan_ssid2|2|2427|2442|2|"; + char buff5[] = "N\tStartScan\t2\t10\tscan_ssid1\t10\tscan_ssid2\t2\t2427\t2442\t2\t"; mContext->oneProcess = buff5; - mContext->nPos = strlen("N|StartScan|"); + mContext->nPos = strlen("N\tStartScan\t"); mContext->nSize = strlen(buff5); EXPECT_TRUE(RpcStartScan(mServer, mContext) == 0); } @@ -705,14 +692,14 @@ HWTEST_F(WifiHalCRpcServerTest, RpcStartScanTest, TestSize.Level1) HWTEST_F(WifiHalCRpcServerTest, RpcGetScanInfosTest, TestSize.Level1) { EXPECT_TRUE(RpcGetScanInfos(nullptr, nullptr) < 0); - char buff[] = "N|GetScanInfos|x|"; + char buff[] = "N\tGetScanInfos\tx\t"; mContext->oneProcess = buff; - mContext->nPos = strlen("N|GetScanInfos|"); + mContext->nPos = strlen("N\tGetScanInfos\t"); mContext->nSize = strlen(buff); EXPECT_TRUE(RpcGetScanInfos(mServer, mContext) < 0); - char buff1[] = "N|GetScanInfos|12|"; + char buff1[] = "N\tGetScanInfos\t12\t"; mContext->oneProcess = buff1; - mContext->nPos = strlen("N|GetScanInfos|"); + mContext->nPos = strlen("N\tGetScanInfos\t"); mContext->nSize = strlen(buff1); EXPECT_TRUE(RpcGetScanInfos(mServer, mContext) == 0); } @@ -720,14 +707,14 @@ HWTEST_F(WifiHalCRpcServerTest, RpcGetScanInfosTest, TestSize.Level1) HWTEST_F(WifiHalCRpcServerTest, RpcGetNetworkListTest, TestSize.Level1) { EXPECT_TRUE(RpcGetNetworkList(nullptr, nullptr) < 0); - char buff[] = "N|GetNetworkList|x|"; + char buff[] = "N\tGetNetworkList\tx\t"; mContext->oneProcess = buff; - mContext->nPos = strlen("N|GetNetworkList|"); + mContext->nPos = strlen("N\tGetNetworkList\t"); mContext->nSize = strlen(buff); EXPECT_TRUE(RpcGetNetworkList(mServer, mContext) < 0); - char buff1[] = "N|GetNetworkList|12|"; + char buff1[] = "N\tGetNetworkList\t12\t"; mContext->oneProcess = buff1; - mContext->nPos = strlen("N|GetNetworkList|"); + mContext->nPos = strlen("N\tGetNetworkList\t"); mContext->nSize = strlen(buff1); EXPECT_TRUE(RpcGetNetworkList(mServer, mContext) == 0); } @@ -735,39 +722,42 @@ HWTEST_F(WifiHalCRpcServerTest, RpcGetNetworkListTest, TestSize.Level1) HWTEST_F(WifiHalCRpcServerTest, RpcStartPnoScanTest, TestSize.Level1) { EXPECT_TRUE(RpcStartPnoScan(nullptr, nullptr) < 0); - char buff[] = "N|StartPnoScan|1|x|1|2|3|asd|4|asdf|1|5|asdfg|2|5040|5080|"; + char buff[] = "N\tStartPnoScan\t1\tx\t1\t2\t3\tasd\t4\tasdf\t1\t5\tasdfg\t2\t5040\t5080\t"; mContext->oneProcess = buff; - mContext->nPos = strlen("N|StartPnoScan|"); + mContext->nPos = strlen("N\tStartPnoScan\t"); mContext->nSize = strlen(buff); EXPECT_TRUE(RpcStartPnoScan(mServer, mContext) < 0); - char buff1[] = "N|StartPnoScan|1|2|1|2|10|scan_ssid1|10|scan_ssid2"; + char buff1[] = "N\tStartPnoScan\t1\t2\t1\t2\t10\tscan_ssid1\t10\tscan_ssid2"; mContext->oneProcess = buff1; - mContext->nPos = strlen("N|StartPnoScan|"); + mContext->nPos = strlen("N\tStartPnoScan\t"); mContext->nSize = strlen(buff1); EXPECT_TRUE(RpcStartPnoScan(mServer, mContext) < 0); - char buff2[] = "N|StartPnoScan|1|2|1|2|10|scan_ssid1|10|scan_ssid2|x|"; + char buff2[] = "N\tStartPnoScan\t1\t2\t1\t2\t10\tscan_ssid1\t10\tscan_ssid2\tx\t"; mContext->oneProcess = buff2; - mContext->nPos = strlen("N|StartPnoScan|"); + mContext->nPos = strlen("N\tStartPnoScan\t"); mContext->nSize = strlen(buff2); EXPECT_TRUE(RpcStartPnoScan(mServer, mContext) < 0); - char buff3[] = "N|StartPnoScan|1|2|1|2|10|scan_ssid1|10|scan_ssid2|2|10|save_ssid1|10|save_ssid2"; + char buff3[] = "N\tStartPnoScan\t1\t2\t1\t2\t10\tscan_ssid1\t10\tscan_ssid2\t2\t10\tsave_ssid1\t10\tsave_ssid2"; mContext->oneProcess = buff3; - mContext->nPos = strlen("N|StartPnoScan|"); + mContext->nPos = strlen("N\tStartPnoScan\t"); mContext->nSize = strlen(buff3); EXPECT_TRUE(RpcStartPnoScan(mServer, mContext) < 0); - char buff4[] = "N|StartPnoScan|1|2|1|2|10|scan_ssid1|10|scan_ssid2|2|10|save_ssid1|10|save_ssid2|x|"; + char buff4[] = + "N\tStartPnoScan\t1\t2\t1\t2\t10\tscan_ssid1\t10\tscan_ssid2\t2\t10\tsave_ssid1\t10\tsave_ssid2\tx\t"; mContext->oneProcess = buff4; - mContext->nPos = strlen("N|StartPnoScan|"); + mContext->nPos = strlen("N\tStartPnoScan\t"); mContext->nSize = strlen(buff4); EXPECT_TRUE(RpcStartPnoScan(mServer, mContext) < 0); - char buff5[] = "N|StartPnoScan|1|2|1|2|10|scan_ssid1|10|scan_ssid2|2|10|save_ssid1|10|save_ssid2|2|5040|x|"; + char buff5[] = + "N\tStartPnoScan\t1\t2\t1\t2\t10\tscan_ssid1\t10\tscan_ssid2\t2\t10\tsave_ssid1\t10\tsave_ssid2\t2\t5040\tx\t"; mContext->oneProcess = buff5; - mContext->nPos = strlen("N|StartPnoScan|"); + mContext->nPos = strlen("N\tStartPnoScan\t"); mContext->nSize = strlen(buff5); EXPECT_TRUE(RpcStartPnoScan(mServer, mContext) < 0); - char buff6[] = "N|StartPnoScan|1|2|1|2|10|scan_ssid1|10|scan_ssid2|2|10|save_ssid1|10|save_ssid2|2|5040|5080|"; + char buff6[] = + "N\tStartPnoScan\t1\t2\t1\t2\t10\tscan_ssid1\t10\tscan_ssid2\t2\t10\tsave_ssid1\t10\tsave_ssid2\t2\t5040\t5080\t"; mContext->oneProcess = buff6; - mContext->nPos = strlen("N|StartPnoScan|"); + mContext->nPos = strlen("N\tStartPnoScan\t"); mContext->nSize = strlen(buff6); EXPECT_TRUE(RpcStartPnoScan(mServer, mContext) == 0); } @@ -781,14 +771,14 @@ HWTEST_F(WifiHalCRpcServerTest, RpcStopPnoScanTest, TestSize.Level1) HWTEST_F(WifiHalCRpcServerTest, RpcConnectTest, TestSize.Level1) { EXPECT_TRUE(RpcConnect(nullptr, nullptr) < 0); - char buff[] = "N|Connect|x|"; + char buff[] = "N\tConnect\tx\t"; mContext->oneProcess = buff; - mContext->nPos = strlen("N|Connect|"); + mContext->nPos = strlen("N\tConnect\t"); mContext->nSize = strlen(buff); EXPECT_TRUE(RpcConnect(mServer, mContext) < 0); - char buff1[] = "N|Connect|1|"; + char buff1[] = "N\tConnect\t1\t"; mContext->oneProcess = buff1; - mContext->nPos = strlen("N|Connect|"); + mContext->nPos = strlen("N\tConnect\t"); mContext->nSize = strlen(buff1); EXPECT_TRUE(RpcConnect(mServer, mContext) == 0); } @@ -796,14 +786,14 @@ HWTEST_F(WifiHalCRpcServerTest, RpcConnectTest, TestSize.Level1) HWTEST_F(WifiHalCRpcServerTest, RpcWpaAutoConnectTest, TestSize.Level1) { EXPECT_TRUE(RpcWpaAutoConnect(nullptr, nullptr) < 0); - char buff[] = "N|WpaAutoConnect|0ad|"; + char buff[] = "N\tWpaAutoConnect\t0ad\t"; mContext->oneProcess = buff; - mContext->nPos = strlen("N|WpaAutoConnect|"); + mContext->nPos = strlen("N\tWpaAutoConnect\t"); mContext->nSize = strlen(buff); EXPECT_TRUE(RpcWpaAutoConnect(mServer, mContext) < 0); - char buff1[] = "N|WpaAutoConnect|1|"; + char buff1[] = "N\tWpaAutoConnect\t1\t"; mContext->oneProcess = buff1; - mContext->nPos = strlen("N|WpaAutoConnect|"); + mContext->nPos = strlen("N\tWpaAutoConnect\t"); mContext->nSize = strlen(buff1); EXPECT_TRUE(RpcWpaAutoConnect(mServer, mContext) == 0); } @@ -835,14 +825,14 @@ HWTEST_F(WifiHalCRpcServerTest, RpcGetStaCapabilitiesTest, TestSize.Level1) HWTEST_F(WifiHalCRpcServerTest, RpcGetDeviceMacAddressTest, TestSize.Level1) { EXPECT_TRUE(RpcGetDeviceMacAddress(nullptr, nullptr) < 0); - char buff[] = "N|GetDeviceMacAddress|x|"; + char buff[] = "N\tGetDeviceMacAddress\tx\t"; mContext->oneProcess = buff; - mContext->nPos = strlen("N|GetDeviceMacAddress|"); + mContext->nPos = strlen("N\tGetDeviceMacAddress\t"); mContext->nSize = strlen(buff); EXPECT_TRUE(RpcGetDeviceMacAddress(mServer, mContext) < 0); - char buff1[] = "N|GetDeviceMacAddress|17|"; + char buff1[] = "N\tGetDeviceMacAddress\t17\t"; mContext->oneProcess = buff1; - mContext->nPos = strlen("N|GetDeviceMacAddress|"); + mContext->nPos = strlen("N\tGetDeviceMacAddress\t"); mContext->nSize = strlen(buff1); EXPECT_TRUE(RpcGetDeviceMacAddress(mServer, mContext) == 0); } @@ -850,14 +840,14 @@ HWTEST_F(WifiHalCRpcServerTest, RpcGetDeviceMacAddressTest, TestSize.Level1) HWTEST_F(WifiHalCRpcServerTest, RpcGetFrequenciesTest, TestSize.Level1) { EXPECT_TRUE(RpcGetFrequencies(nullptr, nullptr) < 0); - char buff[] = "N|GetFrequencies|1|"; + char buff[] = "N\tGetFrequencies\t1\t"; mContext->oneProcess = buff; - mContext->nPos = strlen("N|GetFrequencies|"); + mContext->nPos = strlen("N\tGetFrequencies\t"); mContext->nSize = strlen(buff); EXPECT_TRUE(RpcGetFrequencies(mServer, mContext) < 0); - char buff1[] = "N|GetFrequencies|1|128|"; + char buff1[] = "N\tGetFrequencies\t1\t128\t"; mContext->oneProcess = buff1; - mContext->nPos = strlen("N|GetFrequencies|"); + mContext->nPos = strlen("N\tGetFrequencies\t"); mContext->nSize = strlen(buff1); EXPECT_TRUE(RpcGetFrequencies(mServer, mContext) == 0); } @@ -865,19 +855,19 @@ HWTEST_F(WifiHalCRpcServerTest, RpcGetFrequenciesTest, TestSize.Level1) HWTEST_F(WifiHalCRpcServerTest, RpcSetAssocMacAddrTest, TestSize.Level1) { EXPECT_TRUE(RpcSetAssocMacAddr(nullptr, nullptr) < 0); - char buff[] = "N|SetAssocMacAddr|x|7d9c039dfeba46|"; + char buff[] = "N\tSetAssocMacAddr\tx\t7d9c039dfeba46\t"; mContext->oneProcess = buff; - mContext->nPos = strlen("N|SetAssocMacAddr|"); + mContext->nPos = strlen("N\tSetAssocMacAddr\t"); mContext->nSize = strlen(buff); EXPECT_TRUE(RpcSetAssocMacAddr(mServer, mContext) < 0); - char buff1[] = "N|SetAssocMacAddr|6|7d9c039dfeba46|"; + char buff1[] = "N\tSetAssocMacAddr\t6\t7d9c039dfeba46\t"; mContext->oneProcess = buff1; - mContext->nPos = strlen("N|SetAssocMacAddr|"); + mContext->nPos = strlen("N\tSetAssocMacAddr\t"); mContext->nSize = strlen(buff1); EXPECT_TRUE(RpcSetAssocMacAddr(mServer, mContext) < 0); - char buff2[] = "N|SetAssocMacAddr|7|7d9c039dfeba46|"; + char buff2[] = "N\tSetAssocMacAddr\t7\t7d9c039dfeba46\t"; mContext->oneProcess = buff2; - mContext->nPos = strlen("N|SetAssocMacAddr|"); + mContext->nPos = strlen("N\tSetAssocMacAddr\t"); mContext->nSize = strlen(buff2); EXPECT_TRUE(RpcSetAssocMacAddr(mServer, mContext) == 0); } @@ -885,19 +875,19 @@ HWTEST_F(WifiHalCRpcServerTest, RpcSetAssocMacAddrTest, TestSize.Level1) HWTEST_F(WifiHalCRpcServerTest, RpcSetScanningMacAddressTest, TestSize.Level1) { EXPECT_TRUE(RpcSetScanningMacAddress(nullptr, nullptr) < 0); - char buff[] = "N|SetScanningMacAddress|x|7d9c039dfeba46|"; + char buff[] = "N\tSetScanningMacAddress\tx\t7d9c039dfeba46\t"; mContext->oneProcess = buff; - mContext->nPos = strlen("N|SetScanningMacAddress|"); + mContext->nPos = strlen("N\tSetScanningMacAddress\t"); mContext->nSize = strlen(buff); EXPECT_TRUE(RpcSetScanningMacAddress(mServer, mContext) < 0); - char buff1[] = "N|SetScanningMacAddress|6|7d9c039dfeba46|"; + char buff1[] = "N\tSetScanningMacAddress\t6\t7d9c039dfeba46\t"; mContext->oneProcess = buff1; - mContext->nPos = strlen("N|SetScanningMacAddress|"); + mContext->nPos = strlen("N\tSetScanningMacAddress\t"); mContext->nSize = strlen(buff1); EXPECT_TRUE(RpcSetScanningMacAddress(mServer, mContext) < 0); - char buff2[] = "N|SetScanningMacAddress|7|7d9c039dfeba46|"; + char buff2[] = "N\tSetScanningMacAddress\t7\t7d9c039dfeba46\t"; mContext->oneProcess = buff2; - mContext->nPos = strlen("N|SetScanningMacAddress|"); + mContext->nPos = strlen("N\tSetScanningMacAddress\t"); mContext->nSize = strlen(buff2); EXPECT_TRUE(RpcSetScanningMacAddress(mServer, mContext) == 0); } @@ -905,19 +895,19 @@ HWTEST_F(WifiHalCRpcServerTest, RpcSetScanningMacAddressTest, TestSize.Level1) HWTEST_F(WifiHalCRpcServerTest, RpcDeauthLastRoamingBssidTest, TestSize.Level1) { EXPECT_TRUE(RpcDeauthLastRoamingBssid(nullptr, nullptr) < 0); - char buff[] = "N|DeauthLastRoamingBssid|x|7d9c039dfeba46|"; + char buff[] = "N\tDeauthLastRoamingBssid\tx\t7d9c039dfeba46\t"; mContext->oneProcess = buff; - mContext->nPos = strlen("N|DeauthLastRoamingBssid|"); + mContext->nPos = strlen("N\tDeauthLastRoamingBssid\t"); mContext->nSize = strlen(buff); EXPECT_TRUE(RpcDeauthLastRoamingBssid(mServer, mContext) < 0); - char buff1[] = "N|DeauthLastRoamingBssid|6|7d9c039dfeba46|"; + char buff1[] = "N\tDeauthLastRoamingBssid\t6\t7d9c039dfeba46\t"; mContext->oneProcess = buff1; - mContext->nPos = strlen("N|DeauthLastRoamingBssid|"); + mContext->nPos = strlen("N\tDeauthLastRoamingBssid\t"); mContext->nSize = strlen(buff1); EXPECT_TRUE(RpcDeauthLastRoamingBssid(mServer, mContext) < 0); - char buff2[] = "N|DeauthLastRoamingBssid|7|7d9c039dfeba46|"; + char buff2[] = "N\tDeauthLastRoamingBssid\t7\t7d9c039dfeba46\t"; mContext->oneProcess = buff2; - mContext->nPos = strlen("N|DeauthLastRoamingBssid|"); + mContext->nPos = strlen("N\tDeauthLastRoamingBssid\t"); mContext->nSize = strlen(buff2); EXPECT_TRUE(RpcDeauthLastRoamingBssid(mServer, mContext) == 0); } @@ -931,34 +921,34 @@ HWTEST_F(WifiHalCRpcServerTest, RpcGetSupportFeatureTest, TestSize.Level1) HWTEST_F(WifiHalCRpcServerTest, RpcRunCmdTest, TestSize.Level1) { EXPECT_TRUE(RpcRunCmd(nullptr, nullptr) < 0); - char buff[] = "N|RunCmd|wlan0"; + char buff[] = "N\tRunCmd\twlan0"; mContext->oneProcess = buff; - mContext->nPos = strlen("N|RunCmd|"); + mContext->nPos = strlen("N\tRunCmd\t"); mContext->nSize = strlen(buff); EXPECT_TRUE(RpcRunCmd(mServer, mContext) < 0); - char buff1[] = "N|RunCmd|wlan0|x|"; + char buff1[] = "N\tRunCmd\twlan0\tx\t"; mContext->oneProcess = buff1; - mContext->nPos = strlen("N|RunCmd|"); + mContext->nPos = strlen("N\tRunCmd\t"); mContext->nSize = strlen(buff1); EXPECT_TRUE(RpcRunCmd(mServer, mContext) < 0); - char buff2[] = "N|RunCmd|wlan0|1|x|"; + char buff2[] = "N\tRunCmd\twlan0\t1\tx\t"; mContext->oneProcess = buff2; - mContext->nPos = strlen("N|RunCmd|"); + mContext->nPos = strlen("N\tRunCmd\t"); mContext->nSize = strlen(buff2); EXPECT_TRUE(RpcRunCmd(mServer, mContext) < 0); - char buff3[] = "N|RunCmd|wlan0|1|6|7d9c039dfeba46|"; + char buff3[] = "N\tRunCmd\twlan0\t1\t6\t7d9c039dfeba46\t"; mContext->oneProcess = buff3; - mContext->nPos = strlen("N|RunCmd|"); + mContext->nPos = strlen("N\tRunCmd\t"); mContext->nSize = strlen(buff3); EXPECT_TRUE(RpcRunCmd(mServer, mContext) < 0); - char buff4[] = "N|RunCmd|wlan0|1|7|7d9c039dfeba46|"; + char buff4[] = "N\tRunCmd\twlan0\t1\t7\t7d9c039dfeba46\t"; mContext->oneProcess = buff4; - mContext->nPos = strlen("N|RunCmd|"); + mContext->nPos = strlen("N\tRunCmd\t"); mContext->nSize = strlen(buff4); EXPECT_TRUE(RpcRunCmd(mServer, mContext) == 0); - char buff5[] = "N|RunCmd|0123456789012345678901|1|7|7d9c039dfeba46|"; + char buff5[] = "N\tRunCmd\t0123456789012345678901\t1\t7\t7d9c039dfeba46\t"; mContext->oneProcess = buff5; - mContext->nPos = strlen("N|RunCmd|"); + mContext->nPos = strlen("N\tRunCmd\t"); mContext->nSize = strlen(buff5); EXPECT_TRUE(RpcRunCmd(mServer, mContext) == 0); } @@ -966,14 +956,14 @@ HWTEST_F(WifiHalCRpcServerTest, RpcRunCmdTest, TestSize.Level1) HWTEST_F(WifiHalCRpcServerTest, RpcSetWifiTxPowerTest, TestSize.Level1) { EXPECT_TRUE(RpcSetWifiTxPower(nullptr, nullptr) < 0); - char buff[] = "N|SetWifiTxPower|12"; + char buff[] = "N\tSetWifiTxPower\t12"; mContext->oneProcess = buff; - mContext->nPos = strlen("N|SetWifiTxPower|"); + mContext->nPos = strlen("N\tSetWifiTxPower\t"); mContext->nSize = strlen(buff); EXPECT_TRUE(RpcSetWifiTxPower(mServer, mContext) < 0); - char buff1[] = "N|SetWifiTxPower|12|"; + char buff1[] = "N\tSetWifiTxPower\t12\t"; mContext->oneProcess = buff1; - mContext->nPos = strlen("N|SetWifiTxPower|"); + mContext->nPos = strlen("N\tSetWifiTxPower\t"); mContext->nSize = strlen(buff1); EXPECT_TRUE(RpcSetWifiTxPower(mServer, mContext) == 0); } @@ -981,14 +971,14 @@ HWTEST_F(WifiHalCRpcServerTest, RpcSetWifiTxPowerTest, TestSize.Level1) HWTEST_F(WifiHalCRpcServerTest, RpcRemoveNetworkTest, TestSize.Level1) { EXPECT_TRUE(RpcRemoveNetwork(nullptr, nullptr) < 0); - char buff[] = "N|RemoveNetwork|12"; + char buff[] = "N\tRemoveNetwork\t12"; mContext->oneProcess = buff; - mContext->nPos = strlen("N|RemoveNetwork|"); + mContext->nPos = strlen("N\tRemoveNetwork\t"); mContext->nSize = strlen(buff); EXPECT_TRUE(RpcRemoveNetwork(mServer, mContext) < 0); - char buff1[] = "N|RemoveNetwork|12|"; + char buff1[] = "N\tRemoveNetwork\t12\t"; mContext->oneProcess = buff1; - mContext->nPos = strlen("N|RemoveNetwork|"); + mContext->nPos = strlen("N\tRemoveNetwork\t"); mContext->nSize = strlen(buff1); EXPECT_TRUE(RpcRemoveNetwork(mServer, mContext) == 0); } @@ -1002,14 +992,14 @@ HWTEST_F(WifiHalCRpcServerTest, RpcAddNetworkTest, TestSize.Level1) HWTEST_F(WifiHalCRpcServerTest, RpcEnableNetworkTest, TestSize.Level1) { EXPECT_TRUE(RpcEnableNetwork(nullptr, nullptr) < 0); - char buff[] = "N|EnableNetwork|12"; + char buff[] = "N\tEnableNetwork\t12"; mContext->oneProcess = buff; - mContext->nPos = strlen("N|EnableNetwork|"); + mContext->nPos = strlen("N\tEnableNetwork\t"); mContext->nSize = strlen(buff); EXPECT_TRUE(RpcEnableNetwork(mServer, mContext) < 0); - char buff1[] = "N|EnableNetwork|12|"; + char buff1[] = "N\tEnableNetwork\t12\t"; mContext->oneProcess = buff1; - mContext->nPos = strlen("N|EnableNetwork|"); + mContext->nPos = strlen("N\tEnableNetwork\t"); mContext->nSize = strlen(buff1); EXPECT_TRUE(RpcEnableNetwork(mServer, mContext) == 0); } @@ -1017,14 +1007,14 @@ HWTEST_F(WifiHalCRpcServerTest, RpcEnableNetworkTest, TestSize.Level1) HWTEST_F(WifiHalCRpcServerTest, RpcDisableNetworkTest, TestSize.Level1) { EXPECT_TRUE(RpcDisableNetwork(nullptr, nullptr) < 0); - char buff[] = "N|DisableNetwork|12"; + char buff[] = "N\tDisableNetwork\t12"; mContext->oneProcess = buff; - mContext->nPos = strlen("N|DisableNetwork|"); + mContext->nPos = strlen("N\tDisableNetwork\t"); mContext->nSize = strlen(buff); EXPECT_TRUE(RpcDisableNetwork(mServer, mContext) < 0); - char buff1[] = "N|DisableNetwork|12|"; + char buff1[] = "N\tDisableNetwork\t12\t"; mContext->oneProcess = buff1; - mContext->nPos = strlen("N|DisableNetwork|"); + mContext->nPos = strlen("N\tDisableNetwork\t"); mContext->nSize = strlen(buff1); EXPECT_TRUE(RpcDisableNetwork(mServer, mContext) == 0); } @@ -1032,19 +1022,19 @@ HWTEST_F(WifiHalCRpcServerTest, RpcDisableNetworkTest, TestSize.Level1) HWTEST_F(WifiHalCRpcServerTest, RpcSetNetworkTest, TestSize.Level1) { EXPECT_TRUE(RpcSetNetwork(nullptr, nullptr) < 0); - char buff[] = "N|SetNetwork|0|1"; + char buff[] = "N\tSetNetwork\t0\t1"; mContext->oneProcess = buff; - mContext->nPos = strlen("N|SetNetwork|"); + mContext->nPos = strlen("N\tSetNetwork\t"); mContext->nSize = strlen(buff); EXPECT_TRUE(RpcSetNetwork(mServer, mContext) < 0); - char buff1[] = "N|SetNetwork|0|1|12|afsdgljsd"; + char buff1[] = "N\tSetNetwork\t0\t1\t12\tafsdgljsd"; mContext->oneProcess = buff1; - mContext->nPos = strlen("N|SetNetwork|"); + mContext->nPos = strlen("N\tSetNetwork\t"); mContext->nSize = strlen(buff1); EXPECT_TRUE(RpcSetNetwork(mServer, mContext) == 0); - char buff2[] = "N|SetNetwork|0|1|12|afsdgljsd|"; + char buff2[] = "N\tSetNetwork\t0\t1\t12\tafsdgljsd\t"; mContext->oneProcess = buff2; - mContext->nPos = strlen("N|SetNetwork|"); + mContext->nPos = strlen("N\tSetNetwork\t"); mContext->nSize = strlen(buff2); EXPECT_TRUE(RpcSetNetwork(mServer, mContext) == 0); } @@ -1052,14 +1042,14 @@ HWTEST_F(WifiHalCRpcServerTest, RpcSetNetworkTest, TestSize.Level1) HWTEST_F(WifiHalCRpcServerTest, RpcWpaGetNetworkTest, TestSize.Level1) { EXPECT_TRUE(RpcWpaGetNetwork(nullptr, nullptr) < 0); - char buff[] = "N|WpaGetNetwork|2|ssid"; + char buff[] = "N\tWpaGetNetwork\t2\tssid"; mContext->oneProcess = buff; - mContext->nPos = strlen("N|WpaGetNetwork|"); + mContext->nPos = strlen("N\tWpaGetNetwork\t"); mContext->nSize = strlen(buff); EXPECT_TRUE(RpcWpaGetNetwork(mServer, mContext) < 0); - char buff1[] = "N|WpaGetNetwork|2|ssid|"; + char buff1[] = "N\tWpaGetNetwork\t2\tssid\t"; mContext->oneProcess = buff1; - mContext->nPos = strlen("N|WpaGetNetwork|"); + mContext->nPos = strlen("N\tWpaGetNetwork\t"); mContext->nSize = strlen(buff1); EXPECT_TRUE(RpcWpaGetNetwork(mServer, mContext) == 0); } @@ -1073,14 +1063,14 @@ HWTEST_F(WifiHalCRpcServerTest, RpcSaveNetworkConfigTest, TestSize.Level1) HWTEST_F(WifiHalCRpcServerTest, RpcStartWpsPbcModeTest, TestSize.Level1) { EXPECT_TRUE(RpcStartWpsPbcMode(nullptr, nullptr) < 0); - char buff[] = "N|StartWpsPbcMode|1|2|adsgfkdsj"; + char buff[] = "N\tStartWpsPbcMode\t1\t2\tadsgfkdsj"; mContext->oneProcess = buff; - mContext->nPos = strlen("N|StartWpsPbcMode|"); + mContext->nPos = strlen("N\tStartWpsPbcMode\t"); mContext->nSize = strlen(buff); EXPECT_TRUE(RpcStartWpsPbcMode(mServer, mContext) < 0); - char buff1[] = "N|StartWpsPbcMode|1|2|adsgfkdsj|"; + char buff1[] = "N\tStartWpsPbcMode\t1\t2\tadsgfkdsj\t"; mContext->oneProcess = buff1; - mContext->nPos = strlen("N|StartWpsPbcMode|"); + mContext->nPos = strlen("N\tStartWpsPbcMode\t"); mContext->nSize = strlen(buff1); EXPECT_TRUE(RpcStartWpsPbcMode(mServer, mContext) == 0); } @@ -1088,14 +1078,14 @@ HWTEST_F(WifiHalCRpcServerTest, RpcStartWpsPbcModeTest, TestSize.Level1) HWTEST_F(WifiHalCRpcServerTest, RpcStartWpsPinModeTest, TestSize.Level1) { EXPECT_TRUE(RpcStartWpsPinMode(nullptr, nullptr) < 0); - char buff[] = "N|StartWpsPinMode|1|2|adsgfkdsj"; + char buff[] = "N\tStartWpsPinMode\t1\t2\tadsgfkdsj"; mContext->oneProcess = buff; - mContext->nPos = strlen("N|StartWpsPinMode|"); + mContext->nPos = strlen("N\tStartWpsPinMode\t"); mContext->nSize = strlen(buff); EXPECT_TRUE(RpcStartWpsPinMode(mServer, mContext) < 0); - char buff1[] = "N|StartWpsPinMode|1|2|adsgfkdsj|"; + char buff1[] = "N\tStartWpsPinMode\t1\t2\tadsgfkdsj\t"; mContext->oneProcess = buff1; - mContext->nPos = strlen("N|StartWpsPinMode|"); + mContext->nPos = strlen("N\tStartWpsPinMode\t"); mContext->nSize = strlen(buff1); EXPECT_TRUE(RpcStartWpsPinMode(mServer, mContext) == 0); } @@ -1121,29 +1111,29 @@ HWTEST_F(WifiHalCRpcServerTest, RpcGetRoamingCapabilitiesTest, TestSize.Level1) HWTEST_F(WifiHalCRpcServerTest, RpcSetRoamConfigTest, TestSize.Level1) { EXPECT_TRUE(RpcSetRoamConfig(nullptr, nullptr) < 0); - char buff[] = "N|SetRoamConfig|x|fdsagdsa|safdgfds|1|vcxzcbvx|"; + char buff[] = "N\tSetRoamConfig\tx\tfdsagdsa\tsafdgfds\t1\tvcxzcbvx\t"; mContext->oneProcess = buff; - mContext->nPos = strlen("N|SetRoamConfig|"); + mContext->nPos = strlen("N\tSetRoamConfig\t"); mContext->nSize = strlen(buff); EXPECT_TRUE(RpcSetRoamConfig(mServer, mContext) < 0); - char buff1[] = "N|SetRoamConfig|2|fdsagdsa|safdgfds"; + char buff1[] = "N\tSetRoamConfig\t2\tfdsagdsa\tsafdgfds"; mContext->oneProcess = buff1; - mContext->nPos = strlen("N|SetRoamConfig|"); + mContext->nPos = strlen("N\tSetRoamConfig\t"); mContext->nSize = strlen(buff1); EXPECT_TRUE(RpcSetRoamConfig(mServer, mContext) < 0); - char buff2[] = "N|SetRoamConfig|2|fdsagdsa|safdgfds|x|vcxzcbvx|"; + char buff2[] = "N\tSetRoamConfig\t2\tfdsagdsa\tsafdgfds\tx\tvcxzcbvx\t"; mContext->oneProcess = buff2; - mContext->nPos = strlen("N|SetRoamConfig|"); + mContext->nPos = strlen("N\tSetRoamConfig\t"); mContext->nSize = strlen(buff2); EXPECT_TRUE(RpcSetRoamConfig(mServer, mContext) < 0); - char buff3[] = "N|SetRoamConfig|2|fdsagdsa|safdgfds|1|vcxzcbvx"; + char buff3[] = "N\tSetRoamConfig\t2\tfdsagdsa\tsafdgfds\t1\tvcxzcbvx"; mContext->oneProcess = buff3; - mContext->nPos = strlen("N|SetRoamConfig|"); + mContext->nPos = strlen("N\tSetRoamConfig\t"); mContext->nSize = strlen(buff3); EXPECT_TRUE(RpcSetRoamConfig(mServer, mContext) < 0); - char buff4[] = "N|SetRoamConfig|2|fdsagdsa|safdgfds|1|vcxzcbvx|"; + char buff4[] = "N\tSetRoamConfig\t2\tfdsagdsa\tsafdgfds\t1\tvcxzcbvx\t"; mContext->oneProcess = buff4; - mContext->nPos = strlen("N|SetRoamConfig|"); + mContext->nPos = strlen("N\tSetRoamConfig\t"); mContext->nSize = strlen(buff4); EXPECT_TRUE(RpcSetRoamConfig(mServer, mContext) == 0); } @@ -1151,14 +1141,14 @@ HWTEST_F(WifiHalCRpcServerTest, RpcSetRoamConfigTest, TestSize.Level1) HWTEST_F(WifiHalCRpcServerTest, RpcGetConnectSignalInfoTest, TestSize.Level1) { EXPECT_TRUE(RpcGetConnectSignalInfo(nullptr, nullptr) < 0); - char buff[] = "N|GetConnectSignalInfo|ssid"; + char buff[] = "N\tGetConnectSignalInfo\tssid"; mContext->oneProcess = buff; - mContext->nPos = strlen("N|GetConnectSignalInfo|"); + mContext->nPos = strlen("N\tGetConnectSignalInfo\t"); mContext->nSize = strlen(buff); EXPECT_TRUE(RpcGetConnectSignalInfo(mServer, mContext) < 0); - char buff1[] = "N|GetConnectSignalInfo|00:00:00:00:00:00|"; + char buff1[] = "N\tGetConnectSignalInfo\t00:00:00:00:00:00\t"; mContext->oneProcess = buff1; - mContext->nPos = strlen("N|GetConnectSignalInfo|"); + mContext->nPos = strlen("N\tGetConnectSignalInfo\t"); mContext->nSize = strlen(buff1); EXPECT_TRUE(RpcGetConnectSignalInfo(mServer, mContext) == 0); } @@ -1166,26 +1156,34 @@ HWTEST_F(WifiHalCRpcServerTest, RpcGetConnectSignalInfoTest, TestSize.Level1) HWTEST_F(WifiHalCRpcServerTest, RpcStartSoftApTest, TestSize.Level1) { EXPECT_TRUE(RpcStartSoftAp(nullptr, nullptr) < 0); + char buff[] = "N\tStartSoftAp\t0\t"; + mContext->oneProcess = buff; + mContext->nPos = strlen("N\tStartSoftAp\t"); + mContext->nSize = strlen(buff); EXPECT_TRUE(RpcStartSoftAp(mServer, mContext) == 0); } HWTEST_F(WifiHalCRpcServerTest, RpcStopSoftApTest, TestSize.Level1) { EXPECT_TRUE(RpcStopSoftAp(nullptr, nullptr) < 0); + char buff[] = "N\tStopSoftAp\t0\t"; + mContext->oneProcess = buff; + mContext->nPos = strlen("N\tStopSoftAp\t"); + mContext->nSize = strlen(buff); EXPECT_TRUE(RpcStopSoftAp(mServer, mContext) == 0); } HWTEST_F(WifiHalCRpcServerTest, RpcSetHostapdConfigTest, TestSize.Level1) { EXPECT_TRUE(RpcSetHostapdConfig(nullptr, nullptr) < 0); - char buff[] = "N|SetHostapdConfig|tests|5|adc123456|9|1|0|6|20|"; + char buff[] = "N\tSetHostapdConfig\ttests\t5\tadc123456\t9\t1\t0\t6\t20\t0\t"; mContext->oneProcess = buff; - mContext->nPos = strlen("N|SetHostapdConfig|"); + mContext->nPos = strlen("N\tSetHostapdConfig\t"); mContext->nSize = strlen(buff); EXPECT_TRUE(RpcSetHostapdConfig(mServer, mContext) == 0); - char buff1[] = "N|SetHostapdConfig|tests|5|adc123456|9|1|0|6|20"; + char buff1[] = "N\tSetHostapdConfig\ttests\t5\tadc123456\t9\t1\t0\t6\t20"; mContext->oneProcess = buff1; - mContext->nPos = strlen("N|SetHostapdConfig|"); + mContext->nPos = strlen("N\tSetHostapdConfig\t"); mContext->nSize = strlen(buff1); EXPECT_TRUE(RpcSetHostapdConfig(mServer, mContext) < 0); } @@ -1193,14 +1191,14 @@ HWTEST_F(WifiHalCRpcServerTest, RpcSetHostapdConfigTest, TestSize.Level1) HWTEST_F(WifiHalCRpcServerTest, RpcGetStaInfosTest, TestSize.Level1) { EXPECT_TRUE(RpcGetStaInfos(nullptr, nullptr) < 0); - char buff[] = "N|GetStaInfos|128"; + char buff[] = "N\tGetStaInfos\t128"; mContext->oneProcess = buff; - mContext->nPos = strlen("N|GetStaInfos|"); + mContext->nPos = strlen("N\tGetStaInfos\t"); mContext->nSize = strlen(buff); EXPECT_TRUE(RpcGetStaInfos(mServer, mContext) < 0); - char buff1[] = "N|GetStaInfos|128|"; + char buff1[] = "N\tGetStaInfos\t128\t0\t"; mContext->oneProcess = buff1; - mContext->nPos = strlen("N|GetStaInfos|"); + mContext->nPos = strlen("N\tGetStaInfos\t"); mContext->nSize = strlen(buff1); EXPECT_TRUE(RpcGetStaInfos(mServer, mContext) == 0); } @@ -1208,14 +1206,14 @@ HWTEST_F(WifiHalCRpcServerTest, RpcGetStaInfosTest, TestSize.Level1) HWTEST_F(WifiHalCRpcServerTest, RpcSetCountryCodeTest, TestSize.Level1) { EXPECT_TRUE(RpcSetCountryCode(nullptr, nullptr) < 0); - char buff[] = "N|SetCountryCode|CN"; + char buff[] = "N\tSetCountryCode\tCN"; mContext->oneProcess = buff; - mContext->nPos = strlen("N|SetCountryCode|"); + mContext->nPos = strlen("N\tSetCountryCode\t"); mContext->nSize = strlen(buff); EXPECT_TRUE(RpcSetCountryCode(mServer, mContext) < 0); - char buff1[] = "N|SetCountryCode|CN|"; + char buff1[] = "N\tSetCountryCode\tCN\t0\t"; mContext->oneProcess = buff1; - mContext->nPos = strlen("N|SetCountryCode|"); + mContext->nPos = strlen("N\tSetCountryCode\t"); mContext->nSize = strlen(buff1); EXPECT_TRUE(RpcSetCountryCode(mServer, mContext) == 0); } @@ -1223,19 +1221,19 @@ HWTEST_F(WifiHalCRpcServerTest, RpcSetCountryCodeTest, TestSize.Level1) HWTEST_F(WifiHalCRpcServerTest, RpcSetMacFilterTest, TestSize.Level1) { EXPECT_TRUE(RpcSetMacFilter(nullptr, nullptr) < 0); - char buff[] = "N|SetMacFilter|x|345697dbf921d3|"; + char buff[] = "N\tSetMacFilter\tx\t345697dbf921d3\t"; mContext->oneProcess = buff; - mContext->nPos = strlen("N|SetMacFilter|"); + mContext->nPos = strlen("N\tSetMacFilter\t"); mContext->nSize = strlen(buff); EXPECT_TRUE(RpcSetMacFilter(mServer, mContext) < 0); - char buff1[] = "N|SetMacFilter|6|345697dbf921d3|"; + char buff1[] = "N\tSetMacFilter\t6\t345697dbf921d3\t"; mContext->oneProcess = buff1; - mContext->nPos = strlen("N|SetMacFilter|"); + mContext->nPos = strlen("N\tSetMacFilter\t"); mContext->nSize = strlen(buff1); EXPECT_TRUE(RpcSetMacFilter(mServer, mContext) < 0); - char buff2[] = "N|SetMacFilter|7|345697dbf921d3|"; + char buff2[] = "N\tSetMacFilter\t7\t345697dbf921d3\t0\t"; mContext->oneProcess = buff2; - mContext->nPos = strlen("N|SetMacFilter|"); + mContext->nPos = strlen("N\tSetMacFilter\t"); mContext->nSize = strlen(buff2); EXPECT_TRUE(RpcSetMacFilter(mServer, mContext) == 0); } @@ -1243,19 +1241,19 @@ HWTEST_F(WifiHalCRpcServerTest, RpcSetMacFilterTest, TestSize.Level1) HWTEST_F(WifiHalCRpcServerTest, RpcDelMacFilterTest, TestSize.Level1) { EXPECT_TRUE(RpcDelMacFilter(nullptr, nullptr) < 0); - char buff[] = "N|DelMacFilter|x|345697dbf921d3|"; + char buff[] = "N\tDelMacFilter\tx\t345697dbf921d3\t"; mContext->oneProcess = buff; - mContext->nPos = strlen("N|DelMacFilter|"); + mContext->nPos = strlen("N\tDelMacFilter\t"); mContext->nSize = strlen(buff); EXPECT_TRUE(RpcDelMacFilter(mServer, mContext) < 0); - char buff1[] = "N|DelMacFilter|6|345697dbf921d3|"; + char buff1[] = "N\tDelMacFilter\t6\t345697dbf921d3\t"; mContext->oneProcess = buff1; - mContext->nPos = strlen("N|DelMacFilter|"); + mContext->nPos = strlen("N\tDelMacFilter\t"); mContext->nSize = strlen(buff1); EXPECT_TRUE(RpcDelMacFilter(mServer, mContext) < 0); - char buff2[] = "N|DelMacFilter|7|345697dbf921d3|"; + char buff2[] = "N\tDelMacFilter\t7\t345697dbf921d3\t0\t"; mContext->oneProcess = buff2; - mContext->nPos = strlen("N|DelMacFilter|"); + mContext->nPos = strlen("N\tDelMacFilter\t"); mContext->nSize = strlen(buff2); EXPECT_TRUE(RpcDelMacFilter(mServer, mContext) == 0); } @@ -1263,19 +1261,19 @@ HWTEST_F(WifiHalCRpcServerTest, RpcDelMacFilterTest, TestSize.Level1) HWTEST_F(WifiHalCRpcServerTest, RpcDisassociateStaTest, TestSize.Level1) { EXPECT_TRUE(RpcDisassociateSta(nullptr, nullptr) < 0); - char buff[] = "N|DisassociateSta|x|345697dbf921d3|"; + char buff[] = "N\tDisassociateSta\tx\t345697dbf921d3\t"; mContext->oneProcess = buff; - mContext->nPos = strlen("N|DisassociateSta|"); + mContext->nPos = strlen("N\tDisassociateSta\t"); mContext->nSize = strlen(buff); EXPECT_TRUE(RpcDisassociateSta(mServer, mContext) < 0); - char buff1[] = "N|DisassociateSta|6|345697dbf921d3|"; + char buff1[] = "N\tDisassociateSta\t6\t345697dbf921d3\t"; mContext->oneProcess = buff1; - mContext->nPos = strlen("N|DisassociateSta|"); + mContext->nPos = strlen("N\tDisassociateSta\t"); mContext->nSize = strlen(buff1); EXPECT_TRUE(RpcDisassociateSta(mServer, mContext) < 0); - char buff2[] = "N|DisassociateSta|7|345697dbf921d3|"; + char buff2[] = "N\tDisassociateSta\t7\t345697dbf921d3\t0\t"; mContext->oneProcess = buff2; - mContext->nPos = strlen("N|DisassociateSta|"); + mContext->nPos = strlen("N\tDisassociateSta\t"); mContext->nSize = strlen(buff2); EXPECT_TRUE(RpcDisassociateSta(mServer, mContext) == 0); } @@ -1283,14 +1281,14 @@ HWTEST_F(WifiHalCRpcServerTest, RpcDisassociateStaTest, TestSize.Level1) HWTEST_F(WifiHalCRpcServerTest, RpcGetValidFrequenciesForBandTest, TestSize.Level1) { EXPECT_TRUE(RpcGetValidFrequenciesForBand(nullptr, nullptr) < 0); - char buff[] = "N|GetValidFrequenciesForBand|1|128"; + char buff[] = "N\tGetValidFrequenciesForBand\t1\t128"; mContext->oneProcess = buff; - mContext->nPos = strlen("N|GetValidFrequenciesForBand|"); + mContext->nPos = strlen("N\tGetValidFrequenciesForBand\t"); mContext->nSize = strlen(buff); EXPECT_TRUE(RpcGetValidFrequenciesForBand(mServer, mContext) < 0); - char buff1[] = "N|GetValidFrequenciesForBand|1|128|"; + char buff1[] = "N\tGetValidFrequenciesForBand\t1\t128\t0\t"; mContext->oneProcess = buff1; - mContext->nPos = strlen("N|GetValidFrequenciesForBand|"); + mContext->nPos = strlen("N\tGetValidFrequenciesForBand\t"); mContext->nSize = strlen(buff1); EXPECT_TRUE(RpcGetValidFrequenciesForBand(mServer, mContext) == 0); } diff --git a/tests/wifi_standard/wifi_hal/unittest/wifi_hal_crpc_server_test.h b/wifi/test/wifi_standard/wifi_hal/unittest/wifi_hal_crpc_server_test.h similarity index 100% rename from tests/wifi_standard/wifi_hal/unittest/wifi_hal_crpc_server_test.h rename to wifi/test/wifi_standard/wifi_hal/unittest/wifi_hal_crpc_server_test.h diff --git a/tests/wifi_standard/wifi_hal/unittest/wifi_hal_hostapd_test.cpp b/wifi/test/wifi_standard/wifi_hal/unittest/wifi_hal_hostapd_test.cpp similarity index 70% rename from tests/wifi_standard/wifi_hal/unittest/wifi_hal_hostapd_test.cpp rename to wifi/test/wifi_standard/wifi_hal/unittest/wifi_hal_hostapd_test.cpp index a0d7a791cd8239c65b04dd06b3461a3118203667..9462b43738281c792a0570eeda96247229fa955f 100644 --- a/tests/wifi_standard/wifi_hal/unittest/wifi_hal_hostapd_test.cpp +++ b/wifi/test/wifi_standard/wifi_hal/unittest/wifi_hal_hostapd_test.cpp @@ -40,13 +40,13 @@ void WifiHalHostapdTest::SetUpTestCase() InitCallbackMsg(); SetRpcServerInited(mServer); MockInitApSupportedCmd(); - mInterface = GetWifiHostapdDev(); + mInterface = GetWifiHostapdDev(0); } void WifiHalHostapdTest::TearDownTestCase() { sleep(1); - ReleaseHostapdDev(); + ReleaseHostapdDev(0); if (mServer != nullptr) { ReleaseRpcServer(mServer); mServer = nullptr; @@ -58,129 +58,129 @@ void WifiHalHostapdTest::TearDownTestCase() HWTEST_F(WifiHalHostapdTest, EnableApTest, TestSize.Level1) { MockEraseSupportedCmd("ENABLE"); - int ret = mInterface->enableAp(); + int ret = mInterface->enableAp(0); EXPECT_TRUE(ret != 0); MockSetWpaExpectCmdResponse("ENABLE", "OK"); - ret = mInterface->enableAp(); + ret = mInterface->enableAp(0); EXPECT_TRUE(ret == 0); MockWpaCallback(mInterface->ctrlConn, "<3>AP-ENABLED \n"); } HWTEST_F(WifiHalHostapdTest, SetApInfoTest, TestSize.Level1) { - EXPECT_TRUE(mInterface->setApInfo(nullptr) < 0); + EXPECT_TRUE(mInterface->setApInfo(nullptr, 0) < 0); HostapdConfig conf; ASSERT_TRUE(memset_s(&conf, sizeof(conf), 0, sizeof(conf)) == EOK); conf.securityType = WPA_PSK; - EXPECT_TRUE(mInterface->setApInfo(&conf) < 0); + EXPECT_TRUE(mInterface->setApInfo(&conf, 0) < 0); StrSafeCopy(conf.preSharedKey, sizeof(conf.preSharedKey), "1234567"); - EXPECT_TRUE(mInterface->setApInfo(&conf) < 0); + EXPECT_TRUE(mInterface->setApInfo(&conf, 0) < 0); StrSafeCopy(conf.preSharedKey, sizeof(conf.preSharedKey), "12345678"); conf.preSharedKeyLen = strlen(conf.preSharedKey); - EXPECT_TRUE(mInterface->setApInfo(&conf) == 0); + EXPECT_TRUE(mInterface->setApInfo(&conf, 0) == 0); conf.securityType = WPA2_PSK; - EXPECT_TRUE(mInterface->setApInfo(&conf) == 0); + EXPECT_TRUE(mInterface->setApInfo(&conf, 0) == 0); conf.securityType = NONE; - EXPECT_TRUE(mInterface->setApInfo(&conf) == 0); + EXPECT_TRUE(mInterface->setApInfo(&conf, 0) == 0); conf.securityType = IEEE8021X; - EXPECT_TRUE(mInterface->setApInfo(&conf) < 0); + EXPECT_TRUE(mInterface->setApInfo(&conf, 0) < 0); conf.securityType = NONE; conf.band = AP_2GHZ_BAND; - EXPECT_TRUE(mInterface->setApInfo(&conf) == 0); + EXPECT_TRUE(mInterface->setApInfo(&conf, 0) == 0); conf.band = AP_5GHZ_BAND; - EXPECT_TRUE(mInterface->setApInfo(&conf) == 0); + EXPECT_TRUE(mInterface->setApInfo(&conf, 0) == 0); conf.band = -1; - EXPECT_TRUE(mInterface->setApInfo(&conf) < 0); + EXPECT_TRUE(mInterface->setApInfo(&conf, 0) < 0); conf.band = AP_DFS_BAND; - EXPECT_TRUE(mInterface->setApInfo(&conf) < 0); + EXPECT_TRUE(mInterface->setApInfo(&conf, 0) < 0); } HWTEST_F(WifiHalHostapdTest, DisableApTest, TestSize.Level1) { MockEraseSupportedCmd("DISABLE"); - int ret = mInterface->disableAp(); + int ret = mInterface->disableAp(0); EXPECT_TRUE(ret != 0); MockSetWpaExpectCmdResponse("DISABLE", "OK"); - ret = mInterface->disableAp(); + ret = mInterface->disableAp(0); EXPECT_TRUE(ret == 0); MockWpaCallback(mInterface->ctrlConn, "<3>AP-DISABLED \n"); } HWTEST_F(WifiHalHostapdTest, AddBlockListTest, TestSize.Level1) { - EXPECT_TRUE(mInterface->addBlocklist(nullptr) < 0); - EXPECT_TRUE(mInterface->addBlocklist("00:00:00:00:00:00") == 0); + EXPECT_TRUE(mInterface->addBlocklist(nullptr, 0) < 0); + EXPECT_TRUE(mInterface->addBlocklist("00:00:00:00:00:00", 0) == 0); MockSetWpaExpectCmdResponse("DENY_ACL", "UNKNOWN COMMAND"); - EXPECT_TRUE(mInterface->addBlocklist("00:00:00:00:00:00") == 0); + EXPECT_TRUE(mInterface->addBlocklist("00:00:00:00:00:00", 0) == 0); MockSetWpaExpectCmdResponse("DENY_ACL", "OK"); } HWTEST_F(WifiHalHostapdTest, DelBlockListTest, TestSize.Level1) { - EXPECT_TRUE(mInterface->delBlocklist(nullptr) < 0); - EXPECT_TRUE(mInterface->delBlocklist("00:00:00:00:00:00") == 0); + EXPECT_TRUE(mInterface->delBlocklist(nullptr, 0) < 0); + EXPECT_TRUE(mInterface->delBlocklist("00:00:00:00:00:00", 0) == 0); MockSetWpaExpectCmdResponse("DENY_ACL", "UNKNOWN COMMAND"); - EXPECT_TRUE(mInterface->delBlocklist("00:00:00:00:00:00") == 0); + EXPECT_TRUE(mInterface->delBlocklist("00:00:00:00:00:00", 0) == 0); MockSetWpaExpectCmdResponse("DENY_ACL", "OK"); } HWTEST_F(WifiHalHostapdTest, GetApStatusTest, TestSize.Level1) { - EXPECT_TRUE(mInterface->status(nullptr) < 0); + EXPECT_TRUE(mInterface->status(nullptr, 0) < 0); StatusInfo info; ASSERT_TRUE(memset_s(&info, sizeof(info), 0, sizeof(info)) == EOK); - EXPECT_TRUE(mInterface->status(&info) == 0); + EXPECT_TRUE(mInterface->status(&info, 0) == 0); char buf[BUFSIZE_REQUEST] = "test1=adsgdjks\nteset2=gflsdfis\ntest3=" "gfdklse\nstate=disable\ngfdsd=gdhjs\n"; MockSetWpaExpectCmdResponse("STATUS", buf); - EXPECT_TRUE(mInterface->status(&info) == 0); + EXPECT_TRUE(mInterface->status(&info, 0) == 0); EXPECT_TRUE(strcmp(info.state, "disable") == 0); } HWTEST_F(WifiHalHostapdTest, HostapdCliCmdListStaTest, TestSize.Level1) { - EXPECT_TRUE(mInterface->showConnectedDevList(nullptr, 0) < 0); + EXPECT_TRUE(mInterface->showConnectedDevList(nullptr, 0, 0) < 0); char buff[256] = {0}; int size = 256; MockEraseSupportedCmd("STA-FIRST"); - EXPECT_TRUE(mInterface->showConnectedDevList(buff, size) < 0); + EXPECT_TRUE(mInterface->showConnectedDevList(buff, size, 0) < 0); MockSetWpaExpectCmdResponse("STA-FIRST", "00:00:00:00:00:00"); MockSetWpaExpectCmdResponse("STA-NEXT", "FAIL"); - EXPECT_TRUE(mInterface->showConnectedDevList(buff, size) == 0); + EXPECT_TRUE(mInterface->showConnectedDevList(buff, size, 0) == 0); EXPECT_TRUE(strcmp(buff, ",00:00:00:00:00:00") == 0); } HWTEST_F(WifiHalHostapdTest, ReloadApConfigInfoTest, TestSize.Level1) { MockEraseSupportedCmd("RELOAD"); - int ret = mInterface->reloadApConfigInfo(); + int ret = mInterface->reloadApConfigInfo(0); EXPECT_TRUE(ret != 0); MockSetWpaExpectCmdResponse("RELOAD", "OK"); - ret = mInterface->reloadApConfigInfo(); + ret = mInterface->reloadApConfigInfo(0); EXPECT_TRUE(ret == 0); } HWTEST_F(WifiHalHostapdTest, DisConnectedDevTest, TestSize.Level1) { MockWpaCallback(mInterface->ctrlConn, "<3>AP-STA-CONNECTED 00:00:00:00:00:00\n"); - EXPECT_TRUE(mInterface->disConnectedDev(nullptr) < 0); + EXPECT_TRUE(mInterface->disConnectedDev(nullptr, 0) < 0); MockEraseSupportedCmd("DISASSOCIATE"); - int ret = mInterface->disConnectedDev("00:00:00:00:00:00"); + int ret = mInterface->disConnectedDev("00:00:00:00:00:00", 0); EXPECT_TRUE(ret != 0); MockSetWpaExpectCmdResponse("DISASSOCIATE", "OK"); - ret = mInterface->disConnectedDev("00:00:00:00:00:00"); + ret = mInterface->disConnectedDev("00:00:00:00:00:00", 0); EXPECT_TRUE(ret == 0); MockWpaCallback(mInterface->ctrlConn, "<3>AP-STA-DISCONNECTED 00:00:00:00:00:00\n"); } HWTEST_F(WifiHalHostapdTest, SetCountryCodeTest, TestSize.Level1) { - EXPECT_TRUE(mInterface->setCountryCode(nullptr) < 0); + EXPECT_TRUE(mInterface->setCountryCode(nullptr, 0) < 0); MockEraseSupportedCmd("SET"); - int ret = mInterface->setCountryCode("CN"); + int ret = mInterface->setCountryCode("CN", 0); EXPECT_TRUE(ret != 0); MockSetWpaExpectCmdResponse("SET", "OK"); - ret = mInterface->setCountryCode("CN"); + ret = mInterface->setCountryCode("CN", 0); EXPECT_TRUE(ret == 0); } } // namespace Wifi diff --git a/tests/wifi_standard/wifi_hal/unittest/wifi_hal_hostapd_test.h b/wifi/test/wifi_standard/wifi_hal/unittest/wifi_hal_hostapd_test.h similarity index 100% rename from tests/wifi_standard/wifi_hal/unittest/wifi_hal_hostapd_test.h rename to wifi/test/wifi_standard/wifi_hal/unittest/wifi_hal_hostapd_test.h diff --git a/tests/wifi_standard/wifi_hal/unittest/wifi_hal_p2p_interface_test.cpp b/wifi/test/wifi_standard/wifi_hal/unittest/wifi_hal_p2p_interface_test.cpp similarity index 98% rename from tests/wifi_standard/wifi_hal/unittest/wifi_hal_p2p_interface_test.cpp rename to wifi/test/wifi_standard/wifi_hal/unittest/wifi_hal_p2p_interface_test.cpp index 09bf66611dd43023e405751cdbcc2a97d441bd6d..b4839e873700a528466906c14fc429ae899d6a87 100644 --- a/tests/wifi_standard/wifi_hal/unittest/wifi_hal_p2p_interface_test.cpp +++ b/wifi/test/wifi_standard/wifi_hal/unittest/wifi_hal_p2p_interface_test.cpp @@ -125,7 +125,7 @@ HWTEST_F(WifiHalP2pInterfaceTest, P2pListNetworksTest, TestSize.Level1) char replyBuff[] = "network id / ssid / bssid / flags\n" "0\tDIRECT-OHOS\t00:00:00:00:00:00\t[DISABLED][P2P-PERSISTENT]\n"; MockSetWpaExpectCmdResponse("LIST_NETWORKS", replyBuff); - HidlP2pNetworkList info; + P2pNetworkList info; ASSERT_TRUE(memset_s(&info, sizeof(info), 0, sizeof(info)) == EOK); EXPECT_TRUE(P2pListNetworks(&info) == WIFI_HAL_SUCCESS); } @@ -178,7 +178,7 @@ HWTEST_F(WifiHalP2pInterfaceTest, P2pSetListenChannelTest, TestSize.Level1) HWTEST_F(WifiHalP2pInterfaceTest, P2pConnectTest, TestSize.Level1) { EXPECT_TRUE(P2pConnect(NULL) == WIFI_HAL_FAILED); - HidlP2pConnectInfo info; + P2pConnectInfo info; ASSERT_TRUE(memset_s(&info, sizeof(info), 0, sizeof(info)) == EOK); EXPECT_TRUE(P2pConnect(&info) == WIFI_HAL_SUCCESS); } @@ -228,7 +228,7 @@ HWTEST_F(WifiHalP2pInterfaceTest, P2pGetGroupCapabilityTest, TestSize.Level1) HWTEST_F(WifiHalP2pInterfaceTest, P2pAddServiceTest, TestSize.Level1) { EXPECT_TRUE(P2pAddService(nullptr) == WIFI_HAL_FAILED); - HidlP2pServiceInfo info; + P2pServiceInfo info; ASSERT_TRUE(memset_s(&info, sizeof(info), 0, sizeof(info)) == EOK); EXPECT_TRUE(P2pAddService(&info) == WIFI_HAL_INVALID_PARAM); info.mode = 0; @@ -243,7 +243,7 @@ HWTEST_F(WifiHalP2pInterfaceTest, P2pAddServiceTest, TestSize.Level1) HWTEST_F(WifiHalP2pInterfaceTest, P2pRemoveServiceTest, TestSize.Level1) { EXPECT_TRUE(P2pRemoveService(nullptr) == WIFI_HAL_FAILED); - HidlP2pServiceInfo info; + P2pServiceInfo info; ASSERT_TRUE(memset_s(&info, sizeof(info), 0, sizeof(info)) == EOK); EXPECT_TRUE(P2pRemoveService(&info) == WIFI_HAL_INVALID_PARAM); info.mode = 0; @@ -276,7 +276,7 @@ HWTEST_F(WifiHalP2pInterfaceTest, P2pSetMiracastTypeTest, TestSize.Level1) HWTEST_F(WifiHalP2pInterfaceTest, P2pRespServerDiscoveryTest, TestSize.Level1) { EXPECT_TRUE(P2pRespServerDiscovery(nullptr) == WIFI_HAL_FAILED); - HidlP2pServDiscReqInfo info; + P2pServDiscReqInfo info; ASSERT_TRUE(memset_s(&info, sizeof(info), 0, sizeof(info)) == EOK); info.tlvs = (char *)calloc(32, sizeof(char)); EXPECT_TRUE(P2pRespServerDiscovery(&info) == WIFI_HAL_SUCCESS); diff --git a/tests/wifi_standard/wifi_hal/unittest/wifi_hal_p2p_interface_test.h b/wifi/test/wifi_standard/wifi_hal/unittest/wifi_hal_p2p_interface_test.h similarity index 100% rename from tests/wifi_standard/wifi_hal/unittest/wifi_hal_p2p_interface_test.h rename to wifi/test/wifi_standard/wifi_hal/unittest/wifi_hal_p2p_interface_test.h diff --git a/tests/wifi_standard/wifi_hal/unittest/wifi_hal_sta_interface_test.cpp b/wifi/test/wifi_standard/wifi_hal/unittest/wifi_hal_sta_interface_test.cpp similarity index 98% rename from tests/wifi_standard/wifi_hal/unittest/wifi_hal_sta_interface_test.cpp rename to wifi/test/wifi_standard/wifi_hal/unittest/wifi_hal_sta_interface_test.cpp index 872fb002b7a0b8ebb8426a1bd6fd917e1c6dcb38..9bfcb5ee13566e3c68184e97179b9df6a91fc6d8 100644 --- a/tests/wifi_standard/wifi_hal/unittest/wifi_hal_sta_interface_test.cpp +++ b/wifi/test/wifi_standard/wifi_hal/unittest/wifi_hal_sta_interface_test.cpp @@ -82,7 +82,7 @@ HWTEST_F(WifiHalStaInterfaceTest, DisableNetworkTest, TestSize.Level1) HWTEST_F(WifiHalStaInterfaceTest, SetNetworkTest, TestSize.Level1) { EXPECT_TRUE(SetNetwork(0, nullptr, 0) == WIFI_HAL_FAILED); - HidlSetNetworkConfig conf; + SetNetworkConfig conf; conf.cfgParam = DEVICE_CONFIG_SSID; StrSafeCopy(conf.cfgValue, sizeof(conf.cfgValue), "network_ssid"); EXPECT_TRUE(SetNetwork(0, &conf, 1) == WIFI_HAL_SUCCESS); @@ -156,7 +156,7 @@ HWTEST_F(WifiHalStaInterfaceTest, WpaGetCountryCodeTest, TestSize.Level1) HWTEST_F(WifiHalStaInterfaceTest, WpaGetNetWorkTest, TestSize.Level1) { EXPECT_TRUE(WpaGetNetWork(nullptr) == WIFI_HAL_FAILED); - HidlGetNetworkConfig conf; + GetNetworkConfig conf; ASSERT_TRUE(memset_s(&conf, sizeof(conf), 0, sizeof(conf)) == EOK); conf.networkId = 0; StrSafeCopy(conf.param, sizeof(conf.param), "ssid"); @@ -171,7 +171,7 @@ HWTEST_F(WifiHalStaInterfaceTest, WpaAutoConnectTest, TestSize.Level1) HWTEST_F(WifiHalStaInterfaceTest, GetNetworkListTest, TestSize.Level1) { EXPECT_TRUE(GetNetworkList(nullptr, nullptr) == WIFI_HAL_FAILED); - HidlNetworkInfo infos[20]; + WifiNetworkInfo infos[20]; ASSERT_TRUE(memset_s(infos, sizeof(infos), 0, sizeof(infos)) == EOK); int maxSize = 20; EXPECT_TRUE(GetNetworkList(infos, &maxSize) == WIFI_HAL_SUCCESS); @@ -195,7 +195,7 @@ HWTEST_F(WifiHalStaInterfaceTest, WpaBlocklistClearTest, TestSize.Level1) HWTEST_F(WifiHalStaInterfaceTest, GetConnectSignalInfoTest, TestSize.Level1) { EXPECT_TRUE(GetConnectSignalInfo(nullptr, nullptr) == WIFI_HAL_FAILED); - HidlWpaSignalInfo info; + WpaSignalInfo info; ASSERT_TRUE(memset_s(&info, sizeof(info), 0, sizeof(info)) == EOK); WifiErrorNo ret = GetConnectSignalInfo("00:00:00:00:00:00", &info); EXPECT_TRUE(ret != WIFI_HAL_SUPPLICANT_NOT_INIT && ret != WIFI_HAL_GET_WIFI_COND_FAILED); diff --git a/tests/wifi_standard/wifi_hal/unittest/wifi_hal_sta_interface_test.h b/wifi/test/wifi_standard/wifi_hal/unittest/wifi_hal_sta_interface_test.h similarity index 100% rename from tests/wifi_standard/wifi_hal/unittest/wifi_hal_sta_interface_test.h rename to wifi/test/wifi_standard/wifi_hal/unittest/wifi_hal_sta_interface_test.h diff --git a/tests/wifi_standard/wifi_hal/unittest/wifi_hal_vendor.conf b/wifi/test/wifi_standard/wifi_hal/unittest/wifi_hal_vendor.conf similarity index 100% rename from tests/wifi_standard/wifi_hal/unittest/wifi_hal_vendor.conf rename to wifi/test/wifi_standard/wifi_hal/unittest/wifi_hal_vendor.conf diff --git a/tests/wifi_standard/wifi_hal/unittest/wifi_hal_vendor_interface_test.c b/wifi/test/wifi_standard/wifi_hal/unittest/wifi_hal_vendor_interface_test.c similarity index 100% rename from tests/wifi_standard/wifi_hal/unittest/wifi_hal_vendor_interface_test.c rename to wifi/test/wifi_standard/wifi_hal/unittest/wifi_hal_vendor_interface_test.c diff --git a/tests/wifi_standard/wifi_hal/unittest/wifi_hal_wpa_p2p_test.cpp b/wifi/test/wifi_standard/wifi_hal/unittest/wifi_hal_wpa_p2p_test.cpp similarity index 99% rename from tests/wifi_standard/wifi_hal/unittest/wifi_hal_wpa_p2p_test.cpp rename to wifi/test/wifi_standard/wifi_hal/unittest/wifi_hal_wpa_p2p_test.cpp index 7d19b97b778263483ad6196c70c4debd1c2579e0..634e62cecd8a045828da2e6f7e715879bf218aad 100644 --- a/tests/wifi_standard/wifi_hal/unittest/wifi_hal_wpa_p2p_test.cpp +++ b/wifi/test/wifi_standard/wifi_hal/unittest/wifi_hal_wpa_p2p_test.cpp @@ -325,7 +325,7 @@ HWTEST_F(WifiHalWpaP2pTest, WpaP2pCliCmdReInviteTest, TestSize.Level1) HWTEST_F(WifiHalWpaP2pTest, WpaP2pCliCmdServiceAddTest, TestSize.Level1) { EXPECT_TRUE(mInterface->wpaP2pCliCmdServiceAdd(nullptr, nullptr) != P2P_SUP_ERRCODE_SUCCESS); - HidlP2pServiceInfo info; + P2pServiceInfo info; ASSERT_TRUE(memset_s(&info, sizeof(info), 0, sizeof(info)) == EOK); EXPECT_TRUE(mInterface->wpaP2pCliCmdServiceAdd(mInterface, &info) != P2P_SUP_ERRCODE_SUCCESS); StrSafeCopy(info.name, sizeof(info.name), "random_string"); @@ -346,7 +346,7 @@ HWTEST_F(WifiHalWpaP2pTest, WpaP2pCliCmdServiceAddTest, TestSize.Level1) HWTEST_F(WifiHalWpaP2pTest, WpaP2pCliCmdServiceDelTest, TestSize.Level1) { EXPECT_TRUE(mInterface->wpaP2pCliCmdServiceDel(nullptr, nullptr) != P2P_SUP_ERRCODE_SUCCESS); - HidlP2pServiceInfo info; + P2pServiceInfo info; ASSERT_TRUE(memset_s(&info, sizeof(info), 0, sizeof(info)) == EOK); EXPECT_TRUE(mInterface->wpaP2pCliCmdServiceDel(mInterface, &info) != P2P_SUP_ERRCODE_SUCCESS); StrSafeCopy(info.name, sizeof(info.name), "random_string"); @@ -474,7 +474,7 @@ HWTEST_F(WifiHalWpaP2pTest, WpaP2pCliCmdStoreConfigTest, TestSize.Level1) HWTEST_F(WifiHalWpaP2pTest, WpaP2pCliCmdNetworkListTest, TestSize.Level1) { EXPECT_TRUE(mInterface->wpaP2pCliCmdNetworkList(nullptr, nullptr) != P2P_SUP_ERRCODE_SUCCESS); - HidlP2pNetworkList infoList; + P2pNetworkList infoList; ASSERT_TRUE(memset_s(&infoList, sizeof(infoList), 0, sizeof(infoList)) == EOK); MockEraseSupportedCmd("LIST_NETWORKS"); EXPECT_TRUE(mInterface->wpaP2pCliCmdNetworkList(mInterface, &infoList) != P2P_SUP_ERRCODE_SUCCESS); @@ -503,7 +503,7 @@ HWTEST_F(WifiHalWpaP2pTest, WpaP2pCliCmdNetworkListTest, TestSize.Level1) HWTEST_F(WifiHalWpaP2pTest, WpaP2pCliCmdConnectTest, TestSize.Level1) { EXPECT_TRUE(mInterface->wpaP2pCliCmdConnect(nullptr, nullptr) != P2P_SUP_ERRCODE_SUCCESS); - HidlP2pConnectInfo info; + P2pConnectInfo info; ASSERT_TRUE(memset_s(&info, sizeof(info), 0, sizeof(info)) == EOK); info.mode = 0; info.goIntent = 0; @@ -551,7 +551,7 @@ HWTEST_F(WifiHalWpaP2pTest, WpaP2pCliCmdP2pGetPeerTest, TestSize.Level1) { EXPECT_TRUE(mInterface->wpaP2pCliCmdP2pGetPeer(nullptr, nullptr, nullptr) != P2P_SUP_ERRCODE_SUCCESS); const char *bssid = "00:00:00:00:00:00"; - HidlP2pDeviceInfo info; + P2pDeviceInfo info; MockEraseSupportedCmd("P2P_PEER"); EXPECT_TRUE(mInterface->wpaP2pCliCmdP2pGetPeer(mInterface, nullptr, &info) != P2P_SUP_ERRCODE_SUCCESS); MockSetWpaExpectCmdResponse("P2P_PEER", "group_capab=0x0\n"); @@ -574,7 +574,7 @@ HWTEST_F(WifiHalWpaP2pTest, WpaP2pCliCmdSetPersistentReconnectTest, TestSize.Lev HWTEST_F(WifiHalWpaP2pTest, WpaP2pCliCmdRespServerDiscoveryTest, TestSize.Level1) { EXPECT_TRUE(mInterface->wpaP2pCliCmdRespServerDiscovery(nullptr, nullptr) != P2P_SUP_ERRCODE_SUCCESS); - HidlP2pServDiscReqInfo info; + P2pServDiscReqInfo info; ASSERT_TRUE(memset_s(&info, sizeof(info), 0, sizeof(info)) == EOK); info.freq = 2412; info.dialogToken = 0; diff --git a/tests/wifi_standard/wifi_hal/unittest/wifi_hal_wpa_p2p_test.h b/wifi/test/wifi_standard/wifi_hal/unittest/wifi_hal_wpa_p2p_test.h similarity index 100% rename from tests/wifi_standard/wifi_hal/unittest/wifi_hal_wpa_p2p_test.h rename to wifi/test/wifi_standard/wifi_hal/unittest/wifi_hal_wpa_p2p_test.h diff --git a/tests/wifi_standard/wifi_hal/unittest/wifi_hal_wpa_sta_test.cpp b/wifi/test/wifi_standard/wifi_hal/unittest/wifi_hal_wpa_sta_test.cpp similarity index 99% rename from tests/wifi_standard/wifi_hal/unittest/wifi_hal_wpa_sta_test.cpp rename to wifi/test/wifi_standard/wifi_hal/unittest/wifi_hal_wpa_sta_test.cpp index 551d816e384b704492cec8d8f5a149b97750022f..827da570ddc52dc4c9d5ebe38edbf51af29c75b2 100644 --- a/tests/wifi_standard/wifi_hal/unittest/wifi_hal_wpa_sta_test.cpp +++ b/wifi/test/wifi_standard/wifi_hal/unittest/wifi_hal_wpa_sta_test.cpp @@ -333,7 +333,7 @@ HWTEST_F(WifiHalWpaStaTest, WpaCliCmdWpaBlockListClearTest, TestSize.Level1) HWTEST_F(WifiHalWpaStaTest, WpaCliCmdListNetworksTest, TestSize.Level1) { EXPECT_TRUE(mInterface->wpaCliCmdListNetworks(mInterface, nullptr, nullptr) < 0); - HidlNetworkInfo a[256]; + WifiNetworkInfo a[256]; ASSERT_TRUE(memset_s(a, sizeof(a), 0, sizeof(a)) == EOK); int size = 256; MockEraseSupportedCmd("LIST_NETWORKS"); @@ -362,7 +362,7 @@ HWTEST_F(WifiHalWpaStaTest, WpaCliCmdListNetworksTest, TestSize.Level1) HWTEST_F(WifiHalWpaStaTest, WpaCliCmdGetSignalInfoTest, TestSize.Level1) { EXPECT_TRUE(mInterface->wpaCliCmdGetSignalInfo(mInterface, nullptr) < 0); - HidlWpaSignalInfo info; + WpaSignalInfo info; ASSERT_TRUE(memset_s(&info, sizeof(info), 0, sizeof(info)) == EOK); EXPECT_TRUE(mInterface->wpaCliCmdGetSignalInfo(mInterface, &info) == 0); MockEraseSupportedCmd("SIGNAL_POLL"); diff --git a/tests/wifi_standard/wifi_hal/unittest/wifi_hal_wpa_sta_test.h b/wifi/test/wifi_standard/wifi_hal/unittest/wifi_hal_wpa_sta_test.h similarity index 100% rename from tests/wifi_standard/wifi_hal/unittest/wifi_hal_wpa_sta_test.h rename to wifi/test/wifi_standard/wifi_hal/unittest/wifi_hal_wpa_sta_test.h diff --git a/wifi/utils/BUILD.gn b/wifi/utils/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..f3dc45bc564f8bfdb48648b516237e1d7af854bd --- /dev/null +++ b/wifi/utils/BUILD.gn @@ -0,0 +1,87 @@ +# Copyright (C) 2021-2022 Huawei Device Co., Ltd. +# 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. + +if (defined(ohos_lite)) { + import("//build/lite/config/component/lite_component.gni") + import("//foundation/communication/wifi/wifi/wifi_lite.gni") + + shared_library("wifi_utils") { + include_dirs = [ + "$WIFI_ROOT_DIR/services/wifi_standard/wifi_framework/wifi_toolkit/log", + "$WIFI_ROOT_DIR/utils/inc", + "//base/hiviewdfx/hilog_lite/interfaces/native/innerkits", + "//third_party/bounds_checking_function/include", + ] + + sources = [ "src/wifi_common_util.cpp" ] + + deps = [ + "//base/hiviewdfx/hilog_lite/frameworks/featured:hilog_shared", + "//third_party/bounds_checking_function:libsec_shared", + ] + + cflags_cc = [ + "-std=c++17", + "-fno-rtti", + ] + ldflags = [ + "-fPIC", + "-Wl,-E", + ] + defines = [ "OHOS_ARCH_LITE" ] + } +} else { + import("//build/ohos.gni") + import("//foundation/communication/wifi/wifi/wifi.gni") + + ohos_shared_library("wifi_utils") { + install_enable = true + include_dirs = [ + "$WIFI_ROOT_DIR/utils/inc", + "//base/hiviewdfx/hisysevent/interfaces/native/innerkits/hisysevent/include", + "$WIFI_ROOT_DIR/services/wifi_standard/wifi_framework/wifi_toolkit/log", + ] + + sources = [ + "src/wifi_common_util.cpp", + "src/wifi_hisysevent.cpp", + ] + + deps = [ + "//base/hiviewdfx/hilog/interfaces/native/innerkits:libhilog", + "//foundation/systemabilitymgr/samgr/interfaces/innerkits/samgr_proxy:samgr_proxy", + ] + + external_deps = [ + "ability_base:want", + "ability_runtime:app_manager", + "bundle_framework:appexecfwk_core", + "c_utils:utils", + "hisysevent_native:libhisysevent", + "ipc:ipc_core", + ] + + cflags_cc = [ + "-std=c++17", + "-fno-rtti", + ] + + ldflags = [ + "-fPIC", + "-Wl,-E", + ] + + part_name = "wifi" + subsystem_name = "communication" + } +} diff --git a/wifi/utils/inc/wifi_common_util.h b/wifi/utils/inc/wifi_common_util.h new file mode 100644 index 0000000000000000000000000000000000000000..2afc1626a831a7354ede754e004c2fb372bcdb26 --- /dev/null +++ b/wifi/utils/inc/wifi_common_util.h @@ -0,0 +1,185 @@ +/* + * Copyright (C) 2021-2022 Huawei Device Co., Ltd. + * 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 OHOS_WIFI_COMMON_UTIL_H +#define OHOS_WIFI_COMMON_UTIL_H + +#include +#include +#include +#include "securec.h" + +#ifndef WIFI_MAC_LEN +#define WIFI_MAC_LEN 6 +#endif + +namespace OHOS { +namespace Wifi { +/** + * @Description MAC address anonymization + * + *

eg: a2:7c:b0:98:e3:92 -> a2:7c:**:**:**:92 + * + * @param str - Input MAC address + * @return std::string - Processed MAC + */ +std::string MacAnonymize(const std::string str); + +/** + * @Description MAC address anonymization + * + *

eg: 192.168.0.1 -> 192.***.*.1 + * + * @param str - Input MAC address + * @return std::string - Processed MAC + */ +std::string IpAnonymize(const std::string str); + +/** + * @Description Ssid anonymization + * + *

a) Length less than or equal to 2, all bits are hidden; + * b) Length less than or equal to 4, hiding the middle bit; + * c) Length less than or equal to 8, hiding 3 bits from the second bit; + * d) Length greater than or equal to 9, showing the first and last three bits, the middle bits are hidden + *

eg: + * 1 -> * + * 12 -> ** + * 123 -> 1*3 + * 1234 -> 1**4 + * 12345 -> 1***5 + * 123456 -> 1***56 + * 1234567 -> 1***567 + * 12345678 -> 1***5678 + * 123456789 -> 123***789 + * 12345678910 -> 123*****910 + * + * @param str - Input ssid + * @return std::string - Processed ssid + */ +std::string SsidAnonymize(const std::string str); + +/** + * @Description Converting string MAC to a C-style MAC address + * + * @param strMac - Input MAC address + * @param mac - conversion result + * @return errno_t - EOK for success, failure for other values. + */ +errno_t MacStrToArray(const std::string& strMac, unsigned char mac[WIFI_MAC_LEN]); + +/** + * @Description Converting C-style MAC to a string MAC + * + * @param mac - Input MAC address + * @return string - conversion result. + */ +std::string MacArrayToStr(const unsigned char mac[WIFI_MAC_LEN]); + +/** + * @Description Check whether the array of MAC address is empty + * + * @param mac - Input MAC address + * @return bool - true: empty, false: not empty + */ +bool IsMacArrayEmpty(const unsigned char mac[WIFI_MAC_LEN]); + +/** + * @Description Converting a string IP Address to an integer IP address + * + * @param strIp - Input string IP address + * @return unsigned int - integer IP address + */ +unsigned int Ip2Number(const std::string& strIp); + +/** + * @Description Converting an integer IP address to a string IP Address + * + * @param intIp - Input integer IP address + * @return string - string IP address + */ +std::string Number2Ip(unsigned int intIp); + +/** + * @Description Splitting strings by delimiter + * + * @param str - Input string + * @param delim - Split delimiter + * @return std::vector - Split result + */ +std::vector StrSplit(const std::string& str, const std::string& delim); + +#ifndef OHOS_ARCH_LITE +/** + * @Description get bundle name, it can only be obtained at the interfaces layer. + * + * @return bool - bundle name + */ +std::string GetBundleName(); + +/** + * @Description Check whether the app is a system app + * + * @return bool - Returns true for yes, false for no. + */ +bool IsSystemApp(); + +/** + * @Description get calling uid + * + * @return int - calling uid + */ +int GetCallingUid(); + +/** + * @Description Check uid the app is a foregroud app + * + * @param uid - Input uid + * @return bool - Returns true for yes, false for no. + */ +bool IsForegroundApp(const int uid); + +/** + * @Description Convert frequency to channel + * + * @return int - channel + */ +int FrequencyToChannel(int freq); + +/** + * @Description Convert channel to frequency + * + * @return int - frequency + */ +int ChannelToFrequency(int channel); + +/** + * @Description Time consuming statistics + * + */ +class TimeStats final { +public: + TimeStats(const std::string desc); + TimeStats() = delete; + ~TimeStats(); + +private: + std::string m_desc; + std::chrono::steady_clock::time_point m_startTime; +}; +#endif +} // namespace Wifi +} // namespace OHOS +#endif \ No newline at end of file diff --git a/wifi/utils/inc/wifi_hisysevent.h b/wifi/utils/inc/wifi_hisysevent.h new file mode 100644 index 0000000000000000000000000000000000000000..253812776b8b881fab742cd187451958fde363ff --- /dev/null +++ b/wifi/utils/inc/wifi_hisysevent.h @@ -0,0 +1,62 @@ +/* + * Copyright (C) 2022 Huawei Device Co., Ltd. + * 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 OHOS_WIFI_HISYSEVENT_H +#define OHOS_WIFI_HISYSEVENT_H + +#include + +namespace OHOS { +namespace Wifi { +enum class WifiOperType { + ENABLE, + DISABLE +}; + +enum class WifiConnectionType { + CONNECT, + DISCONNECT +}; + +const int HISYS_EVENT_DEFAULT_VALUE = -1; + +const std::string HISYS_STA_POWER_STATE_CHANGE = "wifiStateChange"; +const std::string HISYS_STA_CONN_STATE_CHANGE = "wifiConnectionChange"; +const std::string HISYS_STA_SCAN_STATE_CHANGE = "wifiScanStateChange"; +const std::string HISYS_STA_RSSI_STATE_CHANGE = "wifiRssiChange"; +const std::string HISYS_HOTSPOT_STATE_CHANGE = "hotspotStateChange"; +const std::string HISYS_HOTSPOT_STA_JOIN = "hotspotStaJoin"; +const std::string HISYS_HOTSPOT_STA_LEAVE = "hotspotStaLeave"; +const std::string HISYS_P2P_STATE_CHANGE = "p2pStateChange"; +const std::string HISYS_P2P_CONN_STATE_CHANGE = "p2pConnectionChange"; +const std::string HISYS_P2P_DEVICE_STATE_CHANGE = "p2pDeviceChange"; +const std::string HISYS_P2P_PERSISTENT_GROUP_CHANGE = "p2pPersistentGroupChange"; +const std::string HISYS_P2P_PEER_DEVICE_CHANGE = "p2pPeerDeviceChange"; +const std::string HISYS_P2P_DISCOVERY_CHANGE = "p2pDiscoveryChange"; + +const std::string HISYS_SERVICE_TYPE_STA = "STA"; +const std::string HISYS_SERVICE_TYPE_AP = "AP"; +const std::string HISYS_SERVICE_TYPE_P2P = "P2P"; + +void WriteWifiStateHiSysEvent(const std::string& serviceType, WifiOperType operType); + +void WriteWifiConnectionHiSysEvent(const WifiConnectionType& type, const std::string& pkgName); + +void WriteWifiScanHiSysEvent(const int result, const std::string& pkgName); + +void WriteWifiEventReceivedHiSysEvent(const std::string& eventType, int value); +} // namespace Wifi +} // namespace OHOS +#endif \ No newline at end of file diff --git a/wifi/utils/src/wifi_common_util.cpp b/wifi/utils/src/wifi_common_util.cpp new file mode 100644 index 0000000000000000000000000000000000000000..7ca25ab73721b8e36a44961d2957b280c5f74fc2 --- /dev/null +++ b/wifi/utils/src/wifi_common_util.cpp @@ -0,0 +1,349 @@ +/* + * Copyright (C) 2021-2022 Huawei Device Co., Ltd. + * 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 "wifi_common_util.h" +#include +#include +#include +#ifndef OHOS_ARCH_LITE +#include "app_mgr_client.h" +#include "bundle_mgr_interface.h" +#include "if_system_ability_manager.h" +#include "ipc_skeleton.h" +#include "iservice_registry.h" +#include "system_ability_definition.h" +#endif +#include "wifi_logger.h" + +namespace OHOS { +namespace Wifi { +DEFINE_WIFILOG_LABEL("WifiCommonUtil"); + +constexpr int INVALID_FREQ_OR_CHANNEL = -1; +constexpr int FREQ_2G_MIN = 2412; +constexpr int FREQ_2G_MAX = 2472; +constexpr int FREQ_5G_MIN = 5170; +constexpr int FREQ_5G_MAX = 5825; +constexpr int CHANNEL_14_FREQ = 2484; +constexpr int CHANNEL_14 = 14; +constexpr int CENTER_FREQ_DIFF = 5; +constexpr int CHANNEL_2G_MIN = 1; +constexpr int CHANNEL_5G_MIN = 34; +constexpr int MIN_24G_CHANNEL = 1; +constexpr int MAX_24G_CHANNEL = 13; +constexpr int MIN_5G_CHANNEL = 36; +constexpr int MAX_5G_CHANNEL = 165; +constexpr int FREQ_CHANNEL_1 = 2412; +constexpr int FREQ_CHANNEL_36 = 5180; + +static std::string DataAnonymize(const std::string str, const char delim, + const char hiddenCh, const int startIdx = 0) +{ + std::string s = str; + constexpr auto minDelimSize = 2; + constexpr auto minKeepSize = 6; + if (std::count(s.begin(), s.end(), delim) < minDelimSize) { + if (s.size() <= minKeepSize) { + return std::string(s.size(), hiddenCh); + } + auto idx1 = 2; + const auto idx2 = s.size() - 4; + while (idx1++ < idx2) { + s[idx1] = hiddenCh; + } + return s; + } + + std::string::size_type begin = s.find_first_of(delim); + std::string::size_type end = s.find_last_of(delim); + int idx = 0; + while (idx++ < startIdx && begin < end) { + begin = s.find_first_of(delim, begin + 1); + } + while (begin++ != end) { + if (s[begin] != delim) { + s[begin] = hiddenCh; + } + } + return s; +} + +std::string MacAnonymize(const std::string str) +{ + return DataAnonymize(str, ':', '*', 1); +} + +std::string IpAnonymize(const std::string str) +{ + return DataAnonymize(str, '.', '*'); +} + +std::string SsidAnonymize(const std::string str) +{ + if (str.empty()) { + return str; + } + + std::string s = str; + constexpr char hiddenChar = '*'; + constexpr size_t minHiddenSize = 3; + constexpr size_t headKeepSize = 3; + constexpr size_t tailKeepSize = 3; + auto func = [hiddenChar](char& c) { c = hiddenChar; }; + if (s.size() < minHiddenSize) { + std::for_each(s.begin(), s.end(), func); + return s; + } + + if (s.size() < (minHiddenSize + headKeepSize + tailKeepSize)) { + size_t beginIndex = 1; + size_t hiddenSize = s.size() - minHiddenSize + 1; + hiddenSize = hiddenSize > minHiddenSize ? minHiddenSize : hiddenSize; + std::for_each(s.begin() + beginIndex, s.begin() + beginIndex + hiddenSize, func); + return s; + } + std::for_each(s.begin() + headKeepSize, s.begin() + s.size() - tailKeepSize, func); + return s; +} + +static unsigned char ConvertStrChar(char ch) +{ + constexpr int numDiffForHexAlphabet = 10; + if (ch >= '0' && ch <= '9') { + return (ch - '0'); + } + if (ch >= 'A' && ch <= 'F') { + return (ch - 'A' + numDiffForHexAlphabet); + } + if (ch >= 'a' && ch <= 'f') { + return (ch - 'a' + numDiffForHexAlphabet); + } + return 0; +} + +errno_t MacStrToArray(const std::string& strMac, unsigned char mac[WIFI_MAC_LEN]) +{ + constexpr int strMacLen = 18; + char tempArray[strMacLen] = { 0 }; + errno_t ret = memcpy_s(tempArray, strMacLen, strMac.c_str(), strMac.size() + 1); + if (ret != EOK) { + return ret; + } + + int idx = 0; + constexpr int bitWidth = 4; + char *ptr = nullptr; + char *p = strtok_s(tempArray, ":", &ptr); + while (p != nullptr) { + mac[idx++] = (ConvertStrChar(*p) << bitWidth) | ConvertStrChar(*(p + 1)); + p = strtok_s(nullptr, ":", &ptr); + } + return EOK; +} + +static char ConvertArrayChar(unsigned char ch) +{ + constexpr int maxDecNum = 9; + constexpr int numDiffForHexAlphabet = 10; + if (ch <= maxDecNum) { + return '0' + ch; + } + if (ch >= 0xa && ch <= 0xf) { + return ch + 'a' - numDiffForHexAlphabet; + } + return '0'; +} + +std::string MacArrayToStr(const unsigned char mac[WIFI_MAC_LEN]) +{ + constexpr int bitWidth = 4; + constexpr int noColonBit = 5; + std::stringstream ss; + for (int i = 0; i != WIFI_MAC_LEN; ++i) { + ss << ConvertArrayChar(mac[i] >> bitWidth) << ConvertArrayChar(mac[i] & 0xf); + if (i != noColonBit) { + ss << ":"; + } + } + return ss.str(); +} + +bool IsMacArrayEmpty(const unsigned char mac[WIFI_MAC_LEN]) +{ + for (int i = 0; i != WIFI_MAC_LEN; ++i) { + if (mac[i] != 0) { + return false; + } + } + return true; +} + +unsigned int Ip2Number(const std::string& strIp) +{ + std::string::size_type front = 0; + std::string::size_type back = 0; + unsigned int number = 0; + int size = 32; + constexpr int sectionSize = 8; + + std::string ip(strIp + '.'); + while ((back = ip.find_first_of('.', back)) != (std::string::size_type)std::string::npos) { + number |= std::stol(ip.substr(front, back - front).c_str()) << (size -= sectionSize); + front = ++back; + } + return number; +} + +std::string Number2Ip(unsigned int intIp) +{ + constexpr int fourthPartMoveLen = 24; + constexpr int thirdPartMoveLen = 16; + constexpr int secondPartMoveLen = 8; + + std::string ip; + ip.append(std::to_string((intIp & 0xff000000) >> fourthPartMoveLen)); + ip.push_back('.'); + ip.append(std::to_string((intIp & 0x00ff0000) >> thirdPartMoveLen)); + ip.push_back('.'); + ip.append(std::to_string((intIp & 0x0000ff00) >> secondPartMoveLen)); + ip.push_back('.'); + ip.append(std::to_string(intIp & 0x000000ff)); + return ip; +} + +std::vector StrSplit(const std::string& str, const std::string& delim) { + std::regex re(delim); + std::sregex_token_iterator + first{ str.begin(), str.end(), re, -1 }, + last; + return { first, last }; +} + +#ifndef OHOS_ARCH_LITE +sptr GetBundleManager() +{ + sptr systemManager = SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager(); + if (systemManager == nullptr) { + WIFI_LOGE("Get system ability manager failed!"); + return nullptr; + } + return iface_cast(systemManager->GetSystemAbility(BUNDLE_MGR_SERVICE_SYS_ABILITY_ID)); +} + +std::string GetBundleName() +{ + sptr bundleInstance = GetBundleManager(); + if (bundleInstance == nullptr) { + WIFI_LOGE("bundle instance is null!"); + return ""; + } + + std::string bundleName; + int uid = IPCSkeleton::GetCallingUid(); + if (!bundleInstance->GetBundleNameForUid(uid, bundleName)) { + WIFI_LOGE("Get bundle name failed!"); + } + WIFI_LOGI("Get bundle name uid[%{public}d]: %{public}s", uid, bundleName.c_str()); + return bundleName; +} + +bool IsSystemApp() +{ + sptr bundleInstance = GetBundleManager(); + if (bundleInstance == nullptr) { + return false; + } + + int uid = IPCSkeleton::GetCallingUid(); + bool isSysApp = bundleInstance->CheckIsSystemAppByUid(uid); + WIFI_LOGI("Is system App uid[%{public}d]: %{public}d", uid, isSysApp); + return isSysApp; +} + +int GetCallingUid() +{ + return IPCSkeleton::GetCallingUid(); +} + +bool IsForegroundApp(const int uid) +{ + using namespace OHOS::AppExecFwk; + using namespace OHOS::AppExecFwk::Constants; + constexpr int32_t UID_CALLINGUID_TRANSFORM_DIVISOR = 200000; + int32_t userId = static_cast(uid / UID_CALLINGUID_TRANSFORM_DIVISOR); + + auto appMgrClient = std::make_unique(); + appMgrClient->ConnectAppMgrService(); + AppMgrResultCode ret; + std::vector infos; + ret = appMgrClient->GetProcessRunningInfosByUserId(infos, userId); + if (ret != AppMgrResultCode::RESULT_OK) { + WIFI_LOGE("GetProcessRunningInfosByUserId fail, ret = [%{public}d]", ret); + return false; + } + + auto iter = std::find_if(infos.begin(), infos.end(), [&uid](const RunningProcessInfo &rhs) { + return ((rhs.uid_ == uid) && (rhs.state_ == AppProcessState::APP_STATE_FOREGROUND || + rhs.state_ == AppProcessState::APP_STATE_FOCUS)); + }); + if (iter != infos.end()) { + return true; + } + return false; +} + +int FrequencyToChannel(int freq) +{ + WIFI_LOGI("FrequencyToChannel: %{public}d", freq); + int channel = INVALID_FREQ_OR_CHANNEL; + if (freq >= FREQ_2G_MIN && freq <= FREQ_2G_MAX) { + channel = (freq - FREQ_2G_MIN) / CENTER_FREQ_DIFF + CHANNEL_2G_MIN; + } else if (freq == CHANNEL_14_FREQ) { + channel = CHANNEL_14; + } else if (freq >= FREQ_5G_MIN && freq <= FREQ_5G_MAX) { + channel = (freq - FREQ_5G_MIN) / CENTER_FREQ_DIFF + CHANNEL_5G_MIN; + } + return channel; +} + +int ChannelToFrequency(int channel) +{ + WIFI_LOGI("ChannelToFrequency: %{public}d", channel); + if (channel >= MIN_24G_CHANNEL && channel <= MAX_24G_CHANNEL) { + return ((channel - MIN_24G_CHANNEL) * CENTER_FREQ_DIFF + FREQ_CHANNEL_1); + } + if (MIN_5G_CHANNEL <= channel && channel <= MAX_5G_CHANNEL) { + return ((channel - MIN_5G_CHANNEL) * CENTER_FREQ_DIFF + FREQ_CHANNEL_36); + } + return INVALID_FREQ_OR_CHANNEL; +} + +TimeStats::TimeStats(const std::string desc): m_desc(desc) +{ + m_startTime = std::chrono::steady_clock::now(); + WIFI_LOGI("[Time stats][start] %{public}s.", m_desc.c_str()); +} + +TimeStats::~TimeStats() +{ + auto us = std::chrono::duration_cast + (std::chrono::steady_clock::now() - m_startTime).count(); + constexpr int TIME_BASE = 1000; + WIFI_LOGI("[Time stats][end] %{public}s, time cost:%{public}lldus, %{public}lldms, %{public}llds", + m_desc.c_str(), us, us / TIME_BASE, us / TIME_BASE / TIME_BASE); +} +#endif +} // namespace Wifi +} // namespace OHOS diff --git a/wifi/utils/src/wifi_hisysevent.cpp b/wifi/utils/src/wifi_hisysevent.cpp new file mode 100644 index 0000000000000000000000000000000000000000..55eff627f8ca8855f7fc243b9c3061d9dc8582e9 --- /dev/null +++ b/wifi/utils/src/wifi_hisysevent.cpp @@ -0,0 +1,54 @@ +/* + * Copyright (C) 2022 Huawei Device Co., Ltd. + * 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 "wifi_hisysevent.h" +#include "hisysevent.h" +#include "wifi_logger.h" + +namespace OHOS { +namespace Wifi { +DEFINE_WIFILOG_LABEL("WifiHiSysEvent"); + +template +static void WriteEvent(const std::string& eventType, Types... args) +{ + int ret = HiviewDFX::HiSysEvent::Write(HiviewDFX::HiSysEvent::Domain::COMMUNICATION, eventType, + HiviewDFX::HiSysEvent::EventType::STATISTIC, args...); + if (ret != 0) { + WIFI_LOGE("Write event fail: %{public}s", eventType.c_str()); + } +} + +void WriteWifiStateHiSysEvent(const std::string& serviceType, WifiOperType operType) +{ + WriteEvent("WIFI_STATE", "TYPE", serviceType, "OPER_TYPE", static_cast(operType)); +} + +void WriteWifiConnectionHiSysEvent(const WifiConnectionType& type, const std::string& pkgName) +{ + WriteEvent("WIFI_CONNECTION", "TYPE", static_cast(type), "PACKAGE_NAME", pkgName); +} + +void WriteWifiScanHiSysEvent(const int result, const std::string& pkgName) +{ + WriteEvent("WIFI_SCAN", "EXECUTE_RESULT", result, "PACKAGE_NAME", pkgName); +} + +void WriteWifiEventReceivedHiSysEvent(const std::string& eventType, int value) +{ + WriteEvent("WIFI_EVENT_RECEIVED", "EVENT_TYPE", eventType, "VALUE", value); +} +} // namespace Wifi +} // namespace OHOS \ No newline at end of file diff --git a/wifi/wifi.gni b/wifi/wifi.gni new file mode 100644 index 0000000000000000000000000000000000000000..920d16839866e9f7c31ae342375e2ad3588e39a2 --- /dev/null +++ b/wifi/wifi.gni @@ -0,0 +1,27 @@ +# Copyright (c) 2022 Huawei Device Co., Ltd. +# 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. + +ability_runtime_path = "//foundation/ability/ability_runtime" +SUBSYSTEM_DIR = "//foundation/communication" +WIFI_ROOT_DIR = "$SUBSYSTEM_DIR/wifi/wifi" +DHCP_ROOT_DIR = "$SUBSYSTEM_DIR/wifi/dhcp" + +declare_args() { + wifi_feature_with_p2p = true + wifi_feature_with_ap_intf = "wlan" + wifi_feature_with_ap_num = 1 + wifi_feature_with_auth_disable = false + wifi_feature_with_dhcp_disable = false + wifi_feature_with_encryption = false + wifi_feature_is_hdi_supported = false +} diff --git a/wifi/wifi_lite.gni b/wifi/wifi_lite.gni new file mode 100644 index 0000000000000000000000000000000000000000..3dd85109dcc12face87470130396809174d9bf01 --- /dev/null +++ b/wifi/wifi_lite.gni @@ -0,0 +1,29 @@ +# Copyright (c) 2022 Huawei Device Co., Ltd. +# 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. + +ability_runtime_services_path = "//foundation/ability/ability_runtime/services" +ability_runtime_innerkits_path = + "//foundation/ability/ability_runtime/interfaces/inner_api" + +SUBSYSTEM_DIR = "//foundation/communication" +WIFI_ROOT_DIR = "$SUBSYSTEM_DIR/wifi/wifi" +DHCP_ROOT_DIR = "$SUBSYSTEM_DIR/wifi/dhcp" + +declare_args() { + wifi_feature_with_p2p = false + wifi_feature_with_ap_intf = "wlan" + wifi_feature_with_ap_num = 1 + wifi_feature_with_auth_disable = false + wifi_feature_with_dhcp_disable = false + wifi_feature_is_hdi_supported = false +}

接口名

描述

@@ -106,7 +110,7 @@ WLAN基础功能由@ohos.wifi\_native\_js类提供,其接口\(JS接口\)说明

function connectToDevice(config: WifiDeviceConfig): boolean

连接到WLAN网络。

+

通过配置信息连接到WLAN网络。

NA