From 38249a56d21b4df8ad60c56f728d5eea4618b01a Mon Sep 17 00:00:00 2001 From: bayanxing Date: Wed, 19 Jan 2022 23:32:35 +0800 Subject: [PATCH 1/4] feat: add p2p js api. Signed-off-by: bayanxing --- .../native_cpp/napi/wifi_napi_entry.cpp | 15 + .../native_cpp/napi/wifi_napi_event.cpp | 18 + .../native_cpp/napi/wifi_napi_p2p.cpp | 397 ++++++++++++++++++ .../innerkits/native_cpp/napi/wifi_napi_p2p.h | 51 +++ .../wifi_standard/include/wifi_p2p.h | 2 +- .../wifi_standard/interfaces/wifi_msg.h | 2 + 6 files changed, 484 insertions(+), 1 deletion(-) diff --git a/interfaces/innerkits/native_cpp/napi/wifi_napi_entry.cpp b/interfaces/innerkits/native_cpp/napi/wifi_napi_entry.cpp index 31c53cbc8..24220664a 100755 --- a/interfaces/innerkits/native_cpp/napi/wifi_napi_entry.cpp +++ b/interfaces/innerkits/native_cpp/napi/wifi_napi_entry.cpp @@ -77,6 +77,21 @@ static napi_value Init(napi_env env, napi_value exports) { DECLARE_NAPI_FUNCTION("setHotspotConfig", SetHotspotConfig), DECLARE_NAPI_FUNCTION("getHotspotConfig", GetHotspotConfig), DECLARE_NAPI_FUNCTION("getStations", GetStations), + DECLARE_NAPI_FUNCTION("enableP2p", EnableP2p), + DECLARE_NAPI_FUNCTION("disableP2p", DisableP2p), + DECLARE_NAPI_FUNCTION("getP2pLinkedInfo", GetP2pLinkedInfo), + DECLARE_NAPI_FUNCTION("getCurrentGroup", GetCurrentGroup), + DECLARE_NAPI_FUNCTION("getP2pDevices", GetP2pDevices), + DECLARE_NAPI_FUNCTION("createGroup", CreateGroup), + DECLARE_NAPI_FUNCTION("removeGroup", RemoveGroup), + DECLARE_NAPI_FUNCTION("p2pConnect", P2pConnect), + DECLARE_NAPI_FUNCTION("p2pDisConnect", P2pDisConnect), + DECLARE_NAPI_FUNCTION("startDiscoverDevices", StartDiscoverDevices), + DECLARE_NAPI_FUNCTION("stopDiscoverDevices", StopDiscoverDevices), + DECLARE_NAPI_FUNCTION("startP2pListen", StartP2pListen), + DECLARE_NAPI_FUNCTION("stopP2pListen", StopP2pListen), + DECLARE_NAPI_FUNCTION("deletePersistentGroup", DeletePersistentGroup), + DECLARE_NAPI_FUNCTION("setP2pDeviceName", SetP2pDeviceName) }; NAPI_CALL(env, napi_define_properties(env, exports, sizeof(desc) / sizeof(napi_property_descriptor), desc)); diff --git a/interfaces/innerkits/native_cpp/napi/wifi_napi_event.cpp b/interfaces/innerkits/native_cpp/napi/wifi_napi_event.cpp index 7a1a5a4fc..64782c88b 100755 --- a/interfaces/innerkits/native_cpp/napi/wifi_napi_event.cpp +++ b/interfaces/innerkits/native_cpp/napi/wifi_napi_event.cpp @@ -31,6 +31,12 @@ 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_EVENT_TYPE_P2P_DEVICES_STATE = "p2pDevicesChange"; +const std::string WIFI_EVENT_TYPE_P2P_STATE = "p2pStateChange"; +const std::string WIFI_EVENT_TYPE_P2P_CONN_STATE = "p2pConnStateChange"; +const std::string WIFI_EVENT_TYPE_P2P_PEER_DISCOVERY_STATE = "p2pPeerDiscoveryStateChange"; +const std::string WIFI_EVENT_TYPE_P2P_CURRENT_DEVICE_STATE = "p2pCurrentDeviceChange"; +const std::string WIFI_EVENT_TYPE_P2P_GROUP_STATE = "p2pGroupStateChange"; 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"; @@ -39,6 +45,12 @@ 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"; +const std::string WIFI_USUAL_EVENT_P2P_DEVICES_CHANGE = "usual.event.wifi.p2p.DEVICES_CHANGE"; +const std::string WIFI_USUAL_EVENT_P2P_STATE_CHANGE = "usual.event.wifi.p2p.STATE_CHANGE"; +const std::string WIFI_USUAL_EVENT_P2P_CONN_STATE_CHANGE = "usual.event.wifi.p2p.CONN_STATE_CHANGE"; +const std::string WIFI_USUAL_EVENT_P2P_PEER_DISCOVERY_STATE_CHANG = "usual.event.wifi.p2p.PEER_DISCOVERY_STATE_CHANGE"; +const std::string WIFI_USUAL_EVENT_P2P_CURRENT_DEVICE_STATE_CHANGE = "usual.event.wifi.p2p.CURRENT_DEVICE_CHANGE"; +const std::string WIFI_USUAL_EVENT_P2P_GROUP_STATE_CHANGE = "usual.event.wifi.p2p.GROUP_STATE_CHANGED"; std::shared_mutex g_regInfoMutex; static std::map g_eventRegisterInfo; @@ -49,6 +61,12 @@ static std::map g_mapEventTypeToUsualEvent = { { 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 }, + { WIFI_EVENT_TYPE_P2P_DEVICES_STATE, WIFI_USUAL_EVENT_P2P_DEVICES_CHANGE }, + { WIFI_EVENT_TYPE_P2P_STATE, WIFI_USUAL_EVENT_P2P_STATE_CHANGE }, + { WIFI_EVENT_TYPE_P2P_CONN_STATE, WIFI_USUAL_EVENT_P2P_CONN_STATE_CHANGE }, + { WIFI_EVENT_TYPE_P2P_PEER_DISCOVERY_STATE, WIFI_USUAL_EVENT_P2P_PEER_DISCOVERY_STATE_CHANG }, + { WIFI_EVENT_TYPE_P2P_CURRENT_DEVICE_STATE, WIFI_USUAL_EVENT_P2P_CURRENT_DEVICE_STATE_CHANGE }, + { WIFI_EVENT_TYPE_P2P_GROUP_STATE, WIFI_USUAL_EVENT_P2P_GROUP_STATE_CHANGE } }; static std::map g_mapUserDefinedEventProcessFunc = {}; diff --git a/interfaces/innerkits/native_cpp/napi/wifi_napi_p2p.cpp b/interfaces/innerkits/native_cpp/napi/wifi_napi_p2p.cpp index f62b96aba..8fa4f3418 100755 --- a/interfaces/innerkits/native_cpp/napi/wifi_napi_p2p.cpp +++ b/interfaces/innerkits/native_cpp/napi/wifi_napi_p2p.cpp @@ -18,6 +18,403 @@ namespace OHOS { namespace Wifi { +DEFINE_WIFILOG_LABEL("WifiNAPIP2p"); +std::unique_ptr wifiP2pPtr = WifiP2p::GetInstance(WIFI_P2P_ABILITY_ID); + +napi_value EnableP2p(napi_env env, napi_callback_info info) +{ + TRACE_FUNC_CALL; + NAPI_ASSERT(env, wifiP2pPtr != nullptr, "[NAPI] Wifi p2p instance is null."); + + ErrCode ret = wifiP2pPtr->EnableP2p(); + napi_value result; + napi_get_boolean(env, ret == WIFI_OPT_SUCCESS, &result); + return result; +} + +napi_value DisableP2p(napi_env env, napi_callback_info info) +{ + TRACE_FUNC_CALL; + NAPI_ASSERT(env, wifiP2pPtr != nullptr, "[NAPI] Wifi p2p instance is null."); + + ErrCode ret = wifiP2pPtr->DisableP2p(); + napi_value result; + napi_get_boolean(env, ret == WIFI_OPT_SUCCESS, &result); + return result; +} + +static void DeviceInfoToJs(const napi_env& env, const WifiP2pDevice& device, napi_value& result) +{ + SetValueUtf8String(env, "deviceName", device.GetDeviceName().c_str(), result); + SetValueUtf8String(env, "macAddress", device.GetDeviceAddress().c_str(), result); + SetValueUtf8String(env, "primaryDeviceType", device.GetPrimaryDeviceType().c_str(), result); + SetValueUtf8String(env, "secondaryDeviceType", device.GetSecondaryDeviceType().c_str(), result); + SetValueInt32(env, "status", static_cast(device.GetP2pDeviceStatus()), result); + SetValueUnsignedInt32(env, "supportWpsConfigMethods", device.GetWpsConfigMethod(), result); + SetValueInt32(env, "deviceCapabilitys", device.GetDeviceCapabilitys(), result); + SetValueInt32(env, "groupCapabilitys", device.GetGroupCapabilitys(), result); +} + +static void WfdInfoToJs(const napi_env& env, const WifiP2pWfdInfo& wfdInfo, napi_value& result) +{ + SetValueBool(env, "wfdEnabled", wfdInfo.GetWfdEnabled(), result); + SetValueInt32(env, "deviceInfo", wfdInfo.GetDeviceInfo(), result); + SetValueInt32(env, "ctrlPort", wfdInfo.GetCtrlPort(), result); + SetValueInt32(env, "maxThroughput", wfdInfo.GetMaxThroughput(), result); +} + +static bool DeviceInfosToJs(const napi_env& env, + const std::vector& vecDevices, napi_value& arrayResult) +{ + uint32_t idx = 0; + for (auto& each : vecDevices) { + napi_value eachObj; + napi_create_object(env, &eachObj); + DeviceInfoToJs(env, each, eachObj); + WifiP2pWfdInfo info = each.GetWfdInfo(); + napi_value wfdInfo; + napi_create_object(env, &wfdInfo); + WfdInfoToJs(env, info, wfdInfo); + napi_set_named_property(env, eachObj, "wfdInfo", wfdInfo); + napi_status status = napi_set_element(env, arrayResult, idx++, eachObj); + if (status != napi_ok) { + WIFI_LOGE("wifi napi set element error: %{public}d, idx: %{public}d", status, idx - 1); + return false; + } + } + return true; +} + +static bool GroupInfosToJs(const napi_env& env, WifiP2pGroupInfo& groupInfo, napi_value& result) +{ + SetValueBool(env, "isP2pGroupOwner", groupInfo.IsGroupOwner(), result); + SetValueUtf8String(env, "passphrase", groupInfo.GetPassphrase().c_str(), result); + SetValueUtf8String(env, "interface", groupInfo.GetInterface().c_str(), result); + SetValueUtf8String(env, "groupName", groupInfo.GetGroupName().c_str(), result); + SetValueInt32(env, "networkId", groupInfo.GetNetworkId(), result); + SetValueInt32(env, "frequency", groupInfo.GetFrequency(), result); + SetValueBool(env, "isP2pPersistent", groupInfo.IsPersistent(), result); + SetValueInt32(env, "groupStatus", static_cast(groupInfo.GetP2pGroupStatus()), result); + SetValueUtf8String(env, "goIpAddress", groupInfo.GetGoIpAddress().c_str(), result); + + WifiP2pDevice ownerDevice = groupInfo.GetOwner(); + napi_value owner; + napi_create_object(env, &owner); + DeviceInfoToJs(env, ownerDevice, owner); + napi_status status = napi_set_named_property(env, result, "owner", owner); + if (status != napi_ok) { + WIFI_LOGE("napi_set_named_property owner fail"); + return false; + } + if (!groupInfo.IsClientDevicesEmpty()) { + const std::vector& vecDevices = groupInfo.GetClientDevices(); + napi_value devices; + napi_create_array_with_length(env, vecDevices.size(), &devices); + if (!DeviceInfosToJs(env, vecDevices, devices)) { + return false; + } + status = napi_set_named_property(env, result, "clientDevices", devices); + if (status != napi_ok) { + WIFI_LOGE("napi_set_named_property clientDevices fail"); + return false; + } + } + return true; +} + +napi_value GetCurrentGroup(napi_env env, napi_callback_info info) +{ + TRACE_FUNC_CALL; + size_t argc = 2; + napi_value argv[argc]; + napi_value thisVar = nullptr; + void *data = nullptr; + NAPI_CALL(env, napi_get_cb_info(env, info, &argc, argv, &thisVar, &data)); + + P2pGroupInfoAsyncContext *asyncContext = new P2pGroupInfoAsyncContext(env); + NAPI_ASSERT(env, asyncContext != nullptr, "asyncContext is null."); + napi_create_string_latin1(env, "getCurrentGroup", NAPI_AUTO_LENGTH, &asyncContext->resourceName); + + asyncContext->executeFunc = [&](void* data) -> void { + P2pGroupInfoAsyncContext *context = static_cast(data); + TRACE_FUNC_CALL_NAME("wifiP2pPtr->GetCurrentGroup"); + context->isSuccess = (wifiP2pPtr->GetCurrentGroup(context->groupInfo) == WIFI_OPT_SUCCESS); + }; + + asyncContext->completeFunc = [&](void* data) -> void { + P2pGroupInfoAsyncContext *context = static_cast(data); + napi_create_object(context->env, &context->result); + context->isSuccess = GroupInfosToJs(context->env, context->groupInfo, context->result); + WIFI_LOGI("Push get current group result to client"); + }; + + size_t nonCallbackArgNum = 0; + return DoAsyncWork(env, asyncContext, argc, argv, nonCallbackArgNum); +} + +napi_value StartP2pListen(napi_env env, napi_callback_info info) +{ + TRACE_FUNC_CALL; + size_t argc = 2; + napi_value argv[argc]; + napi_value thisVar; + NAPI_CALL(env, napi_get_cb_info(env, info, &argc, argv, &thisVar, NULL)); + + napi_valuetype valueType; + napi_valuetype value2Type; + napi_typeof(env, argv[0], &valueType); + napi_typeof(env, argv[1], &value2Type); + NAPI_ASSERT(env, valueType == napi_number, "Wrong argument 1 type. napi_number expected."); + NAPI_ASSERT(env, value2Type == napi_object, "Wrong argument 2 type. napi_number expected."); + + NAPI_ASSERT(env, wifiP2pPtr != nullptr, "[NAPI] Wifi p2p instance is null."); + int period; + int interval; + napi_get_value_int32(env, argv[0], &period); + napi_get_value_int32(env, argv[1], &interval); + ErrCode ret = wifiP2pPtr->StartP2pListen(period, interval); + napi_value result; + napi_get_boolean(env, ret == WIFI_OPT_SUCCESS, &result); + return result; +} + +napi_value StopP2pListen(napi_env env, napi_callback_info info) +{ + TRACE_FUNC_CALL; + NAPI_ASSERT(env, wifiP2pPtr != nullptr, "[NAPI] Wifi p2p instance is null."); + + ErrCode ret = wifiP2pPtr->StopP2pListen(); + napi_value result; + napi_get_boolean(env, ret == WIFI_OPT_SUCCESS, &result); + return result; +} + +napi_value DeletePersistentGroup(napi_env env, napi_callback_info info) +{ + TRACE_FUNC_CALL; + size_t argc = 1; + napi_value argv[argc]; + napi_value thisVar; + NAPI_CALL(env, napi_get_cb_info(env, info, &argc, argv, &thisVar, NULL)); + + napi_valuetype valueType; + napi_typeof(env, argv[0], &valueType); + NAPI_ASSERT(env, valueType == napi_number, "Wrong argument type. napi_number expected."); + + NAPI_ASSERT(env, wifiP2pPtr != nullptr, "[NAPI] Wifi p2p instance is null."); + WifiP2pGroupInfo groupInfo; + int netId = -999; + napi_get_value_int32(env, argv[0], &netId); + groupInfo.SetNetworkId(netId); + ErrCode ret = wifiP2pPtr->DeleteGroup(groupInfo); + napi_value result; + napi_get_boolean(env, ret == WIFI_OPT_SUCCESS, &result); + return result; +} + +napi_value StartDiscoverDevices(napi_env env, napi_callback_info info) +{ + TRACE_FUNC_CALL; + NAPI_ASSERT(env, wifiP2pPtr != nullptr, "[NAPI] Wifi p2p instance is null."); + + ErrCode ret = wifiP2pPtr->DiscoverDevices(); + napi_value result; + napi_get_boolean(env, ret == WIFI_OPT_SUCCESS, &result); + return result; +} + +napi_value StopDiscoverDevices(napi_env env, napi_callback_info info) +{ + TRACE_FUNC_CALL; + NAPI_ASSERT(env, wifiP2pPtr != nullptr, "[NAPI] Wifi p2p instance is null."); + + ErrCode ret = wifiP2pPtr->StopDiscoverDevices(); + napi_value result; + napi_get_boolean(env, ret == WIFI_OPT_SUCCESS, &result); + return result; +} + +napi_value GetP2pDevices(napi_env env, napi_callback_info info) +{ + size_t argc = 2; + napi_value argv[argc]; + napi_value thisVar = nullptr; + void *data = nullptr; + NAPI_CALL(env, napi_get_cb_info(env, info, &argc, argv, &thisVar, &data)); + NAPI_ASSERT(env, wifiP2pPtr != nullptr, "Wifi p2p instance is null."); + + QueryP2pDeviceAsyncContext *asyncContext = new QueryP2pDeviceAsyncContext(env); + NAPI_ASSERT(env, asyncContext != nullptr, "asyncContext is null."); + napi_create_string_latin1(env, "queryP2pDevices", NAPI_AUTO_LENGTH, &asyncContext->resourceName); + + asyncContext->executeFunc = [&](void* data) -> void { + QueryP2pDeviceAsyncContext *context = static_cast(data); + context->isSuccess = (wifiP2pPtr->QueryP2pDevices(context->vecP2pDevices) == WIFI_OPT_SUCCESS); + WIFI_LOGI("GetP2pDeviceList, size: %{public}zu", context->vecP2pDevices.size()); + }; + + asyncContext->completeFunc = [&](void* data) -> void { + QueryP2pDeviceAsyncContext *context = static_cast(data); + napi_create_array_with_length(context->env, context->vecP2pDevices.size(), &context->result); + context->isSuccess = DeviceInfosToJs(context->env, context->vecP2pDevices, context->result); + WIFI_LOGI("Push P2p Device List to client"); + }; + + size_t nonCallbackArgNum = 0; + return DoAsyncWork(env, asyncContext, argc, argv, nonCallbackArgNum); +} + +napi_value SetP2pDeviceName(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_ASSERT(env, argc == 1, "Wrong number of arguments"); + + napi_valuetype valueType; + napi_typeof(env, argv[0], &valueType); + NAPI_ASSERT(env, valueType == napi_string, "Wrong argument type. napi_number expected."); + + NAPI_ASSERT(env, wifiP2pPtr != nullptr, "Wifi p2p instance is null."); + + char name[64] = {0}; + size_t typeLen = 0; + napi_get_value_string_utf8(env, argv[0], name, sizeof(name), &typeLen); + ErrCode ret = wifiP2pPtr->SetP2pDeviceName(name); + napi_value result; + napi_get_boolean(env, ret == WIFI_OPT_SUCCESS, &result); + return result; +} + +static void JsObjToP2pConfig(const napi_env& env, const napi_value& object, WifiP2pConfig& config) +{ + std::string address = ""; + int netId = -1; + std::string passphrase = ""; + int groupOwnerIntent = -1; + std::string groupName = ""; + int band = static_cast(GroupOwnerBand::GO_BAND_AUTO); + JsObjectToString(env, object, "macAddress", WIFI_MAC_LENGTH + 1, address); + JsObjectToInt(env, object, "goBand", band); + JsObjectToInt(env, object, "netId", netId); + JsObjectToString(env, object, "passphrase", MAX_PASSPHRASE_LENGTH + 1, passphrase); + JsObjectToInt(env, object, "groupOwnerIntent", groupOwnerIntent); + JsObjectToString(env, object, "groupName", DEVICE_NAME_LENGTH + 1, groupName); + config.SetDeviceAddress(address); + config.SetGoBand(static_cast(band)); + config.SetNetId(netId); + config.SetPassphrase(passphrase); + config.SetGroupOwnerIntent(groupOwnerIntent); + config.SetGroupName(groupName); +} + +napi_value P2pConnect(napi_env env, napi_callback_info info) +{ + TRACE_FUNC_CALL; + size_t argc = 1; + napi_value argv[argc]; + napi_value thisVar; + NAPI_CALL(env, napi_get_cb_info(env, info, &argc, argv, &thisVar, NULL)); + + napi_valuetype valueType; + napi_typeof(env, argv[0], &valueType); + NAPI_ASSERT(env, valueType == napi_object, "Wrong argument type. Object expected."); + + NAPI_ASSERT(env, wifiP2pPtr != nullptr, "[NAPI] Wifi p2p instance is null."); + WifiP2pConfig config; + JsObjToP2pConfig(env, argv[0], config); + ErrCode ret = wifiP2pPtr->P2pConnect(config); + if (ret != WIFI_OPT_SUCCESS) { + WIFI_LOGE("Connect to device fail: %{public}d", ret); + } + napi_value result; + napi_get_boolean(env, ret == WIFI_OPT_SUCCESS, &result); + return result; +} + +napi_value P2pDisConnect(napi_env env, napi_callback_info info) +{ + TRACE_FUNC_CALL; + NAPI_ASSERT(env, wifiP2pPtr != nullptr, "[NAPI] Wifi p2p instance is null."); + + ErrCode ret = wifiP2pPtr->P2pDisConnect(); + napi_value result; + napi_get_boolean(env, ret == WIFI_OPT_SUCCESS, &result); + return result; +} + +napi_value CreateGroup(napi_env env, napi_callback_info info) +{ + TRACE_FUNC_CALL; + size_t argc = 1; + napi_value argv[1]; + napi_value thisVar; + NAPI_CALL(env, napi_get_cb_info(env, info, &argc, argv, &thisVar, NULL)); + + napi_valuetype valueType; + napi_typeof(env, argv[0], &valueType); + NAPI_ASSERT(env, valueType == napi_object, "Wrong argument type. Object expected."); + + NAPI_ASSERT(env, wifiP2pPtr != nullptr, "[NAPI] Wifi p2p instance is null."); + WifiP2pConfig config; + JsObjToP2pConfig(env, argv[0], config); + + ErrCode ret = wifiP2pPtr->FormGroup(config); + napi_value result; + napi_get_boolean(env, ret == WIFI_OPT_SUCCESS, &result); + return result; +} + +napi_value RemoveGroup(napi_env env, napi_callback_info info) +{ + TRACE_FUNC_CALL; + NAPI_ASSERT(env, wifiP2pPtr != nullptr, "[NAPI] Wifi p2p instance is null."); + + ErrCode ret = wifiP2pPtr->RemoveGroup(); + napi_value result; + napi_get_boolean(env, ret == WIFI_OPT_SUCCESS, &result); + return result; +} + +static void LinkedInfoToJs(const napi_env& env, WifiP2pLinkedInfo& linkedInfo, napi_value& result) +{ + SetValueInt32(env, "connectState", static_cast(linkedInfo.GetConnectState()), result); + SetValueBool(env, "isP2pGroupOwner", linkedInfo.IsGroupOwner(), result); + SetValueUtf8String(env, "groupOwnerAddress", linkedInfo.GetGroupOwnerAddress().c_str(), result); +} + +napi_value GetP2pLinkedInfo(napi_env env, napi_callback_info info) +{ + TRACE_FUNC_CALL; + size_t argc = 2; + napi_value argv[argc]; + napi_value thisVar = nullptr; + void *data = nullptr; + NAPI_CALL(env, napi_get_cb_info(env, info, &argc, argv, &thisVar, &data)); + NAPI_ASSERT(env, wifiP2pPtr != nullptr, "Wifi p2p instance is null."); + + P2pLinkedInfoAsyncContext *asyncContext = new P2pLinkedInfoAsyncContext(env); + NAPI_ASSERT(env, asyncContext != nullptr, "asyncContext is null."); + napi_create_string_latin1(env, "queryP2pLinkedInfo", NAPI_AUTO_LENGTH, &asyncContext->resourceName); + + asyncContext->executeFunc = [&](void* data) -> void { + P2pLinkedInfoAsyncContext *context = static_cast(data); + TRACE_FUNC_CALL_NAME("wifiP2pPtr->QueryP2pLinkedInfo"); + context->isSuccess = (wifiP2pPtr->QueryP2pLinkedInfo(context->linkedInfo) == WIFI_OPT_SUCCESS); + }; + + asyncContext->completeFunc = [&](void* data) -> void { + P2pLinkedInfoAsyncContext *context = static_cast(data); + napi_create_object(context->env, &context->result); + LinkedInfoToJs(context->env, context->linkedInfo, context->result); + WIFI_LOGI("Push get linkedInfo result to client"); + }; + + size_t nonCallbackArgNum = 0; + return DoAsyncWork(env, asyncContext, argc, argv, nonCallbackArgNum); +} } // namespace Wifi } // namespace OHOS diff --git a/interfaces/innerkits/native_cpp/napi/wifi_napi_p2p.h b/interfaces/innerkits/native_cpp/napi/wifi_napi_p2p.h index e0078915b..c7eeb584e 100755 --- a/interfaces/innerkits/native_cpp/napi/wifi_napi_p2p.h +++ b/interfaces/innerkits/native_cpp/napi/wifi_napi_p2p.h @@ -17,10 +17,61 @@ #define WIFI_NAPI_P2P_H_ #include "wifi_napi_utils.h" +#include "wifi_p2p.h" namespace OHOS { namespace Wifi { +napi_value EnableP2p(napi_env env, napi_callback_info info); +napi_value DisableP2p(napi_env env, napi_callback_info info); +napi_value GetP2pLinkedInfo(napi_env env, napi_callback_info info); +napi_value GetCurrentGroup(napi_env env, napi_callback_info info); +napi_value GetP2pDevices(napi_env env, napi_callback_info info); +napi_value CreateGroup(napi_env env, napi_callback_info info); +napi_value RemoveGroup(napi_env env, napi_callback_info info); +napi_value P2pConnect(napi_env env, napi_callback_info info); +napi_value P2pDisConnect(napi_env env, napi_callback_info info); +napi_value StartDiscoverDevices(napi_env env, napi_callback_info info); +napi_value StopDiscoverDevices(napi_env env, napi_callback_info info); +napi_value StartP2pListen(napi_env env, napi_callback_info info); +napi_value StopP2pListen(napi_env env, napi_callback_info info); +napi_value DeletePersistentGroup(napi_env env, napi_callback_info info); +napi_value SetP2pDeviceName(napi_env env, napi_callback_info info); +class QueryP2pDeviceAsyncContext : public AsyncContext { +public: + std::vector vecP2pDevices; + + QueryP2pDeviceAsyncContext(napi_env env, napi_async_work work = nullptr, napi_deferred deferred = nullptr) + : AsyncContext(env, work, deferred) {} + + QueryP2pDeviceAsyncContext() = delete; + + ~QueryP2pDeviceAsyncContext() override {} +}; + +class P2pLinkedInfoAsyncContext : public AsyncContext { +public: + WifiP2pLinkedInfo linkedInfo; + + P2pLinkedInfoAsyncContext(napi_env env, napi_async_work work = nullptr, napi_deferred deferred = nullptr) + : AsyncContext(env, work, deferred) {} + + P2pLinkedInfoAsyncContext() = delete; + + ~P2pLinkedInfoAsyncContext() override {} +}; + +class P2pGroupInfoAsyncContext : public AsyncContext { +public: + WifiP2pGroupInfo groupInfo; + + P2pGroupInfoAsyncContext(napi_env env, napi_async_work work = nullptr, napi_deferred deferred = nullptr) + : AsyncContext(env, work, deferred) {} + + P2pGroupInfoAsyncContext() = delete; + + ~P2pGroupInfoAsyncContext() override {} +}; } // namespace Wifi } // namespace OHOS diff --git a/interfaces/innerkits/native_cpp/wifi_standard/include/wifi_p2p.h b/interfaces/innerkits/native_cpp/wifi_standard/include/wifi_p2p.h index e0b25ce8f..6fb8ccf35 100644 --- a/interfaces/innerkits/native_cpp/wifi_standard/include/wifi_p2p.h +++ b/interfaces/innerkits/native_cpp/wifi_standard/include/wifi_p2p.h @@ -16,7 +16,7 @@ #define OHOS_WIFI_P2P_H #include "wifi_errcode.h" -#include "wifi_p2p_msg.h" +#include "wifi_msg.h" #include "i_wifi_p2p_callback.h" namespace OHOS { diff --git a/interfaces/innerkits/native_cpp/wifi_standard/interfaces/wifi_msg.h b/interfaces/innerkits/native_cpp/wifi_standard/interfaces/wifi_msg.h index 4cf1a4661..0d78b16aa 100755 --- a/interfaces/innerkits/native_cpp/wifi_standard/interfaces/wifi_msg.h +++ b/interfaces/innerkits/native_cpp/wifi_standard/interfaces/wifi_msg.h @@ -35,6 +35,8 @@ namespace Wifi { #define IPV4_ADDRESS_TYPE 0 #define IPV6_ADDRESS_TYPE 1 #define DEVICE_NAME_LENGTH 32 +#define WIFI_MAC_LENGTH 17 +#define MAX_PASSPHRASE_LENGTH 63 enum class SupplicantState { DISCONNECTED = 0, -- Gitee From bf02a8ad1c9d2446c769c8836da4cc3baaf6c737 Mon Sep 17 00:00:00 2001 From: z00588131 Date: Thu, 20 Jan 2022 13:41:42 +0000 Subject: [PATCH 2/4] fix(*): 1. hid2d code optimize and fix problem; 2. update bundle.json file Signed-off-by: z00588131 --- bundle.json | 19 ++++++++++++++----- .../wifi_standard/c_adapter/wifi_c_p2p.cpp | 3 ++- .../common/net_helper/if_config.cpp | 2 ++ .../wifi_manage/wifi_hid2d_service_utils.cpp | 18 +++++++++++++++--- .../wifi_manage/wifi_hid2d_service_utils.h | 1 + .../wifi_manage/wifi_p2p/BUILD.gn | 1 + .../wifi_p2p/group_formed_state.cpp | 1 + .../wifi_p2p/p2p_group_operating_state.cpp | 9 ++++++--- .../wifi_manage/wifi_p2p/test/BUILD.gn | 1 + 9 files changed, 43 insertions(+), 12 deletions(-) diff --git a/bundle.json b/bundle.json index b9db3e9d4..fae05e5a7 100755 --- a/bundle.json +++ b/bundle.json @@ -35,7 +35,7 @@ "destPath": "foundation/communication/wifi" }, "component": { - "name": "wifi", + "name": "wifi_standard", "subsystem": "communication", "syscap": [ "SystemCapability.Communication.WiFi" @@ -68,10 +68,19 @@ "inner_kits": [ { "header" : { - "header_base": [ - "//foundation/communication/wifi/interfaces/innerkits/native_c", - "//foundation/communication/wifi/interfaces/innerkits/native_cpp/wifi_standard/include" - ], + "header_base": "//foundation/communication/wifi/interfaces/innerkits/native_c", + "header_files": [ + "wifi_device.h", + "wifi_hotspot.h", + "wifi_p2p.h", + "wifi_hid2d.h" + ] + }, + "name" : "//foundation/communication/wifi/interfaces/innerkits/native_cpp/wifi_standard:wifi_sdk" + }, + { + "header" : { + "header_base": "//foundation/communication/wifi/interfaces/innerkits/native_cpp/wifi_standard/include", "header_files": [ "wifi_device.h", "wifi_hotspot.h", diff --git a/interfaces/innerkits/native_cpp/wifi_standard/c_adapter/wifi_c_p2p.cpp b/interfaces/innerkits/native_cpp/wifi_standard/c_adapter/wifi_c_p2p.cpp index 481d4e63c..70b07fd15 100755 --- a/interfaces/innerkits/native_cpp/wifi_standard/c_adapter/wifi_c_p2p.cpp +++ b/interfaces/innerkits/native_cpp/wifi_standard/c_adapter/wifi_c_p2p.cpp @@ -345,8 +345,9 @@ public: if (!devices.empty()) { devicePtr = new WifiP2pDevice[(int)devices.size()]; } + WifiP2pDevice *p = devicePtr; for (auto& each : devices) { - if (ConvertP2PDeviceCppToC(each, devicePtr++) != OHOS::Wifi::WIFI_OPT_SUCCESS) { + if (ConvertP2PDeviceCppToC(each, p++) != OHOS::Wifi::WIFI_OPT_SUCCESS) { WIFI_LOGE("peers changed convert p2p device failed!"); return; } diff --git a/services/wifi_standard/wifi_framework/common/net_helper/if_config.cpp b/services/wifi_standard/wifi_framework/common/net_helper/if_config.cpp index 3662167d2..4da4c5408 100755 --- a/services/wifi_standard/wifi_framework/common/net_helper/if_config.cpp +++ b/services/wifi_standard/wifi_framework/common/net_helper/if_config.cpp @@ -143,6 +143,8 @@ void IfConfig::SetNetDns(const std::string& ifName, const std::string& dns1, con */ void IfConfig::FlushIpAddr(const std::string& ifName, const int& ipType) { + LOGI("Flush IP, ifName: %{public}s", ifName.c_str()); + if (ipType != static_cast(IpType::IPTYPE_IPV4)) { return; } diff --git a/services/wifi_standard/wifi_framework/wifi_manage/wifi_hid2d_service_utils.cpp b/services/wifi_standard/wifi_framework/wifi_manage/wifi_hid2d_service_utils.cpp index a8e493fc3..24a9a33de 100755 --- a/services/wifi_standard/wifi_framework/wifi_manage/wifi_hid2d_service_utils.cpp +++ b/services/wifi_standard/wifi_framework/wifi_manage/wifi_hid2d_service_utils.cpp @@ -31,8 +31,9 @@ std::atomic_int SharedLinkManager::sharedLinkCount(0); bool IpPool::InitIpPool(const std::string& serverIp) { - std::unique_lock guard(g_ipPoolMutex); + WIFI_LOGI("Init ip pool"); + std::unique_lock guard(g_ipPoolMutex); if (!ipList.empty()) { return true; } @@ -53,8 +54,9 @@ bool IpPool::InitIpPool(const std::string& serverIp) std::string IpPool::GetIp(const std::string& gcMac) { - std::unique_lock guard(g_ipPoolMutex); + WIFI_LOGI("Get ip, gcMac: %{public}s", gcMac.c_str()); + std::unique_lock guard(g_ipPoolMutex); std::string ip = ""; if (ipList.empty()) { WIFI_LOGE("Alloc ip failed!"); @@ -68,8 +70,9 @@ std::string IpPool::GetIp(const std::string& gcMac) void IpPool::ReleaseIp(const std::string& gcMac) { - std::unique_lock guard(g_ipPoolMutex); + WIFI_LOGI("Release ip, gcMac: %{public}s", gcMac.c_str()); + std::unique_lock guard(g_ipPoolMutex); auto iter = mapGcMacToAllocIp.find(gcMac); if (iter == mapGcMacToAllocIp.end()) { return; @@ -84,6 +87,15 @@ void IpPool::ReleaseIp(const std::string& gcMac) } } +void IpPool::ReleaseIpPool() +{ + WIFI_LOGI("Release ip pool"); + + std::unique_lock guard(g_ipPoolMutex); + mapGcMacToAllocIp.clear(); + ipList.clear(); +} + bool IpPool::IsValidIp(const std::string& ip) { if (ip.empty()) { diff --git a/services/wifi_standard/wifi_framework/wifi_manage/wifi_hid2d_service_utils.h b/services/wifi_standard/wifi_framework/wifi_manage/wifi_hid2d_service_utils.h index 5cae549c4..b364fe6cc 100755 --- a/services/wifi_standard/wifi_framework/wifi_manage/wifi_hid2d_service_utils.h +++ b/services/wifi_standard/wifi_framework/wifi_manage/wifi_hid2d_service_utils.h @@ -28,6 +28,7 @@ public: static bool InitIpPool(const std::string& serverIp); static std::string GetIp(const std::string& gcMac); static void ReleaseIp(const std::string& gcMac); + static void ReleaseIpPool(); private: static bool IsValidIp(const std::string& ip); diff --git a/services/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/BUILD.gn b/services/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/BUILD.gn index e1dc0e9fc..1f316fac2 100644 --- a/services/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/BUILD.gn +++ b/services/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/BUILD.gn @@ -17,6 +17,7 @@ ohos_shared_library("wifi_p2p_service") { install_enable = true sources = [ "//foundation/communication/wifi/services/wifi_standard/wifi_framework/common/net_helper/dhcpd_interface.cpp", + "//foundation/communication/wifi/services/wifi_standard/wifi_framework/common/net_helper/if_config.cpp", "//foundation/communication/wifi/services/wifi_standard/wifi_framework/common/net_helper/mac_address.cpp", "//foundation/communication/wifi/services/wifi_standard/wifi_framework/wifi_manage/common/handler.cpp", "//foundation/communication/wifi/services/wifi_standard/wifi_framework/wifi_manage/common/internal_message.cpp", diff --git a/services/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/group_formed_state.cpp b/services/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/group_formed_state.cpp index f5d66c680..f923fcb5a 100644 --- a/services/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/group_formed_state.cpp +++ b/services/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/group_formed_state.cpp @@ -206,6 +206,7 @@ bool GroupFormedState::ProcessDisconnectEvt(const InternalMessage &msg) const return EXECUTED; } + IpPool::ReleaseIp(device.GetDeviceAddress()); device.SetP2pDeviceStatus(P2pDeviceStatus::PDS_AVAILABLE); deviceManager.UpdateDeviceStatus(device); // used for peers change event querying device infos groupManager.RemoveCurrGroupClient(device); diff --git a/services/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/p2p_group_operating_state.cpp b/services/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/p2p_group_operating_state.cpp index b45f9714d..5b15e17a0 100644 --- a/services/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/p2p_group_operating_state.cpp +++ b/services/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/p2p_group_operating_state.cpp @@ -17,6 +17,7 @@ #include "wifi_p2p_hal_interface.h" #include "p2p_state_machine.h" #include "wifi_logger.h" +#include "if_config.h" DEFINE_WIFILOG_P2P_LABEL("P2pGroupOperatingState"); @@ -175,7 +176,7 @@ bool P2pGroupOperatingState::ProcessCreateGroupTimeOut(const InternalMessage &ms bool P2pGroupOperatingState::ProcessGroupRemovedEvt(const InternalMessage &msg) const { - WIFI_LOGI("recv event: %{public}d", msg.GetMessageName()); + WIFI_LOGI("recv group remove event: %{public}d", msg.GetMessageName()); if (groupManager.GetCurrentGroup().IsPersistent()) { groupManager.StashGroups(); WifiP2pGroupInfo copy = groupManager.GetCurrentGroup(); @@ -184,6 +185,10 @@ bool P2pGroupOperatingState::ProcessGroupRemovedEvt(const InternalMessage &msg) groupManager.SetCurrentGroup(copy); groupManager.StashGroups(); } + p2pStateMachine.ChangeConnectedStatus(P2pConnectedState::P2P_DISCONNECTED); + IpPool::ReleaseIpPool(); + IfConfig::GetInstance().FlushIpAddr(groupManager.GetCurrentGroup().GetInterface(), IpType::IPTYPE_IPV4); + SharedLinkManager::SetSharedLinkCount(SHARED_LINKE_COUNT_ON_DISCONNECTED); if (groupManager.GetCurrentGroup().IsGroupOwner()) { if (!p2pStateMachine.StopDhcpServer()) { WIFI_LOGW("failed to stop Dhcp server."); @@ -197,8 +202,6 @@ 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; } diff --git a/tests/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/test/BUILD.gn b/tests/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/test/BUILD.gn index f9fdd9883..0aa944f4f 100644 --- a/tests/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/test/BUILD.gn +++ b/tests/wifi_standard/wifi_framework/wifi_manage/wifi_p2p/test/BUILD.gn @@ -32,6 +32,7 @@ ohos_unittest("wifi_p2p_test") { "//foundation/communication/wifi/services/wifi_standard/wifi_framework/common/log/log_helper.c", "//foundation/communication/wifi/services/wifi_standard/wifi_framework/common/net_helper/base_address.cpp", "//foundation/communication/wifi/services/wifi_standard/wifi_framework/common/net_helper/dhcpd_interface.cpp", + "//foundation/communication/wifi/services/wifi_standard/wifi_framework/common/net_helper/if_config.cpp", "//foundation/communication/wifi/services/wifi_standard/wifi_framework/common/net_helper/ip_tools.cpp", "//foundation/communication/wifi/services/wifi_standard/wifi_framework/common/net_helper/ipv4_address.cpp", "//foundation/communication/wifi/services/wifi_standard/wifi_framework/common/net_helper/ipv6_address.cpp", -- Gitee From 1a7e2603efcf1bb66f3ba93bef853ce513b45c2e Mon Sep 17 00:00:00 2001 From: zhangfeng Date: Tue, 25 Jan 2022 06:20:01 +0000 Subject: [PATCH 3/4] fix(*): 1. update p2p_supplicant.conf file; 2. power consumption optimize Signed-off-by: zhangfeng --- services/wifi_standard/ipc_framework/cRPC/src/server.c | 4 ++-- services/wifi_standard/wifi_hal/etc/init/p2p_supplicant.conf | 2 ++ 2 files changed, 4 insertions(+), 2 deletions(-) diff --git a/services/wifi_standard/ipc_framework/cRPC/src/server.c b/services/wifi_standard/ipc_framework/cRPC/src/server.c index c30e29d64..97e425812 100644 --- a/services/wifi_standard/ipc_framework/cRPC/src/server.c +++ b/services/wifi_standard/ipc_framework/cRPC/src/server.c @@ -1,5 +1,5 @@ /* - * Copyright (C) 2021 Huawei Device Co., Ltd. + * Copyright (C) 2021-2022 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -199,7 +199,7 @@ int RunRpcLoop(RpcServer *server) EventLoop *loop = server->loop; while (!loop->stop) { BeforeLoop(server); - int retval = epoll_wait(loop->epfd, loop->epEvents, loop->setSize, 1); /* wait 1ms */ + int retval = epoll_wait(loop->epfd, loop->epEvents, loop->setSize, -1); for (int i = 0; i < retval; ++i) { struct epoll_event *e = loop->epEvents + i; int fd = e->data.fd; diff --git a/services/wifi_standard/wifi_hal/etc/init/p2p_supplicant.conf b/services/wifi_standard/wifi_hal/etc/init/p2p_supplicant.conf index 37ceb0401..e7df5673a 100755 --- a/services/wifi_standard/wifi_hal/etc/init/p2p_supplicant.conf +++ b/services/wifi_standard/wifi_hal/etc/init/p2p_supplicant.conf @@ -24,3 +24,5 @@ p2p_go_intent=0 persistent_reconnect=1 serial_number=0123456789ABCDEF p2p_ssid_postfix=-ohos +p2p_go_ht40=1 +p2p_go_vht=1 -- Gitee From d18332c1c010564bbffd100cce55da25c6ae6372 Mon Sep 17 00:00:00 2001 From: zhangfeng Date: Wed, 26 Jan 2022 07:12:53 +0000 Subject: [PATCH 4/4] fix(*): Js module multi thread problem fix Signed-off-by: zhangfeng --- README.md | 27 +- README_zh.md | 29 +- .../native_cpp/napi/wifi_napi_device.cpp | 14 +- .../native_cpp/napi/wifi_napi_entry.cpp | 27 +- .../native_cpp/napi/wifi_napi_event.cpp | 701 ++++++++++-------- .../native_cpp/napi/wifi_napi_event.h | 121 +-- .../native_cpp/napi/wifi_napi_p2p.cpp | 52 +- .../innerkits/native_cpp/napi/wifi_napi_p2p.h | 2 +- .../native_cpp/napi/wifi_napi_utils.cpp | 16 +- .../native_cpp/napi/wifi_napi_utils.h | 8 +- interfaces/kits/jskits/@ohos.wifi.d.ts | 26 +- 11 files changed, 546 insertions(+), 477 deletions(-) diff --git a/README.md b/README.md index 8109dfcb9..c1c3304b4 100755 --- a/README.md +++ b/README.md @@ -157,14 +157,19 @@ import wf from '@ohos.wifi'; // Import the @ohos.wifi class. ```js // Start a scan. var isScanSuccess = wf.scan(); // true - + // Wait for some time. - + // Obtain the scan result. - wf.getScanInfos(result => { - var num = Object.keys(result).length; - console.info("wifi scan result mum: " + num); - for (var i = 0; i < num; ++i) { + wf.getScanInfos((err, result) => { + if (err) { + console.error("get scan info error"); + return; + } + + var len = Object.keys(result).length; + console.log("get scan info number: " + len); + for (var i = 0; i < len; ++i) { console.info("ssid: " + result[i].ssid); console.info("bssid: " + result[i].bssid); console.info("securityType: " + result[i].securityType); @@ -173,7 +178,7 @@ import wf from '@ohos.wifi'; // Import the @ohos.wifi class. console.info("frequency: " + result[i].frequency); console.info("timestamp: " + result[i].timestamp); } - }) + }); ``` @@ -190,13 +195,19 @@ Set up a WLAN connection. "isHiddenSsid":false, "securityType":3, } + Method 1: // Add a hotspot configuration. - wf.addDeviceConfig(config, (result) => { + wf.addDeviceConfig(config, (err, result) => { + if (err) { + console.error("add device config error"); + return; + } console.info("config id: " + result); // Set up a WLAN based on the hotspot configuration ID. wf.connectToNetwork(result); }); + Method 2: // Set up a WLAN by calling connectToDevice with the hotspot configuration passed. wf.connectToDevice(config); diff --git a/README_zh.md b/README_zh.md index 0dffea01a..e2ab4483c 100755 --- a/README_zh.md +++ b/README_zh.md @@ -157,14 +157,19 @@ import wf from '@ohos.wifi'; // 导入js接口类 ```js // 调用WLAN扫描接口 var isScanSuccess = wf.scan(); // true - + // 延迟一定时间 - + // 获取扫描结果 - wf.getScanInfos(result => { - var num = Object.keys(result).length; - console.info("wifi scan result mum: " + num); - for (var i = 0; i < num; ++i) { + wf.getScanInfos((err, result) => { + if (err) { + console.error("get scan info error"); + return; + } + + var len = Object.keys(result).length; + console.log("get scan info number: " + len); + for (var i = 0; i < len; ++i) { console.info("ssid: " + result[i].ssid); console.info("bssid: " + result[i].bssid); console.info("securityType: " + result[i].securityType); @@ -173,7 +178,7 @@ import wf from '@ohos.wifi'; // 导入js接口类 console.info("frequency: " + result[i].frequency); console.info("timestamp: " + result[i].timestamp); } - }) + }); ``` @@ -190,14 +195,18 @@ import wf from '@ohos.wifi'; // 导入js接口类 "isHiddenSsid":false, "securityType":3, } - 方式一: + 方式一: // 添加配置 - wf.addDeviceConfig(config, (result) => { + wf.addDeviceConfig(config, (err, result) => { + if (err) { + console.error("add device config error"); + return; + } console.info("config id: " + result); // 通过配置id连接WLAN wf.connectToNetwork(result); }); - 方式二: + 方式二: // 通过配置信息直接连接WLAN wf.connectToDevice(config); ``` diff --git a/interfaces/innerkits/native_cpp/napi/wifi_napi_device.cpp b/interfaces/innerkits/native_cpp/napi/wifi_napi_device.cpp index ed3486151..4354ae772 100755 --- a/interfaces/innerkits/native_cpp/napi/wifi_napi_device.cpp +++ b/interfaces/innerkits/native_cpp/napi/wifi_napi_device.cpp @@ -96,7 +96,7 @@ static SecTypeJs SecurityTypeNativeToJs(const WifiSecurity& cppSecurityType) return jsSecurityType; } -static bool NativeScanInfosToJsObj(const napi_env& env, +static ErrCode NativeScanInfosToJsObj(const napi_env& env, const std::vector& vecScnIanfos, napi_value& arrayResult) { uint32_t idx = 0; @@ -115,10 +115,10 @@ static bool NativeScanInfosToJsObj(const napi_env& env, napi_status status = napi_set_element(env, arrayResult, idx++, eachObj); if (status != napi_ok) { WIFI_LOGE("Wifi napi set element error: %{public}d, idx: %{public}d", status, idx - 1); - return false; + return WIFI_OPT_FAILED; } } - return true; + return WIFI_OPT_SUCCESS; } napi_value GetScanInfos(napi_env env, napi_callback_info info) @@ -138,14 +138,14 @@ napi_value GetScanInfos(napi_env env, napi_callback_info info) asyncContext->executeFunc = [&](void* data) -> void { ScanInfoAsyncContext *context = static_cast(data); TRACE_FUNC_CALL_NAME("wifiScanPtr->GetScanInfoList"); - context->isSuccess = (wifiScanPtr->GetScanInfoList(context->vecScanInfos) == WIFI_OPT_SUCCESS); + context->errorCode = wifiScanPtr->GetScanInfoList(context->vecScanInfos); WIFI_LOGI("GetScanInfoList, size: %{public}zu", context->vecScanInfos.size()); }; asyncContext->completeFunc = [&](void* data) -> void { ScanInfoAsyncContext *context = static_cast(data); napi_create_array_with_length(context->env, context->vecScanInfos.size(), &context->result); - context->isSuccess = NativeScanInfosToJsObj(context->env, context->vecScanInfos, context->result); + context->errorCode = NativeScanInfosToJsObj(context->env, context->vecScanInfos, context->result); WIFI_LOGI("Push scan info list to client"); }; @@ -223,7 +223,7 @@ napi_value AddDeviceConfig(napi_env env, napi_callback_info info) if (context->addResult < 0 || ret != WIFI_OPT_SUCCESS) { context->addResult = -1; } - context->isSuccess = (ret == WIFI_OPT_SUCCESS); + context->errorCode = ret; }; asyncContext->completeFunc = [&](void* data) -> void { @@ -425,7 +425,7 @@ napi_value GetLinkedInfo(napi_env env, napi_callback_info info) asyncContext->executeFunc = [&](void* data) -> void { LinkedInfoAsyncContext *context = static_cast(data); TRACE_FUNC_CALL_NAME("wifiDevicePtr->GetLinkedInfo"); - context->isSuccess = (wifiDevicePtr->GetLinkedInfo(context->linkedInfo) == WIFI_OPT_SUCCESS); + context->errorCode = wifiDevicePtr->GetLinkedInfo(context->linkedInfo); }; asyncContext->completeFunc = [&](void* data) -> void { diff --git a/interfaces/innerkits/native_cpp/napi/wifi_napi_entry.cpp b/interfaces/innerkits/native_cpp/napi/wifi_napi_entry.cpp index 24220664a..0afcac047 100755 --- a/interfaces/innerkits/native_cpp/napi/wifi_napi_entry.cpp +++ b/interfaces/innerkits/native_cpp/napi/wifi_napi_entry.cpp @@ -1,5 +1,5 @@ /* - * Copyright (C) 2021 Huawei Device Co., Ltd. + * Copyright (C) 2021-2022 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -22,26 +22,6 @@ 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 */ @@ -91,11 +71,12 @@ static napi_value Init(napi_env env, napi_value exports) { DECLARE_NAPI_FUNCTION("startP2pListen", StartP2pListen), DECLARE_NAPI_FUNCTION("stopP2pListen", StopP2pListen), DECLARE_NAPI_FUNCTION("deletePersistentGroup", DeletePersistentGroup), - DECLARE_NAPI_FUNCTION("setP2pDeviceName", SetP2pDeviceName) + DECLARE_NAPI_FUNCTION("setP2pDeviceName", SetP2pDeviceName), + DECLARE_NAPI_FUNCTION("on", On), + DECLARE_NAPI_FUNCTION("off", Off), }; NAPI_CALL(env, napi_define_properties(env, exports, sizeof(desc) / sizeof(napi_property_descriptor), desc)); - InitEventClass(env, exports); return exports; } diff --git a/interfaces/innerkits/native_cpp/napi/wifi_napi_event.cpp b/interfaces/innerkits/native_cpp/napi/wifi_napi_event.cpp index 64782c88b..e863c08ed 100755 --- a/interfaces/innerkits/native_cpp/napi/wifi_napi_event.cpp +++ b/interfaces/innerkits/native_cpp/napi/wifi_napi_event.cpp @@ -1,5 +1,5 @@ /* - * Copyright (C) 2021 Huawei Device Co., Ltd. + * Copyright (C) 2021-2022 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -14,347 +14,296 @@ */ #include "wifi_napi_event.h" -#include +#include #include "wifi_napi_utils.h" +#include "wifi_device.h" +#include "wifi_scan.h" +#include "wifi_p2p.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_EVENT_TYPE_P2P_DEVICES_STATE = "p2pDevicesChange"; -const std::string WIFI_EVENT_TYPE_P2P_STATE = "p2pStateChange"; -const std::string WIFI_EVENT_TYPE_P2P_CONN_STATE = "p2pConnStateChange"; -const std::string WIFI_EVENT_TYPE_P2P_PEER_DISCOVERY_STATE = "p2pPeerDiscoveryStateChange"; -const std::string WIFI_EVENT_TYPE_P2P_CURRENT_DEVICE_STATE = "p2pCurrentDeviceChange"; -const std::string WIFI_EVENT_TYPE_P2P_GROUP_STATE = "p2pGroupStateChange"; - -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"; -const std::string WIFI_USUAL_EVENT_P2P_DEVICES_CHANGE = "usual.event.wifi.p2p.DEVICES_CHANGE"; -const std::string WIFI_USUAL_EVENT_P2P_STATE_CHANGE = "usual.event.wifi.p2p.STATE_CHANGE"; -const std::string WIFI_USUAL_EVENT_P2P_CONN_STATE_CHANGE = "usual.event.wifi.p2p.CONN_STATE_CHANGE"; -const std::string WIFI_USUAL_EVENT_P2P_PEER_DISCOVERY_STATE_CHANG = "usual.event.wifi.p2p.PEER_DISCOVERY_STATE_CHANGE"; -const std::string WIFI_USUAL_EVENT_P2P_CURRENT_DEVICE_STATE_CHANGE = "usual.event.wifi.p2p.CURRENT_DEVICE_CHANGE"; -const std::string WIFI_USUAL_EVENT_P2P_GROUP_STATE_CHANGE = "usual.event.wifi.p2p.GROUP_STATE_CHANGED"; - -std::shared_mutex g_regInfoMutex; -static std::map g_eventRegisterInfo; - -static std::map g_mapEventTypeToUsualEvent = { - { WIFI_EVENT_TYPE_POWER_STATE, WIFI_USUAL_EVENT_POWER_STATE }, - { WIFI_EVENT_TYPE_CONN_STATE, WIFI_USUAL_EVENT_CONN_STATE }, - { 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 }, - { WIFI_EVENT_TYPE_P2P_DEVICES_STATE, WIFI_USUAL_EVENT_P2P_DEVICES_CHANGE }, - { WIFI_EVENT_TYPE_P2P_STATE, WIFI_USUAL_EVENT_P2P_STATE_CHANGE }, - { WIFI_EVENT_TYPE_P2P_CONN_STATE, WIFI_USUAL_EVENT_P2P_CONN_STATE_CHANGE }, - { WIFI_EVENT_TYPE_P2P_PEER_DISCOVERY_STATE, WIFI_USUAL_EVENT_P2P_PEER_DISCOVERY_STATE_CHANG }, - { WIFI_EVENT_TYPE_P2P_CURRENT_DEVICE_STATE, WIFI_USUAL_EVENT_P2P_CURRENT_DEVICE_STATE_CHANGE }, - { WIFI_EVENT_TYPE_P2P_GROUP_STATE, WIFI_USUAL_EVENT_P2P_GROUP_STATE_CHANGE } +const std::string EVENT_STA_POWER_STATE_CHANGE = "wifiStateChange"; +const std::string EVENT_STA_CONN_STATE_CHANGE = "wifiConnectionChange"; +const std::string EVENT_STA_SCAN_STATE_CHANGE = "wifiScanStateChange"; +const std::string EVENT_STA_RSSI_STATE_CHANGE = "wifiRssiChange"; +const std::string EVENT_HOTSPOT_STATE_CHANGE = "hotspotStateChange"; +const std::string EVENT_HOTSPOT_STA_JOIN = "hotspotStaJoin"; +const std::string EVENT_HOTSPOT_STA_LEAVE = "hotspotStaLeave"; +const std::string EVENT_P2P_STATE_CHANGE = "p2pStateChange"; +const std::string EVENT_P2P_CONN_STATE_CHANGE = "p2pConnectionChange"; +const std::string EVENT_P2P_DEVICE_STATE_CHANGE = "p2pDeviceChange"; +const std::string EVENT_P2P_PERSISTENT_GROUP_CHANGE = "p2pPersistentGroupChange"; +const std::string EVENT_P2P_PEER_DEVICE_CHANGE = "p2pPeerDeviceChange"; +const std::string EVENT_P2P_DISCOVERY_CHANGE = "p2pPeerDeviceChange"; + +static std::set g_supportEventList = { + EVENT_STA_POWER_STATE_CHANGE, + EVENT_STA_CONN_STATE_CHANGE, + EVENT_STA_SCAN_STATE_CHANGE, + EVENT_STA_RSSI_STATE_CHANGE, + EVENT_HOTSPOT_STATE_CHANGE, + EVENT_HOTSPOT_STA_JOIN, + EVENT_HOTSPOT_STA_LEAVE, + EVENT_P2P_STATE_CHANGE, + EVENT_P2P_CONN_STATE_CHANGE, + EVENT_P2P_DEVICE_STATE_CHANGE, + EVENT_P2P_PERSISTENT_GROUP_CHANGE, + EVENT_P2P_PEER_DEVICE_CHANGE, + EVENT_P2P_DISCOVERY_CHANGE, }; -static std::map g_mapUserDefinedEventProcessFunc = {}; +void NapiEvent::EventNotify(AsyncEventData *asyncEvent) +{ + WIFI_LOGI("Enter wifi event notify"); + uv_loop_s* loop = nullptr; + napi_get_uv_event_loop(asyncEvent->env, &loop); + + uv_work_t* work = new uv_work_t; + if (work == nullptr) { + WIFI_LOGE("uv_work_t work is null."); + delete asyncEvent; + asyncEvent = nullptr; + return; + } -class EventRegisterInfo { -public: - explicit EventRegisterInfo(EventManager* context) : m_context(context) { + WIFI_LOGI("Get the event loop, napi_env: %{public}p", asyncEvent->env); + work->data = asyncEvent; + uv_queue_work( + loop, + work, + [](uv_work_t* work) {}, + [](uv_work_t* work, int status) { + AsyncEventData *asyncData = static_cast(work->data); + if (asyncData == nullptr) { + WIFI_LOGE("asyncData is null."); + return; + } + WIFI_LOGI("Napi event uv_queue_work, env: %{public}p, status: %{public}d", asyncData->env, status); + napi_handle_scope scope = nullptr; + napi_open_handle_scope(asyncData->env, &scope); + if (scope == nullptr) { + WIFI_LOGE("scope is nullptr"); + napi_close_handle_scope(asyncData->env, scope); + return; + } + napi_value undefine; + napi_get_undefined(asyncData->env, &undefine); + napi_value handler = nullptr; + napi_get_reference_value(asyncData->env, asyncData->callbackRef, &handler); + + WIFI_LOGI("Push event to js, env: %{public}p, ref : %{public}p", asyncData->env, &asyncData->callbackRef); + if (napi_call_function(asyncData->env, nullptr, handler, 1, &asyncData->jsEvent, &undefine) != napi_ok) { + WIFI_LOGE("Report event to Js failed"); + } + napi_close_handle_scope(asyncData->env, scope); + if (asyncData != nullptr) { + delete asyncData; + asyncData = nullptr; + } + if (work != nullptr) { + delete work; + work = nullptr; + } + } + ); +} + +bool NapiEvent::CheckIsRegister(const std::string& type) +{ + return g_eventRegisterInfo.find(type) != g_eventRegisterInfo.end(); +} + +napi_value NapiEvent::CreateResult(const napi_env& env, int value) { + napi_value result; + napi_create_int32(env, value, &result); + return result; +} + +napi_value NapiEvent::CreateResult(const napi_env& env, const StationInfo& info) +{ + napi_value result; + napi_create_object(env, &result); + SetValueUtf8String(env, "name", info.deviceName.c_str(), result); + SetValueUtf8String(env, "macAddress", info.bssid.c_str(), result); + SetValueUtf8String(env, "ipAddress", info.ipAddr.c_str(), result); + return result; +} + +napi_value NapiEvent::CreateResult(const napi_env& env, const WifiP2pDevice& device) +{ + napi_value result; + napi_create_object(env, &result); + SetValueUtf8String(env, "deviceName", device.GetDeviceName().c_str(), result); + SetValueUtf8String(env, "deviceAddress", device.GetDeviceAddress().c_str(), result); + SetValueUtf8String(env, "primaryDeviceType", device.GetPrimaryDeviceType().c_str(), result); + SetValueInt32(env, "devStatus", static_cast(device.GetP2pDeviceStatus()), result); + SetValueInt32(env, "groupCapability", device.GetGroupCapabilitys(), result); + return result; +} + +napi_value NapiEvent::CreateResult(const napi_env& env, const std::vector& devices) +{ + uint32_t idx = 0; + napi_value arrayResult; + napi_create_array_with_length(env, devices.size(), &arrayResult); + for (auto& each : devices) { + if (napi_set_element(env, arrayResult, idx++, CreateResult(env, each)) != napi_ok) { + WIFI_LOGE("Array result set element error, idx: %{public}d", idx - 1); + } } + return arrayResult; +} + +napi_value NapiEvent::CreateResult(const napi_env& env, const WifiP2pLinkedInfo& info) +{ + napi_value result; + napi_create_object(env, &result); + SetValueInt32(env, "connectState", static_cast(info.GetConnectState()), result); + SetValueBool(env, "isGroupOwner", info.IsGroupOwner(), result); + SetValueUtf8String(env, "groupOwnerAddr", info.GetGroupOwnerAddress().c_str(), result); + return result; +} + +napi_value NapiEvent::NapiEvent::CreateResult(const napi_env& env, napi_value placehoders) +{ + return placehoders == nullptr ? UndefinedNapiValue(env) : placehoders; +} - EventRegisterInfo() { +class WifiNapiDeviceEventCallback : public IWifiDeviceCallBack, public NapiEvent { +public: + WifiNapiDeviceEventCallback() { } - virtual ~EventRegisterInfo() { + virtual ~WifiNapiDeviceEventCallback() { } - std::set& GetHandlersCb() { - return m_handlersCb; +public: + void OnWifiStateChanged(int state) override { + WIFI_LOGI("sta received state changed event: %{public}d", state); + CheckAndNotify(EVENT_STA_POWER_STATE_CHANGE, state); } - void SetSubscriber(std::shared_ptr& subscriber) { - m_subscriber = subscriber; + void OnWifiConnectionChanged(int state, const WifiLinkedInfo &info) override { + WIFI_LOGI("sta received connection changed event: %{public}d", state); + CheckAndNotify(EVENT_STA_CONN_STATE_CHANGE, state); } - std::shared_ptr GetSubscriber() { - return m_subscriber; + void OnWifiRssiChanged(int rssi) override { + WIFI_LOGI("sta received rssi changed event: %{public}d", rssi); + CheckAndNotify(EVENT_STA_RSSI_STATE_CHANGE, rssi); } - void SetContext(EventManager* context) { - m_context = context; + void OnWifiWpsStateChanged(int state, const std::string &pinCode) override { } - EventManager* GetContext() { - return m_context; + void OnStreamChanged(int direction) override { } -private: - std::set m_handlersCb; - std::shared_ptr m_subscriber; - EventManager *m_context; + OHOS::sptr AsObject() override { + return nullptr; + } }; -void Event::SetName(std::string& name) { - m_name = name; -} - -std::string Event::GetName() { - return m_name; -} - -napi_env Event::GetEnv() { - return m_env; -} - -napi_value WifiCommonEvent::PackResult() { - napi_value result; - napi_create_int32(GetEnv(), m_value, &result); - return result; -} - -static bool GetUsualEventByEventType(const std::string& type, std::string& usual) { - std::map::const_iterator it = g_mapEventTypeToUsualEvent.find(type); - if (it == g_mapEventTypeToUsualEvent.end()) { - return false; +class WifiNapiScanEventCallback : public IWifiScanCallback, public NapiEvent { +public: + WifiNapiScanEventCallback() { } - 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; - } + virtual ~WifiNapiScanEventCallback() { } - 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; +public: + void OnWifiScanStateChanged(int state) override { + WIFI_LOGI("scan received state changed event: %{public}d", state); + CheckAndNotify(EVENT_STA_SCAN_STATE_CHANGE, state); } - EventManager *manager = nullptr; - { - std::shared_lock guard(g_regInfoMutex); - std::map::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; - } + OHOS::sptr AsObject() override { + return nullptr; } +}; - std::map::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"); - } +class WifiNapiHotspotEventCallback : public IWifiHotspotCallback, public NapiEvent { +public: + WifiNapiHotspotEventCallback() { } -} - -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 guard(g_regInfoMutex); - std::map::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; - } + virtual ~WifiNapiHotspotEventCallback() { } - napi_close_handle_scope(m_env, scope); - return result; -} -bool EventManager::SubscribeServiceEvent(const std::string& event) { - MatchingSkills matchingSkills; - matchingSkills.AddEvent(event); - CommonEventSubscribeInfo subscriberInfo(matchingSkills); - std::shared_ptr subscriber = std::make_shared(subscriberInfo); - 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()); +public: + void OnHotspotStateChanged(int state) override { + WIFI_LOGI("Hotspot received state changed event: %{public}d", state); + CheckAndNotify(EVENT_HOTSPOT_STATE_CHANGE, state); } - 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()); + void OnHotspotStaJoin(const StationInfo &info) override { + WIFI_LOGI("Hotspot received sta join event"); + CheckAndNotify(EVENT_HOTSPOT_STA_JOIN, info); } - return result; -} -bool EventManager::SubscribeEvent(const std::string& name, napi_value handler) { - WIFI_LOGI("Subscribe event: %{public}s", name.c_str()); + void OnHotspotStaLeave(const StationInfo &info) override { + WIFI_LOGI("Hotspot received sta leave event"); + CheckAndNotify(EVENT_HOTSPOT_STA_LEAVE, info); + } - if (!IsEventTypeExist(name)) { - WIFI_LOGE("Subscribe event is not a valid event: %{public}s", name.c_str()); - return false; + OHOS::sptr AsObject() override { + return nullptr; } - SetEventType(name); - std::unique_lock guard(g_regInfoMutex); - std::map::iterator it = g_eventRegisterInfo.find(name); - if (it == g_eventRegisterInfo.end()) { - std::string usualEvent; - GetUsualEventByEventType(name, usualEvent); - bool result = SubscribeServiceEvent(usualEvent); - if (!result) { - WIFI_LOGE("Service register event failed: %{public}s", name.c_str()); - return false; - } +}; - EventRegisterInfo regInfo(this); - g_eventRegisterInfo[name] = regInfo; +class WifiNapiP2pEventCallback : public IWifiP2pCallback, public NapiEvent { +public: + WifiNapiP2pEventCallback() { } - if (g_eventRegisterInfo[name].GetContext() != this) { - WIFI_LOGW("Subscribe event context changed!"); - g_eventRegisterInfo[name].SetContext(this); + virtual ~WifiNapiP2pEventCallback() { } - napi_ref handlerRef = nullptr; - napi_create_reference(m_env, handler, 1, &handlerRef); - g_eventRegisterInfo[name].GetHandlersCb().insert(handlerRef); - return true; -} +public: + void OnP2pStateChanged(int state) override { + WIFI_LOGI("received p2p state changed event: %{public}d", state); + CheckAndNotify(EVENT_P2P_STATE_CHANGE, state); + } -void EventManager::DeleteHanderRef(std::set& setRefs, napi_value handler) { - for (auto& each : setRefs) { - napi_value handlerTemp = nullptr; - napi_get_reference_value(m_env, each, &handlerTemp); - bool isEqual = false; - napi_strict_equals(m_env, handlerTemp, handler, &isEqual); - if (isEqual) { - napi_delete_reference(m_env, each); - setRefs.erase(each); - return; - } + void OnP2pPersistentGroupsChanged(void) override { + WIFI_LOGI("received persistent group changed event"); + CheckAndNotify(EVENT_P2P_PERSISTENT_GROUP_CHANGE, nullptr); } -} -void EventManager::DeleteAllHanderRef(std::set& setRefs) { - for (auto& each : setRefs) { - napi_delete_reference(m_env, each); + void OnP2pThisDeviceChanged(const WifiP2pDevice& device) override { + WIFI_LOGI("received this device changed event"); + CheckAndNotify(EVENT_P2P_DEVICE_STATE_CHANGE, device); } - setRefs.clear(); -} -bool EventManager::UnsubscribeEvent(const std::string& name, napi_value handler) { - WIFI_LOGI("Unsubscribe event: %{public}s", name.c_str()); + void OnP2pPeersChanged(const std::vector& devices) override { + WIFI_LOGI("received peers changed event: %{public}d", (int)devices.size()); + CheckAndNotify(EVENT_P2P_PEER_DEVICE_CHANGE, devices); + } - if (!IsEventTypeExist(name)) { - WIFI_LOGE("Unsubscribe event is not a valid event: %{public}s", name.c_str()); - return false; + void OnP2pServicesChanged(const std::vector& srvInfo) override { } - bool isNeedUnsubscribe = false; - std::unique_lock guard(g_regInfoMutex); - std::map::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; + void OnP2pConnectionChanged(const WifiP2pLinkedInfo& info) override { + WIFI_LOGI("received connection changed event"); + CheckAndNotify(EVENT_P2P_CONN_STATE_CHANGE, info); } - 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; - } + + void OnP2pDiscoveryChanged(bool isChange) override { + WIFI_LOGI("received discovery state changed event"); + CheckAndNotify(EVENT_P2P_DISCOVERY_CHANGE, (int)isChange); } - return true; -} -void EventManager::SetEventType(const std::string& type) { - m_eventType = type; -} + void OnP2pActionResult(P2pActionCallback action, ErrCode code) override { + } -napi_env EventManager::GetEnv() { - return m_env; -} + OHOS::sptr AsObject() override { + return nullptr; + } +}; napi_value On(napi_env env, napi_callback_info cbinfo) { TRACE_FUNC_CALL; @@ -373,16 +322,10 @@ napi_value On(napi_env env, napi_callback_info cbinfo) { 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"); - } + char type[64] = {0}; + size_t typeLen = 0; + napi_get_value_string_utf8(env, argv[0], type, sizeof(type), &typeLen); + EventRegister::GetInstance().Register(env, type, argv[1]); napi_value result = nullptr; napi_get_undefined(env, &result); return result; @@ -408,42 +351,164 @@ napi_value Off(napi_env env, napi_callback_info cbinfo) { 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"); - } + char type[64] = {0}; + size_t typeLen = 0; + napi_get_value_string_utf8(env, argv[0], type, sizeof(type), &typeLen); + EventRegister::GetInstance().Unregister(env, type, argc >= requireArgcWithCb ? argv[1] : nullptr); napi_value result = nullptr; napi_get_undefined(env, &result); return result; } -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); +sptr wifiDeviceCallback = + sptr(new (std::nothrow) WifiNapiDeviceEventCallback()); - EventManager *eventManager = new EventManager(env, thisVar); - if (eventManager == nullptr) { - WIFI_LOGE("Init listener constructor failed"); - return nullptr; +sptr wifiScanCallback = + sptr(new (std::nothrow) WifiNapiScanEventCallback()); + +sptr wifiHotspotCallback = + sptr(new (std::nothrow) WifiNapiHotspotEventCallback()); + +sptr wifiP2pCallback = + sptr(new (std::nothrow) WifiNapiP2pEventCallback()); + +bool EventRegister::isEventRegistered = false; + +ErrCode EventRegister::RegisterWifiEvents() +{ + std::unique_ptr wifiStaPtr = WifiDevice::GetInstance(WIFI_DEVICE_ABILITY_ID); + if (wifiStaPtr == nullptr) { + WIFI_LOGE("Register sta event get instance failed!"); + return WIFI_OPT_FAILED; + } + ErrCode ret = wifiStaPtr->RegisterCallBack(wifiDeviceCallback); + if (ret != WIFI_OPT_SUCCESS) { + WIFI_LOGE("Register sta event failed!"); + return ret; + } + + std::unique_ptr wifiScanPtr = WifiScan::GetInstance(WIFI_SCAN_ABILITY_ID); + if (wifiScanPtr == nullptr) { + WIFI_LOGE("Register scan event get instance failed!"); + return WIFI_OPT_FAILED; + } + ret = wifiScanPtr->RegisterCallBack(wifiScanCallback); + if (ret != WIFI_OPT_SUCCESS) { + WIFI_LOGE("Register scan event failed!"); + return ret; + } + + std::unique_ptr wifiHotspotPtr = WifiHotspot::GetInstance(WIFI_HOTSPOT_ABILITY_ID); + if (wifiHotspotPtr == nullptr) { + WIFI_LOGE("Register hotspot event get instance failed!"); + return WIFI_OPT_FAILED; + } + ret = wifiHotspotPtr->RegisterCallBack(wifiHotspotCallback); + if (ret != WIFI_OPT_SUCCESS) { + WIFI_LOGE("Register hotspot event failed!"); + return ret; + } + + std::unique_ptr wifiP2pPtr = WifiP2p::GetInstance(WIFI_P2P_ABILITY_ID); + if (wifiP2pPtr == nullptr) { + WIFI_LOGE("Register p2p event get instance failed!"); + return WIFI_OPT_FAILED; + } + ret = wifiP2pPtr->RegisterCallBack(wifiP2pCallback); + if (ret != WIFI_OPT_SUCCESS) { + WIFI_LOGE("Register p2p event failed!"); + return ret; + } + return ret; +} + +EventRegister& EventRegister::GetInstance() +{ + static EventRegister inst; + return inst; +} + +bool EventRegister::IsEventSupport(const std::string& type) +{ + return g_supportEventList.find(type) != g_supportEventList.end(); +} + +void EventRegister::Register(const napi_env& env, const std::string& type, napi_value handler) +{ + WIFI_LOGI("Register event: %{public}s, env: %{public}p", type.c_str(), env); + + if (!IsEventSupport(type)) { + WIFI_LOGE("Register type error or not support!"); + return; + } + std::unique_lock guard(g_regInfoMutex); + if (!isEventRegistered) { + if (RegisterWifiEvents() != WIFI_OPT_SUCCESS) { + return; + } + isEventRegistered = true; + } + napi_ref handlerRef = nullptr; + napi_create_reference(env, handler, 1, &handlerRef); + RegObj regObj(env, handlerRef); + auto iter = g_eventRegisterInfo.find(type); + if (iter == g_eventRegisterInfo.end()) { + g_eventRegisterInfo[type] = std::vector{regObj}; + } else { + iter->second.emplace_back(regObj); + } +} + +void EventRegister::DeleteRegisterObj(std::vector& vecRegObjs, napi_value& handler) +{ + auto iter = vecRegObjs.begin(); + for (; iter != vecRegObjs.end();) { + napi_value handlerTemp = nullptr; + napi_get_reference_value(iter->m_regEnv, iter->m_regHanderRef, &handlerTemp); + bool isEqual = false; + napi_strict_equals(iter->m_regEnv, handlerTemp, handler, &isEqual); + if (isEqual) { + napi_delete_reference(iter->m_regEnv, iter->m_regHanderRef); + WIFI_LOGI("Delete register object ref."); + iter = vecRegObjs.erase(iter); + } else { + ++iter; + } + } +} + +void EventRegister::DeleteAllRegisterObj(std::vector& vecRegObjs) +{ + for (auto& each : vecRegObjs) { + napi_delete_reference(each.m_regEnv, each.m_regHanderRef); + } + vecRegObjs.clear(); +} + +void EventRegister::Unregister(const napi_env& env, const std::string& type, napi_value handler) +{ + WIFI_LOGI("Unregister event: %{public}s, env: %{public}p", type.c_str(), env); + + if (!IsEventSupport(type)) { + WIFI_LOGE("Unregister type error or not support!"); + return; + } + + std::unique_lock guard(g_regInfoMutex); + auto iter = g_eventRegisterInfo.find(type); + if (iter == g_eventRegisterInfo.end()) { + WIFI_LOGE("Unregister type not registered!"); + return; + } + if (handler != nullptr) { + DeleteRegisterObj(iter->second, handler); + } else { + WIFI_LOGW("All callback is unsubscribe for event: %{public}s", type.c_str()); + DeleteAllRegisterObj(iter->second); + } + if (iter->second.empty()) { + g_eventRegisterInfo.erase(iter); } - 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 diff --git a/interfaces/innerkits/native_cpp/napi/wifi_napi_event.h b/interfaces/innerkits/native_cpp/napi/wifi_napi_event.h index f3a4238e3..1928a2149 100755 --- a/interfaces/innerkits/native_cpp/napi/wifi_napi_event.h +++ b/interfaces/innerkits/native_cpp/napi/wifi_napi_event.h @@ -1,5 +1,5 @@ /* - * Copyright (C) 2021 Huawei Device Co., Ltd. + * Copyright (C) 2021-2022 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -20,85 +20,102 @@ #include #include #include "napi/native_api.h" -#include "common_event_manager.h" +#include "wifi_errcode.h" +#include +#include "wifi_hotspot.h" namespace OHOS { namespace Wifi { - -typedef void (*UserDefinedEventProcessFunc)(const napi_env& env, const std::string& type, - const OHOS::EventFwk::CommonEventData& data); - -class Event { +class AsyncEventData { public: - Event(napi_env env, std::string& name) : m_env(env), m_name(name) { + napi_env env; + napi_ref callbackRef; + napi_value jsEvent; + + explicit AsyncEventData(napi_env e, napi_ref r, napi_value v) { + env = e; + callbackRef = r; + jsEvent = v; } - virtual ~Event() { - } - - virtual napi_value PackResult() = 0; - - void SetName(std::string& name); + AsyncEventData() = delete; - std::string GetName(); - - napi_env GetEnv(); - -private: - napi_env m_env; - std::string m_name; + virtual ~AsyncEventData() { + } }; -class WifiCommonEvent: public Event { +class RegObj { public: - WifiCommonEvent(napi_env env, std::string& name, int value) : Event(env, name), m_value(value) { + RegObj() : m_regEnv(0), m_regHanderRef(nullptr) { + } + explicit RegObj(const napi_env& env, const napi_ref& ref) { + m_regEnv = env; + m_regHanderRef = ref; } - virtual napi_value PackResult(); + ~RegObj() { + } -private: - int m_value; + napi_env m_regEnv; + napi_ref m_regHanderRef; }; -class WifiEventSubscriber : public OHOS::EventFwk::CommonEventSubscriber { -public: - explicit WifiEventSubscriber(const OHOS::EventFwk::CommonEventSubscribeInfo &subscribeInfo) : - CommonEventSubscriber(subscribeInfo) { - } +static std::shared_mutex g_regInfoMutex; +static std::map> g_eventRegisterInfo; - virtual ~WifiEventSubscriber() { +class NapiEvent { +public: + bool CheckIsRegister(const std::string& type); + napi_value CreateResult(const napi_env& env, int value); + napi_value CreateResult(const napi_env& env, const StationInfo& info); + napi_value CreateResult(const napi_env& env, napi_value placehoders); + napi_value CreateResult(const napi_env& env, const WifiP2pDevice& device); + napi_value CreateResult(const napi_env& env, const std::vector& devices); + napi_value CreateResult(const napi_env& env, const WifiP2pLinkedInfo& info); + void EventNotify(AsyncEventData *asyncEvent); + + template + void CheckAndNotify(const std::string& type, const T& obj) { + std::shared_lock guard(g_regInfoMutex); + if (!CheckIsRegister(type)) { + return; + } + + std::vector& vecObj = g_eventRegisterInfo[type]; + for (auto& each : vecObj) { + napi_value result = CreateResult(each.m_regEnv, obj); + AsyncEventData *asyncEvent = new AsyncEventData(each.m_regEnv, each.m_regHanderRef, result); + if (asyncEvent == nullptr) { + return; + } + EventNotify(asyncEvent); + } } - - virtual void OnReceiveEvent(const OHOS::EventFwk::CommonEventData &data) override; }; -class EventRegisterInfo; -class EventManager { +class EventRegister { public: - EventManager(napi_env env, napi_value thisVar); - virtual ~EventManager(); + EventRegister() { + } + ~EventRegister() { + } - 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(); + static EventRegister& GetInstance(); -private: - bool SubscribeServiceEvent(const std::string& event); - bool UnsubscribeServiceEvent(const std::string& event); - void DeleteHanderRef(std::set& setRefs, napi_value handler); - void DeleteAllHanderRef(std::set& setRefs); - void SetEventType(const std::string& type); + void Register(const napi_env& env, const std::string& type, napi_value handler); + void Unregister(const napi_env& env, const std::string& type, napi_value handler); private: - napi_env m_env; - napi_ref m_thisVarRef; - std::string m_eventType; + ErrCode RegisterWifiEvents(); + bool IsEventSupport(const std::string& type); + void DeleteRegisterObj(std::vector& vecRegObjs, napi_value& handler); + void DeleteAllRegisterObj(std::vector& vecRegObjs); + + static bool isEventRegistered; }; napi_value On(napi_env env, napi_callback_info cbinfo); napi_value Off(napi_env env, napi_callback_info cbinfo); -napi_value EventListenerConstructor(napi_env env, napi_callback_info cbinfo); } // namespace Wifi } // namespace OHOS diff --git a/interfaces/innerkits/native_cpp/napi/wifi_napi_p2p.cpp b/interfaces/innerkits/native_cpp/napi/wifi_napi_p2p.cpp index 8fa4f3418..443b76f3f 100755 --- a/interfaces/innerkits/native_cpp/napi/wifi_napi_p2p.cpp +++ b/interfaces/innerkits/native_cpp/napi/wifi_napi_p2p.cpp @@ -1,5 +1,5 @@ /* - * Copyright (C) 2021 Huawei Device Co., Ltd. + * Copyright (C) 2021-2022 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -25,7 +25,7 @@ std::unique_ptr wifiP2pPtr = WifiP2p::GetInstance(WIFI_P2P_ABILITY_ID); napi_value EnableP2p(napi_env env, napi_callback_info info) { TRACE_FUNC_CALL; - NAPI_ASSERT(env, wifiP2pPtr != nullptr, "[NAPI] Wifi p2p instance is null."); + NAPI_ASSERT(env, wifiP2pPtr != nullptr, "Wifi p2p instance is null."); ErrCode ret = wifiP2pPtr->EnableP2p(); napi_value result; @@ -36,7 +36,7 @@ napi_value EnableP2p(napi_env env, napi_callback_info info) napi_value DisableP2p(napi_env env, napi_callback_info info) { TRACE_FUNC_CALL; - NAPI_ASSERT(env, wifiP2pPtr != nullptr, "[NAPI] Wifi p2p instance is null."); + NAPI_ASSERT(env, wifiP2pPtr != nullptr, "Wifi p2p instance is null."); ErrCode ret = wifiP2pPtr->DisableP2p(); napi_value result; @@ -64,7 +64,7 @@ static void WfdInfoToJs(const napi_env& env, const WifiP2pWfdInfo& wfdInfo, napi SetValueInt32(env, "maxThroughput", wfdInfo.GetMaxThroughput(), result); } -static bool DeviceInfosToJs(const napi_env& env, +static ErrCode DeviceInfosToJs(const napi_env& env, const std::vector& vecDevices, napi_value& arrayResult) { uint32_t idx = 0; @@ -80,13 +80,13 @@ static bool DeviceInfosToJs(const napi_env& env, napi_status status = napi_set_element(env, arrayResult, idx++, eachObj); if (status != napi_ok) { WIFI_LOGE("wifi napi set element error: %{public}d, idx: %{public}d", status, idx - 1); - return false; + return WIFI_OPT_FAILED; } } - return true; + return WIFI_OPT_SUCCESS; } -static bool GroupInfosToJs(const napi_env& env, WifiP2pGroupInfo& groupInfo, napi_value& result) +static ErrCode GroupInfosToJs(const napi_env& env, WifiP2pGroupInfo& groupInfo, napi_value& result) { SetValueBool(env, "isP2pGroupOwner", groupInfo.IsGroupOwner(), result); SetValueUtf8String(env, "passphrase", groupInfo.GetPassphrase().c_str(), result); @@ -105,22 +105,22 @@ static bool GroupInfosToJs(const napi_env& env, WifiP2pGroupInfo& groupInfo, nap napi_status status = napi_set_named_property(env, result, "owner", owner); if (status != napi_ok) { WIFI_LOGE("napi_set_named_property owner fail"); - return false; + return WIFI_OPT_FAILED; } if (!groupInfo.IsClientDevicesEmpty()) { const std::vector& vecDevices = groupInfo.GetClientDevices(); napi_value devices; napi_create_array_with_length(env, vecDevices.size(), &devices); - if (!DeviceInfosToJs(env, vecDevices, devices)) { - return false; + if (DeviceInfosToJs(env, vecDevices, devices) != WIFI_OPT_SUCCESS) { + return WIFI_OPT_FAILED; } status = napi_set_named_property(env, result, "clientDevices", devices); if (status != napi_ok) { WIFI_LOGE("napi_set_named_property clientDevices fail"); - return false; + return WIFI_OPT_FAILED; } } - return true; + return WIFI_OPT_SUCCESS; } napi_value GetCurrentGroup(napi_env env, napi_callback_info info) @@ -139,13 +139,13 @@ napi_value GetCurrentGroup(napi_env env, napi_callback_info info) asyncContext->executeFunc = [&](void* data) -> void { P2pGroupInfoAsyncContext *context = static_cast(data); TRACE_FUNC_CALL_NAME("wifiP2pPtr->GetCurrentGroup"); - context->isSuccess = (wifiP2pPtr->GetCurrentGroup(context->groupInfo) == WIFI_OPT_SUCCESS); + context->errorCode = wifiP2pPtr->GetCurrentGroup(context->groupInfo); }; asyncContext->completeFunc = [&](void* data) -> void { P2pGroupInfoAsyncContext *context = static_cast(data); napi_create_object(context->env, &context->result); - context->isSuccess = GroupInfosToJs(context->env, context->groupInfo, context->result); + context->errorCode = GroupInfosToJs(context->env, context->groupInfo, context->result); WIFI_LOGI("Push get current group result to client"); }; @@ -168,7 +168,7 @@ napi_value StartP2pListen(napi_env env, napi_callback_info info) NAPI_ASSERT(env, valueType == napi_number, "Wrong argument 1 type. napi_number expected."); NAPI_ASSERT(env, value2Type == napi_object, "Wrong argument 2 type. napi_number expected."); - NAPI_ASSERT(env, wifiP2pPtr != nullptr, "[NAPI] Wifi p2p instance is null."); + NAPI_ASSERT(env, wifiP2pPtr != nullptr, "Wifi p2p instance is null."); int period; int interval; napi_get_value_int32(env, argv[0], &period); @@ -182,7 +182,7 @@ napi_value StartP2pListen(napi_env env, napi_callback_info info) napi_value StopP2pListen(napi_env env, napi_callback_info info) { TRACE_FUNC_CALL; - NAPI_ASSERT(env, wifiP2pPtr != nullptr, "[NAPI] Wifi p2p instance is null."); + NAPI_ASSERT(env, wifiP2pPtr != nullptr, "Wifi p2p instance is null."); ErrCode ret = wifiP2pPtr->StopP2pListen(); napi_value result; @@ -202,7 +202,7 @@ napi_value DeletePersistentGroup(napi_env env, napi_callback_info info) napi_typeof(env, argv[0], &valueType); NAPI_ASSERT(env, valueType == napi_number, "Wrong argument type. napi_number expected."); - NAPI_ASSERT(env, wifiP2pPtr != nullptr, "[NAPI] Wifi p2p instance is null."); + NAPI_ASSERT(env, wifiP2pPtr != nullptr, "Wifi p2p instance is null."); WifiP2pGroupInfo groupInfo; int netId = -999; napi_get_value_int32(env, argv[0], &netId); @@ -216,7 +216,7 @@ napi_value DeletePersistentGroup(napi_env env, napi_callback_info info) napi_value StartDiscoverDevices(napi_env env, napi_callback_info info) { TRACE_FUNC_CALL; - NAPI_ASSERT(env, wifiP2pPtr != nullptr, "[NAPI] Wifi p2p instance is null."); + NAPI_ASSERT(env, wifiP2pPtr != nullptr, "Wifi p2p instance is null."); ErrCode ret = wifiP2pPtr->DiscoverDevices(); napi_value result; @@ -227,7 +227,7 @@ napi_value StartDiscoverDevices(napi_env env, napi_callback_info info) napi_value StopDiscoverDevices(napi_env env, napi_callback_info info) { TRACE_FUNC_CALL; - NAPI_ASSERT(env, wifiP2pPtr != nullptr, "[NAPI] Wifi p2p instance is null."); + NAPI_ASSERT(env, wifiP2pPtr != nullptr, "Wifi p2p instance is null."); ErrCode ret = wifiP2pPtr->StopDiscoverDevices(); napi_value result; @@ -250,14 +250,14 @@ napi_value GetP2pDevices(napi_env env, napi_callback_info info) asyncContext->executeFunc = [&](void* data) -> void { QueryP2pDeviceAsyncContext *context = static_cast(data); - context->isSuccess = (wifiP2pPtr->QueryP2pDevices(context->vecP2pDevices) == WIFI_OPT_SUCCESS); + context->errorCode = wifiP2pPtr->QueryP2pDevices(context->vecP2pDevices); WIFI_LOGI("GetP2pDeviceList, size: %{public}zu", context->vecP2pDevices.size()); }; asyncContext->completeFunc = [&](void* data) -> void { QueryP2pDeviceAsyncContext *context = static_cast(data); napi_create_array_with_length(context->env, context->vecP2pDevices.size(), &context->result); - context->isSuccess = DeviceInfosToJs(context->env, context->vecP2pDevices, context->result); + context->errorCode = DeviceInfosToJs(context->env, context->vecP2pDevices, context->result); WIFI_LOGI("Push P2p Device List to client"); }; @@ -323,7 +323,7 @@ napi_value P2pConnect(napi_env env, napi_callback_info info) napi_typeof(env, argv[0], &valueType); NAPI_ASSERT(env, valueType == napi_object, "Wrong argument type. Object expected."); - NAPI_ASSERT(env, wifiP2pPtr != nullptr, "[NAPI] Wifi p2p instance is null."); + NAPI_ASSERT(env, wifiP2pPtr != nullptr, "Wifi p2p instance is null."); WifiP2pConfig config; JsObjToP2pConfig(env, argv[0], config); ErrCode ret = wifiP2pPtr->P2pConnect(config); @@ -338,7 +338,7 @@ napi_value P2pConnect(napi_env env, napi_callback_info info) napi_value P2pDisConnect(napi_env env, napi_callback_info info) { TRACE_FUNC_CALL; - NAPI_ASSERT(env, wifiP2pPtr != nullptr, "[NAPI] Wifi p2p instance is null."); + NAPI_ASSERT(env, wifiP2pPtr != nullptr, "Wifi p2p instance is null."); ErrCode ret = wifiP2pPtr->P2pDisConnect(); napi_value result; @@ -358,7 +358,7 @@ napi_value CreateGroup(napi_env env, napi_callback_info info) napi_typeof(env, argv[0], &valueType); NAPI_ASSERT(env, valueType == napi_object, "Wrong argument type. Object expected."); - NAPI_ASSERT(env, wifiP2pPtr != nullptr, "[NAPI] Wifi p2p instance is null."); + NAPI_ASSERT(env, wifiP2pPtr != nullptr, "Wifi p2p instance is null."); WifiP2pConfig config; JsObjToP2pConfig(env, argv[0], config); @@ -371,7 +371,7 @@ napi_value CreateGroup(napi_env env, napi_callback_info info) napi_value RemoveGroup(napi_env env, napi_callback_info info) { TRACE_FUNC_CALL; - NAPI_ASSERT(env, wifiP2pPtr != nullptr, "[NAPI] Wifi p2p instance is null."); + NAPI_ASSERT(env, wifiP2pPtr != nullptr, "Wifi p2p instance is null."); ErrCode ret = wifiP2pPtr->RemoveGroup(); napi_value result; @@ -403,7 +403,7 @@ napi_value GetP2pLinkedInfo(napi_env env, napi_callback_info info) asyncContext->executeFunc = [&](void* data) -> void { P2pLinkedInfoAsyncContext *context = static_cast(data); TRACE_FUNC_CALL_NAME("wifiP2pPtr->QueryP2pLinkedInfo"); - context->isSuccess = (wifiP2pPtr->QueryP2pLinkedInfo(context->linkedInfo) == WIFI_OPT_SUCCESS); + context->errorCode = wifiP2pPtr->QueryP2pLinkedInfo(context->linkedInfo); }; asyncContext->completeFunc = [&](void* data) -> void { diff --git a/interfaces/innerkits/native_cpp/napi/wifi_napi_p2p.h b/interfaces/innerkits/native_cpp/napi/wifi_napi_p2p.h index c7eeb584e..db359f4c6 100755 --- a/interfaces/innerkits/native_cpp/napi/wifi_napi_p2p.h +++ b/interfaces/innerkits/native_cpp/napi/wifi_napi_p2p.h @@ -1,5 +1,5 @@ /* - * Copyright (C) 2021 Huawei Device Co., Ltd. + * Copyright (C) 2021-2022 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at diff --git a/interfaces/innerkits/native_cpp/napi/wifi_napi_utils.cpp b/interfaces/innerkits/native_cpp/napi/wifi_napi_utils.cpp index a93b9c555..3677e26ef 100755 --- a/interfaces/innerkits/native_cpp/napi/wifi_napi_utils.cpp +++ b/interfaces/innerkits/native_cpp/napi/wifi_napi_utils.cpp @@ -1,5 +1,5 @@ /* - * Copyright (C) 2021 Huawei Device Co., Ltd. + * Copyright (C) 2021-2022 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -236,15 +236,19 @@ static napi_value DoCallBackAsyncWork(const napi_env& env, AsyncContext *asyncCo napi_get_undefined(env, &undefine); napi_value callback; context->completeFunc(data); - if (context->isSuccess) { + constexpr int ARGS_TWO = 2; + napi_value result[ARGS_TWO] = {nullptr}; + napi_create_uint32(env, context->errorCode, &result[0]); + result[1] = context->result; + if (context->errorCode == ERR_CODE_SUCCESS) { napi_get_reference_value(env, context->callback[0], &callback); - napi_call_function(env, nullptr, callback, 1, &context->result, &undefine); + napi_call_function(env, nullptr, callback, ARGS_TWO, 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); + napi_call_function(env, nullptr, callback, ARGS_TWO, result, &undefine); } else { - WIFI_LOGE("Get scan info callback func is null"); + WIFI_LOGE("Get callback func[1] is null"); } } if (context->callback[0] != nullptr) { @@ -283,7 +287,7 @@ static napi_value DoPromiseAsyncWork(const napi_env& env, AsyncContext *asyncCon } AsyncContext *context = (AsyncContext *)data; context->completeFunc(data); - if (context->isSuccess) { + if (context->errorCode == ERR_CODE_SUCCESS) { napi_resolve_deferred(context->env, context->deferred, context->result); } else { napi_reject_deferred(context->env, context->deferred, context->result); diff --git a/interfaces/innerkits/native_cpp/napi/wifi_napi_utils.h b/interfaces/innerkits/native_cpp/napi/wifi_napi_utils.h index 3364788aa..e5d23b1f0 100755 --- a/interfaces/innerkits/native_cpp/napi/wifi_napi_utils.h +++ b/interfaces/innerkits/native_cpp/napi/wifi_napi_utils.h @@ -1,5 +1,5 @@ /* - * Copyright (C) 2021 Huawei Device Co., Ltd. + * Copyright (C) 2021-2022 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -40,6 +40,8 @@ private: #define TRACE_FUNC_CALL TraceFuncCall func(__func__) #define TRACE_FUNC_CALL_NAME(name) TraceFuncCall funcName(name) +constexpr int ERR_CODE_SUCCESS = 0; + class AsyncContext { public: napi_env env; @@ -50,7 +52,7 @@ public: std::function completeFunc; napi_value resourceName; napi_value result; - bool isSuccess; + int errorCode; AsyncContext(napi_env e, napi_async_work w = nullptr, napi_deferred d = nullptr) { @@ -60,7 +62,7 @@ public: executeFunc = nullptr; completeFunc = nullptr; result = nullptr; - isSuccess = false; + errorCode = ERR_CODE_SUCCESS; } AsyncContext() = delete; diff --git a/interfaces/kits/jskits/@ohos.wifi.d.ts b/interfaces/kits/jskits/@ohos.wifi.d.ts index cc24ede20..a503f80f5 100755 --- a/interfaces/kits/jskits/@ohos.wifi.d.ts +++ b/interfaces/kits/jskits/@ohos.wifi.d.ts @@ -393,12 +393,12 @@ declare namespace wifi { function p2pConnect(config: WifiP2PConfig): boolean; /** - * Disconnects a P2P connection. + * Canceling a P2P connection. * * @return Returns {@code true} if the scanning is successful; returns {@code false} otherwise. * @since 8 */ - function p2pDisconnect(): boolean; + function p2pCancelConnect(): boolean; /** * Discovers Wi-Fi P2P devices. @@ -416,26 +416,6 @@ declare namespace wifi { */ function stopDiscoveryDevices(): boolean; - /** - * Enables P2P listening. - * - *

After P2P listening is enabled, your application can listen for and respond to requests from other devices. - * - * @return Returns {@code true} if the scanning is successful; returns {@code false} otherwise. - * @since 8 - */ - function startListen(): boolean; - - /** - * Disables P2P listening. - * - *

After P2P listening is disabled, your application cannot listen for requests from other devices. - * - * @return Returns {@code true} if the scanning is successful; returns {@code false} otherwise. - * @since 8 - */ - function stopListen(): boolean; - /** * Deletes the persistent P2P group with the specified network ID. * @@ -950,7 +930,7 @@ declare namespace wifi { deviceAddress: string; /** Primary device type */ - primaryDeviceType: number; + primaryDeviceType: string; /** Device status */ devStatus: P2pDeviceStatus; -- Gitee