diff --git a/dsoftbus/OhOeCommunication/OpenHarmonyAppSample/entry/src/main/cpp/CMakeLists.txt b/dsoftbus/OhOeCommunication/OpenHarmonyAppSample/entry/src/main/cpp/CMakeLists.txt new file mode 100644 index 0000000000000000000000000000000000000000..dc6cccf5cec1e2c0637bd58c0dee106462002e3c --- /dev/null +++ b/dsoftbus/OhOeCommunication/OpenHarmonyAppSample/entry/src/main/cpp/CMakeLists.txt @@ -0,0 +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. +# the minimum version of CMake.指明了对cmake的最低(高)版本的要求 +cmake_minimum_required(VERSION 3.4.1) +#配置项目信息 +project(softbus_client_run CXX) +#指定编程语言 +set(NATIVERENDER_ROOT_PATH ${CMAKE_CURRENT_SOURCE_DIR}) +#设置头文件的搜索目录 +include_directories( + ${NATIVERENDER_ROOT_PATH} + ${NATIVERENDER_ROOT_PATH}/include + ) +# 添加名为xxx的库 +add_library(${PROJECT_NAME} SHARED softbus_client_interface.cpp softbus_client_run.cpp) +#构建此可执行文件需要链接的库 +target_link_libraries(${PROJECT_NAME} PUBLIC libace_napi.z.so libsec_shared.z.so libsoftbus_client.z.so libhilog_ndk.z.so libc++.a) diff --git a/dsoftbus/OhOeCommunication/OpenHarmonyAppSample/entry/src/main/cpp/include/softbus_client_interface.h b/dsoftbus/OhOeCommunication/OpenHarmonyAppSample/entry/src/main/cpp/include/softbus_client_interface.h new file mode 100644 index 0000000000000000000000000000000000000000..a012023a8bc0179543943c3aa34165f49e0083ba --- /dev/null +++ b/dsoftbus/OhOeCommunication/OpenHarmonyAppSample/entry/src/main/cpp/include/softbus_client_interface.h @@ -0,0 +1,97 @@ +#ifndef SOFTBUS_CLIENT_H +#define SOFTBUS_CLIENT_H +#undef LOG_TAG +#define LOG_TAG "SoftBusClient" + +#include "softbus_bus_center.h" +#include +#include +typedef void(callBack)(std::string fileName); + +const std::string PICTURE_SAVE_PATH = "/data/storage/el2/base/haps/entry/files/"; + +extern std::map sessionNameAndId; + +struct DeviceDetail { + std::string deviceName; + std::string ipaddress; + int port; + std::string deviceId; + std::string networkId; + int sessionId; +}; +/** + * @brief Creates a session server based on a package name and session name. + * @return Returns 0 if the operation is successful; return other numbers when the operation was unsuccessful. + */ +int CreateSessionServerInterface(callBack *func); + +/** + * @brief Remove a session server based on a package name and session name. + */ +void RemoveSessionServerInterface(); + +/** + * @brief Close session by session id. + */ +void CloseSessionInterface(int sessionId); + +/** + * @brief Publishes a specified service. + * @return Returns 0 if the operation is successful; return other numbers when the operation was unsuccessful. + */ +int PublishServiceInterface(); + +/** + * @brief Stop Publishing Services + */ +void UnPublishServiceInterface(); + +/** + * @brief Subscribes to a specified service. + * @return Returns 0 if the operation is successful; return other numbers when the operation was unsuccessful. + */ +int DiscoveryInterface(); + +/** + * @brief Stop subscribes to a specified service. + */ +void StopDiscoveryInterface(); + +/** + * @brief Obtains basic information about all the online devices. + * @return + */ +int GetAllNodeDeviceInfoInterface(NodeBasicInfo **dev); + +/** + * Obtain information about the connected device + * @param deviceDetail + * @param dev + * @param devNum + * @return + */ +int GetDeviceDetailInterface(DeviceDetail *deviceDetail, NodeBasicInfo *dev, int devNum); + +/** + *@brief + */ +void FreeNodeInfoInterface(NodeBasicInfo *dev); + +/** + * @brief Initiate a session open request, which is an asynchronous process. + * @param peerNetworkId + * @return + */ +int OpenSessionInterface(const char *peerNetworkId, const char *peerSessionName); + +/** + * @brief Sends data based on a session ID. + * @param sessionId Session id of peer device + * @param data Data to be sent + * @param len Length of data to be sent + * @return Returns 0 if the operation is successful; return other numbers when the operation was unsuccessful. + */ +int SendBytesInterface(int sessionId, const void *data, unsigned int len); + +#endif //SOFTBUS_CLIENT_H \ No newline at end of file diff --git a/dsoftbus/OhOeCommunication/OpenHarmonyAppSample/entry/src/main/cpp/softbus_client_interface.cpp b/dsoftbus/OhOeCommunication/OpenHarmonyAppSample/entry/src/main/cpp/softbus_client_interface.cpp new file mode 100644 index 0000000000000000000000000000000000000000..553b6e1447cb4a4fa1abf8d3386687e84150d1c8 --- /dev/null +++ b/dsoftbus/OhOeCommunication/OpenHarmonyAppSample/entry/src/main/cpp/softbus_client_interface.cpp @@ -0,0 +1,403 @@ +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include "napi/native_api.h" +#include "hilog/log.h" +#include "softbus_client_interface.h" +#include "discovery_service.h" +#include "softbus_bus_center.h" +#include "session.h" +#include "softbus_common.h" + +using namespace std; + +#define PACKAGE_NAME "softbus_sample" +#define LOCAL_SESSION_NAME "session_test" +#define DEFAULT_PUBLISH_ID 123 +#define DEFAULT_CAPABILITY "osdCapability" +#define DEFAULT_SESSION_GROUP "group_test" + +const int DISCOVER_SLEEP_TIME = 1000; // 发现设备的等待时间,确保设备信息获取到 + +static callBack *callBackFunc; // 接收消息后传给APP侧的回调函数 +int g_sessionId; +std::map sessionNameAndId; // session name和session id的对应map +std::map deviceIdAndInfo; + +string getCurrentTime(); + +/** + * @brief 服务发布成功后的回调函数 + * + * @param publishId 服务id + */ +void PublishSuccess(int publishId) { + OH_LOG_INFO(LOG_APP, "[INFO] CB: publish %{public}d done", publishId); +} + +/** + * @brief 服务发布失败后的回调函数 + * + * @param publishId 服务ID + * @param reason 失败原因 + */ +void PublishFailed(int publishId, PublishFailReason reason) { + OH_LOG_ERROR(LOG_APP, "[ERROR] CB: publish %{public}d failed, reason=%{public}d", publishId, (int)reason); +} + +/** + * 连接通道建立后的接收到消息的回调函数 + * @param sessionId 建立连接的设备的sessionId,必须是中数据。 + * @param data 对端设备发送的数据 + * @param dataLength 对端设备发送数据的大小 + */ +void OnReceiveCallback(int sessionId, const void *data, unsigned int dataLength) { + OH_LOG_INFO(LOG_APP, "[INFO] The sessionId: %{public}d data is received and the callback function is started.", sessionId); + callBackFunc((char *)data); +} + +/** + * @brief 服务发布的封装接口 + * + * @return int 发布成功返回0,否则返回1 + */ +int PublishServiceInterface() { + OH_LOG_INFO(LOG_APP, "[INFO] Start to PublishService"); + PublishInfo info = { + .publishId = DEFAULT_PUBLISH_ID, + .mode = DISCOVER_MODE_PASSIVE, + .medium = COAP, + .freq = LOW, + .capability = DEFAULT_CAPABILITY, + .capabilityData = nullptr, + .dataLen = 0, + }; + IPublishCallback cb = { + .OnPublishSuccess = PublishSuccess, + .OnPublishFail = PublishFailed, + }; + + int hwpadPublicResult = PublishService(PACKAGE_NAME, &info, &cb); + return hwpadPublicResult; +} + +/** + * @brief 停止发布服务封装接口 + * + */ +void UnPublishServiceInterface() { + int ret; + ret = UnPublishService(PACKAGE_NAME, DEFAULT_PUBLISH_ID); + if (ret != 0) { + OH_LOG_ERROR(LOG_APP, "[ERROR] UnPublishService hwpad fail:%{public}d", ret); + } +} + +/** + * @brief 组网内设备探测到的回调函数 + * + * @param device 设备信息 + */ +void DeviceFound(const DeviceInfo *device) { + unsigned int i; + OH_LOG_INFO(LOG_APP, "[INFO] CB: Device has found:"); + OH_LOG_INFO(LOG_APP, "\tdevId=%{public}s", device->devId); + OH_LOG_INFO(LOG_APP, "\tdevName=%{public}s", device->devName); + OH_LOG_INFO(LOG_APP, "\tdevType=%{public}d", device->devType); + OH_LOG_INFO(LOG_APP, "\taddrNum=%{public}d", device->addrNum); + for (i = 0; i < device->addrNum; i++) { + OH_LOG_INFO(LOG_APP, "\taddr%{public}d:type=%{public}d,", i + 1, device->addr[i].type); + switch (device->addr[i].type) { + case CONNECTION_ADDR_WLAN: + case CONNECTION_ADDR_ETH: + OH_LOG_INFO(LOG_APP, "\tip=%{public}s,port=%{public}d,", device->addr[i].info.ip.ip, device->addr[i].info.ip.port); + break; + default: + break; + } + OH_LOG_INFO(LOG_APP, "\tpeerUid=%{public}s", device->addr[i].peerUid); + } + OH_LOG_INFO(LOG_APP, "\tcapabilityBitmapNum=%{public}d", device->capabilityBitmapNum); + for (i = 0; i < device->addrNum; i++) { + OH_LOG_INFO(LOG_APP, "\tcapabilityBitmap[%{public}d]=0x%x", i + 1, device->capabilityBitmap[i]); + } + OH_LOG_INFO(LOG_APP, "\tcustData=%{public}s", device->custData); + + DeviceDetail detail; + detail.deviceName = device->devName; + detail.deviceId = device->devId; + detail.ipaddress = device->addr[0].info.ip.ip; + detail.port = device->addr[0].info.ip.port; + deviceIdAndInfo[device->devId] = detail; +} + +/** + * @brief 探测组网内设备成功的回调函数 + * + * @param subscribeId 其他设备发布服务的ID + */ +void DiscoverySuccess(int subscribeId) { + OH_LOG_INFO(LOG_APP, "[INFO] CB: discover subscribeId=%{public}d", subscribeId); +} + +/** + * @brief 探测组网内设备失败的回调函数 + * + * @param subscribeId 其他设备发布服务的ID + * @param reason 失败原因 + */ +void DiscoveryFailed(int subscribeId, DiscoveryFailReason reason) { + OH_LOG_ERROR(LOG_APP, "[ERROR] CB: discover subscribeId=%{public}d failed, reason=%{public}d", subscribeId, (int)reason); +} + +/** + * @brief 开启组网内设备探测的封装函数 + * + * @return int 成功返回0,失败返回1 + */ +int DiscoveryInterface() { + OH_LOG_INFO(LOG_APP, "[INFO] Start to Discovery"); + SubscribeInfo info = { + .subscribeId = DEFAULT_PUBLISH_ID, + .mode = DISCOVER_MODE_ACTIVE, + .medium = COAP, + .freq = LOW, + .isSameAccount = false, + .isWakeRemote = false, + .capability = DEFAULT_CAPABILITY, + .capabilityData = nullptr, + .dataLen = 0, + }; + IDiscoveryCallback cb = { + .OnDeviceFound = DeviceFound, + .OnDiscoverFailed = DiscoveryFailed, + .OnDiscoverySuccess = DiscoverySuccess, + }; + + deviceIdAndInfo.clear(); + int hwpadDiscoveryResult = StartDiscovery(PACKAGE_NAME, &info, &cb); + sleep(DISCOVER_SLEEP_TIME); + return hwpadDiscoveryResult; +} + +/** + * @brief 停止其他设备探测的封装函数 + * + */ +void StopDiscoveryInterface() { + int ret; + ret = StopDiscovery(PACKAGE_NAME, DEFAULT_PUBLISH_ID); + if (ret) { + OH_LOG_ERROR(LOG_APP, "[ERROR] StopDiscovery fail:%{public}d", ret); + } +} + +/** + * @brief session通道建立的回调函数 + * + * @param sessionId 建立的session的id + * @param result session建立结果 + * @return int 成功返回0,失败返回1 + */ +int SessionOpened(int sessionId, int result) { + if (result == 0) { + g_sessionId = sessionId; + char peerSessionName[50]; + GetPeerSessionName(sessionId, peerSessionName, 50); + sessionNameAndId[peerSessionName] = sessionId; + OH_LOG_INFO(LOG_APP, "[INFO] CB: session %{public}d open success, session name is: %{public}s", sessionId, peerSessionName); + } else { + OH_LOG_ERROR(LOG_APP, "[ERROR] CB: session %{public}d open failed, result is: %{public}d", sessionId, result); + } + + return result; +} + +/** + * @brief session关闭 + * + * @param sessionId 要关闭的session的Id + */ +void SessionClosed(int sessionId) { + OH_LOG_INFO(LOG_APP, "[INFO] CB: session %{public}d closed", sessionId); +} + +/** + * @brief 其他设备通过sendMessage方法发送消息,接收数据后的回调函数 + * + * @param sessionId 和对端设备的session id + * @param data 接收到的数据 + * @param dataLen 接收到的数据长度 + */ +void MessageReceived(int sessionId, const void *data, unsigned int dataLen) { + OH_LOG_INFO(LOG_APP, "[INFO] CB: session %{public}d received %u bytes message=%{public}s", sessionId, dataLen, (const char *)data); +} + +/** + * @brief 创建session服务的封装接口,需要指定session打开后和接受消息后的回调函数 + * + * @param func 自定义接受消息后的回调函数 + * @return int 成功返回0,否则返回1 + */ +int CreateSessionServerInterface(callBack *func) { + OH_LOG_INFO(LOG_APP, "[INFO] Start to CreateSessionServer"); + callBackFunc = func; + const ISessionListener sessionCB = { + .OnSessionOpened = SessionOpened, + .OnSessionClosed = SessionClosed, + .OnBytesReceived = OnReceiveCallback, + .OnMessageReceived = MessageReceived, + }; + int hwpadSessionResult = CreateSessionServer(PACKAGE_NAME, LOCAL_SESSION_NAME, &sessionCB); + + return hwpadSessionResult; +} + +/** + * @brief 停止创建session的服务 + * + */ +void RemoveSessionServerInterface() { + int ret; + ret = RemoveSessionServer(PACKAGE_NAME, LOCAL_SESSION_NAME); + if (ret) { + OH_LOG_ERROR(LOG_APP, "[ERROR] RemoveSessionServer hwpad fail:%{public}d", ret); + } +} + +/** + * @brief 创建session的封装接口 + * + * @param peerNetworkId 对端设备的network id + * @param peerSessionName 对端设备的session名称 + * @return int 成功返回0,否则返回1 + */ +int OpenSessionInterface(const char *peerNetworkId, const char *peerSessionName) { + OH_LOG_INFO(LOG_APP, "[INFO] Start to open session peerNetworkId: %{public}s peerSessionName: %{public}s", peerNetworkId, peerSessionName); + int timeout = 5; + g_sessionId = -1; + + SessionAttribute attr = { + .dataType = TYPE_BYTES, + .linkTypeNum = 1, + .linkType = {LINK_TYPE_WIFI_WLAN_2G}, + .attr = {RAW_STREAM}, + }; + + int sessionId = OpenSession(LOCAL_SESSION_NAME, peerSessionName, peerNetworkId, + DEFAULT_SESSION_GROUP, &attr); + if (sessionId < 0) { + OH_LOG_ERROR(LOG_APP, "[ERROR] OpenSessionInterface fail, ret=%{public}d", sessionId); + return sessionId; + } + // 等待5s确保session id获取到 + while (timeout) { + if (g_sessionId == sessionId) { + OH_LOG_INFO(LOG_APP, "[INFO] Obtaining the sessionId of device (sessionName:%{public}s, networkId: %{public}s), sessionId is: %{public}d", + peerSessionName, peerNetworkId, sessionId); + return sessionId; + } + timeout--; + sleep(1); + } + return -1; +} + +/** + * @brief 关闭session的封装接口 + * + * @param sessionId 要关闭的session id + */ +void CloseSessionInterface(int sessionId) { + CloseSession(sessionId); +} + +/** + * @brief 获得组网内已认证的设备信息 + * + * @param dev 接收设备信息的指针 + * @return int 成功返回设备数量,失败返回1 + */ +int GetAllNodeDeviceInfoInterface(NodeBasicInfo **dev) { + int ret, num; + + ret = GetAllNodeDeviceInfo(PACKAGE_NAME, dev, &num); + if (ret) { + OH_LOG_ERROR(LOG_APP, "[ERROR] GetAllNodeDeviceInfo by %{public}s fail:%{public}d", PACKAGE_NAME, ret); + return -1; + } + + OH_LOG_INFO(LOG_APP, "[INFO] by %{public}s return %{public}d Node", PACKAGE_NAME, num); + return num; +} + +/** + * @brief 丰富通过GetAllNodeDeviceInfo接口获取的设备信息 + * + * @param deviceDetail 接收设备详细信息的指针 + * @param dev 通过GetAllNodeDeviceInfo获取的设备接口 + * @param devNum 发现的设备的数量 + * @return int 获取到信息的设备的数量 + */ +int GetDeviceDetailInterface(DeviceDetail *deviceDetail, NodeBasicInfo *dev, int devNum) { + char devId[UDID_BUF_LEN]; + int ret, count = 0; + for (int i = 0; i < devNum; i++) { + ret = GetNodeKeyInfo(PACKAGE_NAME, dev[i].networkId, NODE_KEY_UDID, (uint8_t *)devId, UDID_BUF_LEN); + if (ret == 0) { + deviceDetail[i] = deviceIdAndInfo[devId]; + deviceDetail[i].deviceName = dev[i].deviceName; + deviceDetail[i].networkId = dev[i].networkId; + OH_LOG_INFO(LOG_APP, "[INFO] Get device info: {deviceName: %{public}s, deviceId: %{public}s}", + deviceDetail[i].deviceName.c_str(), dev[i].networkId); + count++; + } + } + return count; +} + +/** + * @brief 释放发现的组网内的设备 + * + * @param dev 要释放的设备的指针 + */ +void FreeNodeInfoInterface(NodeBasicInfo *dev) { + FreeNodeInfo(dev); +} + +/** + * @brief 通过SendBytes方式发送数据的封装接口 + * + * @param sessionId 和目标设备建立的session的id + * @param data 发送的数据 + * @param len 发送数据的长度 + * @return int 成功返回0,否则返回1 + */ +int SendBytesInterface(int sessionId, const void *data, unsigned int len) { + int ret; + ret = SendBytes(sessionId, data, len); + if (ret) { + OH_LOG_INFO(LOG_APP, "[INFO] SendBytes fail:%{public}d", ret); + } + return ret; +} + +/*** + * 获取当前时间 + * @return + */ +string getCurrentTime() { + time_t rawTime; + time(&rawTime); + struct tm *timeInfo = localtime(&rawTime); + char buffer[256]; + strftime(buffer, 256, "%Y-%m-%d-%H-%M-%S", timeInfo); + return buffer; +} diff --git a/dsoftbus/OhOeCommunication/OpenHarmonyAppSample/entry/src/main/cpp/softbus_client_run.cpp b/dsoftbus/OhOeCommunication/OpenHarmonyAppSample/entry/src/main/cpp/softbus_client_run.cpp new file mode 100644 index 0000000000000000000000000000000000000000..a18b140c98a427140de4a5de23110a2820c4b91a --- /dev/null +++ b/dsoftbus/OhOeCommunication/OpenHarmonyAppSample/entry/src/main/cpp/softbus_client_run.cpp @@ -0,0 +1,277 @@ +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include "discovery_service.h" +#include "softbus_client_interface.h" +#include "napi/native_api.h" +#include "hilog/log.h" + +using namespace std; + +static napi_env envRef; +static napi_ref callbackRef; +NodeBasicInfo *dev; +static int openedSessionId; + +static void sessionDisconnect(int stepNum); + +static string getConnectedDeviceInfo(DeviceDetail *deviceDetails, int arrayLength); + +/** + * 建立连接前的初始化功能,包括创建sessionServer,发布软总线能力,发现同局域网下的设备等。 + * @return 初始化的结果。 + */ +static string sessionServerInit(callBack *func) { + int ret; + + // 创建sessionServer + ret = CreateSessionServerInterface(func); + if (ret) { + OH_LOG_ERROR(LOG_APP, "[ERROR] failed"); + return " failed"; + } + // 发布服务 + ret = PublishServiceInterface(); + if (ret) { + OH_LOG_ERROR(LOG_APP, "[ERROR] failed"); + sessionDisconnect(4); + return " failed"; + } + // 启动探测 + ret = DiscoveryInterface(); + if (ret) { + OH_LOG_ERROR(LOG_APP, "[ERROR] failed"); + sessionDisconnect(3); + return " failed"; + } + + OH_LOG_INFO(LOG_APP, "[INFO] Session server init success!!!"); + return "[INFO] Session server init success"; +} + +/** + * 发现组网内设备 + * @return 建立连接的设备信息 + */ +static string sessionConnect() { + + // 重新探测设备 + StopDiscoveryInterface(); + DiscoveryInterface(); + + openedSessionId = -1; + dev = nullptr; + int devNum = GetAllNodeDeviceInfoInterface(&dev); //返回组网内的设备数 + if (devNum <= 0) { + OH_LOG_ERROR(LOG_APP, "[ERROR] failed"); + return " failed"; + } + + DeviceDetail deviceDetails[devNum]; + int connectNum = GetDeviceDetailInterface(deviceDetails, dev, devNum); + OH_LOG_INFO(LOG_APP, "[INFO] Connected device count: %{public}d", connectNum); + + return getConnectedDeviceInfo(deviceDetails, connectNum); +} + +/*** + * 设备连接失败,或者手动关闭连接时调用,用于释放资源 + * @param stepNum 失败的步骤 + * @param sessionId 需要关闭的session id,默认为-1,表示使用不到该参数。 + */ +static void sessionDisconnect(int stepNum) { + switch (stepNum) { + case 0: + // 关闭session连接 + // closeAllSession(); + OH_LOG_INFO(LOG_APP, "[INFO] Session close end!!!"); + case 1: + // 释放节点信息 + FreeNodeInfoInterface(dev); + OH_LOG_INFO(LOG_APP, "[INFO] Node free end!!!"); + case 2: + // 取消探测 + StopDiscoveryInterface(); + OH_LOG_INFO(LOG_APP, "[INFO] Discovery stop end!!!"); + case 3: + // 关闭发布特定服务能力 + UnPublishServiceInterface(); + OH_LOG_INFO(LOG_APP, "[INFO] Service UnPublish end!!!"); + case 4: + // 移除sever + RemoveSessionServerInterface(); + OH_LOG_INFO(LOG_APP, "[INFO] SessionServer remove end!!!"); + break; + default: + // 不知执行到哪一步时,全部关闭。 + // closeAllSession(); + FreeNodeInfoInterface(dev); + StopDiscoveryInterface(); + UnPublishServiceInterface(); + RemoveSessionServerInterface(); + } +} + +/** + * 通过分布式软总线发送消息 + * @param sessionId 对端设备的session id + * @param data 发送的数据 + * @param dataLength 发送数据的长度 + * @return 发送是否成功,返回0为成功,否则为不成功 + */ +static int sendData(const char *peerSessionName, const char *data, unsigned int dataLength) { + if (strcmp(peerSessionName, "session_test") != 0 || openedSessionId <= 0 || !data || dataLength <= 0) { + OH_LOG_ERROR(LOG_APP, "[ERROR] peerSessionName: %{public}s or sessionId: %{public}d or data: %{public}s or dataLength: %{public}d is not available", + peerSessionName, openedSessionId, data, dataLength); + return -1; + } + int ret = SendBytesInterface(openedSessionId, data, dataLength); + if (ret) { + OH_LOG_ERROR(LOG_APP, "[ERROR] Failed to send data to sessionId: %{public}d Return value %{public}d ", openedSessionId, ret); + return ret; + } + OH_LOG_INFO(LOG_APP, "[INFO] Successfully send data to the device of : %{public}s", peerSessionName); + return ret; +} + +/** + * @brief 组装需要回传展示的设备信息 + * + * @param deviceDetails 通过GetDeviceDetailInterface接口获取的设备信息 + * @param connectNum 设备数量 + * @return string 组装的设备信息 + */ +static string getConnectedDeviceInfo(DeviceDetail *deviceDetails, int connectNum) { + stringstream fmt; + for (int i = 0; i < connectNum; i++) { + fmt << "deviceName: " << deviceDetails[i].deviceName << "\n" + << "ipAddress: " << deviceDetails[i].ipaddress << "\n" + << "port: " << deviceDetails[i].port << ";\n"; + } + return fmt.str(); +} + +/** + * @brief 接收数据后App的回调函数 + * + * @param receiveData 其他设备传输的数据 + */ +static void receiveCallback(string receiveData) { + OH_LOG_INFO(LOG_APP, "[INFO] Ets callback is call"); + napi_value jsReceiveData, jsCallback = nullptr, jsResult = nullptr; + napi_create_string_utf8(envRef, receiveData.c_str(), receiveData.length(), &jsReceiveData); + + napi_get_reference_value(envRef, callbackRef, &jsCallback); + napi_call_function(envRef, nullptr, jsCallback, 1, &jsReceiveData, &jsResult); + OH_LOG_INFO(LOG_APP, "[INFO] Ets callback end"); +} + +/** + * session服务初始化的napi封装接口 + */ +static napi_value sessionServerInitC(napi_env env, napi_callback_info info) { + envRef = env; + size_t argc = 1; + napi_value args[argc]; + napi_get_cb_info(env, info, &argc, args, nullptr, nullptr); + + napi_valuetype callbackType = napi_undefined; + napi_typeof(env, args[0], &callbackType); + napi_create_reference(env, args[0], 1, &callbackRef); + + napi_value initResult; + string result = sessionServerInit(receiveCallback); + napi_create_string_utf8(env, result.c_str(), NAPI_AUTO_LENGTH, &initResult); + return initResult; +} + +/** + * session连接的napi封装接口 + */ +static napi_value sessionConnectC(napi_env env, napi_callback_info info) { + napi_value connectResult; + string result = sessionConnect(); + napi_create_string_utf8(env, result.c_str(), NAPI_AUTO_LENGTH, &connectResult); + return connectResult; +} + +/** + * 发送数据的napi封装接口 + */ +static napi_value sendDataC(napi_env env, napi_callback_info info) { + size_t bufferSize = 128; + size_t copied; + // 参数数量 + size_t argc = 3; + // 声明参数数组 + napi_value args[3] = {nullptr}; + // 获取传入的参数并依次放入参数数组中 + napi_get_cb_info(env, info, &argc, args, nullptr, nullptr); + // 对第一个js参数类型进行判定 + napi_valuetype valueType0; + napi_typeof(env, args[0], &valueType0); + // 对第二个js参数类型进行判定 + napi_valuetype valueType1; + napi_typeof(env, args[1], &valueType1); + // 对第三个js参数类型进行判定 + napi_valuetype valueType2; + napi_typeof(env, args[2], &valueType2); + // 将第一个传入参数转化为string类型 + char value0Buffer[128]; + napi_get_value_string_utf8(env, args[0], value0Buffer, bufferSize, &copied); + // 将第二个传入参数转化为string类型 + char value1Buffer[128]; + napi_get_value_string_utf8(env, args[1], value1Buffer, bufferSize, &copied); + // 将第三个传入参数转化为int类型 + int value2; + napi_get_value_int32(env, args[2], &value2); + // 调用发送消息的函数 + napi_value sendResult; + int result = sendData(value0Buffer, value1Buffer, value2); + napi_create_int32(env, result, &sendResult); + + return sendResult; +} + +/** + * 关闭连接的napi封装接口 + */ +static napi_value sessionDisconnectC(napi_env env, napi_callback_info info) { + napi_value disconnectResult = nullptr; + sessionDisconnect(0); + return disconnectResult; +} + +// napi函数注册 +EXTERN_C_START +static napi_value Init(napi_env env, napi_value exports) { + napi_property_descriptor desc[] = { + {"sessionServerInit", nullptr, sessionServerInitC, nullptr, nullptr, nullptr, napi_default, nullptr}, + {"sessionConnect", nullptr, sessionConnectC, nullptr, nullptr, nullptr, napi_default, nullptr}, + {"sendData", nullptr, sendDataC, nullptr, nullptr, nullptr, napi_default, nullptr}, + {"sessionDisconnect", nullptr, sessionDisconnectC, nullptr, nullptr, nullptr, napi_default, nullptr}, + }; + napi_define_properties(env, exports, sizeof(desc) / sizeof(desc[0]), desc); + return exports; +} +EXTERN_C_END + +static napi_module demoModule = { + .nm_version = 1, + .nm_flags = 0, + .nm_filename = nullptr, + .nm_register_func = Init, + .nm_modname = "libsoftbus_client_run", + .nm_priv = ((void *)0), + .reserved = {0}, +}; + +extern "C" __attribute__((constructor)) void RegisterModule(void) { + napi_module_register(&demoModule); +} diff --git a/dsoftbus/OhOeCommunication/OpenHarmonyAppSample/entry/src/main/cpp/types/libsoftbus_client_run/index.d.ts b/dsoftbus/OhOeCommunication/OpenHarmonyAppSample/entry/src/main/cpp/types/libsoftbus_client_run/index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..8279d9648ec9307bd02e9b464ee7801729a6b935 --- /dev/null +++ b/dsoftbus/OhOeCommunication/OpenHarmonyAppSample/entry/src/main/cpp/types/libsoftbus_client_run/index.d.ts @@ -0,0 +1,18 @@ +/* + * 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. + */ +export const sessionServerInit: () => string; +export const sessionConnect: () => string; +export const sendData: (a: string, b: string, c: number) => number; +export const sessionDisconnect: () => void; \ No newline at end of file diff --git a/dsoftbus/OhOeCommunication/OpenHarmonyAppSample/entry/src/main/cpp/types/libsoftbus_client_run/package.json b/dsoftbus/OhOeCommunication/OpenHarmonyAppSample/entry/src/main/cpp/types/libsoftbus_client_run/package.json new file mode 100644 index 0000000000000000000000000000000000000000..2cbf19996ddc99cf6fb992fb35c3f171d331d371 --- /dev/null +++ b/dsoftbus/OhOeCommunication/OpenHarmonyAppSample/entry/src/main/cpp/types/libsoftbus_client_run/package.json @@ -0,0 +1,4 @@ +{ + "name": "libsoftbus_client_run.so", + "types": "./index.d.ts" +} \ No newline at end of file