feat(P2P): add Wi-Fi hid2d feature

Signed-off-by: z00588131 <hw.zhangfeng@huawei.com>
This commit is contained in:
z00588131 2022-01-12 12:10:05 +00:00
parent f7d5adcebd
commit 72ce11c119
146 changed files with 10160 additions and 5158 deletions

98
OAT.xml
View File

@ -1,50 +1,50 @@
<?xml version="1.0" encoding="UTF-8"?>
<!-- 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.
This is the configuration file template for OpenHarmony OSS Audit Tool, please copy it to your project root dir and modify it refer to OpenHarmony/tools_oat/README.
-->
<configuration>
<oatconfig>
<licensefile></licensefile>
<policylist>
<policy name="projectPolicy" desc="">
</policy>
</policylist>
<filefilterlist>
<filefilter name="defaultFilter" desc="Files not to check">
</filefilter>
<filefilter name="defaultPolicyFilter" desc="Filters for compatibilitylicense header policies">
<filteritem type="filename" name="*.cfg" desc="The JSON format does not support comments."/>
</filefilter>
<filefilter name="copyrightPolicyFilter" desc="Filters for copyright header policies">
<filteritem type="filename" name="*.cfg" desc="The JSON format does not support comments."/>
</filefilter>
<filefilter name="licenseFileNamePolicyFilter" desc="Filters for LICENSE file policies">
</filefilter>
<filefilter name="readmeFileNamePolicyFilter" desc="Filters for README file policies">
</filefilter>
<filefilter name="readmeOpenSourcefileNamePolicyFilter" desc="Filters for README.OpenSource file policies">
</filefilter>
<filefilter name="binaryFileTypePolicyFilter" desc="Filters for binary file policies">
<filteritem type="filename" name="*.png" desc="Image for markdown doc"/>
</filefilter>
</filefilterlist>
<licensematcherlist>
</licensematcherlist>
</oatconfig>
<?xml version="1.0" encoding="UTF-8"?>
<!-- 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.
This is the configuration file template for OpenHarmony OSS Audit Tool, please copy it to your project root dir and modify it refer to OpenHarmony/tools_oat/README.
-->
<configuration>
<oatconfig>
<licensefile></licensefile>
<policylist>
<policy name="projectPolicy" desc="">
</policy>
</policylist>
<filefilterlist>
<filefilter name="defaultFilter" desc="Files not to check">
</filefilter>
<filefilter name="defaultPolicyFilter" desc="Filters for compatibilitylicense header policies">
<filteritem type="filename" name="*.cfg" desc="The JSON format does not support comments."/>
</filefilter>
<filefilter name="copyrightPolicyFilter" desc="Filters for copyright header policies">
<filteritem type="filename" name="*.cfg" desc="The JSON format does not support comments."/>
</filefilter>
<filefilter name="licenseFileNamePolicyFilter" desc="Filters for LICENSE file policies">
</filefilter>
<filefilter name="readmeFileNamePolicyFilter" desc="Filters for README file policies">
</filefilter>
<filefilter name="readmeOpenSourcefileNamePolicyFilter" desc="Filters for README.OpenSource file policies">
</filefilter>
<filefilter name="binaryFileTypePolicyFilter" desc="Filters for binary file policies">
<filteritem type="filename" name="*.png" desc="Image for markdown doc"/>
</filefilter>
</filefilterlist>
<licensematcherlist>
</licensematcherlist>
</oatconfig>
</configuration>

View File

@ -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. 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 // 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 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. 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 // HARMONY_OS_LITE_WIFI_STATION_INFO_H
/** @} */

View File

@ -1,273 +1,283 @@
/*
* 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 <b>networkId</b>. \n
*
* @param config Indicates the hotspot configuration to add.
* @param result Indicates the generated <b>networkId</b>. Each <b>networkId</b> 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 <b>networkId</b>.
*
* @param networkId Indicates the <b>networkId</b> 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 <b>networkId</b>. If the config is diabled, it will
* not be auto connected.
*
* @param networkId Indicates the <b>networkId</b> 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 <b>networkId</b>. 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 <b>networkId</b> 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 <b>networkId</b>.
*
* Before calling this function, call {@link AddDeviceConfig} to add a hotspot configuration. \n
*
* @param networkId Indicates the <b>networkId</b> 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 <b>-1</b> 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 <b>networkId</b>. \n
*
* @param config Indicates the hotspot configuration to add.
* @param result Indicates the generated <b>networkId</b>. Each <b>networkId</b> 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 <b>networkId</b>.
*
* @param networkId Indicates the <b>networkId</b> 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 <b>networkId</b>. If the config is diabled, it will
* not be auto connected.
*
* @param networkId Indicates the <b>networkId</b> 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 <b>networkId</b>. 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 <b>networkId</b> 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 <b>networkId</b>.
*
* Before calling this function, call {@link AddDeviceConfig} to add a hotspot configuration. \n
*
* @param networkId Indicates the <b>networkId</b> 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 <b>-1</b> 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(const WifiEvent *event);
#ifdef __cplusplus
}
#endif
#endif // WIFI_DEVICE_C_H
/** @} */

View File

@ -1,233 +1,233 @@
/*
* 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 <b>networkId</b> when the configuration file is unavailable.
*
* Generally, the configuration file is unavailable because the configuration matching the <b>networkId</b> 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 <b>\0</b>. \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 <b>\0</b>. \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 <b>networkId</b> */
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 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 <b>networkId</b> when the configuration file is unavailable.
*
* Generally, the configuration file is unavailable because the configuration matching the <b>networkId</b> 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 <b>\0</b>. \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 <b>\0</b>. \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 <b>networkId</b> */
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
/** @} */

View File

@ -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
/** @} */

View File

@ -1,117 +1,117 @@
/*
* 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 <b>NULL</b>. \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 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT 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 <b>NULL</b>. \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
/** @} */

View File

@ -0,0 +1,257 @@
/*
* 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
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;
/**
* @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 - operate result
*/
WifiErrorCode Hid2dRequestGcIp(const unsigned char gcMac[MAC_LEN], unsigned int ipAddr[IPV4_ARRAY_LEN]);
/**
* @Description Increase(+1) shared link reference counting
*
* @return WifiErrorCode - operate result
*/
WifiErrorCode Hid2dSharedlinkIncrease();
/**
* @Description Decrease(-1) shared link reference counting
*
* @return WifiErrorCode - operate result
*/
WifiErrorCode Hid2dSharedlinkDecrease();
/**
* @Description Create hid2d group, used on the GO side.
*
* @param frequency - frequency
* @param type - frequency type
* @return WifiErrorCode - operate 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 - operate 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 - operate 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 - operate 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 - operate 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 - operate 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 - operate 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 - operate 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 - operate 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();
#ifdef __cplusplus
}
#endif
#endif

View File

@ -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
* <b>0xFFFFFFFF</b> is added, the beacon does not contain the IEs. \n
* The transmit power is added to the <b>ie</b> 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 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
* <b>0xFFFFFFFF</b> is added, the beacon does not contain the IEs. \n
* The transmit power is added to the <b>ie</b> 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_
/** @} */

View File

@ -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 <b>-88</b> (included) to <b>-82</b> (excluded),
* and that for a 5 GHz hotspot ranges from <b>-85</b> (included) to <b>-79</b> (excluded). */
RSSI_LEVEL_1 = 1,
/** Level 2. The RSSI value for a 2.4 GHz hotspot ranges from <b>-82</b> (included) to <b>-75</b> (excluded),
* and that for a 5 GHz hotspot ranges from <b>-79</b> (included) to <b>-72</b> (excluded). */
RSSI_LEVEL_2 = 2,
/** Level 3. The RSSI value for a 2.4 GHz hotspot ranges from <b>-75</b> (included) to <b>-65</b> (excluded),
* and that for a 5 GHz hotspot ranges from <b>-72</b> (included) to <b>-65</b> (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 <b>-65</b>. */
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 <b>-88</b> (included) to <b>-82</b> (excluded),
* and that for a 5 GHz hotspot ranges from <b>-85</b> (included) to <b>-79</b> (excluded). */
RSSI_LEVEL_1 = 1,
/** Level 2. The RSSI value for a 2.4 GHz hotspot ranges from <b>-82</b> (included) to <b>-75</b> (excluded),
* and that for a 5 GHz hotspot ranges from <b>-79</b> (included) to <b>-72</b> (excluded). */
RSSI_LEVEL_2 = 2,
/** Level 3. The RSSI value for a 2.4 GHz hotspot ranges from <b>-75</b> (included) to <b>-65</b> (excluded),
* and that for a 5 GHz hotspot ranges from <b>-72</b> (included) to <b>-65</b> (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 <b>-65</b>. */
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
/** @} */

View File

@ -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 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
/** @} */

View File

@ -0,0 +1,207 @@
/*
* 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 - operate result
*/
WifiErrorCode EnableP2p();
/**
* @Description Disable the P2P mode.
*
* @return WifiErrorCode - operate result
*/
WifiErrorCode DisableP2p();
/**
* @Description Get p2p enable status
*
* @param state - enable status
* @return WifiErrorCode - operate result
*/
WifiErrorCode GetP2pEnableStatus(P2pState* state);
/**
* @Description Start Wi-Fi P2P device search.
*
* @return WifiErrorCode - operate result
*/
WifiErrorCode DiscoverDevices();
/**
* @Description Stop Wi-Fi P2P device search.
*
* @return WifiErrorCode - operate result
*/
WifiErrorCode StopDiscoverDevices();
/**
* @Description Start the search for the Wi-Fi P2P service.
*
* @return WifiErrorCode - operate result
*/
WifiErrorCode DiscoverServices();
/**
* @Description Stop the search for the Wi-Fi P2P service.
*
* @return WifiErrorCode - operate result
*/
WifiErrorCode StopDiscoverServices();
/**
* @Description Enable Wi-Fi P2P listening.
*
* @param period - period
* @param interval - interval
* @return WifiErrorCode - operate result
*/
WifiErrorCode StartP2pListen(int period, int interval);
/**
* @Description Disable Wi-Fi P2P listening.
*
* @return ErrCode - operate result
*/
WifiErrorCode StopP2pListen();
/**
* @Description Creating a P2P Group.
*
* @param config - WifiP2pConfig object
* @return WifiErrorCode - operate result
*/
WifiErrorCode CreateGroup(const WifiP2pConfig* config);
/**
* @Description Remove a P2P Group.
*
* @param config - WifiP2pConfig object
* @return WifiErrorCode - operate result
*/
WifiErrorCode RemoveGroup();
/**
* @Description Delete a p2p Group.
*
* @param group - WifiP2pGroupInfo object
* @return ErrCode - operate result
*/
WifiErrorCode DeleteGroup(const WifiP2pGroupInfo* group);
/**
* @Description P2P connection.
*
* @param config - WifiP2pConfig object
* @return WifiErrorCode - operate result
*/
WifiErrorCode P2pConnect(const WifiP2pConfig* config);
/**
* @Description P2P disconnection.
*
* @return WifiErrorCode - operate result
*/
WifiErrorCode P2pDisConnect();
/**
* @Description Get the Current Group object.
*
* @param groupInfo - the WifiP2pGroupInfo object
* @return WifiErrorCode - operate result
*/
WifiErrorCode GetCurrentGroup(WifiP2pGroupInfo* groupInfo);
/**
* @Description Obtains the P2P connection status.
*
* @param status - the P2P connection status
* @return WifiErrorCode - operate 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 - operate result
*/
WifiErrorCode QueryP2pDevices(WifiP2pDevice* clientDevices, int size, int* retSize);
/**
* @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 - operate result
*/
WifiErrorCode QueryP2pGroups(WifiP2pGroupInfo* groupInfo, int size);
/**
* @Description register p2p state changed event
*
* @param callback - callback function
* @return ErrCode - operate result
*/
WifiErrorCode RegisterP2pStateChangedCallback(const P2pStateChangedCallback callback);
/**
* @Description register p2p persistent group change event
*
* @param callback - callback function
* @return ErrCode - operate result
*/
WifiErrorCode RegisterP2pPersistentGroupsChangedCallback(const P2pPersistentGroupsChangedCallback callback);
/**
* @Description register p2p connection change event
*
* @param callback - callback function
* @return ErrCode - operate result
*/
WifiErrorCode RegisterP2pConnectionChangedCallback(const P2pConnectionChangedCallback callback);
/**
* @Description register p2p peers change event
*
* @param callback - callback function
* @return ErrCode - operate result
*/
WifiErrorCode RegisterP2pPeersChangedCallback(const P2pPeersChangedCallback callback);
#ifdef __cplusplus
}
#endif
#endif

View File

@ -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 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

View File

@ -1,67 +1,67 @@
/*
* 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 "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
/** @} */

File diff suppressed because it is too large Load Diff

View File

@ -1,103 +1,103 @@
/*
* 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 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 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 */
};
class ScanInfoAsyncContext : public AsyncContext {
public:
std::vector<WifiScanInfo> vecScanInfos;
ScanInfoAsyncContext(napi_env env, napi_async_work work = nullptr, napi_deferred deferred = nullptr) :
AsyncContext(env, work, deferred){}
ScanInfoAsyncContext() = delete;
virtual ~ScanInfoAsyncContext(){}
};
class AddDeviceConfigContext : public AsyncContext {
public:
WifiDeviceConfig *config;
int addResult;
AddDeviceConfigContext(napi_env env, napi_async_work work = nullptr, napi_deferred deferred = nullptr) :
AsyncContext(env, work, deferred){
config = nullptr;
addResult = -1;
}
AddDeviceConfigContext() = delete;
virtual ~AddDeviceConfigContext(){}
};
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
/*
* 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 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 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 */
};
class ScanInfoAsyncContext : public AsyncContext {
public:
std::vector<WifiScanInfo> vecScanInfos;
ScanInfoAsyncContext(napi_env env, napi_async_work work = nullptr, napi_deferred deferred = nullptr) :
AsyncContext(env, work, deferred){}
ScanInfoAsyncContext() = delete;
virtual ~ScanInfoAsyncContext(){}
};
class AddDeviceConfigContext : public AsyncContext {
public:
WifiDeviceConfig *config;
int addResult;
AddDeviceConfigContext(napi_env env, napi_async_work work = nullptr, napi_deferred deferred = nullptr) :
AsyncContext(env, work, deferred){
config = nullptr;
addResult = -1;
}
AddDeviceConfigContext() = delete;
virtual ~AddDeviceConfigContext(){}
};
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

View File

@ -1,142 +1,142 @@
/*
* 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 {
#ifndef ENABLE_NAPI_COMPATIBLE
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("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("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("enableHotspot", EnableHotspot),
DECLARE_NAPI_FUNCTION("disableHotspot", DisableHotspot),
DECLARE_NAPI_FUNCTION("setHotspotConfig", SetHotspotConfig),
DECLARE_NAPI_FUNCTION("getHotspotConfig", GetHotspotConfig),
DECLARE_NAPI_FUNCTION("getStations", GetStations),
};
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",
.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
/*
* 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 {
#ifndef ENABLE_NAPI_COMPATIBLE
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("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("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("enableHotspot", EnableHotspot),
DECLARE_NAPI_FUNCTION("disableHotspot", DisableHotspot),
DECLARE_NAPI_FUNCTION("setHotspotConfig", SetHotspotConfig),
DECLARE_NAPI_FUNCTION("getHotspotConfig", GetHotspotConfig),
DECLARE_NAPI_FUNCTION("getStations", GetStations),
};
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",
.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

View File

@ -1,431 +1,431 @@
/*
* 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 <shared_mutex>
#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_EVENT_TYPE_SCAN_STATE = "wifiScanStateChange";
const std::string WIFI_EVENT_TYPE_RSSI_STATE = "wifiRssiChange";
const std::string WIFI_EVENT_TYPE_HOTSPOT_STATE = "hotspotStateChange";
const std::string WIFI_EVENT_TYPE_AP_STA_JOIN = "hotspotStaJoin";
const std::string WIFI_EVENT_TYPE_AP_STA_LEAVE = "hotspotStaLeave";
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";
const std::string WIFI_USUAL_EVENT_SCAN_STATE = "usual.event.wifi.SCAN_STATE";
const std::string WIFI_USUAL_EVENT_RSSI_STATE = "usual.event.wifi.RSSI_VALUE";
const std::string WIFI_USUAL_EVENT_HOTSPOT_STATE = "usual.event.wifi.HOTSPOT_STATE";
const std::string WIFI_USUAL_EVENT_AP_STA_JOIN = "usual.event.wifi.WIFI_HS_STA_JOIN";
const std::string WIFI_USUAL_EVENT_AP_STA_LEAVE = "usual.event.wifi.WIFI_HS_STA_LEAVE";
std::shared_mutex g_regInfoMutex;
static std::map<std::string, EventRegisterInfo> g_eventRegisterInfo;
static std::map<std::string, std::string> g_mapEventTypeToUsualEvent = {
{ WIFI_EVENT_TYPE_POWER_STATE, WIFI_USUAL_EVENT_POWER_STATE },
{ WIFI_EVENT_TYPE_CONN_STATE, WIFI_USUAL_EVENT_CONN_STATE },
{ WIFI_EVENT_TYPE_SCAN_STATE, WIFI_USUAL_EVENT_SCAN_STATE },
{ WIFI_EVENT_TYPE_RSSI_STATE, WIFI_USUAL_EVENT_RSSI_STATE },
{ WIFI_EVENT_TYPE_HOTSPOT_STATE, WIFI_USUAL_EVENT_HOTSPOT_STATE },
};
static std::map<std::string, UserDefinedEventProcessFunc> g_mapUserDefinedEventProcessFunc = {};
class EventRegisterInfo {
public:
explicit EventRegisterInfo(EventManager* context) : m_context(context) {
}
EventRegisterInfo() {
}
virtual ~EventRegisterInfo() {
}
std::set<napi_ref>& GetHandlersCb() {
return m_handlersCb;
}
void SetSubscriber(std::shared_ptr<WifiEventSubscriber>& subscriber) {
m_subscriber = subscriber;
}
std::shared_ptr<WifiEventSubscriber> GetSubscriber() {
return m_subscriber;
}
void SetContext(EventManager* context) {
m_context = context;
}
EventManager* GetContext() {
return m_context;
}
private:
std::set<napi_ref> m_handlersCb;
std::shared_ptr<WifiEventSubscriber> 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<std::string, std::string>::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("Received event: %{public}s, value: %{public}d", event.c_str(), code);
std::string type;
if (!GetEventTypeByUsualEvent(event, type)) {
WIFI_LOGI("Received event: %{public}s is ignored", event.c_str());
return;
}
EventManager *manager = nullptr;
{
std::shared_lock<std::shared_mutex> guard(g_regInfoMutex);
std::map<std::string, EventRegisterInfo>::iterator it = g_eventRegisterInfo.find(type);
if (it == g_eventRegisterInfo.end()) {
WIFI_LOGE("No register info for event: %{public}s", type.c_str());
return;
}
manager = it->second.GetContext();
if (manager == nullptr) {
WIFI_LOGE("Context is null");
return;
}
}
std::map<std::string, UserDefinedEventProcessFunc>::iterator iter = g_mapUserDefinedEventProcessFunc.find(type);
if (iter != g_mapUserDefinedEventProcessFunc.end()) {
WIFI_LOGI("Has user-defined func for event: %{public}s", type.c_str());
iter->second(manager->GetEnv(), type, data);
} else {
WIFI_LOGI("Use default policy to process event: %{public}s", type.c_str());
WifiCommonEvent commonEvent(manager->GetEnv(), type, code);
if (!manager->Send(commonEvent)) {
WIFI_LOGE("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("Report event: %{public}s", event.GetName().c_str());
napi_handle_scope scope = nullptr;
napi_open_handle_scope(m_env, &scope);
std::shared_lock<std::shared_mutex> guard(g_regInfoMutex);
std::map<std::string, EventRegisterInfo>::iterator it = g_eventRegisterInfo.find(event.GetName());
if (it == g_eventRegisterInfo.end()) {
WIFI_LOGE("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("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<WifiEventSubscriber> subscriber = std::make_shared<WifiEventSubscriber>(subscriberInfo);
if (subscriber == nullptr) {
WIFI_LOGE("subscriber is null.");
return false;
}
WIFI_LOGI("Subscribe event -> %{public}s", event.c_str());
bool result = CommonEventManager::SubscribeCommonEvent(subscriber);
if (result) {
g_eventRegisterInfo[m_eventType].SetSubscriber(subscriber);
} else {
WIFI_LOGE("Subscribe service event error: %{public}s", event.c_str());
}
return result;
}
bool EventManager::UnsubscribeServiceEvent(const std::string& event) {
bool result = CommonEventManager::UnSubscribeCommonEvent(g_eventRegisterInfo[m_eventType].GetSubscriber());
if (!result) {
WIFI_LOGE("Unsubscribe service event error: %{public}s", event.c_str());
}
return result;
}
bool EventManager::SubscribeEvent(const std::string& name, napi_value handler) {
WIFI_LOGI("Subscribe event: %{public}s", name.c_str());
if (!IsEventTypeExist(name)) {
WIFI_LOGE("Subscribe event is not a valid event: %{public}s", name.c_str());
return false;
}
SetEventType(name);
std::unique_lock<std::shared_mutex> guard(g_regInfoMutex);
std::map<std::string, EventRegisterInfo>::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("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("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<napi_ref>& 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<napi_ref>& 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("Unsubscribe event: %{public}s", name.c_str());
if (!IsEventTypeExist(name)) {
WIFI_LOGE("Unsubscribe event is not a valid event: %{public}s", name.c_str());
return false;
}
bool isNeedUnsubscribe = false;
std::unique_lock<std::shared_mutex> guard(g_regInfoMutex);
std::map<std::string, EventRegisterInfo>::iterator it = g_eventRegisterInfo.find(name);
if (it == g_eventRegisterInfo.end()) {
WIFI_LOGE("Unsubscribe event is not subscribe: %{public}s", name.c_str());
return false;
}
if (handler != nullptr) {
DeleteHanderRef(it->second.GetHandlersCb(), handler);
} else {
WIFI_LOGW("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("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) {
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");
EventManager *manager = nullptr;
napi_status status = napi_unwrap(env, thisVar, (void**)&manager);
if (status == napi_ok && manager != nullptr) {
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("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) {
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");
}
EventManager *manager = nullptr;
napi_status status = napi_unwrap(env, thisVar, (void**)&manager);
if (status == napi_ok && manager != nullptr) {
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("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) {
WIFI_LOGI("Event listener constructor");
napi_value thisVar = nullptr;
void* data = nullptr;
napi_get_cb_info(env, cbinfo, nullptr, nullptr, &thisVar, &data);
EventManager *eventManager = new EventManager(env, thisVar);
if (eventManager == nullptr) {
WIFI_LOGE("Init listener constructor failed");
return nullptr;
}
napi_wrap(
env, thisVar, eventManager,
[](napi_env env, void* data, void* hint) {
WIFI_LOGI("Event listener destructor");
EventManager *eventManager = (EventManager *)data;
delete eventManager;
eventManager = nullptr;
},
nullptr, nullptr);
return thisVar;
}
} // 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_napi_event.h"
#include <shared_mutex>
#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_EVENT_TYPE_SCAN_STATE = "wifiScanStateChange";
const std::string WIFI_EVENT_TYPE_RSSI_STATE = "wifiRssiChange";
const std::string WIFI_EVENT_TYPE_HOTSPOT_STATE = "hotspotStateChange";
const std::string WIFI_EVENT_TYPE_AP_STA_JOIN = "hotspotStaJoin";
const std::string WIFI_EVENT_TYPE_AP_STA_LEAVE = "hotspotStaLeave";
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";
const std::string WIFI_USUAL_EVENT_SCAN_STATE = "usual.event.wifi.SCAN_STATE";
const std::string WIFI_USUAL_EVENT_RSSI_STATE = "usual.event.wifi.RSSI_VALUE";
const std::string WIFI_USUAL_EVENT_HOTSPOT_STATE = "usual.event.wifi.HOTSPOT_STATE";
const std::string WIFI_USUAL_EVENT_AP_STA_JOIN = "usual.event.wifi.WIFI_HS_STA_JOIN";
const std::string WIFI_USUAL_EVENT_AP_STA_LEAVE = "usual.event.wifi.WIFI_HS_STA_LEAVE";
std::shared_mutex g_regInfoMutex;
static std::map<std::string, EventRegisterInfo> g_eventRegisterInfo;
static std::map<std::string, std::string> g_mapEventTypeToUsualEvent = {
{ WIFI_EVENT_TYPE_POWER_STATE, WIFI_USUAL_EVENT_POWER_STATE },
{ WIFI_EVENT_TYPE_CONN_STATE, WIFI_USUAL_EVENT_CONN_STATE },
{ WIFI_EVENT_TYPE_SCAN_STATE, WIFI_USUAL_EVENT_SCAN_STATE },
{ WIFI_EVENT_TYPE_RSSI_STATE, WIFI_USUAL_EVENT_RSSI_STATE },
{ WIFI_EVENT_TYPE_HOTSPOT_STATE, WIFI_USUAL_EVENT_HOTSPOT_STATE },
};
static std::map<std::string, UserDefinedEventProcessFunc> g_mapUserDefinedEventProcessFunc = {};
class EventRegisterInfo {
public:
explicit EventRegisterInfo(EventManager* context) : m_context(context) {
}
EventRegisterInfo() {
}
virtual ~EventRegisterInfo() {
}
std::set<napi_ref>& GetHandlersCb() {
return m_handlersCb;
}
void SetSubscriber(std::shared_ptr<WifiEventSubscriber>& subscriber) {
m_subscriber = subscriber;
}
std::shared_ptr<WifiEventSubscriber> GetSubscriber() {
return m_subscriber;
}
void SetContext(EventManager* context) {
m_context = context;
}
EventManager* GetContext() {
return m_context;
}
private:
std::set<napi_ref> m_handlersCb;
std::shared_ptr<WifiEventSubscriber> 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<std::string, std::string>::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("Received event: %{public}s, value: %{public}d", event.c_str(), code);
std::string type;
if (!GetEventTypeByUsualEvent(event, type)) {
WIFI_LOGI("Received event: %{public}s is ignored", event.c_str());
return;
}
EventManager *manager = nullptr;
{
std::shared_lock<std::shared_mutex> guard(g_regInfoMutex);
std::map<std::string, EventRegisterInfo>::iterator it = g_eventRegisterInfo.find(type);
if (it == g_eventRegisterInfo.end()) {
WIFI_LOGE("No register info for event: %{public}s", type.c_str());
return;
}
manager = it->second.GetContext();
if (manager == nullptr) {
WIFI_LOGE("Context is null");
return;
}
}
std::map<std::string, UserDefinedEventProcessFunc>::iterator iter = g_mapUserDefinedEventProcessFunc.find(type);
if (iter != g_mapUserDefinedEventProcessFunc.end()) {
WIFI_LOGI("Has user-defined func for event: %{public}s", type.c_str());
iter->second(manager->GetEnv(), type, data);
} else {
WIFI_LOGI("Use default policy to process event: %{public}s", type.c_str());
WifiCommonEvent commonEvent(manager->GetEnv(), type, code);
if (!manager->Send(commonEvent)) {
WIFI_LOGE("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("Report event: %{public}s", event.GetName().c_str());
napi_handle_scope scope = nullptr;
napi_open_handle_scope(m_env, &scope);
std::shared_lock<std::shared_mutex> guard(g_regInfoMutex);
std::map<std::string, EventRegisterInfo>::iterator it = g_eventRegisterInfo.find(event.GetName());
if (it == g_eventRegisterInfo.end()) {
WIFI_LOGE("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("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<WifiEventSubscriber> subscriber = std::make_shared<WifiEventSubscriber>(subscriberInfo);
if (subscriber == nullptr) {
WIFI_LOGE("subscriber is null.");
return false;
}
WIFI_LOGI("Subscribe event -> %{public}s", event.c_str());
bool result = CommonEventManager::SubscribeCommonEvent(subscriber);
if (result) {
g_eventRegisterInfo[m_eventType].SetSubscriber(subscriber);
} else {
WIFI_LOGE("Subscribe service event error: %{public}s", event.c_str());
}
return result;
}
bool EventManager::UnsubscribeServiceEvent(const std::string& event) {
bool result = CommonEventManager::UnSubscribeCommonEvent(g_eventRegisterInfo[m_eventType].GetSubscriber());
if (!result) {
WIFI_LOGE("Unsubscribe service event error: %{public}s", event.c_str());
}
return result;
}
bool EventManager::SubscribeEvent(const std::string& name, napi_value handler) {
WIFI_LOGI("Subscribe event: %{public}s", name.c_str());
if (!IsEventTypeExist(name)) {
WIFI_LOGE("Subscribe event is not a valid event: %{public}s", name.c_str());
return false;
}
SetEventType(name);
std::unique_lock<std::shared_mutex> guard(g_regInfoMutex);
std::map<std::string, EventRegisterInfo>::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("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("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<napi_ref>& 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<napi_ref>& 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("Unsubscribe event: %{public}s", name.c_str());
if (!IsEventTypeExist(name)) {
WIFI_LOGE("Unsubscribe event is not a valid event: %{public}s", name.c_str());
return false;
}
bool isNeedUnsubscribe = false;
std::unique_lock<std::shared_mutex> guard(g_regInfoMutex);
std::map<std::string, EventRegisterInfo>::iterator it = g_eventRegisterInfo.find(name);
if (it == g_eventRegisterInfo.end()) {
WIFI_LOGE("Unsubscribe event is not subscribe: %{public}s", name.c_str());
return false;
}
if (handler != nullptr) {
DeleteHanderRef(it->second.GetHandlersCb(), handler);
} else {
WIFI_LOGW("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("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) {
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");
EventManager *manager = nullptr;
napi_status status = napi_unwrap(env, thisVar, (void**)&manager);
if (status == napi_ok && manager != nullptr) {
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("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) {
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");
}
EventManager *manager = nullptr;
napi_status status = napi_unwrap(env, thisVar, (void**)&manager);
if (status == napi_ok && manager != nullptr) {
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("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) {
WIFI_LOGI("Event listener constructor");
napi_value thisVar = nullptr;
void* data = nullptr;
napi_get_cb_info(env, cbinfo, nullptr, nullptr, &thisVar, &data);
EventManager *eventManager = new EventManager(env, thisVar);
if (eventManager == nullptr) {
WIFI_LOGE("Init listener constructor failed");
return nullptr;
}
napi_wrap(
env, thisVar, eventManager,
[](napi_env env, void* data, void* hint) {
WIFI_LOGI("Event listener destructor");
EventManager *eventManager = (EventManager *)data;
delete eventManager;
eventManager = nullptr;
},
nullptr, nullptr);
return thisVar;
}
} // namespace Wifi
} // namespace OHOS

View File

@ -1,106 +1,106 @@
/*
* 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 <string>
#include <set>
#include <map>
#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<napi_ref>& setRefs, napi_value handler);
void DeleteAllHanderRef(std::set<napi_ref>& 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
/*
* 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 <string>
#include <set>
#include <map>
#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<napi_ref>& setRefs, napi_value handler);
void DeleteAllHanderRef(std::set<napi_ref>& 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

View File

@ -1,195 +1,195 @@
/*
* 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_hotspot.h"
#include "wifi_logger.h"
#include <vector>
namespace OHOS {
namespace Wifi {
DEFINE_WIFILOG_LABEL("WifiNAPIHotspot");
std::unique_ptr<WifiHotspot> wifiHotspotPtr = WifiHotspot::GetInstance(WIFI_HOTSPOT_ABILITY_ID);
std::map<SecTypeJs, KeyMgmt> 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;
NAPI_ASSERT(env, wifiHotspotPtr != nullptr, "Wifi hotspot instance is null.");
ErrCode ret = wifiHotspotPtr->EnableHotspot();
if (ret != WIFI_OPT_SUCCESS) {
WIFI_LOGE("Enable hotspot error: %{public}d", ret);
}
napi_value result;
napi_get_boolean(env, ret == WIFI_OPT_SUCCESS, &result);
return result;
}
napi_value DisableHotspot(napi_env env, napi_callback_info info)
{
TRACE_FUNC_CALL;
NAPI_ASSERT(env, wifiHotspotPtr != nullptr, "Wifi hotspot instance is null.");
ErrCode ret = wifiHotspotPtr->DisableHotspot();
if (ret != WIFI_OPT_SUCCESS) {
WIFI_LOGE("Disable hotspot error: %{public}d", ret);
}
napi_value result;
napi_get_boolean(env, ret == WIFI_OPT_SUCCESS, &result);
return result;
}
napi_value IsHotspotActive(napi_env env, napi_callback_info info)
{
NAPI_ASSERT(env, wifiHotspotPtr != nullptr, "Wifi hotspot instance is null.");
napi_value result;
napi_get_boolean(env, wifiHotspotPtr->IsHotspotActive(), &result);
return result;
}
static KeyMgmt GetKeyMgmtFromJsSecurityType(int secType)
{
std::map<SecTypeJs, KeyMgmt>::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<int>(each.first);
}
}
return static_cast<int>(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", 33, 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
value = 0;
JsObjectToString(env, object, "preSharedKey", 64, 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);
NAPI_ASSERT(env, valueType == napi_object, "Wrong argument type. Object expected.");
NAPI_ASSERT(env, wifiHotspotPtr != nullptr, "Wifi hotspot instance is null.");
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);
}
}
napi_value result;
napi_get_boolean(env, ret == WIFI_OPT_SUCCESS, &result);
return result;
}
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<int>(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;
NAPI_ASSERT(env, wifiHotspotPtr != nullptr, "Wifi hotspot instance is null.");
HotspotConfig config;
ErrCode ret = wifiHotspotPtr->GetHotspotConfig(config);
if (ret != WIFI_OPT_SUCCESS) {
WIFI_LOGE("Get hotspot config error: %{public}d", ret);
}
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>& 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;
NAPI_ASSERT(env, wifiHotspotPtr != nullptr, "Wifi hotspot instance is null.");
std::vector<StationInfo> 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());
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;
}
} // 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_napi_hotspot.h"
#include "wifi_hotspot.h"
#include "wifi_logger.h"
#include <vector>
namespace OHOS {
namespace Wifi {
DEFINE_WIFILOG_LABEL("WifiNAPIHotspot");
std::unique_ptr<WifiHotspot> wifiHotspotPtr = WifiHotspot::GetInstance(WIFI_HOTSPOT_ABILITY_ID);
std::map<SecTypeJs, KeyMgmt> 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;
NAPI_ASSERT(env, wifiHotspotPtr != nullptr, "Wifi hotspot instance is null.");
ErrCode ret = wifiHotspotPtr->EnableHotspot();
if (ret != WIFI_OPT_SUCCESS) {
WIFI_LOGE("Enable hotspot error: %{public}d", ret);
}
napi_value result;
napi_get_boolean(env, ret == WIFI_OPT_SUCCESS, &result);
return result;
}
napi_value DisableHotspot(napi_env env, napi_callback_info info)
{
TRACE_FUNC_CALL;
NAPI_ASSERT(env, wifiHotspotPtr != nullptr, "Wifi hotspot instance is null.");
ErrCode ret = wifiHotspotPtr->DisableHotspot();
if (ret != WIFI_OPT_SUCCESS) {
WIFI_LOGE("Disable hotspot error: %{public}d", ret);
}
napi_value result;
napi_get_boolean(env, ret == WIFI_OPT_SUCCESS, &result);
return result;
}
napi_value IsHotspotActive(napi_env env, napi_callback_info info)
{
NAPI_ASSERT(env, wifiHotspotPtr != nullptr, "Wifi hotspot instance is null.");
napi_value result;
napi_get_boolean(env, wifiHotspotPtr->IsHotspotActive(), &result);
return result;
}
static KeyMgmt GetKeyMgmtFromJsSecurityType(int secType)
{
std::map<SecTypeJs, KeyMgmt>::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<int>(each.first);
}
}
return static_cast<int>(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", 33, 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
value = 0;
JsObjectToString(env, object, "preSharedKey", 64, 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);
NAPI_ASSERT(env, valueType == napi_object, "Wrong argument type. Object expected.");
NAPI_ASSERT(env, wifiHotspotPtr != nullptr, "Wifi hotspot instance is null.");
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);
}
}
napi_value result;
napi_get_boolean(env, ret == WIFI_OPT_SUCCESS, &result);
return result;
}
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<int>(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;
NAPI_ASSERT(env, wifiHotspotPtr != nullptr, "Wifi hotspot instance is null.");
HotspotConfig config;
ErrCode ret = wifiHotspotPtr->GetHotspotConfig(config);
if (ret != WIFI_OPT_SUCCESS) {
WIFI_LOGE("Get hotspot config error: %{public}d", ret);
}
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>& 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;
NAPI_ASSERT(env, wifiHotspotPtr != nullptr, "Wifi hotspot instance is null.");
std::vector<StationInfo> 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());
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;
}
} // namespace Wifi
} // namespace OHOS

View File

@ -1,32 +1,32 @@
/*
* 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 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);
} // 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_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 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);
} // namespace Wifi
} // namespace OHOS
#endif

View File

@ -1,23 +1,23 @@
/*
* 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) 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

View File

@ -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) 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

View File

@ -1,314 +1,314 @@
/*
* 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");
TraceFuncCall::TraceFuncCall(std::string funcName): m_funcName(funcName)
{
if (m_isTrace) {
m_startTime = std::chrono::steady_clock::now();
WIFI_LOGD("Call func: %{public}s (start)", m_funcName.c_str());
}
}
TraceFuncCall::~TraceFuncCall()
{
if (m_isTrace) {
auto us = std::chrono::duration_cast<std::chrono::microseconds>
(std::chrono::steady_clock::now() - m_startTime).count();
constexpr int usForPerMs = 1000;
WIFI_LOGD("Call 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 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)
{
napi_value value;
napi_status status = napi_create_string_utf8(env, str, NAPI_AUTO_LENGTH, &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;
napi_value undefine;
napi_get_undefined(env, &undefine);
napi_value callback;
context->completeFunc(data);
if (context->isSuccess) {
napi_get_reference_value(env, context->callback[0], &callback);
napi_call_function(env, nullptr, callback, 1, &context->result, &undefine);
} else {
if (context->callback[1]) {
napi_get_reference_value(env, context->callback[1], &callback);
napi_call_function(env, nullptr, callback, 1, &context->result, &undefine);
} else {
WIFI_LOGE("Get scan info callback func is null");
}
}
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);
if (context->isSuccess) {
napi_resolve_deferred(context->env, context->deferred, context->result);
} else {
napi_reject_deferred(context->env, context->deferred, context->result);
}
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
/*
* 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");
TraceFuncCall::TraceFuncCall(std::string funcName): m_funcName(funcName)
{
if (m_isTrace) {
m_startTime = std::chrono::steady_clock::now();
WIFI_LOGD("Call func: %{public}s (start)", m_funcName.c_str());
}
}
TraceFuncCall::~TraceFuncCall()
{
if (m_isTrace) {
auto us = std::chrono::duration_cast<std::chrono::microseconds>
(std::chrono::steady_clock::now() - m_startTime).count();
constexpr int usForPerMs = 1000;
WIFI_LOGD("Call 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 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)
{
napi_value value;
napi_status status = napi_create_string_utf8(env, str, NAPI_AUTO_LENGTH, &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;
napi_value undefine;
napi_get_undefined(env, &undefine);
napi_value callback;
context->completeFunc(data);
if (context->isSuccess) {
napi_get_reference_value(env, context->callback[0], &callback);
napi_call_function(env, nullptr, callback, 1, &context->result, &undefine);
} else {
if (context->callback[1]) {
napi_get_reference_value(env, context->callback[1], &callback);
napi_call_function(env, nullptr, callback, 1, &context->result, &undefine);
} else {
WIFI_LOGE("Get scan info callback func is null");
}
}
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);
if (context->isSuccess) {
napi_resolve_deferred(context->env, context->deferred, context->result);
} else {
napi_reject_deferred(context->env, context->deferred, context->result);
}
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

View File

@ -1,96 +1,96 @@
/*
* 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 <string>
#include <chrono>
#include "napi/native_api.h"
#include "napi/native_node_api.h"
namespace OHOS {
namespace Wifi {
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)
class AsyncContext {
public:
napi_env env;
napi_async_work work;
napi_deferred deferred;
napi_ref callback[2] = { 0 };
std::function<void(void*)> executeFunc;
std::function<void(void*)> completeFunc;
napi_value resourceName;
napi_value result;
bool isSuccess;
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;
isSuccess = false;
}
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 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);
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) */
};
} // 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_NAPI_UTILS_H_
#define WIFI_NAPI_UTILS_H_
#include <string>
#include <chrono>
#include "napi/native_api.h"
#include "napi/native_node_api.h"
namespace OHOS {
namespace Wifi {
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)
class AsyncContext {
public:
napi_env env;
napi_async_work work;
napi_deferred deferred;
napi_ref callback[2] = { 0 };
std::function<void(void*)> executeFunc;
std::function<void(void*)> completeFunc;
napi_value resourceName;
napi_value result;
bool isSuccess;
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;
isSuccess = false;
}
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 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);
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) */
};
} // namespace Wifi
} // namespace OHOS
#endif

View File

@ -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
@ -29,6 +29,7 @@ config("wifi_sdk_header") {
"//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",
"//foundation/communication/wifi/services/wifi_standard/wifi_framework/dhcp_manage/mgr_service/include",
]
}
@ -101,6 +102,7 @@ ohos_source_set("wifi_p2p_proxy_impl") {
external_deps = [ "ipc:ipc_core" ]
}
ohos_shared_library("wifi_sdk") {
install_enable = true
@ -112,10 +114,14 @@ ohos_shared_library("wifi_sdk") {
sources = [
"c_adapter/wifi_c_device.cpp",
"c_adapter/wifi_c_event.cpp",
"c_adapter/wifi_c_hid2d.cpp",
"c_adapter/wifi_c_hotspot.cpp",
"c_adapter/wifi_c_p2p.cpp",
"c_adapter/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_p2p.cpp",

View File

@ -1,332 +1,339 @@
/*
* 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 "wifi_common_util.h"
DEFINE_WIFILOG_LABEL("WifiCDevice");
static std::map<WifiSecurityType, std::string> 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<OHOS::Wifi::WifiDevice> wifiDevicePtr = OHOS::Wifi::WifiDevice::GetInstance(WIFI_DEVICE_ABILITY_ID);
std::unique_ptr<OHOS::Wifi::WifiScan> 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<OHOS::Wifi::WifiScanInfo> 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<int>(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<WifiSecurityType, std::string>::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<int>(each.first);
}
}
return static_cast<int>(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<OHOS::Wifi::WifiDeviceConfig> 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 "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 "wifi_common_util.h"
DEFINE_WIFILOG_LABEL("WifiCDevice");
static std::map<WifiSecurityType, std::string> 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<OHOS::Wifi::WifiDevice> wifiDevicePtr = OHOS::Wifi::WifiDevice::GetInstance(WIFI_DEVICE_ABILITY_ID);
std::unique_ptr<OHOS::Wifi::WifiScan> 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<OHOS::Wifi::WifiScanInfo> 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<int>(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<WifiSecurityType, std::string>::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<int>(each.first);
}
}
return static_cast<int>(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<OHOS::Wifi::WifiDeviceConfig> 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;
}
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;
}

View File

@ -1,290 +1,290 @@
/*
* 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 <set>
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<ConnectionChangeCb> 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<ScanStateChangeCb> 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<HotspotStateChangeCb> 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<HotspotJoinCb> 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<HotspotLeaveCb> 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<WifiEventSubscriber> subscriber = std::make_shared<WifiEventSubscriber>(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<std::string, std::shared_ptr<WifiEventSubscriber>>::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<ConnectionChangeCb> m_setConnectionChangeCb;
static std::set<ScanStateChangeCb> m_setScanStateChangeCb;
static std::set<HotspotStateChangeCb> m_setHotspotChangeCb;
static std::set<HotspotJoinCb> m_setHotspotJoinCb;
static std::set<HotspotLeaveCb> m_setHotspotLeaveCb;
std::map<std::string, std::shared_ptr<WifiEventSubscriber> > m_mapEventSubscriber;
};
std::set<ConnectionChangeCb> EventManager::m_setConnectionChangeCb;
std::set<ScanStateChangeCb> EventManager::m_setScanStateChangeCb;
std::set<HotspotStateChangeCb> EventManager::m_setHotspotChangeCb;
std::set<HotspotJoinCb> EventManager::m_setHotspotJoinCb;
std::set<HotspotLeaveCb> 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;
}
/*
* 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 <set>
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<ConnectionChangeCb> 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<ScanStateChangeCb> 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<HotspotStateChangeCb> 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<HotspotJoinCb> 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<HotspotLeaveCb> 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<WifiEventSubscriber> subscriber = std::make_shared<WifiEventSubscriber>(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<std::string, std::shared_ptr<WifiEventSubscriber>>::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<ConnectionChangeCb> m_setConnectionChangeCb;
static std::set<ScanStateChangeCb> m_setScanStateChangeCb;
static std::set<HotspotStateChangeCb> m_setHotspotChangeCb;
static std::set<HotspotJoinCb> m_setHotspotJoinCb;
static std::set<HotspotLeaveCb> m_setHotspotLeaveCb;
std::map<std::string, std::shared_ptr<WifiEventSubscriber> > m_mapEventSubscriber;
};
std::set<ConnectionChangeCb> EventManager::m_setConnectionChangeCb;
std::set<ScanStateChangeCb> EventManager::m_setScanStateChangeCb;
std::set<HotspotStateChangeCb> EventManager::m_setHotspotChangeCb;
std::set<HotspotJoinCb> EventManager::m_setHotspotJoinCb;
std::set<HotspotLeaveCb> 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;
}

View File

@ -0,0 +1,197 @@
/*
* 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 "native_c/wifi_hid2d.h"
#include "native_cpp/wifi_standard/include/wifi_hid2d.h"
#include "define.h"
#include "wifi_logger.h"
#include "wifi_c_utils.h"
#include "wifi_common_util.h"
#include "native_c/wifi_device.h"
DEFINE_WIFILOG_LABEL("WifiCHid2d");
std::unique_ptr<OHOS::Wifi::Hid2d> 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()
{
CHECK_PTR_RETURN(wifiHid2dPtr, ERROR_WIFI_NOT_AVAILABLE);
return GetCErrorCode(wifiHid2dPtr->Hid2dSharedlinkIncrease());
}
WifiErrorCode Hid2dSharedlinkDecrease()
{
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<int>(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<int>(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)
{
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<int>(request->prefBandwidth));
}
static void ConvertRecommendChannelResponse(const OHOS::Wifi::RecommendChannelResponse& rsp,
RecommendChannelResponse* response)
{
response->status = RecommendStatus(static_cast<int>(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);
WifiLinkedInfo linkedInfo;
WifiErrorCode ret = GetLinkedInfo(&linkedInfo);
if (ret == WIFI_SUCCESS && linkedInfo.connState == WIFI_CONNECTED) {
response->status = RS_SUCCESS;
response->index = 0;
constexpr int FREQ_2G_MAX = 2472;
constexpr int CHANNEL_14_FREQ = 2484;
if (linkedInfo.frequency <= FREQ_2G_MAX || linkedInfo.frequency == CHANNEL_14_FREQ) {
response->centerFreq = linkedInfo.frequency;
response->centerFreq1 = 0;
} else {
response->centerFreq = 0;
response->centerFreq1 = linkedInfo.frequency;
}
response->centerFreq2 = 0;
response->bandwidth = linkedInfo.band;
return WIFI_SUCCESS;
}
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<int> 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<int>(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<int>(cfgType)), cfgData, setDataValidLen));
}
int Hid2dIsWideBandwidthSupported()
{
constexpr int NOT_SUPPORT = 0; // false
return NOT_SUPPORT;
}

View File

@ -1,184 +1,184 @@
/*
* 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 "ip_tools.h"
#include "wifi_common_util.h"
DEFINE_WIFILOG_LABEL("WifiCHotspot");
std::unique_ptr<OHOS::Wifi::WifiHotspot> 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<WifiSecurityType, OHOS::Wifi::KeyMgmt> 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<WifiSecurityType, OHOS::Wifi::KeyMgmt>::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<int>(each.first);
}
}
return static_cast<int>(WifiSecurityType::WIFI_SEC_TYPE_OPEN);
}
static bool IsSecurityTypeSupported(int secType)
{
WifiSecurityType key = WifiSecurityType(secType);
std::map<WifiSecurityType, OHOS::Wifi::KeyMgmt>::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<int>(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<OHOS::Wifi::StationInfo>& vecStaList, StationInfo *result)
{
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::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<OHOS::Wifi::StationInfo> 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 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT 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 "ip_tools.h"
#include "wifi_common_util.h"
DEFINE_WIFILOG_LABEL("WifiCHotspot");
std::unique_ptr<OHOS::Wifi::WifiHotspot> 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<WifiSecurityType, OHOS::Wifi::KeyMgmt> 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<WifiSecurityType, OHOS::Wifi::KeyMgmt>::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<int>(each.first);
}
}
return static_cast<int>(WifiSecurityType::WIFI_SEC_TYPE_OPEN);
}
static bool IsSecurityTypeSupported(int secType)
{
WifiSecurityType key = WifiSecurityType(secType);
std::map<WifiSecurityType, OHOS::Wifi::KeyMgmt>::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<int>(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<OHOS::Wifi::StationInfo>& vecStaList, StationInfo *result)
{
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::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<OHOS::Wifi::StationInfo> 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);
}

View File

@ -0,0 +1,447 @@
/*
* 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 "native_c/wifi_p2p.h"
#include "wifi_logger.h"
#include "native_cpp/wifi_standard/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<OHOS::Wifi::WifiP2p> 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)
{
cppConfig.SetDeviceAddress(OHOS::Wifi::MacArrayToStr(config->devAddr));
cppConfig.SetGoBand(OHOS::Wifi::GroupOwnerBand(static_cast<int>(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);
OHOS::Wifi::WifiP2pConfig cppConfig;
ConvertConfigCToCpp(config, cppConfig);
return GetCErrorCode(wifiP2pPtr->FormGroup(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<int>(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)
{
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<int>(group->groupStatus)));
std::vector<OHOS::Wifi::WifiP2pDevice> 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);
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);
OHOS::Wifi::WifiP2pConfig deviceConfig;
ConvertConfigCToCpp(config, deviceConfig);
return GetCErrorCode(wifiP2pPtr->P2pConnect(deviceConfig));
}
WifiErrorCode P2pDisConnect()
{
CHECK_PTR_RETURN(wifiP2pPtr, ERROR_WIFI_NOT_AVAILABLE);
return GetCErrorCode(wifiP2pPtr->P2pDisConnect());
}
static OHOS::Wifi::ErrCode ConvertP2PDeviceCppToC(const OHOS::Wifi::WifiP2pDevice& cppDevice, WifiP2pDevice* p2pDevice)
{
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<int>(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)
{
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<int>(cppGroup.GetP2pGroupStatus()));
const std::vector<OHOS::Wifi::WifiP2pDevice>& 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)
{
if (groupInfo == nullptr) {
WIFI_LOGE("get current group input args is null!");
return ERROR_WIFI_INVALID_ARGS;
}
CHECK_PTR_RETURN(wifiP2pPtr, ERROR_WIFI_NOT_AVAILABLE);
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)
{
if (status == nullptr) {
WIFI_LOGE("input args is null!");
return ERROR_WIFI_INVALID_ARGS;
}
CHECK_PTR_RETURN(wifiP2pPtr, ERROR_WIFI_NOT_AVAILABLE);
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 QueryP2pDevices(WifiP2pDevice* clientDevices, int size, int* retSize)
{
CHECK_PTR_RETURN(wifiP2pPtr, ERROR_WIFI_NOT_AVAILABLE);
std::vector<OHOS::Wifi::WifiP2pDevice> 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);
std::vector<OHOS::Wifi::WifiP2pGroupInfo> 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<OHOS::Wifi::WifiP2pDevice> &devices) override {
WIFI_LOGI("received peers changed event: %{public}d", (int)devices.size());
WifiP2pDevice *devicePtr = nullptr;
if (!devices.empty()) {
devicePtr = new WifiP2pDevice[(int)devices.size()];
}
for (auto& each : devices) {
if (ConvertP2PDeviceCppToC(each, devicePtr++) != OHOS::Wifi::WIFI_OPT_SUCCESS) {
WIFI_LOGE("peers changed convert p2p device failed!");
return;
}
}
if (peersChangeCb != nullptr) {
peersChangeCb(devicePtr, (int)devices.size());
}
if (devicePtr != nullptr) {
delete[] devicePtr;
devicePtr = nullptr;
}
}
void OnP2pServicesChanged(const std::vector<OHOS::Wifi::WifiP2pServiceInfo> &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 {
}
OHOS::sptr<OHOS::IRemoteObject> AsObject() override {
return nullptr;
}
public:
WifiP2pCEventCallback() {
stateChangeCb = nullptr;
groupChangeCb = nullptr;
connectionChangeCb = nullptr;
peersChangeCb = nullptr;
}
virtual ~WifiP2pCEventCallback() {
}
public:
P2pStateChangedCallback stateChangeCb;
P2pPersistentGroupsChangedCallback groupChangeCb;
P2pConnectionChangedCallback connectionChangeCb;
P2pPeersChangedCallback peersChangeCb;
private:
WifiP2pLinkedInfo ConvertP2pLinkedInfo(const OHOS::Wifi::WifiP2pLinkedInfo& linkedInfo) {
WifiP2pLinkedInfo info;
info.connectState = P2pConnectionState(static_cast<int>(linkedInfo.GetConnectState()));
info.isP2pGroupOwner = linkedInfo.IsGroupOwner();
OHOS::Wifi::MacStrToArray(linkedInfo.GetGroupOwnerAddress(), info.groupOwnerAddress);
return info;
}
};
OHOS::sptr<WifiP2pCEventCallback> sptrCallback =
OHOS::sptr<WifiP2pCEventCallback>(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);
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);
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);
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);
sptrCallback->peersChangeCb = callback;
wifiP2pPtr->RegisterCallBack(sptrCallback);
return WIFI_SUCCESS;
}

View File

@ -1,45 +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 <map>
namespace OHOS {
namespace Wifi {
static std::map<ErrCode, WifiErrorCode> 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<ErrCode, WifiErrorCode>::const_iterator iter = g_ErrCodeMap.find(errCode);
return iter == g_ErrCodeMap.end() ? ERROR_WIFI_UNKNOWN : iter->second;
}
} // 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 <map>
#include "wifi_common_util.h"
namespace OHOS {
namespace Wifi {
static std::map<ErrCode, WifiErrorCode> 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<ErrCode, WifiErrorCode>::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<std::string> 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

View File

@ -1,38 +1,67 @@
/*
* 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 <string>
#include "native_c/wifi_device_config.h"
#include "native_c/wifi_error_code.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);
} // 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 <string>
#include <vector>
#include "native_c/wifi_device_config.h"
#include "native_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
/**
* @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 - operate 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

View File

@ -1,5 +1,5 @@
/*
* Copyright (C) 2021 Huawei Device Co., Ltd.
* Copyright (C) 2021-2022 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
@ -260,6 +260,14 @@ 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 - operate result
*/
virtual bool SetLowLatencyMode(bool enabled) = 0;
};
} // namespace Wifi
} // namespace OHOS

View File

@ -0,0 +1,139 @@
/*
* 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 <vector>
#include "wifi_hid2d_msg.h"
namespace OHOS {
namespace Wifi {
class Hid2d {
public:
static std::unique_ptr<Hid2d> CreateWifiHid2d(int system_ability_id);
static std::unique_ptr<Hid2d> 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 - operate result
*/
virtual ErrCode Hid2dRequestGcIp(const std::string& gcMac, std::string& ipAddr) = 0;
/**
* @Description Increase(+1) hid2d shared link reference counting
*
* @return ErrCode - operate result
*/
virtual ErrCode Hid2dSharedlinkIncrease() = 0;
/**
* @Description Decrease(-1) hid2d shared link reference counting
*
* @return ErrCode - operate result
*/
virtual ErrCode Hid2dSharedlinkDecrease() = 0;
/**
* @Description Create hid2d group, used on the GO side.
*
* @param frequency - frequency
* @param type - frequency type
* @return ErrCode - operate 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 - operate 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 - operate 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 - operate 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 - operate 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 - operate result
*/
virtual ErrCode Hid2dGetRecommendChannel(const RecommendChannelRequest& request,
RecommendChannelResponse& response) = 0;
/**
* @Description get 5G channel list
*
* @param vecChannelList - result for channel list
* @return ErrCode - operate result
*/
virtual ErrCode Hid2dGetChannelListFor5G(std::vector<int>& 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 - operate 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 - operate result
*/
virtual ErrCode Hid2dSetPeerWifiCfgInfo(PeerCfgType cfgType,
char cfgData[CFG_DATA_MAX_BYTES], int setDataValidLen) = 0;
};
} // namespace Wifi
} // namespace OHOS
#endif

View File

@ -1,5 +1,5 @@
/*
* Copyright (C) 2021 Huawei Device Co., Ltd.
* Copyright (C) 2021-2022 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
@ -114,7 +114,7 @@ public:
/**
* @Description Creating a P2P Group.
*
* @param config - WifiP2pGroupInfo object
* @param config - WifiP2pConfig object
* @return ErrCode - operate result
*/
virtual ErrCode FormGroup(const WifiP2pConfig &config) = 0;

View File

@ -1,5 +1,5 @@
/*
* Copyright (C) 2021 Huawei Device Co., Ltd.
* Copyright (C) 2021-2022 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.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,6 +53,7 @@
#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 */
/* -------------ap module message define----------------- */
#define WIFI_SVR_CMD_ENABLE_WIFI_AP 0x1100 /* open ap */
@ -100,6 +101,18 @@
#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 */
/* -----------register event type and message define-------------- */
#define WIFI_CBK_CMD_STATE_CHANGE 0x1001 /* STA state change event */

View File

@ -1,5 +1,5 @@
/*
* Copyright (C) 2021 Huawei Device Co., Ltd.
* Copyright (C) 2021-2022 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
@ -268,6 +268,14 @@ 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 - operate result
*/
virtual bool SetLowLatencyMode(bool enabled) = 0;
public:
DECLARE_INTERFACE_DESCRIPTOR(u"ohos.wifi.IWifiDeviceService");
};

View File

@ -1,5 +1,5 @@
/*
* Copyright (C) 2021 Huawei Device Co., Ltd.
* Copyright (C) 2021-2022 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.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 {
@ -246,6 +247,111 @@ public:
*/
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 - operate result
*/
virtual ErrCode Hid2dRequestGcIp(const std::string& gcMac, std::string& ipAddr) = 0;
/**
* @Description Increase(+1) hid2d shared link reference counting
*
* @return ErrCode - operate result
*/
virtual ErrCode Hid2dSharedlinkIncrease() = 0;
/**
* @Description Decrease(-1) hid2d shared link reference counting
*
* @return ErrCode - operate result
*/
virtual ErrCode Hid2dSharedlinkDecrease() = 0;
/**
* @Description Create hid2d group, used on the GO side.
*
* @param frequency - frequency
* @param type - frequency type
* @return ErrCode - operate 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 - operate 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 - operate 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 - operate 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 - operate 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 - operate result
*/
virtual ErrCode Hid2dGetRecommendChannel(const RecommendChannelRequest& request,
RecommendChannelResponse& response) = 0;
/**
* @Description get 5G channel list
*
* @param vecChannelList - result for channel list
* @return ErrCode - operate result
*/
virtual ErrCode Hid2dGetChannelListFor5G(std::vector<int>& 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 - operate 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 - operate result
*/
virtual ErrCode Hid2dSetPeerWifiCfgInfo(PeerCfgType cfgType,
char cfgData[CFG_DATA_MAX_BYTES], int setDataValidLen) = 0;
public:
DECLARE_INTERFACE_DESCRIPTOR(u"ohos.wifi.IWifiP2pService");
};

View File

@ -0,0 +1,151 @@
/*
* 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 <string>
#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
};
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;
};
} // namespace Wifi
} // namespace OHOS
#endif

View File

@ -1,5 +1,5 @@
/*
* Copyright (C) 2021 Huawei Device Co., Ltd.
* Copyright (C) 2021-2022 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
@ -54,6 +54,8 @@ enum class P2pActionCallback : unsigned char {
P2pConnect,
P2pDisConnect,
P2pSetDeviceName,
CreateHid2dGroup,
Hid2dConnect,
UNKNOWN
};

View File

@ -1,5 +1,5 @@
/*
* Copyright (C) 2021 Huawei Device Co., Ltd.
* Copyright (C) 2021-2022 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
@ -250,5 +250,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

View File

@ -1,5 +1,5 @@
/*
* Copyright (C) 2021 Huawei Device Co., Ltd.
* Copyright (C) 2021-2022 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
@ -275,6 +275,14 @@ public:
*/
ErrCode GetDeviceMacAddress(std::string &result) override;
/**
* @Description set low latency mode
*
* @param enabled - true: enable low latency, false: disable low latency
* @return bool - operate result
*/
bool SetLowLatencyMode(bool enabled) override;
private:
int systemAbilityId_;
sptr<IWifiDevice> client_;

View File

@ -1,5 +1,5 @@
/*
* Copyright (C) 2021 Huawei Device Co., Ltd.
* Copyright (C) 2021-2022 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
@ -964,6 +964,29 @@ ErrCode WifiDeviceProxy::GetDeviceMacAddress(std::string &result)
return WIFI_OPT_SUCCESS;
}
bool WifiDeviceProxy::SetLowLatencyMode(bool enabled)
{
if (mRemoteDied) {
WIFI_LOGD("failed to `%{public}s`,remote service is died!", __func__);
return WIFI_OPT_FAILED;
}
MessageOption option;
MessageParcel data;
MessageParcel reply;
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<IRemoteObject> &remoteObject)
{
WIFI_LOGD("Remote service is died!");

View File

@ -1,5 +1,5 @@
/*
* Copyright (C) 2021 Huawei Device Co., Ltd.
* Copyright (C) 2021-2022 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
@ -266,6 +266,18 @@ public:
*/
ErrCode GetDeviceMacAddress(std::string &result) override;
/**
* @Description set low latency mode
*
* @param enabled - true: enable low latency, false: disable low latency
* @return bool - operate result
*/
bool SetLowLatencyMode(bool enabled) override;
/**
* @Description Handle remote object died event.
* @param remoteObject remote object.
*/
void OnRemoteDied(const wptr<IRemoteObject> &remoteObject) override;
private:

View File

@ -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> Hid2d::CreateWifiHid2d(int systemAbilityId)
{
std::unique_ptr<WifiP2pImpl> impl = std::make_unique<WifiP2pImpl>(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> Hid2d::GetInstance(int systemAbilityId)
{
std::unique_ptr<WifiP2pImpl> impl = std::make_unique<WifiP2pImpl>(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

View File

@ -0,0 +1,60 @@
/*
* 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"
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

View File

@ -1,5 +1,5 @@
/*
* Copyright (C) 2021 Huawei Device Co., Ltd.
* Copyright (C) 2021-2022 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
@ -148,7 +148,12 @@ public:
*/
ErrCode GetSupportedFeatures(long &features) override;
/**
* @Description Handle remote object died event.
* @param remoteObject remote object.
*/
void OnRemoteDied(const wptr<IRemoteObject>& remoteObject) override;
private:
static BrokerDelegator<WifiHotspotProxy> g_delegator;

View File

@ -1,5 +1,5 @@
/*
* Copyright (C) 2021 Huawei Device Co., Ltd.
* Copyright (C) 2021-2022 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.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_LOGGER_H
#define OHOS_WIFI_LOGGER_H
@ -45,6 +46,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

View File

@ -1,5 +1,5 @@
/*
* Copyright (C) 2021 Huawei Device Co., Ltd.
* Copyright (C) 2021-2022 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.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_stub.h"
#include "define.h"
#include "wifi_p2p_msg.h"
@ -88,7 +89,7 @@ void WifiP2pCallbackStub::SetRemoteDied(bool val)
void WifiP2pCallbackStub::OnP2pStateChanged(int state)
{
WIFI_LOGD("WifiP2pCallbackStub::OnP2pStateChanged");
WIFI_LOGD("WifiP2pCallbackStub::OnP2pStateChanged: %{public}d", state);
if (userCallback_) {
userCallback_->OnP2pStateChanged(state);
}
@ -133,7 +134,7 @@ void WifiP2pCallbackStub::OnP2pServicesChanged(const std::vector<WifiP2pServiceI
void WifiP2pCallbackStub::OnP2pConnectionChanged(const WifiP2pLinkedInfo &info)
{
WIFI_LOGD("WifiP2pCallbackStub::OnP2pConnectionChanged");
WIFI_LOGD("WifiP2pCallbackStub::OnP2pConnectionChanged: %{public}d", static_cast<int>(info.GetConnectState()));
if (userCallback_) {
userCallback_->OnP2pConnectionChanged(info);
}

View File

@ -1,5 +1,5 @@
/*
* Copyright (C) 2021 Huawei Device Co., Ltd.
* Copyright (C) 2021-2022 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.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");
@ -226,15 +228,90 @@ 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<int>& 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);
}
} // namespace Wifi
} // namespace OHOS

View File

@ -1,5 +1,5 @@
/*
* Copyright (C) 2021 Huawei Device Co., Ltd.
* Copyright (C) 2021-2022 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.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();
@ -254,6 +255,111 @@ public:
*/
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 - operate result
*/
ErrCode Hid2dRequestGcIp(const std::string& gcMac, std::string& ipAddr) override;
/**
* @Description Increase(+1) hid2d shared link reference counting
*
* @return ErrCode - operate result
*/
ErrCode Hid2dSharedlinkIncrease() override;
/**
* @Description Decrease(-1) hid2d shared link reference counting
*
* @return ErrCode - operate result
*/
ErrCode Hid2dSharedlinkDecrease() override;
/**
* @Description Create hid2d group, used on the GO side.
*
* @param frequency - frequency
* @param type - frequency type
* @return ErrCode - operate 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 - operate 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 - operate 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 - operate 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 - operate 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 - operate result
*/
ErrCode Hid2dGetRecommendChannel(const RecommendChannelRequest& request,
RecommendChannelResponse& response) override;
/**
* @Description get 5G channel list
*
* @param vecChannelList - result for channel list
* @return ErrCode - operate result
*/
ErrCode Hid2dGetChannelListFor5G(std::vector<int>& 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 - operate 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 - operate result
*/
ErrCode Hid2dSetPeerWifiCfgInfo(PeerCfgType cfgType,
char cfgData[CFG_DATA_MAX_BYTES], int setDataValidLen) override;
private:
int systemAbilityId_;
sptr<IWifiP2p> client_;

View File

@ -1,5 +1,5 @@
/*
* Copyright (C) 2021 Huawei Device Co., Ltd.
* Copyright (C) 2021-2022 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
@ -901,6 +901,354 @@ ErrCode WifiP2pProxy::GetSupportedFeatures(long &features)
return WIFI_OPT_SUCCESS;
}
ErrCode WifiP2pProxy::Hid2dRequestGcIp(const std::string& gcMac, std::string& ipAddr)
{
if (mRemoteDied) {
WIFI_LOGD("failed to `%{public}s`,remote service is died!", __func__);
return WIFI_OPT_FAILED;
}
MessageOption option;
MessageParcel data;
MessageParcel reply;
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_LOGD("failed to `%{public}s`,remote service is died!", __func__);
return WIFI_OPT_FAILED;
}
MessageOption option;
MessageParcel data;
MessageParcel reply;
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_LOGD("failed to `%{public}s`,remote service is died!", __func__);
return WIFI_OPT_FAILED;
}
MessageOption option;
MessageParcel data;
MessageParcel reply;
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_LOGD("failed to `%{public}s`,remote service is died!", __func__);
return WIFI_OPT_FAILED;
}
MessageOption option;
MessageParcel data;
MessageParcel reply;
data.WriteInt32(0);
data.WriteInt32(frequency);
data.WriteInt32(static_cast<int>(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_LOGD("failed to `%{public}s`,remote service is died!", __func__);
return WIFI_OPT_FAILED;
}
MessageOption option;
MessageParcel data;
MessageParcel reply;
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_LOGD("failed to `%{public}s`,remote service is died!", __func__);
return WIFI_OPT_FAILED;
}
MessageOption option;
MessageParcel data;
MessageParcel reply;
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<int>(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_LOGD("failed to `%{public}s`,remote service is died!", __func__);
return WIFI_OPT_FAILED;
}
MessageOption option;
MessageParcel data;
MessageParcel reply;
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_LOGD("failed to `%{public}s`,remote service is died!", __func__);
return WIFI_OPT_FAILED;
}
MessageOption option;
MessageParcel data;
MessageParcel reply;
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_LOGD("failed to `%{public}s`,remote service is died!", __func__);
return WIFI_OPT_FAILED;
}
MessageOption option;
MessageParcel data, reply;
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<int>(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<int>& vecChannelList)
{
if (mRemoteDied) {
WIFI_LOGD("failed to `%{public}s`,remote service is died!", __func__);
return WIFI_OPT_FAILED;
}
MessageOption option;
MessageParcel data;
MessageParcel reply;
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);
}
int listSize = reply.ReadInt32();
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 (mRemoteDied) {
WIFI_LOGD("failed to `%{public}s`,remote service is died!", __func__);
return WIFI_OPT_FAILED;
}
MessageOption option;
MessageParcel data;
MessageParcel reply;
data.WriteInt32(0);
data.WriteInt32(static_cast<int>(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_LOGD("`%{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_LOGD("failed to `%{public}s`,remote service is died!", __func__);
return WIFI_OPT_FAILED;
}
MessageOption option;
MessageParcel data;
MessageParcel reply;
data.WriteInt32(0);
data.WriteInt32(static_cast<int>(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());
}
void WifiP2pProxy::OnRemoteDied(const wptr<IRemoteObject>& remoteObject)
{
WIFI_LOGD("Remote service is died!");

View File

@ -1,5 +1,5 @@
/*
* Copyright (C) 2021 Huawei Device Co., Ltd.
* Copyright (C) 2021-2022 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
@ -245,6 +245,115 @@ public:
*/
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 - operate result
*/
ErrCode Hid2dRequestGcIp(const std::string& gcMac, std::string& ipAddr) override;
/**
* @Description Increase(+1) hid2d shared link reference counting
*
* @return ErrCode - operate result
*/
ErrCode Hid2dSharedlinkIncrease() override;
/**
* @Description Decrease(-1) hid2d shared link reference counting
*
* @return ErrCode - operate result
*/
ErrCode Hid2dSharedlinkDecrease() override;
/**
* @Description Create hid2d group, used on the GO side.
*
* @param frequency - frequency
* @param type - frequency type
* @return ErrCode - operate 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 - operate 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 - operate 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 - operate 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 - operate 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 - operate result
*/
ErrCode Hid2dGetRecommendChannel(const RecommendChannelRequest& request,
RecommendChannelResponse& response) override;
/**
* @Description get 5G channel list
*
* @param vecChannelList - result for channel list
* @return ErrCode - operate result
*/
ErrCode Hid2dGetChannelListFor5G(std::vector<int>& 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 - operate 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 - operate result
*/
ErrCode Hid2dSetPeerWifiCfgInfo(PeerCfgType cfgType,
char cfgData[CFG_DATA_MAX_BYTES], int setDataValidLen) override;
/**
* @Description Handle remote object died event.
* @param remoteObject remote object.
*/
void OnRemoteDied(const wptr<IRemoteObject> &remoteObject) override;
private:

View File

@ -136,7 +136,7 @@ declare namespace wifi {
* Obtains information about a Wi-Fi connection.
*
* @return Returns the Wi-Fi connection information.
* @since 8
* @since 7
*/
function getLinkedInfo(): Promise<WifiLinkedInfo>;
function getLinkedInfo(callback: AsyncCallback<WifiLinkedInfo>): void;
@ -145,7 +145,7 @@ declare namespace wifi {
* Checks whether a Wi-Fi connection has been set up.
*
* @return Returns {@code true} if a Wi-Fi connection has been set up; returns {@code false} otherwise.
* @since 8
* @since 7
*/
function isConnected(): boolean;
@ -155,7 +155,7 @@ declare namespace wifi {
* <p>To check whether this device supports a specified feature.
*
* @return Returns the features supported by this device.
* @since 8
* @since 7
* @systemapi Hide this for inner system use.
*/
function getSupportedFeatures(): number;
@ -165,7 +165,7 @@ declare namespace wifi {
*
* @param featureId Indicates the ID of the feature.
* @return Returns {@code true} if this device supports the specified feature; returns {@code false} otherwise.
* @since 8
* @since 7
*/
function isFeatureSupported(featureId: number): boolean;
@ -175,7 +175,7 @@ declare namespace wifi {
* <p>The MAC address is unique and cannot be changed.
*
* @return Returns the MAC address of the Wi-Fi device.
* @since 8
* @since 7
* @systemapi Hide this for inner system use.
*/
function getDeviceMacAddress(): string[];
@ -186,7 +186,7 @@ declare namespace wifi {
* <p>The IP information includes the host IP address, gateway address, and DNS information.
*
* @return Returns the IP information of the Wi-Fi connection.
* @since 8
* @since 7
*/
function getIpInfo(): IpInfo;
@ -194,7 +194,7 @@ declare namespace wifi {
* Obtains the country code of this device.
*
* @return Returns the country code of this device.
* @since 8
* @since 7
*/
function getCountryCode(): string;
@ -202,7 +202,7 @@ declare namespace wifi {
* Re-associates to current network.
*
* @return {@code true} if the Wi-Fi network is re-associate successfully.
* @since 8
* @since 7
* @systemapi Hide this for inner system use.
*/
function reassociate(): boolean;
@ -211,7 +211,7 @@ declare namespace wifi {
* Re-connects to current network.
*
* @return {@code true} if the Wi-Fi network is re-connect successfully.
* @since 8
* @since 7
* @systemapi Hide this for inner system use.
*/
function reconnect(): boolean;
@ -222,7 +222,7 @@ declare namespace wifi {
* <p>You can obtain only the Wi-Fi configurations you created on your own application.
*
* @return Returns the list of all existing Wi-Fi configurations you created on your application.
* @since 8
* @since 7
* @systemapi Hide this for inner system use.
*/
function getDeviceConfigs(): Array<WifiDeviceConfig>;
@ -234,7 +234,7 @@ declare namespace wifi {
*
* @return Returns the network ID in the updated Wi-Fi configuration if the update is successful;
* returns {@code -1} if the specified Wi-Fi configuration is not contained in the list.
* @since 8
* @since 7
* @systemapi Hide this for inner system use.
*/
function updateNetwork(config: WifiDeviceConfig): number;
@ -246,7 +246,7 @@ declare namespace wifi {
*
* @param netId Identifies the network to disable.
* @return Returns {@code true} if the specified network is disabled; returns {@code false} otherwise.
* @since 8
* @since 7
* @systemapi Hide this for inner system use.
*/
function disableNetwork(netId: number): boolean;
@ -256,7 +256,7 @@ declare namespace wifi {
*
* @return Returns {@code true} if all the saved Wi-Fi configurations are removed;
* returns {@code false} otherwise.
* @since 8
* @since 7
* @systemapi Hide this for inner system use.
*/
function removeAllNetwork(): boolean;
@ -271,7 +271,7 @@ declare namespace wifi {
* @param id Indicates the ID of the Wi-Fi network,
* which can be obtained using the {@link #addDeviceConfig} or {@link #getLinkedInfo} method.
* @return Returns {@code true} if the Wi-Fi network is deleted successfully; returns {@code false} otherwise.
* @since 8
* @since 7
* @systemapi Hide this for inner system use.
*/
function removeDevice(id: number): boolean;
@ -282,7 +282,7 @@ declare namespace wifi {
* <p>This method is asynchronous. After the Wi-Fi hotspot is enabled, Wi-Fi may be disabled.
*
* @return Returns {@code true} if this method is called successfully; returns {@code false} otherwise.
* @since 8
* @since 7
* @systemapi Hide this for inner system use.
*/
function enableHotspot(): boolean;
@ -293,7 +293,7 @@ declare namespace wifi {
* <p>This method is asynchronous. If Wi-Fi is enabled after the Wi-Fi hotspot is disabled, Wi-Fi may be re-enabled.
*
* @return Returns {@code true} if this method is called successfully; returns {@code false} otherwise.
* @since 8
* @since 7
* @systemapi Hide this for inner system use.
*/
function disableHotspot(): boolean;
@ -302,7 +302,7 @@ declare namespace wifi {
* Checks whether Wi-Fi hotspot is active on a device.
*
* @return Returns {@code true} if Wi-Fi hotspot is enabled; returns {@code false} otherwise.
* @since 8
* @since 7
* @systemapi Hide this for inner system use.
*/
function isHotspotActive(): boolean;
@ -316,7 +316,7 @@ declare namespace wifi {
* The SSID and {@code securityType} must be available and correct.
* If {@code securityType} is not {@code open}, {@code preSharedKey} must be available and correct.
* @return Returns {@code true} if the method is called successfully; returns {@code false} otherwise.
* @since 8
* @since 7
* @systemapi Hide this for inner system use.
*/
function setHotspotConfig(config: HotspotConfig): boolean;
@ -325,7 +325,7 @@ declare namespace wifi {
* Obtains the Wi-Fi hotspot configuration.
*
* @return Returns the configuration of an existing or enabled Wi-Fi hotspot.
* @since 8
* @since 7
* @systemapi Hide this for inner system use.
*/
function getHotspotConfig(): HotspotConfig;
@ -336,7 +336,7 @@ declare namespace wifi {
* <p>This method can only be used on a device that serves as a Wi-Fi hotspot.
*
* @return Returns the list of clients that are connected to the Wi-Fi hotspot.
* @since 8
* @since 7
* @systemapi Hide this for inner system use.
*/
function getStations(): Array<StationInfo>;
@ -344,7 +344,7 @@ declare namespace wifi {
/**
* Defines the EventListener class and provides functions to subscribe or unsubscribe the Wi-Fi events.
*
* @since 8
* @since 7
* @SysCap SystemCapability.Communication.WiFi
* @devices phone, tablet, tv, wearable, car
*/
@ -429,7 +429,7 @@ declare namespace wifi {
* Subscribe Wi-Fi hotspot state change events.
*
* @return Returns 0: inactive, 1: active, 2: activating, 3: deactivating
* @since 8
* @since 7
*/
on(type: "hotspotStateChange", callback: Callback<number>): void;
@ -438,7 +438,7 @@ declare namespace wifi {
*
* <p>All callback functions will be deregistered If there is no specific callback parameter.</p>
*
* @since 8
* @since 7
*/
off(type: "hotspotStateChange", callback?: Callback<number>): void;
@ -446,7 +446,7 @@ declare namespace wifi {
* Subscribe Wi-Fi hotspot sta join events.
*
* @return Returns StationInfo
* @since 8
* @since 7
* @systemapi Hide this for inner system use.
*/
on(type: "hotspotStaJoin", callback: Callback<StationInfo>): void;
@ -456,7 +456,7 @@ declare namespace wifi {
*
* <p>All callback functions will be deregistered If there is no specific callback parameter.</p>
*
* @since 8
* @since 7
* @systemapi Hide this for inner system use.
*/
off(type: "hotspotStaJoin", callback?: Callback<StationInfo>): void;
@ -465,7 +465,7 @@ declare namespace wifi {
* Subscribe Wi-Fi hotspot sta leave events.
*
* @return Returns {@link #StationInfo} object
* @since 8
* @since 7
* @systemapi Hide this for inner system use.
*/
on(type: "hotspotStaLeave", callback: Callback<StationInfo>): void;
@ -474,7 +474,7 @@ declare namespace wifi {
* Unsubscribe Wi-Fi hotspot sta leave events.
*
* @return Returns {@link #StationInfo} object
* @since 8
* @since 7
* @systemapi Hide this for inner system use.
*/
off(type: "hotspotStaLeave", callback?: Callback<StationInfo>): void;
@ -547,7 +547,7 @@ declare namespace wifi {
/**
* Wi-Fi connection information.
*
* @since 8
* @since 7
*/
interface WifiLinkedInfo {
/** The SSID of the Wi-Fi hotspot */
@ -603,7 +603,7 @@ declare namespace wifi {
/**
* Wi-Fi IP information.
*
* @since 8
* @since 7
*/
interface IpInfo {
/** The IP address of the Wi-Fi connection */
@ -631,7 +631,7 @@ declare namespace wifi {
/**
* Wi-Fi hotspot configuration information.
*
* @since 8
* @since 7
* @systemapi
*/
interface HotspotConfig {
@ -654,7 +654,7 @@ declare namespace wifi {
/**
* Wi-Fi station information.
*
* @since 8
* @since 7
* @systemapi
*/
interface StationInfo {
@ -671,7 +671,7 @@ declare namespace wifi {
/**
* The state of the supplicant enumeration.
*
* @since 8
* @since 7
* @systemapi
*/
export enum SuppState {
@ -715,7 +715,7 @@ declare namespace wifi {
/**
* The state of Wi-Fi connection enumeration.
*
* @since 8
* @since 7
*/
export enum ConnState {
/** The device is searching for an available AP. */

View File

@ -1,5 +1,5 @@
/*
* Copyright (C) 2021 Huawei Device Co., Ltd.
* Copyright (C) 2021-2022 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.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,4 +34,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)) { \
WIFI_LOGI("Pointer %{public}s in %{public}s is NULL!", #ptr, __func__); \
return retValue; \
}
#endif
#endif

View File

@ -1,5 +1,5 @@
/*
* Copyright (C) 2021 Huawei Device Co., Ltd.
* Copyright (C) 2021-2022 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.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,8 +26,6 @@ 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;

View File

@ -1,5 +1,5 @@
/*
* Copyright (C) 2021 Huawei Device Co., Ltd.
* Copyright (C) 2021-2022 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.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,18 @@
#include "securec.h"
#include "if_config.h"
#include "ip_tools.h"
#include <thread>
namespace OHOS {
namespace Wifi {
const std::string SYSTEM_COMMAND_IP = "/system/bin/ip";
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 SYSTEM_COMMAND_ERR = -1;
const int SYSTEM_NOT_EXECUTED = 127;
const int IPV6_SUFFIX_LEN = 3;
const int MAX_IFNAME_LEN = 13;
const int RECEIVE_BUFFER_LEN = 64;
IfConfig &IfConfig::GetInstance()
{
@ -49,6 +51,38 @@ IfConfig::IfConfig()
IfConfig::~IfConfig()
{}
bool IfConfig::SyncExecuteCommand(const std::string& cmd)
{
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;
}
bool IfConfig::AsyncExecuteCommand(const std::string& cmd)
{
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 : Execute script commands
* @Return success:true failed:false
@ -60,21 +94,15 @@ bool IfConfig::ExecCommand(const std::vector<std::string> &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);
return false;
}
return true;
LOGI("Exec cmd start: [%s]", command.c_str());
return AsyncExecuteCommand(command);
}
/**
* @Description : Set the network card address, routing, DNS
* @Description : Set the network card routing, DNS
* @Return success:0 failed:-1
*/
int IfConfig::SetIfAddr(const DhcpResult &dhcpResult, int ipType)
int IfConfig::SetIfDnsAndRoute(const DhcpResult &dhcpResult, int ipType)
{
LOGD("ipType=%d, ip=%s, gateway=%s, subnet=%s, strDns1=%s, strDns2=%s",
dhcpResult.iptype,
@ -84,10 +112,8 @@ int IfConfig::SetIfAddr(const DhcpResult &dhcpResult, int ipType)
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!");
LOGI("set dns and route finished!");
return 0;
}
@ -117,7 +143,7 @@ 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<int>(StaIpType::IPTYPE_IPV4)) {
if (ipType != static_cast<int>(IpType::IPTYPE_IPV4)) {
return;
}
struct ifreq ifr;
@ -155,7 +181,9 @@ 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<int>(StaIpType::IPTYPE_IPV4)) {
LOGI("Add ip address, ifName = %{public}s", ifName.c_str());
if (ipType == static_cast<int>(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) {
@ -220,7 +248,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<int>(StaIpType::IPTYPE_IPV4)) {
if (ipType == static_cast<int>(IpType::IPTYPE_IPV4)) {
AddIpv4Route(ifName, ipAddr, mask, gateWay);
} else {
AddIpv6Route(ifName, ipAddr, mask, gateWay);
@ -235,7 +263,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 %s, mask is %s, gateWay is %s",
ifName.c_str(),
ipAddr.c_str(),
mask.c_str(),
@ -366,8 +394,31 @@ void IfConfig::SetProxy(
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<struct sockaddr_in *>(&ifr.ifr_addr);
ipAddr = inet_ntoa(sin->sin_addr);
close(fd);
return true;
}
} // namespace Wifi
} // namespace OHOS

View File

@ -1,5 +1,5 @@
/*
* Copyright (C) 2021 Huawei Device Co., Ltd.
* Copyright (C) 2021-2022 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.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,10 +18,16 @@
#include <memory>
#include "wifi_log.h"
#include "dhcp_define.h"
#include "sta_define.h"
namespace OHOS {
namespace Wifi {
typedef enum IpType {
IPTYPE_IPV4,
IPTYPE_IPV6,
IPTYPE_MIX,
IPTYPE_BUTT,
} IpType;
class IfConfig {
public:
IfConfig();
@ -36,7 +42,7 @@ 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);
@ -57,6 +63,26 @@ public:
const std::string &pac);
bool ExecCommand(const std::vector<std::string> &vecCommandArg);
bool GetIpAddr(const std::string& ifName, std::string& ipAddr);
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);
/**
* @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);
};
} // namespace Wifi
} // namespace OHOS

View File

@ -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(".");

View File

@ -1,5 +1,5 @@
/*
* Copyright (C) 2021 Huawei Device Co., Ltd.
* Copyright (C) 2021-2022 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.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,14 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "mac_address.h"
#include <unistd.h>
#include <climits>
#include <algorithm>
#include <net/if.h>
#include <sys/ioctl.h>
#include <netinet/if_ether.h>
#include "securec.h"
#include "log_helper.h"
#include "wifi_log.h"
@ -129,5 +134,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 stuct 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

View File

@ -1,5 +1,5 @@
/*
* Copyright (C) 2021 Huawei Device Co., Ltd.
* Copyright (C) 2021-2022 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.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_MAC_ADDRESS_H
#define OHOS_MAC_ADDRESS_H
@ -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.

View File

@ -1,5 +1,5 @@
/*
* Copyright (C) 2021 Huawei Device Co., Ltd.
* Copyright (C) 2021-2022 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
@ -222,6 +222,20 @@ private:
*/
int UnsubscribeDhcpEvent(const std::string &strAction);
/**
* @Description : release result notify memory.
*
*/
void ReleaseResultNotifyMemory();
/**
* @Description : Unsubscribe all dhcp event.
*
* @param strAction - event action [in]
* @Return : success - DHCP_OPT_SUCCESS, failed - others.
*/
int UnsubscribeAllDhcpEvent();
private:
std::mutex mResultNotifyMutex;
bool isExitDhcpResultHandleThread;

View File

@ -1,5 +1,5 @@
/*
* Copyright (C) 2021 Huawei Device Co., Ltd.
* Copyright (C) 2021-2022 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.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 <netinet/ip.h>
#include <sys/stat.h>
namespace OHOS {
namespace Wifi {
const int ETH_MAC_ADDR_INDEX_0 = 0;
@ -76,6 +75,8 @@ const std::string DHCP_SERVER_LEASES_FILE("/data/dhcp/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 */

View File

@ -1,5 +1,5 @@
/*
* Copyright (C) 2021 Huawei Device Co., Ltd.
* Copyright (C) 2021-2022 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.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.

View File

@ -1,5 +1,5 @@
/*
* Copyright (C) 2021 Huawei Device Co., Ltd.
* Copyright (C) 2021-2022 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
@ -35,9 +35,11 @@ DhcpClientServiceImpl::DhcpClientServiceImpl()
isExitDhcpResultHandleThread = false;
pDhcpResultHandleThread = nullptr;
m_mapDhcpResultNotify.clear();
if (!m_mapDhcpResultNotify.empty()) {
ReleaseResultNotifyMemory();
m_mapDhcpResultNotify.clear();
}
m_mapEventSubscriber.clear();
InitDhcpMgrThread();
DhcpFunc::CreateDirs(DHCP_WORK_DIR);
}
@ -46,20 +48,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,6 +92,7 @@ void DhcpClientServiceImpl::ExitDhcpMgrThread()
if (!m_mapDhcpResultNotify.empty()) {
WIFI_LOGE("ExitDhcpMgrThread() error, m_mapDhcpResultNotify is not empty!");
ReleaseResultNotifyMemory();
m_mapDhcpResultNotify.clear();
}
}
@ -231,6 +241,21 @@ int DhcpClientServiceImpl::UnsubscribeDhcpEvent(const std::string &strAction)
return DHCP_OPT_SUCCESS;
}
int DhcpClientServiceImpl::UnsubscribeAllDhcpEvent()
{
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;
}
}
}
m_mapEventSubscriber.clear();
WIFI_LOGI("UnsubscribeDhcpEvent all dhcp event success!");
return DHCP_OPT_SUCCESS;
}
void DhcpClientServiceImpl::RunDhcpResultHandleThreadFunc()
{
for (; ;) {
@ -656,6 +681,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;

View File

@ -1,5 +1,5 @@
/*
* Copyright (C) 2021 Huawei Device Co., Ltd.
* Copyright (C) 2021-2022 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.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;

View File

@ -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
@ -113,7 +113,11 @@ ohos_source_set("wifi_hotspot_service_impl") {
}
ohos_source_set("wifi_p2p_service_impl") {
sources = [
"//foundation/communication/wifi/interfaces/innerkits/native_cpp/wifi_standard/src/wifi_hid2d_msg.cpp",
"//foundation/communication/wifi/interfaces/innerkits/native_cpp/wifi_standard/src/wifi_p2p_msg.cpp",
"//foundation/communication/wifi/services/wifi_standard/wifi_framework/common/net_helper/if_config.cpp",
"wifi_hid2d_cfg.cpp",
"wifi_hid2d_service_utils.cpp",
"wifi_p2p_callback_proxy.cpp",
"wifi_p2p_death_recipient.cpp",
"wifi_p2p_service_impl.cpp",
@ -224,6 +228,7 @@ ohos_shared_library("wifi_p2p_ability") {
":wifi_manager_service",
":wifi_p2p_service_impl",
"//base/hiviewdfx/hilog/interfaces/native/innerkits:libhilog",
"//foundation/communication/wifi/utils/src:wifi_utils",
"//foundation/distributedschedule/safwk/interfaces/innerkits/safwk:system_ability_fwk",
"//utils/native/base:utils",
]

View File

@ -1,5 +1,5 @@
/*
* Copyright (C) 2021 Huawei Device Co., Ltd.
* Copyright (C) 2021-2022 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.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 <inttypes.h>
#include "state_machine.h"
#include "wifi_log.h"
@ -621,6 +622,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;

View File

@ -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
@ -80,6 +80,7 @@ ohos_source_set("log_helper") {
ohos_shared_library("wifi_idl_client") {
install_enable = true
sources = [
"//foundation/communication/wifi/interfaces/innerkits/native_cpp/wifi_standard/src/wifi_hid2d_msg.cpp",
"//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",

View File

@ -1,5 +1,5 @@
/*
* Copyright (C) 2021 Huawei Device Co., Ltd.
* Copyright (C) 2021-2022 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
@ -1082,4 +1082,26 @@ WifiErrorNo P2pAddNetwork(int *networkId)
ReadClientEnd(client);
UnlockRpcClient(client);
return result;
}
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;
}

View File

@ -1,5 +1,5 @@
/*
* Copyright (C) 2021 Huawei Device Co., Ltd.
* Copyright (C) 2021-2022 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
@ -420,6 +420,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

View File

@ -1,5 +1,5 @@
/*
* Copyright (C) 2021 Huawei Device Co., Ltd.
* Copyright (C) 2021-2022 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
@ -300,9 +300,14 @@ typedef struct HidlP2pGroupConfig {
char cfgValue[WIFI_P2P_GROUP_CONFIG_VALUE_LENGTH]; /* param value */
} HidlP2pGroupConfig;
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

View File

@ -1,5 +1,5 @@
/*
* Copyright (C) 2021 Huawei Device Co., Ltd.
* Copyright (C) 2021-2022 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.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 <cstdio>
#include "wifi_global_func.h"
@ -1585,5 +1586,27 @@ 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;
}
} // namespace Wifi
} // namespace OHOS

View File

@ -1,5 +1,5 @@
/*
* Copyright (C) 2021 Huawei Device Co., Ltd.
* Copyright (C) 2021-2022 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.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 {
@ -993,6 +994,15 @@ 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;
public:
RpcClient *pRpcClient;

View File

@ -1,5 +1,5 @@
/*
* Copyright (C) 2021 Huawei Device Co., Ltd.
* Copyright (C) 2021-2022 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
@ -280,5 +280,10 @@ const P2pHalCallback &WifiP2PHalInterface::GetP2pCallbackInst(void) const
{
return mP2pCallback;
}
WifiErrorNo WifiP2PHalInterface::Hid2dConnect(const Hid2dConnectConfig &config) const
{
return mIdlClient->ReqP2pHid2dConnect(config);
}
} // namespace Wifi
} // namespace OHOS

View File

@ -1,5 +1,5 @@
/*
* Copyright (C) 2021 Huawei Device Co., Ltd.
* Copyright (C) 2021-2022 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.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
@ -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;
};

View File

@ -22,6 +22,7 @@ ohos_shared_library("wifi_ap_service") {
"../common/state.cpp",
"../common/state_machine.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/if_config.cpp",
"ap_config_use.cpp",
"ap_idle_state.cpp",
"ap_interface.cpp",

View File

@ -1,5 +1,5 @@
/*
* Copyright (C) 2021 Huawei Device Co., Ltd.
* Copyright (C) 2021-2022 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.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 <fstream>
#include <vector>
#include "network_interface.h"
#include "if_config.h"
#include "wifi_logger.h"
DEFINE_WIFILOG_HOTSPOT_LABEL("WifiApNatManager");
@ -34,7 +35,6 @@ 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
{
@ -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;
}
@ -156,24 +156,5 @@ bool WifiApNatManager::WriteDataToFile(const std::string &fileName, const std::s
outf.close();
return true;
}
bool WifiApNatManager::ExecCommand(const std::vector<std::string> &vecCommandArg) const
{
std::string command;
for (auto iter : vecCommandArg) {
command += iter;
command += " ";
}
WIFI_LOGE("exec cmd: [%{private}s]", command.c_str());
int ret = system(command.c_str());
if (ret == -1 || ret == SYSTEM_NOT_EXECUTED) {
WIFI_LOGE("exec failed. cmd: %{private}s, error:%{public}d.", command.c_str(), errno);
return false;
}
return true;
}
} // namespace Wifi
} // namespace OHOS

View File

@ -1,5 +1,5 @@
/*
* Copyright (C) 2021 Huawei Device Co., Ltd.
* Copyright (C) 2021-2022 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.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<std::string> &vecCommandArg) const;
};
} // namespace Wifi
} // namespace OHOS

View File

@ -1,5 +1,5 @@
/*
* Copyright (C) 2021 Huawei Device Co., Ltd.
* Copyright (C) 2021-2022 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.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,6 +28,7 @@
#include "define.h"
#include "wifi_dumper.h"
#include "wifi_common_util.h"
#include "wifi_protect_manager.h"
DEFINE_WIFILOG_LABEL("WifiDeviceServiceImpl");
namespace OHOS {
@ -642,6 +643,12 @@ ErrCode WifiDeviceServiceImpl::GetDeviceMacAddress(std::string &result)
return WIFI_OPT_SUCCESS;
}
bool WifiDeviceServiceImpl::SetLowLatencyMode(bool enabled)
{
WIFI_LOGI("SetLowLatencyMode");
return WifiProtectManager::GetInstance().SetLowLatencyMode(enabled);
}
ErrCode WifiDeviceServiceImpl::CheckCanEnableWifi(void)
{
if (WifiPermissionUtils::VerifySetWifiInfoPermission() == PERMISSION_DENIED) {

View File

@ -1,5 +1,5 @@
/*
* Copyright (C) 2021 Huawei Device Co., Ltd.
* Copyright (C) 2021-2022 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
@ -100,6 +100,8 @@ public:
ErrCode GetDeviceMacAddress(std::string &result) override;
bool SetLowLatencyMode(bool enabled) override;
int32_t Dump(int32_t fd, const std::vector<std::u16string>& args) override;
private:

View File

@ -1,5 +1,5 @@
/*
* Copyright (C) 2021 Huawei Device Co., Ltd.
* Copyright (C) 2021-2022 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
@ -65,6 +65,7 @@ void WifiDeviceStub::InitHandleMap()
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;
return;
}
@ -611,5 +612,14 @@ 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));
}
} // namespace Wifi
} // namespace OHOS

View File

@ -1,5 +1,5 @@
/*
* Copyright (C) 2021 Huawei Device Co., Ltd.
* Copyright (C) 2021-2022 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.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
@ -65,6 +66,7 @@ private:
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);
private:
void ReadWifiDeviceConfig(MessageParcel &data, WifiDeviceConfig &config);

View File

@ -0,0 +1,793 @@
/*
* 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_cfg.h"
#include <random>
#include <sstream>
#include "wifi_logger.h"
DEFINE_WIFILOG_P2P_LABEL("WifiHid2dCfg");
namespace OHOS {
namespace Wifi {
static constexpr int INVALID_VALUE_OR_TYPE = -1;
static constexpr int INDEX_START = 0;
static constexpr int INDEX_LENGTH = 1;
static constexpr int INDEX_VALUE = 2;
static constexpr int TYPE_VERSION = 1;
static constexpr int TYPE_P2P_CHANNEL_OPT = 2;
static constexpr int TYPE_DBDC = 3;
static constexpr int TYPE_CSA = 4;
static constexpr int TYPE_RADAR_DETECT = 5;
static constexpr int TYPE_CREATE_DFS_CHANNEL = 6;
static constexpr int TYPE_CREATE_INDOOR_CHANNEL = 7;
static constexpr int TYPE_CURRENT_STA_CHANNEL = 8;
static constexpr int TYPE_CURRENT_AP_IS_PORTAL = 9;
static constexpr int TYPE_CURRENT_AP_SSID = 10;
static constexpr int TYPE_CURRENT_AP_BSSID = 11;
static constexpr int TYPE_CURRENT_STA_HAS_INTERNET = 12;
static constexpr int TYPE_P2P_SUPPORT_CHANNEL = 13;
static constexpr int TYPE_CURRENT_AP_PASSWORD = 14;
static constexpr int TYPE_CURRENT_AP_SECURITY_TYPE = 15;
static constexpr int TYPE_CURRENT_AP_ROUTE_TYPE = 16;
static constexpr int TYPE_DEVICE_TYPE = 17;
static constexpr int TYPE_CURRENT_SESSION_ID_TYPE = 18;
static constexpr int TYPE_STA_STATE_FOR_CALLBACK = 1;
static constexpr int TYPE_STA_CHANNEL_FOR_CALLBACK = 2;
static constexpr int TYPE_AP_SSID_FOR_CALLBACK = 3;
static constexpr int TYPE_AP_BSSID_FOR_CALLBACK = 4;
static constexpr int LENGTH_OFFSET = 1;
static constexpr int VALUE_OFFSET = 2;
static constexpr int NORMAL_TYPE_LENGTH = 1; // Most scenes of length(length) in Tlv is 1
static constexpr int TYPE_AND_LENGTH = 2; // Most scenes of length(type + length) is 2
static constexpr int TYPICAL_TLV_LENGTH = 3; // Most scenes of length(tpye + length +value) is 3
static constexpr int MAX_SSID_LENGTH = 32;
static constexpr int MAX_PASSWORD_LENGTH = 64;
static constexpr int BSSID_LENGTH = 6;
static constexpr int BYTE_MASK = 0xFF;
static constexpr int MAX_BYTES = 255;
static constexpr int THE_NUM_FROM_CH1_TO_CH11 = 11;
static constexpr int DBAC_VERSION = 2;
static constexpr int SESSION_ID_LENGTH = 20;
static constexpr int CHANNEL_12 = 12;
DeviceWifiInfo::DeviceWifiInfo()
{
m_version = DBAC_VERSION;
m_isChooseP2pChannelOpt = false;
m_isSupportDbdc = false;
m_isSupportCsa = false;
m_isP2pSupportRadarDetect = false;
m_isP2pSupportDfsChannel = false;
m_isP2pSupportIndoorChannel = false;
m_isPortalAp = false;
m_staChannel = 0;
m_currentApSsid = "";
m_currentApBssid = "";
m_isCurrentApHasInternet = false;
m_pwd = "";
m_sessionId = "";
m_securityType = INVALID_VALUE_OR_TYPE;
m_routerType = INVALID_VALUE_OR_TYPE;
m_deviceType = DeviceClass::Default;
}
DeviceWifiInfo::~DeviceWifiInfo()
{
}
DeviceClass DeviceWifiInfo::GetDeviceClass()
{
/* Read from configuration items */
return DeviceClass::Default;
}
void DeviceWifiInfo::UpdateDeviceCapability()
{
m_isChooseP2pChannelOpt = false;
m_isSupportDbdc = false;
m_isSupportCsa = false;
m_isP2pSupportRadarDetect = false;
m_isP2pSupportDfsChannel = false;
m_isP2pSupportIndoorChannel = false;
m_deviceType = GetDeviceClass();
}
void DeviceWifiInfo::ResetWifiDeviceCfg()
{
m_staChannel = 0;
m_currentApSsid = "";
m_currentApBssid = "";
m_isCurrentApHasInternet = false;
m_pwd = "";
m_isPortalAp = false;
m_securityType = INVALID_VALUE_OR_TYPE;
m_routerType = INVALID_VALUE_OR_TYPE;
}
int DeviceWifiInfo::GetVersion()
{
WIFI_LOGI("GetVersion : %{public}d ", m_version);
return m_version;
}
void DeviceWifiInfo::SetVerison(int version)
{
if (version <= 0) {
return;
}
m_version = version;
}
bool DeviceWifiInfo::GetCapsOfChooseP2pChannelOpt()
{
return m_isChooseP2pChannelOpt;
}
void DeviceWifiInfo::SetCapsOfChooseP2pChannelOpt(bool isEnabled)
{
m_isChooseP2pChannelOpt = isEnabled;
}
bool DeviceWifiInfo::GetCapsOfDbdc()
{
return m_isSupportDbdc;
}
void DeviceWifiInfo::SetCapsOfDbdc(bool isSupportDbdc)
{
m_isSupportDbdc = isSupportDbdc;
}
bool DeviceWifiInfo::GetCapsOfCsa()
{
return m_isSupportCsa;
}
void DeviceWifiInfo::SetCapsOfCsa(bool isSupportCsa)
{
m_isSupportCsa = isSupportCsa;
}
bool DeviceWifiInfo::GetCapsOfP2pRadarDetect()
{
return m_isP2pSupportRadarDetect;
}
void DeviceWifiInfo::SetCapsOfP2pRadarDetect(bool isP2pSupportRadarDetect)
{
m_isP2pSupportRadarDetect = isP2pSupportRadarDetect;
}
bool DeviceWifiInfo::GetCapsOfP2pDfsChannel() {
return m_isP2pSupportDfsChannel;
}
void DeviceWifiInfo::SetCapsOfP2pDfsChannel(bool isP2pSupportDfsChannel)
{
m_isP2pSupportDfsChannel = isP2pSupportDfsChannel;
}
bool DeviceWifiInfo::GetCapsOfP2pIndoorChannel()
{
return m_isP2pSupportIndoorChannel;
}
void DeviceWifiInfo::SetCapsOfP2pIndoorChannel(bool isP2pSupportIndoorChannel)
{
m_isP2pSupportIndoorChannel = isP2pSupportIndoorChannel;
}
void DeviceWifiInfo::SetStaChannel(int channel)
{
WIFI_LOGI("Set sta channel: %{public}d ", channel);
if (channel < 0) {
return;
}
m_staChannel = channel;
}
int DeviceWifiInfo::GetStaChannel()
{
return m_staChannel;
}
bool DeviceWifiInfo::GetApType()
{
return m_isPortalAp;
}
void DeviceWifiInfo::SetApType(bool isPortalAp)
{
m_isPortalAp = isPortalAp;
}
std::string DeviceWifiInfo::GetCurrentApSsid()
{
return m_currentApSsid;
}
void DeviceWifiInfo::SetCurrentApSsid(const std::string& ssid)
{
m_currentApSsid = ssid;
}
std::string DeviceWifiInfo::GetCurrentApBssid() {
return m_currentApBssid;
}
void DeviceWifiInfo::SetCurrentApBssid(const std::string& bssid)
{
m_currentApBssid = bssid;
}
void DeviceWifiInfo::SetCurrentApHasInternet(bool hasInternet)
{
m_isCurrentApHasInternet = hasInternet;
}
bool DeviceWifiInfo::GetCurrentApHasInternet()
{
return m_isCurrentApHasInternet;
}
std::vector<int> DeviceWifiInfo::GetP2pSupportChannel()
{
return m_P2pSupportChannelList;
}
void DeviceWifiInfo::SetP2pSupportChannel(std::vector<int>& channels)
{
if (channels.empty()) {
return;
}
m_P2pSupportChannelList = channels;
}
std::string DeviceWifiInfo::GetApPwd()
{
return m_pwd;
}
void DeviceWifiInfo::SetApPwd(const std::string& pwd)
{
m_pwd = pwd;
}
int DeviceWifiInfo::GetApSecurityType()
{
return m_securityType;
}
void DeviceWifiInfo::SetApSecurityType(int securityType)
{
m_securityType = securityType;
}
int DeviceWifiInfo::GetRouterType()
{
return m_routerType;
}
std::string DeviceWifiInfo::GenerateSessionId()
{
constexpr int sessionIdSize = 20;
constexpr int hexMaxNum = 15;
std::random_device rd;
std::mt19937 gen(rd());
std::uniform_int_distribution<> dis(0, hexMaxNum);
std::stringstream ss;
ss << std::hex;
for (int i = 0; i != sessionIdSize; ++i) {
ss << dis(gen);
}
m_sessionId = ss.str();
return m_sessionId;
}
std::string DeviceWifiInfo::GetSessionId()
{
return m_sessionId;
}
void DeviceWifiInfo::SetSessionId(std::string sessionId)
{
m_sessionId = sessionId;
}
void DeviceWifiInfo::ClearSessionId()
{
m_sessionId = "";
}
void DeviceWifiInfo::SetRouteType(int routerType)
{
m_routerType = routerType;
}
DeviceClass DeviceWifiInfo::GetDeviceType()
{
return m_deviceType;
}
void DeviceWifiInfo::SetDeviceType(DeviceClass deviceType)
{
m_deviceType = deviceType;
}
int DeviceWifiInfo::GetValueFromType(int type)
{
int value = INVALID_VALUE_OR_TYPE;
switch (type) {
case TYPE_VERSION:
value = GetVersion();
break;
case TYPE_P2P_CHANNEL_OPT:
value = GetCapsOfChooseP2pChannelOpt() ? 1 : 0;
break;
case TYPE_DBDC:
value = GetCapsOfDbdc() ? 1 : 0;
break;
case TYPE_CSA:
value = GetCapsOfCsa() ? 1 : 0;
break;
case TYPE_RADAR_DETECT:
value = GetCapsOfP2pRadarDetect() ? 1 : 0;
break;
case TYPE_CREATE_DFS_CHANNEL:
value = GetCapsOfP2pDfsChannel() ? 1 : 0;
break;
case TYPE_CREATE_INDOOR_CHANNEL:
value = GetCapsOfP2pIndoorChannel() ? 1 : 0;
break;
case TYPE_CURRENT_STA_CHANNEL:
value = GetStaChannel();
break;
case TYPE_CURRENT_AP_IS_PORTAL:
value = GetApType() ? 1 : 0;
break;
default:
WIFI_LOGI("GetValueFromType invalid type = %{public}d", type);
break;
}
return value;
}
void DeviceWifiInfo::SetDeviceCfg(int type, int inputValue)
{
switch (type) {
case TYPE_VERSION:
SetVerison(inputValue);
break;
case TYPE_P2P_CHANNEL_OPT:
SetCapsOfChooseP2pChannelOpt(inputValue == 1);
break;
case TYPE_DBDC:
SetCapsOfDbdc(inputValue == 1);
break;
case TYPE_CSA:
SetCapsOfCsa(inputValue == 1);
break;
case TYPE_RADAR_DETECT:
SetCapsOfP2pRadarDetect(inputValue == 1);
break;
case TYPE_CREATE_DFS_CHANNEL:
SetCapsOfP2pDfsChannel(inputValue == 1);
break;
case TYPE_CREATE_INDOOR_CHANNEL:
SetCapsOfP2pIndoorChannel(inputValue == 1);
break;
case TYPE_CURRENT_STA_CHANNEL:
SetStaChannel(inputValue);
break;
case TYPE_CURRENT_AP_IS_PORTAL:
SetApType(inputValue == 1);
break;
default:
WIFI_LOGI("SetDeviceCfg invalid type = %{public}d", type);
break;
}
}
WifiHid2dCfg::WifiHid2dCfg()
{
}
WifiHid2dCfg::~WifiHid2dCfg()
{
}
WifiHid2dCfg& WifiHid2dCfg::GetInstance()
{
static WifiHid2dCfg inst;
return inst;
}
DeviceWifiInfo WifiHid2dCfg::m_selfDeviceInfo;
DeviceWifiInfo WifiHid2dCfg::m_peerDeviceInfo;
DeviceWifiInfo& WifiHid2dCfg::GetSelfDeviceCfgInfo()
{
return m_selfDeviceInfo;
}
DeviceWifiInfo& WifiHid2dCfg::GetPeerDeviceCfgInfo()
{
return m_peerDeviceInfo;
}
std::string WifiHid2dCfg::ParseStringFromByteArray(char* data, int dataLen, int index, int maxLength)
{
if (data == nullptr || dataLen < index + INDEX_VALUE) {
return "";
}
int length = data[index + INDEX_LENGTH] & BYTE_MASK;
if (length > maxLength + 1) { /* +1 for the end character '\0' of the C-style string */
WIFI_LOGE("invalid length = %{public}d", length);
return "";
}
char* ssidArray = new char[maxLength + 1]; /* +1 for the end character '\0' of the C-style string */
if (ssidArray == nullptr) {
return "";
}
if (memcpy_s(ssidArray, maxLength + 1, data + index + INDEX_VALUE, length) != EOK) {
WIFI_LOGE("parse string from byte array memcpy_s failed!");
delete[] ssidArray;
return "";
}
int needCopylen = FindIndexFromByteArray(ssidArray, maxLength + 1, 0);
std::string s(needCopylen + 1, '\0');
for (int i = 0; i <= needCopylen && i < maxLength + 1; ++i) {
s[i] = ssidArray[i];
}
delete[] ssidArray;
return s;
}
/** 2.4g channel count from channel 1 to channel 11 */
void WifiHid2dCfg::ParseP2pSupportChannelFromByteArray(char* data, int dataLen,
int index, std::vector<int>& p2pSupportChannels)
{
if (data == nullptr || dataLen < (index + INDEX_VALUE)) {
return;
}
int length = data[index + LENGTH_OFFSET] & BYTE_MASK;
if (dataLen < (index + length)) {
return;
}
// To save space, channels 1 to 11 are not carried when the peer information is obtained.
// channels 1 to 11 are supported by all countries, p2pSupportChannels should include it
int i = 0;
for (i = 0; i < THE_NUM_FROM_CH1_TO_CH11; i++) {
p2pSupportChannels.emplace_back(i + 1);
}
for (int j = 0; j < data[index + LENGTH_OFFSET]; j++) {
p2pSupportChannels.emplace_back(data[index + VALUE_OFFSET + j] & BYTE_MASK);
}
std::sort(p2pSupportChannels.begin(), p2pSupportChannels.end());
}
void WifiHid2dCfg::HandlePeerApPassword()
{
}
void WifiHid2dCfg::HandleTlvData(int type, char* cfgData, int cfgDataLen, int index)
{
std::vector<int> p2pSupportChannels;
switch (type) {
case TYPE_CURRENT_AP_SSID:
m_peerDeviceInfo.SetCurrentApSsid(ParseStringFromByteArray(cfgData, cfgDataLen, index, MAX_SSID_LENGTH));
break;
case TYPE_CURRENT_AP_BSSID:
unsigned char macAddr[BSSID_LENGTH];
if (memcpy_s(macAddr, BSSID_LENGTH, cfgData + index + INDEX_VALUE, BSSID_LENGTH) != EOK) {
return;
}
m_peerDeviceInfo.SetCurrentApBssid(MacArrayToStr(macAddr));
break;
case TYPE_CURRENT_STA_HAS_INTERNET:
m_peerDeviceInfo.SetCurrentApHasInternet((cfgData[index + VALUE_OFFSET] & BYTE_MASK) == 0x01);
break;
case TYPE_P2P_SUPPORT_CHANNEL:
ParseP2pSupportChannelFromByteArray(cfgData, cfgDataLen, index, p2pSupportChannels);
m_peerDeviceInfo.SetP2pSupportChannel(p2pSupportChannels);
break;
case TYPE_CURRENT_AP_PASSWORD:
m_peerDeviceInfo.SetApPwd(ParseStringFromByteArray(cfgData, cfgDataLen, index, MAX_PASSWORD_LENGTH));
break;
case TYPE_CURRENT_AP_SECURITY_TYPE:
m_peerDeviceInfo.SetApSecurityType(cfgData[index + VALUE_OFFSET] & BYTE_MASK);
break;
case TYPE_CURRENT_AP_ROUTE_TYPE:
m_peerDeviceInfo.SetRouteType(cfgData[index + VALUE_OFFSET] & BYTE_MASK);
break;
case TYPE_DEVICE_TYPE:
m_peerDeviceInfo.SetDeviceType(DeviceClass(cfgData[index + VALUE_OFFSET] & BYTE_MASK));
break;
case TYPE_CURRENT_SESSION_ID_TYPE:
m_peerDeviceInfo.SetSessionId(ParseStringFromByteArray(cfgData, cfgDataLen, index, SESSION_ID_LENGTH));
break;
default:
WIFI_LOGE("handle tlv data invalid type = %{public}d", type);
return;
}
}
int WifiHid2dCfg::ParsePeerDeviceCfgInfo(PeerCfgType cfgType, char* cfgData, int cfgDataLen)
{
if (cfgData == nullptr || cfgDataLen == 0) {
return INVALID_VALUE_OR_TYPE;
}
if (cfgType != PeerCfgType::TYPE_OF_SET_PEER_CONFIG) {
return INVALID_VALUE_OR_TYPE;
}
m_peerDeviceInfo.ResetWifiDeviceCfg();
int length = cfgData[INDEX_START] & BYTE_MASK;
if (cfgDataLen != length) {
return INVALID_VALUE_OR_TYPE;
}
WIFI_LOGI("parse peer device cfg length = %{public}d", length);
for (int i = 1; i < length;) {
if ((i + LENGTH_OFFSET) >= length) {
break;
}
int valueLength = cfgData[i + LENGTH_OFFSET] & BYTE_MASK;
if ((i + valueLength + TYPE_AND_LENGTH) > length) {
break;
}
int type = cfgData[i];
int valueIndex = i + VALUE_OFFSET;
if (type > 0 && type <= TYPE_CURRENT_AP_IS_PORTAL && valueIndex < length) {
m_peerDeviceInfo.SetDeviceCfg(type, cfgData[valueIndex] & BYTE_MASK);
i += valueLength + TYPE_AND_LENGTH;
continue;
}
HandleTlvData(type, cfgData, cfgDataLen, i);
i += valueLength + TYPE_AND_LENGTH;
}
if (m_peerDeviceInfo.GetApSecurityType() != INVALID_VALUE_OR_TYPE) {
HandlePeerApPassword();
}
return 0;
}
int WifiHid2dCfg::ParsePeerDeviceStaChanngeInfo(PeerCfgType cfgType, char* cfgData, int cfgDataLen)
{
if (cfgData == nullptr || cfgDataLen == 0) {
return INVALID_VALUE_OR_TYPE;
}
if (cfgType != PeerCfgType::TYPE_OF_SET_PEER_STATE_CHANGE) {
return INVALID_VALUE_OR_TYPE;
}
if (cfgDataLen != cfgData[0]) {
return INVALID_VALUE_OR_TYPE;
}
for (int i = 1; i < cfgDataLen;) {
int type = cfgData[i];
switch (type) {
case TYPE_STA_STATE_FOR_CALLBACK:
case TYPE_STA_CHANNEL_FOR_CALLBACK:
case TYPE_AP_SSID_FOR_CALLBACK:
case TYPE_AP_BSSID_FOR_CALLBACK:
default:
break;
}
i += (cfgData[i + LENGTH_OFFSET] & BYTE_MASK) + TYPE_AND_LENGTH;
}
return 0;
}
int WifiHid2dCfg::FindIndexFromByteArray(char* data, int dataLen, int value)
{
if (data == nullptr) {
return 0;
}
int i = 0;
for (i = 0; i < dataLen; i++) {
if (data[i] == value) {
return i;
}
}
return i;
}
int WifiHid2dCfg::SetBssidByte(int typeBssidValue, char* dataArray, int dataArrayLen, int offset)
{
if (dataArray == nullptr) {
return 0;
}
int length = INDEX_VALUE + BSSID_LENGTH;
if (dataArrayLen < (offset + length)) {
return 0;
}
dataArray[offset] = (char)typeBssidValue;
std::string bssid = m_selfDeviceInfo.GetCurrentApBssid();
dataArray[offset + INDEX_LENGTH] = BSSID_LENGTH;
unsigned char macByteAddr[BSSID_LENGTH] = { 0 };
if (!bssid.empty()) {
if (MacStrToArray(bssid, macByteAddr) != EOK) {
return 0;
}
}
if (memcpy_s(dataArray + offset + INDEX_VALUE, dataArrayLen - (offset + INDEX_VALUE),
macByteAddr, BSSID_LENGTH) != EOK) {
return 0;
}
return length;
}
int WifiHid2dCfg::SetP2pSupportChannelByte(char* dataArray, int dataArrayLen, int offset)
{
if (dataArray == nullptr || dataArrayLen < (offset + INDEX_LENGTH)) {
return 0;
}
std::vector<int> p2pSupportChannelList = m_selfDeviceInfo.GetP2pSupportChannel();
if (p2pSupportChannelList.empty() || (p2pSupportChannelList.size() - THE_NUM_FROM_CH1_TO_CH11 <= 0)) {
WIFI_LOGI("Channel list is invalid.");
return 0;
}
dataArray[offset] = TYPE_P2P_SUPPORT_CHANNEL;
int length = p2pSupportChannelList.size() - THE_NUM_FROM_CH1_TO_CH11;
dataArray[offset + INDEX_LENGTH] = (char)length;
if (dataArrayLen < (offset + length + INDEX_VALUE)) {
return 0;
}
int index = 0;
for (int channel : p2pSupportChannelList) {
// To save space, channels 1 to 11 are not carried when exchanging information with the peer device for
// Channels 1 to 11 are supported by all countries and dataArray should not contains channel 1 to 11
if (channel >= CHANNEL_12) {
dataArray[offset + INDEX_VALUE + index] = (char)channel;
index++;
}
}
return length + VALUE_OFFSET;
}
int WifiHid2dCfg::BuildTlvForIntVal(int type, int Value, char* tlvData, int tlvDataLen, int offset)
{
if (tlvData == nullptr) {
return 0;
}
if (tlvDataLen <= (offset + INDEX_VALUE)) {
return 0;
}
tlvData[offset] = (char)type;
tlvData[offset + INDEX_LENGTH] = NORMAL_TYPE_LENGTH;
tlvData[offset + INDEX_VALUE] = (char)Value;
return TYPICAL_TLV_LENGTH;
}
int WifiHid2dCfg::BuildTlvForStrVal(int type, std::string value, char* tlvData, int tlvDataLen, int offset)
{
if (tlvData == nullptr) {
return 0;
}
if (value.empty() || (type == TYPE_CURRENT_AP_PASSWORD && value.length() > MAX_PASSWORD_LENGTH) ||
(type == TYPE_CURRENT_AP_SSID && value.length() > MAX_SSID_LENGTH)) {
tlvData[offset] = (char)type;
tlvData[offset + LENGTH_OFFSET] = (char)NORMAL_TYPE_LENGTH;
tlvData[offset + VALUE_OFFSET] = 0;
return TYPICAL_TLV_LENGTH;
}
/* +1 for the end character '\0' of the C-style string */
if (tlvDataLen < offset + value.length() + 1) {
return 0;
}
tlvData[offset] = (char)type;
/* +1 for the end character '\0' of the C-style string */
tlvData[offset + LENGTH_OFFSET] = (char)value.length() + 1;
if (memcpy_s(tlvData + offset + VALUE_OFFSET, tlvDataLen - (offset + VALUE_OFFSET),
value.c_str(), value.length() + 1) != EOK) {
return 0;
}
return tlvData[offset + LENGTH_OFFSET] + TYPE_AND_LENGTH;
}
void WifiHid2dCfg::HandlePeerStaStateChange(char* data, int dataLen, int index)
{
if (data == nullptr || dataLen <= (index + INDEX_VALUE)) {
return;
}
if (data[index + INDEX_VALUE] == 0) { // 0 : disconnect
m_peerDeviceInfo.ResetWifiDeviceCfg();
}
}
void WifiHid2dCfg::GetSelfDeviceCfg(SelfCfgType cfgType, char cfgInfo[CFG_DATA_MAX_BYTES], int& getDatValidLen)
{
getDatValidLen = 0;
if ((cfgType != SelfCfgType::TYPE_OF_GET_SELF_CONFIG &&
cfgType != SelfCfgType::TYPE_OF_GET_SELF_CONFIG_WITH_PASSWORD)) {
return;
}
char* totalCfgInfo = new char[MAX_BYTES];
if (totalCfgInfo == nullptr) {
return;
}
if (memset_s(totalCfgInfo, MAX_BYTES, 0, MAX_BYTES) != EOK) {
delete[] totalCfgInfo;
return;
}
int i = 1;
int position = 1;
for (i = 1; i <= TYPE_CURRENT_AP_IS_PORTAL; i++) {
position += BuildTlvForIntVal(i, m_selfDeviceInfo.GetValueFromType(i), totalCfgInfo, MAX_BYTES, position);
}
std::string ssid = m_selfDeviceInfo.GetCurrentApSsid();
position += BuildTlvForStrVal(TYPE_CURRENT_AP_SSID, ssid, totalCfgInfo, MAX_BYTES, position);
position += SetBssidByte(TYPE_CURRENT_AP_BSSID, totalCfgInfo, MAX_BYTES, position);
position += BuildTlvForIntVal(TYPE_CURRENT_STA_HAS_INTERNET, m_selfDeviceInfo.GetCurrentApHasInternet() ? 1 : 0,
totalCfgInfo, MAX_BYTES, position);
position += SetP2pSupportChannelByte(totalCfgInfo, MAX_BYTES, position);
if (cfgType == SelfCfgType::TYPE_OF_GET_SELF_CONFIG_WITH_PASSWORD) {
std::string pwd = m_selfDeviceInfo.GetApPwd();
position += BuildTlvForStrVal(TYPE_CURRENT_AP_PASSWORD, pwd, totalCfgInfo, MAX_BYTES, position);
position += BuildTlvForIntVal(TYPE_CURRENT_AP_SECURITY_TYPE, m_selfDeviceInfo.GetApSecurityType(),
totalCfgInfo, MAX_BYTES, position);
}
position += BuildTlvForIntVal(TYPE_CURRENT_AP_ROUTE_TYPE, m_selfDeviceInfo.GetRouterType(),
totalCfgInfo, MAX_BYTES, position);
position += BuildTlvForIntVal(TYPE_DEVICE_TYPE, static_cast<int>(m_selfDeviceInfo.GetDeviceType()),
totalCfgInfo, MAX_BYTES, position);
std::string sessionID = m_selfDeviceInfo.GenerateSessionId();
position += BuildTlvForStrVal(TYPE_CURRENT_SESSION_ID_TYPE, sessionID, totalCfgInfo, MAX_BYTES, position);
totalCfgInfo[INDEX_START] = (char)position;
getDatValidLen = totalCfgInfo[INDEX_START] & BYTE_MASK;
WIFI_LOGI("self device cfg length = %{public}d", getDatValidLen);
if (getDatValidLen <= 0) {
getDatValidLen = 0;
delete[] totalCfgInfo;
return;
}
if (memcpy_s(cfgInfo, CFG_DATA_MAX_BYTES, totalCfgInfo, getDatValidLen) != EOK) {
WIFI_LOGI("GetSelfDeviceCfg memcpy_s failed!");
getDatValidLen = 0;
}
delete[] totalCfgInfo;
}
int WifiHid2dCfg::Hid2dSetPeerWifiCfgInfo(PeerCfgType cfgType, char cfgInfo[CFG_DATA_MAX_BYTES], int setDataValidLen)
{
WIFI_LOGI("Hid2dSetPeerWifiCfgInfo cfgType = %{public}d", cfgType);
if (cfgType == PeerCfgType::TYPE_OF_SET_PEER_CONFIG) {
return ParsePeerDeviceCfgInfo(cfgType, cfgInfo, setDataValidLen);
}
else if (cfgType == PeerCfgType::TYPE_OF_SET_PEER_STATE_CHANGE) {
return ParsePeerDeviceStaChanngeInfo(cfgType, cfgInfo, setDataValidLen);
} else {
return INVALID_VALUE_OR_TYPE;
}
}
} // namespace Wifi
} // namespace OHOS

View File

@ -0,0 +1,256 @@
/*
* 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_CFG_H
#define OHOS_WIFI_HID2D_CFG_H
#include <vector>
#include <string>
#include "wifi_common_util.h"
#include "wifi_hid2d_msg.h"
namespace OHOS {
namespace Wifi {
enum class DeviceType {
/** phone device type id */
DEVICE_TYPE_PHONE_ID = 0,
/** pad device type id */
DEVICE_TYPE_PAD_ID = 1,
/** pad tv type id */
DEVICE_TYPE_TV_ID = 2,
/** pad pc type id */
DEVICE_TYPE_PC_ID = 3,
/** pad display type id */
DEVICE_TYPE_DISPLAY_ID = 4,
/** pad car type id */
DEVICE_TYPE_CAR_ID = 5,
};
enum class DeviceClass {
Default,
TABLET,
TV,
CAR
};
class DeviceWifiInfo {
public:
DeviceWifiInfo();
~DeviceWifiInfo();
DeviceClass GetDeviceClass();
void UpdateDeviceCapability();
void ResetWifiDeviceCfg();
int GetVersion();
void SetVerison(int version);
bool GetCapsOfChooseP2pChannelOpt();
void SetCapsOfChooseP2pChannelOpt(bool isEnabled);
bool GetCapsOfDbdc();
void SetCapsOfDbdc(bool isSupportDbdc);
bool GetCapsOfCsa();
void SetCapsOfCsa(bool isSupportCsa);
bool GetCapsOfP2pRadarDetect();
void SetCapsOfP2pRadarDetect(bool isP2pSupportRadarDetect);
bool GetCapsOfP2pDfsChannel();
void SetCapsOfP2pDfsChannel(bool isP2pSupportDfsChannel);
bool GetCapsOfP2pIndoorChannel();
void SetCapsOfP2pIndoorChannel(bool isP2pSupportIndoorChannel);
void SetStaChannel(int channel);
int GetStaChannel();
bool GetApType();
void SetApType(bool isPortalAp);
std::string GetCurrentApSsid();
void SetCurrentApSsid(const std::string& ssid);
std::string GetCurrentApBssid();
void SetCurrentApBssid(const std::string& bssid);
void SetCurrentApHasInternet(bool hasInternet);
bool GetCurrentApHasInternet();
std::vector<int> GetP2pSupportChannel();
void SetP2pSupportChannel(std::vector<int>& channels);
std::string GetApPwd();
void SetApPwd(const std::string& pwd);
int GetApSecurityType();
void SetApSecurityType(int securityType);
int GetRouterType();
std::string GenerateSessionId();
std::string GetSessionId();
/**
* set SessionId of current cast service
*
* @param sessionId input sessionId generated by p2p go
*/
void SetSessionId(std::string sessionId);
/**
* clear SessionId of current cast service
*/
void ClearSessionId();
void SetRouteType(int routerType);
DeviceClass GetDeviceType();
/**
* set Go or Gc device type
*
* @param deviceType input Go or Gc device type
*/
void SetDeviceType(DeviceClass deviceType);
/**
* get device config value from type
*
* @param type device wifi config type
* @return the type value
*/
int GetValueFromType(int type);
/**
* set device config info according type
*
* @param type device wifi config type
* @param inputValue the value of type
*/
void SetDeviceCfg(int type, int inputValue);
private:
int m_version; // dual band adaptive concurrent
bool m_isChooseP2pChannelOpt;
bool m_isSupportDbdc;
bool m_isSupportCsa;
bool m_isP2pSupportRadarDetect;
bool m_isP2pSupportDfsChannel;
bool m_isP2pSupportIndoorChannel;
bool m_isPortalAp;
int m_staChannel;
std::string m_currentApSsid;
std::string m_currentApBssid;
bool m_isCurrentApHasInternet;
std::vector<int> m_P2pSupportChannelList;
std::string m_pwd;
std::string m_sessionId;
int m_securityType;
int m_routerType;
DeviceClass m_deviceType;
};
class WifiHid2dCfg {
public:
static WifiHid2dCfg& GetInstance();
DeviceWifiInfo& GetSelfDeviceCfgInfo();
DeviceWifiInfo& GetPeerDeviceCfgInfo();
/**
* get self device configuration in TLV format:type + length + value
*
* @param cfgType self wifi configuration type
* @param cfgInfo configuration information
* @param getDatValidLen configuration valid length
*/
void GetSelfDeviceCfg(SelfCfgType cfgType, char cfgInfo[CFG_DATA_MAX_BYTES], int& getDatValidLen);
/**
* set peer wifi p2p config info
*
* @param cfgType self wifi configuration type
* @param cfgData byte array
* @param setDataValidLen the valid length of "cfgData"
* @return 0: success, -1: fail
*/
int Hid2dSetPeerWifiCfgInfo(PeerCfgType cfgType, char cfgInfo[CFG_DATA_MAX_BYTES], int setDataValidLen);
private:
WifiHid2dCfg();
~WifiHid2dCfg();
std::string ParseStringFromByteArray(char* data, int dataLen, int index, int maxLength);
/** 2.4g channel count from channel 1 to channel 11 */
void ParseP2pSupportChannelFromByteArray(char* data, int dataLen, int index, std::vector<int>& p2pSupportChannels);
void HandlePeerApPassword();
void HandleTlvData(int type, char* cfgData, int cfgDataLen, int index);
int ParsePeerDeviceCfgInfo(PeerCfgType cfgType, char* cfgData, int cfgDataLen);
int ParsePeerDeviceStaChanngeInfo(PeerCfgType cfgType, char* cfgData, int cfgDataLen);
/**
* find the value of index in byte array
*
* @param data byte array
* @param value intput the value to find index
* @return index in byte array
*/
int FindIndexFromByteArray(char* data, int dataLen, int value);
int SetBssidByte(int typeBssidValue, char* dataArray, int dataArrayLen, int offset);
int SetP2pSupportChannelByte(char* dataArray, int dataArrayLen, int offset);
int BuildTlvForIntVal(int type, int Value, char* tlvData, int tlvDataLen, int offset);
int BuildTlvForStrVal(int type, std::string value, char* tlvData, int tlvDataLen, int offset);
void HandlePeerStaStateChange(char* data, int dataLen, int index);
private:
static DeviceWifiInfo m_selfDeviceInfo;
static DeviceWifiInfo m_peerDeviceInfo;
};
} // namespace Wifi
} // namespace OHOS
#endif

View File

@ -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.
*/
#include "wifi_hid2d_service_utils.h"
#include <regex>
#include <shared_mutex>
#include "dhcp_define.h"
#include "wifi_logger.h"
DEFINE_WIFILOG_P2P_LABEL("Hid2dIpPool");
namespace OHOS {
namespace Wifi {
std::list<std::string> IpPool::ipList;
std::map<std::string, std::string> 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)
{
std::unique_lock<std::shared_mutex> 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)
{
std::unique_lock<std::shared_mutex> 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)
{
std::unique_lock<std::shared_mutex> 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);
}
}
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

View File

@ -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.
*/
#ifndef OHOS_WIFI_HID2D_SERVICE_UTILS_H
#define OHOS_WIFI_HID2D_SERVICE_UTILS_H
#include <string>
#include <list>
#include <map>
#include <atomic>
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);
private:
static bool IsValidIp(const std::string& ip);
static std::list<std::string> ipList;
static std::map<std::string, std::string> 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

View File

@ -1,5 +1,5 @@
/*
* Copyright (C) 2021 Huawei Device Co., Ltd.
* Copyright (C) 2021-2022 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
@ -266,6 +266,8 @@ 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);
@ -314,6 +316,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");
@ -418,6 +422,8 @@ void WifiInternalEventDispatcher::InvokeHotspotCallbacks(const WifiEventCallback
void WifiInternalEventDispatcher::DealHotspotCallbackMsg(
WifiInternalEventDispatcher &instance, const WifiEventCallbackMsg &msg)
{
WIFI_LOGI("WifiInternalEventDispatcher:: Deal Hotspot Event Callback Msg: %{public}d", msg.msgCode);
auto callback = instance.GetSingleHotspotCallback();
if (callback != nullptr) {
switch (msg.msgCode) {
@ -456,6 +462,7 @@ void WifiInternalEventDispatcher::SendP2pCallbackMsg(sptr<IWifiP2pCallback> &cal
if (callback == nullptr) {
return;
}
switch (msg.msgCode) {
case WIFI_CBK_MSG_P2P_STATE_CHANGE:
callback->OnP2pStateChanged(msg.msgData);
@ -491,6 +498,8 @@ void WifiInternalEventDispatcher::SendP2pCallbackMsg(sptr<IWifiP2pCallback> &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);

View File

@ -24,6 +24,7 @@ ohos_shared_library("wifi_p2p_service") {
"//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",
"//foundation/communication/wifi/services/wifi_standard/wifi_framework/wifi_manage/wifi_hid2d_service_utils.cpp",
"authorizing_negotiation_request_state.cpp",
"group_formed_state.cpp",
"group_negotiation_state.cpp",

View File

@ -1,5 +1,5 @@
/*
* Copyright (C) 2021 Huawei Device Co., Ltd.
* Copyright (C) 2021-2022 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.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"
@ -100,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;
@ -142,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());
@ -204,12 +207,11 @@ bool GroupFormedState::ProcessDisconnectEvt(const InternalMessage &msg) const
}
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);
return EXECUTED;
}

View File

@ -1,5 +1,5 @@
/*
* Copyright (C) 2021 Huawei Device Co., Ltd.
* Copyright (C) 2021-2022 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.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

View File

@ -1,5 +1,5 @@
/*
* Copyright (C) 2021 Huawei Device Co., Ltd.
* Copyright (C) 2021-2022 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
@ -129,6 +129,7 @@ bool GroupNegotiationState::ProcessGroupStartedEvt(InternalMessage &msg) const
WIFI_LOGD("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;

View File

@ -1,5 +1,5 @@
/*
* Copyright (C) 2021 Huawei Device Co., Ltd.
* Copyright (C) 2021-2022 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.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 {
@ -216,6 +218,23 @@ public:
* @return ErrCode - operate 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 - operate 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 - operate result
*/
virtual ErrCode Hid2dConnect(const Hid2dConnectConfig& config) = 0;
};
} // namespace Wifi
} // namespace OHOS

View File

@ -1,5 +1,5 @@
/*
* Copyright (C) 2021 Huawei Device Co., Ltd.
* Copyright (C) 2021-2022 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.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
@ -107,6 +108,8 @@ enum class P2P_STATE_MACHINE_CMD {
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

View File

@ -1,5 +1,5 @@
/*
* Copyright (C) 2021 Huawei Device Co., Ltd.
* Copyright (C) 2021-2022 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.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 <string>
#include "wifi_logger.h"
@ -48,6 +49,7 @@ void P2pEnabledState::GoInState()
static_cast<int>(P2P_STATE_MACHINE_CMD::CMD_START_LISTEN), defaultPeriodTime, defaultIntervalTime);
}
} else {
WIFI_LOGE("P2pSettingsInitialization Failed, Start Disable P2P!");
p2pStateMachine.SendMessage(static_cast<int>(P2P_STATE_MACHINE_CMD::CMD_P2P_DISABLE));
}
}
@ -101,7 +103,7 @@ void P2pEnabledState::Init()
}
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);
@ -137,7 +139,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);
@ -153,13 +155,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);
@ -207,7 +209,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;
}
@ -255,10 +257,15 @@ bool P2pEnabledState::P2pConfigInitialization()
WIFI_LOGE("Failed to set the SSID prefix");
}
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();
@ -290,15 +297,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();
@ -327,9 +334,7 @@ bool P2pEnabledState::P2pSettingsInitialization()
result = false;
}
groupManager.UpdateGroupsNetwork(wpaGroups);
p2pStateMachine.UpdatePersistentGroups();
return result;
}
@ -375,7 +380,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;
@ -408,7 +413,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);
@ -544,7 +549,7 @@ bool P2pEnabledState::ProcessCmdSetDeviceName(InternalMessage &msg) const
}
bool P2pEnabledState::ProcessCmdSetWfdInfo(InternalMessage &msg) const
{
WIFI_LOGI("recv CMD: %{public}d", msg.GetMessageName());
WIFI_LOGI("P2P ProcessCmdSetWfdInfo recv CMD: %{public}d", msg.GetMessageName());
WifiP2pWfdInfo wfdInfo;
if (!msg.GetMessageObj(wfdInfo)) {
WIFI_LOGE("Failed to obtain wfd information.");
@ -567,7 +572,7 @@ bool P2pEnabledState::ProcessCmdSetWfdInfo(InternalMessage &msg) const
bool P2pEnabledState::ProcessCmdCancelConnect(InternalMessage &msg) const
{
WIFI_LOGI("recv CMD: %{public}d", msg.GetMessageName());
WIFI_LOGI("P2P ProcessCmdCancelConnect recv CMD: %{public}d", msg.GetMessageName());
p2pStateMachine.BroadcastActionResult(P2pActionCallback::P2pDisConnect, ErrCode::WIFI_OPT_FAILED);
return EXECUTED;
}

View File

@ -1,5 +1,5 @@
/*
* Copyright (C) 2021 Huawei Device Co., Ltd.
* Copyright (C) 2021-2022 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.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_group_operating_state.h"
#include "wifi_p2p_hal_interface.h"
#include "p2p_state_machine.h"
@ -29,6 +30,7 @@ P2pGroupOperatingState::P2pGroupOperatingState(P2pStateMachine &stateMachine, Wi
groupManager(groupMgr),
deviceManager(deviceMgr)
{}
void P2pGroupOperatingState::GoInState()
{
WIFI_LOGI(" GoInState");
@ -56,6 +58,8 @@ 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
@ -108,6 +112,7 @@ bool P2pGroupOperatingState::ProcessCmdCreateGroup(const InternalMessage &msg) c
}
return EXECUTED;
}
bool P2pGroupOperatingState::ProcessGroupStartedEvt(const InternalMessage &msg) const
{
p2pStateMachine.StopTimer(static_cast<int>(P2P_STATE_MACHINE_CMD::CREATE_GROUP_TIMED_OUT));
@ -155,6 +160,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;
@ -166,6 +172,7 @@ 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());
@ -190,10 +197,12 @@ bool P2pGroupOperatingState::ProcessGroupRemovedEvt(const InternalMessage &msg)
}
WifiP2pGroupInfo invalidGroup;
groupManager.SetCurrentGroup(invalidGroup);
SharedLinkManager::SetSharedLinkCount(SHARED_LINKE_COUNT_ON_DISCONNECTED);
p2pStateMachine.ChangeConnectedStatus(P2pConnectedState::P2P_DISCONNECTED);
p2pStateMachine.SwitchState(&p2pStateMachine.p2pIdleState);
return EXECUTED;
}
bool P2pGroupOperatingState::ProcessCmdDisable(const InternalMessage &msg) const
{
/**
@ -202,6 +211,7 @@ bool P2pGroupOperatingState::ProcessCmdDisable(const InternalMessage &msg) const
p2pStateMachine.DelayMessage(&msg);
return ProcessCmdRemoveGroup(msg);
}
bool P2pGroupOperatingState::ProcessCmdRemoveGroup(const InternalMessage &msg) const
{
/**
@ -248,6 +258,7 @@ bool P2pGroupOperatingState::ProcessCmdRemoveGroup(const InternalMessage &msg) c
}
return EXECUTED;
}
bool P2pGroupOperatingState::ProcessCmdDeleteGroup(const InternalMessage &msg) const
{
/**
@ -285,6 +296,27 @@ bool P2pGroupOperatingState::ProcessCmdDeleteGroup(const InternalMessage &msg) c
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<int>(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) {

View File

@ -1,5 +1,5 @@
/*
* Copyright (C) 2021 Huawei Device Co., Ltd.
* Copyright (C) 2021-2022 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.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
@ -120,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<P2P_STATE_MACHINE_CMD, ProcessFun> mProcessFunMap;

View File

@ -1,5 +1,5 @@
/*
* Copyright (C) 2021 Huawei Device Co., Ltd.
* Copyright (C) 2021-2022 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.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,10 @@ 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));
}
bool P2pIdleState::ProcessCmdStopDiscPeer(InternalMessage &msg) const
@ -131,6 +136,23 @@ 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 (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());
@ -246,6 +268,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;
@ -310,6 +333,13 @@ 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::ExecuteStateMsg(InternalMessage *msg)
{
if (msg == nullptr) {

View File

@ -1,5 +1,5 @@
/*
* Copyright (C) 2021 Huawei Device Co., Ltd.
* Copyright (C) 2021-2022 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.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
@ -147,6 +148,20 @@ 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;
private:
using ProcessFun = bool (P2pIdleState::*)(InternalMessage &msg) const;
std::map<P2P_STATE_MACHINE_CMD, ProcessFun> mProcessFunMap;

View File

@ -1,5 +1,5 @@
/*
* Copyright (C) 2021 Huawei Device Co., Ltd.
* Copyright (C) 2021-2022 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.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"
@ -194,5 +195,15 @@ 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);
}
} // namespace Wifi
} // namespace OHOS

Some files were not shown because too many files have changed in this diff Show More