From e1b5a242c77fb66ec73f9dfa91e95c5b5f1e6adb Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=BC=A0=E9=9B=B7?= Date: Mon, 21 Jul 2025 14:48:49 +0800 Subject: [PATCH] service_code_6 MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: 张雷 --- .../device_manager_ipc_interface_code.h | 6 +- .../ipc/model/ipc_notify_service_found_req.h | 35 +++ .../ipc/model/ipc_notify_service_lost_req.h | 34 +++ .../model/ipc_start_discovery_service_req.h | 54 ++++ .../model/ipc_stop_discovery_service_req.h | 43 +++ .../include/deviceprofile_connector.h | 8 + .../src/deviceprofile_connector.cpp | 97 +++++++ .../native_cpp/include/device_manager.h | 4 + .../include/device_manager_callback.h | 7 + .../native_cpp/include/device_manager_impl.h | 4 + .../native_cpp/include/dm_device_info.h | 54 ++++ .../idevice_manager_service_listener.h | 3 + .../include/notify/device_manager_notify.h | 7 + .../native_cpp/src/device_manager_impl.cpp | 57 ++++ .../src/ipc/standard/ipc_cmd_parser.cpp | 87 ++++++ .../src/notify/device_manager_notify.cpp | 57 ++++ services/implementation/BUILD.gn | 2 + .../softbus/service_discovery_callback.h | 30 +++ .../dependency/softbus/softbus_connector.h | 14 + .../include/device_manager_service_impl.h | 7 + .../device_manager_service_impl_lite.h | 4 + .../discovery/dm_service_discovery_manager.h | 51 ++++ .../dependency/softbus/softbus_connector.cpp | 90 +++++++ .../src/device_manager_service_impl.cpp | 25 ++ .../src/device_manager_service_impl_lite.cpp | 12 + .../dm_service_discovery_manager.cpp | 160 +++++++++++ .../service/include/device_manager_service.h | 7 + .../include/device_manager_service_listener.h | 2 + .../include/idevice_manager_service_impl.h | 3 + .../service/src/device_manager_service.cpp | 79 ++++++ .../src/device_manager_service_listener.cpp | 20 ++ .../src/ipc/standard/ipc_cmd_parser.cpp | 63 +++++ .../UTTest_softbus_connector.cpp | 98 +++++++ test/unittest/BUILD.gn | 32 +++ ...Test_device_manager_service_impl_first.cpp | 18 ++ ...UTTest_device_manager_service_listener.cpp | 32 +++ .../UTTest_device_manager_service_listener.h | 3 + .../UTTest_device_manager_service_three.cpp | 136 ++++++++++ .../UTTest_device_manager_service_three.h | 3 + .../UTTest_dm_service_discovery_manager.cpp | 248 ++++++++++++++++++ .../UTTest_dm_service_discovery_manager.h | 47 ++++ .../mock/device_manager_service_impl_mock.cpp | 10 + .../mock/device_manager_service_impl_mock.h | 4 + .../dm_service_discovery_manager_mock.cpp | 33 +++ .../mock/dm_service_discovery_manager_mock.h | 43 +++ test/unittest/mock/softbus_connector_mock.cpp | 21 ++ test/unittest/mock/softbus_connector_mock.h | 11 +- 47 files changed, 1863 insertions(+), 2 deletions(-) create mode 100644 common/include/ipc/model/ipc_notify_service_found_req.h create mode 100644 common/include/ipc/model/ipc_notify_service_lost_req.h create mode 100644 common/include/ipc/model/ipc_start_discovery_service_req.h create mode 100644 common/include/ipc/model/ipc_stop_discovery_service_req.h create mode 100644 services/implementation/include/dependency/softbus/service_discovery_callback.h create mode 100644 services/implementation/include/discovery/dm_service_discovery_manager.h create mode 100644 services/implementation/src/discovery/dm_service_discovery_manager.cpp create mode 100644 test/unittest/UTTest_dm_service_discovery_manager.cpp create mode 100644 test/unittest/UTTest_dm_service_discovery_manager.h create mode 100644 test/unittest/mock/dm_service_discovery_manager_mock.cpp create mode 100644 test/unittest/mock/dm_service_discovery_manager_mock.h diff --git a/common/include/device_manager_ipc_interface_code.h b/common/include/device_manager_ipc_interface_code.h index 418684851..912bea029 100644 --- a/common/include/device_manager_ipc_interface_code.h +++ b/common/include/device_manager_ipc_interface_code.h @@ -123,7 +123,11 @@ enum DMIpcCmdInterfaceCode { CHECK_SRC_SAME_ACCOUNT, CHECK_SINK_SAME_ACCOUNT, // Add ipc msg here - IPC_MSG_BUTT + IPC_MSG_BUTT, + START_SERVICE_DISCOVERING, + STOP_SERVICE_DISCOVERING, + NOTIFY_SERVICE_FOUND, + NOTIFY_SERVICE_LOST }; } // namespace DistributedHardware } // namespace OHOS diff --git a/common/include/ipc/model/ipc_notify_service_found_req.h b/common/include/ipc/model/ipc_notify_service_found_req.h new file mode 100644 index 000000000..fbf7ee2c3 --- /dev/null +++ b/common/include/ipc/model/ipc_notify_service_found_req.h @@ -0,0 +1,35 @@ +#ifndef OHOS_DM_IPC_NOTIFY_SERVICE_FOUND_REQ_H +#define OHOS_DM_IPC_NOTIFY_SERVICE_FOUND_REQ_H + +#include "dm_device_info.h" + +namespace OHOS { +namespace DistributedHardware { +class IpcNotifyServiceFoundReq : public IpcReq { + DECLARE_IPC_MODEL(IpcNotifyServiceFoundReq); + +public: + int64_t GetLocalServiceId() + { + return localServiceId_; + } + void SetLocalServiceId(const int64_t& serviceId) + { + localServiceId_ = serviceId; + } + ServiceInfo GetServiceInfo() + { + return serviceInfo_; + } + void SetServiceInfo(const ServiceInfo& serviceInfo) + { + serviceInfo_ = serviceInfo; + } + +private: + int64_t localServiceId_; + ServiceInfo serviceInfo_; +}; +} // namespace DistributedHardware +} // namespace OHOS +#endif // OHOS_DM_IPC_NOTIFY_SERVICE_FOUND_REQ_H \ No newline at end of file diff --git a/common/include/ipc/model/ipc_notify_service_lost_req.h b/common/include/ipc/model/ipc_notify_service_lost_req.h new file mode 100644 index 000000000..40df760e6 --- /dev/null +++ b/common/include/ipc/model/ipc_notify_service_lost_req.h @@ -0,0 +1,34 @@ +#ifndef OHOS_OM_IPC_NOTIFY_SERVICE_LOST_REQ_H +#define OHOS_OM_IPC_NOTIFY_SERVICE_LOST_REQ_H +#include "dm_device_info.h" +#include "ipc_req.h" +namespace OHOS { +namespace DistributedHardware { +class IpcNotifyServiceLostReq : public IpcReq { + DECLARE_IPC_MODEL(IpcNotifyServiceLostReq); + +public: + int64_t GetLocalServiceId() + { + return localServiceId_; + } + void SetLocalServiceId(const int64_t& serviceId) + { + localServiceId_ = serviceId; + } + int64_t GetServiceId() + { + return serviceId_; + } + void SetServiceId(const int64_t& serviceId) + { + serviceId_ = serviceId; + } + +private: + int64_t localServiceId_; + int64_t serviceId_; +}; +} // namespace DistributedHardware +} // namespace OHOS +#endif // OHOS_OM_IPC_NOTIFY_SERVICE_LOST_REQ_H \ No newline at end of file diff --git a/common/include/ipc/model/ipc_start_discovery_service_req.h b/common/include/ipc/model/ipc_start_discovery_service_req.h new file mode 100644 index 000000000..f5f99a6db --- /dev/null +++ b/common/include/ipc/model/ipc_start_discovery_service_req.h @@ -0,0 +1,54 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef OHOS_DM_IPC_START_DISCOVERY_SERVICE_REQ_H +#define OHOS_DM_IPC_START_DISCOVERY_SERVICE_REQ_H + +#include "dm_subscribe_info.h" +#include "ipc_req.h" + +namespace OHOS { +namespace DistributedHardware { +class IpcStartServiceDiscoveryReq : public IpcReq { + DECLARE_IPC_MODEL(IpcStartServiceDiscoveryReq); + +public: + std::string GetDiscParam() const + { + return discParam_; + } + + void SetDiscParam(const std::string& discParam) + { + discParam_ = discParam; + } + + int64_t GetServiceId() const + { + return serviceId_; + } + + void SetServiceId(int64_t serviceId) + { + serviceId_ = serviceId; + } + +private: + std::string discParam_; + int64_t serviceId_; +}; +} // namespace DistributedHardware +} // namespace OHOS +#endif // OHOS_DM_IPC_START_DISCOVERY_SERVICE_REQ_H \ No newline at end of file diff --git a/common/include/ipc/model/ipc_stop_discovery_service_req.h b/common/include/ipc/model/ipc_stop_discovery_service_req.h new file mode 100644 index 000000000..d6aba6239 --- /dev/null +++ b/common/include/ipc/model/ipc_stop_discovery_service_req.h @@ -0,0 +1,43 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef OHOS_DM_IPC_STOP_DISCOVERY_SERVICE_REQ_H +#define OHOS_DM_IPC_STOP_DISCOVERY_SERVICE_REQ_H + +#include "dm_subscribe_info.h" +#include "ipc_req.h" + +namespace OHOS { +namespace DistributedHardware { +class IpcStopServiceDiscoveryReq : public IpcReq { + DECLARE_IPC_MODEL(IpcStopServiceDiscoveryReq); + +public: + int64_t GetServiceId() const + { + return serviceId_; + } + + void SetServiceId(int64_t serviceId) + { + serviceId_ = serviceId; + } + +private: + int64_t serviceId_; +}; +} // namespace DistributedHardware +} // namespace OHOS +#endif // OHOS_DM_IPC_STOP_DISCOVERY_SERVICE_REQ_H \ No newline at end of file diff --git a/commondependency/include/deviceprofile_connector.h b/commondependency/include/deviceprofile_connector.h index b6e6df3ec..2b4f2b089 100644 --- a/commondependency/include/deviceprofile_connector.h +++ b/commondependency/include/deviceprofile_connector.h @@ -328,6 +328,14 @@ public: const DmAccessCallee &callee, const std::string &sinkUdid); DM_EXPORT void DeleteHoDevice(const std::string &peerUdid, const std::vector &foreGroundUserIds, const std::vector &backGroundUserIds); + + DM_EXPORT int32_t GetServiceInfoByServiceId(ServiceInfoUniqueKey key, ServiceInfoProfile& serviceInfoProfile); + DM_EXPORT int32_t PutServiceInfoProfile(const ServiceInfoProfile& serviceInfoProfile); + DM_EXPORT int32_t UpdateServiceInfoProfile(const ServiceInfoProfile& serviceInfoProfile); + DM_EXPORT int32_t DeleteServiceInfoProfile(const ServiceInfoUniqueKey& key); + DM_EXPORT int32_t GetServiceInfoProfileByUniqueKey( + const ServiceInfoUniqueKey& key, ServiceInfoProfile& serviceInfoProfile); + private: int32_t HandleDmAuthForm(DistributedDeviceProfile::AccessControlProfile profiles, DmDiscoveryInfo discoveryInfo); void GetParamBindTypeVec(DistributedDeviceProfile::AccessControlProfile profiles, std::string requestDeviceId, diff --git a/commondependency/src/deviceprofile_connector.cpp b/commondependency/src/deviceprofile_connector.cpp index 132a0a795..16ab20b0c 100644 --- a/commondependency/src/deviceprofile_connector.cpp +++ b/commondependency/src/deviceprofile_connector.cpp @@ -3489,6 +3489,103 @@ bool DeviceProfileConnector::CheckExtWhiteList(const std::string &pkgName) return false; } +int32_t DeviceProfileConnector::GetServiceInfoByServiceId( + ServiceInfoUniqueKey key, ServiceInfoProfile& serviceInfoProfile) +{ + // DistributedDeviceProfile::ServiceInfoProfile info; + // DistributedDeviceProfile::ServiceInfoUniqueKey keyIndex(key.deviceId, key.userId, key.tokenId, key.serviceId); + // auto ret - DistributedDeviceProfileClient::GetInstance().GetServiceInfoProfileByUniquekey(keyIndex, info); + // if (ret != 0) { + // return ret; + // } + // ServiceInfo& serviceInfo = serviceInfoProfile.serviceRegInfo.serviceInfo; + // serviceInfoProfile.deviceId = info.GetDeviceId(); + // serviceInfoProfile.userId = info.GetUserId(); + // serviceInfoProfile.networkId = info.GetNetworkId(); + // serviceInfoProfile.tokenId = info.GetTokenId(); + + // serviceInfo.serviceId = info.GetServiceId(); + // serviceInfo.serviceType = info.GetServiceType(); + // serviceInfo.serviceName = info.GetServiceName(); + // serviceInfo.serviceDisplayName = info.GetServiceDisplayName(); + // serviceInfo.customData = info.GetCustomData(); + // serviceInfo.dataLen = info.GetCustomDataLen(); + // serviceInfo.bundleName = info.GetBundleName(); + // serviceInfo.moduleName = info.GetModuleName(); + // serviceInfo.abilityName = info.GetAbilityName(); + // serviceInfo.authBoxType = info.GetAuthBoxType(); + // serviceInfo.authType = info.GetAuthType(); + // serviceInfo.pinExchangeType = info.GetPinExchangeType(); + // serviceInfo.pinCode = info.GetPinCode(); + // serviceInfo.description = info.GetDescription(); + // serviceInfo.serviceDicoveryScope = info.GetServiceDicoveryScope(); + // serviceInfoProfile.extraInfo = info.GetExtraInfo(); + return DM_OK; +} + +int32_t DeviceProfileConnector::PutServiceInfoProfile(const ServiceInfoProfile& serviceInfoProfile) +{ + // DistributedDeviceProfile::ServiceInfoProfile dpserviceInfoprofile; + // TransferDmToDpServiceInfoProfile(serviceInfoProfile, dpServiceInfoProfile); + // int32_t ret = DistributedDeviceProfileClient::GetInstance().PutServiceInfoProfile(dpServi ceInfoProfile); + // LOGI("SQW put dp ret=%{public}d, service name=%{puublic}s,service id=%{public}ld, deviceid=%{public}s, " + // "tokenid=%{public}s, userid=%(public)d", + // reet, dpServiceInfoProfile.GetServiceName().c_str(), + // dpsServiceInfoProfile.GetServiceId() dpserviceInfoProfile.GetDeviceId().c_str(), + // dpServiceInfoProfile.GetTokenId().c_str() dpServiceInfoProfile.GetUserId()); + // if (ret != DM_OK) { + // LOGE("failed: %(public}d", ret); + // return ret; + // } + return DM_OK; +} + +int32_t DeviceProfileConnector::UpdateServiceInfoProfile(const ServiceInfoProfile& serviceInfoProfile) +{ + // DistributedDeviceProfile::ServiceInfoProfile dpserviceinfoprofile; + // TransferDmToDpServiceInfoProfile(dmServiceInfoProtfile, dpServiceInfoProfile); + // int32_t ret = DistributedDeviceProfileClient::GetInstance().UpdateServiceInfoProfile(dpse rviceInfoProfile); + // if (ret != DM_OK) { + // LOGE("failed: %(public}d", ret); + // return ret; + // } + return DM_OK; +} + +int32_t DeviceProfileConnector::DeleteServiceInfoProfile(const ServiceInfoUniqueKey& key) +{ + // DistributedDeviceProfile::ServiceInfoUniquekey dpKey; + // dpKey.SetDeviceId(key.deviceId); + // dpKey.SetServiceId(key.serviceId); + // dpKey.SetTokenid(key.tokenid); + // dpkey.SetUserid(key.userId); + // int32_t ret = DistributedDeviceProfileClient::GetInstance().DeleteServiceInfoProfile(dpke y); + // if (ret != DM_OK) { + // LOGE("failed: %{public}d", ret); + // return ret; + // } + return DM_OK; +} + +int32_t DeviceProfileConnector::GetServiceInfoProfileByUniqueKey( + const ServiceInfoUniqueKey& key, ServiceInfoProfile& serviceInfoProfile) +{ + // DistributedDeviceProfile::ServiceInfoUniqueKey dpKeey; + // dpkey.SetDeviceId(key.deviceId); + // dpKey.SetServiceId(key.serviceId); + // dpKey.SetTokenid(key.tokenid); + // dpkey.SetUserId(key.userId); + // ServiceInfoProfile dpServiceInfoProfile; + // int32_t ret = + // DistributedDeviceProfileClient::GetInstance().GetServiceInfoProfileByUniqueKey(dpkey, dpserviceinfoProfile); + // if (ret != DM_OK) { + // LOGE("failed: %{public}d", ret); + // return ret; + // } + // TransferDpToDmServiceInfoProfile(dpServiceInfoProfile, serviceInfoProfile); + return DM_OK; +} + IDeviceProfileConnector *CreateDpConnectorInstance() { return &DeviceProfileConnector::GetInstance(); diff --git a/interfaces/inner_kits/native_cpp/include/device_manager.h b/interfaces/inner_kits/native_cpp/include/device_manager.h index da0db3936..54f692414 100644 --- a/interfaces/inner_kits/native_cpp/include/device_manager.h +++ b/interfaces/inner_kits/native_cpp/include/device_manager.h @@ -653,6 +653,10 @@ public: virtual bool CheckSinkAccessControl(const DmAccessCaller &caller, const DmAccessCallee &callee) = 0; virtual bool CheckSrcIsSameAccount(const DmAccessCaller &caller, const DmAccessCallee &callee) = 0; virtual bool CheckSinkIsSameAccount(const DmAccessCaller &caller, const DmAccessCallee &callee) = 0; + + virtual int32_t StartServiceDiscovery(const int64_t localServiceId, std::map discParam, + std::shared_ptr callback) = 0; + virtual int32_t StopServiceDiscovery(const ServiceFilter& serviceFilter) = 0; }; } // namespace DistributedHardware } // namespace OHOS diff --git a/interfaces/inner_kits/native_cpp/include/device_manager_callback.h b/interfaces/inner_kits/native_cpp/include/device_manager_callback.h index e40343680..ae776048f 100644 --- a/interfaces/inner_kits/native_cpp/include/device_manager_callback.h +++ b/interfaces/inner_kits/native_cpp/include/device_manager_callback.h @@ -179,6 +179,13 @@ public: } virtual void OnCredentialAuthStatus(const std::string &deviceList, uint16_t deviceTypeId, int32_t errcode) = 0; }; + +class ServiceDiscoveryCallback { +public: + virtual ~ServiceDiscoveryCallback() {} + virtual void OnServiceFound(const ServiceInfo* service) = 0; + virtual void OnServiceLost(const uint16_t serviceId) = 0; +}; } // namespace DistributedHardware } // namespace OHOS #endif // OHOS_DM_CALLBACK_H diff --git a/interfaces/inner_kits/native_cpp/include/device_manager_impl.h b/interfaces/inner_kits/native_cpp/include/device_manager_impl.h index 863626aef..a5201d6af 100644 --- a/interfaces/inner_kits/native_cpp/include/device_manager_impl.h +++ b/interfaces/inner_kits/native_cpp/include/device_manager_impl.h @@ -440,6 +440,10 @@ public: virtual bool CheckSrcIsSameAccount(const DmAccessCaller &caller, const DmAccessCallee &callee) override; virtual bool CheckSinkIsSameAccount(const DmAccessCaller &caller, const DmAccessCallee &callee) override; + virtual int32_t StartServiceDiscovery(const int64_t localServiceId, std::map discParam, + std::shared_ptr callback) override; + virtual int32_t StopServiceDiscovery(const ServiceFilter& serviceFilter) override; + private: DeviceManagerImpl() = default; ~DeviceManagerImpl() = default; diff --git a/interfaces/inner_kits/native_cpp/include/dm_device_info.h b/interfaces/inner_kits/native_cpp/include/dm_device_info.h index 67c3a32ae..d360e0301 100644 --- a/interfaces/inner_kits/native_cpp/include/dm_device_info.h +++ b/interfaces/inner_kits/native_cpp/include/dm_device_info.h @@ -292,6 +292,7 @@ typedef struct PeerTargetId { * wlan ip port. */ uint16_t wifiPort = 0; + int64_t serviceId = 0; bool operator==(const PeerTargetId &other) const { @@ -469,6 +470,59 @@ typedef struct DMAclQuadInfo { std::string peerUdid; int32_t peerUserId; } DMAclQuadInfo; + +typedef struct ServiceInfo { + int64_t serviceId; // Unique service ID (64 bytes) m + std::string serviceType; // 15 字节 + std::string serviceName; // 9字节,应用对该服务起 + std::string serviceDisplayName; // 暂定7~128宁节, + std::string customData; // 0-512字节,业务自定义字 + uint32_t dataLen; // 自定义宁段长度 + std::string bundleName; // 业务包名(FA必填) + std::string moduleName; // 一个包名对应多个module + std::string abilityName; // 一个module对应多个能力(F +} ServiceInfo; + +typedef struct ServiceRegInfo { + ServiceInfo serviceInfo; + std::string authorizationDescription; // authorization服务sink端瑞弹框显示的信息(不能同步) + std::string extraInfo; // 可扩展字段 +} ServiceRegInfo; + +typedef struct ServiceFilter { + int64_t serviceId; + std::string serviceType; + std::string serviceName; + std::string serviceDisplayName; + std::string customData; +} ServiceFilter; + +typedef struct ServiceInfoUniqueKey { + std::string deviceId; + int32_t userId; + std::string tokenId; + int64_t serviceId; +} ServiceInfoUniqueKey; + +typedef struct ServiceInfoProfile { + ServiceRegInfo serviceRegInfo; + std::string deviceId; + int32_t userId; + std::string networkid; + std::string tokenId; + std::string extraInfo; +} ServiceInfoProfile; + +typedef struct ServiceBindlocalInfo { + std::string localUdid; + int32_t userId; + uint32_t tokenId; +} ServiceBindLocalInfo; + +typedef struct DmServiceAddress { + std::string bleMac; + uint32_t actionid; +} DmServiceAddress; } // namespace DistributedHardware } // namespace OHOS #endif // OHOS_DM_DEVICE_INFO_H \ No newline at end of file diff --git a/interfaces/inner_kits/native_cpp/include/idevice_manager_service_listener.h b/interfaces/inner_kits/native_cpp/include/idevice_manager_service_listener.h index 336c5b631..336e10dcf 100644 --- a/interfaces/inner_kits/native_cpp/include/idevice_manager_service_listener.h +++ b/interfaces/inner_kits/native_cpp/include/idevice_manager_service_listener.h @@ -177,6 +177,9 @@ public: virtual std::string GetLocalDisplayDeviceName() = 0; virtual int32_t OpenAuthSessionWithPara(const std::string &deviceId, int32_t actionId, bool isEnable160m) = 0; + + virtual void OnServiceFound(int64_t localServiceId, const ServiceInfo& softbusService) = 0; + virtual void OnServiceLost(int64_t localServiceId, int64_t serviceId) = 0; }; } // namespace DistributedHardware } // namespace OHOS diff --git a/interfaces/inner_kits/native_cpp/include/notify/device_manager_notify.h b/interfaces/inner_kits/native_cpp/include/notify/device_manager_notify.h index 39a229cc8..173a9388e 100644 --- a/interfaces/inner_kits/native_cpp/include/notify/device_manager_notify.h +++ b/interfaces/inner_kits/native_cpp/include/notify/device_manager_notify.h @@ -88,6 +88,9 @@ public: void OnSetRemoteDeviceNameResult(const std::string &pkgName, const std::string &deviceId, int32_t code); void UnRegisterPinHolderCallback(const std::string &pkgName); + void RegisterServiceDiscoveryCallback(int64_t serviceId, std::shared_ptr callback); + void UnRegisterServiceDiscoveryCallback(int64_t serviceId); + public: static void DeviceInfoOnline(const DmDeviceInfo &deviceInfo, std::shared_ptr tempCbk); static void DeviceInfoOffline(const DmDeviceInfo &deviceInfo, std::shared_ptr tempCbk); @@ -103,6 +106,7 @@ public: std::shared_ptr tempCbk); static void DeviceTrustChange(const std::string &udid, const std::string &uuid, DmAuthForm authForm, std::shared_ptr tempCbk); + public: void OnRemoteDied(); void OnDeviceOnline(const std::string &pkgName, const DmDeviceInfo &deviceInfo); @@ -139,6 +143,8 @@ public: std::string content); std::shared_ptr GetDiscoveryCallback(const std::string &pkgName, uint16_t subscribeId); void GetCallBack(std::map> &callbackMap); + void OnServiceFound(int64_t localServiceId, const ServiceInfo& serviceInfo); + void OnServiceLost(int64_t localServiceId, int64_t serviceld); private: #if !defined(__LITEOS_M__) @@ -166,6 +172,7 @@ private: std::map> setLocalDeviceNameCallback_; std::map>> setRemoteDeviceNameCallback_; + std::map> serviceDiscoveryCallbacks_; }; } // namespace DistributedHardware } // namespace OHOS diff --git a/interfaces/inner_kits/native_cpp/src/device_manager_impl.cpp b/interfaces/inner_kits/native_cpp/src/device_manager_impl.cpp index 0b2bfebae..ca65961a6 100644 --- a/interfaces/inner_kits/native_cpp/src/device_manager_impl.cpp +++ b/interfaces/inner_kits/native_cpp/src/device_manager_impl.cpp @@ -15,6 +15,8 @@ #include "device_manager_impl.h" #include + +#include "device_manager_ipc_interface_code.h" #include "device_manager_notify.h" #include "dm_anonymous.h" #include "dm_constants.h" @@ -53,6 +55,7 @@ #include "ipc_get_trustdevice_rsp.h" #include "ipc_import_auth_code_req.h" #include "ipc_notify_event_req.h" +#include "ipc_notify_service_found_req.h" #include "ipc_permission_req.h" #include "ipc_publish_req.h" #include "ipc_put_device_profile_info_list_req.h" @@ -63,6 +66,8 @@ #include "ipc_set_remote_device_name_req.h" #include "ipc_set_useroperation_req.h" #include "ipc_skeleton.h" +#include "ipc_start_discovery_service_req.h" +#include "ipc_stop_discovery_service_req.h" #include "ipc_sync_callback_req.h" #include "ipc_unauthenticate_device_req.h" #include "ipc_unbind_device_req.h" @@ -2994,5 +2999,57 @@ bool DeviceManagerImpl::CheckAclByIpcCode(const DmAccessCaller &caller, const Dm anonyLocalUdid_); return result; } + +int32_t DeviceManagerImpl::StartServiceDiscovery(const int64_t localServiceId, + std::map discParam, std::shared_ptr callback) +{ + LOGI("StartServiceDiscovery Start"); + if (callback == nullptr) { + LOGE("StartServiceDiscovery failed: input callback isnull."); + return ERR_DM_INPUT_PARA_INVALID; + } + DeviceManagerNotify::GetInstance().RegisterServiceDiscoveryCallback(localServiceId, callback); + std::string discParamStr = ConvertMapToJsonString(discParam); + std::shared_ptr req = std::make_shared(); + std::shared_ptr rsp = std::make_shared(); + req->SetServiceId(localServiceId); + req->SetDiscParam(discParamStr); + int32_t ret = ipcClientProxy_->SendRequest(START_SERVICE_DISCOVERING, req, rsp); + if (ret != DM_OK) { + LOGE("StartServiceDiscovery error: Send Request failed ret: %{public}d", ret); + return ERR_DM_IPC_SEND_REQUEST_FAILED; + } + ret = rsp->GetErrCode(); + if (ret != DM_OK) { + LOGE("StartServiceDiscovery error: Failed with ret %{public}d", ret); + return ret; + } + SysEventWrite(std::string(START_DEVICE_DISCOVERY_SUCCESS), DM_HISYEVENT_BEHAVIOR, + std::string(START_DEVICE_DISCOVERY_SUCCESS_MSG)); + LOGI("StartServiceDiscovery Start"); + return DM_OK; +} + +int32_t DeviceManagerImpl::StopServiceDiscovery(const ServiceFilter& serviceFilter) +{ + // TODO:具体逻辑待处理,原内容未实现 + LOGI("StopServiceDiscovery Start"); + std::shared_ptr req = std::make_shared(); + std::shared_ptr rsp = std::make_shared(); + req->SetServiceId(serviceFilter.serviceId); + int32_t ret = ipcClientProxy_->SendRequest(STOP_SERVICE_DISCOVERING, req, rsp); + if (ret != DM_OK) { + LOGE("StopServiceDiscovery error: Send Request faileed ret: %{public}d", ret); + return ERR_DM_IPC_SEND_REQUEST_FAILED; + } + ret = rsp->GetErrCode(); + if (ret != DM_OK) { + LOGE("StopServiceDiscovery error: Failed with ret %{public}d :", ret); + return ret; + } + DeviceManagerNotify::GetInstance().UnRegisterServiceDiscoveryCallback(serviceFilter.serviceId); + LOGI("StopServiceDiscovery Start"); + return DM_OK; +} } // namespace DistributedHardware } // namespace OHOS diff --git a/interfaces/inner_kits/native_cpp/src/ipc/standard/ipc_cmd_parser.cpp b/interfaces/inner_kits/native_cpp/src/ipc/standard/ipc_cmd_parser.cpp index a30e5493b..025dd905f 100644 --- a/interfaces/inner_kits/native_cpp/src/ipc/standard/ipc_cmd_parser.cpp +++ b/interfaces/inner_kits/native_cpp/src/ipc/standard/ipc_cmd_parser.cpp @@ -70,6 +70,7 @@ #include "ipc_unpublish_req.h" #include "ipc_unauthenticate_device_req.h" #include "securec.h" +#include "ipc_start_discovery_service_req.h" namespace OHOS { class IRemoteObject; } namespace OHOS { @@ -2217,5 +2218,91 @@ ON_IPC_READ_RESPONSE(CHECK_SINK_SAME_ACCOUNT, MessageParcel &reply, std::shared_ { return ReadResponse(CHECK_SINK_SAME_ACCOUNT, reply, pBaseRsp); } + +ON_IPC_SET_REQUEST(START_SERVICE_DISCOVERING, std::shared_ptr pBaseReq, MessageParcel& data) +{ + if (pBaseReq == nullptr) { + LOGE("pBaseReq is null"); + return ERR_DM_FAILED; + } + std::shared_ptr pReq = std::static_pointer_cast(pBaseReq); + int64_t serviceId = pReq->GetServiceId(); + if (!data.WriteInt64(serviceId)) { + LOGE("write GetServiceId failed"); + return ERR_DM_IPC_WRITE_FAILED; + } + std::string discParam = pReq->GetDiscParam(); + if (!data.WriteString(discParam)) { + LOGE("writeGetDiscParam failed"); + return ERR_DM_IPC_WRITE_FAILED; + } + return DM_OK; +} + +ON_IPC_READ_RESPONSE(START_SERVICE_DISCOVERING, MessageParcel& reply, std::shared_ptr pBaseRsp) +{ + if (pBaseRsp == nullptr) { + LOGE("pBaseRsp is null"); + return ERR_DM_FAILED; + } + std::shared_ptr pRsp = std::static_pointer_cast(pBaseRsp); + pRsp->SetErrCode(reply.ReadInt32()); + return DM_OK; +} + +ON_IPC_SET_REQUEST(STOP_SERVICE_DISCOVERING, std::shared_ptr pBaseReq, MessageParcel& data) +{ + if (pBaseReq == nullptr) { + LOGE("pBaseReq is null"); + return ERR_DM_FAILED; + } + std::shared_ptr pReq = std::static_pointer_cast(pBaseReq); + int64_t serviceId = pReq->GetServiceId(); + if (!data.WriteInt64(serviceId)) { + LOGE("writeGetServiceIdfailed"); + return ERR_DM_IPC_WRITE_FAILED; + } + std::string discParam = pReq->GetDiscParam(); + if (!data.WriteString(discParam)) { + LOGE("write GetDiscParam failed"); + return ERR_DM_IPC_WRITE_FAILED; + } + return DM_OK; +} + +ON_IPC_READ_RESPONSE(STOP_SERVICE_DISCOVERING, MessageParcel& reply, std::shared_ptr pBaseRsp) +{ + if (pBaseRsp == nullptr) { + LOGE("pBaseRspis null"); + return ERR_DM_FAILED; + } + std::shared_ptr pRsp = std::static_pointer_cast(pBaseRsp); + pRsp->SetErrCode(reply.ReadInt32()); + return DM_OK; +} + +ON_IPC_CMD(NOTIFY_SERVICE_FOUND, MessageParcel& data, MessageParcel& reply) +{ + int64_t localServiceId = data.ReadInt64(); + ServiceInfo serviceInfo = { 0 }; + serviceInfo.serviceId = data.ReadInt64(); + serviceInfo.serviceType = data.ReadString(); + serviceInfo.serviceName = data.ReadString(); + serviceInfo.serviceDisplayName = data.ReadString(); + serviceInfo.customData = data.ReadString(); + serviceInfo.dataLen = data.ReadUint32(); + DeviceManagerNotify::GetInstance().OnServiceFound(localServiceId, serviceInfo); + reply.WriteInt32(DM_OK); + return DM_OK; +} + +ON_IPC_CMD(NOTIFY_SERVICE_LOST, MessageParcel& data, MessageParcel& reply) +{ + int64_t localServiceId = data.ReadInt64(); + int64_t serviceId = data.ReadInt64(); + DeviceManagerNotify::GetInstance().OnServiceLost(localServiceId, serviceId); + reply.WriteInt32(DM_OK); + return DM_OK; +} } // namespace DistributedHardware } // namespace OHOS diff --git a/interfaces/inner_kits/native_cpp/src/notify/device_manager_notify.cpp b/interfaces/inner_kits/native_cpp/src/notify/device_manager_notify.cpp index 278ebade4..e3ffa54f0 100644 --- a/interfaces/inner_kits/native_cpp/src/notify/device_manager_notify.cpp +++ b/interfaces/inner_kits/native_cpp/src/notify/device_manager_notify.cpp @@ -1480,5 +1480,62 @@ void DeviceManagerNotify::UnRegisterPinHolderCallback(const std::string &pkgName std::lock_guard autoLock(lock_); pinHolderCallback_.erase(pkgName); } + +void DeviceManagerNotify::RegisterServiceDiscoveryCallback( + int64_t serviceId, std::shared_ptr callback) +{ + if (callback == nullptr) { + LOGE("Invalid parameter, pkgName is empty."); + return; + } + std::lock_guard autolock(lock_); + serviceDiscoveryCallbacks_[serviceId] = callback; +} +void DeviceManagerNotify::UnRegisterServiceDiscoveryCallback(int64_t serviceId) +{ + std::lock_guard autolock(lock_); + if (serviceDiscoveryCallbacks_.count(serviceId) == 0) { + LOGE("error,Service Discovery not register."); + return; + } + serviceDiscoveryCallbacks_.erase(serviceId); +} + +void DeviceManagerNotify::OnServiceFound(int64_t localServiceId, const ServiceInfo& serviceInfo) +{ + std::shared_ptr tempCbk; + std::lock_guard autolock(lock_); + auto iter = serviceDiscoveryCallbacks_.find(localServiceId); + if (iter == serviceDiscoveryCallbacks_.end()) { + LOGE("error, callback not register for localserviceId %{public}lld", localServiceId); + return; + } + tempCbk = iter->second; + if (tempCbk == nullptr) { + LOGE("OnDeviceFound error, registered service discoverry callback is nullptr."); + return; + } + LOGD("Complete with serviceInfo"); + tempCbk->OnServiceFound(&serviceInfo); +} + +void DeviceManagerNotify::OnServiceLost(int64_t localServiceId, int64_t serviceId) +{ + std::shared_ptr tempCbk; + std::lock_guard autolock(lock_); + auto iter = serviceDiscoveryCallbacks_.find(localServiceId); + if (iter == serviceDiscoveryCallbacks_.end()) { + LOGE("error, callback not register for localServiceId %{public}lld", localServiceId); + return; + } + tempCbk = iter->second; + if (tempCbk == nullptr) { + LOGE("OnDeviceFound error, registered service discoovery callback is nullptr."); + return; + } + LOGD("Complete with serviceId"); + tempCbk->OnServiceLost(serviceId); +} + } // namespace DistributedHardware } // namespace OHOS diff --git a/services/implementation/BUILD.gn b/services/implementation/BUILD.gn index d8c4ef707..6fb64472a 100644 --- a/services/implementation/BUILD.gn +++ b/services/implementation/BUILD.gn @@ -121,6 +121,7 @@ if (defined(ohos_lite)) { "include/credential", "include/cryptomgr", "include/devicestate", + "include/discovery", "include/dependency/commonevent", "include/dependency/deviceprofile", "include/dependency/multipleuser", @@ -211,6 +212,7 @@ if (defined(ohos_lite)) { "src/device_manager_service_impl.cpp", "src/devicestate/dm_device_state_manager.cpp", "src/i18n/dm_language_manager.cpp", + "src/discovery/dm_service_discovery_manager.cpp", ] public_configs = [ ":devicemanagerserviceimpl_config" ] diff --git a/services/implementation/include/dependency/softbus/service_discovery_callback.h b/services/implementation/include/dependency/softbus/service_discovery_callback.h new file mode 100644 index 000000000..f503d69d1 --- /dev/null +++ b/services/implementation/include/dependency/softbus/service_discovery_callback.h @@ -0,0 +1,30 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef OHOS_DM_SERVICE_DISCOVERY_CALLBACK_H +#define OHOS_DM_SERVICE_DISCOVERY_CALLBACK_H +#include "dm_device_info.h" + +namespace OHOS { +namespace DistributedHardware { +class IServiceDiscoveryCallback { +public: + virtual void OnServiceFound(int64_t localServiceId, const ServiceInfo& softbusService) = 0; + virtual void OnServiceLost(int64_t localServiceId, int64_t serviceId) = 0; +}; +} // namespace DistributedHardware +} // namespace OHOS + +#endif // OHOS_DM_SERVICE_DISCOVERY_CALLBACK_H \ No newline at end of file diff --git a/services/implementation/include/dependency/softbus/softbus_connector.h b/services/implementation/include/dependency/softbus/softbus_connector.h index be6e0468b..b2945e533 100644 --- a/services/implementation/include/dependency/softbus/softbus_connector.h +++ b/services/implementation/include/dependency/softbus/softbus_connector.h @@ -31,6 +31,7 @@ #include "deviceprofile_connector.h" #include "softbus_session.h" #endif +#include "service_discovery_callback.h" #include "softbus_connector_callback.h" #include "softbus_state_callback.h" #include "hichain_auth_connector.h" @@ -107,6 +108,9 @@ public: */ int32_t UnRegisterConnectorCallback(); + static void OnSoftbusOnServiceFound(const ServiceInfo* service); + static void OnSoftbusOnServiceLost(const char* serviceIdStr); + public: SoftbusConnector(); ~SoftbusConnector(); @@ -146,6 +150,12 @@ public: int32_t GetAclListHash(const DevUserInfo &localDevUserInfo, const DevUserInfo &remoteDevUserInfo, std::string &aclList); + int32_t StartServiceDiscovery(const ServiceInfoProfile& serviceInfoProfile); + int32_t StopServiceDiscovery(const ServiceInfoProfile& serviceInfoProfile); + int32_t RegisterServiceDiscoveryCallback( + int64_t serviceId, const std::shared_ptr callback); + int32_t UnRegisterServiceDiscoveryCallback(int64_t serviceId); + private: static std::shared_ptr SetAddrAndJson(const ConnectionAddr *addr, JsonObject &jsonPara, std::string &connectAddr); @@ -177,6 +187,10 @@ private: static std::mutex processInfoVecMutex_; static std::mutex processChangeInfoVecMutex_; static std::shared_ptr connectorCallback_; + + static std::map> serviceDiscoveryCallbackMap_; + static std::mutex serviceDiscoveryCallbackMutex_; + // static IServiceDiscoveryCb serviceDiscoveryCallback_; }; } // namespace DistributedHardware } // namespace OHOS diff --git a/services/implementation/include/device_manager_service_impl.h b/services/implementation/include/device_manager_service_impl.h index 9efda6ff9..49185431b 100644 --- a/services/implementation/include/device_manager_service_impl.h +++ b/services/implementation/include/device_manager_service_impl.h @@ -32,6 +32,7 @@ #include "dm_credential_manager.h" #include "dm_device_info.h" #include "dm_device_state_manager.h" +#include "dm_service_discovery_manager.h" #include "dm_single_instance.h" #include "dp_inited_callback.h" #include "idevice_manager_service_impl.h" @@ -205,6 +206,10 @@ public: const DmAccessCallee &callee, const std::string &sinkUdid); void DeleteHoDevice(const std::string &peerUdid, const std::vector &foreGroundUserIds, const std::vector &backGroundUserIds); + + int32_t StartServiceDiscovery(const ServiceInfoProfile& serviceinfoProfile); + int32_t StopServiceDiscovery(const ServiceInfoProfile& serviceinfoProfile); + private: int32_t PraseNotifyEventJson(const std::string &event, JsonObject &jsonObject); std::string GetUdidHashByNetworkId(const std::string &networkId); @@ -332,6 +337,8 @@ private: std::map> configsMap_; // Import when authMgr is not initialized std::mutex authMgrMapMtx_; std::map> authMgrMap_; // New protocol sharing + + std::shared_ptr serviceDiscoveryMgr_; }; using CreateDMServiceFuncPtr = IDeviceManagerServiceImpl *(*)(void); diff --git a/services/implementation/include/device_manager_service_impl_lite.h b/services/implementation/include/device_manager_service_impl_lite.h index 8ec4d49a2..7c6afa7fb 100644 --- a/services/implementation/include/device_manager_service_impl_lite.h +++ b/services/implementation/include/device_manager_service_impl_lite.h @@ -182,6 +182,10 @@ public: const DmAccessCallee &callee, const std::string &sinkUdid); void DeleteHoDevice(const std::string &peerUdid, const std::vector &foreGroundUserIds, const std::vector &backGroundUserIds); + + virtual int32_t StartServiceDiscovery(ServiceInfoProfile& serviceInfoProfile) override; + virtual int32_t StopServiceDiscovery(ServiceInfoProfile& serviceInfoProfile) override; + private: std::string GetUdidHashByNetworkId(const std::string &networkId); diff --git a/services/implementation/include/discovery/dm_service_discovery_manager.h b/services/implementation/include/discovery/dm_service_discovery_manager.h new file mode 100644 index 000000000..b6132775b --- /dev/null +++ b/services/implementation/include/discovery/dm_service_discovery_manager.h @@ -0,0 +1,51 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef OHOS_DM_SERVICE_DISCOVERY_MANAGER_H +#define OHOS_DM_SERVICE_DISCOVERY_MANAGER_H + +#include "dm_timer.h" +#include "idevice_manager_service_listener.h" +#include "service_discovery_callback.h" +#include "softbus_connector.h" + +namespace OHOS { +namespace DistributedHardware { +class DmServiceDiscoveryManager final : public IServiceDiscoveryCallback, + public std::enable_shared_from_this { +public: + DmServiceDiscoveryManager( + std::shared_ptr softbusConnector, std::shared_ptr listener); + ~DmServiceDiscoveryManager(); + int32_t StartServiceDiscovery(const ServiceInfoProfile& serviceInfoProfile); + int32_t StopServiceDiscovery(const ServiceInfoProfile& seerviceInfoProfile); + void OnServiceFound(int64_t localServiceId, const ServiceInfo& softbusService); + void OnServiceLost(int64_t localServiceId, int64_t serviceId); + void HandleDiscoveryTimeout(std::string& name); + int32_t CheckDiscoveryMap(const ServiceInfoProfile& serviceInfoProfile); + +private: + void ServiceDiscoveryTimer(const int64_t& serviceId); + +private: + std::shared_ptr softbusConnector_; + std::shared_ptr listener_; + std::map discoveryMap_; + std::shared_ptr timer_; + std::mutex locks_; +}; +} // namespace DistributedHardware +} // namespace OHOS +#endif // OHOS_DM_SERVICE_DISCOVERY_MANAGER_H \ No newline at end of file diff --git a/services/implementation/src/dependency/softbus/softbus_connector.cpp b/services/implementation/src/dependency/softbus/softbus_connector.cpp index db5974f1b..e652ec005 100644 --- a/services/implementation/src/dependency/softbus/softbus_connector.cpp +++ b/services/implementation/src/dependency/softbus/softbus_connector.cpp @@ -61,6 +61,14 @@ std::mutex SoftbusConnector::processInfoVecMutex_; std::mutex SoftbusConnector::processChangeInfoVecMutex_; std::shared_ptr SoftbusConnector::connectorCallback_ = nullptr; +std::map> SoftbusConnector::serviceDiscoveryCallbackMap_ = {}; +std::mutex SoftbusConnector::serviceDiscoveryCallbackMutex_; + +// IServiceDiscoveryCb SoftbusConnector::serviceDiscoveryCallback_ = { +// .OnServiceFound = SoftbusConnector::OnSoftbusOnServiceFound, +// .OnServiceLost = SoftbusConnector::OnSoftbusOnServiceLost, +// }; // namespace DistributedHardware + SoftbusConnector::SoftbusConnector() { #if !(defined(__LITEOS_M__) || defined(LITE_DEVICE)) @@ -896,5 +904,87 @@ void SoftbusConnector::ConvertNodeBasicInfoToDmDevice(const NodeBasicInfo &nodeB dmDeviceInfo.extraData = ToString(extraJson); } } + +int32_t SoftbusConnector::StartServiceDiscovery(const ServiceInfoProfile& serviceInfoProfile) +{ + const ServiceInfo& serviceInfo = serviceInfoProfile.serviceRegInfo.serviceInfo; + std::string serviceIdStr = std::to_string(serviceInfo.serviceId); + // DiscoveryInfo discoveryInfo = { 0 }; + // discoveryInfo.localServiceId = serviceIdStr.c_str(); + // discoveryInfo.serviceType = serviceInfo.serviceType.c_str(); + // discoveryInfo.customData = (unsigned char*)serviceInfo.customData.c_str(); + // discoveryInfo.dataLen = serviceInfo.dataLen; + // ServiceDiscoveryParam discoveryParam; + // discoveryParam.media = SERVICE_MEDIUM_TYPE_AUTO; + // discoveryParam.mode = SERVICE_DISCOVER_NODE_ACTIVE; + // discoveryParam.freq - FREQ_EXTREMELY_HIGH; + // int32_t ret = ::StartServiceDiscovery(&discoveryinfo, &disceoveryParaM, &serviceDiscoveryCallback_); + // if (ret != DM_OK) { + // LOGE("[SOFTBUS]RefreshLNN failed, ret: %(public)d.", ret); + // return ret; + // } + return DM_OK; +} + +int32_t SoftbusConnector::StopServiceDiscovery(const ServiceInfoProfile& serviceInfoProfile) +{ + const ServiceInfo& serviceInfo = serviceInfoProfile.serviceRegInfo.serviceInfo; + std::string serviceIdStr = std::to_string(serviceInfo.serviceId); + // int32_t ret = ::StopServiceDiscovery(serviceIdStr.c_str(), serviceInfo.serviceType.c_str()); + // if (ret != DM_OK) { + // LOGE("[SOFTBUS]RefreshLNN failed, ret: %(public)d.", ret); + // return ret; + // } + return DM_OK; +} + +int32_t SoftbusConnector::RegisterServiceDiscoveryCallback( + int64_t serviceId, const std::shared_ptr callback) +{ + std::lock_guard lock(serviceDiscoveryCallbackMutex_); + serviceDiscoveryCallbackMap_.emplace(serviceId, callback); + return DM_OK; +} + +int32_t SoftbusConnector::UnRegisterServiceDiscoveryCallback(int64_t serviceId) +{ + std::lock_guard lock(serviceDiscoveryCallbackMutex_); + serviceDiscoveryCallbackMap_.erase(serviceId); + return DM_OK; +} + +void SoftbusConnector::OnSoftbusOnServiceFound(const ServiceInfo* service) +{ + if (service == nullptr) { + LOGE("[SOFTBUS]service is null."); + return; + } + ServiceInfo serviceInfo = { 0 }; + serviceInfo.serviceId = service->serviceId; + serviceInfo.serviceType = service->serviceType; + serviceInfo.serviceName = service->serviceName; + serviceInfo.serviceDisplayName = service->serviceDisplayName; + serviceInfo.customData = service->customData; + serviceInfo.dataLen = service->dataLen; + std::lock_guard lock(serviceDiscoveryCallbackMutex_); + for (auto& iter : serviceDiscoveryCallbackMap_) { + iter.second->OnServiceFound(iter.first, serviceInfo); + } +} + +void SoftbusConnector::OnSoftbusOnServiceLost(const char* serviceIdStr) +{ + if (serviceIdStr == nullptr) { + LOGE("[SOFTBUS]serviceid is null."); + return; + } + int64_t serviceId; + sscanf(serviceIdStr, "%llx", &serviceId); + std::lock_guard lock(serviceDiscoveryCallbackMutex_); + for (auto& iter : serviceDiscoveryCallbackMap_) { + iter.second->OnServiceLost(iter.first, serviceId); + } +} + } // namespace DistributedHardware } // namespace OHOS diff --git a/services/implementation/src/device_manager_service_impl.cpp b/services/implementation/src/device_manager_service_impl.cpp index 3b29c520a..60259f46f 100644 --- a/services/implementation/src/device_manager_service_impl.cpp +++ b/services/implementation/src/device_manager_service_impl.cpp @@ -486,6 +486,10 @@ int32_t DeviceManagerServiceImpl::Initialize(const std::shared_ptr(new DpInitedCallback()); DeviceProfileConnector::GetInstance().SubscribeDeviceProfileInited(dpInitedCallback_); } + if (serviceDiscoveryMgr_ == nullptr) { + serviceDiscoveryMgr_ = std::make_shared(softbusConnector_, listener); + } + listener_ = listener; CreateGlobalClassicalAuthMgr(); if (authMgr_ != nullptr) { @@ -3080,6 +3084,27 @@ void DeviceManagerServiceImpl::DeleteSessionKey(int32_t userId, DeviceProfileConnector::GetInstance().DeleteSessionKey(userId, skId); } +int32_t DeviceManagerServiceImpl::StartServiceDiscovery(const ServiceInfoProfile& serviceInfoProfile) +{ + if (softbusConnector_ == nullptr || serviceDiscoveryMgr_ == nullptr) { + LOGE("softbusConnector_ is nullpter!"); + return ERR_DM_PUBLISH_FAILED; + } + + // 用发现管理开始发现服务 + return serviceDiscoveryMgr_->StartServiceDiscovery(serviceInfoProfile); +} + +int32_t DeviceManagerServiceImpl::StopServiceDiscovery(const ServiceInfoProfile& serviceInfoProfile) +{ + if (softbusConnector_ == nullptr || serviceDiscoveryMgr_ == nullptr) { + LOGE("softbusConnector_ is nullpter!"); + return ERR_DM_PUBLISH_FAILED; + } + // 调用发现管理停止发现服务 + return serviceDiscoveryMgr_->StopServiceDiscovery(serviceInfoProfile); +} + extern "C" IDeviceManagerServiceImpl *CreateDMServiceObject(void) { return new DeviceManagerServiceImpl; diff --git a/services/implementation/src/device_manager_service_impl_lite.cpp b/services/implementation/src/device_manager_service_impl_lite.cpp index 445f2b070..5a5509f38 100644 --- a/services/implementation/src/device_manager_service_impl_lite.cpp +++ b/services/implementation/src/device_manager_service_impl_lite.cpp @@ -741,6 +741,18 @@ void DeviceManagerServiceImpl::DeleteHoDevice(const std::string &peerUdid, return; } +int32_t DeviceManagerServiceImpl::StartServiceDiscovery(ServiceInfoProfile& serviceInfoProfile) +{ + (void)serviceInfoProfile; + return DM_OK; +} + +int32_t DeviceManagerServiceImpl::StopServiceDiscovery(ServiceInfoProfile& serviceInfoProfile) +{ + (void)serviceInfoProfile; + return DM_OK; +} + extern "C" IDeviceManagerServiceImpl *CreateDMServiceObject(void) { return new DeviceManagerServiceImpl; diff --git a/services/implementation/src/discovery/dm_service_discovery_manager.cpp b/services/implementation/src/discovery/dm_service_discovery_manager.cpp new file mode 100644 index 000000000..8143508c8 --- /dev/null +++ b/services/implementation/src/discovery/dm_service_discovery_manager.cpp @@ -0,0 +1,160 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "dm_service_discovery_manager.h" + +#include "dm_anonymous.h" +#include "dm_constants.h" +#include "dm_log.h" +namespace OHOS { +namespace DistributedHardware { +constexpr const char* DISCOVERY_SERVICE_TIMEOUT_TASK = "deviceManagerTiner:discoveryservice"; + +const int32_t DISCOVERY_SERVICE_TIMEOUT = 120; + +DmServiceDiscoveryManager::DmServiceDiscoveryManager( + std::shared_ptr softbusConnector, std::shared_ptr listener) + : softbusConnector_(softbusConnector), listener_(listener) +{ + LOGI("DmserviceDiscoveryManager constructor"); +} + +DmServiceDiscoveryManager::~DmServiceDiscoveryManager() {} + +void DmServiceDiscoveryManager::ServiceDiscoveryTimer(const int64_t& serviceId) +{ + if (timer_ == nullptr) { + timer_ = std::make_shared(); + } + timer_->StartTimer(std::string(DISCOVERY_SERVICE_TIMEOUT_TASK) + std::to_string(serviceId), + DISCOVERY_SERVICE_TIMEOUT, [this](std::string name) { HandleDiscoveryTimeout(name); }); +} + +int32_t DmServiceDiscoveryManager::CheckDiscoveryMap(const ServiceInfoProfile& serviceInfoProfile) +{ + if (discoveryMap_.empty()) { + return DM_OK; + } + const ServiceInfo& serviceInfo = serviceInfoProfile.serviceRegInfo.serviceInfo; + auto item = discoveryMap_.find(serviceInfo.serviceId); + if (item == discoveryMap_.end()) { + LOGE("serviceId:%{public}lld Publishservice repeated", serviceInfo.serviceId); + return ERR_DM_DISCOVERY_REPEATED; + } + std::size_t DM_MAX_SERVICE_ID_NUM = 900000; + if (discoveryMap_.size() < DM_MAX_SERVICE_ID_NUM) { + return DM_OK; + } + std::map::iterator it; + ServiceInfoProfile historyServiceInfo; + std::size_t reportNum = 0; + for (it = discoveryMap_.begin(); it != discoveryMap_.end(); it++) { + historyServiceInfo = it->second; + if (historyServiceInfo.tokenId == serviceInfoProfile.tokenId) { + reportNum++; + } + } + if (reportNum >= DM_MAX_SERVICE_ID_NUM) { + LOGE("tokenId:%{public}s Discoveryservice repeated", serviceInfoProfile.tokenId.c_str()); + return ERR_DM_DISCOVERY_REPEATED; + } + return DM_OK; +} + +int32_t DmServiceDiscoveryManager::StartServiceDiscovery(const ServiceInfoProfile& serviceInfoProfile) +{ + const ServiceInfo& serviceInfo = serviceInfoProfile.serviceRegInfo.serviceInfo; + int32_t ret = CheckDiscoveryMap(serviceInfoProfile); + if (ret != DM_OK) { + return ret; + } + std::lock_guard autolock(locks_); + discoveryMap_.emplace(serviceInfo.serviceId, serviceInfoProfile); + softbusConnector_->RegisterServiceDiscoveryCallback( + serviceInfo.serviceId, std::shared_ptr(shared_from_this())); + ServiceDiscoveryTimer(serviceInfo.serviceId); + return softbusConnector_->StartServiceDiscovery(serviceInfoProfile); +} + +int32_t DmServiceDiscoveryManager::StopServiceDiscovery(const ServiceInfoProfile& serviceInfoProfile) +{ + const ServiceInfo& serviceInfo = serviceInfoProfile.serviceRegInfo.serviceInfo; + std::lock_guard autolock(locks_); + auto item = discoveryMap_.find(serviceInfo.serviceId); + if (item == discoveryMap_.end()) { + LOGE("DmservicePublishManager: serviceId:%{public}lld notDiscoveryservice", serviceInfo.serviceId); + return DM_OK; + } + if (timer_ != nullptr) { + timer_->DeleteTimer(std::string(DISCOVERY_SERVICE_TIMEOUT_TASK) + std::to_string(serviceInfo.serviceId)); + discoveryMap_.erase(serviceInfo.serviceId); + softbusConnector_->UnRegisterServiceDiscoveryCallback(serviceInfo.serviceId); + } + return softbusConnector_->StopServiceDiscovery(serviceInfoProfile); +} + +void DmServiceDiscoveryManager::HandleDiscoveryTimeout(std::string& name) +{ + LOGI("DmServicePublishManager: HandlePublishTimeout"); + std::string serviceIdStr = name.substr(strlen(DISCOVERY_SERVICE_TIMEOUT_TASK)); + int64_t serviceId; + sscanf(serviceIdStr.c_str(), "%lld", &serviceId); + auto item = discoveryMap_.find(serviceId); + if (item == discoveryMap_.end()) { + LOGE("DmservicePublishManager: serviceId:%{public}lld rnot Discoveryservice", serviceId); + return; + } + StopServiceDiscovery(item->second); +} + +void DmServiceDiscoveryManager::OnServiceFound(int64_t localServiceId, const ServiceInfo& softbusService) +{ + LOGI("DmServiceDiscoveryManager localServiceId = %{public}lld", localServiceId); + LOGI("DmServiceDiscoveryManager serviceId - %{public}lld", softbusService.serviceId); + ServiceInfoProfile serviceInfoProfile; + const ServiceInfo& serviceInfo = serviceInfoProfile.serviceRegInfo.serviceInfo; + { + std::lock_guard autolock(locks_); + auto iter = discoveryMap_.find(localServiceId); + if (iter == discoveryMap_.end()) { + LOGE("subscribeid not found by serviceId %{public}lld", localServiceId); + return; + } + serviceInfoProfile = iter->second; + } + if (serviceInfo.serviceType == softbusService.serviceType && serviceInfo.customData == softbusService.customData) { + listener_->OnServiceFound(localServiceId, softbusService); + } + return; +} + +void DmServiceDiscoveryManager::OnServiceLost(int64_t localServiceId, int64_t serviceId) +{ + LOGI("DmserviceDiscoveryManager localServiceId = %{public}lld", localServiceId); + LOGI("DmServiceDiscoveryManager serviceId = %{public}lld", serviceId); + // TODO:non-value function + { + std::lock_guard autolock(locks_); + auto iter = discoveryMap_.find(localServiceId); + if (iter == discoveryMap_.end()) { + LOGE("subscribeid not found by serviceId = %{public}lld", localServiceId); + return; + } + } + listener_->OnServiceLost(localServiceId, serviceId); + return; +} +} // namespace DistributedHardware +} // namespace OHOS \ No newline at end of file diff --git a/services/service/include/device_manager_service.h b/services/service/include/device_manager_service.h index 069a2ad13..810e93584 100644 --- a/services/service/include/device_manager_service.h +++ b/services/service/include/device_manager_service.h @@ -29,6 +29,8 @@ #include "pin_holder.h" #include "device_manager_service_listener.h" #include "idevice_manager_service_impl.h" +#include "dm_device_info.h" +#include "dm_subscribe_info.h" #include "hichain_listener.h" #include "i_dm_check_api_white_list.h" #include "i_dm_service_impl_ext_resident.h" @@ -275,6 +277,11 @@ public: bool CheckSinkAccessControl(const DmAccessCaller &caller, const DmAccessCallee &callee); bool CheckSrcIsSameAccount(const DmAccessCaller &caller, const DmAccessCallee &callee); bool CheckSinkIsSameAccount(const DmAccessCaller &caller, const DmAccessCallee &callee); + + int32_t StartServiceDiscovery( + const std::string& localServiceId, const std::map& discParam); + int32_t StopServiceDiscovery(const ServiceFilter& serviceFilter); + private: bool IsDMServiceImplReady(); bool IsDMImplSoLoaded(); diff --git a/services/service/include/device_manager_service_listener.h b/services/service/include/device_manager_service_listener.h index 216835016..54a61191f 100644 --- a/services/service/include/device_manager_service_listener.h +++ b/services/service/include/device_manager_service_listener.h @@ -90,6 +90,8 @@ public: void OnSetRemoteDeviceNameResult(const ProcessInfo &processInfo, const std::string &deviceId, const std::string &deviceName, int32_t code) override; void SetExistPkgName(const std::set &pkgNameSet) override; + void OnServiceFound(int64_t localServiceId, const ServiceInfo& softbusService) override; + void OnServiceLost(int64_t localServiceId, int64_t serviceId) override; std::string GetLocalDisplayDeviceName() override; int32_t OpenAuthSessionWithPara(const std::string &deviceId, int32_t actionId, bool isEnable160m) override; diff --git a/services/service/include/idevice_manager_service_impl.h b/services/service/include/idevice_manager_service_impl.h index 949542bed..78fbd84c9 100644 --- a/services/service/include/idevice_manager_service_impl.h +++ b/services/service/include/idevice_manager_service_impl.h @@ -286,6 +286,9 @@ public: const DmAccessCallee &callee, const std::string &sinkUdid) = 0; virtual void DeleteHoDevice(const std::string &peerUdid, const std::vector &foreGroundUserIds, const std::vector &backGroundUserIds) = 0; + + virtual int32_t StartServiceDiscovery(const ServiceInfoProfile& serviceInfoProfile) = 0; + virtual int32_t StopServiceDiscovery(const ServiceInfoProfile& serviceInfoProfile) = 0; }; using CreateDMServiceFuncPtr = IDeviceManagerServiceImpl *(*)(void); diff --git a/services/service/src/device_manager_service.cpp b/services/service/src/device_manager_service.cpp index f68075c02..df0b92ad5 100644 --- a/services/service/src/device_manager_service.cpp +++ b/services/service/src/device_manager_service.cpp @@ -4638,5 +4638,84 @@ void DeviceManagerService::HandleAccountLogoutEventCallback(const std::string &c MultipleUserConnector::GetCurrentDMAccountInfo()); } #endif + +int32_t DeviceManagerService::StartServiceDiscovery( + const std::string& localServiceId, const std::map& discParam) +{ + std::string pkgName = discParam.at("pkgName"); + ServiceInfoProfile serviceInfoProfile; + ServiceInfo& serviceInfo = serviceInfoProfile.serviceRegInfo.serviceInfo; + serviceInfo.serviceId = stoi(localServiceId); + serviceInfo.serviceType = discParam.at("serviceType"); + serviceInfo.serviceName = discParam.at("serviceName"); + serviceInfo.serviceDisplayName = discParam.at("serviceDisplayName"); + serviceInfo.customData = discParam.at("customData"); + serviceInfo.dataLen = serviceInfo.customData.length(); + int32_t userId = -1; + MultipleUserConnector::GetCallerUserId(userId); + std::vector userVec; + int32_t ret = MultipleUserConnector::GetForegroundUserIds(userVec); + if (ret != DM_OK || userVec.size() == 0) { + LOGE("get userId error ret: %{public}d.", ret); + return ERR_DM_DISCOVERY_FAILED; + } + bool isAllowe = false; + for (auto id : userVec) { + if (userId == id) { + isAllowe = true; + break; + } + } + isAllowe = isAllowe || (userId == 0); + if (!isAllowe) { + return ERR_DM_DISCOVERY_FAILED; + } + if (IsDMServiceImplReady()) { + LOGE("StartServiceDiscovery failed, instance notinit or init failed."); + return ERR_DM_INIT_FAILED; + } + DmDeviceInfo deviceInfo; + GetLocalDeviceInfo(deviceInfo); + serviceInfoProfile.deviceId = deviceInfo.deviceId; + serviceInfoProfile.userId = userId; + serviceInfoProfile.tokenId = std::to_string(IPCSkeleton::GetCallingTokenID()); + ret = dmServiceImpl_->StartServiceDiscovery(serviceInfoProfile); + if (ret != 0) { + LOGE("StartServiceDiscovery error, failed ret: %{public}d", ret); + return ret; + } + return DM_OK; +} + +int32_t DeviceManagerService::StopServiceDiscovery(const ServiceFilter& serviceFilter) +{ + ServiceInfoProfile ServiceInfoProfile; + ServiceInfo& serviceInfo = ServiceInfoProfile.serviceRegInfo.serviceInfo; + serviceInfo.serviceId = serviceFilter.serviceId; + serviceInfo.serviceType = serviceFilter.serviceType; + serviceInfo.serviceName = serviceFilter.serviceName; + serviceInfo.serviceDisplayName = serviceFilter.serviceDisplayName; + serviceInfo.customData = serviceFilter.customData; + serviceInfo.dataLen = serviceInfo.customData.length(); + int32_t userId = -1; + MultipleUserConnector::GetCallerUserId(userId); + if (IsDMServiceImplReady()) { + LOGE("StopServiceDiscovery failed, instance not init or init failed."); + return ERR_DM_INIT_FAILED; + } + // TODO:no check user id in uservec, service id discoveried, dont need verify? + // TODO:待实现 + DmDeviceInfo deviceInfo; + GetLocalDeviceInfo(deviceInfo); + ServiceInfoProfile.deviceId = deviceInfo.deviceId; + ServiceInfoProfile.userId = userId; + ServiceInfoProfile.tokenId = std::to_string(IPCSkeleton::GetCallingTokenID()); + auto ret = dmServiceImpl_->StopServiceDiscovery(ServiceInfoProfile); + if (ret != 0) { + LOGE("StopServiceDiscovery error, failed ret: %{public}d", ret); + return ret; + } + return DM_OK; +} } // namespace DistributedHardware } // namespace OHOS diff --git a/services/service/src/device_manager_service_listener.cpp b/services/service/src/device_manager_service_listener.cpp index bc47a6a81..afd0cdb8b 100644 --- a/services/service/src/device_manager_service_listener.cpp +++ b/services/service/src/device_manager_service_listener.cpp @@ -39,6 +39,8 @@ #include "ipc_notify_get_device_profile_info_list_req.h" #include "ipc_notify_pin_holder_event_req.h" #include "ipc_notify_publish_result_req.h" +#include "ipc_notify_service_found_req.h" +#include "ipc_notify_service_lost_req.h" #include "ipc_notify_set_local_device_name_req.h" #include "ipc_notify_set_remote_device_name_req.h" #include "ipc_server_stub.h" @@ -1052,5 +1054,23 @@ int32_t DeviceManagerServiceListener::OpenAuthSessionWithPara(const std::string return ERR_DM_UNSUPPORTED_METHOD; #endif } + +void DeviceManagerServiceListener::OnServiceFound(int64_t localServiceId, const ServiceInfo& softbusService) +{ + std::shared_ptr pReq = std::make_shared(); + std::shared_ptr pRsp = std::make_shared(); + pReq->SetLocalServiceId(localServiceId); + pReq->SetServiceInfo(softbusService); + ipcServerListener_.SendRequest(NOTIFY_SERVICE_FOUND, pReq, pRsp); +} + +void DeviceManagerServiceListener::OnServiceLost(int64_t localServiceId, int64_t serviceId) +{ + std::shared_ptr pReq = std::make_shared(); + std::shared_ptr pRsp = std::make_shared(); + pReq->SetLocalServiceId(localServiceId); + pReq->SetServiceId(serviceId); + ipcServerListener_.SendRequest(NOTIFY_SERVICE_LOST, pReq, pRsp); +} } // namespace DistributedHardware } // namespace OHOS diff --git a/services/service/src/ipc/standard/ipc_cmd_parser.cpp b/services/service/src/ipc/standard/ipc_cmd_parser.cpp index e8f908bca..60724d932 100644 --- a/services/service/src/ipc/standard/ipc_cmd_parser.cpp +++ b/services/service/src/ipc/standard/ipc_cmd_parser.cpp @@ -40,6 +40,8 @@ #include "ipc_notify_get_device_profile_info_list_req.h" #include "ipc_notify_publish_result_req.h" #include "ipc_notify_pin_holder_event_req.h" +#include "ipc_notify_service_found_req.h" +#include "ipc_notify_service_lost_req.h" #include "ipc_notify_set_local_device_name_req.h" #include "ipc_notify_set_remote_device_name_req.h" #include "ipc_server_client_proxy.h" @@ -132,6 +134,28 @@ void CancelXcollieTimer(int32_t id) OHOS::HiviewDFX::XCollie::GetInstance().CancelTimer(id); } +bool EncodeDmServiceInfo(const ServiceInfo& serviceInfo, MessageParcel& parcel) +{ + bool bRet = true; + bRet = (bRet && parcel.WriteInt64(serviceInfo.serviceId)); + std::string serviceTypeStr(serviceInfo.serviceType); + bRet = (bRet && parcel.WriteString(serviceTypeStr)); + std::string serviceNameStr(serviceInfo.serviceName); + bRet = (bRet && parcel.WriteString(serviceNameStr)); + std::string serviceDisplayNameStr(serviceInfo.serviceDisplayName); + bRet = (bRet && parcel.WriteString(serviceDisplayNameStr)); + std::string customDataStr(serviceInfo.customData); + bRet = (bRet && parcel.WriteString(customDataStr)); + bRet = (bRet && parcel.WriteUint32(serviceInfo.dataLen)); + std::string bundleNameStr(serviceInfo.bundleName); + bRet = (bRet && parcel.WriteString(bundleNameStr)); + std::string moduleNameStr(serviceInfo.moduleName); + bRet = (bRet && parcel.WriteString(moduleNameStr)); + std::string abilityNamestr(serviceInfo.abilityName); + bRet = (bRet && parcel.WriteString(abilityNamestr)); + return bRet; +} + bool EncodeDmDeviceInfo(const DmDeviceInfo &devInfo, MessageParcel &parcel) { bool bRet = true; @@ -171,6 +195,7 @@ bool EncodePeerTargetId(const PeerTargetId &targetId, MessageParcel &parcel) bRet = (bRet && parcel.WriteString(targetId.bleMac)); bRet = (bRet && parcel.WriteString(targetId.wifiIp)); bRet = (bRet && parcel.WriteUint16(targetId.wifiPort)); + bRet = (bRet && parcel.WriteInt64(targetId.serviceId)); return bRet; } @@ -181,6 +206,7 @@ void DecodePeerTargetId(MessageParcel &parcel, PeerTargetId &targetId) targetId.bleMac = parcel.ReadString(); targetId.wifiIp = parcel.ReadString(); targetId.wifiPort = parcel.ReadUint16(); + targetId.serviceId = parcel.ReadInt64(); } ON_IPC_SET_REQUEST(SERVER_DEVICE_STATE_NOTIFY, std::shared_ptr pBaseReq, MessageParcel &data) @@ -1988,6 +2014,43 @@ ON_IPC_CMD(GET_LOCAL_DEVICE_NAME_OLD, MessageParcel &data, MessageParcel &reply) return DM_OK; } +ON_IPC_CMD(START_SERVICE_DISCOVERING, MessageParcel& data, MessageParcel& reply) +{ + int64_t serviceId = data.ReadInt64(); + std::string localServiceId = std::to_string(serviceId); + DmDiscoverMode discoverMode = static_cast(data.ReadInt32()); + std::string discParamStr = data.ReadString(); + std::map discParam; + ParseMapFromJsonString(discParamStr, discParam); + int32_t result = DeviceManagerService::GetInstance().StartServiceDiscovery(localServiceId, discParam); + if (!reply.WriteInt32(result)) { + LOGE("Write result failed"); + return ERR_DM_IPC_WRITE_FAILED; + } + return DM_OK; +} + +ON_IPC_CMD(STOP_SERVICE_DISCOVERING, MessageParcel& data, MessageParcel& reply) +{ + int64_t serviceId = data.ReadInt64(); + std::string discParamStr = data.ReadString(); + std::map discParam; + ParseMapFromJsonString(discParamStr, discParam); + ServiceFilter serviceFliter; + serviceFliter.serviceId = serviceId; + serviceFliter.serviceType = discParam["serviceType"]; + serviceFliter.serviceName = discParam["serviceName"]; + serviceFliter.serviceDisplayName = discParam["serviceDisplayName"]; + serviceFliter.customData = discParam["customData"]; + + int32_t result = DeviceManagerService::GetInstance().StopServiceDiscovery(serviceFliter); + if (!reply.WriteInt32(result)) { + LOGE("write result failed"); + return ERR_DM_IPC_WRITE_FAILED; + } + return DM_OK; +} + ON_IPC_CMD(CHECK_SRC_ACCESS_CONTROL, MessageParcel &data, MessageParcel &reply) { return OnIpcCmd(CHECK_SRC_ACCESS_CONTROL, data, reply); diff --git a/test/softbusunittest/UTTest_softbus_connector.cpp b/test/softbusunittest/UTTest_softbus_connector.cpp index 7d97ecee6..42012b693 100644 --- a/test/softbusunittest/UTTest_softbus_connector.cpp +++ b/test/softbusunittest/UTTest_softbus_connector.cpp @@ -47,6 +47,14 @@ public: void DeleteOffLineTimer(std::string udidHash) override {} }; +class ServiceDiscoveryCallbackTest : public IServiceDiscoveryCallback { +public: + ServiceDiscoveryCallbackTest() {} + virtual ~ServiceDiscoveryCallbackTest() {} + void OnServiceFound(int64_t localServiceId, const ServiceInfo& softbusService) override {} + void OnServiceLost(int64_t localServiceId, int64_t serviceId) override {} +}; + void SoftbusConnectorTest::SetUp() { } @@ -845,6 +853,96 @@ HWTEST_F(SoftbusConnectorTest, GetDeviceUdidHashByUdid_002, testing::ext::TestSi bool isForceJoin = false; softbusConnector->JoinLnn(deviceId, isForceJoin); } + +HWTEST_F(SoftbusConnectorTest, StartServiceDiscovery_001, testing::ext::TestSize.Level1) +{ + ServiceInfoProfile serviceInfoProfile; + ServiceInfo& serviceInfo = serviceInfoProfile.serviceRegInfo.serviceInfo; + serviceInfo.serviceId = 12345; + serviceInfo.serviceType = "testServiceType"; + serviceInfo.serviceName = "testServiceName"; + serviceInfo.serviceDisplayName = "testServiceDisplayName"; + serviceInfo.customData = "testCustomData"; + serviceInfo.dataLen = serviceInfo.customData.length(); + + + std::shared_ptr softbusConnector = std::make_shared(); + int32_t ret = softbusConnector->StartServiceDiscovery(serviceInfoProfile); + EXPECT_EQ(ret, DM_OK); +} + +HWTEST_F(SoftbusConnectorTest, StopServiceDiscovery_001, testing::ext::TestSize.Level1) +{ + ServiceInfoProfile serviceInfoProfile; + ServiceInfo& serviceInfo = serviceInfoProfile.serviceRegInfo.serviceInfo; + serviceInfo.serviceId = 12345; + serviceInfo.serviceType = "testServiceType"; + serviceInfo.serviceName = "testServiceName"; + serviceInfo.serviceDisplayName = "testServiceDisplayName"; + serviceInfo.customData = "testCustomData"; + serviceInfo.dataLen = serviceInfo.customData.length(); + + std::shared_ptr softbusConnector = std::make_shared(); + int32_t ret = softbusConnector->StopServiceDiscovery(serviceInfoProfile); + EXPECT_EQ(ret, DM_OK); +} + +HWTEST_F(SoftbusConnectorTest, RegisterServiceDiscoveryCallback_001, testing::ext::TestSize.Level1) +{ + int64_t serviceId = 12345; + auto callback = std::make_shared(); + + std::shared_ptr softbusConnector = std::make_shared(); + int32_t ret = softbusConnector->RegisterServiceDiscoveryCallback(serviceId, callback); + EXPECT_EQ(ret, DM_OK); +} + +HWTEST_F(SoftbusConnectorTest, UnRegisterServiceDiscoveryCallback_001, testing::ext::TestSize.Level1) +{ + int64_t serviceId = 12345; + std::shared_ptr softbusConnector = std::make_shared(); + auto callback = std::make_shared(); + softbusConnector->RegisterServiceDiscoveryCallback(serviceId, callback); + + int32_t ret = softbusConnector->UnRegisterServiceDiscoveryCallback(serviceId); + EXPECT_EQ(ret, DM_OK); +} + +HWTEST_F(SoftbusConnectorTest, OnSoftbusOnServiceFound_001, testing::ext::TestSize.Level1) +{ + std::shared_ptr softbusConnector = std::make_shared(); + softbusConnector->OnSoftbusOnServiceFound(nullptr); +} + +HWTEST_F(SoftbusConnectorTest, OnSoftbusOnServiceFound_002, testing::ext::TestSize.Level1) +{ + ServiceInfo service; + service.serviceId = 12345; + service.serviceType = "testServiceType"; + service.serviceName = "testServiceName"; + service.serviceDisplayName = "testServiceDisplayName"; + service.customData = "testCustomData"; + service.dataLen = service.customData.length(); + + std::shared_ptr softbusConnector = std::make_shared(); + softbusConnector->OnSoftbusOnServiceFound(&service); + EXPECT_TRUE(softbusConnector->serviceDiscoveryCallbackMap_.empty()); +} + +HWTEST_F(SoftbusConnectorTest, OnSoftbusOnServiceLost_001, testing::ext::TestSize.Level1) +{ + std::shared_ptr softbusConnector = std::make_shared(); + softbusConnector->OnSoftbusOnServiceLost(nullptr); +} + +HWTEST_F(SoftbusConnectorTest, OnSoftbusOnServiceLost_002, testing::ext::TestSize.Level1) +{ + std::shared_ptr softbusConnector = std::make_shared(); + const char* serviceIdStr = "12345"; + + softbusConnector->OnSoftbusOnServiceLost(serviceIdStr); + EXPECT_TRUE(softbusConnector->serviceDiscoveryCallbackMap_.empty()); +} } // namespace } // namespace DistributedHardware } // namespace OHOS- \ No newline at end of file diff --git a/test/unittest/BUILD.gn b/test/unittest/BUILD.gn index b405c21c9..437cf3f2a 100644 --- a/test/unittest/BUILD.gn +++ b/test/unittest/BUILD.gn @@ -66,6 +66,7 @@ group("unittest") { ":UTTest_dm_radar_helper_test", ":UTTest_dm_screen_common_event", ":UTTest_dm_service_load", + ":UTTest_dm_service_discovery_manager", ":UTTest_dm_softbus_cache", ":UTTest_dm_timer", ":UTTest_dm_transport", @@ -1870,6 +1871,37 @@ ohos_unittest("UTTest_dm_screen_common_event") { ## UnitTest UTTest_dm_screen_common_event }}} +## UnitTest UTTest_dm_service_discovery_manager {{{ +ohos_unittest("UTTest_dm_service_discovery_manager") { + module_out_path = module_out_path + + include_dirs = [ + "${devicemanager_path}/commondependency/include", + "${devicemanager_path}/test/unittest", + ] + + sources = [ + "${devicemanager_path}/test/unittest/UTTest_dm_service_discovery_manager.cpp", + "${devicemanager_path}/test/unittest/mock/softbus_connector_mock.cpp", + "${devicemanager_path}/test/unittest/mock/dm_service_discovery_manager_mock.cpp", + ] + + deps = [ ":device_manager_test_common" ] + + external_deps = [ + "device_info_manager:distributed_device_profile_common", + "device_info_manager:distributed_device_profile_sdk", + "device_auth:deviceauth_sdk", + "dsoftbus:softbus_client", + "ffrt:libffrt", + "googletest:gmock", + "googletest:gmock_main", + "hilog:libhilog", + ] +} + +## UnitTest UTTest_dm_service_discovery_manager }}} + ## UnitTest UTTest_relationship_sync_mgr {{{ ohos_unittest("UTTest_relationship_sync_mgr") { module_out_path = module_out_path diff --git a/test/unittest/UTTest_device_manager_service_impl_first.cpp b/test/unittest/UTTest_device_manager_service_impl_first.cpp index d778f7436..c85cb6bf7 100644 --- a/test/unittest/UTTest_device_manager_service_impl_first.cpp +++ b/test/unittest/UTTest_device_manager_service_impl_first.cpp @@ -822,6 +822,24 @@ HWTEST_F(DeviceManagerServiceImplFirstTest, DeleteAclByTokenId_002, testing::ext EXPECT_TRUE(delACLInfoVec.empty()); EXPECT_TRUE(userIdVec.empty()); } + +HWTEST_F(DeviceManagerServiceImplFirstTest, StartServiceDiscovery_001, testing::ext::TestSize.Level1) +{ + deviceManagerServiceImpl_->softbusConnector_ = nullptr; + + ServiceInfoProfile serviceInfoProfile; + int32_t ret = deviceManagerServiceImpl_->StartServiceDiscovery(serviceInfoProfile); + EXPECT_EQ(ret, ERR_DM_PUBLISH_FAILED); +} + +HWTEST_F(DeviceManagerServiceImplFirstTest, StopServiceDiscovery_001, testing::ext::TestSize.Level1) +{ + deviceManagerServiceImpl_->softbusConnector_ = nullptr; + + ServiceInfoProfile serviceInfoProfile; + int32_t ret = deviceManagerServiceImpl_->StopServiceDiscovery(serviceInfoProfile); + EXPECT_EQ(ret, ERR_DM_PUBLISH_FAILED); +} } // namespace } // namespace DistributedHardware } // namespace OHOS diff --git a/test/unittest/UTTest_device_manager_service_listener.cpp b/test/unittest/UTTest_device_manager_service_listener.cpp index ff761bb53..1c096b102 100644 --- a/test/unittest/UTTest_device_manager_service_listener.cpp +++ b/test/unittest/UTTest_device_manager_service_listener.cpp @@ -49,6 +49,7 @@ void DeviceManagerServiceListenerTest::SetUpTestCase() DmIpcServerListener::dmIpcServerListener = ipcServerListenerMock_; DmKVAdapterManager::dmKVAdapterManager = kVAdapterManagerMock_; DmAppManager::dmAppManager = appManagerMock_; + DeviceManagerImpl::GetInstance().ipcClientProxy_ = ipcClientProxyMock_; } void DeviceManagerServiceListenerTest::TearDownTestCase() @@ -63,6 +64,8 @@ void DeviceManagerServiceListenerTest::TearDownTestCase() kVAdapterManagerMock_ = nullptr; DmAppManager::dmAppManager = nullptr; appManagerMock_ = nullptr; + DeviceManagerImpl::GetInstance().ipcClientProxy_ = nullptr; + ipcClientProxyMock_ = nullptr; } namespace { @@ -1103,6 +1106,35 @@ HWTEST_F(DeviceManagerServiceListenerTest, OpenAuthSessionWithPara_001, testing: int32_t ret = listener_->OpenAuthSessionWithPara(deviceId, actionId, isEnable160m); EXPECT_NE(ret, DM_OK); } + +HWTEST_F(DeviceManagerServiceListenerTest, OnServiceFound_001, testing::ext::TestSize.Level1) +{ + int64_t localServiceId = 12345; + ServiceInfo softbusService; + softbusService.serviceId = 67890; + softbusService.serviceType = "testServiceType"; + softbusService.serviceName = "testServiceName"; + softbusService.serviceDisplayName = "testServiceDisplayName"; + softbusService.customData = "testCustomData"; + softbusService.dataLen = softbusService.customData.length(); + + std::shared_ptr listener = std::make_shared(); + EXPECT_CALL(*ipcClientProxyMock_, SendRequest(NOTIFY_SERVICE_FOUND, testing::_, testing::_)) + .Times(1); + listener->OnServiceFound(localServiceId, softbusService); +} + +HWTEST_F(DeviceManagerServiceListenerTest, OnServiceLost_Success, testing::ext::TestSize.Level1) +{ + int64_t localServiceId = 12345; + int64_t serviceId = 67890; + + std::shared_ptr listener = std::make_shared(); + EXPECT_CALL(*ipcClientProxyMock_, SendRequest(NOTIFY_SERVICE_LOST, testing::_, testing::_)) + .Times(1); + + listener->OnServiceLost(localServiceId, serviceId); +} } // namespace } // namespace DistributedHardware } // namespace OHOS diff --git a/test/unittest/UTTest_device_manager_service_listener.h b/test/unittest/UTTest_device_manager_service_listener.h index 771c19722..ba8b75a9f 100644 --- a/test/unittest/UTTest_device_manager_service_listener.h +++ b/test/unittest/UTTest_device_manager_service_listener.h @@ -21,12 +21,14 @@ #include "device_manager_service_listener.h" #include "dm_device_info.h" +#include "device_manager_impl.h" #include "ipc_server_listener.h" #include "dm_softbus_cache_mock.h" #include "dm_crypto_mock.h" #include "ipc_server_listener_mock.h" #include "kv_adapter_manager_mock.h" #include "app_manager_mock.h" +#include "mock/mock_ipc_client_proxy.h" namespace OHOS { namespace DistributedHardware { @@ -44,6 +46,7 @@ public: static inline std::shared_ptr kVAdapterManagerMock_ = std::make_shared(); static inline std::shared_ptr appManagerMock_ = std::make_shared(); + static inline std::shared_ptr ipcClientProxyMock_ = std::make_shared(); }; } // namespace DistributedHardware } // namespace OHOS diff --git a/test/unittest/UTTest_device_manager_service_three.cpp b/test/unittest/UTTest_device_manager_service_three.cpp index 5ca56ab14..96e4d6210 100644 --- a/test/unittest/UTTest_device_manager_service_three.cpp +++ b/test/unittest/UTTest_device_manager_service_three.cpp @@ -64,6 +64,7 @@ void DeviceManagerServiceThreeTest::TearDown() Mock::VerifyAndClearExpectations(permissionManagerMock_.get()); Mock::VerifyAndClearExpectations(softbusListenerMock_.get()); Mock::VerifyAndClearExpectations(deviceManagerServiceImplMock_.get()); + Mock::VerifyAndClearExpectations(multipleUserConnectorMock_.get()); } void DeviceManagerServiceThreeTest::SetUpTestCase() @@ -72,6 +73,7 @@ void DeviceManagerServiceThreeTest::SetUpTestCase() DmPermissionManager::dmPermissionManager = permissionManagerMock_; DmSoftbusListener::dmSoftbusListener = softbusListenerMock_; DmDeviceManagerServiceImpl::dmDeviceManagerServiceImpl = deviceManagerServiceImplMock_; + DmMultipleUserConnector::dmMultipleUserConnector = multipleUserConnectorMock_; } void DeviceManagerServiceThreeTest::TearDownTestCase() @@ -84,6 +86,8 @@ void DeviceManagerServiceThreeTest::TearDownTestCase() softbusListenerMock_ = nullptr; DmDeviceManagerServiceImpl::dmDeviceManagerServiceImpl = nullptr; deviceManagerServiceImplMock_ = nullptr; + DmMultipleUserConnector::dmMultipleUserConnector = nullptr; + multipleUserConnectorMock_ = nullptr; } namespace { @@ -909,6 +913,138 @@ HWTEST_F(DeviceManagerServiceThreeTest, UnloadDMDeviceRiskDetect_301, testing::e DeviceManagerService::GetInstance().UnloadDMDeviceRiskDetect(); EXPECT_EQ(DeviceManagerService::GetInstance().dmDeviceRiskDetect_, nullptr); } + +HWTEST_F(DeviceManagerServiceThreeTest, StartServiceDiscovery_001, testing::ext::TestSize.Level1) +{ + std::string localServiceId = "12345"; + std::map discParam = { + {"pkgName", "testPkgName"}, + {"serviceType", "testServiceType"}, + {"serviceName", "testServiceName"}, + {"serviceDisplayName", "testServiceDisplayName"}, + {"customData", "testCustomData"} + }; + + EXPECT_CALL(*multipleUserConnectorMock_, GetCallerUserId(testing::_)).WillOnce(SetArgReferee<0>(-1)); + int32_t ret = DeviceManagerService::GetInstance().StartServiceDiscovery(localServiceId, discParam); + EXPECT_EQ(ret, ERR_DM_DISCOVERY_FAILED); +} + +HWTEST_F(DeviceManagerServiceThreeTest, StartServiceDiscovery_002, testing::ext::TestSize.Level1) +{ + std::string localServiceId = "12345"; + std::map discParam = { + {"pkgName", "testPkgName"}, + {"serviceType", "testServiceType"}, + {"serviceName", "testServiceName"}, + {"serviceDisplayName", "testServiceDisplayName"}, + {"customData", "testCustomData"} + }; + + EXPECT_CALL(*multipleUserConnectorMock_, GetForegroundUserIds(testing::_)).WillOnce(Return(ERR_DM_FAILED)); + int32_t ret = DeviceManagerService::GetInstance().StartServiceDiscovery(localServiceId, discParam); + EXPECT_EQ(ret, ERR_DM_DISCOVERY_FAILED); +} + +HWTEST_F(DeviceManagerServiceThreeTest, StartServiceDiscovery_003, testing::ext::TestSize.Level1) +{ + std::string localServiceId = "12345"; + std::map discParam = { + {"pkgName", "testPkgName"}, + {"serviceType", "testServiceType"}, + {"serviceName", "testServiceName"}, + {"serviceDisplayName", "testServiceDisplayName"}, + {"customData", "testCustomData"} + }; + + EXPECT_CALL(*multipleUserConnectorMock_, GetCallerUserId(testing::_)).WillOnce(SetArgReferee<0>(1)); + EXPECT_CALL(*multipleUserConnectorMock_, GetForegroundUserIds(testing::_)) + .WillOnce(DoAll(SetArgReferee<0>(std::vector{2, 3}), Return(DM_OK))); + + int32_t ret = DeviceManagerService::GetInstance().StartServiceDiscovery(localServiceId, discParam); + EXPECT_EQ(ret, ERR_DM_DISCOVERY_FAILED); +} + +HWTEST_F(DeviceManagerServiceThreeTest, StartServiceDiscovery_004, testing::ext::TestSize.Level1) +{ + std::string localServiceId = "12345"; + std::map discParam = { + {"pkgName", "testPkgName"}, + {"serviceType", "testServiceType"}, + {"serviceName", "testServiceName"}, + {"serviceDisplayName", "testServiceDisplayName"}, + {"customData", "testCustomData"} + }; + + EXPECT_CALL(*deviceManagerServiceMock_, IsDMServiceImplReady()).WillOnce(Return(false)); + int32_t ret = DeviceManagerService::GetInstance().StartServiceDiscovery(localServiceId, discParam); + EXPECT_EQ(ret, ERR_DM_INIT_FAILED); +} + +HWTEST_F(DeviceManagerServiceThreeTest, StartServiceDiscovery_005, testing::ext::TestSize.Level1) +{ + std::string localServiceId = "12345"; + std::map discParam = { + {"pkgName", "testPkgName"}, + {"serviceType", "testServiceType"}, + {"serviceName", "testServiceName"}, + {"serviceDisplayName", "testServiceDisplayName"}, + {"customData", "testCustomData"} + }; + + EXPECT_CALL(*multipleUserConnectorMock_, GetCallerUserId(testing::_)).WillOnce(SetArgReferee<0>(1)); + EXPECT_CALL(*multipleUserConnectorMock_, GetForegroundUserIds(testing::_)) + .WillOnce(DoAll(SetArgReferee<0>(std::vector{1}), Return(DM_OK))); + EXPECT_CALL(*deviceManagerServiceMock_, IsDMServiceImplReady()).WillOnce(Return(true)); + EXPECT_CALL(*deviceManagerServiceImplMock_, StartServiceDiscovery(testing::_)).WillOnce(Return(DM_OK)); + + int32_t ret = DeviceManagerService::GetInstance().StartServiceDiscovery(localServiceId, discParam); + EXPECT_EQ(ret, DM_OK); +} + +HWTEST_F(DeviceManagerServiceThreeTest, StopServiceDiscovery_001, testing::ext::TestSize.Level1) +{ + ServiceFilter serviceFilter; + serviceFilter.serviceId = 12345; + serviceFilter.serviceType = "testServiceType"; + serviceFilter.serviceName = "testServiceName"; + serviceFilter.serviceDisplayName = "testServiceDisplayName"; + serviceFilter.customData = "testCustomData"; + + EXPECT_CALL(*deviceManagerServiceMock_, IsDMServiceImplReady()).WillOnce(Return(true)); + int32_t ret = DeviceManagerService::GetInstance().StopServiceDiscovery(serviceFilter); + EXPECT_EQ(ret, ERR_DM_INIT_FAILED); +} + +HWTEST_F(DeviceManagerServiceThreeTest, StopServiceDiscovery_002, testing::ext::TestSize.Level1) +{ + ServiceFilter serviceFilter; + serviceFilter.serviceId = 12345; + serviceFilter.serviceType = "testServiceType"; + serviceFilter.serviceName = "testServiceName"; + serviceFilter.serviceDisplayName = "testServiceDisplayName"; + serviceFilter.customData = "testCustomData"; + + EXPECT_CALL(*deviceManagerServiceMock_, IsDMServiceImplReady()).WillOnce(Return(false)); + EXPECT_CALL(*deviceManagerServiceImplMock_, StopServiceDiscovery(testing::_)).WillOnce(Return(ERR_DM_FAILED)); + int32_t ret = DeviceManagerService::GetInstance().StopServiceDiscovery(serviceFilter); + EXPECT_EQ(ret, ERR_DM_FAILED); +} + +HWTEST_F(DeviceManagerServiceThreeTest, StopServiceDiscovery_003, testing::ext::TestSize.Level1) +{ + ServiceFilter serviceFilter; + serviceFilter.serviceId = 12345; + serviceFilter.serviceType = "testServiceType"; + serviceFilter.serviceName = "testServiceName"; + serviceFilter.serviceDisplayName = "testServiceDisplayName"; + serviceFilter.customData = "testCustomData"; + + EXPECT_CALL(*deviceManagerServiceMock_, IsDMServiceImplReady()).WillOnce(Return(false)); + EXPECT_CALL(*deviceManagerServiceImplMock_, StopServiceDiscovery(testing::_)).WillOnce(Return(DM_OK)); + int32_t ret = DeviceManagerService::GetInstance().StopServiceDiscovery(serviceFilter); + EXPECT_EQ(ret, DM_OK); +} } // namespace } // namespace DistributedHardware } // namespace OHOS diff --git a/test/unittest/UTTest_device_manager_service_three.h b/test/unittest/UTTest_device_manager_service_three.h index 4f7c7666b..3f03c34cc 100644 --- a/test/unittest/UTTest_device_manager_service_three.h +++ b/test/unittest/UTTest_device_manager_service_three.h @@ -31,6 +31,7 @@ #include "softbus_listener_mock.h" #include "device_manager_service_mock.h" #include "device_manager_service_impl_mock.h" +#include "multiple_user_connector_mock.h" namespace OHOS { namespace DistributedHardware { @@ -49,6 +50,8 @@ public: std::make_shared(); static inline std::shared_ptr deviceManagerServiceImplMock_ = std::make_shared(); + static inline std::shared_ptr multipleUserConnectorMock_ = + std::make_shared(); }; } // namespace DistributedHardware } // namespace OHOS diff --git a/test/unittest/UTTest_dm_service_discovery_manager.cpp b/test/unittest/UTTest_dm_service_discovery_manager.cpp new file mode 100644 index 000000000..0f9f7fce1 --- /dev/null +++ b/test/unittest/UTTest_dm_service_discovery_manager.cpp @@ -0,0 +1,248 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "UTTest_dm_service_discovery_manager.h" + +#include + +//#include "dm_log.h" +#include "dm_constants.h" +// #include "dm_adapter_manager.h" +// #include "ipc_notify_device_state_req.h" +// #include "ipc_notify_auth_result_req.h" +// #include "ipc_notify_device_found_req.h" +// #include "ipc_notify_discover_result_req.h" +// #include "hichain_connector.h" +// #include "device_manager_service_listener.h" + +using namespace testing; +using namespace testing::ext; + +namespace OHOS { +namespace DistributedHardware { +void DmServiceDiscoveryManagerTest::SetUp() +{ + if (discoveryManager_ == nullptr) { + discoveryManager_ = std::make_shared(softbusConnector_, listener_); + } +} + +void DmServiceDiscoveryManagerTest::TearDown() +{ + Mock::VerifyAndClearExpectations(softbusConnectorMock_.get()); + Mock::VerifyAndClearExpectations(dmServiceDiscoveryManagerMock_.get()); +} + +void DmServiceDiscoveryManagerTest::SetUpTestCase() +{ + softbusConnectorMock_ = std::make_shared(); + DmSoftbusConnector::dmSoftbusConnector = softbusConnectorMock_; + dmServiceDiscoveryManagerMock_ = std::make_shared(); + DmDmServiceDiscoveryManager::dmServiceDiscoveryManager = dmServiceDiscoveryManagerMock_; +} + +void DmServiceDiscoveryManagerTest::TearDownTestCase() +{ + DmSoftbusConnector::dmSoftbusConnector = nullptr; + softbusConnectorMock_ = nullptr; + DmDmServiceDiscoveryManager::dmServiceDiscoveryManager = nullptr; + dmServiceDiscoveryManagerMock_ = nullptr; +} + +HWTEST_F(DmServiceDiscoveryManagerTest, ServiceDiscoveryTimer_001, testing::ext::TestSize.Level1) +{ + int64_t serviceId = 12345; + + discoveryManager_->timer_ = nullptr; + discoveryManager_->ServiceDiscoveryTimer(serviceId); + EXPECT_NE(discoveryManager_->timer_, nullptr); +} + +HWTEST_F(DmServiceDiscoveryManagerTest, ServiceDiscoveryTimer_002, testing::ext::TestSize.Level1) +{ + int64_t serviceId = 12345; + + discoveryManager_->timer_ = std::make_shared(); + discoveryManager_->ServiceDiscoveryTimer(serviceId); + EXPECT_NE(discoveryManager_->timer_, nullptr); +} + +HWTEST_F(DmServiceDiscoveryManagerTest, CheckDiscoveryMap_001, testing::ext::TestSize.Level1) +{ + discoveryManager_->discoveryMap_.clear(); + ServiceInfoProfile serviceInfoProfile; + int32_t ret = discoveryManager_->CheckDiscoveryMap(serviceInfoProfile); + EXPECT_EQ(ret, DM_OK); + EXPECT_TRUE(discoveryManager_->discoveryMap_.empty()); +} + +HWTEST_F(DmServiceDiscoveryManagerTest, CheckDiscoveryMap_002, testing::ext::TestSize.Level1) +{ + discoveryManager_->discoveryMap_.clear(); + ServiceInfoProfile serviceInfoProfile; + serviceInfoProfile.serviceRegInfo.serviceInfo.serviceId = 12345; + discoveryManager_->discoveryMap_.emplace(67890, serviceInfoProfile); + int32_t ret = discoveryManager_->CheckDiscoveryMap(serviceInfoProfile); + EXPECT_EQ(ret, ERR_DM_DISCOVERY_REPEATED); +} + +HWTEST_F(DmServiceDiscoveryManagerTest, CheckDiscoveryMap_003, testing::ext::TestSize.Level1) +{ + discoveryManager_->discoveryMap_.clear(); + ServiceInfoProfile serviceInfoProfile; + serviceInfoProfile.serviceRegInfo.serviceInfo.serviceId = 12345; + discoveryManager_->discoveryMap_.emplace(12345, serviceInfoProfile); + int32_t ret = discoveryManager_->CheckDiscoveryMap(serviceInfoProfile); + EXPECT_EQ(ret, DM_OK); +} + +HWTEST_F(DmServiceDiscoveryManagerTest, CheckDiscoveryMap_004, testing::ext::TestSize.Level1) +{ + discoveryManager_->discoveryMap_.clear(); + std::size_t DM_MAX_SERVICE_ID_NUM = 900000; + for (std::size_t i = 0; i < DM_MAX_SERVICE_ID_NUM; ++i) { + ServiceInfoProfile serviceInfoProfile; + serviceInfoProfile.serviceRegInfo.serviceInfo.serviceId = i; + discoveryManager_->discoveryMap_.emplace(i, serviceInfoProfile); + } + ServiceInfoProfile serviceInfoProfile; + serviceInfoProfile.serviceRegInfo.serviceInfo.serviceId = DM_MAX_SERVICE_ID_NUM + 1; + int32_t ret = discoveryManager_->CheckDiscoveryMap(serviceInfoProfile); + EXPECT_EQ(ret, DM_OK); +} + +HWTEST_F(DmServiceDiscoveryManagerTest, CheckDiscoveryMap_005, testing::ext::TestSize.Level1) +{ + discoveryManager_->discoveryMap_.clear(); + std::size_t DM_MAX_SERVICE_ID_NUM = 900000; + ServiceInfoProfile serviceInfoProfile; + serviceInfoProfile.tokenId = "testTokenId"; + for (std::size_t i = 0; i < DM_MAX_SERVICE_ID_NUM; ++i) { + ServiceInfoProfile historyServiceInfo; + historyServiceInfo.tokenId = "testTokenId"; + discoveryManager_->discoveryMap_.emplace(i, historyServiceInfo); + } + int32_t ret = discoveryManager_->CheckDiscoveryMap(serviceInfoProfile); + EXPECT_EQ(ret, ERR_DM_DISCOVERY_REPEATED); +} + +HWTEST_F(DmServiceDiscoveryManagerTest, StartServiceDiscovery_001, testing::ext::TestSize.Level1) +{ + ServiceInfoProfile serviceInfoProfile; + EXPECT_CALL(*dmServiceDiscoveryManagerMock_, CheckDiscoveryMap(testing::_)).WillOnce(Return(ERR_DM_DISCOVERY_REPEATED)); + int32_t ret = discoveryManager_->StartServiceDiscovery(serviceInfoProfile); + EXPECT_EQ(ret, ERR_DM_DISCOVERY_REPEATED); +} + +HWTEST_F(DmServiceDiscoveryManagerTest, StartServiceDiscovery_002, testing::ext::TestSize.Level1) +{ + ServiceInfoProfile serviceInfoProfile; + serviceInfoProfile.serviceRegInfo.serviceInfo.serviceId = 12345; + + EXPECT_CALL(*dmServiceDiscoveryManagerMock_, CheckDiscoveryMap(testing::_)).WillOnce(Return(DM_OK)); + EXPECT_CALL(*softbusConnectorMock_, RegisterServiceDiscoveryCallback(12345, testing::_)).Times(1); + EXPECT_CALL(*softbusConnectorMock_, StartServiceDiscovery(testing::_)).WillOnce(Return(DM_OK)); + + int32_t ret = discoveryManager_->StartServiceDiscovery(serviceInfoProfile); + EXPECT_EQ(ret, DM_OK); +} + +HWTEST_F(DmServiceDiscoveryManagerTest, StartServiceDiscovery_003, testing::ext::TestSize.Level1) +{ + ServiceInfoProfile serviceInfoProfile; + serviceInfoProfile.serviceRegInfo.serviceInfo.serviceId = 67890; + + EXPECT_CALL(*dmServiceDiscoveryManagerMock_, CheckDiscoveryMap(testing::_)).WillOnce(Return(DM_OK)); + EXPECT_CALL(*softbusConnectorMock_, RegisterServiceDiscoveryCallback(67890, testing::_)).Times(1); + EXPECT_CALL(*softbusConnectorMock_, StartServiceDiscovery(testing::_)).WillOnce(Return(DM_OK)); + + int32_t ret = discoveryManager_->StartServiceDiscovery(serviceInfoProfile); + EXPECT_EQ(ret, DM_OK); +} + +HWTEST_F(DmServiceDiscoveryManagerTest, StartServiceDiscovery_004, testing::ext::TestSize.Level1) +{ + ServiceInfoProfile serviceInfoProfile; + serviceInfoProfile.serviceRegInfo.serviceInfo.serviceId = 12345; + + EXPECT_CALL(*dmServiceDiscoveryManagerMock_, CheckDiscoveryMap(testing::_)).WillOnce(Return(DM_OK)); + EXPECT_CALL(*softbusConnectorMock_, RegisterServiceDiscoveryCallback(12345, testing::_)).Times(1); + EXPECT_CALL(*softbusConnectorMock_, StartServiceDiscovery(testing::_)).WillOnce(Return(ERR_DM_DISCOVERY_FAILED)); + + int32_t ret = discoveryManager_->StartServiceDiscovery(serviceInfoProfile); + EXPECT_EQ(ret, ERR_DM_DISCOVERY_FAILED); +} + +HWTEST_F(DmServiceDiscoveryManagerTest, StopServiceDiscovery_001, testing::ext::TestSize.Level1) +{ + ServiceInfoProfile serviceInfoProfile; + serviceInfoProfile.serviceRegInfo.serviceInfo.serviceId = 12345; + + discoveryManager_->discoveryMap_.clear(); + int32_t ret = discoveryManager_->StopServiceDiscovery(serviceInfoProfile); + EXPECT_EQ(ret, DM_OK); +} + +HWTEST_F(DmServiceDiscoveryManagerTest, StopServiceDiscovery_002, testing::ext::TestSize.Level1) +{ + ServiceInfoProfile serviceInfoProfile; + serviceInfoProfile.serviceRegInfo.serviceInfo.serviceId = 12345; + + discoveryManager_->timer_ = std::make_shared(); + discoveryManager_->discoveryMap_.emplace(12345, serviceInfoProfile); + + EXPECT_CALL(*softbusConnectorMock_, UnRegisterServiceDiscoveryCallback(12345)).Times(1); + EXPECT_CALL(*softbusConnectorMock_, StopServiceDiscovery(testing::_)).WillOnce(Return(DM_OK)); + + int32_t ret = discoveryManager_->StopServiceDiscovery(serviceInfoProfile); + EXPECT_EQ(ret, DM_OK); +} + +HWTEST_F(DmServiceDiscoveryManagerTest, StopServiceDiscovery_003, testing::ext::TestSize.Level1) +{ + ServiceInfoProfile serviceInfoProfile; + serviceInfoProfile.serviceRegInfo.serviceInfo.serviceId = 12345; + + discoveryManager_->timer_ = nullptr; + discoveryManager_->discoveryMap_.emplace(12345, serviceInfoProfile); + + EXPECT_CALL(*softbusConnectorMock_, UnRegisterServiceDiscoveryCallback(12345)).Times(0); + EXPECT_CALL(*softbusConnectorMock_, StopServiceDiscovery(testing::_)).WillOnce(Return(DM_OK)); + + int32_t ret = discoveryManager_->StopServiceDiscovery(serviceInfoProfile); + EXPECT_EQ(ret, DM_OK); +} + +HWTEST_F(DmServiceDiscoveryManagerTest, HandleDiscoveryTimeout_001, testing::ext::TestSize.Level1) +{ + std::string timeoutTaskName = std::string("deviceManagerTiner:discoveryservice") + "12345"; + discoveryManager_->discoveryMap_.clear(); + + EXPECT_CALL(*dmServiceDiscoveryManagerMock_, StopServiceDiscovery(testing::_)).Times(0); + discoveryManager_->HandleDiscoveryTimeout(timeoutTaskName); +} + +HWTEST_F(DmServiceDiscoveryManagerTest, HandleDiscoveryTimeout_002, testing::ext::TestSize.Level1) +{ + std::string timeoutTaskName = std::string("deviceManagerTiner:discoveryservice") + "12345"; + ServiceInfoProfile serviceInfoProfile; + serviceInfoProfile.serviceRegInfo.serviceInfo.serviceId = 12345; + discoveryManager_->discoveryMap_.emplace(12345, serviceInfoProfile); + + EXPECT_CALL(*dmServiceDiscoveryManagerMock_, StopServiceDiscovery(testing::_)).Times(1); + discoveryManager_->HandleDiscoveryTimeout(timeoutTaskName); +} +} +} \ No newline at end of file diff --git a/test/unittest/UTTest_dm_service_discovery_manager.h b/test/unittest/UTTest_dm_service_discovery_manager.h new file mode 100644 index 000000000..033f11446 --- /dev/null +++ b/test/unittest/UTTest_dm_service_discovery_manager.h @@ -0,0 +1,47 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +#ifndef OHOS_UTTEST_DM_DEVICE_DISCOVERY_MANAGER_H +#define OHOS_UTTEST_DM_DEVICE_DISCOVERY_MANAGER_H + +#include +#include + +#include "dm_service_discovery_manager.h" +#include "device_manager_service_listener.h" +#include "softbus_connector.h" +#include "dm_service_discovery_manager_mock.h" +#include "softbus_connector_mock.h" + +namespace OHOS { +namespace DistributedHardware { +class DmServiceDiscoveryManagerTest : public testing::Test { +public: + static void SetUpTestCase(); + static void TearDownTestCase(); + void SetUp() override; + void TearDown() override; + + std::shared_ptr softbusConnector_ = std::make_shared(); + std::shared_ptr listener_ = std::make_shared(); + std::shared_ptr discoveryManager_ = + std::make_shared(softbusConnector_, listener_); + static inline std::shared_ptr softbusConnectorMock_ = + std::make_shared(); + static inline std::shared_ptr dmServiceDiscoveryManagerMock_ = + std::make_shared(); +}; +} // namespace DistributedHardware +} // namespace OHOS +#endif diff --git a/test/unittest/mock/device_manager_service_impl_mock.cpp b/test/unittest/mock/device_manager_service_impl_mock.cpp index 80ac6e8c6..343516d92 100644 --- a/test/unittest/mock/device_manager_service_impl_mock.cpp +++ b/test/unittest/mock/device_manager_service_impl_mock.cpp @@ -116,5 +116,15 @@ bool DeviceManagerServiceImpl::CheckIsSameAccount(const DmAccessCaller &caller, return DmDeviceManagerServiceImpl::dmDeviceManagerServiceImpl->CheckIsSameAccount(caller, srcUdid, callee, sinkUdid); } + +int32_t DeviceManagerServiceImpl::StartServiceDiscovery(const ServiceInfoProfile& serviceInfoProfile) +{ + return DmDeviceManagerServiceImpl::dmDeviceManagerServiceImpl->StartServiceDiscovery(serviceInfoProfile); +} + +int32_t DeviceManagerServiceImpl::StopServiceDiscovery(const ServiceInfoProfile& serviceInfoProfile) +{ + return DmDeviceManagerServiceImpl::dmDeviceManagerServiceImpl->StopServiceDiscovery(serviceInfoProfile); +} } // namespace DistributedHardware } // namespace OHOS \ No newline at end of file diff --git a/test/unittest/mock/device_manager_service_impl_mock.h b/test/unittest/mock/device_manager_service_impl_mock.h index 2886de7e3..2ac5bba90 100644 --- a/test/unittest/mock/device_manager_service_impl_mock.h +++ b/test/unittest/mock/device_manager_service_impl_mock.h @@ -50,6 +50,8 @@ public: const DmAccessCallee &callee, const std::string &sinkUdid) = 0; virtual bool CheckIsSameAccount(const DmAccessCaller &caller, const std::string &srcUdid, const DmAccessCallee &callee, const std::string &sinkUdid) = 0; + virtual int32_t StartServiceDiscovery(const ServiceInfoProfile& serviceInfoProfile) = 0; + virtual int32_t StopServiceDiscovery(const ServiceInfoProfile& serviceInfoProfile) = 0; public: static inline std::shared_ptr dmDeviceManagerServiceImpl = nullptr; }; @@ -77,6 +79,8 @@ public: const DmAccessCallee &callee, const std::string &sinkUdid)); MOCK_METHOD(bool, CheckIsSameAccount, (const DmAccessCaller &caller, const std::string &srcUdid, const DmAccessCallee &callee, const std::string &sinkUdid)); + MOCK_METHOD(int32_t, StartServiceDiscovery, (const ServiceInfoProfile& serviceInfoProfile)); + MOCK_METHOD(int32_t, StopServiceDiscovery, (const ServiceInfoProfile& serviceInfoProfile)); }; } } diff --git a/test/unittest/mock/dm_service_discovery_manager_mock.cpp b/test/unittest/mock/dm_service_discovery_manager_mock.cpp new file mode 100644 index 000000000..8deb02daf --- /dev/null +++ b/test/unittest/mock/dm_service_discovery_manager_mock.cpp @@ -0,0 +1,33 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "dm_service_discovery_manager_mock.h" + +#include "gtest/gtest.h" + +namespace OHOS { +namespace DistributedHardware { + +int32_t DmServiceDiscoveryManager::CheckDiscoveryMap(const ServiceInfoProfile& serviceInfoProfile) +{ + return DmDmServiceDiscoveryManager::dmServiceDiscoveryManager->CheckDiscoveryMap(serviceInfoProfile); +} + +int32_t DmServiceDiscoveryManager::StopServiceDiscovery(const ServiceInfoProfile& serviceInfoProfile) +{ + return DmDmServiceDiscoveryManager::dmServiceDiscoveryManager->StopServiceDiscovery(serviceInfoProfile); +} +} // namespace DistributedHardware +} // namespace OHOS \ No newline at end of file diff --git a/test/unittest/mock/dm_service_discovery_manager_mock.h b/test/unittest/mock/dm_service_discovery_manager_mock.h new file mode 100644 index 000000000..e0d0f6cfe --- /dev/null +++ b/test/unittest/mock/dm_service_discovery_manager_mock.h @@ -0,0 +1,43 @@ +/* + * Copyright (C) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +#ifndef OHOS_DM_SERVICE_DISCOVERY_MANAGER_MOCK_H +#define OHOS_DM_SERVICE_DISCOVERY_MANAGER_MOCK_H + +#include +#include + +#include "dm_service_discovery_manager.h" + +namespace OHOS { +namespace DistributedHardware { +class DmDmServiceDiscoveryManager { +public: + virtual ~DmDmServiceDiscoveryManager() = default; +public: + virtual int32_t CheckDiscoveryMap(const ServiceInfoProfile& serviceInfoProfile) = 0; + virtual int32_t StopServiceDiscovery(const ServiceInfoProfile& serviceInfoProfile) = 0; + +public: + static inline std::shared_ptr dmServiceDiscoveryManager = nullptr; +}; + +class DmServiceDiscoveryManagerMock : public DmDmServiceDiscoveryManager { +public: + MOCK_METHOD(int32_t, CheckDiscoveryMap, (const ServiceInfoProfile& serviceInfoProfile)); + MOCK_METHOD(int32_t, StopServiceDiscovery, (const ServiceInfoProfile& serviceInfoProfile)); +}; +} +} +#endif diff --git a/test/unittest/mock/softbus_connector_mock.cpp b/test/unittest/mock/softbus_connector_mock.cpp index d49c8c253..27d42e889 100644 --- a/test/unittest/mock/softbus_connector_mock.cpp +++ b/test/unittest/mock/softbus_connector_mock.cpp @@ -59,5 +59,26 @@ int32_t SoftbusConnector::SyncLocalAclListProcess(const DevUserInfo &localDevUse return DmSoftbusConnector::dmSoftbusConnector->SyncLocalAclListProcess(localDevUserInfo, remoteDevUserInfo, remoteAclList); } + +int32_t SoftbusConnector::RegisterServiceDiscoveryCallback(int64_t serviceId, + const std::shared_ptr callback) +{ + return DmSoftbusConnector::dmSoftbusConnector->RegisterServiceDiscoveryCallback(serviceId, callback); +} + +int32_t SoftbusConnector::StartServiceDiscovery(const ServiceInfoProfile& serviceInfoProfile) +{ + return DmSoftbusConnector::dmSoftbusConnector->StartServiceDiscovery(serviceInfoProfile); +} + +int32_t SoftbusConnector::StopServiceDiscovery(const ServiceInfoProfile& serviceInfoProfile) +{ + return DmSoftbusConnector::dmSoftbusConnector->StopServiceDiscovery(serviceInfoProfile); +} + +int32_t SoftbusConnector::UnRegisterServiceDiscoveryCallback(int64_t serviceId) +{ + return DmSoftbusConnector::dmSoftbusConnector->UnRegisterServiceDiscoveryCallback(serviceId); +} } // namespace DistributedHardware } // namespace OHOS \ No newline at end of file diff --git a/test/unittest/mock/softbus_connector_mock.h b/test/unittest/mock/softbus_connector_mock.h index e71d229f6..cc4eb410f 100644 --- a/test/unittest/mock/softbus_connector_mock.h +++ b/test/unittest/mock/softbus_connector_mock.h @@ -35,7 +35,11 @@ public: virtual void SetProcessInfoVec(std::vector processInfoVec) = 0; virtual int32_t SyncLocalAclListProcess(const DevUserInfo &localDevUserInfo, const DevUserInfo &remoteDevUserInfo, std::string remoteAclList) = 0; - + virtual int32_t RegisterServiceDiscoveryCallback(int64_t serviceId, + const std::shared_ptr callback) = 0; + virtual int32_t StartServiceDiscovery(const ServiceInfoProfile& serviceInfoProfile) = 0; + virtual int32_t StopServiceDiscovery(const ServiceInfoProfile& serviceInfoProfile) = 0; + virtual int32_t UnRegisterServiceDiscoveryCallback(int64_t serviceId) = 0; public: static inline std::shared_ptr dmSoftbusConnector = nullptr; }; @@ -50,6 +54,11 @@ public: MOCK_METHOD(void, SetProcessInfo, (ProcessInfo processInfo)); MOCK_METHOD(void, SetProcessInfoVec, (std::vector processInfoVec)); MOCK_METHOD(int32_t, SyncLocalAclListProcess, (const DevUserInfo &, const DevUserInfo &, std::string)); + MOCK_METHOD(int32_t, RegisterServiceDiscoveryCallback, (int64_t serviceId, + const std::shared_ptr callback)); + MOCK_METHOD(int32_t, StartServiceDiscovery, (const ServiceInfoProfile& serviceInfoProfile)); + MOCK_METHOD(int32_t, StopServiceDiscovery, (const ServiceInfoProfile& serviceInfoProfile)); + MOCK_METHOD(int32_t, UnRegisterServiceDiscoveryCallback, (int64_t serviceId)); }; } } -- Gitee