From 4a856b714736437a1a466a0e3596cec42825000f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E8=94=A1=E9=98=94?= Date: Tue, 8 Mar 2022 09:06:05 +0000 Subject: [PATCH 01/19] =?UTF-8?q?!25=20DM=E4=BB=A3=E7=A0=81=E6=96=B0?= =?UTF-8?q?=E6=A1=86=E6=9E=B6=E5=8A=9F=E8=83=BD=E4=BF=AE=E6=94=B9=E5=90=88?= =?UTF-8?q?=E5=85=A5=20*=20=E4=BF=AE=E6=94=B9DM=E6=A8=A1=E5=9D=97=E6=96=B0?= =?UTF-8?q?=E6=A1=86=E6=9E=B6=E4=B8=8B=E6=A0=B8=E5=BF=83=E7=9B=AE=E5=BD=95?= =?UTF-8?q?=E4=BE=A7=E4=BB=A3=E7=A0=81?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../inner_kits/native_cpp/BUILD.gn | 162 ++++++ .../native_cpp/include/device_manager.h | 60 +++ .../include/device_manager_callback.h | 81 +++ .../native_cpp/include/device_manager_impl.h | 74 +++ .../native_cpp/include/dm_app_image_info.h | 183 +++++++ .../native_cpp/include/dm_device_info.h | 68 +++ .../native_cpp/include/dm_subscribe_info.h | 79 +++ .../include/notify/device_manager_notify.h | 81 +++ .../native_cpp/src/device_manager.cpp | 27 + .../native_cpp/src/device_manager_impl.cpp | 472 ++++++++++++++++++ .../src/notify/device_manager_notify.cpp | 295 +++++++++++ .../include/device_manager_service.h | 30 +- .../include/device_manager_service_listener.h | 7 +- .../dispatch/authenticate_device_req.h | 120 +++++ .../include/dispatch/command_dispatch.h | 40 ++ .../dispatch/get_authenticationparam_rsp.h | 41 ++ .../include/dispatch/get_dmfaparam_rsp.h | 43 ++ .../dispatch/get_info_by_network_req.h | 42 ++ .../dispatch/get_info_by_network_rsp.h | 54 ++ .../dispatch/get_local_device_info_rsp.h | 43 ++ .../include/dispatch/get_trustdevice_req.h | 63 +++ .../include/dispatch/get_trustdevice_rsp.h | 44 ++ .../include/dispatch/message_def.h | 60 +++ .../include/dispatch/message_processing.h | 49 ++ .../include/dispatch/message_req.h | 62 +++ .../include/dispatch/message_rsp.h | 42 ++ .../include/dispatch/server_init.h | 22 + .../include/dispatch/server_stub.h | 24 + .../include/dispatch/set_useroperation_req.h | 41 ++ .../include/dispatch/start_discovery_req.h | 86 ++++ .../include/dispatch/stop_discovery_req.h | 42 ++ .../dispatch/unauthenticate_device_req.h | 43 ++ .../dispatch/verify_authenticate_req.h | 62 +++ .../src/device_manager_service.cpp | 245 ++++----- .../src/dispatch/command_dispatch.cpp | 215 ++++++++ .../device_manager_service_listener_mini.cpp | 98 ++++ .../src/dispatch/message_processing.cpp | 244 +++++++++ .../src/dispatch/server_init.cpp | 46 ++ .../src/dispatch/server_stub.cpp | 119 +++++ .../src/dispatch/server_stub_bak.cpp | 114 +++++ 40 files changed, 3589 insertions(+), 134 deletions(-) create mode 100644 interfaces_mini/inner_kits/native_cpp/BUILD.gn create mode 100644 interfaces_mini/inner_kits/native_cpp/include/device_manager.h create mode 100644 interfaces_mini/inner_kits/native_cpp/include/device_manager_callback.h create mode 100644 interfaces_mini/inner_kits/native_cpp/include/device_manager_impl.h create mode 100644 interfaces_mini/inner_kits/native_cpp/include/dm_app_image_info.h create mode 100644 interfaces_mini/inner_kits/native_cpp/include/dm_device_info.h create mode 100644 interfaces_mini/inner_kits/native_cpp/include/dm_subscribe_info.h create mode 100644 interfaces_mini/inner_kits/native_cpp/include/notify/device_manager_notify.h create mode 100644 interfaces_mini/inner_kits/native_cpp/src/device_manager.cpp create mode 100644 interfaces_mini/inner_kits/native_cpp/src/device_manager_impl.cpp create mode 100644 interfaces_mini/inner_kits/native_cpp/src/notify/device_manager_notify.cpp create mode 100644 services/devicemanagerservice/include/dispatch/authenticate_device_req.h create mode 100644 services/devicemanagerservice/include/dispatch/command_dispatch.h create mode 100644 services/devicemanagerservice/include/dispatch/get_authenticationparam_rsp.h create mode 100644 services/devicemanagerservice/include/dispatch/get_dmfaparam_rsp.h create mode 100644 services/devicemanagerservice/include/dispatch/get_info_by_network_req.h create mode 100644 services/devicemanagerservice/include/dispatch/get_info_by_network_rsp.h create mode 100644 services/devicemanagerservice/include/dispatch/get_local_device_info_rsp.h create mode 100644 services/devicemanagerservice/include/dispatch/get_trustdevice_req.h create mode 100644 services/devicemanagerservice/include/dispatch/get_trustdevice_rsp.h create mode 100644 services/devicemanagerservice/include/dispatch/message_def.h create mode 100644 services/devicemanagerservice/include/dispatch/message_processing.h create mode 100644 services/devicemanagerservice/include/dispatch/message_req.h create mode 100644 services/devicemanagerservice/include/dispatch/message_rsp.h create mode 100644 services/devicemanagerservice/include/dispatch/server_init.h create mode 100644 services/devicemanagerservice/include/dispatch/server_stub.h create mode 100644 services/devicemanagerservice/include/dispatch/set_useroperation_req.h create mode 100644 services/devicemanagerservice/include/dispatch/start_discovery_req.h create mode 100644 services/devicemanagerservice/include/dispatch/stop_discovery_req.h create mode 100644 services/devicemanagerservice/include/dispatch/unauthenticate_device_req.h create mode 100644 services/devicemanagerservice/include/dispatch/verify_authenticate_req.h create mode 100644 services/devicemanagerservice/src/dispatch/command_dispatch.cpp create mode 100644 services/devicemanagerservice/src/dispatch/device_manager_service_listener_mini.cpp create mode 100644 services/devicemanagerservice/src/dispatch/message_processing.cpp create mode 100644 services/devicemanagerservice/src/dispatch/server_init.cpp create mode 100644 services/devicemanagerservice/src/dispatch/server_stub.cpp create mode 100644 services/devicemanagerservice/src/dispatch/server_stub_bak.cpp diff --git a/interfaces_mini/inner_kits/native_cpp/BUILD.gn b/interfaces_mini/inner_kits/native_cpp/BUILD.gn new file mode 100644 index 000000000..fbb4f13b7 --- /dev/null +++ b/interfaces_mini/inner_kits/native_cpp/BUILD.gn @@ -0,0 +1,162 @@ +# Copyright (C) 2021 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +if (defined(ohos_lite)) { + import("//build/lite/config/component/lite_component.gni") +} else { + import("//build/ohos.gni") +} +import("//foundation/distributedhardware/devicemanager/devicemanager.gni") + +if (defined(ohos_lite)) { + if (ohos_kernel_type == "liteos_m") { + static_library("devicemanagersdk_mini") { + include_dirs = [ + "include", + "include/notify", + "${utils_path}/include/log", + "${common_path}/include", + "//foundation/distributedhardware/devicemanager/services/devicemanagerservice/include/dispatch", + ] + include_dirs += [ + "//utils/native/lite/include", + "//base/hiviewdfx/hilog_lite/interfaces/native/innerkits/hilog", + "//third_party/bounds_checking_function/include", + "//foundation/distributedschedule/samgr_lite/interfaces/kits/samgr", + "//third_party/json/include", + ] + + sources = [ + "src/device_manager.cpp", + "src/device_manager_impl.cpp", + "src/notify/device_manager_notify.cpp", + ] + + defines = [ + "LITE_DEVICE", + "HI_LOG_ENABLE", + "DH_LOG_TAG=\"devicemanagerkit\"", + "LOG_DOMAIN=0xD004100", + ] + + deps = [ + "${utils_path}:devicemanagerutils_mini", + "//base/hiviewdfx/hilog_lite/frameworks/featured:hilog_static", + "//foundation/distributedschedule/samgr_lite/samgr", + "//third_party/bounds_checking_function:libsec_static", + "//utils/native/lite:utils", + ] + } + } else { + shared_library("devicemanagersdk") { + include_dirs = [ + "include", + "include/ipc", + "include/ipc/lite", + "include/notify", + "${utils_path}/include/log", + "${utils_path}/include/ipc/lite", + "${common_path}/include/ipc", + "${common_path}/include/ipc/model", + "${common_path}/include", + ] + include_dirs += [ + "//utils/native/lite/include", + "//base/hiviewdfx/hilog_lite/interfaces/native/innerkits/hilog", + "//third_party/bounds_checking_function/include", + "//foundation/communication/ipc_lite/interfaces/kits", + "//foundation/distributedschedule/samgr_lite/interfaces/kits/samgr", + "//third_party/json/include", + ] + + sources = [ + "src/device_manager.cpp", + "src/device_manager_impl.cpp", + "src/ipc/ipc_client_proxy.cpp", + "src/ipc/lite/ipc_client_manager.cpp", + "src/ipc/lite/ipc_client_server_proxy.cpp", + "src/ipc/lite/ipc_client_stub.cpp", + "src/ipc/lite/ipc_cmd_parser.cpp", + "src/notify/device_manager_notify.cpp", + ] + + defines = [ + "LITE_DEVICE", + "HI_LOG_ENABLE", + "DH_LOG_TAG=\"devicemanagerkit\"", + "LOG_DOMAIN=0xD004100", + ] + + deps = [ + "${utils_path}:devicemanagerutils", + "//base/hiviewdfx/hilog_lite/frameworks/featured:hilog_shared", + "//foundation/communication/ipc_lite:liteipc_adapter", + "//foundation/distributedschedule/samgr_lite/samgr:samgr", + "//third_party/bounds_checking_function:libsec_shared", + "//utils/native/lite:utils", + ] + } + } +} else { + ohos_shared_library("devicemanagersdk") { + include_dirs = [ + "//utils/native/base/include", + "//utils/system/safwk/native/include", + "include", + "include/ipc/standard", + "include/ipc", + "include/notify", + "${utils_path}/include/log", + "${common_path}/include/ipc", + "${common_path}/include/ipc/model", + "${utils_path}/include/ipc/standard", + "${common_path}/include", + "//third_party/json/include", + ] + + sources = [ + "src/device_manager.cpp", + "src/device_manager_impl.cpp", + "src/ipc/ipc_client_proxy.cpp", + "src/ipc/standard/ipc_client_manager.cpp", + "src/ipc/standard/ipc_client_server_proxy.cpp", + "src/ipc/standard/ipc_client_stub.cpp", + "src/ipc/standard/ipc_cmd_parser.cpp", + "src/notify/device_manager_notify.cpp", + ] + + deps = [ + "${utils_path}:devicemanagerutils", + "//utils/native/base:utils", + ] + + defines = [ + "HI_LOG_ENABLE", + "DH_LOG_TAG=\"devicemanagerkit\"", + "LOG_DOMAIN=0xD004100", + ] + + external_deps = [ + "appexecfwk_standard:appexecfwk_base", + "appexecfwk_standard:appexecfwk_core", + "hiviewdfx_hilog_native:libhilog", + "ipc:ipc_core", + "safwk:system_ability_fwk", + "samgr_standard:samgr_proxy", + ] + + subsystem_name = "distributedhardware" + + part_name = "device_manager_base" + } +} diff --git a/interfaces_mini/inner_kits/native_cpp/include/device_manager.h b/interfaces_mini/inner_kits/native_cpp/include/device_manager.h new file mode 100644 index 000000000..10944ccd9 --- /dev/null +++ b/interfaces_mini/inner_kits/native_cpp/include/device_manager.h @@ -0,0 +1,60 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef DEVICE_MANAGER_H +#define DEVICE_MANAGER_H + +#include +#include +#include + +#include "device_manager_callback.h" +#include "dm_subscribe_info.h" +#include "dm_app_image_info.h" + +namespace OHOS { +namespace DistributedHardware { +class DeviceManager { +public: + static DeviceManager &GetInstance(); +public: + virtual int32_t InitDeviceManager(const std::string &pkgName, std::shared_ptr dmInitCallback) = 0; + virtual int32_t UnInitDeviceManager(const std::string &pkgName) = 0; + virtual int32_t GetTrustedDeviceList(const std::string &pkgName, const std::string &extra, + std::vector &deviceList) = 0; + virtual int32_t GetLocalDeviceInfo(const std::string &pkgName, DmDeviceInfo &deviceInfo) = 0; + virtual int32_t RegisterDevStateCallback(const std::string &pkgName, const std::string &extra, + std::shared_ptr callback) = 0; + virtual int32_t UnRegisterDevStateCallback(const std::string &pkgName) = 0; + virtual int32_t StartDeviceDiscovery(const std::string &pkgName, const DmSubscribeInfo &subscribeInfo, + const std::string &extra, std::shared_ptr callback) = 0; + virtual int32_t StopDeviceDiscovery(const std::string &pkgName, uint16_t subscribeId) = 0; + virtual int32_t AuthenticateDevice(const std::string &pkgName, int32_t authType, const DmDeviceInfo &deviceInfo, + const std::string &extra, std::shared_ptr callback) = 0; + virtual int32_t UnAuthenticateDevice(const std::string &pkgName, const std::string &deviceId) = 0; + virtual int32_t VerifyAuthentication(const std::string &pkgName, const std::string &authPara, + std::shared_ptr callback) = 0; + // virtual int32_t GetAuthenticationParam(std::string &pkgName, DmAuthParam &authParam) = 0; + virtual int32_t RegisterDeviceManagerFaCallback(const std::string &pkgName, + std::shared_ptr callback) = 0; + virtual int32_t UnRegisterDeviceManagerFaCallback(const std::string &pkgName) = 0; + virtual int32_t GetFaParam(const std::string &pkgName, DmAuthParam &faParam) = 0; + virtual int32_t SetUserOperation(const std::string &pkgName, int32_t action) = 0; + virtual int32_t GetUdidByNetworkId(const std::string &pkgName, const std::string &netWorkId, std::string &udid) = 0; + virtual int32_t GetUuidByNetworkId(const std::string &pkgName, const std::string &netWorkId, std::string &uuid) = 0; +}; +} // namespace DistributedHardware +} // namespace OHOS +#endif // OHOS_DEVICE_MANAGER_H diff --git a/interfaces_mini/inner_kits/native_cpp/include/device_manager_callback.h b/interfaces_mini/inner_kits/native_cpp/include/device_manager_callback.h new file mode 100644 index 000000000..74bcc5985 --- /dev/null +++ b/interfaces_mini/inner_kits/native_cpp/include/device_manager_callback.h @@ -0,0 +1,81 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef OHOS_DEVICE_MANAGER_CALLBACK_H +#define OHOS_DEVICE_MANAGER_CALLBACK_H + +#include +#include + +#include "dm_device_info.h" + +namespace OHOS { +namespace DistributedHardware { +class DmInitCallback { +public: + virtual ~DmInitCallback() + { + } + virtual void OnRemoteDied() = 0; +}; + +class DeviceStateCallback { +public: + virtual ~DeviceStateCallback() + { + } + virtual void OnDeviceOnline(const DmDeviceInfo &deviceInfo) = 0; + virtual void OnDeviceReady(const DmDeviceInfo &deviceInfo) = 0; + virtual void OnDeviceOffline(const DmDeviceInfo &deviceInfo) = 0; + virtual void OnDeviceChanged(const DmDeviceInfo &deviceInfo) = 0; +}; + +class DiscoveryCallback { +public: + virtual ~DiscoveryCallback() + { + } + virtual void OnDiscoverySuccess(uint16_t subscribeId) = 0; + virtual void OnDiscoveryFailed(uint16_t subscribeId, int32_t failedReason) = 0; + virtual void OnDeviceFound(uint16_t subscribeId, const DmDeviceInfo &deviceInfo) = 0; +}; + +class AuthenticateCallback { +public: + virtual ~AuthenticateCallback() + { + } + virtual void OnAuthResult(const std::string &deviceId, const std::string &token, int32_t status, + int32_t reason) = 0; +}; + +class VerifyAuthCallback { +public: + virtual ~VerifyAuthCallback() + { + } + virtual void OnVerifyAuthResult(const std::string &deviceId, int32_t resultCode, const std::string flag) = 0; +}; + +class DeviceManagerFaCallback { +public: + virtual ~DeviceManagerFaCallback() + { + } + virtual void OnCall(const std::string ¶mJson) = 0; +}; +} // namespace DistributedHardware +} // namespace OHOS +#endif // OHOS_DEVICE_MANAGER_CALLBACK_H diff --git a/interfaces_mini/inner_kits/native_cpp/include/device_manager_impl.h b/interfaces_mini/inner_kits/native_cpp/include/device_manager_impl.h new file mode 100644 index 000000000..490fdb0f2 --- /dev/null +++ b/interfaces_mini/inner_kits/native_cpp/include/device_manager_impl.h @@ -0,0 +1,74 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef OHOS_DEVICE_MANAGER_IMPL_H +#define OHOS_DEVICE_MANAGER_IMPL_H + +#include +#include +#include "device_manager.h" +#include "single_instance.h" + + +namespace OHOS { +namespace DistributedHardware { +class DeviceManagerImpl : public DeviceManager { +#define DEVICEMANAGER_MESSAGE_FAILED -1 +DECLARE_SINGLE_INSTANCE(DeviceManagerImpl); +//public: +// static DeviceManagerImpl &GetInstance(); + +public: + virtual int32_t InitDeviceManager(const std::string &pkgName, + std::shared_ptr dmInitCallback) override; + virtual int32_t UnInitDeviceManager(const std::string &pkgName) override; + virtual int32_t GetTrustedDeviceList(const std::string &pkgName, const std::string &extra, + std::vector &deviceList) override; + virtual int32_t GetLocalDeviceInfo(const std::string &pkgName, DmDeviceInfo &deviceInfo) override; + virtual int32_t RegisterDevStateCallback(const std::string &pkgName, const std::string &extra, + std::shared_ptr callback) override; + virtual int32_t UnRegisterDevStateCallback(const std::string &pkgName) override; + + virtual int32_t StartDeviceDiscovery(const std::string &pkgName, const DmSubscribeInfo &subscribeInfo, + const std::string &extra, + std::shared_ptr callback) override; + virtual int32_t StopDeviceDiscovery(const std::string &pkgName, uint16_t subscribeId) override; + virtual int32_t AuthenticateDevice(const std::string &pkgName, int32_t authType, const DmDeviceInfo &deviceInfo, + const std::string &extra, + std::shared_ptr callback) override; + virtual int32_t UnAuthenticateDevice(const std::string &pkgName, const std::string &deviceId) override; + virtual int32_t VerifyAuthentication(const std::string &pkgName, const std::string &authPara, + std::shared_ptr callback) override; + // virtual int32_t GetAuthenticationParam(std::string &pkgName, DmAuthParam &authParam) override; + virtual int32_t RegisterDeviceManagerFaCallback(const std::string &pkgName, + std::shared_ptr callback) override; + virtual int32_t UnRegisterDeviceManagerFaCallback(const std::string &pkgName) override; + virtual int32_t GetFaParam(const std::string &pkgName, DmAuthParam &faParam) override; + virtual int32_t SetUserOperation(const std::string &pkgName, int32_t action) override; + virtual int32_t GetUdidByNetworkId(const std::string &pkgName, const std::string &netWorkId, + std::string &udid) override; + virtual int32_t GetUuidByNetworkId(const std::string &pkgName, const std::string &netWorkId, + std::string &uuid) override; +//private: +// DeviceManagerImpl() = default; +// ~DeviceManagerImpl() = default; +// DeviceManagerImpl(const DeviceManagerImpl &) = delete; +// DeviceManagerImpl &operator=(const DeviceManagerImpl &) = delete; +// DeviceManagerImpl(DeviceManagerImpl &&) = delete; +// DeviceManagerImpl &operator=(DeviceManagerImpl &&) = delete; +}; +} // namespace DistributedHardware +} // namespace OHOS +#endif // OHOS_DEVICE_MANAGER_IMPL_H diff --git a/interfaces_mini/inner_kits/native_cpp/include/dm_app_image_info.h b/interfaces_mini/inner_kits/native_cpp/include/dm_app_image_info.h new file mode 100644 index 000000000..9fbccd7d6 --- /dev/null +++ b/interfaces_mini/inner_kits/native_cpp/include/dm_app_image_info.h @@ -0,0 +1,183 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef OHOS_DEVICE_MANAGER_APP_IMAGE_INFO_H +#define OHOS_DEVICE_MANAGER_APP_IMAGE_INFO_H + +#include + +#include "securec.h" + +namespace OHOS { +namespace DistributedHardware { +class DmAppImageInfo { +public: + DmAppImageInfo() = default; + explicit DmAppImageInfo(uint8_t *appIcon_, int32_t appIconLen_, uint8_t *appThumbnail_, int32_t appThumbnailLen_) + { + SaveData(appIcon_, appIconLen_, appThumbnail_, appThumbnailLen_); + } + + void Reset(uint8_t *appIcon_, int32_t appIconLen_, uint8_t *appThumbnail_, int32_t appThumbnailLen_) + { + SaveData(appIcon_, appIconLen_, appThumbnail_, appThumbnailLen_); + } + + void ResetIcon(uint8_t *appIcon_, int32_t appIconLen_) + { + SaveIconData(appIcon_, appIconLen_); + } + + void InitThumbnail(int32_t appThumbnailLen_) + { + if (appThumbnailLen_ <= 0 || appThumbnailLen_ > THUMB_MAX_LEN) { + appThumbnailLen = 0; + appThumbnail = nullptr; + return; + } + + appThumbnail = new (std::nothrow) uint8_t[appThumbnailLen_] {0}; + if (appThumbnail != nullptr) { + appThumbnailLen = appThumbnailLen_; + } + } + + int32_t SetThumbnailData(uint8_t *srcBuffer, int32_t srcBufferLen, int32_t copyIndex, int32_t copyLen) + { + if (srcBuffer == nullptr || srcBufferLen <= 0 || copyLen > srcBufferLen || copyIndex < 0) { + return -1; + } + + if ((copyIndex + copyLen) > appThumbnailLen) { + return -1; + } + + if (appThumbnail == nullptr) { + return -1; + } + + if (memcpy_s(appThumbnail + copyIndex, appThumbnailLen - copyIndex, srcBuffer, copyLen) != 0) { + return -1; + } + + return 0; + } + + ~DmAppImageInfo() + { + if (appIcon != nullptr) { + delete[] appIcon; + appIcon = nullptr; + } + if (appThumbnail != nullptr) { + delete[] appThumbnail; + appThumbnail = nullptr; + } + } + + DmAppImageInfo(const DmAppImageInfo &other) + { + if (this != &other) { + *this = other; + } + } + + DmAppImageInfo& operator=(const DmAppImageInfo &other) + { + if (this != &other) { + SaveData(other.GetAppIcon(), other.GetAppIconLen(), other.GetAppThumbnail(), other.GetAppThumbnailLen()); + } + return *this; + } + + DmAppImageInfo(DmAppImageInfo&&) = delete; + DmAppImageInfo& operator=(DmAppImageInfo&&) = delete; + + int32_t GetAppIconLen() const + { + return appIconLen; + } + + const uint8_t *GetAppIcon() const + { + return appIcon; + } + + int32_t GetAppThumbnailLen() const + { + return appThumbnailLen; + } + + const uint8_t *GetAppThumbnail() const + { + return appThumbnail; + } +private: + void SaveData(const uint8_t *appIcon_, int32_t appIconLen_, const uint8_t *appThumbnail_, int32_t appThumbnailLen_) + { + SaveIconData(appIcon_, appIconLen_); + SaveThumbnailData(appThumbnail_, appThumbnailLen_); + } + + void SaveIconData(const uint8_t *appIcon_, int32_t appIconLen_) + { + if (appIconLen_ > 0 && appIconLen_ < ICON_MAX_LEN && appIcon_ != nullptr) { + if (appIconLen < appIconLen_) { + if (appIcon != nullptr && appIconLen > 0) { + delete[] appIcon; + appIcon = nullptr; + appIconLen = 0; + } + appIcon = new (std::nothrow) uint8_t[appIconLen_] {0}; + } + if (appIcon != nullptr) { + appIconLen = appIconLen_; + if (memcpy_s(appIcon, appIconLen, appIcon_, appIconLen_) != 0) { + return; + } + } + } + } + + void SaveThumbnailData(const uint8_t *appThumbnail_, int32_t appThumbnailLen_) + { + if (appThumbnailLen_ > 0 && appThumbnailLen_ < THUMB_MAX_LEN && appThumbnail_ != nullptr) { + if (appThumbnailLen < appThumbnailLen_) { + if (appThumbnail != nullptr && appThumbnailLen > 0) { + delete[] appThumbnail; + appThumbnail = nullptr; + appThumbnailLen = 0; + } + appThumbnail = new (std::nothrow) uint8_t[appThumbnailLen_] {0}; + } + if (appThumbnail != nullptr) { + appThumbnailLen = appThumbnailLen_; + if (memcpy_s(appThumbnail, appThumbnailLen, appThumbnail_, appThumbnailLen_) != 0) { + return; + } + } + } + } +private: + int32_t appIconLen {0}; + uint8_t *appIcon {nullptr}; + int32_t appThumbnailLen {0}; + uint8_t *appThumbnail {nullptr}; + const int32_t ICON_MAX_LEN = 32 * 1024; + const int32_t THUMB_MAX_LEN = 153 * 1024; +}; +} // namespace DistributedHardware +} // namespace OHOS +#endif // OHOS_DEVICE_MANAGER_APP_IMAGE_INFO_H diff --git a/interfaces_mini/inner_kits/native_cpp/include/dm_device_info.h b/interfaces_mini/inner_kits/native_cpp/include/dm_device_info.h new file mode 100644 index 000000000..57e942870 --- /dev/null +++ b/interfaces_mini/inner_kits/native_cpp/include/dm_device_info.h @@ -0,0 +1,68 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef OHOS_DEVICE_MANAGER_DEVICE_INFO_H +#define OHOS_DEVICE_MANAGER_DEVICE_INFO_H + +#include + +#include "dm_app_image_info.h" + +#define DM_MAX_DEVICE_ID_LEN (96) +#define DM_MAX_DEVICE_NAME_LEN (128) + +namespace OHOS { +namespace DistributedHardware { +typedef enum DmDeviceType { + DEVICE_TYPE_UNKNOWN = 0x00, + DEVICE_TYPE_WIFI_CAMERA = 0x08, + DEVICE_TYPE_AUDIO = 0x0A, + DEVICE_TYPE_PC = 0x0C, + DEVICE_TYPE_PHONE = 0x0E, + DEVICE_TYPE_PAD = 0x11, + DEVICE_TYPE_WATCH = 0x6D, + DEVICE_TYPE_CAR = 0x83, + DEVICE_TYPE_TV = 0x9C, +} DmDeviceType; + +typedef enum DmDeviceState { + DEVICE_STATE_UNKNOWN = -1, + DEVICE_STATE_ONLINE = 0, + DEVICE_INFO_READY = 1, + DEVICE_STATE_OFFLINE = 2, + DEVICE_INFO_CHANGED = 3, +} DmDeviceState; + +typedef struct DmDeviceInfo { + char deviceId[DM_MAX_DEVICE_ID_LEN]; + char deviceName[DM_MAX_DEVICE_NAME_LEN]; + uint16_t deviceTypeId; +} DmDeviceInfo; + +typedef struct DmAuthParam { + std::string authToken; + std::string packageName; + std::string appName; + std::string appDescription; + int32_t authType; + int32_t business; + int32_t pincode; + int32_t direction; + int32_t pinToken; + DmAppImageInfo imageinfo; +} DmAuthParam; +} // namespace DistributedHardware +} // namespace OHOS +#endif // OHOS_DEVICE_MANAGER_DEVICE_INFO_H diff --git a/interfaces_mini/inner_kits/native_cpp/include/dm_subscribe_info.h b/interfaces_mini/inner_kits/native_cpp/include/dm_subscribe_info.h new file mode 100644 index 000000000..91e12f88f --- /dev/null +++ b/interfaces_mini/inner_kits/native_cpp/include/dm_subscribe_info.h @@ -0,0 +1,79 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef OHOS_DEVICE_MANAGER_SUBSCRIBE_INFO_H +#define OHOS_DEVICE_MANAGER_SUBSCRIBE_INFO_H + +#include + +#define DM_MAX_DEVICE_CAPABILITY_LEN 65 + +namespace OHOS { +namespace DistributedHardware { +typedef enum DmDiscoverMode { + /* Passive */ + DM_DISCOVER_MODE_PASSIVE = 0x55, + /* Proactive */ + DM_DISCOVER_MODE_ACTIVE = 0xAA +} DmDiscoverMode; + +typedef enum DmExchangeMedium { + /** Automatic medium selection */ + DM_AUTO = 0, + /** Bluetooth */ + DM_BLE = 1, + /** Wi-Fi */ + DM_COAP = 2, + /** USB */ + DM_USB = 3, + DM_MEDIUM_BUTT +} DmExchangeMedium; + +/** + * @brief Enumerates frequencies for publishing services. + * + * This enumeration applies only to Bluetooth and is not supported currently. + */ +typedef enum DmExchangeFreq { + /** Low */ + DM_LOW = 0, + /** Medium */ + DM_MID = 1, + /** High */ + DM_HIGH = 2, + /** Super-high */ + DM_SUPER_HIGH = 3, + DM_FREQ_BUTT +} DmExchangeFreq; + +typedef struct DmSubscribeInfo { + /** Service ID */ + uint16_t subscribeId; + /** Discovery mode for service subscription. For details, see {@link DmDiscoverMode}. */ + DmDiscoverMode mode; + /** Service subscription medium. For details, see {@link DmExchangeMedium}. */ + DmExchangeMedium medium; + /** Service subscription frequency. For details, see {@link DmExchangeFreq}. */ + DmExchangeFreq freq; + /** only find the device with the same account */ + bool isSameAccount; + /** find the sleeping devices */ + bool isWakeRemote; + /** Service subscription capability. */ + char capability[DM_MAX_DEVICE_CAPABILITY_LEN]; +} DmSubscribeInfo; +} // namespace DistributedHardware +} // namespace OHOS +#endif // OHOS_DEVICE_MANAGER_SUBSCRIBE_INFO_H diff --git a/interfaces_mini/inner_kits/native_cpp/include/notify/device_manager_notify.h b/interfaces_mini/inner_kits/native_cpp/include/notify/device_manager_notify.h new file mode 100644 index 000000000..5379a14a5 --- /dev/null +++ b/interfaces_mini/inner_kits/native_cpp/include/notify/device_manager_notify.h @@ -0,0 +1,81 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef OHOS_DEVICE_MANAGER_NOTIFY_H +#define OHOS_DEVICE_MANAGER_NOTIFY_H + +#include +#include +#include +#include +#include +#include + +#include "dm_device_info.h" +#include "dm_subscribe_info.h" +#include "device_manager_callback.h" +#include "single_instance.h" + +namespace OHOS { +namespace DistributedHardware { +class DeviceManagerNotify { +DECLARE_SINGLE_INSTANCE(DeviceManagerNotify); +public: + void RegisterDeathRecipientCallback(const std::string &pkgName, std::shared_ptr dmInitCallback); + void UnRegisterDeathRecipientCallback(const std::string &pkgName); + void RegisterDeviceStateCallback(const std::string &pkgName, std::shared_ptr callback); + void UnRegisterDeviceStateCallback(const std::string &pkgName); + void RegisterDiscoveryCallback(const std::string &pkgName, uint16_t subscribeId, + std::shared_ptr callback); + void UnRegisterDiscoveryCallback(const std::string &pkgName, uint16_t subscribeId); + void RegisterAuthenticateCallback(const std::string &pkgName, const std::string &deviceId, + std::shared_ptr callback); + void UnRegisterAuthenticateCallback(const std::string &pkgName, const std::string &deviceId); + void UnRegisterPackageCallback(const std::string &pkgName); + void RegisterVerifyAuthenticationCallback(const std::string &pkgName, const std::string &authPara, + std::shared_ptr callback); + void UnRegisterVerifyAuthenticationCallback(const std::string &pkgName); + void RegisterDeviceManagerFaCallback(const std::string &pkgName, std::shared_ptr callback); + void UnRegisterDeviceManagerFaCallback(const std::string &pkgName); + +public: + void OnRemoteDied(); + void OnDeviceOnline(const std::string &pkgName, const DmDeviceInfo &deviceInfo); + void OnDeviceOffline(const std::string &pkgName, const DmDeviceInfo &deviceInfo); + void OnDeviceChanged(const std::string &pkgName, const DmDeviceInfo &deviceInfo); + void OnDeviceReady(const std::string &pkgName, const DmDeviceInfo &deviceInfo); + void OnDeviceFound(const std::string &pkgName, uint16_t subscribeId, const DmDeviceInfo &deviceInfo); + void OnDiscoveryFailed(const std::string &pkgName, uint16_t subscribeId, int32_t failedReason); + void OnDiscoverySuccess(const std::string &pkgName, uint16_t subscribeId); + void OnAuthResult(const std::string &pkgName, const std::string &deviceId, const std::string &token, + uint32_t status, uint32_t reason); + void OnVerifyAuthResult(const std::string &pkgName, const std::string &deviceId, int32_t resultCode, const std::string flag); + void OnFaCall(std::string &pkgName, std::string ¶mJson); + void AddPkgName(const std::string &pkgName); + void DeletePkgName(const std::string &pkgName); + const std::list& GetPkgNameList() const; +private: +// std::mutex lock_; + std::map> deviceStateCallback_; + std::map>> deviceDiscoveryCallbacks_; + std::map>> authenticateCallback_; + std::map> verifyAuthCallback_; + std::map> dmInitCallback_; + std::map> dmFaCallback_; + std::list dmPkgName_; +}; +} // namespace DistributedHardware +} // namespace OHOS +#endif // OHOS_DEVICE_MANAGER_NOTIFY_H diff --git a/interfaces_mini/inner_kits/native_cpp/src/device_manager.cpp b/interfaces_mini/inner_kits/native_cpp/src/device_manager.cpp new file mode 100644 index 000000000..e9a3b456d --- /dev/null +++ b/interfaces_mini/inner_kits/native_cpp/src/device_manager.cpp @@ -0,0 +1,27 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "device_manager.h" + +#include "device_manager_impl.h" + +namespace OHOS { +namespace DistributedHardware { +DeviceManager &DeviceManager::GetInstance() +{ + return DeviceManagerImpl::GetInstance(); +} +} // namespace DistributedHardware +} // namespace OHOS diff --git a/interfaces_mini/inner_kits/native_cpp/src/device_manager_impl.cpp b/interfaces_mini/inner_kits/native_cpp/src/device_manager_impl.cpp new file mode 100644 index 000000000..694abca6e --- /dev/null +++ b/interfaces_mini/inner_kits/native_cpp/src/device_manager_impl.cpp @@ -0,0 +1,472 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +#include "command_dispatch.h" +#include "device_manager_impl.h" +#include "message_processing.h" +// #include "device_manager_errno.h" +// #include "device_manager_log.h" +#include "dm_log.h" +#include "device_manager_notify.h" +// #include "constants.h" +#include "dm_constants.h" +#include "message_def.h" +#include "get_trustdevice_req.h" +#include "get_trustdevice_rsp.h" +#include "start_discovery_req.h" +#include "stop_discovery_req.h" +#include "set_useroperation_req.h" +#include "get_authenticationparam_rsp.h" +#include "authenticate_device_req.h" +#include "verify_authenticate_req.h" + +#include "get_local_device_info_rsp.h" +#include "get_info_by_network_rsp.h" +#include "get_info_by_network_req.h" +#include "unauthenticate_device_req.h" +#include "get_dmfaparam_rsp.h" + + +namespace OHOS { +namespace DistributedHardware { +IMPLEMENT_SINGLE_INSTANCE(DeviceManagerImpl); + + + +//DeviceManagerImpl &DeviceManagerImpl::GetInstance() +//{ +// static DeviceManagerImpl instance; +// return instance; +//} +int32_t DeviceManagerImpl::InitDeviceManager(const std::string &pkgName, std::shared_ptr dmInitCallback) +{ + LOGI("DeviceManager::InitDeviceManager start, pkgName: %s", pkgName.c_str()); + if (pkgName.empty() || dmInitCallback == nullptr) { + LOGE("InitDeviceManager error: Invalid parameter"); + return DM_INVALID_VALUE; + } + + DeviceManagerNotify::GetInstance().AddPkgName(pkgName); + DeviceManagerNotify::GetInstance().RegisterDeathRecipientCallback(pkgName, dmInitCallback); + LOGI("InitDeviceManager success"); + return DM_OK; +} + +int32_t DeviceManagerImpl::UnInitDeviceManager(const std::string &pkgName) +{ + LOGI("DeviceManager::UnInitDeviceManager start, pkgName: %s", pkgName.c_str()); + if (pkgName.empty()) { + LOGE("InitDeviceManager error: Invalid parameter"); + return DM_INVALID_VALUE; + } + DeviceManagerNotify::GetInstance().DeletePkgName(pkgName); + DeviceManagerNotify::GetInstance().UnRegisterPackageCallback(pkgName); + LOGI("UnInitDeviceManager success"); + return DM_OK; +} + +int32_t DeviceManagerImpl::GetTrustedDeviceList(const std::string &pkgName, const std::string &extra, + std::vector &deviceList) +{ + LOGI("DeviceManager::GetTrustedDeviceList start, pkgName: %s", pkgName.c_str()); + if (pkgName.empty()) { + LOGE("GetTrustedDeviceList error: Invalid para"); + return DM_INVALID_VALUE; + } + + std::shared_ptr req = std::make_shared(); + std::shared_ptr rsp = std::make_shared(); + req->SetPkgName(pkgName); + req->SetExtra(extra); + + if (CommandDispatch::GetInstance().MessageSendCmd(GET_TRUST_DEVICE_LIST, req, rsp) != DM_OK) { + return DEVICEMANAGER_MESSAGE_FAILED; + } + + int32_t ret = rsp->GetErrCode(); + if (ret != DM_OK) { + LOGE("GetTrustedDeviceList error: failed ret: %d", ret); + return ret; + } + + deviceList = rsp->GetDeviceVec(); + LOGI("GetTrustedDeviceList completed, pkgName: %s", pkgName.c_str()); + return DM_OK; +} + +int32_t DeviceManagerImpl::GetLocalDeviceInfo(const std::string &pkgName, DmDeviceInfo &info) +{ + LOGI("DeviceManager::GetLocalDeviceInfo start, pkgName: %s", pkgName.c_str()); + if (pkgName.empty()) { + LOGE("GetLocalDeviceInfo error: Invalid para"); + return DM_INVALID_VALUE; + } + + std::shared_ptr req = std::make_shared(); + std::shared_ptr rsp = std::make_shared(); + req->SetPkgName(pkgName); + + if (CommandDispatch::GetInstance().MessageSendCmd(GET_LOCAL_DEVICE_INFO, req, rsp) != DM_OK) { + return DEVICEMANAGER_MESSAGE_FAILED; + } + + if (rsp->GetErrCode() != DM_OK) { + LOGE("GetLocalDeviceInfo error: failed ret: %d", rsp->GetErrCode()); + return DM_IPC_RESPOND_ERROR; + } + + info = rsp->GetLocalDeviceInfo(); + LOGI("GetLocalDeviceInfo completed,pkgname%s", req->GetPkgName().c_str()); + return DM_OK; +} + +int32_t DeviceManagerImpl::RegisterDevStateCallback(const std::string &pkgName, const std::string &extra, + std::shared_ptr callback) +{ + LOGI("DeviceManager::RegisterDevStateCallback start, pkgName: %s", pkgName.c_str()); + + + if (pkgName.empty() || callback == nullptr) { + LOGE("RegisterDevStateCallback error: Invalid para"); + return DM_INVALID_VALUE; + } + + DeviceManagerNotify::GetInstance().RegisterDeviceStateCallback(pkgName, callback); + LOGI("RegisterDevStateCallback completed, pkgName: %s", pkgName.c_str()); + return DM_OK; +} + +int32_t DeviceManagerImpl::UnRegisterDevStateCallback(const std::string &pkgName) +{ + LOGI("DeviceManager::UnRegisterDevStateCallback start, pkgName: %s", pkgName.c_str()); + + + if (pkgName.empty()) { + LOGE("UnRegisterDevStateCallback error: Invalid para"); + return DM_INVALID_VALUE; + } + + DeviceManagerNotify::GetInstance().UnRegisterDeviceStateCallback(pkgName); + LOGI("UnRegisterDevStateCallback completed, pkgName: %s", pkgName.c_str()); + return DM_OK; +} +int32_t DeviceManagerImpl::StartDeviceDiscovery(const std::string &pkgName, const DmSubscribeInfo &subscribeInfo, + const std::string &extra, std::shared_ptr callback) +{ + LOGI("DeviceManager::StartDeviceDiscovery start, pkgName: %s", pkgName.c_str()); + + if (pkgName.empty() || callback == nullptr) { + LOGE("StartDeviceDiscovery error: Invalid para"); + return DM_INVALID_VALUE; + } + + LOGI("DeviceManager StartDeviceDiscovery in, pkgName %s", pkgName.c_str()); + DeviceManagerNotify::GetInstance().RegisterDiscoveryCallback(pkgName, subscribeInfo.subscribeId, callback); + + std::shared_ptr req = std::make_shared(); + std::shared_ptr rsp = std::make_shared(); + req->SetPkgName(pkgName); + req->SetExtra(extra); + req->SetSubscribeInfo(subscribeInfo); + + if (CommandDispatch::GetInstance().MessageSendCmd(START_DEVICE_DISCOVER, req, rsp) != DM_OK) { + return DEVICEMANAGER_MESSAGE_FAILED; + } + int32_t ret = rsp->GetErrCode(); + if (ret != DM_OK) { + LOGE("StartDeviceDiscovery error: Failed with ret %d", ret); + return ret; + } + return DM_OK; +} + +int32_t DeviceManagerImpl::StopDeviceDiscovery(const std::string &pkgName, uint16_t subscribeId) +{ + LOGI("DeviceManager::StopDeviceDiscovery start , pkgName: %s", pkgName.c_str()); + + if (pkgName.empty()) { + LOGE("StopDeviceDiscovery error: Invalid para"); + return DM_INVALID_VALUE; + } + + LOGI("StopDeviceDiscovery in, pkgName %s", pkgName.c_str()); + std::shared_ptr req = std::make_shared(); + std::shared_ptr rsp = std::make_shared(); + req->SetPkgName(pkgName); + req->SetSubscribeId(subscribeId); + + if (CommandDispatch::GetInstance().MessageSendCmd(STOP_DEVICE_DISCOVER, req, rsp) != DM_OK) { + return DEVICEMANAGER_MESSAGE_FAILED; + } + int32_t ret = rsp->GetErrCode(); + if (ret != DM_OK) { + LOGE("StopDeviceDiscovery error: Failed with ret %d", ret); + return ret; + } + + DeviceManagerNotify::GetInstance().UnRegisterDiscoveryCallback(pkgName, subscribeId); + LOGI("StopDeviceDiscovery completed, pkgName: %s", pkgName.c_str()); + return DM_OK; +} + +int32_t DeviceManagerImpl::AuthenticateDevice(const std::string &pkgName, int32_t authType, + const DmDeviceInfo &deviceInfo, const std::string &extra, + std::shared_ptr callback) +{ + LOGI("DeviceManager::AuthenticateDevice start , pkgName: %s", pkgName.c_str()); + + + if (pkgName.empty()) { + LOGE("AuthenticateDevice error: Invalid para"); + return DM_INVALID_VALUE; + } + + std::string strDeviceId = deviceInfo.deviceId; + DeviceManagerNotify::GetInstance().RegisterAuthenticateCallback(pkgName, strDeviceId, callback); + std::shared_ptr req = std::make_shared(); + std::shared_ptr rsp = std::make_shared(); + req->SetPkgName(pkgName); + req->SetExtra(extra); + req->SetAuthType(authType); + req->SetDeviceInfo(deviceInfo); + + + if (CommandDispatch::GetInstance().MessageSendCmd(AUTHENTICATE_DEVICE, req, rsp) != DM_OK) { + return DEVICEMANAGER_MESSAGE_FAILED; + } + + int32_t ret = rsp->GetErrCode(); + if (ret != DM_OK) { + LOGE("AuthenticateDevice error: Failed with ret %d", ret); + return ret; + } + + LOGI("DeviceManager::AuthenticateDevice completed, pkgName: %s", pkgName.c_str()); + return DM_OK; +} + +int32_t DeviceManagerImpl::UnAuthenticateDevice(const std::string &pkgName, const std::string &deviceId) +{ + LOGI("DeviceManager::UnAuthenticateDevice start , pkgName: %s, deviceId: %s", pkgName.c_str(), deviceId.c_str()); + + + if (deviceId.empty()) { + LOGE("UnAuthenticateDevice error: Invalid para"); + return DM_INVALID_VALUE; + } + + DmDeviceInfo deviceInfo; + strcpy_s(deviceInfo.deviceId, DM_MAX_DEVICE_ID_LEN, deviceId.c_str()); + std::shared_ptr req = std::make_shared(); + std::shared_ptr rsp = std::make_shared(); + req->SetPkgName(pkgName); + req->SetDeviceInfo(deviceInfo); + + if (CommandDispatch::GetInstance().MessageSendCmd(UNAUTHENTICATE_DEVICE, req, rsp) != DM_OK) { + return DEVICEMANAGER_MESSAGE_FAILED; + } + + int32_t ret = rsp->GetErrCode(); + if (ret != DM_OK) { + LOGE("UnAuthenticateDevice error: Failed with ret %d", ret); + return ret; + } + + LOGI("UnAuthenticateDevice completed, pkgName: %s", pkgName.c_str()); + return DM_OK; +} + + +// int32_t DeviceManagerImpl::GetAuthenticationParam(std::string &pkgName, DmAuthParam &authParam) +// { +// LOGI("DeviceManager::GetAuthenticationParam start"); + +// std::shared_ptr req = std::make_shared(); +// std::shared_ptr rsp = std::make_shared(); +// req->SetPkgName(pkgName); +// if (CommandDispatch::GetInstance().MessageSendCmd(SERVER_GET_AUTHENTCATION_INFO, req, rsp) != DM_OK) { +// return DEVICEMANAGER_MESSAGE_FAILED; +// } + +// if (rsp->GetErrCode() == DM_OK) { +// authParam = rsp->GetAuthParam(); +// } + +// return DM_OK; +// } + +int32_t DeviceManagerImpl::RegisterDeviceManagerFaCallback(const std::string &pkgName, + std::shared_ptr callback) +{ + LOGI("DeviceManager::RegisterDeviceManagerFaCallback start, pkgName: %s", pkgName.c_str()); + if (pkgName.empty() || callback == nullptr) { + LOGE("RegisterDeviceManagerFaCallback error: Invalid para"); + return DM_INVALID_VALUE; + } + DeviceManagerNotify::GetInstance().RegisterDeviceManagerFaCallback(pkgName, callback); + LOGI("DeviceManager::RegisterDevStateCallback completed, pkgName: %s", pkgName.c_str()); + return DM_OK; +} + +int32_t DeviceManagerImpl::UnRegisterDeviceManagerFaCallback(const std::string &pkgName) +{ + LOGI("DeviceManager::UnRegisterDeviceManagerFaCallback start, pkgName: %s", pkgName.c_str()); + if (pkgName.empty()) { + LOGE("UnRegisterDeviceManagerFaCallback error: Invalid para"); + return DM_INVALID_VALUE; + } + DeviceManagerNotify::GetInstance().UnRegisterDeviceManagerFaCallback(pkgName); + LOGI("DeviceManager::UnRegisterDevStateCallback completed, pkgName: %s", pkgName.c_str()); + return DM_OK; +} +int32_t DeviceManagerImpl::VerifyAuthentication(const std::string &pkgName, const std::string &authPara, + std::shared_ptr callback) +{ + LOGI("DeviceManager::VerifyAuthentication start, pkgName: %s", pkgName.c_str()); + + if (pkgName.empty()) { + LOGE("VerifyAuthentication error: Invalid para"); + return DM_INVALID_VALUE; + } + + DeviceManagerNotify::GetInstance().RegisterVerifyAuthenticationCallback(pkgName, authPara, callback); + + std::shared_ptr req = std::make_shared(); + std::shared_ptr rsp = std::make_shared(); + req->SetPkgName(pkgName); + req->SetAuthPara(authPara); + + if (CommandDispatch::GetInstance().MessageSendCmd(VERIFY_AUTHENTICATION, req, rsp) != DM_OK) { + return DEVICEMANAGER_MESSAGE_FAILED; + } + + int32_t ret = rsp->GetErrCode(); + if (ret != DM_OK) { + LOGE("VerifyAuthentication error: Failed with ret %d", ret); + return ret; + } + + LOGI("VerifyAuthentication completed, pkgName: %s", pkgName.c_str()); + return DM_OK; +} + +int32_t DeviceManagerImpl::GetFaParam(const std::string &pkgName, DmAuthParam &dmFaParam) +{ + LOGI("DeviceManager::GetFaParam start, pkgName: %s", pkgName.c_str()); + if (pkgName.empty()) { + LOGE("GetFaParam failed, pkgName is empty"); + return DM_INVALID_VALUE; + } + + std::shared_ptr req = std::make_shared(); + std::shared_ptr rsp = std::make_shared(); + req->SetPkgName(pkgName); + + if (CommandDispatch::GetInstance().MessageSendCmd(SERVER_GET_DMFA_INFO, req, rsp) != DM_OK) { + return DEVICEMANAGER_MESSAGE_FAILED; + } + + dmFaParam = rsp->GetDmAuthParam(); + LOGI("GetFaParam completed, pkgName: %s", pkgName.c_str()); + return DM_OK; +} + + + +int32_t DeviceManagerImpl::SetUserOperation(const std::string &pkgName, int32_t action) +{ + LOGI("DeviceManager::SetUserOperation start, pkgName: %s", pkgName.c_str()); + + if (pkgName.empty()) { + LOGE("VerifyAuthentication failed, pkgName is empty"); + return DM_INVALID_VALUE; + } + + std::shared_ptr req = std::make_shared(); + std::shared_ptr rsp = std::make_shared(); + + req->SetPkgName(pkgName); + req->SetOperation(action); + + if (CommandDispatch::GetInstance().MessageSendCmd(SERVER_USER_AUTH_OPERATION, req, rsp) != DM_OK) { + return DEVICEMANAGER_MESSAGE_FAILED; + } + int32_t ret = rsp->GetErrCode(); + if (ret != DM_OK) { + LOGE("SetUserOperation Failed with ret %d", ret); + return ret; + } + + LOGI("SetUserOperation completed, pkgName: %s", pkgName.c_str()); + return DM_OK; +} + +int32_t DeviceManagerImpl::GetUdidByNetworkId(const std::string &pkgName, const std::string &netWorkId, + std::string &udid) +{ + if (pkgName.empty()) { + LOGE("GetUdidByNetworkId failed, pkgName is empty"); + return DM_INVALID_VALUE; + } + + std::shared_ptr req = std::make_shared(); + std::shared_ptr rsp = std::make_shared(); + req->SetPkgName(pkgName); + req->SetNetWorkId(netWorkId); + + if (CommandDispatch::GetInstance().MessageSendCmd(GET_UDID_BY_NETWORK, req, rsp) != DM_OK) { + return DEVICEMANAGER_MESSAGE_FAILED; + } + + int32_t ret = rsp->GetErrCode(); + if (ret != DM_OK) { + LOGE("DeviceManager::GetUdidByNetworkId Failed with ret %d", ret); + return ret; + } + + udid = rsp->GetUdid(); + return DM_OK; +} + +int32_t DeviceManagerImpl::GetUuidByNetworkId(const std::string &pkgName, const std::string &netWorkId, + std::string &uuid) +{ + if (pkgName.empty()) { + LOGE("GetUuidByNetworkId failed, pkgName is empty"); + return DM_INVALID_VALUE; + } + + std::shared_ptr req = std::make_shared(); + std::shared_ptr rsp = std::make_shared(); + req->SetPkgName(pkgName); + req->SetNetWorkId(netWorkId); + + if (CommandDispatch::GetInstance().MessageSendCmd(GET_UUID_BY_NETWORK, req, rsp) != DM_OK) { + return DEVICEMANAGER_MESSAGE_FAILED; + } + + int32_t ret = rsp->GetErrCode(); + if (ret != DM_OK) { + LOGE("GetUuidByNetworkId Failed with ret %d", ret); + return ret; + } + uuid = rsp->GetUuid(); + return DM_OK; +} + + + + +} // namespace DistributedHardware +} // namespace OHOS diff --git a/interfaces_mini/inner_kits/native_cpp/src/notify/device_manager_notify.cpp b/interfaces_mini/inner_kits/native_cpp/src/notify/device_manager_notify.cpp new file mode 100644 index 000000000..1d7b304da --- /dev/null +++ b/interfaces_mini/inner_kits/native_cpp/src/notify/device_manager_notify.cpp @@ -0,0 +1,295 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "device_manager_notify.h" + +// #include "device_manager_log.h" +#include "dm_log.h" +// #include "device_manager_errno.h" +#include "nlohmann/json.hpp" +#include "dm_constants.h" +#include "device_manager.h" + +namespace OHOS { +namespace DistributedHardware { +IMPLEMENT_SINGLE_INSTANCE(DeviceManagerNotify); + +void DeviceManagerNotify::RegisterDeathRecipientCallback(const std::string &pkgName, + std::shared_ptr dmInitCallback) +{ + //std::lock_guard autoLock(lock_); + dmInitCallback_[pkgName] = dmInitCallback; +} + +void DeviceManagerNotify::UnRegisterDeathRecipientCallback(const std::string &pkgName) +{ + //std::lock_guard autoLock(lock_); + dmInitCallback_.erase(pkgName); +} + +void DeviceManagerNotify::RegisterDeviceStateCallback(const std::string &pkgName, + std::shared_ptr callback) +{ + //std::lock_guard autoLock(lock_); + deviceStateCallback_[pkgName] = callback; +} + +void DeviceManagerNotify::UnRegisterDeviceStateCallback(const std::string &pkgName) +{ + //std::lock_guard autoLock(lock_); + deviceStateCallback_.erase(pkgName); +} + +void DeviceManagerNotify::RegisterDiscoveryCallback(const std::string &pkgName, uint16_t subscribeId, + std::shared_ptr callback) +{ + //std::lock_guard autoLock(lock_); + if (deviceDiscoveryCallbacks_.count(pkgName) == 0) { + deviceDiscoveryCallbacks_[pkgName] = std::map>(); + } + deviceDiscoveryCallbacks_[pkgName][subscribeId] = callback; +} + +void DeviceManagerNotify::UnRegisterDiscoveryCallback(const std::string &pkgName, uint16_t subscribeId) +{ + //std::lock_guard autoLock(lock_); + if (deviceDiscoveryCallbacks_.count(pkgName) > 0) { + deviceDiscoveryCallbacks_[pkgName].erase(subscribeId); + if (deviceDiscoveryCallbacks_[pkgName].empty()) { + deviceDiscoveryCallbacks_.erase(pkgName); + } + } +} + +void DeviceManagerNotify::RegisterAuthenticateCallback(const std::string &pkgName, const std::string &deviceId, + std::shared_ptr callback) +{ + //std::lock_guard autoLock(lock_); + if (authenticateCallback_.count(pkgName) == 0) { + authenticateCallback_[pkgName] = std::map>(); + } + authenticateCallback_[pkgName][deviceId] = callback; +} + +void DeviceManagerNotify::UnRegisterAuthenticateCallback(const std::string &pkgName, const std::string &deviceId) +{ + //std::lock_guard autoLock(lock_); + if (authenticateCallback_.count(pkgName) > 0) { + authenticateCallback_[pkgName].erase(deviceId); + if (authenticateCallback_[pkgName].empty()) { + authenticateCallback_.erase(pkgName); + } + } +} + +void DeviceManagerNotify::UnRegisterPackageCallback(const std::string &pkgName) +{ + //std::lock_guard autoLock(lock_); + deviceStateCallback_.erase(pkgName); + deviceDiscoveryCallbacks_.erase(pkgName); + authenticateCallback_.erase(pkgName); + dmInitCallback_.erase(pkgName); +} + +void DeviceManagerNotify::RegisterVerifyAuthenticationCallback(const std::string &pkgName, const std::string &authPara, + std::shared_ptr callback) +{ + //std::lock_guard autoLock(lock_); + verifyAuthCallback_[pkgName] = callback; +} + +void DeviceManagerNotify::UnRegisterVerifyAuthenticationCallback(const std::string &pkgName) +{ + //std::lock_guard autoLock(lock_); + verifyAuthCallback_.erase(pkgName); +} + +void DeviceManagerNotify::RegisterDeviceManagerFaCallback(const std::string &pkgName, + std::shared_ptr callback) +{ + //std::lock_guard autoLock(lock_); + dmFaCallback_[pkgName] = callback; +} + +void DeviceManagerNotify::UnRegisterDeviceManagerFaCallback(const std::string &pkgName) +{ + //std::lock_guard autoLock(lock_); + if (dmFaCallback_.count(pkgName) == 0) { + LOGE("DeviceManager UnRegisterDeviceManagerFaCallback not register"); + return; + } + dmFaCallback_.erase(pkgName); +} + + +void DeviceManagerNotify::OnRemoteDied() +{ + LOGW("DeviceManager : OnRemoteDied"); + for (auto iter : dmInitCallback_) { + iter.second->OnRemoteDied(); + } +} + +void DeviceManagerNotify::OnDeviceOnline(const std::string &pkgName, const DmDeviceInfo &deviceInfo) +{ + LOGI("DeviceManager OnDeviceOnline pkgName:%s", pkgName.c_str()); + //std::lock_guard autoLock(lock_); + if (deviceStateCallback_.count(pkgName) == 0) { + LOGE("DeviceManager OnDeviceOnlinecallback not register"); + return; + } + deviceStateCallback_[pkgName]->OnDeviceOnline(deviceInfo); +} + +void DeviceManagerNotify::OnDeviceOffline(const std::string &pkgName, const DmDeviceInfo &deviceInfo) +{ + LOGI("DeviceManager OnDeviceOffline pkgName:%s", pkgName.c_str()); + // std::lock_guard autoLock(lock_); + if (deviceStateCallback_.count(pkgName) == 0) { + LOGE("DeviceManager OnDeviceOfflinecallback not register"); + return; + } + deviceStateCallback_[pkgName]->OnDeviceOffline(deviceInfo); +} + +void DeviceManagerNotify::OnDeviceChanged(const std::string &pkgName, const DmDeviceInfo &deviceInfo) +{ + LOGI("DeviceManager OnDeviceChanged pkgName:%s", pkgName.c_str()); + // std::lock_guard autoLock(lock_); + if (deviceStateCallback_.count(pkgName) == 0) { + LOGE("DeviceManager OnDeviceChangedcallback not register"); + return; + } + deviceStateCallback_[pkgName]->OnDeviceChanged(deviceInfo); +} + +void DeviceManagerNotify::OnDeviceFound(const std::string &pkgName, uint16_t subscribeId, + const DmDeviceInfo &deviceInfo) +{ + LOGI("DeviceManager OnDeviceFound pkgName:%s, subscribeId:%d.", pkgName.c_str(), (int32_t)subscribeId); + //std::lock_guard autoLock(lock_); + if (deviceDiscoveryCallbacks_.count(pkgName) == 0) { + LOGE("DeviceManager OnDeviceFound: no register DiscoveryCallback for this package"); + return; + } + std::map> &discoverCallMap = deviceDiscoveryCallbacks_[pkgName]; + auto iter = discoverCallMap.find(subscribeId); + if (iter == discoverCallMap.end()) { + LOGE("DeviceManager OnDeviceFound: no register DiscoveryCallback for subscribeId %d", subscribeId); + return; + } + iter->second->OnDeviceFound(subscribeId, deviceInfo); +} + +void DeviceManagerNotify::OnDiscoveryFailed(const std::string &pkgName, uint16_t subscribeId, int32_t failedReason) +{ + LOGI("DeviceManager OnDiscoveryFailed pkgName:%s, subscribeId %d, reason %d", pkgName.c_str(), subscribeId, + failedReason); + //std::lock_guard autoLock(lock_); + if (deviceDiscoveryCallbacks_.count(pkgName) == 0) { + LOGE("DeviceManager OnDiscoveryFailed: no register DiscoveryCallback for this package"); + return; + } + std::map> &discoverCallMap = deviceDiscoveryCallbacks_[pkgName]; + auto iter = discoverCallMap.find(subscribeId); + if (iter == discoverCallMap.end()) { + LOGE("DeviceManager OnDiscoveryFailed: no register DiscoveryCallback for subscribeId %d", subscribeId); + return; + } + iter->second->OnDiscoveryFailed(subscribeId, failedReason); +} + +void DeviceManagerNotify::OnDiscoverySuccess(const std::string &pkgName, uint16_t subscribeId) +{ + LOGI("DeviceManager OnDiscoverySuccess pkgName:%s, subscribeId:%d.", pkgName.c_str(), subscribeId); + //std::lock_guard autoLock(lock_); + if (deviceDiscoveryCallbacks_.count(pkgName) == 0) { + LOGE("DeviceManager OnDiscoverySuccess: no register DiscoveryCallback for this package"); + return; + } + std::map> &discoverCallMap = deviceDiscoveryCallbacks_[pkgName]; + auto iter = discoverCallMap.find(subscribeId); + if (iter == discoverCallMap.end()) { + LOGE("DeviceManager OnDiscoverySuccess: no register DiscoveryCallback for subscribeId %d", subscribeId); + return; + } + iter->second->OnDiscoverySuccess(subscribeId); +} + +void DeviceManagerNotify::OnAuthResult(const std::string &pkgName, const std::string &deviceId, + const std::string &token, uint32_t status, uint32_t reason) +{ + LOGI("DeviceManagerNotify::OnAuthResult pkgName:%s, status:%d, reason:%d", pkgName.c_str(), status, reason); + //std::lock_guard autoLock(lock_); + if (authenticateCallback_.count(pkgName) == 0) { + LOGE("DeviceManager OnAuthResult: no register authCallback for this package"); + return; + } + std::map> &authCallMap = authenticateCallback_[pkgName]; + auto iter = authCallMap.find(deviceId); + if (iter == authCallMap.end()) { + LOGE("DeviceManager OnAuthResult: no register authCallback for deviceID "); + return; + } + iter->second->OnAuthResult(deviceId, token, status, reason); + authenticateCallback_[pkgName].erase(deviceId); + if (authenticateCallback_[pkgName].empty()) { + authenticateCallback_.erase(pkgName); + } +} + +void DeviceManagerNotify::OnVerifyAuthResult(const std::string &pkgName, const std::string &deviceId, + int32_t resultCode, const std::string flag) +{ + LOGI("DeviceManagerNotify::OnCheckAuthResult pkgName:%s, resultCode:%d, flag:%d", pkgName.c_str(), resultCode, + flag); + //std::lock_guard autoLock(lock_); + if (verifyAuthCallback_.count(pkgName) == 0) { + LOGE("DeviceManager OnCheckAuthResult: no register authCallback for this package"); + return; + } + verifyAuthCallback_[pkgName]->OnVerifyAuthResult(deviceId, resultCode, flag); + verifyAuthCallback_.erase(pkgName); +} + +void DeviceManagerNotify::OnFaCall(std::string &pkgName, std::string ¶mJson) +{ + LOGI("DeviceManager OnFaCallback pkgName:%s", pkgName.c_str()); + //std::lock_guard autoLock(lock_); + if (dmFaCallback_.count(pkgName) == 0) { + LOGE("DeviceManager DmFaCallback not register"); + return; + } + dmFaCallback_[pkgName]->OnCall(paramJson); +} + +void DeviceManagerNotify::AddPkgName(const std::string &pkgName) +{ + dmPkgName_.push_back(pkgName); +} + +void DeviceManagerNotify::DeletePkgName(const std::string &pkgName) +{ + dmPkgName_.remove(pkgName); +} + +const std::list& DeviceManagerNotify::GetPkgNameList() const +{ + return dmPkgName_; +} + + +} // namespace DistributedHardware +} // namespace OHOS diff --git a/services/devicemanagerservice/include/device_manager_service.h b/services/devicemanagerservice/include/device_manager_service.h index d5e636928..a810768fe 100644 --- a/services/devicemanagerservice/include/device_manager_service.h +++ b/services/devicemanagerservice/include/device_manager_service.h @@ -19,14 +19,16 @@ #include #include -#include "dm_ability_manager.h" -#include "dm_auth_manager.h" +// #include "dm_ability_manager.h" +// #include "dm_auth_manager.h" #include "dm_device_info.h" -#include "dm_device_info_manager.h" -#include "dm_device_state_manager.h" -#include "dm_discovery_manager.h" +// #include "dm_device_info_manager.h" +// #include "dm_device_state_manager.h" +// #include "dm_discovery_manager.h" #include "single_instance.h" -#include "softbus_connector.h" +// #include "softbus_connector.h" + +#include "dm_subscribe_info.h" namespace OHOS { namespace DistributedHardware { @@ -54,14 +56,14 @@ public: private: DeviceManagerService() = default; bool intFlag_ = false; - std::shared_ptr authMgr_; - std::shared_ptr deviceInfoMgr_; - std::shared_ptr deviceStateMgr_; - std::shared_ptr discoveryMgr_; - std::shared_ptr softbusConnector_; - std::shared_ptr listener_; - std::shared_ptr abilityMgr_; - std::shared_ptr hiChainConnector_; + // std::shared_ptr authMgr_; + // std::shared_ptr deviceInfoMgr_; + // std::shared_ptr deviceStateMgr_; + // std::shared_ptr discoveryMgr_; + // std::shared_ptr softbusConnector_; + // std::shared_ptr listener_; + // std::shared_ptr abilityMgr_; + // std::shared_ptr hiChainConnector_; }; } // namespace DistributedHardware } // namespace OHOS diff --git a/services/devicemanagerservice/include/device_manager_service_listener.h b/services/devicemanagerservice/include/device_manager_service_listener.h index e52d9ed73..49da7ea06 100644 --- a/services/devicemanagerservice/include/device_manager_service_listener.h +++ b/services/devicemanagerservice/include/device_manager_service_listener.h @@ -20,8 +20,11 @@ #include #include "dm_device_info.h" +#if (defined(__LINUX__) || defined(__LITEOS_A__)) #include "ipc_notify_dmfa_result_req.h" #include "ipc_server_listener.h" +#endif + namespace OHOS { namespace DistributedHardware { @@ -38,7 +41,9 @@ public: void OnFaCall(std::string &pkgName, std::string ¶mJson); private: - IpcServerListener ipcServerListener_; +#if (defined(__LINUX__) || defined(__LITEOS_A__)) +IpcServerListener ipcServerListener_; +#endif }; } // namespace DistributedHardware } // namespace OHOS diff --git a/services/devicemanagerservice/include/dispatch/authenticate_device_req.h b/services/devicemanagerservice/include/dispatch/authenticate_device_req.h new file mode 100644 index 000000000..c361ead51 --- /dev/null +++ b/services/devicemanagerservice/include/dispatch/authenticate_device_req.h @@ -0,0 +1,120 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef OHOS_DEVICE_MANAGER_AUTHENTICATE_DEVICE_REQ_H +#define OHOS_DEVICE_MANAGER_AUTHENTICATE_DEVICE_REQ_H + +#include "message_req.h" + +#include "dm_device_info.h" +#include "dm_app_image_info.h" + +namespace OHOS { +namespace DistributedHardware { +class AuthenticateDeviceReq : public MessageReq { +DECLARE_MESSAGE_MODEL(AuthenticateDeviceReq); +public: + const DmDeviceInfo& GetDeviceInfo() const + { + return deviceInfo_; + } + + void SetDeviceInfo(const DmDeviceInfo &deviceInfo) + { + deviceInfo_ = deviceInfo; + } + + int32_t GetAuthType() + { + return authType_; + } + + void SetAuthType(int32_t authType) + { + authType_ = authType; + } + + // const DmAppImageInfo& GetAppImageInfo() const + // { + // return appImageInfo_; + // } + + // void SetAppImageInfo(const DmAppImageInfo &appImageInfo) + // { + // appImageInfo_ = appImageInfo; + // } + + const std::string& GetExtra() const + { + return extra_; + } + + void SetExtra(const std::string &extra) + { + extra_ = extra; + } +private: + DmDeviceInfo deviceInfo_; + int32_t authType_; + // DmAppImageInfo appImageInfo_; + std::string extra_; +}; +} // namespace DistributedHardware +} // namespace OHOS +#endif // OHOS_DEVICE_MANAGER_AUTHENTICATE_DEVICE_REQ_H + +// namespace OHOS { +// namespace DistributedHardware { +// class IpcAuthenticateDeviceReq : public IpcReq { +// DECLARE_IPC_MODEL(IpcAuthenticateDeviceReq); + +// public: +// const DmDeviceInfo &GetDeviceInfo() const +// { +// return deviceInfo_; +// } + +// void SetDeviceInfo(const DmDeviceInfo &deviceInfo) +// { +// deviceInfo_ = deviceInfo; +// } + +// int32_t GetAuthType() +// { +// return authType_; +// } + +// void SetAuthType(int32_t authType) +// { +// authType_ = authType; +// } + +// const std::string &GetExtra() const +// { +// return extra_; +// } + +// void SetExtra(const std::string &extra) +// { +// extra_ = extra; +// } + +// private: +// DmDeviceInfo deviceInfo_; +// int32_t authType_; +// std::string extra_; +// }; +// } // namespace DistributedHardware +// } // namespace OHOS diff --git a/services/devicemanagerservice/include/dispatch/command_dispatch.h b/services/devicemanagerservice/include/dispatch/command_dispatch.h new file mode 100644 index 000000000..efe52f3b9 --- /dev/null +++ b/services/devicemanagerservice/include/dispatch/command_dispatch.h @@ -0,0 +1,40 @@ +/* + * Copyright (c) 2020 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef OHOS_DEVICE_MANAGER_COMMAND_DISPATCH_H +#define OHOS_DEVICE_MANAGER_COMMAND_DISPATCH_H + +#include +#include +#include +#include "single_instance.h" +#include "message_processing.h" +#include "message_req.h" +#include "message_rsp.h" + + + +namespace OHOS { +namespace DistributedHardware { + +class CommandDispatch { +DECLARE_SINGLE_INSTANCE(CommandDispatch); +public: + int32_t CmdProcessing(int32_t cmdCode, std::shared_ptr req, std::shared_ptr rsp); + int32_t MessageSendCmd(int32_t cmdCode, std::shared_ptr req, std::shared_ptr rsp); +}; +} +} +#endif \ No newline at end of file diff --git a/services/devicemanagerservice/include/dispatch/get_authenticationparam_rsp.h b/services/devicemanagerservice/include/dispatch/get_authenticationparam_rsp.h new file mode 100644 index 000000000..b66e73d02 --- /dev/null +++ b/services/devicemanagerservice/include/dispatch/get_authenticationparam_rsp.h @@ -0,0 +1,41 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef OHOS_DEVICE_MANAGER_GET_AUTH_PARAM_RSP_H +#define OHOS_DEVICE_MANAGER_GET_AUTH_PARAM_RSP_H + +#include "message_rsp.h" +#include "dm_device_info.h" + +namespace OHOS { +namespace DistributedHardware { +class GetAuthParamRsp : public MessageRsp { +DECLARE_MESSAGE_MODEL(GetAuthParamRsp); +public: + const DmAuthParam& GetAuthParam() const + { + return authParam_; + } + + void SetAuthParam(DmAuthParam &authParam) + { + authParam_ = authParam; + } +private: + DmAuthParam authParam_; +}; +} // namespace DistributedHardware +} // namespace OHOS +#endif // OHOS_DEVICE_MANAGER_GET_AUTH_PARAM_RSP_H \ No newline at end of file diff --git a/services/devicemanagerservice/include/dispatch/get_dmfaparam_rsp.h b/services/devicemanagerservice/include/dispatch/get_dmfaparam_rsp.h new file mode 100644 index 000000000..b8a913d00 --- /dev/null +++ b/services/devicemanagerservice/include/dispatch/get_dmfaparam_rsp.h @@ -0,0 +1,43 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef OHOS_DEVICE_MANAGER_GET_DM_FA_PARAM_RSP_H +#define OHOS_DEVICE_MANAGER_GET_DM_FA_PARAM_RSP_H + +#include "dm_device_info.h" +#include "message_rsp.h" + +namespace OHOS { +namespace DistributedHardware { +class GetDmFaParamRsp : public MessageRsp { + DECLARE_MESSAGE_MODEL(GetDmFaParamRsp); + +public: + const DmAuthParam GetDmAuthParam() const + { + return dmFaParam_; + } + + void SetDmAuthParam(const DmAuthParam &dmFaParam) + { + dmFaParam_ = dmFaParam; + } + +private: + DmAuthParam dmFaParam_; +}; +} // namespace DistributedHardware +} // namespace OHOS +#endif // OHOS_DEVICE_MANAGER_GET_DM_FA_PARAM_RSP_H \ No newline at end of file diff --git a/services/devicemanagerservice/include/dispatch/get_info_by_network_req.h b/services/devicemanagerservice/include/dispatch/get_info_by_network_req.h new file mode 100644 index 000000000..10af9d757 --- /dev/null +++ b/services/devicemanagerservice/include/dispatch/get_info_by_network_req.h @@ -0,0 +1,42 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef OHOS_DEVICE_MANAGER_GET_INFO_BY_NETWORK_REQ_H +#define OHOS_DEVICE_MANAGER_GET_INFO_BY_NETWORK_REQ_H + +#include "message_req.h" + +namespace OHOS { +namespace DistributedHardware { +class GetInfoByNetWorkReq : public MessageReq { + DECLARE_MESSAGE_MODEL(GetInfoByNetWorkReq); + +public: + const std::string GetNetWorkId() const + { + return netWorkId_; + } + + void SetNetWorkId(const std::string &netWorkId) + { + netWorkId_ = netWorkId; + } + +private: + std::string netWorkId_; +}; +} // namespace DistributedHardware +} // namespace OHOS +#endif // OHOS_DEVICE_MANAGER_GET_INFO_BY_NETWORK_REQ_H \ No newline at end of file diff --git a/services/devicemanagerservice/include/dispatch/get_info_by_network_rsp.h b/services/devicemanagerservice/include/dispatch/get_info_by_network_rsp.h new file mode 100644 index 000000000..471711caf --- /dev/null +++ b/services/devicemanagerservice/include/dispatch/get_info_by_network_rsp.h @@ -0,0 +1,54 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef OHOS_DEVICE_MANAGER_GET_INFO_BY_NETWORK_RSP_H +#define OHOS_DEVICE_MANAGER_GET_INFO_BY_NETWORK_RSP_H + +#include + +#include "message_rsp.h" + +namespace OHOS { +namespace DistributedHardware { +class GetInfoByNetWorkRsp : public MessageRsp { + DECLARE_MESSAGE_MODEL(GetInfoByNetWorkRsp); + +public: + const std::string GetUdid() const + { + return udid_; + } + + void SetUdid(const std::string &udid) + { + udid_ = udid; + } + const std::string GetUuid() const + { + return uuid_; + } + + void SetUuid(const std::string &uuid) + { + uuid_ = uuid; + } + +private: + std::string udid_; + std::string uuid_; +}; +} // namespace DistributedHardware +} // namespace OHOS +#endif // OHOS_DEVICE_MANAGER_GET_INFO_BY_NETWORK_RSP_H \ No newline at end of file diff --git a/services/devicemanagerservice/include/dispatch/get_local_device_info_rsp.h b/services/devicemanagerservice/include/dispatch/get_local_device_info_rsp.h new file mode 100644 index 000000000..45930888d --- /dev/null +++ b/services/devicemanagerservice/include/dispatch/get_local_device_info_rsp.h @@ -0,0 +1,43 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef OHOS_DEVICE_MANAGER_GET_LOCAL_DEVICE_INFO_RSP_H +#define OHOS_DEVICE_MANAGER_GET_LOCAL_DEVICE_INFO_RSP_H + +#include "dm_device_info.h" +#include "message_rsp.h" + +namespace OHOS { +namespace DistributedHardware { +class GetLocalDeviceInfoRsp : public MessageRsp { + DECLARE_MESSAGE_MODEL(GetLocalDeviceInfoRsp); + +public: + const DmDeviceInfo &GetLocalDeviceInfo() const + { + return localDeviceInfo_; + } + + void SetLocalDeviceInfo(DmDeviceInfo &localDeviceInfo) + { + localDeviceInfo_ = localDeviceInfo; + } + +private: + DmDeviceInfo localDeviceInfo_; +}; +} // namespace DistributedHardware +} // namespace OHOS +#endif // OHOS_DM_IPC_GET_LOCAL_DEVICE_INFO_RSP_H \ No newline at end of file diff --git a/services/devicemanagerservice/include/dispatch/get_trustdevice_req.h b/services/devicemanagerservice/include/dispatch/get_trustdevice_req.h new file mode 100644 index 000000000..f071baa9d --- /dev/null +++ b/services/devicemanagerservice/include/dispatch/get_trustdevice_req.h @@ -0,0 +1,63 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef OHOS_DEVICE_MANAGER_GET_TRUST_DEVICE_REQ_H +#define OHOS_DEVICE_MANAGER_GET_TRUST_DEVICE_REQ_H + +#include "message_req.h" + +namespace OHOS { +namespace DistributedHardware { +class GetTrustDeviceReq : public MessageReq { +DECLARE_MESSAGE_MODEL(GetTrustDeviceReq); +public: + const std::string& GetExtra() const + { + return extra_; + } + + void SetExtra(const std::string &extra) + { + extra_ = extra; + } +private: + std::string extra_; +}; +} // namespace DistributedHardware +} // namespace OHOS +#endif // OHOS_DEVICE_MANAGER_GET_TRUST_DEVICE_REQ_H + + +// namespace OHOS { +// namespace DistributedHardware { +// class IpcGetTrustDeviceReq : public IpcReq { +// DECLARE_IPC_MODEL(IpcGetTrustDeviceReq); + +// public: +// const std::string &GetExtra() const +// { +// return extra_; +// } + +// void SetExtra(const std::string &extra) +// { +// extra_ = extra; +// } + +// private: +// std::string extra_; +// }; +// } // namespace DistributedHardware +// } // namespace OHOS diff --git a/services/devicemanagerservice/include/dispatch/get_trustdevice_rsp.h b/services/devicemanagerservice/include/dispatch/get_trustdevice_rsp.h new file mode 100644 index 000000000..7b9bef074 --- /dev/null +++ b/services/devicemanagerservice/include/dispatch/get_trustdevice_rsp.h @@ -0,0 +1,44 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef OHOS_DEVICE_MANAGER_GET_TRUSTDEVICE_RSP_H +#define OHOS_DEVICE_MANAGER_GET_TRUSTDEVICE_RSP_H + +#include + +#include "dm_device_info.h" + +#include "message_rsp.h" + +namespace OHOS { +namespace DistributedHardware { +class GetTrustDeviceRsp : public MessageRsp { +DECLARE_MESSAGE_MODEL(GetTrustDeviceRsp); +public: + std::vector GetDeviceVec() const + { + return deviceVec_; + } + + void SetDeviceVec(std::vector& deviceVec) + { + deviceVec_ = deviceVec; + } +private: + std::vector deviceVec_; +}; +} // namespace DistributedHardware +} // namespace OHOS +#endif // OHOS_DEVICE_MANAGER_GET_TRUSTDEVICE_RSP_H diff --git a/services/devicemanagerservice/include/dispatch/message_def.h b/services/devicemanagerservice/include/dispatch/message_def.h new file mode 100644 index 000000000..ea7f6c453 --- /dev/null +++ b/services/devicemanagerservice/include/dispatch/message_def.h @@ -0,0 +1,60 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef DEVICE_MANAGER_MESSAGE_DEF_H +#define DEVICE_MANAGER_MESSAGE_DEF_H + +namespace OHOS { +namespace DistributedHardware { +#define DEVICE_MANAGER_SERVICE_NAME "dev_mgr_svc" +#define MAX_DM_IPC_LEN 2048 + +#define DECLARE_MESSAGE_MODEL(className) \ +public: \ + className() = default; \ + virtual ~className() = default; \ +public: \ + className(const className&) = delete; \ + className& operator= (const className&) = delete; \ + className(className&&) = delete; \ + className& operator= (className&&) = delete \ + +#define DECLARE_MESSAGE_INTERFACE(className) \ + DECLARE_MESSAGE_MODEL(className) + +enum DispatchCmdID { + REGISTER_DEVICE_MANAGER_LISTENER = 0,//无需修改 + UNREGISTER_DEVICE_MANAGER_LISTENER,//无需修改 + GET_TRUST_DEVICE_LIST,//上到下 + GET_LOCAL_DEVICE_INFO,//上到下 + GET_UDID_BY_NETWORK,//上到下,standard实现,lite未实现 + GET_UUID_BY_NETWORK,//上到下,standard实现,lite未实现 + START_DEVICE_DISCOVER,//上到下 + STOP_DEVICE_DISCOVER,//上到下 + AUTHENTICATE_DEVICE,//上到下 + UNAUTHENTICATE_DEVICE,//上到下 + VERIFY_AUTHENTICATION,//上到下,替代CHECK_AUTHENTICATION + SERVER_DEVICE_STATE_NOTIFY,//下到上 + SERVER_DEVICE_FOUND,//下到上 + SERVER_DISCOVER_FINISH,//下到上 + SERVER_AUTH_RESULT,//下到上 + SERVER_VERIFY_AUTH_RESULT,//下到上 + SERVER_GET_DMFA_INFO,//上到下,替代SERVER_GET_AUTHENTCATION_INFO,standard实现,lite未实现 + SERVER_USER_AUTH_OPERATION,//上到下,替代SERVER_USER_AUTHORIZATION_OPERATION + SERVER_DEVICE_FA_NOTIFY,//下到上,替代SERVER_DEVICEMANAGER_FA_NOTIFY +}; +} // namespace DistributedHardware +} // namespace OHOS +#endif // DEVICE_MANAGER_MESSAGE_DEF_H diff --git a/services/devicemanagerservice/include/dispatch/message_processing.h b/services/devicemanagerservice/include/dispatch/message_processing.h new file mode 100644 index 000000000..b8141c673 --- /dev/null +++ b/services/devicemanagerservice/include/dispatch/message_processing.h @@ -0,0 +1,49 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef OHOS_DEVICE_MANAGER_MESSAGE_PROCESSING_H +#define OHOS_DEVICE_MANAGER_MESSAGE_PROCESSING_H + +#include + +#include "dm_app_image_info.h" +#include "dm_device_info.h" +#include "dm_subscribe_info.h" +#include "nlohmann/json.hpp" +#include "get_authenticationparam_rsp.h" +#include "get_trustdevice_rsp.h" +#include "single_instance.h" + +namespace OHOS { +namespace DistributedHardware { +class MessageProcessing { +DECLARE_SINGLE_INSTANCE(MessageProcessing); +public: + int32_t ModuleInit(); + int32_t GetTrustedDeviceList(std::string &pkgName, std::string &extra, DmDeviceInfo **info, int32_t *infoNum, std::shared_ptr prsp); + int32_t StartDeviceDiscovery(std::string &pkgName, const DmSubscribeInfo &dmSubscribeInfo); + int32_t StopDiscovery(std::string &pkgName, uint16_t subscribeId); + int32_t AuthenticateDevice(std::string &pkgName, const DmDeviceInfo &deviceInfo, + const DmAppImageInfo &imageInfo, std::string &extra); + int32_t CheckAuthentication(std::string &authPara); + // int32_t GetAuthenticationParam(std::string &pkgName, DmAuthParam &authParam, std::shared_ptr prsp); + int32_t SetUserOperation(std::string &pkgName, int32_t action); + static int32_t GenRandInt(int32_t minPinToken, int32_t maxPinToken); +private: + int32_t CheckParamValid(nlohmann::json &extraJson, const DmAppImageInfo &imageInfo); +}; +} // namespace DistributedHardware +} // namespace OHOS +#endif // OHOS_DEVICE_MANAGER_MESSAGE_PROCESSING_H diff --git a/services/devicemanagerservice/include/dispatch/message_req.h b/services/devicemanagerservice/include/dispatch/message_req.h new file mode 100644 index 000000000..745ec0876 --- /dev/null +++ b/services/devicemanagerservice/include/dispatch/message_req.h @@ -0,0 +1,62 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef OHOS_DEVICE_MANAGER_MESSAGE_REQ_H +#define OHOS_DEVICE_MANAGER_MESSAGE_REQ_H + +#include + +#include "message_def.h" + +namespace OHOS { +namespace DistributedHardware { +class MessageReq { +DECLARE_MESSAGE_MODEL(MessageReq); +public: + const std::string& GetPkgName() const + { + return pkgName_; + } + + void SetPkgName(const std::string &pkgName) + { + pkgName_ = pkgName; + } +private: + std::string pkgName_; +}; +} // namespace DistributedHardware +} // namespace OHOS +#endif // OHOS_DEVICE_MANAGER_MESSAGE_REQ_H + +// namespace OHOS { +// namespace DistributedHardware { +// class IpcReq { +// DECLARE_IPC_MODEL(IpcReq); + +// public: +// const std::string &GetPkgName() const +// { +// return pkgName_; +// } + +// void SetPkgName(const std::string &pkgName) +// { +// pkgName_ = pkgName; +// } + +// private: +// std::string pkgName_; +// }; diff --git a/services/devicemanagerservice/include/dispatch/message_rsp.h b/services/devicemanagerservice/include/dispatch/message_rsp.h new file mode 100644 index 000000000..ab2c2f070 --- /dev/null +++ b/services/devicemanagerservice/include/dispatch/message_rsp.h @@ -0,0 +1,42 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef OHOS_DEVICE_MANAGER_MESSAGE_RSP_H +#define OHOS_DEVICE_MANAGER_MESSAGE_RSP_H + +#include + +#include "message_def.h" + +namespace OHOS { +namespace DistributedHardware { +class MessageRsp { +DECLARE_MESSAGE_MODEL(MessageRsp); +public: + int32_t GetErrCode() const + { + return errCode_; + } + + void SetErrCode(int32_t errCode) + { + errCode_ = errCode; + } +private: + int32_t errCode_; +}; +} // namespace DistributedHardware +} // namespace OHOS +#endif // OHOS_DEVICE_MANAGER_RSP_H diff --git a/services/devicemanagerservice/include/dispatch/server_init.h b/services/devicemanagerservice/include/dispatch/server_init.h new file mode 100644 index 000000000..9d0ac1e24 --- /dev/null +++ b/services/devicemanagerservice/include/dispatch/server_init.h @@ -0,0 +1,22 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef OHOS_DEVICE_MANAGER_SERVER_INIT_H +#define OHOS_DEVICE_MANAGER_SERVER_INIT_H + + +void Server_Init(); + +#endif // OHOS_DEVICE_MANAGER_SERVER_INIT_H diff --git a/services/devicemanagerservice/include/dispatch/server_stub.h b/services/devicemanagerservice/include/dispatch/server_stub.h new file mode 100644 index 000000000..7a50df58f --- /dev/null +++ b/services/devicemanagerservice/include/dispatch/server_stub.h @@ -0,0 +1,24 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef OHOS_DEVICE_MANAGER_SERVER_STUB_H +#define OHOS_DEVICE_MANAGER_SERVER_STUB_H + +#include +#include +//#include "liteipc_adapter.h" +#include + +#endif // OHOS_DEVICE_MANAGER_IPC_SERVER_STUB_H diff --git a/services/devicemanagerservice/include/dispatch/set_useroperation_req.h b/services/devicemanagerservice/include/dispatch/set_useroperation_req.h new file mode 100644 index 000000000..c60e61d0a --- /dev/null +++ b/services/devicemanagerservice/include/dispatch/set_useroperation_req.h @@ -0,0 +1,41 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef OHOS_DEVICE_MANAGER_GET_USER_OPERATION_REQ_H +#define OHOS_DEVICE_MANAGER_GET_USER_OPERATION_REQ_H +#include "message_req.h" +#include "dm_device_info.h" + +namespace OHOS { +namespace DistributedHardware { +class GetOperationReq : public MessageReq { +DECLARE_MESSAGE_MODEL(GetOperationReq); +public: + int32_t GetOperation() const + { + return action_; + } + + void SetOperation(int32_t action) + { + action_ = action; + } + +private: + int32_t action_ {0}; +}; +} // namespace DistributedHardware +} // namespace OHOS +#endif // OHOS_DEVICE_MANAGER_GET_USER_OPERATION_REQ_H diff --git a/services/devicemanagerservice/include/dispatch/start_discovery_req.h b/services/devicemanagerservice/include/dispatch/start_discovery_req.h new file mode 100644 index 000000000..b987fbd40 --- /dev/null +++ b/services/devicemanagerservice/include/dispatch/start_discovery_req.h @@ -0,0 +1,86 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef OHOS_DEVICE_MANAGER_START_DISCOVERY_REQ_H +#define OHOS_DEVICE_MANAGER_START_DISCOVERY_REQ_H + +#include "message_req.h" + +#include "dm_subscribe_info.h" + +namespace OHOS { +namespace DistributedHardware { +class StartDiscoveryReq : public MessageReq { +DECLARE_MESSAGE_MODEL(StartDiscoveryReq); +public: + const DmSubscribeInfo& GetSubscribeInfo() const + { + return subscribeInfo_; + } + + void SetSubscribeInfo(const DmSubscribeInfo &subscribeInfo) + { + subscribeInfo_ = subscribeInfo; + } + const std::string &GetExtra() const + { + return extra_; + } + + void SetExtra(const std::string &extra) + { + extra_ = extra; + } + +private: + std::string extra_; + DmSubscribeInfo subscribeInfo_; +}; +} // namespace DistributedHardware +} // namespace OHOS +#endif // OHOS_DEVICE_MANAGER_START_DISCOVERY_REQ_H + +// namespace OHOS { +// namespace DistributedHardware { +// class IpcStartDiscoveryReq : public IpcReq { +// DECLARE_IPC_MODEL(IpcStartDiscoveryReq); + +// public: +// const DmSubscribeInfo &GetSubscribeInfo() const +// { +// return subscribeInfo_; +// } + +// void SetSubscribeInfo(const DmSubscribeInfo &subscribeInfo) +// { +// subscribeInfo_ = subscribeInfo; +// } + +// const std::string &GetExtra() const +// { +// return extra_; +// } + +// void SetExtra(const std::string &extra) +// { +// extra_ = extra; +// } + +// private: +// std::string extra_; +// DmSubscribeInfo subscribeInfo_; +// }; +// } // namespace DistributedHardware +// } // namespace OHOS diff --git a/services/devicemanagerservice/include/dispatch/stop_discovery_req.h b/services/devicemanagerservice/include/dispatch/stop_discovery_req.h new file mode 100644 index 000000000..16afa9333 --- /dev/null +++ b/services/devicemanagerservice/include/dispatch/stop_discovery_req.h @@ -0,0 +1,42 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef OHOS_DEVICE_MANAGER_STOP_DISCOVERY_REQ_H +#define OHOS_DEVICE_MANAGER_STOP_DISCOVERY_REQ_H + +#include + +#include "message_req.h" + +namespace OHOS { +namespace DistributedHardware { +class StopDiscoveryReq : public MessageReq { +DECLARE_MESSAGE_MODEL(StopDiscoveryReq); +public: + uint16_t GetSubscribeId() const + { + return subscribeId_; + } + + void SetSubscribeId(uint16_t subscribeId) + { + subscribeId_ = subscribeId; + } +private: + uint16_t subscribeId_ {0}; +}; +} // namespace DistributedHardware +} // namespace OHOS +#endif // OHOS_DEVICE_MANAGER_STOP_DISCOVERY_REQ_H diff --git a/services/devicemanagerservice/include/dispatch/unauthenticate_device_req.h b/services/devicemanagerservice/include/dispatch/unauthenticate_device_req.h new file mode 100644 index 000000000..eebbf3604 --- /dev/null +++ b/services/devicemanagerservice/include/dispatch/unauthenticate_device_req.h @@ -0,0 +1,43 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef OHOS_DEVICE_MANAGER_UNAUTHENTICATE_DEVICE_REQ_H +#define OHOS_DEVICE_MANAGER_UNAUTHENTICATE_DEVICE_REQ_H + +#include "dm_device_info.h" +#include "message_req.h" + +namespace OHOS { +namespace DistributedHardware { +class UnAuthenticateDeviceReq : public MessageReq { + DECLARE_MESSAGE_MODEL(UnAuthenticateDeviceReq); + +public: + const DmDeviceInfo &GetDeviceInfo() const + { + return deviceInfo_; + } + + void SetDeviceInfo(const DmDeviceInfo &deviceInfo) + { + deviceInfo_ = deviceInfo; + } + +private: + DmDeviceInfo deviceInfo_; +}; +} // namespace DistributedHardware +} // namespace OHOS +#endif // OHOS_DEVICE_MANAGER_UNAUTHENTICATE_DEVICE_REQ_H diff --git a/services/devicemanagerservice/include/dispatch/verify_authenticate_req.h b/services/devicemanagerservice/include/dispatch/verify_authenticate_req.h new file mode 100644 index 000000000..c3ae0dccf --- /dev/null +++ b/services/devicemanagerservice/include/dispatch/verify_authenticate_req.h @@ -0,0 +1,62 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef OHOS_DEVICE_MANAGER_VERIFY_AUTHENTICATE_REQ_H +#define OHOS_DEVICE_MANAGER_VERIFY_AUTHENTICATE_REQ_H + +#include "message_req.h" + +namespace OHOS { +namespace DistributedHardware { +class VerifyAuthenticateReq : public MessageReq { +DECLARE_MESSAGE_MODEL(VerifyAuthenticateReq); +public: + const std::string& GetAuthPara() const + { + return authPara_; + } + + void SetAuthPara(const std::string &authPara) + { + authPara_ = authPara; + } +private: + std::string authPara_; +}; +} // namespace DistributedHardware +} // namespace OHOS +#endif // OHOS_DEVICE_MANAGER_CHECK_AUTHENTICATE_REQ_H + +// namespace OHOS { +// namespace DistributedHardware { +// class IpcVerifyAuthenticateReq : public IpcReq { +// DECLARE_IPC_MODEL(IpcVerifyAuthenticateReq); + +// public: +// const std::string &GetAuthPara() const +// { +// return authPara_; +// } + +// void SetAuthPara(const std::string &authPara) +// { +// authPara_ = authPara; +// } + +// private: +// std::string authPara_; +// }; +// } // namespace DistributedHardware +// } // namespace OHOS diff --git a/services/devicemanagerservice/src/device_manager_service.cpp b/services/devicemanagerservice/src/device_manager_service.cpp index cda681629..a0d03611e 100644 --- a/services/devicemanagerservice/src/device_manager_service.cpp +++ b/services/devicemanagerservice/src/device_manager_service.cpp @@ -17,16 +17,16 @@ #include -#include "common_event_support.h" +// #include "common_event_support.h" #include "device_manager_service_listener.h" -#include "dm_common_event_manager.h" +// #include "dm_common_event_manager.h" #include "dm_constants.h" -#include "dm_device_info_manager.h" +// #include "dm_device_info_manager.h" #include "dm_log.h" #include "multiple_user_connector.h" -#include "permission_manager.h" +// #include "permission_manager.h" -using namespace OHOS::EventFwk; +// using namespace OHOS::EventFwk; namespace OHOS { namespace DistributedHardware { @@ -35,12 +35,12 @@ IMPLEMENT_SINGLE_INSTANCE(DeviceManagerService); DeviceManagerService::~DeviceManagerService() { LOGI("DeviceManagerService destructor"); - DmCommonEventManager &dmCommonEventManager = DmCommonEventManager::GetInstance(); - if (dmCommonEventManager.UnsubscribeServiceEvent(CommonEventSupport::COMMON_EVENT_USER_STOPPED)) { - LOGI("subscribe service event success"); - } - softbusConnector_->GetSoftbusSession()->UnRegisterSessionCallback(); - hiChainConnector_->UnRegisterHiChainCallback(); + // DmCommonEventManager &dmCommonEventManager = DmCommonEventManager::GetInstance(); + // if (dmCommonEventManager.UnsubscribeServiceEvent(CommonEventSupport::COMMON_EVENT_USER_STOPPED)) { + // LOGI("subscribe service event success"); + // } + // softbusConnector_->GetSoftbusSession()->UnRegisterSessionCallback(); + // hiChainConnector_->UnRegisterHiChainCallback(); } int32_t DeviceManagerService::Init() @@ -50,76 +50,76 @@ int32_t DeviceManagerService::Init() return DM_INT_MULTIPLE; } - if (!PermissionManager::GetInstance().CheckPermission()) { - LOGI("The caller does not have permission to call"); - return DM_NO_PERMISSION; - } + // if (!PermissionManager::GetInstance().CheckPermission()) { + // LOGI("The caller does not have permission to call"); + // return DM_NO_PERMISSION; + // } - if (softbusConnector_ == nullptr) { - softbusConnector_ = std::make_shared(); - if (softbusConnector_ == nullptr) { - LOGE("Init failed, softbusConnector_ apply for failure"); - return DM_MAKE_SHARED_FAIL; - } - } - if (listener_ == nullptr) { - listener_ = std::make_shared(); - if (softbusConnector_ == nullptr) { - LOGE("Init failed, listener_ apply for failure"); - return DM_MAKE_SHARED_FAIL; - } - } - if (hiChainConnector_ == nullptr) { - hiChainConnector_ = std::make_shared(); - if (hiChainConnector_ == nullptr) { - LOGE("Init failed, hiChainConnector_ apply for failure"); - return DM_MAKE_SHARED_FAIL; - } - } - if (deviceInfoMgr_ == nullptr) { - deviceInfoMgr_ = std::make_shared(softbusConnector_); - if (deviceInfoMgr_ == nullptr) { - LOGE("Init failed, deviceInfoMgr_ apply for failure"); - return DM_MAKE_SHARED_FAIL; - } - } - if (deviceStateMgr_ == nullptr) { - deviceStateMgr_ = std::make_shared(softbusConnector_, listener_, hiChainConnector_); - if (deviceStateMgr_ == nullptr) { - LOGE("Init failed, deviceStateMgr_ apply for failure"); - return DM_MAKE_SHARED_FAIL; - } - deviceStateMgr_->RegisterSoftbusStateCallback(); - } - if (discoveryMgr_ == nullptr) { - discoveryMgr_ = std::make_shared(softbusConnector_, listener_); - if (discoveryMgr_ == nullptr) { - LOGE("Init failed, discoveryMgr_ apply for failure"); - return DM_MAKE_SHARED_FAIL; - } - } - if (authMgr_ == nullptr) { - authMgr_ = std::make_shared(softbusConnector_, listener_, hiChainConnector_); - if (authMgr_ == nullptr) { - LOGE("Init failed, authMgr_ apply for failure"); - return DM_MAKE_SHARED_FAIL; - } - softbusConnector_->GetSoftbusSession()->RegisterSessionCallback(authMgr_); - hiChainConnector_->RegisterHiChainCallback(authMgr_); - } + // if (softbusConnector_ == nullptr) { + // softbusConnector_ = std::make_shared(); + // if (softbusConnector_ == nullptr) { + // LOGE("Init failed, softbusConnector_ apply for failure"); + // return DM_MAKE_SHARED_FAIL; + // } + // } + // if (listener_ == nullptr) { + // listener_ = std::make_shared(); + // if (softbusConnector_ == nullptr) { + // LOGE("Init failed, listener_ apply for failure"); + // return DM_MAKE_SHARED_FAIL; + // } + // } + // if (hiChainConnector_ == nullptr) { + // hiChainConnector_ = std::make_shared(); + // if (hiChainConnector_ == nullptr) { + // LOGE("Init failed, hiChainConnector_ apply for failure"); + // return DM_MAKE_SHARED_FAIL; + // } + // } + // if (deviceInfoMgr_ == nullptr) { + // deviceInfoMgr_ = std::make_shared(softbusConnector_); + // if (deviceInfoMgr_ == nullptr) { + // LOGE("Init failed, deviceInfoMgr_ apply for failure"); + // return DM_MAKE_SHARED_FAIL; + // } + // } + // if (deviceStateMgr_ == nullptr) { + // deviceStateMgr_ = std::make_shared(softbusConnector_, listener_, hiChainConnector_); + // if (deviceStateMgr_ == nullptr) { + // LOGE("Init failed, deviceStateMgr_ apply for failure"); + // return DM_MAKE_SHARED_FAIL; + // } + // deviceStateMgr_->RegisterSoftbusStateCallback(); + // } + // if (discoveryMgr_ == nullptr) { + // discoveryMgr_ = std::make_shared(softbusConnector_, listener_); + // if (discoveryMgr_ == nullptr) { + // LOGE("Init failed, discoveryMgr_ apply for failure"); + // return DM_MAKE_SHARED_FAIL; + // } + // } + // if (authMgr_ == nullptr) { + // authMgr_ = std::make_shared(softbusConnector_, listener_, hiChainConnector_); + // if (authMgr_ == nullptr) { + // LOGE("Init failed, authMgr_ apply for failure"); + // return DM_MAKE_SHARED_FAIL; + // } + // softbusConnector_->GetSoftbusSession()->RegisterSessionCallback(authMgr_); + // hiChainConnector_->RegisterHiChainCallback(authMgr_); + // } - int32_t userId = MultipleUserConnector::GetCurrentAccountUserID(); - if (userId > 0) { - LOGI("get current account user id success"); - MultipleUserConnector::SetSwitchOldUserId(userId); - } + // int32_t userId = MultipleUserConnector::GetCurrentAccountUserID(); + // if (userId > 0) { + // LOGI("get current account user id success"); + // MultipleUserConnector::SetSwitchOldUserId(userId); + // } - DmCommonEventManager &dmCommonEventManager = DmCommonEventManager::GetInstance(); - CommomEventCallback callback = std::bind(&DmAuthManager::UserSwitchEventCallback, *authMgr_.get(), - std::placeholders::_1); - if (dmCommonEventManager.SubscribeServiceEvent(CommonEventSupport::COMMON_EVENT_USER_SWITCHED, callback)) { - LOGI("subscribe service user switch common event success"); - } + // DmCommonEventManager &dmCommonEventManager = DmCommonEventManager::GetInstance(); + // CommomEventCallback callback = std::bind(&DmAuthManager::UserSwitchEventCallback, *authMgr_.get(), + // std::placeholders::_1); + // if (dmCommonEventManager.SubscribeServiceEvent(CommonEventSupport::COMMON_EVENT_USER_SWITCHED, callback)) { + // LOGI("subscribe service user switch common event success"); + // } LOGI("Init success, singleton initialized"); intFlag_ = true; @@ -129,10 +129,10 @@ int32_t DeviceManagerService::Init() int32_t DeviceManagerService::GetTrustedDeviceList(const std::string &pkgName, const std::string &extra, std::vector &deviceList) { - if (!PermissionManager::GetInstance().CheckPermission()) { - LOGI("The caller does not have permission to call"); - return DM_NO_PERMISSION; - } + // if (!PermissionManager::GetInstance().CheckPermission()) { + // LOGI("The caller does not have permission to call"); + // return DM_NO_PERMISSION; + // } if (!intFlag_) { LOGE("GetTrustedDeviceList failed, singleton not init or init fail"); return DM_NOT_INIT; @@ -141,20 +141,22 @@ int32_t DeviceManagerService::GetTrustedDeviceList(const std::string &pkgName, c LOGE("GetTrustedDeviceList failed, pkgName is empty"); return DM_INPUT_PARA_EMPTY; } - return deviceInfoMgr_->GetTrustedDeviceList(pkgName, extra, deviceList); + // return deviceInfoMgr_->GetTrustedDeviceList(pkgName, extra, deviceList); + return 0; } int32_t DeviceManagerService::GetLocalDeviceInfo(DmDeviceInfo &info) { - if (!PermissionManager::GetInstance().CheckPermission()) { - LOGI("The caller does not have permission to call"); - return DM_NO_PERMISSION; - } + // if (!PermissionManager::GetInstance().CheckPermission()) { + // LOGI("The caller does not have permission to call"); + // return DM_NO_PERMISSION; + // } if (!intFlag_) { LOGE("GetLocalDeviceInfo failed, singleton not init or init fail"); return DM_NOT_INIT; } - return deviceInfoMgr_->GetLocalDeviceInfo(info); + // return deviceInfoMgr_->GetLocalDeviceInfo(info); + return 0; } int32_t DeviceManagerService::GetUdidByNetworkId(const std::string &pkgName, const std::string &netWorkId, @@ -169,7 +171,7 @@ int32_t DeviceManagerService::GetUdidByNetworkId(const std::string &pkgName, con LOGE("StartDeviceDiscovery failed, pkgName is empty"); return DM_INPUT_PARA_EMPTY; } - SoftbusConnector::GetUdidByNetworkId(netWorkId.c_str(), udid); + // SoftbusConnector::GetUdidByNetworkId(netWorkId.c_str(), udid); return DM_OK; } @@ -185,17 +187,17 @@ int32_t DeviceManagerService::GetUuidByNetworkId(const std::string &pkgName, con LOGE("StartDeviceDiscovery failed, pkgName is empty"); return DM_INPUT_PARA_EMPTY; } - SoftbusConnector::GetUuidByNetworkId(netWorkId.c_str(), uuid); + // SoftbusConnector::GetUuidByNetworkId(netWorkId.c_str(), uuid); return DM_OK; } int32_t DeviceManagerService::StartDeviceDiscovery(const std::string &pkgName, const DmSubscribeInfo &subscribeInfo, const std::string &extra) { - if (!PermissionManager::GetInstance().CheckPermission()) { - LOGI("The caller does not have permission to call"); - return DM_NO_PERMISSION; - } + // if (!PermissionManager::GetInstance().CheckPermission()) { + // LOGI("The caller does not have permission to call"); + // return DM_NO_PERMISSION; + // } if (!intFlag_) { LOGE("StartDeviceDiscovery failed, singleton not init or init fail"); return DM_NOT_INIT; @@ -204,15 +206,16 @@ int32_t DeviceManagerService::StartDeviceDiscovery(const std::string &pkgName, c LOGE("StartDeviceDiscovery failed, pkgName is empty"); return DM_INPUT_PARA_EMPTY; } - return discoveryMgr_->StartDeviceDiscovery(pkgName, subscribeInfo, extra); + // return discoveryMgr_->StartDeviceDiscovery(pkgName, subscribeInfo, extra); + return 0; } int32_t DeviceManagerService::StopDeviceDiscovery(const std::string &pkgName, uint16_t subscribeId) { - if (!PermissionManager::GetInstance().CheckPermission()) { - LOGI("The caller does not have permission to call"); - return DM_NO_PERMISSION; - } + // if (!PermissionManager::GetInstance().CheckPermission()) { + // LOGI("The caller does not have permission to call"); + // return DM_NO_PERMISSION; + // } if (!intFlag_) { LOGE("StopDeviceDiscovery failed, singleton not init or init fail"); return DM_NOT_INIT; @@ -221,16 +224,17 @@ int32_t DeviceManagerService::StopDeviceDiscovery(const std::string &pkgName, ui LOGE("StopDeviceDiscovery failed, pkgName is empty"); return DM_INPUT_PARA_EMPTY; } - return discoveryMgr_->StopDeviceDiscovery(pkgName, subscribeId); + // return discoveryMgr_->StopDeviceDiscovery(pkgName, subscribeId); + return 0; } int32_t DeviceManagerService::AuthenticateDevice(const std::string &pkgName, int32_t authType, const std::string &deviceId, const std::string &extra) { - if (!PermissionManager::GetInstance().CheckPermission()) { - LOGI("The caller does not have permission to call"); - return DM_NO_PERMISSION; - } + // if (!PermissionManager::GetInstance().CheckPermission()) { + // LOGI("The caller does not have permission to call"); + // return DM_NO_PERMISSION; + // } if (!intFlag_) { LOGE("AuthenticateDevice failed, singleton not init or init fail"); return DM_NOT_INIT; @@ -243,15 +247,16 @@ int32_t DeviceManagerService::AuthenticateDevice(const std::string &pkgName, int LOGE("AuthenticateDevice failed, deviceId is empty"); return DM_INPUT_PARA_EMPTY; } - return authMgr_->AuthenticateDevice(pkgName, authType, deviceId, extra); + // return authMgr_->AuthenticateDevice(pkgName, authType, deviceId, extra); + return 0; } int32_t DeviceManagerService::UnAuthenticateDevice(const std::string &pkgName, const std::string &deviceId) { - if (!PermissionManager::GetInstance().CheckPermission()) { - LOGI("The caller does not have permission to call"); - return DM_NO_PERMISSION; - } + // if (!PermissionManager::GetInstance().CheckPermission()) { + // LOGI("The caller does not have permission to call"); + // return DM_NO_PERMISSION; + // } if (!intFlag_) { LOGE("UnAuthenticateDevice failed, singleton not init or init fail"); return DM_NOT_INIT; @@ -264,20 +269,22 @@ int32_t DeviceManagerService::UnAuthenticateDevice(const std::string &pkgName, c LOGE("UnAuthenticateDevice failed, deviceId is empty"); return DM_INPUT_PARA_EMPTY; } - return authMgr_->UnAuthenticateDevice(pkgName, deviceId); + // return authMgr_->UnAuthenticateDevice(pkgName, deviceId); + return 0; } int32_t DeviceManagerService::VerifyAuthentication(const std::string &authParam) { - if (!PermissionManager::GetInstance().CheckPermission()) { - LOGI("The caller does not have permission to call"); - return DM_NO_PERMISSION; - } + // if (!PermissionManager::GetInstance().CheckPermission()) { + // LOGI("The caller does not have permission to call"); + // return DM_NO_PERMISSION; + // } if (!intFlag_) { LOGE("VerifyAuthentication failed, singleton not init or init fail"); return DM_NOT_INIT; } - return authMgr_->VerifyAuthentication(authParam); + // return authMgr_->VerifyAuthentication(authParam); + return 0; } int32_t DeviceManagerService::GetFaParam(std::string &pkgName, DmAuthParam &authParam) @@ -286,7 +293,7 @@ int32_t DeviceManagerService::GetFaParam(std::string &pkgName, DmAuthParam &auth LOGE("GetFaParam failed, pkgName is empty"); return DM_INPUT_PARA_EMPTY; } - authMgr_->GetAuthenticationParam(authParam); + // authMgr_->GetAuthenticationParam(authParam); return DM_OK; } @@ -296,19 +303,19 @@ int32_t DeviceManagerService::SetUserOperation(std::string &pkgName, int32_t act LOGE("SetUserOperation failed, pkgName is empty"); return DM_INPUT_PARA_EMPTY; } - authMgr_->OnUserOperation(action); + // authMgr_->OnUserOperation(action); return DM_OK; } int32_t DeviceManagerService::RegisterDevStateCallback(const std::string &pkgName, const std::string &extra) { - deviceStateMgr_->RegisterDevStateCallback(pkgName, extra); + // deviceStateMgr_->RegisterDevStateCallback(pkgName, extra); return DM_OK; } int32_t DeviceManagerService::UnRegisterDevStateCallback(const std::string &pkgName, const std::string &extra) { - deviceStateMgr_->UnRegisterDevStateCallback(pkgName, extra); + // deviceStateMgr_->UnRegisterDevStateCallback(pkgName, extra); return DM_OK; } } // namespace DistributedHardware diff --git a/services/devicemanagerservice/src/dispatch/command_dispatch.cpp b/services/devicemanagerservice/src/dispatch/command_dispatch.cpp new file mode 100644 index 000000000..b0cb74802 --- /dev/null +++ b/services/devicemanagerservice/src/dispatch/command_dispatch.cpp @@ -0,0 +1,215 @@ +/* + * Copyright (c) 2020 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +#include "message_processing.h" +#include "command_dispatch.h" +#include "dm_log.h" +#include "message_def.h" +#include "dm_constants.h" +// #include "device_manager_errno.h" +#include "server_stub.h" +#include "securec.h" +#include "dm_device_info.h" +#include "dm_subscribe_info.h" +#include "get_trustdevice_req.h" +#include "start_discovery_req.h" +#include "stop_discovery_req.h" +#include "set_useroperation_req.h" +#include "authenticate_device_req.h" +#include "verify_authenticate_req.h" +#include "get_authenticationparam_rsp.h" +#include "get_trustdevice_rsp.h" +#include "device_manager_service.h" + +#include "get_local_device_info_rsp.h" +#include "get_info_by_network_rsp.h" +#include "get_info_by_network_req.h" +#include "unauthenticate_device_req.h" +#include "get_dmfaparam_rsp.h" + +namespace OHOS { +namespace DistributedHardware{ +IMPLEMENT_SINGLE_INSTANCE(CommandDispatch); +int32_t CommandDispatch::MessageSendCmd(int32_t cmdCode, std::shared_ptr req, std::shared_ptr rsp) +{ + if (req == nullptr || rsp == nullptr) { + LOGE("Message req or rsp is null."); + return DM_INVALID_VALUE; + } + int32_t ret = CommandDispatch::CmdProcessing(cmdCode, req, rsp); + if (ret != DM_OK) { + LOGE("MessageSendCmd Failed with ret: %d", ret); + return ret; + } + return DM_OK; +} + +int32_t CommandDispatch::CmdProcessing(int32_t cmdCode, std::shared_ptr req, std::shared_ptr rsp) +{ + int32_t ret = 1; + LOGI("SendCmd:%d", cmdCode); + switch (cmdCode) { + case GET_TRUST_DEVICE_LIST: { + std::shared_ptr pReq = std::static_pointer_cast(req); + std::shared_ptr prsp = std::static_pointer_cast(rsp); + std::string pkgName = pReq->GetPkgName(); + std::string extra = pReq->GetExtra(); + + LOGI("enter GetTrustedDeviceList"); + // DmDeviceInfo *info = nullptr; + // int32_t infoNum = 0; + // ret = MessageProcessing::GetInstance().GetTrustedDeviceList(pkgName, extra, &info, &infoNum, prsp); + std::vector deviceList; + ret = DeviceManagerService::GetInstance().GetTrustedDeviceList(pkgName, extra, deviceList); + prsp->SetErrCode(ret); + break; + } + case GET_LOCAL_DEVICE_INFO: { + std::shared_ptr pRsp = std::static_pointer_cast(rsp); + DmDeviceInfo dmDeviceInfo = {0}; + int32_t ret = DeviceManagerService::GetInstance().GetLocalDeviceInfo(dmDeviceInfo); + DmDeviceInfo *Info = &dmDeviceInfo; + if (Info != nullptr) { + pRsp->SetLocalDeviceInfo(dmDeviceInfo); + } + pRsp->SetErrCode(ret); + break; + } + case GET_UDID_BY_NETWORK: { + std::shared_ptr pReq = std::static_pointer_cast(req); + std::shared_ptr pRsp = std::static_pointer_cast(rsp); + std::string pkgName = pReq->GetPkgName(); + std::string netWorkId = pReq->GetNetWorkId(); + std::string udid; + + ret = DeviceManagerService::GetInstance().GetUdidByNetworkId(pkgName, netWorkId, udid); + pRsp->SetUdid(udid); + pRsp->SetErrCode(ret); + break; + } + case GET_UUID_BY_NETWORK: { + std::shared_ptr pReq = std::static_pointer_cast(req); + std::shared_ptr pRsp = std::static_pointer_cast(rsp); + std::string pkgName = pReq->GetPkgName(); + std::string netWorkId = pReq->GetNetWorkId(); + std::string uuid; + + int32_t ret = DeviceManagerService::GetInstance().GetUuidByNetworkId(pkgName, netWorkId, uuid); + pRsp->SetUuid(uuid); + pRsp->SetErrCode(ret); + break; + } + case START_DEVICE_DISCOVER: { + std::shared_ptr pReq = std::static_pointer_cast(req); + std::string pkgName = pReq->GetPkgName(); + std::string extra = pReq->GetExtra(); + const DmSubscribeInfo dmSubscribeInfo = pReq->GetSubscribeInfo(); + LOGI("StartDeviceDiscovery service"); + + // ret = MessageProcessing::GetInstance().StartDeviceDiscovery(pkgName, dmSubscribeInfo); + int32_t ret = DeviceManagerService::GetInstance().StartDeviceDiscovery(pkgName, dmSubscribeInfo, extra); + rsp->SetErrCode(ret); + break; + } + case STOP_DEVICE_DISCOVER: { + LOGI("StopDeviceDiscovery service"); + + std::shared_ptr pReq = std::static_pointer_cast(req); + std::string pkgName = pReq->GetPkgName(); + uint16_t subscribeId = pReq->GetSubscribeId(); + // ret = MessageProcessing::GetInstance().StopDiscovery(pkgName, subscribeId); + ret = DeviceManagerService::GetInstance().StopDeviceDiscovery(pkgName, subscribeId); + rsp->SetErrCode(ret); + break; + } + case SERVER_USER_AUTH_OPERATION: { + std::shared_ptr pReq = std::static_pointer_cast(req); + std::string pkgName= pReq->GetPkgName(); + int32_t action = pReq->GetOperation(); + + LOGI("enter server user authorization operation."); + // ret = MessageProcessing::GetInstance().SetUserOperation(pkgName, action); + ret = DeviceManagerService::GetInstance().SetUserOperation(pkgName, action); + rsp->SetErrCode(ret); + break; + } + case SERVER_GET_DMFA_INFO: { + std::shared_ptr pReq = std::static_pointer_cast(req); + std::shared_ptr pRsp = std::static_pointer_cast(rsp); + std::string pkgName = pReq->GetPkgName(); + DmAuthParam authParam = { + .authToken = "", + .packageName = "", + .appName = "", + .appDescription = "", + .authType = 0, + .business = 0, + .pincode = 0, + .direction = 0, + .pinToken = 0 + }; + + LOGI("DeviceManagerStub:: GET_AUTHENTCATION_INFO:pkgName:%s", pkgName.c_str()); + // ret = MessageProcessing::GetInstance().GetAuthenticationParam(pkgName, authParam, prsp); + ret = DeviceManagerService::GetInstance().GetFaParam(pkgName, authParam); + pRsp->SetDmAuthParam(authParam); + pRsp->SetErrCode(ret); + break; + } + case AUTHENTICATE_DEVICE: { + std::shared_ptr pReq = std::static_pointer_cast(req); + std::string pkgName = pReq->GetPkgName(); + std::string extra = pReq->GetExtra(); + DmDeviceInfo deviceInfo = pReq->GetDeviceInfo(); + int32_t authType = pReq->GetAuthType(); + std::string deviceId = deviceInfo.deviceId; + // DmDeviceInfo deviceInfo = pReq->GetDeviceInfo(); + // DmAppImageInfo imageInfo(nullptr, 0, nullptr, 0); + + LOGI("DeviceManagerStub:: AUTHENTCATION_DEVICE:pkgName:%s", pkgName.c_str()); + // ret = MessageProcessing::GetInstance().AuthenticateDevice(pkgName, deviceInfo, imageInfo, extra); + ret = DeviceManagerService::GetInstance().AuthenticateDevice(pkgName, authType, deviceId, extra); + rsp->SetErrCode(ret); + break; + } + case UNAUTHENTICATE_DEVICE: { + std::shared_ptr pReq = std::static_pointer_cast(req); + std::string pkgName = pReq->GetPkgName(); + DmDeviceInfo deviceInfo = pReq->GetDeviceInfo(); + std::string deviceId = deviceInfo.deviceId; + + LOGI("enter server user authorization operation."); + ret = DeviceManagerService::GetInstance().UnAuthenticateDevice(pkgName, deviceId); + rsp->SetErrCode(ret); + break; + } + case VERIFY_AUTHENTICATION: { + std::shared_ptr pReq = std::static_pointer_cast(req); + std::string pkgName = pReq->GetPkgName(); + std::string authParam = pReq->GetAuthPara(); + + LOGI("DeviceManagerStub:: VERIFY_AUTHENTCATION:pkgName:%s", pkgName.c_str()); + // ret = MessageProcessing::GetInstance().CheckAuthentication(authPara); + ret = DeviceManagerService::GetInstance().VerifyAuthentication(authParam); + rsp->SetErrCode(ret); + break; + } + + default: + break; + } + return ret; +} +} +} \ No newline at end of file diff --git a/services/devicemanagerservice/src/dispatch/device_manager_service_listener_mini.cpp b/services/devicemanagerservice/src/dispatch/device_manager_service_listener_mini.cpp new file mode 100644 index 000000000..7cee13f5e --- /dev/null +++ b/services/devicemanagerservice/src/dispatch/device_manager_service_listener_mini.cpp @@ -0,0 +1,98 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "device_manager_service_listener.h" + +#include "dm_anonymous.h" +#include "dm_constants.h" +#include "dm_log.h" + +#include "device_manager_notify.h" + +namespace OHOS { +namespace DistributedHardware { +void DeviceManagerServiceListener::OnDeviceStateChange(const std::string &pkgName, const DmDeviceState &state, + const DmDeviceInfo &info) +{ + LOGI("call OnDeviceStateChange, state=%d", state); + std::list pkgNameList = DeviceManagerNotify::GetInstance().GetPkgNameList(); + for( auto pkgName : pkgNameList) { + DmDeviceState deviceState = static_cast(state); + if (pkgName == "") { + LOGE("OnDeviceOnline, get para failed"); + return; + } + switch (deviceState) { + case DEVICE_STATE_ONLINE: + DeviceManagerNotify::GetInstance().OnDeviceOnline(pkgName, info); + break; + case DEVICE_STATE_OFFLINE: + DeviceManagerNotify::GetInstance().OnDeviceOffline(pkgName, info); + break; + case DEVICE_INFO_CHANGED: + DeviceManagerNotify::GetInstance().OnDeviceChanged(pkgName, info); + break; + default: + LOGE("unknown device state:%d", deviceState); + break; + } + } +} + +void DeviceManagerServiceListener::OnDeviceFound(const std::string &pkgName, uint16_t subscribeId, + const DmDeviceInfo &info) +{ + LOGI("call OnDeviceFound for %s, originId %d, deviceId %s", pkgName.c_str(), subscribeId, + GetAnonyString(std::string(info.deviceId)).c_str()); + DeviceManagerNotify::GetInstance().OnDeviceFound(pkgName, subscribeId, info); +} + +void DeviceManagerServiceListener::OnDiscoveryFailed(const std::string &pkgName, uint16_t subscribeId, + int32_t failedReason) +{ + LOGI("call OnDiscoveryFailed"); + DeviceManagerNotify::GetInstance().OnDiscoveryFailed(pkgName, subscribeId, failedReason); +} + +void DeviceManagerServiceListener::OnDiscoverySuccess(const std::string &pkgName, int32_t subscribeId) +{ + LOGI("call OnDiscoverySuccess"); + DeviceManagerNotify::GetInstance().OnDiscoverySuccess(pkgName, subscribeId); +} + +void DeviceManagerServiceListener::OnAuthResult(const std::string &pkgName, const std::string &deviceId, + const std::string &token, int32_t status, int32_t reason) +{ + LOGI("call package: %s, deviceId: %s", pkgName.c_str(), GetAnonyString(deviceId).c_str()); + DeviceManagerNotify::GetInstance().OnAuthResult(pkgName, deviceId, nullptr, status, reason); +} + +void DeviceManagerServiceListener::OnVerifyAuthResult(const std::string &pkgName, const std::string &deviceId, + int32_t resultCode, const std::string &flag) +{ + LOGI("call OnVerifyAuthResult"); + std::list pkgNameList = DeviceManagerNotify::GetInstance().GetPkgNameList(); + for( auto pkgName : pkgNameList) { + DeviceManagerNotify::GetInstance().OnVerifyAuthResult(pkgName, deviceId, resultCode, flag); + } +} + +void DeviceManagerServiceListener::OnFaCall(std::string &pkgName, std::string ¶mJson) +{ + LOGI("call OnFaCall in"); + DeviceManagerNotify::GetInstance().OnFaCall(pkgName, paramJson); +} +} // namespace DistributedHardware +} // namespace OHOS diff --git a/services/devicemanagerservice/src/dispatch/message_processing.cpp b/services/devicemanagerservice/src/dispatch/message_processing.cpp new file mode 100644 index 000000000..f6652b912 --- /dev/null +++ b/services/devicemanagerservice/src/dispatch/message_processing.cpp @@ -0,0 +1,244 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +#include + +#include "securec.h" +#include "softbus_bus_center.h" +// #include "softbus_adapter.h" +// #include "anonymous_string.h" +#include "dm_anonymous.h" +// #include "auth_manager.h" +#include "dm_constants.h" +// #include "device_manager_errno.h" +// #include "device_manager_log.h" +#include "dm_log.h" +#include "dm_ability_manager.h" +// #include "encrypt_utils.h" +#include "message_processing.h" +#include "get_trustdevice_rsp.h" +#include "get_authenticationparam_rsp.h" + + + +namespace OHOS { +namespace DistributedHardware { + +IMPLEMENT_SINGLE_INSTANCE(MessageProcessing); + +int32_t MessageProcessing::CheckParamValid(nlohmann::json &extraJson, const DmAppImageInfo &imageInfo) +{ + if (!extraJson.contains(APP_NAME_KEY) || + !extraJson.contains(APP_DESCRIPTION_KEY) || + !extraJson.contains(AUTH_TYPE)) { + DMLOG(DM_LOG_ERROR, "Invalid para"); + return DM_INVALID_VALUE; + } + + std::string appName = extraJson[APP_NAME_KEY]; + std::string appDescription = extraJson[APP_DESCRIPTION_KEY]; + + if (appName.empty() || appDescription.empty()) { + DMLOG(DM_LOG_ERROR, "Invalid app image info"); + return DM_INVALID_VALUE; + } + if (extraJson[AUTH_TYPE] != AUTH_TYPE_PIN) { + DMLOG(DM_LOG_ERROR, "invalid auth type, only support pin auth"); + return DM_INVALID_VALUE; + } + return DM_OK; +} + +int32_t MessageProcessing::GenRandInt(int32_t randMin, int32_t randMax) +{ + std::random_device randDevice; + std::mt19937 genRand(randDevice()); + std::uniform_int_distribution disRand(randMin, randMax); + return disRand(genRand); +} + +int32_t MessageProcessing::GetTrustedDeviceList(std::string &pkgName, std::string &extra, + DmDeviceInfo **info, int32_t *infoNum, std::shared_ptr prsp) +{ + if (info == nullptr || infoNum == nullptr) { + return DM_INVALID_VALUE; + } + DMLOG(DM_LOG_INFO, "In, pkgName: %s", pkgName.c_str()); + + std::vector deviceInfoVec; + + NodeBasicInfo *nodeInfo = nullptr; + *info = nullptr; + *infoNum = 0; + + int32_t ret = SoftbusAdapter::GetTrustDevices(pkgName, &nodeInfo, infoNum); + if (ret != DM_OK || *infoNum <= 0 || nodeInfo == nullptr) { + DMLOG(DM_LOG_ERROR, "GetTrustDevices errCode:%d, num:%d", ret, *infoNum); + return ret; + } + + *info = (DmDeviceInfo *)malloc(sizeof(DmDeviceInfo) * (*infoNum)); + if (*info == nullptr) { + FreeNodeInfo(nodeInfo); + return DM_MALLOC_ERROR; + } + + for (int32_t i = 0; i < *infoNum; ++i) { + NodeBasicInfo *nodeBasicInfo = nodeInfo + i; + DmDeviceInfo *deviceInfo = *info + i; + if (memcpy_s(deviceInfo->deviceId, sizeof(deviceInfo->deviceId), nodeBasicInfo->networkId, + std::min(sizeof(deviceInfo->deviceId), sizeof(nodeBasicInfo->networkId))) != DM_OK) { + DMLOG(DM_LOG_ERROR, "memcpy failed"); + } + if (memcpy_s(deviceInfo->deviceName, sizeof(deviceInfo->deviceName), nodeBasicInfo->deviceName, + std::min(sizeof(deviceInfo->deviceName), sizeof(nodeBasicInfo->deviceName))) != DM_OK) { + DMLOG(DM_LOG_ERROR, "memcpy failed"); + } + deviceInfo->deviceTypeId = (DMDeviceType)nodeBasicInfo->deviceTypeId; + deviceInfoVec.emplace_back(*deviceInfo); + } + prsp->SetDeviceVec(deviceInfoVec); + + FreeNodeInfo(nodeInfo); + free(info); + DMLOG(DM_LOG_INFO, "success, pkgName:%s, deviceCount %d", pkgName.c_str(), *infoNum); + return DM_OK; +} + +int32_t MessageProcessing::StartDeviceDiscovery(std::string &pkgName,const DmSubscribeInfo &dmSubscribeInfo) +{ + DMLOG(DM_LOG_INFO, "In, pkgName: %s, subscribeId %d", pkgName.c_str(), + (int32_t)dmSubscribeInfo.subscribeId); + + DMLOG(DM_LOG_INFO, "capability: %s", dmSubscribeInfo.capability); + SubscribeInfo subscribeInfo; + + subscribeInfo.subscribeId = dmSubscribeInfo.subscribeId; + subscribeInfo.mode = (DiscoverMode)dmSubscribeInfo.mode; + subscribeInfo.medium = (ExchanageMedium)dmSubscribeInfo.medium; + subscribeInfo.freq = (ExchangeFreq)dmSubscribeInfo.freq; + subscribeInfo.isSameAccount = dmSubscribeInfo.isSameAccount; + subscribeInfo.isWakeRemote = dmSubscribeInfo.isWakeRemote; + subscribeInfo.capability = dmSubscribeInfo.capability; + subscribeInfo.capabilityData = nullptr; + subscribeInfo.dataLen = 0; + return SoftbusAdapter::StartDiscovery(pkgName, &subscribeInfo); +} + +int32_t MessageProcessing::StopDiscovery(std::string &pkgName, uint16_t subscribeId) +{ + DMLOG(DM_LOG_INFO, "In, pkgName: %s, subscribeId %d", pkgName.c_str(), (int32_t)subscribeId); + return SoftbusAdapter::StopDiscovery(pkgName, subscribeId); +} + +int32_t MessageProcessing::SetUserOperation(std::string &pkgName, int32_t action) +{ + if (pkgName.empty()) { + DMLOG(DM_LOG_ERROR, "invalid para"); + return DM_INVALID_VALUE; + } + + AuthManager::GetInstance().OnUserOperate(action); + return SUCCESS; +} + +int32_t MessageProcessing::GetAuthenticationParam(std::string &pkgName, DmAuthParam &authParam, std::shared_ptr prsp) +{ + DmAuthParam authParamside = { + .packageName = "", + .appName = "", + .appDescription = "", + .authType = 0, + .business = 0, + .pincode = 0, + .direction = 0, + .pinToken = 0 + }; + + if (pkgName.empty()) { + DMLOG(DM_LOG_ERROR, "invalid para"); + return DM_INVALID_VALUE; + } + + DmAbilityManager::GetInstance().StartAbilityDone(); + AuthManager::GetInstance().GetAuthenticationParam(authParam); + + authParamside.direction = authParam.direction; + authParamside.authType = authParam.authType; + if (authParamside.direction == AUTH_SESSION_SIDE_CLIENT) { + authParamside.pinToken = authParam.pinToken; + prsp->SetAuthParam(authParamside); + + DMLOG(DM_LOG_DEBUG, "DeviceManagerStub::is Client so just return direction"); + return DM_OK; + } + + authParamside.packageName = authParam.packageName; + authParamside.appName = authParam.appName; + authParamside.appDescription = authParam.appDescription; + authParamside.business = authParam.business; + authParamside.pincode = authParam.pincode; + + int32_t appIconLen = authParam.imageinfo.GetAppIconLen(); + int32_t appThumbnailLen = authParam.imageinfo.GetAppThumbnailLen(); + uint8_t *appIconBuffer = nullptr; + uint8_t *appThumbBuffer = nullptr; + if (appIconLen > 0 && authParam.imageinfo.GetAppIcon() != nullptr) { + appIconBuffer = const_cast(authParam.imageinfo.GetAppIcon()); + } + if (appThumbnailLen > 0 && authParam.imageinfo.GetAppThumbnail() != nullptr) { + appThumbBuffer = const_cast(authParam.imageinfo.GetAppThumbnail()); + } + + authParamside.imageinfo.Reset(appIconBuffer, appIconLen, appThumbBuffer, appThumbnailLen); + prsp->SetAuthParam(authParamside); + return DM_OK; +} + +int32_t MessageProcessing::AuthenticateDevice(std::string &pkgName, const DmDeviceInfo &deviceInfo, + const DmAppImageInfo &imageInfo, std::string &extra) +{ + if (pkgName.empty() || extra.empty()) { + DMLOG(DM_LOG_ERROR, "invalid para"); + return DM_INVALID_VALUE; + } + nlohmann::json jsonObject = nlohmann::json::parse(extra, nullptr, false); + if (jsonObject.is_discarded()) { + DMLOG(DM_LOG_ERROR, "AuthenticateDevice extra jsonStr error"); + return DM_INVALID_VALUE; + } + int32_t ret = CheckParamValid(jsonObject, imageInfo); + if (ret != DM_OK) { + DMLOG(DM_LOG_ERROR, "AuthenticateDevice para invalid, ret %d", ret); + return ret; + } + DMLOG(DM_LOG_INFO, "AuthenticateDevice In, pkgName: %s, deviceId %s", pkgName.c_str(), + GetAnonyString(deviceInfo.deviceId).c_str()); + + AuthManager::GetInstance().AuthDeviceGroup(pkgName, deviceInfo, imageInfo, extra); + return DM_OK; +} + +int32_t MessageProcessing::CheckAuthentication(std::string &authPara) +{ + if (authPara.empty()) { + DMLOG(DM_LOG_INFO, " DeviceManagerIpcAdapter::CheckAuthentication check authPara failed"); + return DM_INVALID_VALUE; + } + DMLOG(DM_LOG_INFO, " DeviceManagerIpcAdapter::CheckAuthentication"); + return AuthManager::GetInstance().CheckAuthentication(authPara); +} + +} // namespace DistributedHardware +} // namespace OHOS diff --git a/services/devicemanagerservice/src/dispatch/server_init.cpp b/services/devicemanagerservice/src/dispatch/server_init.cpp new file mode 100644 index 000000000..62f333481 --- /dev/null +++ b/services/devicemanagerservice/src/dispatch/server_init.cpp @@ -0,0 +1,46 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include +#include + +#include "dm_log.h" +// #include "device_manager_errno.h" +#include "hichain_connector.h" +#include "server_stub.h" +#include "server_init.h" +#include "samgr_lite.h" +// #include "softbus_adapter.h" + +using namespace OHOS::DistributedHardware; + +void Server_Init() +{ + const int32_t DM_SERVICE_INIT_DELAY = 2; + + sleep(DM_SERVICE_INIT_DELAY); + SAMGR_Bootstrap(); + + if (SoftbusAdapter::Init() != DEVICEMANAGER_OK) { + DMLOG(DM_LOG_ERROR, "softbus adapter init failed"); + return; + } + if (HichainConnector::GetInstance().Init() != DEVICEMANAGER_OK) { + DMLOG(DM_LOG_ERROR, "hichain connector init failed"); + return; + } + + DMLOG(DM_LOG_INFO, "DM server Init success"); +} diff --git a/services/devicemanagerservice/src/dispatch/server_stub.cpp b/services/devicemanagerservice/src/dispatch/server_stub.cpp new file mode 100644 index 000000000..7ee28253e --- /dev/null +++ b/services/devicemanagerservice/src/dispatch/server_stub.cpp @@ -0,0 +1,119 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "server_stub.h" +#include "server_init.h" + +#include "securec.h" + + +#include "ohos_init.h" +#include "samgr_lite.h" +#include "iproxy_server.h" + +#include "dm_log.h" +// #include "device_manager_errno.h" +#include "dm_subscribe_info.h" + +#include "message_def.h" + + +namespace { + const int32_t WAIT_FOR_SERVER = 2; + const int32_t STACK_SIZE = 0x1000; + const int32_t QUEUE_SIZE = 32; +} + +using namespace OHOS::DistributedHardware; + +struct DefaultFeatureApi { + INHERIT_SERVER_IPROXY; +}; + +struct DeviceManagerSamgrService { + INHERIT_SERVICE; + INHERIT_IUNKNOWNENTRY(DefaultFeatureApi); + Identity identity; +}; + + +static const char *GetName(Service *service) +{ + (void)service; + return DEVICE_MANAGER_SERVICE_NAME; +} + +static BOOL Initialize(Service *service, Identity identity) +{ + if (service == NULL) { + LOGW("Initialize invalid param"); + return FALSE; + } + // static int8_t InitFlag = 0; + // if (InitFlag == 0) { + // Server_Init(); + // InitFlag ++; + // LOGI("DevMgrSvcInit InitFlag is : %d", InitFlag); + // } + + + DeviceManagerSamgrService *mgrService = (DeviceManagerSamgrService *)service; + mgrService->identity = identity; + return TRUE; +} + +static BOOL MessageHandle(Service *service, Request *request) +{ + if ((service == NULL) || (request == NULL)) { + LOGW("MessageHandle invalid param"); + return FALSE; + } + return TRUE; +} + +static TaskConfig GetTaskConfig(Service *service) +{ + (void)service; + TaskConfig config = {LEVEL_HIGH, PRI_BELOW_NORMAL, STACK_SIZE, QUEUE_SIZE, SHARED_TASK}; + return config; +} + + + + +static void DevMgrSvcInit(void) +{ + sleep(WAIT_FOR_SERVER); + static DeviceManagerSamgrService service = { + .GetName = GetName, + .Initialize = Initialize, + .MessageHandle = MessageHandle, + .GetTaskConfig = GetTaskConfig, + SERVER_IPROXY_IMPL_BEGIN, + .Invoke = NULL, + IPROXY_END, + }; + + if (!SAMGR_GetInstance()->RegisterService((Service *)&service)) { + LOGE("%s, RegisterService failed", DEVICE_MANAGER_SERVICE_NAME); + return; + } + if (!SAMGR_GetInstance()->RegisterDefaultFeatureApi(DEVICE_MANAGER_SERVICE_NAME, GET_IUNKNOWN(service))) { + LOGE("%s, RegisterDefaultFeatureApi failed", DEVICE_MANAGER_SERVICE_NAME); + return; + } + LOGI("%s, init success", DEVICE_MANAGER_SERVICE_NAME); +} +SYSEX_SERVICE_INIT(DevMgrSvcInit); diff --git a/services/devicemanagerservice/src/dispatch/server_stub_bak.cpp b/services/devicemanagerservice/src/dispatch/server_stub_bak.cpp new file mode 100644 index 000000000..bb83afe69 --- /dev/null +++ b/services/devicemanagerservice/src/dispatch/server_stub_bak.cpp @@ -0,0 +1,114 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "server_stub.h" +#include "server_init.h" + +#include "securec.h" + + +#include "ohos_init.h" +#include "samgr_lite.h" + + +#include "device_manager_log.h" +#include "device_manager_errno.h" +#include "dm_subscribe_info.h" + +#include "message_def.h" + + +namespace { + const int32_t WAIT_FOR_SERVER = 2; + const int32_t STACK_SIZE = 0x1000; + const int32_t QUEUE_SIZE = 32; +} + +using namespace OHOS::DistributedHardware; + +struct DefaultFeatureApi { +// INHERIT_SERVER_IPROXY; +}; + +struct DeviceManagerSamgrService { + INHERIT_SERVICE; + INHERIT_IUNKNOWNENTRY(DefaultFeatureApi); + Identity identity; +}; + + +static const char *GetName(Service *service) +{ + (void)service; + return DEVICE_MANAGER_SERVICE_NAME; +} + +static BOOL Initialize(Service *service, Identity identity) +{ + if (service == NULL) { + DMLOG(DM_LOG_WARN, "invalid param"); + return FALSE; + } + + Server_Init(); + + DeviceManagerSamgrService *mgrService = (DeviceManagerSamgrService *)service; + mgrService->identity = identity; + return TRUE; +} + +static BOOL MessageHandle(Service *service, Request *request) +{ + if ((service == NULL) || (request == NULL)) { + DMLOG(DM_LOG_WARN, "invalid param"); + return FALSE; + } + return TRUE; +} + +static TaskConfig GetTaskConfig(Service *service) +{ + (void)service; + TaskConfig config = {LEVEL_HIGH, PRI_BELOW_NORMAL, STACK_SIZE, QUEUE_SIZE, SHARED_TASK}; + return config; +} + + + + +static void DevMgrSvcInit(void) +{ + sleep(WAIT_FOR_SERVER); + static DeviceManagerSamgrService service = { + .GetName = GetName, + .Initialize = Initialize, + .MessageHandle = MessageHandle, + .GetTaskConfig = GetTaskConfig, + // SERVER_IPROXY_IMPL_BEGIN, + // .Invoke = OnRemoteRequest, + // IPROXY_END, + }; + + if (!SAMGR_GetInstance()->RegisterService((Service *)&service)) { + DMLOG(DM_LOG_ERROR, "%s, RegisterService failed", DEVICE_MANAGER_SERVICE_NAME); + return; + } + if (!SAMGR_GetInstance()->RegisterDefaultFeatureApi(DEVICE_MANAGER_SERVICE_NAME, GET_IUNKNOWN(service))) { + DMLOG(DM_LOG_ERROR, "%s, RegisterDefaultFeatureApi failed", DEVICE_MANAGER_SERVICE_NAME); + return; + } + DMLOG(DM_LOG_INFO, "%s, init success", DEVICE_MANAGER_SERVICE_NAME); +} +SYSEX_SERVICE_INIT(DevMgrSvcInit); -- Gitee From 44e08540349f301c0151b22ed28796563e9908b5 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Convert=2EToInt32=28=E9=98=BF=E4=BC=A6=29?= <619269320@qq.com> Date: Tue, 8 Mar 2022 11:22:08 +0000 Subject: [PATCH 02/19] =?UTF-8?q?!26=20fix:JSI=E9=83=A8=E5=88=86=E4=BB=A3?= =?UTF-8?q?=E7=A0=81=E6=95=B4=E6=94=B9=EF=BC=8C=E8=8E=B7=E5=8F=96bundleNam?= =?UTF-8?q?e=E6=96=B0=E6=96=B9=E6=B3=95=EF=BC=8C=E6=96=B0=E5=A2=9E?= =?UTF-8?q?=E6=8E=A5=E5=8F=A3=E3=80=82=20*=20bug:JSI=E9=83=A8=E5=88=86?= =?UTF-8?q?=E4=BB=A3=E7=A0=81=E6=95=B4=E6=94=B9=EF=BC=8C=E8=8E=B7=E5=8F=96?= =?UTF-8?q?bundleName=E6=96=B0=E6=96=B9=E6=B3=95=EF=BC=8C=E6=96=B0?= =?UTF-8?q?=E5=A2=9E=E6=8E=A5=E5=8F=A3?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- interfaces_mini/kits/js/BUILD.gn | 105 ++ .../kits/js/include/dm_native_event.h | 60 + .../kits/js/include/native_devicemanager_js.h | 186 +++ .../kits/js/src/dm_native_event.cpp | 105 ++ .../kits/js/src/native_devicemanager_js.cpp | 1206 +++++++++++++++++ 5 files changed, 1662 insertions(+) create mode 100644 interfaces_mini/kits/js/BUILD.gn create mode 100644 interfaces_mini/kits/js/include/dm_native_event.h create mode 100644 interfaces_mini/kits/js/include/native_devicemanager_js.h create mode 100644 interfaces_mini/kits/js/src/dm_native_event.cpp create mode 100644 interfaces_mini/kits/js/src/native_devicemanager_js.cpp diff --git a/interfaces_mini/kits/js/BUILD.gn b/interfaces_mini/kits/js/BUILD.gn new file mode 100644 index 000000000..fd6f6c1c4 --- /dev/null +++ b/interfaces_mini/kits/js/BUILD.gn @@ -0,0 +1,105 @@ +# Copyright (C) 2021 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +if (defined(ohos_lite)) { + import("//build/lite/config/component/lite_component.gni") +} else { + import("//build/ohos.gni") +} + +import("//foundation/distributedhardware/devicemanager/devicemanager.gni") + +if (ohos_kernel_type == "liteos_m") { + static_library("devicemanager") { + include_dirs = [ + "//third_party/node/src", + "//third_party/json/include", + "${common_path}/include", + "//utils/native/base/include", + "include", + "${utils_path}/include/log", + "//foundation/ace/ace_engine_lite/interfaces/innerkits/builtin/base", + "//foundation/ace/ace_engine_lite/interfaces/innerkits/builtin/jsi", + "//foundation/ace/ace_engine_lite/interfaces/innerkits/builtin/async", + "//foundation/ace/ace_engine_lite/frameworks/src/core/context/js_app_context.h", + "${innerkits_path}/native_cpp/include", + ] + + sources = [ + "src/dm_native_event.cpp", + "src/native_devicemanager_js.cpp", + ] + + deps = [ + "${utils_path}:devicemanagerutils_mini", + "//foundation/distributedhardware/devicemanager/interfaces_small/inner_kits/native_cpp:devicemanagersdk_mini", + ] + + defines = [ + "HI_LOG_ENABLE", + "DH_LOG_TAG=\"devicemanagerkit_js\"", + "LOG_DOMAIN=0xD004100", + ] + } +} else { + ohos_shared_library("devicemanager") { + include_dirs = [ + "//third_party/node/src", + "//third_party/json/include", + "${common_path}/include", + "//foundation/ace/napi/native_engine", + "//foundation/ace/napi/interfaces/kits", + "//utils/native/base/include", + "include", + "${utils_path}/include/log", + "${common_path}/include/ipc", + "${innerkits_path}/native_cpp/include", + "${innerkits_path}/native_cpp/include/standard", + ] + + sources = [ + "src/dm_native_event.cpp", + "src/native_devicemanager_js.cpp", + ] + + deps = [ + "${utils_path}:devicemanagerutils", + "//foundation/ace/napi:ace_napi", + "//foundation/distributedhardware/devicemanager/interfaces/inner_kits/native_cpp:devicemanagersdk", + "//utils/native/base:utils", + ] + + defines = [ + "HI_LOG_ENABLE", + "DH_LOG_TAG=\"devicemanagerkit_js\"", + "LOG_DOMAIN=0xD004100", + ] + + external_deps = [ + "appexecfwk_standard:appexecfwk_base", + "appexecfwk_standard:appexecfwk_core", + "hiviewdfx_hilog_native:libhilog", + "ipc:ipc_core", + "safwk:system_ability_fwk", + "samgr_standard:samgr_proxy", + ] + + subsystem_name = "distributedhardware" + relative_install_dir = "module/distributedhardware" + part_name = "device_manager_base" + } +} + +group("devicemanager_native_js") { + deps = [ ":devicemanager" ] +} diff --git a/interfaces_mini/kits/js/include/dm_native_event.h b/interfaces_mini/kits/js/include/dm_native_event.h new file mode 100644 index 000000000..d2975263a --- /dev/null +++ b/interfaces_mini/kits/js/include/dm_native_event.h @@ -0,0 +1,60 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +// +#ifndef OHOS_DEVICE_MANAGER_NATIVE_EVENT_H +#define OHOS_DEVICE_MANAGER_NATIVE_EVENT_H + +#include +#include +#include +#include "jsi.h" +#include "dm_device_info.h" + +using namespace std; + +namespace OHOS { +namespace ACELite { + +struct DmEventListener{ + std::string eventType; + JSIValue handlerRef = JSI::CreateUndefined(); + JSIValue thisVarRef_ = JSI::CreateUndefined(); +}; + +struct FuncParams { + JSIValue handlerRef = JSI::CreateUndefined(); + JSIValue thisVarRef_ = JSI::CreateUndefined(); + const JSIValue *args = nullptr; + uint8_t argsSize = 0; +}; + + +class DmNativeEvent{ +public: + DmNativeEvent(); + DmNativeEvent(JSIValue thisVar); + virtual ~DmNativeEvent(); + virtual void On(std::string &eventType, JSIValue handler, JSIValue thisVal); + virtual void Off(std::string &eventType); + virtual void OnEvent(const std::string &eventType, uint8_t argsSize, const JSIValue *data); + static void OnEventAsyncWorkFunc(void *data); +protected: + static std::map> eventMap_; +}; + +} +} + +#endif /* OHOS_DEVICE_MANAGER_NATIVE_EVENT_H */ \ No newline at end of file diff --git a/interfaces_mini/kits/js/include/native_devicemanager_js.h b/interfaces_mini/kits/js/include/native_devicemanager_js.h new file mode 100644 index 000000000..1d914c94b --- /dev/null +++ b/interfaces_mini/kits/js/include/native_devicemanager_js.h @@ -0,0 +1,186 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef OHOS_DEVICE_MANAGER_NATIVE_DEVICEMANAGER_JS_H +#define OHOS_DEVICE_MANAGER_NATIVE_DEVICEMANAGER_JS_H + +#include +#include +#include "device_manager_callback.h" +#include "dm_native_event.h" +#include "dm_device_info.h" +#include "dm_subscribe_info.h" +#include "nlohmann/json.hpp" +#include "dm_device_info.h" +#include "jsi.h" +#include +#include "js_ability.h" +#include "dm_app_image_info.h" + +namespace OHOS { +namespace ACELite { + +#define DM_JSI_BUF_LENGTH (256) + +struct AuthFuncParams { + JSIValue handlerRef = JSI::CreateUndefined(); + JSIValue thisVarRef_ = JSI::CreateUndefined(); + const JSIValue *args = nullptr; + uint8_t argsSize = 0; +}; + +struct AuthAsyncCallbackInfo { + JSIValue thisVal_ = JSI::CreateUndefined(); + + char bundleName[DM_JSI_BUF_LENGTH] = {0}; + + JSIValue callback = JSI::CreateUndefined(); + int32_t authType = -1; +}; + +enum DmJSIDevStateChangeAction { + ONLINE = 0, + READY = 1, + OFFLINE = 2, + CHANGE = 3 +}; + +class DmJSIInitCallback : public OHOS::DistributedHardware::DmInitCallback { +public: + explicit DmJSIInitCallback(std::string &bundleName) : bundleName_(bundleName) {} + virtual ~DmJSIInitCallback() {} + void OnRemoteDied() override; + +private: + std::string bundleName_; +}; + +class DmJSIDeviceStateCallback : public OHOS::DistributedHardware::DeviceStateCallback { +public: + explicit DmJSIDeviceStateCallback(std::string &bundleName) : bundleName_(bundleName) {} + virtual ~DmJSIDeviceStateCallback() {}; + void OnDeviceOnline(const OHOS::DistributedHardware::DmDeviceInfo &deviceInfo) override; + void OnDeviceReady(const OHOS::DistributedHardware::DmDeviceInfo &deviceInfo) override; + void OnDeviceOffline(const OHOS::DistributedHardware::DmDeviceInfo &deviceInfo) override; + void OnDeviceChanged(const OHOS::DistributedHardware::DmDeviceInfo &deviceInfo) override; + +private: + std::string bundleName_; +}; + +class DmJSIDiscoverCallback : public OHOS::DistributedHardware::DiscoveryCallback { +public: + explicit DmJSIDiscoverCallback(std::string &bundleName) : refCount_(0), bundleName_(bundleName) {} + virtual ~DmJSIDiscoverCallback() {}; + void OnDeviceFound(uint16_t subscribeId, const OHOS::DistributedHardware::DmDeviceInfo &deviceInfo) override; + void OnDiscoveryFailed(uint16_t subscribeId, int32_t failedReason) override; + void OnDiscoverySuccess(uint16_t subscribeId) override; + void IncreaseRefCount(); + void DecreaseRefCount(); + int32_t GetRefCount(); +private: + int32_t refCount_ = 0; + pthread_mutex_t lock_; + std::string bundleName_; +}; + +class DmJSIAuthenticateCallback : public OHOS::DistributedHardware::AuthenticateCallback { +public: + explicit DmJSIAuthenticateCallback(std::string &bundleName) : bundleName_(bundleName) {} + virtual ~DmJSIAuthenticateCallback() {}; + void OnAuthResult(const std::string &deviceId, const std::string &token, int32_t status, int32_t reason) override; + +private: + std::string bundleName_; +}; + +class DmJSICheckAuthCallback : public OHOS::DistributedHardware::VerifyAuthCallback { +public: + explicit DmJSICheckAuthCallback(std::string &bundleName) : bundleName_(bundleName) {} + virtual ~DmJSICheckAuthCallback() {}; + void OnVerifyAuthResult(const std::string &deviceId, int32_t resultCode, const std::string flag) override; + +private: + std::string bundleName_; +}; + +class DmJSIDeviceManagerFaCallback : public OHOS::DistributedHardware::DeviceManagerFaCallback { +public: + explicit DmJSIDeviceManagerFaCallback(std::string &bundleName) : bundleName_(bundleName) {} + virtual ~DmJSIDeviceManagerFaCallback() {}; + void OnCall(const std::string ¶mJson) override; + +private: + std::string bundleName_; +}; + +class DeviceManagerModule final : public MemoryHeap,DmNativeEvent{ +public: + explicit DeviceManagerModule(); + virtual ~DeviceManagerModule(); + static JSIValue CreateDeviceManager(const JSIValue thisVal, const JSIValue *args, uint8_t argsSize); + static JSIValue ReleaseDeviceManager(const JSIValue thisVal, const JSIValue *args, uint8_t argsSize); + static JSIValue GetTrustedDeviceListSync(const JSIValue thisVal, const JSIValue *args, uint8_t argsSize); + static JSIValue StartDeviceDiscoverSync(const JSIValue thisVal, const JSIValue *args, uint8_t argsSize); + static JSIValue StopDeviceDiscoverSync(const JSIValue thisVal, const JSIValue *args, uint8_t argsSize); + static JSIValue AuthenticateDevice(const JSIValue thisVal, const JSIValue *args, uint8_t argsSize); + static JSIValue VerifyAuthInfo(const JSIValue thisVal, const JSIValue *args, uint8_t argsSize); + static JSIValue JsOn(const JSIValue thisVal, const JSIValue *args, uint8_t argsSize); + static JSIValue JsOff(const JSIValue thisVal, const JSIValue *args, uint8_t argsSize); + static JSIValue SetUserOperationSync(const JSIValue thisVal, const JSIValue *args, uint8_t argsSize); + static JSIValue GetAuthenticationParamSync(const JSIValue thisVal, const JSIValue *args, uint8_t argsSize); + //add new + static JSIValue GetLocalDeviceInfoSync(const JSIValue thisVal, const JSIValue *args, uint8_t argsSize); + static JSIValue UnAuthenticateDevice(const JSIValue thisVal, const JSIValue *args, uint8_t argsSize); + static DeviceManagerModule *GetDeviceManagerJSI(std::string &bundleName); + static void AuthRsultVerifyInfoAsyncWorkFunc(void *data); + static char *GetJSIAppBundleName(); + static void DmAuthParamToJsAuthParamy(const OHOS::DistributedHardware::DmAuthParam &authParam, JSIValue ¶mResult); + void OnDmfaCall(const std::string ¶mJson); + //... + void OnVerifyResult(const std::string &deviceId, int32_t resultCode, const std::string flag); + //.... + void OnAuthResult(const std::string &deviceId, const std::string &token, int32_t status, int32_t reason); + void OnDiscoverFailed(uint16_t subscribeId, int32_t failedReason); + void OnDeviceFound(uint16_t subscribeId, const OHOS::DistributedHardware::DmDeviceInfo &deviceInfo); + void OnDeviceStateChange(DmJSIDevStateChangeAction action,const OHOS::DistributedHardware::DmDeviceInfo &deviceInfo); + void OnRemoteDied(); + static void JsToDmAuthExtra(const JSIValue ¶m, nlohmann::json &jsonObj); + static void JsToDmTokenInfo(const JSIValue &object,const std::string &fieldStr, nlohmann::json &jsonObj); + static void JsToJsonObject(const JSIValue &object, const std::string &fieldStr, nlohmann::json &jsonObj); + static void JsToDmBuffer(const JSIValue &object, const std::string &fieldStr, uint8_t **bufferPtr, int32_t &bufferLen); + static void JsToDmAuthInfo(const JSIValue &object, std::string &extra); + static void JsToDmAppImageInfoAndDmExtra(const JSIValue &object, OHOS::DistributedHardware::DmAppImageInfo& appImageInfo, std::string &extra, int32_t &authType); + static void JsToDmDeviceInfo(const JSIValue &object, OHOS::DistributedHardware::DmDeviceInfo& info); + static int32_t JsToDmSubscribeInfo(const JSIValue &object, OHOS::DistributedHardware::DmSubscribeInfo& info); + static char *JsObjectToString(const JSIValue &object, const std::string &fieldStr); + static bool JsObjectToBool(const JSIValue &object, const std::string &fieldStr); + static int32_t JsObjectToInt(const JSIValue &object, const std::string &fieldStr); + static void DmAuthParamToJsAuthParam(const OHOS::DistributedHardware::DmAuthParam &authParam, JSIValue ¶mResult); + static void CreateDmCallback(std::string &bundleName, std::string &eventType); + static void ReleaseDmCallback(std::string &bundleName, std::string &eventType); + static void DeviceInfoToJsArray(const std::vector &vecDevInfo, const int32_t idx, JSIValue &arrayResult); + +private: + + std::string bundleName_; + static AuthAsyncCallbackInfo authAsyncCallbackInfo_; + static AuthAsyncCallbackInfo verifyAsyncCallbackInfo_; +}; +void InitDeviceManagerModule(JSIValue exports); +} +} + +#endif // OHOS_DEVICE_MANAGER_NATIVE_DEVICEMANAGER_JS_H diff --git a/interfaces_mini/kits/js/src/dm_native_event.cpp b/interfaces_mini/kits/js/src/dm_native_event.cpp new file mode 100644 index 000000000..7adf9de28 --- /dev/null +++ b/interfaces_mini/kits/js/src/dm_native_event.cpp @@ -0,0 +1,105 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "dm_native_event.h" +#include "jsi.h" +#include "dm_log.h" +#include "js_async_work.h" + +using namespace OHOS::DistributedHardware; + +namespace OHOS { +namespace ACELite { + +std::map> DmNativeEvent::eventMap_; + +DmNativeEvent::DmNativeEvent() +{ + LOGI("DmNativeEvent::DmNativeEvent() in"); +} + +DmNativeEvent::DmNativeEvent(JSIValue thisVar) +{ + LOGI("DmNativeEvent::DmNativeEvent(JSIValue thisVar) in"); +} + +DmNativeEvent::~DmNativeEvent() +{ + LOGI("DmNativeEvent::~DmNativeEvent() in"); +} + + +void DmNativeEvent::On(std::string &eventType, JSIValue handle, JSIValue thisVal) +{ + LOGI("DmNativeEvent On in for event: %s", eventType.c_str()); + std::shared_ptr listener= std::make_shared(); + + listener->eventType = eventType; + listener->handlerRef = JSI::AcquireValue(handle); + + listener->thisVarRef_ = JSI::AcquireValue(thisVal); + eventMap_[eventType] = listener; +} + +void DmNativeEvent::Off(std::string &eventType) +{ + LOGI("DmNativeEvent Off in for event: %s", eventType.c_str()); + auto iter = eventMap_.find(eventType); + if (iter == eventMap_.end()) { + LOGE("eventType %s not find", eventType.c_str()); + return; + } + std::shared_ptr listener = iter->second; + JSI::ReleaseValue(listener->handlerRef); + + JSI::ReleaseValue(listener->thisVarRef_); + eventMap_.erase(eventType); +} + +void DmNativeEvent::OnEvent(const std::string &eventType, uint8_t argsSize, const JSIValue *data) +{ + LOGI("OnEvent for %s", eventType.c_str()); + + auto iter = eventMap_.find(eventType); + if (iter == eventMap_.end()) { + LOGE("eventType %s not find", eventType.c_str()); + return; + } + auto listener = iter->second; + if (!JSI::ValueIsFunction(listener->handlerRef)){ + LOGI("OnEvent for %s handlerRef is null", eventType.c_str()); + return; + } + + FuncParams* params = new FuncParams(); + params->handlerRef = listener->handlerRef; + params->thisVarRef_ = listener->thisVarRef_; + params->args = data; + params->argsSize = argsSize; + + LOGI("OnEventAsyncWorkFunc for %s in", eventType.c_str()); + JsAsyncWork::DispatchAsyncWork(OnEventAsyncWorkFunc, reinterpret_cast(params)); + +} + +void DmNativeEvent::OnEventAsyncWorkFunc(void *data) +{ + LOGI("OnEventAsyncWorkFunc in "); + FuncParams* params = reinterpret_cast(data); + JSI::CallFunction(params->handlerRef, params->thisVarRef_, params->args, params->argsSize); +} + +} +} \ No newline at end of file diff --git a/interfaces_mini/kits/js/src/native_devicemanager_js.cpp b/interfaces_mini/kits/js/src/native_devicemanager_js.cpp new file mode 100644 index 000000000..ea12fe80c --- /dev/null +++ b/interfaces_mini/kits/js/src/native_devicemanager_js.cpp @@ -0,0 +1,1206 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "native_devicemanager_js.h" +#include "jsi.h" +#include +#include "nlohmann/json.hpp" +#include "device_manager.h" +#include "dm_constants.h" +#include "jsi_types.h" +#include "js_async_work.h" +#include "dm_log.h" +#include "dm_device_info.h" + + +using namespace OHOS::DistributedHardware; +using namespace std; + +namespace OHOS { +namespace ACELite { + +const std::string DM_JSI_EVENT_DEVICE_STATE_CHANGE = "deviceStateChange"; +const std::string DM_JSI_EVENT_DEVICE_FOUND = "deviceFound"; +const std::string DM_JSI_EVENT_DEVICE_DISCOVER_FAIL = "discoverFail"; +const std::string DM_JSI_EVENT_DMFA_CALLBACK = "dmFaCallback"; +const std::string DM_JSI_EVENT_DEVICE_SERVICE_DIE = "serviceDie"; + +const std::string DEVICE_MANAGER_JSI_CLASS_NAME = "DeviceManager"; +//int32->uint8_t +const uint8_t DM_JSI_ARGS_ONE = 1; +const uint8_t DM_JSI_ARGS_TWO = 2; +const uint8_t DM_JSI_ARGS_THREE = 3; +const int32_t DM_JSI_SUB_ID_MAX = 65535; + +const int32_t DM_AUTH_TYPE_PINCODE = 1; +const int32_t DM_AUTH_DIRECTION_CLIENT = 1; + +const int32_t DM_JSI_SUBSCRIBE_CAPABILITY_DDMP = 0; +const int32_t DM_JSI_SUBSCRIBE_CAPABILITY_OSD = 1; +const char *DM_CAPABILITY_OSD = "osdCapability"; + +std::map g_deviceManagerMap; +std::map> g_initCallbackMap; +std::map> g_deviceStateCallbackMap; +std::map> g_discoverCallbackMap; +std::map> g_authCallbackMap; +std::map> g_checkAuthCallbackMap; +std::map> g_dmfaCallbackMap; + +AuthAsyncCallbackInfo DeviceManagerModule::authAsyncCallbackInfo_; +AuthAsyncCallbackInfo DeviceManagerModule::verifyAsyncCallbackInfo_; + +DeviceManagerModule *DeviceManagerModule::GetDeviceManagerJSI(std::string &bundleName) +{ + auto iter = g_deviceManagerMap.find(bundleName); + if (iter == g_deviceManagerMap.end()) { + return nullptr; + } + return iter->second; +} + + +DeviceManagerModule::DeviceManagerModule() : DmNativeEvent() +{ + LOGI("new DeviceManagerModule is success"); +} + +DeviceManagerModule::~DeviceManagerModule() +{ + +} + +void DmJSIInitCallback::OnRemoteDied() +{ + DeviceManagerModule *deviceManagerJSI = DeviceManagerModule::GetDeviceManagerJSI(bundleName_); + if (deviceManagerJSI == nullptr) { + LOGE("OnRemoteDied, deviceManagerJSI not find for bunderName %s", bundleName_.c_str()); + return; + } + deviceManagerJSI->OnRemoteDied(); +} + +void DeviceManagerModule::OnRemoteDied() +{ + OnEvent("serviceDie", 0, nullptr); +} + + +void DmJSIDeviceStateCallback::OnDeviceOnline(const DmDeviceInfo &deviceInfo) +{ + DeviceManagerModule *deviceManagerJSI = DeviceManagerModule::GetDeviceManagerJSI(bundleName_); + if (deviceManagerJSI == nullptr) { + LOGE("OnDeviceOnline, deviceManagerJSI not find for bunderName %s", bundleName_.c_str()); + return; + } + deviceManagerJSI->OnDeviceStateChange(DmJSIDevStateChangeAction::ONLINE, deviceInfo); +} + +void DmJSIDeviceStateCallback::OnDeviceReady(const DmDeviceInfo &deviceInfo) +{ + DeviceManagerModule *deviceManagerJSI = DeviceManagerModule::GetDeviceManagerJSI(bundleName_); + if (deviceManagerJSI == nullptr) { + LOGE("OnDeviceOnline, deviceManagerJSI not find for bunderName %s", bundleName_.c_str()); + return; + } + deviceManagerJSI->OnDeviceStateChange(DmJSIDevStateChangeAction::READY, deviceInfo); +} + +void DmJSIDeviceStateCallback::OnDeviceOffline(const DmDeviceInfo &deviceInfo) +{ + DeviceManagerModule *deviceManagerJSI = DeviceManagerModule::GetDeviceManagerJSI(bundleName_); + if (deviceManagerJSI == nullptr) { + LOGE("OnDeviceOffline, deviceManagerJSI not find for bunderName %s", bundleName_.c_str()); + return; + } + deviceManagerJSI->OnDeviceStateChange(DmJSIDevStateChangeAction::OFFLINE, deviceInfo); +} + +void DmJSIDeviceStateCallback::OnDeviceChanged(const DmDeviceInfo &deviceInfo) +{ + DeviceManagerModule *deviceManagerJSI = DeviceManagerModule::GetDeviceManagerJSI(bundleName_); + if (deviceManagerJSI == nullptr) { + LOGE("OnDeviceChanged, deviceManagerJSI not find for bunderName %s", bundleName_.c_str()); + return; + } + deviceManagerJSI->OnDeviceStateChange(DmJSIDevStateChangeAction::CHANGE, deviceInfo); +} + +void DmJSIDiscoverCallback::OnDeviceFound(uint16_t subscribeId, const DmDeviceInfo &deviceInfo) +{ + DeviceManagerModule *deviceManagerJSI = DeviceManagerModule::GetDeviceManagerJSI(bundleName_); + if (deviceManagerJSI == nullptr) { + LOGE("OnDeviceFound, deviceManagerJSI not find for bunderName %s", bundleName_.c_str()); + return; + } + + LOGI("OnDeviceFound for %s, subscribeId %d", bundleName_.c_str(), (int32_t)subscribeId); + deviceManagerJSI->OnDeviceFound(subscribeId, deviceInfo); +} +//OnDiscoveryFailed +void DmJSIDiscoverCallback::OnDiscoveryFailed(uint16_t subscribeId, int32_t failedReason) +{ + DeviceManagerModule *deviceManagerJSI = DeviceManagerModule::GetDeviceManagerJSI(bundleName_); + if (deviceManagerJSI == nullptr) { + LOGE("OnDiscoverFailed, deviceManagerJSI not find for bunderName %s", bundleName_.c_str()); + return; + } + + deviceManagerJSI->OnDiscoverFailed(subscribeId, failedReason); +} + +void DmJSIDiscoverCallback::OnDiscoverySuccess(uint16_t subscribeId) +{ + DeviceManagerModule *deviceManagerJSI = DeviceManagerModule::GetDeviceManagerJSI(bundleName_); + if (deviceManagerJSI == nullptr) { + LOGE("OnDiscoverySuccess, deviceManagerJSI not find for bunderName %s", bundleName_.c_str()); + return; + } + LOGI("DiscoverySuccess for %s, subscribeId %d", bundleName_.c_str(), (int32_t)subscribeId); +} + +void DmJSIAuthenticateCallback::OnAuthResult(const std::string &deviceId, const std::string &token, int32_t status, int32_t reason) +{ + DeviceManagerModule *deviceManagerJSI = DeviceManagerModule::GetDeviceManagerJSI(bundleName_); + if (deviceManagerJSI == nullptr) { + LOGE("OnAuthResult, deviceManagerJSI not find for bunderName %s", bundleName_.c_str()); + return; + } + deviceManagerJSI->OnAuthResult(deviceId, token, status, reason); +} + +void DmJSICheckAuthCallback::OnVerifyAuthResult(const std::string &deviceId, int32_t resultCode, const std::string flag) +{ + DeviceManagerModule *deviceManagerJSI = DeviceManagerModule::GetDeviceManagerJSI(bundleName_); + if (deviceManagerJSI == nullptr) { + LOGE("OnCheckAuthResult, deviceManagerJSI not find for bunderName %s", bundleName_.c_str()); + return; + } + deviceManagerJSI->OnVerifyResult(deviceId, resultCode, flag); +} + +void DmJSIDeviceManagerFaCallback::OnCall(const std::string ¶mJson) +{ + DeviceManagerModule *deviceManagerJSI = DeviceManagerModule::GetDeviceManagerJSI(bundleName_); + if (deviceManagerJSI == nullptr) { + LOGE("OnCall, deviceManagerJSI not find for bunderName %s", bundleName_.c_str()); + return; + } + deviceManagerJSI->OnDmfaCall(paramJson); +} + +void DmJSIDiscoverCallback::IncreaseRefCount() +{ + uint32_t ret = pthread_mutex_init(&lock_, NULL); + if (ret != 0) { + LOGE("init mutex lock failed: %d.", ret); + } + pthread_mutex_lock(&lock_); + refCount_++; + pthread_mutex_unlock(&lock_); + LOGI("IncreaseRefCount: refCount_:%d.", refCount_); + ret = pthread_mutex_destroy(&lock_); + if (ret != 0) { + LOGE("destroy mutex lock failed: %d.", ret); + } +} + +void DmJSIDiscoverCallback::DecreaseRefCount() +{ + uint32_t ret = pthread_mutex_init(&lock_, NULL); + if (ret != 0) { + LOGE("init mutex lock failed: %d.", ret); + } + pthread_mutex_lock(&lock_); + refCount_--; + pthread_mutex_unlock(&lock_); + + LOGI("DecreaseRefCount: refCount_:%d.", refCount_); + ret = pthread_mutex_destroy(&lock_); + if (ret != 0) { + LOGE("destroy mutex lock failed: %d.", ret); + } +} + +int32_t DmJSIDiscoverCallback::GetRefCount() +{ + return refCount_; +} + +void DeviceManagerModule::OnDeviceStateChange(DmJSIDevStateChangeAction action, const DmDeviceInfo &deviceInfo) +{ + JSIValue result = JSI::CreateObject(); + JSI::SetNumberProperty(result, "action", (double)action); + + JSIValue device = JSI::CreateObject(); + JSI::SetStringProperty(device, "deviceId", deviceInfo.deviceId); + JSI::SetStringProperty(device, "deviceName", deviceInfo.deviceName); + JSI::SetNumberProperty(device, "deviceTypeId", (double)deviceInfo.deviceTypeId); + + JSIValue param[2] = {result, device}; + OnEvent("deviceStateChange", DM_JSI_ARGS_TWO, param); + JSI::ReleaseValueList(result, device, ARGS_END); +} + +void DeviceManagerModule::OnDeviceFound(uint16_t subscribeId, const DmDeviceInfo &deviceInfo) +{ + LOGI("OnDeviceFound for subscribeId %d", (int32_t)subscribeId); + JSIValue result = JSI::CreateObject(); + JSI::SetNumberProperty(result, "subscribeId", (double)subscribeId); + + JSIValue device = JSI::CreateObject(); + JSI::SetStringProperty(device, "deviceId", deviceInfo.deviceId); + JSI::SetStringProperty(device, "deviceName", deviceInfo.deviceName); + JSI::SetNumberProperty(device, "deviceTypeId", (double)deviceInfo.deviceTypeId); + LOGI("OnDeviceFound subscribeId %ld ", subscribeId); + LOGI("OnDeviceFound deviceId %s ", deviceInfo.deviceId); + LOGI("OnDeviceFound deviceName %s ", deviceInfo.deviceName); + LOGI("OnDeviceFound deviceTypeId %x ", deviceInfo.deviceTypeId); + + JSIValue param[2] = {result, device}; + OnEvent("deviceFound", DM_JSI_ARGS_TWO, param); + JSI::ReleaseValueList(result, device, ARGS_END); +} + +void DeviceManagerModule::OnDiscoverFailed(uint16_t subscribeId, int32_t failedReason) +{ + LOGI("OnDiscoverFailed for subscribeId %d", (int32_t)subscribeId); + JSIValue result = JSI::CreateObject(); + JSI::SetNumberProperty(result, "subscribeId", (double)subscribeId); + JSIValue reason = JSI::CreateObject(); + JSI::SetNumberProperty(reason, "reason", (double)failedReason); + + JSIValue param[2] = {result, reason}; + OnEvent("discoverFail", DM_JSI_ARGS_TWO, param); + JSI::ReleaseValueList(result, reason, ARGS_END); +} + +void DeviceManagerModule::OnDmfaCall(const std::string ¶mJson) +{ + LOGI("OnCall for paramJson"); + JSIValue result = JSI::CreateObject(); + JSI::SetStringProperty(result, "param", paramJson.c_str()); + + JSIValue param[1] = {result}; + OnEvent("dmFaCallback", DM_JSI_ARGS_ONE, param); + JSI::ReleaseValueList(result, ARGS_END); +} + +void DeviceManagerModule::OnAuthResult(const std::string &deviceId, const std::string &token, int32_t status, int32_t reason) +{ + LOGI("OnAuthResult for status: %d, reason: %d", status, reason); + JSIValue thisVar = authAsyncCallbackInfo_.thisVal_; + JSIValue success = JSI::GetNamedProperty(authAsyncCallbackInfo_.callback, CB_SUCCESS); + JSIValue fail = JSI::GetNamedProperty(authAsyncCallbackInfo_.callback, CB_FAIL); + + JSIValue errOne = JSI::CreateObject(); + JSIValue errTwo = JSI::CreateObject(); + JSIValue successOne = JSI::CreateObject(); + JSIValue successTwo = JSI::CreateObject(); + + if (status == 0) { + LOGI("OnAuthResult success"); + JSI::SetStringProperty(successOne, "deviceId", deviceId.c_str()); + JSIValue param[1] = {successOne}; + AuthFuncParams* params =new AuthFuncParams(); + params->handlerRef = success; + params->thisVarRef_ = thisVar; + params->args = param; + params->argsSize = DM_JSI_ARGS_ONE; + LOGI("OnAuthResult SuccessCallBack in."); + JsAsyncWork::DispatchAsyncWork(AuthRsultVerifyInfoAsyncWorkFunc, reinterpret_cast(params)); + } else { + LOGI("OnAuthResult failed"); + JSI::SetNumberProperty(errOne, "code", (double)status); + JSI::SetNumberProperty(errTwo, "reason", (double)reason); + JSIValue param[2] = {errOne, errTwo}; + AuthFuncParams* params =new AuthFuncParams(); + params->handlerRef = fail; + params->thisVarRef_ = thisVar; + params->args = param; + params->argsSize = DM_JSI_ARGS_TWO; + LOGI("OnAuthResult FailCallBack in."); + JsAsyncWork::DispatchAsyncWork(AuthRsultVerifyInfoAsyncWorkFunc, reinterpret_cast(params)); + + } + g_authCallbackMap.erase(bundleName_); + JSI::ReleaseValueList(thisVar, success, fail, errOne, errTwo, successOne, successTwo, authAsyncCallbackInfo_.thisVal_, authAsyncCallbackInfo_.callback, ARGS_END); +} + +void DeviceManagerModule::OnVerifyResult(const std::string &deviceId, int32_t resultCode, const std::string flag) +{ + LOGI("OnVerifyResult for resultCode: %d, flag: %s", resultCode, flag.c_str()); + JSIValue thisVar = verifyAsyncCallbackInfo_.thisVal_; + JSIValue success = JSI::GetNamedProperty(verifyAsyncCallbackInfo_.callback, CB_SUCCESS); + JSIValue fail = JSI::GetNamedProperty(verifyAsyncCallbackInfo_.callback, CB_FAIL); + + JSIValue successOne = JSI::CreateObject(); + JSIValue successTwo = JSI::CreateObject(); + JSIValue errOne = JSI::CreateObject(); + + if (resultCode == 0) { + LOGI("OnVerifyResult success"); + JSI::SetStringProperty(successOne, "deviceId", deviceId.c_str()); + JSI::SetStringProperty(successTwo, "level", flag.c_str()); + JSIValue param[2] = {successOne, successTwo}; + AuthFuncParams* params =new AuthFuncParams(); + params->handlerRef = success; + params->thisVarRef_ = thisVar; + params->args = param; + params->argsSize = DM_JSI_ARGS_TWO; + LOGI("OnVerifyResult SuccessCallBack in."); + JsAsyncWork::DispatchAsyncWork(AuthRsultVerifyInfoAsyncWorkFunc, reinterpret_cast(params)); + + } else { + LOGI("OnVerifyResult failed"); + JSI::SetNumberProperty(errOne, "code", (double)resultCode); + JSIValue param[1] = {errOne}; + AuthFuncParams* params =new AuthFuncParams(); + params->handlerRef = fail; + params->thisVarRef_ = thisVar; + params->args = param; + params->argsSize = DM_JSI_ARGS_ONE; + LOGI("OnVerifyResult FailCallBack in."); + JsAsyncWork::DispatchAsyncWork(AuthRsultVerifyInfoAsyncWorkFunc, reinterpret_cast(params)); + } + + g_checkAuthCallbackMap.erase(bundleName_); + JSI::ReleaseValueList(thisVar, success, fail, successOne, successTwo, errOne, verifyAsyncCallbackInfo_.thisVal_, verifyAsyncCallbackInfo_.callback, ARGS_END); +} + +void DeviceManagerModule::DeviceInfoToJsArray(const std::vector &vecDevInfo, const int32_t idx, JSIValue &arrayResult) +{ + bool status = false; + JSIValue result = JSI::CreateObject(); + char *deviceId = const_cast(vecDevInfo[idx].deviceId); + char *deviceName = const_cast(vecDevInfo[idx].deviceName); + + JSI::SetStringProperty(result, "deviceId", deviceId); + JSI::SetStringProperty(result, "deviceName", deviceName); + JSI::SetNumberProperty(result, "deviceTypeId", (double)vecDevInfo[idx].deviceTypeId); + + status = JSI::SetPropertyByIndex(arrayResult,idx,result); + if (status == false) { + LOGE("DmDeviceInfo To JsArray set element error"); + } + JSI::ReleaseValue(result); +} + +void DeviceManagerModule::DmAuthParamToJsAuthParamy(const DmAuthParam &authParam, JSIValue ¶mResult) +{ + LOGI("DmAuthParamToJsAuthParamy in"); + JSI::SetNumberProperty(paramResult,"authType",(double)authParam.authType); + + JSIValue extraInfo = JSI::CreateObject(); + JSI::SetNumberProperty(extraInfo,"direction",(double)authParam.direction); + JSI::SetNumberProperty(extraInfo,"pinToken",(double)authParam.pinToken); + if (authParam.direction == DM_AUTH_DIRECTION_CLIENT) { + JSI::SetNamedProperty(paramResult,"extraInfo",extraInfo); + return; + } + JSI::SetStringProperty(extraInfo, "packageName",authParam.packageName.c_str()); + JSI::SetStringProperty(extraInfo, "appName",authParam.appName.c_str()); + JSI::SetStringProperty(extraInfo, "appDescription",authParam.appDescription.c_str()); + JSI::SetNumberProperty(extraInfo,"business",(double)authParam.business); + JSI::SetNumberProperty(extraInfo,"pincode",(double)authParam.pincode); + JSI::SetNamedProperty(paramResult,"extraInfo",extraInfo); + LOGI("DeviceManagerModule::DmAuthParamToJsAuthParamy, packageName: %s", authParam.packageName.c_str()); + LOGI("DeviceManagerModule::DmAuthParamToJsAuthParamy, appName: %s", authParam.appName.c_str()); + LOGI("DeviceManagerModule::DmAuthParamToJsAuthParamy, appDescription: %s", authParam.appDescription.c_str()); + LOGI("DeviceManagerModule::DmAuthParamToJsAuthParamy, business: %d",authParam.business); + LOGI("DeviceManagerModule::DmAuthParamToJsAuthParamy, pincode: %d", authParam.pincode); + LOGI("DeviceManagerModule::DmAuthParamToJsAuthParamy, pinToken: %d", authParam.pinToken); + + size_t appIconLen = (size_t)authParam.imageinfo.GetAppIconLen(); + if (appIconLen > 0) { + uint8_t *appIcon = nullptr; + JSIValue appIconBuffer = JSI::CreateArrayBuffer(appIconLen, appIcon); + if (appIcon != nullptr && + memcpy_s(appIcon, appIconLen, reinterpret_cast(authParam.imageinfo.GetAppIcon()), + appIconLen) == 0) { + JSIValue appIconArray = JSI::CreateTypedArray(TypedArrayType::JSI_UINT8_ARRAY, appIconLen, appIconBuffer, 0); + JSI::SetNamedProperty(paramResult,"appIcon",appIconArray); + } + } + + size_t appThumbnailLen = (size_t)authParam.imageinfo.GetAppThumbnailLen(); + if (appThumbnailLen > 0) { + uint8_t *appThumbnail = nullptr; + JSIValue appThumbnailBuffer = JSI::CreateArrayBuffer(appThumbnailLen, appThumbnail); + if (appThumbnail != nullptr && memcpy_s(appThumbnail, appThumbnailLen, reinterpret_cast(authParam.imageinfo.GetAppThumbnail()), appThumbnailLen) == 0) { + JSIValue appThumbnailArray = JSI::CreateTypedArray(TypedArrayType::JSI_UINT8_ARRAY, appThumbnailLen, appThumbnailBuffer, 0); + JSI::SetNamedProperty(paramResult,"appThumbnail", appThumbnailArray); + } + } +} + +int32_t DeviceManagerModule::JsObjectToInt(const JSIValue &object, + const std::string &fieldStr) +{ + double result = JSI::GetNumberProperty(object,fieldStr.c_str()); + return (int32_t)result; +} + +bool DeviceManagerModule::JsObjectToBool(const JSIValue &object, + const std::string &fieldStr) +{ + bool result = JSI::GetBooleanProperty(object,fieldStr.c_str()); + return result; +} + +char *DeviceManagerModule::JsObjectToString(const JSIValue &object, + const std::string &fieldStr) +{ + char* str = JSI::GetStringProperty(object, fieldStr.c_str()); + return str; +} + +int32_t DeviceManagerModule::JsToDmSubscribeInfo(const JSIValue &object,DmSubscribeInfo &info) +{ + int32_t subscribeId = -1; + subscribeId = JsObjectToInt(object,"subscribeId"); + if (subscribeId < 0 || subscribeId > DM_JSI_SUB_ID_MAX) { + LOGE("DeviceManagerModule::JsToDmSubscribeInfo, subscribeId error, subscribeId: %d ", subscribeId); + return -1; + } + info.subscribeId = (uint16_t)subscribeId; + + int32_t mode = -1; + mode = JsObjectToInt(object, "mode"); + info.mode = (DmDiscoverMode)mode; + + int32_t medium = -1; + medium = JsObjectToInt(object, "medium"); + info.medium = (DmExchangeMedium)medium; + + int32_t freq = -1; + freq = JsObjectToInt(object, "freq"); + info.freq = (DmExchangeFreq)freq; + + info.isSameAccount = JsObjectToBool(object, "isSameAccount"); + info.isWakeRemote = JsObjectToBool(object, "isWakeRemote"); + + int32_t capability = -1; + capability = JsObjectToInt(object, "capability"); + if (capability == DM_JSI_SUBSCRIBE_CAPABILITY_DDMP || capability == DM_JSI_SUBSCRIBE_CAPABILITY_OSD) { + (void)strncpy_s(info.capability, sizeof(info.capability), DM_CAPABILITY_OSD, strlen(DM_CAPABILITY_OSD)); + } + return 0; +} + +void DeviceManagerModule::JsToDmDeviceInfo( const JSIValue &object, + DmDeviceInfo &info) +{ + std::strcpy(info.deviceId, JsObjectToString(object, "deviceId")); + std::strcpy(info.deviceName, JsObjectToString(object, "deviceName")); + uint16_t deviceTypeId = -1; + deviceTypeId = (uint16_t)JsObjectToInt(object, "deviceTypeId"); + info.deviceTypeId = deviceTypeId; +} + +void DeviceManagerModule::JsToDmAppImageInfoAndDmExtra(const JSIValue &object, + DmAppImageInfo& appImageInfo, std::string &extra, int32_t &authType) +{ + LOGI("JsToDmAppImageInfoAndDmExtra in."); + int32_t authTypeTemp = -1; + authTypeTemp = (int32_t)JsObjectToInt(object, "authType"); + authType = authTypeTemp; + + uint8_t *appIconBufferPtr = nullptr; + int32_t appIconBufferLen = 0; + JsToDmBuffer(object, "appIcon", &appIconBufferPtr, appIconBufferLen); + + uint8_t *appThumbnailBufferPtr = nullptr; + int32_t appThumbnailBufferLen = 0; + JsToDmBuffer(object, "appThumbnail", &appThumbnailBufferPtr, appThumbnailBufferLen); + + appImageInfo.Reset(appIconBufferPtr, appIconBufferLen, appThumbnailBufferPtr, appThumbnailBufferLen); + if (appIconBufferPtr != nullptr) { + free(appIconBufferPtr); + appIconBufferPtr = nullptr; + } + if (appThumbnailBufferPtr != nullptr) { + free(appThumbnailBufferPtr); + appThumbnailBufferPtr = nullptr; + } + + nlohmann::json jsonObj; + jsonObj[AUTH_TYPE] = authType; + std::string extraInfo = "extraInfo"; + + JsToJsonObject(object, "extraInfo", jsonObj); + extra = jsonObj.dump(); + LOGI("appIconLen %d, appThumbnailLen %d", appIconBufferLen, appThumbnailBufferLen); +} + +void DeviceManagerModule::JsToDmBuffer(const JSIValue &object, + const std::string &fieldStr, uint8_t **bufferPtr, int32_t &bufferLen) +{ + LOGI("JsToDmBuffer in."); + + JSIValue field = JSI::GetNamedProperty(object, fieldStr.c_str()); + if (field == JSI::CreateUndefined() || field == JSI::CreateNull()){ + LOGE("devicemanager JSI js to str no property: %s", fieldStr.c_str()); + return; + } + + OHOS::ACELite::TypedArrayType type = TypedArrayType::JSI_UINT8_ARRAY; + size_t length = 0; + JSIValue buffer = nullptr; + size_t offset = 0; + uint8_t *data = nullptr; + data = JSI::GetTypedArrayInfo(field, type, length, buffer, offset); + + if (type != TypedArrayType::JSI_UINT8_ARRAY || length == 0 || data == nullptr) { + LOGE("Invaild AppIconInfo"); + return; + } + *bufferPtr = (uint8_t*)calloc(sizeof(uint8_t), length); + if (*bufferPtr == nullptr) { + LOGE("low memory, calloc return nullptr, length is %d, filed %s", length, fieldStr.c_str()); + return; + } + if (memcpy_s(*bufferPtr, length, data, length) != 0) { + LOGE("memcpy_s failed, filed %s", fieldStr.c_str()); + free(*bufferPtr); + *bufferPtr = nullptr; + return; + } + bufferLen = length; +} + +void DeviceManagerModule::JsToJsonObject(const JSIValue &object, + const std::string &fieldStr, nlohmann::json &jsonObj) +{ + LOGI("JsToJsonObject in."); + JSIValue jsonField = JSI::GetNamedProperty(object, fieldStr.c_str()); + if (jsonField == JSI::CreateUndefined() || jsonField == JSI::CreateNull()){ + LOGE("devicemanager JSI js to str no property: %s", fieldStr.c_str()); + return; + } + + JSIValue jsProNameList = nullptr; + uint32_t jsProCount = 0; + jsProNameList = JSI::GetObjectKeys(jsonField); + jsProCount = JSI::GetArrayLength(jsProNameList); + LOGI("Property size=%d.", jsProCount); + + JSIValue jsProName = nullptr; + JSIValue jsProValue = nullptr; + for (uint32_t index = 0; index < jsProCount; index++) { + jsProName = JSI::GetPropertyByIndex(jsProNameList, index); + + std::string strProName = JSI::ValueToString(jsProName); + jsProValue = JSI::GetNamedProperty(jsonField, strProName.c_str()); + + if (JSI::ValueIsString(jsProValue)){ + std::string natValue = JSI::ValueToString(jsProValue); + LOGI("Property name=%s, string, value=%s", strProName.c_str(), natValue.c_str()); + jsonObj[strProName] = natValue; + } + + if (JSI::ValueIsBoolean(jsProValue)){ + bool elementValue = JSI::ValueToBoolean(jsProValue); + LOGI("Property name=%s, boolean, value=%d.", strProName.c_str(), elementValue); + jsonObj[strProName] = elementValue; + } + + if (JSI::ValueIsNumber(jsProValue)){ + int32_t elementValue = 0; + elementValue = (int32_t)JSI::ValueToNumber(jsProValue); + jsonObj[strProName] = elementValue; + LOGI("Property name=%s, number, value=%d.", strProName.c_str(), elementValue); + } + } +} + +void DeviceManagerModule::JsToDmAuthInfo(const JSIValue &object, std::string &extra) +{ + LOGI("%s called.", __func__); + int32_t authType = -1; + int32_t token = -1; + + authType = JsObjectToInt(object, "authType"); + token = JsObjectToInt(object, "token"); + + nlohmann::json jsonObj; + jsonObj[AUTH_TYPE] = authType; + if (authType == DM_AUTH_TYPE_PINCODE) { + jsonObj[PIN_TOKEN] = token; + } else { + jsonObj[TOKEN] = token; + } + JsToJsonObject(object, "extraInfo", jsonObj); + extra = jsonObj.dump(); +} + +void DeviceManagerModule::CreateDmCallback(std::string &bundleName, std::string &eventType) +{ + LOGE("CreateDmCallback for bunderName %s eventType %s", bundleName.c_str(), eventType.c_str()); + if (eventType == DM_JSI_EVENT_DEVICE_STATE_CHANGE) { + auto iter = g_deviceStateCallbackMap.find(bundleName); + if (iter == g_deviceStateCallbackMap.end()) { + auto callback = std::make_shared(bundleName); + std::string extra = ""; + int32_t ret = OHOS::DistributedHardware::DeviceManager::GetInstance().RegisterDevStateCallback(bundleName, extra, callback); + if (ret != 0) { + LOGE("RegisterDevStateCallback failed for bunderName %s", bundleName.c_str()); + return; + } + g_deviceStateCallbackMap[bundleName] = callback; + } + return; + } + + if (eventType == DM_JSI_EVENT_DEVICE_FOUND || eventType == DM_JSI_EVENT_DEVICE_DISCOVER_FAIL) { + std::shared_ptr discoverCallback = nullptr; + auto iter = g_discoverCallbackMap.find(bundleName); + if (iter == g_discoverCallbackMap.end()) { + auto callback = std::make_shared(bundleName); + g_discoverCallbackMap[bundleName] = callback; + discoverCallback = callback; + } else { + discoverCallback = iter->second; + } + + discoverCallback->IncreaseRefCount(); + return; + } + + if (eventType == DM_JSI_EVENT_DMFA_CALLBACK) { + auto iter = g_dmfaCallbackMap.find(bundleName); + if (iter == g_dmfaCallbackMap.end()) { + auto callback = std::make_shared(bundleName); + int32_t ret = OHOS::DistributedHardware::DeviceManager::GetInstance().RegisterDeviceManagerFaCallback(bundleName, callback); + if (ret != 0) { + LOGE("RegisterDeviceManagerFaCallback failed for bunderName %s", bundleName.c_str()); + return; + } + g_dmfaCallbackMap[bundleName] = callback; + } + return; + } +} + +void DeviceManagerModule::ReleaseDmCallback(std::string &bundleName, std::string &eventType) +{ + if (eventType == DM_JSI_EVENT_DEVICE_STATE_CHANGE) { + auto iter = g_deviceStateCallbackMap.find(bundleName); + if (iter == g_deviceStateCallbackMap.end()) { + LOGE("ReleaseDmCallback: cannot find stateCallback for bunderName %s", bundleName.c_str()); + return; + } + int32_t ret = OHOS::DistributedHardware::DeviceManager::GetInstance().UnRegisterDevStateCallback(bundleName); + if (ret != 0) { + LOGE("RegisterDevStateCallback failed for bunderName %s", bundleName.c_str()); + return; + } + g_deviceStateCallbackMap.erase(bundleName); + return; + } + + if (eventType == DM_JSI_EVENT_DEVICE_FOUND || eventType == DM_JSI_EVENT_DEVICE_DISCOVER_FAIL) { + std::shared_ptr discoverCallback = nullptr; + auto iter = g_discoverCallbackMap.find(bundleName); + if (iter == g_discoverCallbackMap.end()) { + return; + } + + discoverCallback = iter->second; + discoverCallback->DecreaseRefCount(); + if (discoverCallback->GetRefCount() == 0) { + g_discoverCallbackMap.erase(bundleName); + } + return; + } + + if (eventType == DM_JSI_EVENT_DMFA_CALLBACK) { + auto iter = g_dmfaCallbackMap.find(bundleName); + if (iter == g_dmfaCallbackMap.end()) { + LOGE("cannot find dmFaCallback for bunderName %s", bundleName.c_str()); + return; + } + int32_t ret = OHOS::DistributedHardware::DeviceManager::GetInstance().UnRegisterDeviceManagerFaCallback(bundleName); + if (ret != 0) { + LOGE("RegisterDevStateCallback failed for bunderName %s", bundleName.c_str()); + return; + } + g_dmfaCallbackMap.erase(bundleName); + return; + } +} + +void DeviceManagerModule::AuthRsultVerifyInfoAsyncWorkFunc(void *data) +{ + LOGI("AuthRsultVerifyInfoAsyncWorkFunc in ............"); + AuthFuncParams* params = reinterpret_cast(data); + JSI::CallFunction(params->handlerRef, params->thisVarRef_, params->args, params->argsSize); +} + +//add new +JSIValue DeviceManagerModule::UnAuthenticateDevice(const JSIValue thisVal, const JSIValue *args, uint8_t argsSize) +{ + LOGI("UnAuthenticateDevice in"); + if (argsSize < 1) { + LOGE("1 argument is required."); + return JSI::CreateNull(); + } + if (!JSI::ValueIsObject(args[0])){ + LOGE("a object is required."); + return JSI::CreateNull(); + } + std::string bundleName = GetJSIAppBundleName(); + std::string deviceId = JSI::GetStringProperty(args[0], "deviceId"); + LOGI("UnAuthenticateDevice deviceId=%s", deviceId.c_str()); + int32_t ret = 0; + #if 1 + ret = OHOS::DistributedHardware::DeviceManager::GetInstance().UnAuthenticateDevice(bundleName, deviceId); + if (ret != 0) { + LOGI("UnAuthenticateDevice for bunderName %s failed, ret %d", bundleName.c_str(), ret); + } + #endif + + JSIValue result = JSI::CreateObject(); + JSI::SetNumberProperty(result, "ret", (double)ret); + return result; +} + +JSIValue DeviceManagerModule::GetLocalDeviceInfoSync(const JSIValue thisVal, const JSIValue *args, uint8_t argsSize) +{ + LOGI("GetLocalDeviceInfoSync in"); + + std::string bundleName = GetJSIAppBundleName(); + DmDeviceInfo deviceInfo; + #if 1 + int32_t ret = OHOS::DistributedHardware::DeviceManager::GetInstance().GetLocalDeviceInfo(bundleName, deviceInfo); + if (ret != 0) { + LOGE("GetLocalDeviceInfoSync for failed, ret %d", ret); + return JSI::CreateNull(); + } + #endif + LOGI("DeviceManager::GetLocalDeviceInfoSync deviceId:%s deviceName:%s deviceTypeId:%d ", deviceInfo.deviceId, + deviceInfo.deviceName, deviceInfo.deviceTypeId); + JSIValue result = JSI::CreateObject(); + char *deviceId = const_cast(deviceInfo.deviceId); + char *deviceName = const_cast(deviceInfo.deviceName); + + JSI::SetStringProperty(result, "deviceId", deviceId); + JSI::SetStringProperty(result, "deviceName", deviceName); + JSI::SetNumberProperty(result, "deviceTypeId", (double)deviceInfo.deviceTypeId); + return result; +} + +JSIValue DeviceManagerModule::SetUserOperationSync(const JSIValue thisVal, const JSIValue *args, uint8_t argsSize) +{ + LOGI("SetUserOperationSync in"); + if (argsSize < 1) { + LOGE("1 argument is required."); + return JSI::CreateNull(); + } + + if (!JSI::ValueIsNumber(args[0])){ + LOGE("a Number is required."); + return JSI::CreateNull(); + } + + std::string bundleName = GetJSIAppBundleName(); + int32_t action = 0; + action = static_cast(JSI::ValueToNumber(args[0])); + + LOGI("SetUserOperation action %d", action); + + int32_t ret = OHOS::DistributedHardware::DeviceManager::GetInstance().SetUserOperation(bundleName, action); + if (ret != 0) { + LOGE("SetUserOperation for bunderName %s failed, ret %d", + bundleName.c_str(), ret); + return JSI::CreateNull(); + } + + return JSI::CreateNull(); +} + +JSIValue DeviceManagerModule::GetAuthenticationParamSync(const JSIValue thisVal, const JSIValue *args, uint8_t argsSize) +{ + LOGI("GetAuthenticationParamSync in"); + std::string bundleName = GetJSIAppBundleName(); + JSIValue resultParam = JSI::CreateObject(); + DmAuthParam authParam; + //add new + #if 1 + int32_t ret = OHOS::DistributedHardware::DeviceManager::GetInstance().GetFaParam(bundleName, authParam); + if (ret != 0) { + LOGE("GetAuthenticationParam for %s failed, ret %d", + bundleName.c_str(), ret); + return JSI::CreateNull(); + } + #endif + DmAuthParamToJsAuthParamy(authParam,resultParam); + return resultParam; +} + +JSIValue DeviceManagerModule::GetTrustedDeviceListSync(const JSIValue thisVal, const JSIValue *args, uint8_t argsSize) +{ + LOGI("GetTrustedDeviceList in"); + JSIValue array = JSI::CreateNull(); + std::string extra = ""; + std::vector devList; + std::string bundleName = GetJSIAppBundleName(); + + int32_t ret = OHOS::DistributedHardware::DeviceManager::GetInstance().GetTrustedDeviceList(bundleName, extra, devList); + if (ret != 0) { + LOGE("GetTrustedDeviceList for bunderName %s failed, ret %d", + bundleName.c_str(), ret); + return array; + } + if (devList.size() > 0) { + bool isArray = false; + array = JSI::CreateArray(devList.size()); + isArray = JSI::ValueIsArray(array); + if (isArray == false) { + LOGE("JSI_create_array fail"); + } + + for (size_t i = 0; i != devList.size(); ++i) { + DeviceInfoToJsArray(devList, i, array); + } + } else { + LOGE("devList is null"); + } + + return array; +} + +JSIValue DeviceManagerModule::StartDeviceDiscoverSync(const JSIValue thisVal, const JSIValue *args, uint8_t argsSize) +{ + LOGI("StartDeviceDiscoverSync in"); + std::string bundleName = GetJSIAppBundleName(); + + if (argsSize < 1){ + LOGE("1 argument is required."); + return JSI::CreateNull(); + } + + if (!JSI::ValueIsObject(args[0])){ + LOGE("a object is required."); + return JSI::CreateNull(); + } + + std::shared_ptr discoverCallback = nullptr; + auto iter = g_discoverCallbackMap.find(bundleName); + if (iter == g_discoverCallbackMap.end()) { + discoverCallback = std::make_shared(bundleName); + g_discoverCallbackMap[bundleName] = discoverCallback; + } else { + discoverCallback = iter->second; + } + DmSubscribeInfo subInfo; + int32_t res = JsToDmSubscribeInfo(args[0], subInfo); + if (res != 0){ + LOGE("Wrong subscribeId."); + return JSI::CreateNull(); + } + + LOGI("subInfo %d , %d, %d, %d, %d , %d, %s", + subInfo.subscribeId, + subInfo.mode, + subInfo.medium, + subInfo.freq, + subInfo.isSameAccount, + subInfo.isWakeRemote, + subInfo.capability); + //add extra + #if 1 + std::string extra = ""; + int32_t ret = OHOS::DistributedHardware::DeviceManager::GetInstance().StartDeviceDiscovery(bundleName, + subInfo, extra, discoverCallback); + if (ret != 0) { + LOGE("StartDeviceDiscovery for bunderName %s failed, ret %d", + bundleName.c_str(), ret); + return JSI::CreateNull(); + } + #endif + return JSI::CreateNull(); +} + +JSIValue DeviceManagerModule::StopDeviceDiscoverSync(const JSIValue thisVal, const JSIValue *args, uint8_t argsSize) +{ + LOGI("StopDeviceDiscoverSync in"); + std::string bundleName = GetJSIAppBundleName(); + + if (argsSize < 1){ + LOGE("1 argument is required."); + return JSI::CreateNull(); + } + + if (!JSI::ValueIsNumber(args[0])){ + LOGE("a Number is required."); + return JSI::CreateNull(); + } + //add new + int16_t subscribeId = 0; + subscribeId = static_cast(JSI::ValueToNumber(args[0])); + LOGI("subscribeId %d ", subscribeId); + + int32_t ret = OHOS::DistributedHardware::DeviceManager::GetInstance().StopDeviceDiscovery(bundleName, subscribeId); + if (ret != 0) { + LOGE("StopDeviceDiscovery for bunderName %s failed, ret %d", + bundleName.c_str(), ret); + return JSI::CreateNull(); + } + + return JSI::CreateNull(); +} + +JSIValue DeviceManagerModule::AuthenticateDevice(const JSIValue thisVal, const JSIValue *args, uint8_t argsSize) +{ + LOGI("AuthenticateDevice in"); + std::string bundleName = GetJSIAppBundleName(); + if (argsSize < 3){ + LOGE("3 argument is required."); + return JSI::CreateNull(); + } + + if (!JSI::ValueIsObject(args[0])){ + LOGE("a object is required."); + return JSI::CreateNull(); + } + + if (!JSI::ValueIsObject(args[1])){ + LOGE("a object is required."); + return JSI::CreateNull(); + } + + authAsyncCallbackInfo_.thisVal_ = JSI::AcquireValue(thisVal); + authAsyncCallbackInfo_.callback = JSI::AcquireValue(args[2]); + + std::shared_ptr authCallback = nullptr; + auto iter = g_authCallbackMap.find(bundleName); + if (iter == g_authCallbackMap.end()) { + authCallback = std::make_shared(bundleName); + g_authCallbackMap[bundleName] = authCallback; + } else { + authCallback = iter->second; + } + DmDeviceInfo deviceInfo; + JsToDmDeviceInfo(args[0], deviceInfo); + + LOGI("deviceInfo %s , %s, %d", + deviceInfo.deviceId, + deviceInfo.deviceName, + deviceInfo.deviceTypeId); + + DmAppImageInfo appImageInfo(nullptr, 0, nullptr, 0); + std::string extra; + JsToDmAppImageInfoAndDmExtra(args[1], appImageInfo, extra, authAsyncCallbackInfo_.authType); + + int32_t ret = OHOS::DistributedHardware::DeviceManager::GetInstance().AuthenticateDevice(bundleName, 1, deviceInfo, + extra, authCallback); + if (ret != 0) { + LOGE("AuthenticateDevice for bunderName %s failed, ret %d", + bundleName.c_str(), ret); + } + + return JSI::CreateUndefined(); +} + +JSIValue DeviceManagerModule::VerifyAuthInfo(const JSIValue thisVal, const JSIValue *args, uint8_t argsSize) +{ + LOGI("VerifyAuthInfo in"); + std::string bundleName = GetJSIAppBundleName(); + if (argsSize < 2){ + LOGE("2 argument is required."); + return JSI::CreateNull(); + } + + if (!JSI::ValueIsObject(args[0])){ + LOGE("a object is required."); + return JSI::CreateNull(); + } + + verifyAsyncCallbackInfo_.thisVal_ = JSI::AcquireValue(thisVal); + verifyAsyncCallbackInfo_.callback = JSI::AcquireValue(args[1]); + + std::shared_ptr verifyCallback = nullptr; + auto iter = g_checkAuthCallbackMap.find(bundleName); + if (iter == g_checkAuthCallbackMap.end()) { + verifyCallback = std::make_shared(bundleName); + g_checkAuthCallbackMap[bundleName] = verifyCallback; + } else { + verifyCallback = iter->second; + } + std::string authParam; + JsToDmAuthInfo(args[0], authParam); + int32_t ret = OHOS::DistributedHardware::DeviceManager::GetInstance().VerifyAuthentication(bundleName, + authParam, verifyCallback); + if (ret != 0) { + LOGE("VerifyAuthInfo for bunderName %s failed, ret %d", + bundleName.c_str(), ret); + } + return JSI::CreateUndefined(); +} + +JSIValue DeviceManagerModule::JsOn(const JSIValue thisVal, const JSIValue *args, uint8_t argsSize) +{ + LOGI("JsOn in"); + std::string bundleName = GetJSIAppBundleName(); + if (argsSize < 2){ + LOGE("2 argument is required."); + return JSI::CreateNull(); + } + if (!JSI::ValueIsString(args[0])){ + LOGE("a string is required."); + return JSI::CreateNull(); + } + if (!JSI::ValueIsFunction(args[1])){ + LOGE("a FUNC is required."); + return JSI::CreateNull(); + } + std::string eventType = JSI::ValueToString(args[0]); + + LOGI("JsOn for bunderName %s, eventType %s ", bundleName.c_str(), + eventType.c_str()); + std::shared_ptr DmNativeEventobj = std::make_shared(thisVal); + DmNativeEventobj->On(eventType, args[1], thisVal); + CreateDmCallback(bundleName, eventType); + + return JSI::CreateUndefined(); +} + +JSIValue DeviceManagerModule::JsOff(const JSIValue thisVal, const JSIValue *args, uint8_t argsSize) +{ + LOGI("JsOff in"); + std::string bundleName = GetJSIAppBundleName(); + + if (!JSI::ValueIsString(args[0])){ + LOGE("a string is required."); + return JSI::CreateNull(); + } + + std::string eventType = JSI::ValueToString(args[0]); + + LOGI("JsOff for bunderName %s, eventType %s ", bundleName.c_str(), + eventType.c_str()); + + DmNativeEvent* DmNativeEventobj = new DmNativeEvent(); + DmNativeEventobj->Off(eventType); + delete(DmNativeEventobj); + ReleaseDmCallback(bundleName, eventType); + + return JSI::CreateUndefined(); +} + +JSIValue DeviceManagerModule::ReleaseDeviceManager(const JSIValue thisVal, const JSIValue *args, uint8_t argsSize) +{ + LOGI("ReleaseDeviceManager in"); + std::string bundleName = GetJSIAppBundleName(); + LOGI("ReleaseDeviceManager for bunderName %s", bundleName.c_str()); + + int32_t ret = OHOS::DistributedHardware::DeviceManager::GetInstance().UnInitDeviceManager(bundleName); + if (ret != 0) { + LOGE("ReleaseDeviceManager for bunderName %s failed, ret %d", + bundleName.c_str(), ret); + JSIValue result = JSI::CreateNumber((double)ret); + return result; + } + + g_deviceManagerMap.erase(bundleName); + g_initCallbackMap.erase(bundleName); + g_deviceStateCallbackMap.erase(bundleName); + g_discoverCallbackMap.erase(bundleName); + g_authCallbackMap.erase(bundleName); + g_checkAuthCallbackMap.erase(bundleName); + + return JSI::CreateUndefined(); +} + +JSIValue DeviceManagerModule::CreateDeviceManager(const JSIValue thisVal, const JSIValue *args, uint8_t argsSize) +{ + if (argsSize < 1) { + LOGE("1 argument is required."); + return JSI::CreateNull(); + } + + if (!JSI::ValueIsString(args[0])) { + LOGE("a string is required."); + return JSI::CreateNull(); + } + std::string bundleName = GetJSIAppBundleName(); + + LOGI("CreateDeviceManager for bunderName is %s", bundleName.c_str()); + + if (DeviceManagerModule::GetDeviceManagerJSI(bundleName) != nullptr) { + LOGI("CreateDeviceManager repeat for bunderName %s", bundleName.c_str()); + return JSI::CreateNull(); + } + + DeviceManagerModule *obj = new DeviceManagerModule(); + obj->bundleName_ = bundleName; + g_deviceManagerMap[bundleName] = obj; + + int32_t ret = 0; + std::shared_ptr initCallback = std::make_shared(bundleName); + ret = OHOS::DistributedHardware::DeviceManager::GetInstance().InitDeviceManager(bundleName, initCallback); + if ( ret == 0 ){ + LOGI("InitDeviceManager for bunderName %s success", bundleName.c_str()); + JSIValue success = JSI::GetNamedProperty(args[1], CB_SUCCESS); + JSIValue data = JSI::CreateObject(); + std::string str = "InitDeviceManager success"; + JSI::SetStringProperty(data, "data", str.c_str()); + JSI::CallFunction(success, thisVal, &data, 1); + } + if (ret != 0){ + LOGI("InitDeviceManager for bunderName %s fail", bundleName.c_str()); + JSIValue fail = JSI::GetNamedProperty(args[1], CB_FAIL); + JSIValue err = JSI::CreateObject(); + std::string str = "InitDeviceManager fail"; + JSI::SetStringProperty(err, "err", str.c_str()); + JSI::CallFunction(fail, thisVal, &err, 1); + } + + return JSI::CreateNull(); +} + +char *DeviceManagerModule::GetJSIAppBundleName() +{ + JSAbility *g_targetJSAbility = new JSAbility(); + const char *pname = g_targetJSAbility->GetPackageName(); + char *packageName = new char[strlen(pname)+1]; + strcpy(packageName, pname); + delete(g_targetJSAbility); + return packageName; +} + +void InitDeviceManagerModule(JSIValue exports) +{ + JSI::SetModuleAPI(exports, "createDeviceManager", DeviceManagerModule::CreateDeviceManager); + JSI::SetModuleAPI(exports, "getTrustedDeviceListSync", DeviceManagerModule::GetTrustedDeviceListSync); + JSI::SetModuleAPI(exports, "release", DeviceManagerModule::ReleaseDeviceManager); + JSI::SetModuleAPI(exports, "startDeviceDiscovery", DeviceManagerModule::StartDeviceDiscoverSync); + JSI::SetModuleAPI(exports, "stopDeviceDiscovery", DeviceManagerModule::StopDeviceDiscoverSync); + JSI::SetModuleAPI(exports, "authenticateDevice", DeviceManagerModule::AuthenticateDevice); + JSI::SetModuleAPI(exports, "verifyAuthInfo", DeviceManagerModule::VerifyAuthInfo); + JSI::SetModuleAPI(exports, "setUserOperation", DeviceManagerModule::SetUserOperationSync); + JSI::SetModuleAPI(exports, "getAuthenticationParam", DeviceManagerModule::GetAuthenticationParamSync); + JSI::SetModuleAPI(exports, "on", DeviceManagerModule::JsOn); + JSI::SetModuleAPI(exports, "off", DeviceManagerModule::JsOff); + JSI::SetModuleAPI(exports, "GetLocalDeviceInfoSync", DeviceManagerModule::GetLocalDeviceInfoSync); + JSI::SetModuleAPI(exports, "UnAuthenticateDevice", DeviceManagerModule::UnAuthenticateDevice); +} + +} +} + + + -- Gitee From 1ea8ed6fc8639e6255b22893051910ce4b6f8cc8 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E8=94=A1=E9=98=94?= Date: Wed, 9 Mar 2022 07:35:37 +0000 Subject: [PATCH 03/19] =?UTF-8?q?!27=20DM=E4=BB=A3=E7=A0=81=E4=BF=AE?= =?UTF-8?q?=E6=94=B9=E7=BC=96=E7=A8=8B=E8=A7=84=E8=8C=83=E9=97=AE=E9=A2=98?= =?UTF-8?q?=20*=20=E4=BF=AE=E6=94=B9=E4=BB=A3=E7=A0=81=E7=BC=96=E7=A8=8B?= =?UTF-8?q?=E8=A7=84=E8=8C=83=E9=97=AE=E9=A2=98?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../native_cpp/include/device_manager.h | 1 - .../native_cpp/include/device_manager_impl.h | 11 +- .../native_cpp/src/device_manager_impl.cpp | 51 +------- .../src/notify/device_manager_notify.cpp | 5 - .../dispatch/authenticate_device_req.h | 55 --------- .../include/dispatch/get_trustdevice_req.h | 23 ---- .../include/dispatch/message_def.h | 38 +++--- .../include/dispatch/message_processing.h | 1 - .../include/dispatch/message_req.h | 20 --- .../include/dispatch/server_stub.h | 1 - .../include/dispatch/start_discovery_req.h | 35 +----- .../dispatch/verify_authenticate_req.h | 22 ---- .../src/dispatch/command_dispatch.cpp | 17 +-- .../src/dispatch/server_stub_bak.cpp | 114 ------------------ 14 files changed, 29 insertions(+), 365 deletions(-) delete mode 100644 services/devicemanagerservice/src/dispatch/server_stub_bak.cpp diff --git a/interfaces_mini/inner_kits/native_cpp/include/device_manager.h b/interfaces_mini/inner_kits/native_cpp/include/device_manager.h index 10944ccd9..75d750993 100644 --- a/interfaces_mini/inner_kits/native_cpp/include/device_manager.h +++ b/interfaces_mini/inner_kits/native_cpp/include/device_manager.h @@ -46,7 +46,6 @@ public: virtual int32_t UnAuthenticateDevice(const std::string &pkgName, const std::string &deviceId) = 0; virtual int32_t VerifyAuthentication(const std::string &pkgName, const std::string &authPara, std::shared_ptr callback) = 0; - // virtual int32_t GetAuthenticationParam(std::string &pkgName, DmAuthParam &authParam) = 0; virtual int32_t RegisterDeviceManagerFaCallback(const std::string &pkgName, std::shared_ptr callback) = 0; virtual int32_t UnRegisterDeviceManagerFaCallback(const std::string &pkgName) = 0; diff --git a/interfaces_mini/inner_kits/native_cpp/include/device_manager_impl.h b/interfaces_mini/inner_kits/native_cpp/include/device_manager_impl.h index 490fdb0f2..8611ac4cf 100644 --- a/interfaces_mini/inner_kits/native_cpp/include/device_manager_impl.h +++ b/interfaces_mini/inner_kits/native_cpp/include/device_manager_impl.h @@ -27,8 +27,7 @@ namespace DistributedHardware { class DeviceManagerImpl : public DeviceManager { #define DEVICEMANAGER_MESSAGE_FAILED -1 DECLARE_SINGLE_INSTANCE(DeviceManagerImpl); -//public: -// static DeviceManagerImpl &GetInstance(); + public: virtual int32_t InitDeviceManager(const std::string &pkgName, @@ -51,7 +50,6 @@ public: virtual int32_t UnAuthenticateDevice(const std::string &pkgName, const std::string &deviceId) override; virtual int32_t VerifyAuthentication(const std::string &pkgName, const std::string &authPara, std::shared_ptr callback) override; - // virtual int32_t GetAuthenticationParam(std::string &pkgName, DmAuthParam &authParam) override; virtual int32_t RegisterDeviceManagerFaCallback(const std::string &pkgName, std::shared_ptr callback) override; virtual int32_t UnRegisterDeviceManagerFaCallback(const std::string &pkgName) override; @@ -61,13 +59,6 @@ public: std::string &udid) override; virtual int32_t GetUuidByNetworkId(const std::string &pkgName, const std::string &netWorkId, std::string &uuid) override; -//private: -// DeviceManagerImpl() = default; -// ~DeviceManagerImpl() = default; -// DeviceManagerImpl(const DeviceManagerImpl &) = delete; -// DeviceManagerImpl &operator=(const DeviceManagerImpl &) = delete; -// DeviceManagerImpl(DeviceManagerImpl &&) = delete; -// DeviceManagerImpl &operator=(DeviceManagerImpl &&) = delete; }; } // namespace DistributedHardware } // namespace OHOS diff --git a/interfaces_mini/inner_kits/native_cpp/src/device_manager_impl.cpp b/interfaces_mini/inner_kits/native_cpp/src/device_manager_impl.cpp index 694abca6e..0c59d44e3 100644 --- a/interfaces_mini/inner_kits/native_cpp/src/device_manager_impl.cpp +++ b/interfaces_mini/inner_kits/native_cpp/src/device_manager_impl.cpp @@ -15,11 +15,8 @@ #include "command_dispatch.h" #include "device_manager_impl.h" #include "message_processing.h" -// #include "device_manager_errno.h" -// #include "device_manager_log.h" #include "dm_log.h" #include "device_manager_notify.h" -// #include "constants.h" #include "dm_constants.h" #include "message_def.h" #include "get_trustdevice_req.h" @@ -30,7 +27,6 @@ #include "get_authenticationparam_rsp.h" #include "authenticate_device_req.h" #include "verify_authenticate_req.h" - #include "get_local_device_info_rsp.h" #include "get_info_by_network_rsp.h" #include "get_info_by_network_req.h" @@ -42,13 +38,6 @@ namespace OHOS { namespace DistributedHardware { IMPLEMENT_SINGLE_INSTANCE(DeviceManagerImpl); - - -//DeviceManagerImpl &DeviceManagerImpl::GetInstance() -//{ -// static DeviceManagerImpl instance; -// return instance; -//} int32_t DeviceManagerImpl::InitDeviceManager(const std::string &pkgName, std::shared_ptr dmInitCallback) { LOGI("DeviceManager::InitDeviceManager start, pkgName: %s", pkgName.c_str()); @@ -70,6 +59,7 @@ int32_t DeviceManagerImpl::UnInitDeviceManager(const std::string &pkgName) LOGE("InitDeviceManager error: Invalid parameter"); return DM_INVALID_VALUE; } + DeviceManagerNotify::GetInstance().DeletePkgName(pkgName); DeviceManagerNotify::GetInstance().UnRegisterPackageCallback(pkgName); LOGI("UnInitDeviceManager success"); @@ -135,8 +125,6 @@ int32_t DeviceManagerImpl::RegisterDevStateCallback(const std::string &pkgName, std::shared_ptr callback) { LOGI("DeviceManager::RegisterDevStateCallback start, pkgName: %s", pkgName.c_str()); - - if (pkgName.empty() || callback == nullptr) { LOGE("RegisterDevStateCallback error: Invalid para"); return DM_INVALID_VALUE; @@ -150,8 +138,6 @@ int32_t DeviceManagerImpl::RegisterDevStateCallback(const std::string &pkgName, int32_t DeviceManagerImpl::UnRegisterDevStateCallback(const std::string &pkgName) { LOGI("DeviceManager::UnRegisterDevStateCallback start, pkgName: %s", pkgName.c_str()); - - if (pkgName.empty()) { LOGE("UnRegisterDevStateCallback error: Invalid para"); return DM_INVALID_VALUE; @@ -165,7 +151,6 @@ int32_t DeviceManagerImpl::StartDeviceDiscovery(const std::string &pkgName, cons const std::string &extra, std::shared_ptr callback) { LOGI("DeviceManager::StartDeviceDiscovery start, pkgName: %s", pkgName.c_str()); - if (pkgName.empty() || callback == nullptr) { LOGE("StartDeviceDiscovery error: Invalid para"); return DM_INVALID_VALUE; @@ -194,7 +179,6 @@ int32_t DeviceManagerImpl::StartDeviceDiscovery(const std::string &pkgName, cons int32_t DeviceManagerImpl::StopDeviceDiscovery(const std::string &pkgName, uint16_t subscribeId) { LOGI("DeviceManager::StopDeviceDiscovery start , pkgName: %s", pkgName.c_str()); - if (pkgName.empty()) { LOGE("StopDeviceDiscovery error: Invalid para"); return DM_INVALID_VALUE; @@ -225,8 +209,6 @@ int32_t DeviceManagerImpl::AuthenticateDevice(const std::string &pkgName, int32_ std::shared_ptr callback) { LOGI("DeviceManager::AuthenticateDevice start , pkgName: %s", pkgName.c_str()); - - if (pkgName.empty()) { LOGE("AuthenticateDevice error: Invalid para"); return DM_INVALID_VALUE; @@ -241,7 +223,6 @@ int32_t DeviceManagerImpl::AuthenticateDevice(const std::string &pkgName, int32_ req->SetAuthType(authType); req->SetDeviceInfo(deviceInfo); - if (CommandDispatch::GetInstance().MessageSendCmd(AUTHENTICATE_DEVICE, req, rsp) != DM_OK) { return DEVICEMANAGER_MESSAGE_FAILED; } @@ -259,8 +240,6 @@ int32_t DeviceManagerImpl::AuthenticateDevice(const std::string &pkgName, int32_ int32_t DeviceManagerImpl::UnAuthenticateDevice(const std::string &pkgName, const std::string &deviceId) { LOGI("DeviceManager::UnAuthenticateDevice start , pkgName: %s, deviceId: %s", pkgName.c_str(), deviceId.c_str()); - - if (deviceId.empty()) { LOGE("UnAuthenticateDevice error: Invalid para"); return DM_INVALID_VALUE; @@ -287,25 +266,6 @@ int32_t DeviceManagerImpl::UnAuthenticateDevice(const std::string &pkgName, cons return DM_OK; } - -// int32_t DeviceManagerImpl::GetAuthenticationParam(std::string &pkgName, DmAuthParam &authParam) -// { -// LOGI("DeviceManager::GetAuthenticationParam start"); - -// std::shared_ptr req = std::make_shared(); -// std::shared_ptr rsp = std::make_shared(); -// req->SetPkgName(pkgName); -// if (CommandDispatch::GetInstance().MessageSendCmd(SERVER_GET_AUTHENTCATION_INFO, req, rsp) != DM_OK) { -// return DEVICEMANAGER_MESSAGE_FAILED; -// } - -// if (rsp->GetErrCode() == DM_OK) { -// authParam = rsp->GetAuthParam(); -// } - -// return DM_OK; -// } - int32_t DeviceManagerImpl::RegisterDeviceManagerFaCallback(const std::string &pkgName, std::shared_ptr callback) { @@ -314,6 +274,7 @@ int32_t DeviceManagerImpl::RegisterDeviceManagerFaCallback(const std::string &pk LOGE("RegisterDeviceManagerFaCallback error: Invalid para"); return DM_INVALID_VALUE; } + DeviceManagerNotify::GetInstance().RegisterDeviceManagerFaCallback(pkgName, callback); LOGI("DeviceManager::RegisterDevStateCallback completed, pkgName: %s", pkgName.c_str()); return DM_OK; @@ -326,6 +287,7 @@ int32_t DeviceManagerImpl::UnRegisterDeviceManagerFaCallback(const std::string & LOGE("UnRegisterDeviceManagerFaCallback error: Invalid para"); return DM_INVALID_VALUE; } + DeviceManagerNotify::GetInstance().UnRegisterDeviceManagerFaCallback(pkgName); LOGI("DeviceManager::UnRegisterDevStateCallback completed, pkgName: %s", pkgName.c_str()); return DM_OK; @@ -334,7 +296,6 @@ int32_t DeviceManagerImpl::VerifyAuthentication(const std::string &pkgName, cons std::shared_ptr callback) { LOGI("DeviceManager::VerifyAuthentication start, pkgName: %s", pkgName.c_str()); - if (pkgName.empty()) { LOGE("VerifyAuthentication error: Invalid para"); return DM_INVALID_VALUE; @@ -382,8 +343,6 @@ int32_t DeviceManagerImpl::GetFaParam(const std::string &pkgName, DmAuthParam &d return DM_OK; } - - int32_t DeviceManagerImpl::SetUserOperation(const std::string &pkgName, int32_t action) { LOGI("DeviceManager::SetUserOperation start, pkgName: %s", pkgName.c_str()); @@ -464,9 +423,5 @@ int32_t DeviceManagerImpl::GetUuidByNetworkId(const std::string &pkgName, const uuid = rsp->GetUuid(); return DM_OK; } - - - - } // namespace DistributedHardware } // namespace OHOS diff --git a/interfaces_mini/inner_kits/native_cpp/src/notify/device_manager_notify.cpp b/interfaces_mini/inner_kits/native_cpp/src/notify/device_manager_notify.cpp index 1d7b304da..5765a5467 100644 --- a/interfaces_mini/inner_kits/native_cpp/src/notify/device_manager_notify.cpp +++ b/interfaces_mini/inner_kits/native_cpp/src/notify/device_manager_notify.cpp @@ -14,10 +14,7 @@ */ #include "device_manager_notify.h" - -// #include "device_manager_log.h" #include "dm_log.h" -// #include "device_manager_errno.h" #include "nlohmann/json.hpp" #include "dm_constants.h" #include "device_manager.h" @@ -289,7 +286,5 @@ const std::list& DeviceManagerNotify::GetPkgNameList() const { return dmPkgName_; } - - } // namespace DistributedHardware } // namespace OHOS diff --git a/services/devicemanagerservice/include/dispatch/authenticate_device_req.h b/services/devicemanagerservice/include/dispatch/authenticate_device_req.h index c361ead51..4bc90cfdd 100644 --- a/services/devicemanagerservice/include/dispatch/authenticate_device_req.h +++ b/services/devicemanagerservice/include/dispatch/authenticate_device_req.h @@ -46,16 +46,6 @@ public: authType_ = authType; } - // const DmAppImageInfo& GetAppImageInfo() const - // { - // return appImageInfo_; - // } - - // void SetAppImageInfo(const DmAppImageInfo &appImageInfo) - // { - // appImageInfo_ = appImageInfo; - // } - const std::string& GetExtra() const { return extra_; @@ -68,53 +58,8 @@ public: private: DmDeviceInfo deviceInfo_; int32_t authType_; - // DmAppImageInfo appImageInfo_; std::string extra_; }; } // namespace DistributedHardware } // namespace OHOS #endif // OHOS_DEVICE_MANAGER_AUTHENTICATE_DEVICE_REQ_H - -// namespace OHOS { -// namespace DistributedHardware { -// class IpcAuthenticateDeviceReq : public IpcReq { -// DECLARE_IPC_MODEL(IpcAuthenticateDeviceReq); - -// public: -// const DmDeviceInfo &GetDeviceInfo() const -// { -// return deviceInfo_; -// } - -// void SetDeviceInfo(const DmDeviceInfo &deviceInfo) -// { -// deviceInfo_ = deviceInfo; -// } - -// int32_t GetAuthType() -// { -// return authType_; -// } - -// void SetAuthType(int32_t authType) -// { -// authType_ = authType; -// } - -// const std::string &GetExtra() const -// { -// return extra_; -// } - -// void SetExtra(const std::string &extra) -// { -// extra_ = extra; -// } - -// private: -// DmDeviceInfo deviceInfo_; -// int32_t authType_; -// std::string extra_; -// }; -// } // namespace DistributedHardware -// } // namespace OHOS diff --git a/services/devicemanagerservice/include/dispatch/get_trustdevice_req.h b/services/devicemanagerservice/include/dispatch/get_trustdevice_req.h index f071baa9d..c4f4fca14 100644 --- a/services/devicemanagerservice/include/dispatch/get_trustdevice_req.h +++ b/services/devicemanagerservice/include/dispatch/get_trustdevice_req.h @@ -38,26 +38,3 @@ private: } // namespace DistributedHardware } // namespace OHOS #endif // OHOS_DEVICE_MANAGER_GET_TRUST_DEVICE_REQ_H - - -// namespace OHOS { -// namespace DistributedHardware { -// class IpcGetTrustDeviceReq : public IpcReq { -// DECLARE_IPC_MODEL(IpcGetTrustDeviceReq); - -// public: -// const std::string &GetExtra() const -// { -// return extra_; -// } - -// void SetExtra(const std::string &extra) -// { -// extra_ = extra; -// } - -// private: -// std::string extra_; -// }; -// } // namespace DistributedHardware -// } // namespace OHOS diff --git a/services/devicemanagerservice/include/dispatch/message_def.h b/services/devicemanagerservice/include/dispatch/message_def.h index ea7f6c453..06e443a7d 100644 --- a/services/devicemanagerservice/include/dispatch/message_def.h +++ b/services/devicemanagerservice/include/dispatch/message_def.h @@ -35,25 +35,25 @@ public: \ DECLARE_MESSAGE_MODEL(className) enum DispatchCmdID { - REGISTER_DEVICE_MANAGER_LISTENER = 0,//无需修改 - UNREGISTER_DEVICE_MANAGER_LISTENER,//无需修改 - GET_TRUST_DEVICE_LIST,//上到下 - GET_LOCAL_DEVICE_INFO,//上到下 - GET_UDID_BY_NETWORK,//上到下,standard实现,lite未实现 - GET_UUID_BY_NETWORK,//上到下,standard实现,lite未实现 - START_DEVICE_DISCOVER,//上到下 - STOP_DEVICE_DISCOVER,//上到下 - AUTHENTICATE_DEVICE,//上到下 - UNAUTHENTICATE_DEVICE,//上到下 - VERIFY_AUTHENTICATION,//上到下,替代CHECK_AUTHENTICATION - SERVER_DEVICE_STATE_NOTIFY,//下到上 - SERVER_DEVICE_FOUND,//下到上 - SERVER_DISCOVER_FINISH,//下到上 - SERVER_AUTH_RESULT,//下到上 - SERVER_VERIFY_AUTH_RESULT,//下到上 - SERVER_GET_DMFA_INFO,//上到下,替代SERVER_GET_AUTHENTCATION_INFO,standard实现,lite未实现 - SERVER_USER_AUTH_OPERATION,//上到下,替代SERVER_USER_AUTHORIZATION_OPERATION - SERVER_DEVICE_FA_NOTIFY,//下到上,替代SERVER_DEVICEMANAGER_FA_NOTIFY + REGISTER_DEVICE_MANAGER_LISTENER = 0, + UNREGISTER_DEVICE_MANAGER_LISTENER, + GET_TRUST_DEVICE_LIST, + GET_LOCAL_DEVICE_INFO, + GET_UDID_BY_NETWORK, + GET_UUID_BY_NETWORK, + START_DEVICE_DISCOVER, + STOP_DEVICE_DISCOVER, + AUTHENTICATE_DEVICE, + UNAUTHENTICATE_DEVICE, + VERIFY_AUTHENTICATION, + SERVER_DEVICE_STATE_NOTIFY, + SERVER_DEVICE_FOUND, + SERVER_DISCOVER_FINISH, + SERVER_AUTH_RESULT, + SERVER_VERIFY_AUTH_RESULT, + SERVER_GET_DMFA_INFO, + SERVER_USER_AUTH_OPERATION, + SERVER_DEVICE_FA_NOTIFY, }; } // namespace DistributedHardware } // namespace OHOS diff --git a/services/devicemanagerservice/include/dispatch/message_processing.h b/services/devicemanagerservice/include/dispatch/message_processing.h index b8141c673..03e3d6af1 100644 --- a/services/devicemanagerservice/include/dispatch/message_processing.h +++ b/services/devicemanagerservice/include/dispatch/message_processing.h @@ -38,7 +38,6 @@ public: int32_t AuthenticateDevice(std::string &pkgName, const DmDeviceInfo &deviceInfo, const DmAppImageInfo &imageInfo, std::string &extra); int32_t CheckAuthentication(std::string &authPara); - // int32_t GetAuthenticationParam(std::string &pkgName, DmAuthParam &authParam, std::shared_ptr prsp); int32_t SetUserOperation(std::string &pkgName, int32_t action); static int32_t GenRandInt(int32_t minPinToken, int32_t maxPinToken); private: diff --git a/services/devicemanagerservice/include/dispatch/message_req.h b/services/devicemanagerservice/include/dispatch/message_req.h index 745ec0876..d8b438a11 100644 --- a/services/devicemanagerservice/include/dispatch/message_req.h +++ b/services/devicemanagerservice/include/dispatch/message_req.h @@ -40,23 +40,3 @@ private: } // namespace DistributedHardware } // namespace OHOS #endif // OHOS_DEVICE_MANAGER_MESSAGE_REQ_H - -// namespace OHOS { -// namespace DistributedHardware { -// class IpcReq { -// DECLARE_IPC_MODEL(IpcReq); - -// public: -// const std::string &GetPkgName() const -// { -// return pkgName_; -// } - -// void SetPkgName(const std::string &pkgName) -// { -// pkgName_ = pkgName; -// } - -// private: -// std::string pkgName_; -// }; diff --git a/services/devicemanagerservice/include/dispatch/server_stub.h b/services/devicemanagerservice/include/dispatch/server_stub.h index 7a50df58f..9667dba08 100644 --- a/services/devicemanagerservice/include/dispatch/server_stub.h +++ b/services/devicemanagerservice/include/dispatch/server_stub.h @@ -18,7 +18,6 @@ #include #include -//#include "liteipc_adapter.h" #include #endif // OHOS_DEVICE_MANAGER_IPC_SERVER_STUB_H diff --git a/services/devicemanagerservice/include/dispatch/start_discovery_req.h b/services/devicemanagerservice/include/dispatch/start_discovery_req.h index b987fbd40..fd88596f5 100644 --- a/services/devicemanagerservice/include/dispatch/start_discovery_req.h +++ b/services/devicemanagerservice/include/dispatch/start_discovery_req.h @@ -50,37 +50,4 @@ private: }; } // namespace DistributedHardware } // namespace OHOS -#endif // OHOS_DEVICE_MANAGER_START_DISCOVERY_REQ_H - -// namespace OHOS { -// namespace DistributedHardware { -// class IpcStartDiscoveryReq : public IpcReq { -// DECLARE_IPC_MODEL(IpcStartDiscoveryReq); - -// public: -// const DmSubscribeInfo &GetSubscribeInfo() const -// { -// return subscribeInfo_; -// } - -// void SetSubscribeInfo(const DmSubscribeInfo &subscribeInfo) -// { -// subscribeInfo_ = subscribeInfo; -// } - -// const std::string &GetExtra() const -// { -// return extra_; -// } - -// void SetExtra(const std::string &extra) -// { -// extra_ = extra; -// } - -// private: -// std::string extra_; -// DmSubscribeInfo subscribeInfo_; -// }; -// } // namespace DistributedHardware -// } // namespace OHOS +#endif // OHOS_DEVICE_MANAGER_START_DISCOVERY_REQ_H \ No newline at end of file diff --git a/services/devicemanagerservice/include/dispatch/verify_authenticate_req.h b/services/devicemanagerservice/include/dispatch/verify_authenticate_req.h index c3ae0dccf..1ad6dda65 100644 --- a/services/devicemanagerservice/include/dispatch/verify_authenticate_req.h +++ b/services/devicemanagerservice/include/dispatch/verify_authenticate_req.h @@ -38,25 +38,3 @@ private: } // namespace DistributedHardware } // namespace OHOS #endif // OHOS_DEVICE_MANAGER_CHECK_AUTHENTICATE_REQ_H - -// namespace OHOS { -// namespace DistributedHardware { -// class IpcVerifyAuthenticateReq : public IpcReq { -// DECLARE_IPC_MODEL(IpcVerifyAuthenticateReq); - -// public: -// const std::string &GetAuthPara() const -// { -// return authPara_; -// } - -// void SetAuthPara(const std::string &authPara) -// { -// authPara_ = authPara; -// } - -// private: -// std::string authPara_; -// }; -// } // namespace DistributedHardware -// } // namespace OHOS diff --git a/services/devicemanagerservice/src/dispatch/command_dispatch.cpp b/services/devicemanagerservice/src/dispatch/command_dispatch.cpp index b0cb74802..47a0a0815 100644 --- a/services/devicemanagerservice/src/dispatch/command_dispatch.cpp +++ b/services/devicemanagerservice/src/dispatch/command_dispatch.cpp @@ -17,7 +17,6 @@ #include "dm_log.h" #include "message_def.h" #include "dm_constants.h" -// #include "device_manager_errno.h" #include "server_stub.h" #include "securec.h" #include "dm_device_info.h" @@ -67,9 +66,6 @@ int32_t CommandDispatch::CmdProcessing(int32_t cmdCode, std::shared_ptrGetExtra(); LOGI("enter GetTrustedDeviceList"); - // DmDeviceInfo *info = nullptr; - // int32_t infoNum = 0; - // ret = MessageProcessing::GetInstance().GetTrustedDeviceList(pkgName, extra, &info, &infoNum, prsp); std::vector deviceList; ret = DeviceManagerService::GetInstance().GetTrustedDeviceList(pkgName, extra, deviceList); prsp->SetErrCode(ret); @@ -117,7 +113,6 @@ int32_t CommandDispatch::CmdProcessing(int32_t cmdCode, std::shared_ptrGetSubscribeInfo(); LOGI("StartDeviceDiscovery service"); - // ret = MessageProcessing::GetInstance().StartDeviceDiscovery(pkgName, dmSubscribeInfo); int32_t ret = DeviceManagerService::GetInstance().StartDeviceDiscovery(pkgName, dmSubscribeInfo, extra); rsp->SetErrCode(ret); break; @@ -128,7 +123,7 @@ int32_t CommandDispatch::CmdProcessing(int32_t cmdCode, std::shared_ptr pReq = std::static_pointer_cast(req); std::string pkgName = pReq->GetPkgName(); uint16_t subscribeId = pReq->GetSubscribeId(); - // ret = MessageProcessing::GetInstance().StopDiscovery(pkgName, subscribeId); + ret = DeviceManagerService::GetInstance().StopDeviceDiscovery(pkgName, subscribeId); rsp->SetErrCode(ret); break; @@ -139,7 +134,7 @@ int32_t CommandDispatch::CmdProcessing(int32_t cmdCode, std::shared_ptrGetOperation(); LOGI("enter server user authorization operation."); - // ret = MessageProcessing::GetInstance().SetUserOperation(pkgName, action); + ret = DeviceManagerService::GetInstance().SetUserOperation(pkgName, action); rsp->SetErrCode(ret); break; @@ -161,7 +156,7 @@ int32_t CommandDispatch::CmdProcessing(int32_t cmdCode, std::shared_ptrSetDmAuthParam(authParam); pRsp->SetErrCode(ret); @@ -174,11 +169,9 @@ int32_t CommandDispatch::CmdProcessing(int32_t cmdCode, std::shared_ptrGetDeviceInfo(); int32_t authType = pReq->GetAuthType(); std::string deviceId = deviceInfo.deviceId; - // DmDeviceInfo deviceInfo = pReq->GetDeviceInfo(); - // DmAppImageInfo imageInfo(nullptr, 0, nullptr, 0); LOGI("DeviceManagerStub:: AUTHENTCATION_DEVICE:pkgName:%s", pkgName.c_str()); - // ret = MessageProcessing::GetInstance().AuthenticateDevice(pkgName, deviceInfo, imageInfo, extra); + ret = DeviceManagerService::GetInstance().AuthenticateDevice(pkgName, authType, deviceId, extra); rsp->SetErrCode(ret); break; @@ -200,7 +193,7 @@ int32_t CommandDispatch::CmdProcessing(int32_t cmdCode, std::shared_ptrGetAuthPara(); LOGI("DeviceManagerStub:: VERIFY_AUTHENTCATION:pkgName:%s", pkgName.c_str()); - // ret = MessageProcessing::GetInstance().CheckAuthentication(authPara); + ret = DeviceManagerService::GetInstance().VerifyAuthentication(authParam); rsp->SetErrCode(ret); break; diff --git a/services/devicemanagerservice/src/dispatch/server_stub_bak.cpp b/services/devicemanagerservice/src/dispatch/server_stub_bak.cpp deleted file mode 100644 index bb83afe69..000000000 --- a/services/devicemanagerservice/src/dispatch/server_stub_bak.cpp +++ /dev/null @@ -1,114 +0,0 @@ -/* - * Copyright (c) 2021 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#include "server_stub.h" -#include "server_init.h" - -#include "securec.h" - - -#include "ohos_init.h" -#include "samgr_lite.h" - - -#include "device_manager_log.h" -#include "device_manager_errno.h" -#include "dm_subscribe_info.h" - -#include "message_def.h" - - -namespace { - const int32_t WAIT_FOR_SERVER = 2; - const int32_t STACK_SIZE = 0x1000; - const int32_t QUEUE_SIZE = 32; -} - -using namespace OHOS::DistributedHardware; - -struct DefaultFeatureApi { -// INHERIT_SERVER_IPROXY; -}; - -struct DeviceManagerSamgrService { - INHERIT_SERVICE; - INHERIT_IUNKNOWNENTRY(DefaultFeatureApi); - Identity identity; -}; - - -static const char *GetName(Service *service) -{ - (void)service; - return DEVICE_MANAGER_SERVICE_NAME; -} - -static BOOL Initialize(Service *service, Identity identity) -{ - if (service == NULL) { - DMLOG(DM_LOG_WARN, "invalid param"); - return FALSE; - } - - Server_Init(); - - DeviceManagerSamgrService *mgrService = (DeviceManagerSamgrService *)service; - mgrService->identity = identity; - return TRUE; -} - -static BOOL MessageHandle(Service *service, Request *request) -{ - if ((service == NULL) || (request == NULL)) { - DMLOG(DM_LOG_WARN, "invalid param"); - return FALSE; - } - return TRUE; -} - -static TaskConfig GetTaskConfig(Service *service) -{ - (void)service; - TaskConfig config = {LEVEL_HIGH, PRI_BELOW_NORMAL, STACK_SIZE, QUEUE_SIZE, SHARED_TASK}; - return config; -} - - - - -static void DevMgrSvcInit(void) -{ - sleep(WAIT_FOR_SERVER); - static DeviceManagerSamgrService service = { - .GetName = GetName, - .Initialize = Initialize, - .MessageHandle = MessageHandle, - .GetTaskConfig = GetTaskConfig, - // SERVER_IPROXY_IMPL_BEGIN, - // .Invoke = OnRemoteRequest, - // IPROXY_END, - }; - - if (!SAMGR_GetInstance()->RegisterService((Service *)&service)) { - DMLOG(DM_LOG_ERROR, "%s, RegisterService failed", DEVICE_MANAGER_SERVICE_NAME); - return; - } - if (!SAMGR_GetInstance()->RegisterDefaultFeatureApi(DEVICE_MANAGER_SERVICE_NAME, GET_IUNKNOWN(service))) { - DMLOG(DM_LOG_ERROR, "%s, RegisterDefaultFeatureApi failed", DEVICE_MANAGER_SERVICE_NAME); - return; - } - DMLOG(DM_LOG_INFO, "%s, init success", DEVICE_MANAGER_SERVICE_NAME); -} -SYSEX_SERVICE_INIT(DevMgrSvcInit); -- Gitee From 217d64329b17a34735200f60ebb705d3a77c20ae Mon Sep 17 00:00:00 2001 From: dang_zehui Date: Wed, 9 Mar 2022 20:18:22 +0800 Subject: [PATCH 04/19] =?UTF-8?q?services=E7=9B=AE=E5=BD=95=E4=BF=AE?= =?UTF-8?q?=E6=94=B9?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../include/authentication/auth_ui.h | 2 +- .../include/config/dm_config_manager.h | 4 + .../include/config/mini/pin_auth.h | 42 ++++ .../commonevent/dm_common_event_manager.h | 78 +++--- .../dependency/hichain/hichain_connector.h | 6 +- .../dependency/softbus/softbus_connector.h | 8 +- .../dependency/softbus/softbus_session.h | 6 +- .../include/dependency/timer/dm_timer.h | 12 +- .../include/device_manager_service.h | 28 +-- .../devicestate/dm_device_state_manager.h | 9 +- .../src/authentication/dm_auth_manager.cpp | 40 ++-- .../src/config/mini/dm_config_manager.cpp | 67 ++++++ .../src/config/mini/pin_auth.cpp | 82 +++++++ .../commonevent/dm_common_event_manager.cpp | 222 +++++++++--------- .../dependency/hichain/hichain_connector.cpp | 8 +- .../multipleuser/multiple_user_connector.cpp | 17 +- .../dependency/softbus/softbus_connector.cpp | 108 ++++++++- .../dependency/softbus/softbus_session.cpp | 6 +- .../src/dependency/timer/mini/dm_timer.cpp | 75 ++++++ .../src/device_manager_service.cpp | 221 +++++++++-------- .../devicestate/dm_device_state_manager.cpp | 64 ++++- 21 files changed, 771 insertions(+), 334 deletions(-) create mode 100644 services/devicemanagerservice/include/config/mini/pin_auth.h create mode 100644 services/devicemanagerservice/src/config/mini/dm_config_manager.cpp create mode 100644 services/devicemanagerservice/src/config/mini/pin_auth.cpp create mode 100644 services/devicemanagerservice/src/dependency/timer/mini/dm_timer.cpp diff --git a/services/devicemanagerservice/include/authentication/auth_ui.h b/services/devicemanagerservice/include/authentication/auth_ui.h index 4ba96cb50..e7473332c 100644 --- a/services/devicemanagerservice/include/authentication/auth_ui.h +++ b/services/devicemanagerservice/include/authentication/auth_ui.h @@ -17,7 +17,7 @@ #define OHOS_DM_AUTH_UI_H #include - +#include #include "dm_ability_manager.h" namespace OHOS { diff --git a/services/devicemanagerservice/include/config/dm_config_manager.h b/services/devicemanagerservice/include/config/dm_config_manager.h index 4a410a1e7..d2082a7b7 100644 --- a/services/devicemanagerservice/include/config/dm_config_manager.h +++ b/services/devicemanagerservice/include/config/dm_config_manager.h @@ -19,7 +19,9 @@ #include #include #include +#if (defined(__LINUX__) || defined(__LITEOS_A__)) #include +#endif #include #include #include @@ -66,10 +68,12 @@ private: DmConfigManager(); private: +#if (defined(__LINUX__) || defined(__LITEOS_A__)) std::mutex authAdapterMutex_; std::mutex cryptoAdapterMutex_; std::mutex decisionAdapterMutex_; std::mutex profileAdapterMutex_; +#endif std::map soAuthLoadInfo_; std::map soAdapterLoadInfo_; std::map> decisionAdapterPtr_; diff --git a/services/devicemanagerservice/include/config/mini/pin_auth.h b/services/devicemanagerservice/include/config/mini/pin_auth.h new file mode 100644 index 000000000..9b4edfbcc --- /dev/null +++ b/services/devicemanagerservice/include/config/mini/pin_auth.h @@ -0,0 +1,42 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef OHOS_DM_PIN_AUTH_H +#define OHOS_DM_PIN_AUTH_H + +#include +#include + +#include "authentication.h" +#include "dm_auth_manager.h" +#include "dm_ability_manager.h" + +namespace OHOS { +namespace DistributedHardware { +class PinAuth : public IAuthentication { +public: + PinAuth(); + ~PinAuth(); + int32_t ShowAuthInfo(std::string &authToken, std::shared_ptr authManager) override; + int32_t StartAuth(std::string &authToken, std::shared_ptr authManager) override; + int32_t VerifyAuthentication(std::string &authToken, const std::string &authParam) override; + +private: + int32_t times_ = 0; + // std::shared_ptr pinAuthUi_; +}; +} // namespace DistributedHardware +} // namespace OHOS +#endif // OHOS_DM_PIN_AUTH_H diff --git a/services/devicemanagerservice/include/dependency/commonevent/dm_common_event_manager.h b/services/devicemanagerservice/include/dependency/commonevent/dm_common_event_manager.h index 81d51bb2a..850e861d3 100644 --- a/services/devicemanagerservice/include/dependency/commonevent/dm_common_event_manager.h +++ b/services/devicemanagerservice/include/dependency/commonevent/dm_common_event_manager.h @@ -18,53 +18,53 @@ #include #include -#include +// #include -#include "common_event.h" -#include "common_event_data.h" -#include "common_event_manager.h" -#include "common_event_subscribe_info.h" -#include "common_event_subscriber.h" +// #include "common_event.h" +// #include "common_event_data.h" +// #include "common_event_manager.h" +// #include "common_event_subscribe_info.h" +// #include "common_event_subscriber.h" #include "dm_log.h" -#include "matching_skills.h" +// #include "matching_skills.h" #include "single_instance.h" namespace OHOS { namespace DistributedHardware { -using CommomEventCallback = std::function; +// using CommomEventCallback = std::function; -struct CommomEventCallbackNode { - int32_t input_; - CommomEventCallback callback_; -}; +// struct CommomEventCallbackNode { +// int32_t input_; +// CommomEventCallback callback_; +// }; -class DmCommonEventManager { -DECLARE_SINGLE_INSTANCE_BASE(DmCommonEventManager); -public: - bool SubscribeServiceEvent(const std::string &event, const CommomEventCallback callback); - bool UnsubscribeServiceEvent(const std::string &event); - class EventSubscriber : public EventFwk::CommonEventSubscriber { - public: - EventSubscriber(const EventFwk::CommonEventSubscribeInfo &subscribeInfo, const CommomEventCallback &callback, - const std::string &event) : EventFwk::CommonEventSubscriber(subscribeInfo), - callback_(callback), event_(event) {} - void OnReceiveEvent(const EventFwk::CommonEventData &data); - private: - CommomEventCallback callback_; - std::string event_; - }; -private: - DmCommonEventManager(); - ~DmCommonEventManager(); -private: - static void DealCallback(void); -private: - static std::mutex callbackQueueMutex_; - static std::mutex eventSubscriberMutex_; - static std::condition_variable notEmpty_; - static std::list callbackQueue_; - std::map> dmEventSubscriber_; -}; +// class DmCommonEventManager { +// DECLARE_SINGLE_INSTANCE_BASE(DmCommonEventManager); +// public: +// bool SubscribeServiceEvent(const std::string &event, const CommomEventCallback callback); +// bool UnsubscribeServiceEvent(const std::string &event); + // class EventSubscriber : public EventFwk::CommonEventSubscriber { + // public: + // EventSubscriber(const EventFwk::CommonEventSubscribeInfo &subscribeInfo, const CommomEventCallback &callback, + // const std::string &event) : EventFwk::CommonEventSubscriber(subscribeInfo), + // callback_(callback), event_(event) {} + // void OnReceiveEvent(const EventFwk::CommonEventData &data); + // private: + // CommomEventCallback callback_; + // std::string event_; + // }; +// private: +// DmCommonEventManager(); +// ~DmCommonEventManager(); +// private: +// static void DealCallback(void); +// private: + // static std::mutex callbackQueueMutex_; + // static std::mutex eventSubscriberMutex_; + // static std::condition_variable notEmpty_; + // static std::list callbackQueue_; + // std::map> dmEventSubscriber_; +// }; } // namespace DistributedHardware } // namespace OHOS #endif // OHOS_EVENT_MANAGER_ADAPT_H \ No newline at end of file diff --git a/services/devicemanagerservice/include/dependency/hichain/hichain_connector.h b/services/devicemanagerservice/include/dependency/hichain/hichain_connector.h index 6c19fe3fd..b8aa3708c 100644 --- a/services/devicemanagerservice/include/dependency/hichain/hichain_connector.h +++ b/services/devicemanagerservice/include/dependency/hichain/hichain_connector.h @@ -46,9 +46,9 @@ void from_json(const nlohmann::json &jsonObject, GroupInfo &groupInfo); class HiChainConnector { public: static bool onTransmit(int64_t requestId, const uint8_t *data, uint32_t dataLen); - static void onFinish(int64_t requestId, int32_t operationCode, const char *returnData); - static void onError(int64_t requestId, int32_t operationCode, int32_t errorCode, const char *errorReturn); - static char *onRequest(int64_t requestId, int32_t operationCode, const char *reqParams); + static void onFinish(int64_t requestId, int operationCode, const char *returnData); + static void onError(int64_t requestId, int operationCode, int errorCode, const char *errorReturn); + static char *onRequest(int64_t requestId, int operationCode, const char *reqParams); public: HiChainConnector(); diff --git a/services/devicemanagerservice/include/dependency/softbus/softbus_connector.h b/services/devicemanagerservice/include/dependency/softbus/softbus_connector.h index a7f5f3aa7..3ffc59eb4 100644 --- a/services/devicemanagerservice/include/dependency/softbus/softbus_connector.h +++ b/services/devicemanagerservice/include/dependency/softbus/softbus_connector.h @@ -34,14 +34,14 @@ namespace OHOS { namespace DistributedHardware { class SoftbusConnector { public: - static void OnPublishSuccess(int32_t publishId); - static void OnPublishFail(int32_t publishId, PublishFailReason reason); + static void OnPublishSuccess(int publishId); + static void OnPublishFail(int publishId, PublishFailReason reason); static void OnSoftBusDeviceOnline(NodeBasicInfo *info); static void OnSoftbusDeviceOffline(NodeBasicInfo *info); static void OnSoftbusDeviceInfoChanged(NodeBasicInfoType type, NodeBasicInfo *info); static void OnSoftbusDeviceFound(const DeviceInfo *device); - static void OnSoftbusDiscoveryFailed(int32_t subscribeId, DiscoveryFailReason failReason); - static void OnSoftbusDiscoverySuccess(int32_t subscribeId); + static void OnSoftbusDiscoveryFailed(int subscribeId, DiscoveryFailReason failReason); + static void OnSoftbusDiscoverySuccess(int subscribeId); static void OnParameterChgCallback(const char *key, const char *value, void *context); static int32_t GetConnectionIpAddress(const std::string &deviceId, std::string &ipAddress); static ConnectionAddr *GetConnectAddr(const std::string &deviceId, std::string &connectAddr); diff --git a/services/devicemanagerservice/include/dependency/softbus/softbus_session.h b/services/devicemanagerservice/include/dependency/softbus/softbus_session.h index 2eab337e6..a62cbc037 100644 --- a/services/devicemanagerservice/include/dependency/softbus/softbus_session.h +++ b/services/devicemanagerservice/include/dependency/softbus/softbus_session.h @@ -30,9 +30,9 @@ namespace OHOS { namespace DistributedHardware { class SoftbusSession { public: - static int32_t OnSessionOpened(int32_t sessionId, int32_t result); - static void OnSessionClosed(int32_t sessionId); - static void OnBytesReceived(int32_t sessionId, const void *data, uint32_t dataLen); + static int OnSessionOpened(int sessionId, int result); + static void OnSessionClosed(int sessionId); + static void OnBytesReceived(int sessionId, const void *data, unsigned int dataLen); public: SoftbusSession(); diff --git a/services/devicemanagerservice/include/dependency/timer/dm_timer.h b/services/devicemanagerservice/include/dependency/timer/dm_timer.h index a4ffec0fd..09d9e596b 100644 --- a/services/devicemanagerservice/include/dependency/timer/dm_timer.h +++ b/services/devicemanagerservice/include/dependency/timer/dm_timer.h @@ -18,12 +18,15 @@ #include #include #include +#if (defined(__LINUX__) || defined(__LITEOS_A__)) #include +#include #include - +#endif #include #include -#include +#include "dm_log.h" + #include "dm_log.h" @@ -60,10 +63,13 @@ private: TimeoutHandle mHandle_; void *mHandleData_; int32_t mTimeFd_[2]; +#if (defined(__LINUX__) || defined(__LITEOS_A__)) struct epoll_event mEv_; struct epoll_event mEvents_[MAX_EVENTS]; - int32_t mEpFd_; std::thread mThread_; + int32_t mEpFd_; +#endif + std::string mTimerName_; }; } // namespace DistributedHardware diff --git a/services/devicemanagerservice/include/device_manager_service.h b/services/devicemanagerservice/include/device_manager_service.h index a810768fe..ab093c9c3 100644 --- a/services/devicemanagerservice/include/device_manager_service.h +++ b/services/devicemanagerservice/include/device_manager_service.h @@ -19,14 +19,14 @@ #include #include -// #include "dm_ability_manager.h" -// #include "dm_auth_manager.h" +#include "dm_ability_manager.h" +#include "dm_auth_manager.h" #include "dm_device_info.h" -// #include "dm_device_info_manager.h" -// #include "dm_device_state_manager.h" -// #include "dm_discovery_manager.h" +#include "dm_device_info_manager.h" +#include "dm_device_state_manager.h" +#include "dm_discovery_manager.h" #include "single_instance.h" -// #include "softbus_connector.h" +#include "softbus_connector.h" #include "dm_subscribe_info.h" @@ -56,14 +56,14 @@ public: private: DeviceManagerService() = default; bool intFlag_ = false; - // std::shared_ptr authMgr_; - // std::shared_ptr deviceInfoMgr_; - // std::shared_ptr deviceStateMgr_; - // std::shared_ptr discoveryMgr_; - // std::shared_ptr softbusConnector_; - // std::shared_ptr listener_; - // std::shared_ptr abilityMgr_; - // std::shared_ptr hiChainConnector_; + std::shared_ptr authMgr_; + std::shared_ptr deviceInfoMgr_; + std::shared_ptr deviceStateMgr_; + std::shared_ptr discoveryMgr_; + std::shared_ptr softbusConnector_; + std::shared_ptr listener_; + std::shared_ptr abilityMgr_; + std::shared_ptr hiChainConnector_; }; } // namespace DistributedHardware } // namespace OHOS diff --git a/services/devicemanagerservice/include/devicestate/dm_device_state_manager.h b/services/devicemanagerservice/include/devicestate/dm_device_state_manager.h index f34198c37..1b5d910c2 100755 --- a/services/devicemanagerservice/include/devicestate/dm_device_state_manager.h +++ b/services/devicemanagerservice/include/devicestate/dm_device_state_manager.h @@ -18,8 +18,11 @@ #include #include +#if (defined(__LINUX__) || defined(__LITEOS_A__)) #include - +#else +#include +#endif #include "device_manager_service_listener.h" #include "dm_adapter_manager.h" #include "softbus_connector.h" @@ -54,8 +57,12 @@ public: private: std::string profileSoName_; +#if (defined(__LINUX__) || defined(__LITEOS_A__)) std::mutex timerMapMutex_; std::mutex remoteDeviceInfosMutex_; +#else + pthread_mutex_t lock_; +#endif std::shared_ptr softbusConnector_; std::shared_ptr listener_; std::map remoteDeviceInfos_; diff --git a/services/devicemanagerservice/src/authentication/dm_auth_manager.cpp b/services/devicemanagerservice/src/authentication/dm_auth_manager.cpp index 359721a01..2bc633f99 100644 --- a/services/devicemanagerservice/src/authentication/dm_auth_manager.cpp +++ b/services/devicemanagerservice/src/authentication/dm_auth_manager.cpp @@ -25,9 +25,9 @@ #include "multiple_user_connector.h" #include "nlohmann/json.hpp" #include "parameter.h" -#include "ui_service_mgr_client.h" -#include "dialog_callback_stub.h" -#include "dialog_callback.h" +// #include "ui_service_mgr_client.h" +// #include "dialog_callback_stub.h" +// #include "dialog_callback.h" namespace OHOS { namespace DistributedHardware { @@ -540,7 +540,7 @@ int32_t DmAuthManager::AddMember(const std::string &deviceId) return DM_FAILED; } LOGI("DmAuthManager::authRequestContext CancelDisplay start"); - Ace::UIServiceMgrClient::GetInstance()->CancelDialog(authResponseContext_->pageId); + // Ace::UIServiceMgrClient::GetInstance()->CancelDialog(authResponseContext_->pageId); return DM_OK; } @@ -569,9 +569,9 @@ void DmAuthManager::AuthenticateFinish() { LOGI("DmAuthManager::AuthenticateFinish start"); if (authResponseState_ != nullptr) { - if (authResponseState_->GetStateType() == AuthState::AUTH_RESPONSE_FINISH) { - Ace::UIServiceMgrClient::GetInstance()->CancelDialog(authResponseContext_->pageId); - } + // if (authResponseState_->GetStateType() == AuthState::AUTH_RESPONSE_FINISH) { + // Ace::UIServiceMgrClient::GetInstance()->CancelDialog(authResponseContext_->pageId); + // } if (authResponseState_->GetStateType() == AuthState::AUTH_RESPONSE_SHOW && authResponseContext_->authType != 1) { authMessageProcessor_->SetResponseContext(authResponseContext_); @@ -597,9 +597,9 @@ void DmAuthManager::AuthenticateFinish() authResponseContext_->state = AuthState::AUTH_REQUEST_INIT; } - if (authResponseContext_->state == AuthState::AUTH_REQUEST_INPUT) { - Ace::UIServiceMgrClient::GetInstance()->CancelDialog(authResponseContext_->pageId); - } + // if (authResponseContext_->state == AuthState::AUTH_REQUEST_INPUT) { + // Ace::UIServiceMgrClient::GetInstance()->CancelDialog(authResponseContext_->pageId); + // } listener_->OnAuthResult(authRequestContext_->hostPkgName, authRequestContext_->deviceId, authRequestContext_->token, authResponseContext_->state, authRequestContext_->reason); @@ -698,16 +698,16 @@ void DmAuthManager::ShowConfigDialog() const std::string params = jsonObj.dump(); std::shared_ptr authMgr_ = shared_from_this(); - Ace::UIServiceMgrClient::GetInstance()->ShowDialog( - "config_dialog_service", - params, - OHOS::Rosen::WindowType::WINDOW_TYPE_SYSTEM_ALARM_WINDOW, - ACE_X, ACE_Y, ACE_WIDTH, ACE_HEIGHT, - [authMgr_](int32_t id, const std::string& event, const std::string& params) { - Ace::UIServiceMgrClient::GetInstance()->CancelDialog(id); - LOGI("CancelDialog start id:%d,event:%s,parms:%s", id, event.c_str(), params.c_str()); - authMgr_->StartAuthProcess(atoi(params.c_str())); - }); + // Ace::UIServiceMgrClient::GetInstance()->ShowDialog( + // "config_dialog_service", + // params, + // OHOS::Rosen::WindowType::WINDOW_TYPE_SYSTEM_ALARM_WINDOW, + // ACE_X, ACE_Y, ACE_WIDTH, ACE_HEIGHT, + // [authMgr_](int32_t id, const std::string& event, const std::string& params) { + // Ace::UIServiceMgrClient::GetInstance()->CancelDialog(id); + // LOGI("CancelDialog start id:%d,event:%s,parms:%s", id, event.c_str(), params.c_str()); + // authMgr_->StartAuthProcess(atoi(params.c_str())); + // }); LOGI("ShowConfigDialog end"); } diff --git a/services/devicemanagerservice/src/config/mini/dm_config_manager.cpp b/services/devicemanagerservice/src/config/mini/dm_config_manager.cpp new file mode 100644 index 000000000..63bc1df57 --- /dev/null +++ b/services/devicemanagerservice/src/config/mini/dm_config_manager.cpp @@ -0,0 +1,67 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +#include "dm_config_manager.h" +#include "dm_constants.h" +#include "dm_log.h" +#include "pin_auth.h" + +namespace OHOS { +namespace DistributedHardware { + + +DmConfigManager &DmConfigManager::GetInstance() +{ + static DmConfigManager instance; + return instance; +} + +DmConfigManager::DmConfigManager() +{ + LOGI("DmConfigManager constructor"); +} + +DmConfigManager::~DmConfigManager() +{ + LOGI("DmAdapterManager destructor"); +} + +std::shared_ptr DmConfigManager::GetDecisionAdapter(const std::string &soName) +{ + return nullptr; +} + +std::shared_ptr DmConfigManager::GetProfileAdapter(const std::string &soName) +{ + return nullptr; +} + +std::shared_ptr DmConfigManager::GetCryptoAdapter(const std::string &soName) +{ + return nullptr; +} + +extern "C" IAuthentication *CreatePinAuthObject(void) +{ + return new PinAuth; +} + +void DmConfigManager::GetAuthAdapter(std::map> &authAdapter) +{ + authAdapter.clear(); + std::shared_ptr iAuthentication(CreatePinAuthObject()); + authAdapter[1] = iAuthentication; +} +} // namespace DistributedHardware +} // namespace OHOS \ No newline at end of file diff --git a/services/devicemanagerservice/src/config/mini/pin_auth.cpp b/services/devicemanagerservice/src/config/mini/pin_auth.cpp new file mode 100644 index 000000000..ffdf88c0b --- /dev/null +++ b/services/devicemanagerservice/src/config/mini/pin_auth.cpp @@ -0,0 +1,82 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "pin_auth.h" + +#include + +#include "dm_constants.h" +#include "dm_log.h" +#include "nlohmann/json.hpp" + +namespace OHOS { +namespace DistributedHardware { +const int32_t MAX_VERIFY_TIMES = 3; +PinAuth::PinAuth() +{ + LOGI("PinAuth constructor"); +} + +PinAuth::~PinAuth() +{ +} + +int32_t PinAuth::ShowAuthInfo(std::string &authToken, std::shared_ptr authManager) +{ + LOGI("ShowConfigDialog end"); + return DM_OK; +} + +int32_t PinAuth::StartAuth(std::string &authToken, std::shared_ptr authManager) +{ + LOGI("StartAuth end"); + return DM_OK; +} + +int32_t PinAuth::VerifyAuthentication(std::string &authToken, const std::string &authParam) +{ + times_ += 1; + nlohmann::json authParamJson = nlohmann::json::parse(authParam, nullptr, false); + if (authParamJson.is_discarded()) { + LOGE("DecodeRequestAuth jsonStr error"); + return DM_FAILED; + } + nlohmann::json authTokenJson = nlohmann::json::parse(authToken, nullptr, false); + if (authParamJson.is_discarded()) { + LOGE("DecodeRequestAuth jsonStr error"); + return DM_FAILED; + } + if (!authParamJson.contains(PIN_CODE_KEY) && !authParamJson.contains(PIN_TOKEN)) { + if (authParam == "0") { + return DM_OK; + } + LOGE("err json string, first time"); + return DM_FAILED; + } + int32_t code = authTokenJson[PIN_CODE_KEY]; + int32_t pinToken = authTokenJson[PIN_TOKEN]; + int32_t inputPinCode = authParamJson[PIN_CODE_KEY]; + int32_t inputPinToken = authParamJson[PIN_TOKEN]; + if (code == inputPinCode && pinToken == inputPinToken) { + return DM_OK; + } else if (code != inputPinCode && times_ < MAX_VERIFY_TIMES) { + return DM_AUTH_INPUT_FAILED; + } else { + return DM_FAILED; + } +} + +} // namespace DistributedHardware +} // namespace OHOS diff --git a/services/devicemanagerservice/src/dependency/commonevent/dm_common_event_manager.cpp b/services/devicemanagerservice/src/dependency/commonevent/dm_common_event_manager.cpp index 798174abe..c25038d00 100644 --- a/services/devicemanagerservice/src/dependency/commonevent/dm_common_event_manager.cpp +++ b/services/devicemanagerservice/src/dependency/commonevent/dm_common_event_manager.cpp @@ -15,124 +15,124 @@ #include "dm_common_event_manager.h" -#include +// #include #include "dm_constants.h" -using namespace OHOS::EventFwk; +// using namespace OHOS::EventFwk; namespace OHOS { namespace DistributedHardware { -std::mutex DmCommonEventManager::callbackQueueMutex_; -std::mutex DmCommonEventManager::eventSubscriberMutex_; -std::condition_variable DmCommonEventManager::notEmpty_; -std::list DmCommonEventManager::callbackQueue_; - -DmCommonEventManager &DmCommonEventManager::GetInstance() -{ - static DmCommonEventManager instance; - return instance; -} - -DmCommonEventManager::DmCommonEventManager() -{ - std::thread th(DealCallback); - th.detach(); -} - -DmCommonEventManager::~DmCommonEventManager() -{ - std::unique_lock mutexLock(eventSubscriberMutex_); - for (auto iter = dmEventSubscriber_.begin(); iter != dmEventSubscriber_.end(); iter++) { - if (!CommonEventManager::UnSubscribeCommonEvent(iter->second)) { - LOGI("Unsubscribe service event failed: %s", iter->first.c_str()); - } - } -} - -void DmCommonEventManager::DealCallback(void) -{ - while (1) { - std::unique_lock callbackQueueMutexLock(callbackQueueMutex_); - notEmpty_.wait(callbackQueueMutexLock, [] { return !callbackQueue_.empty(); }); - CommomEventCallbackNode node = callbackQueue_.front(); - int32_t input = node.input_; - CommomEventCallback funcPrt = node.callback_; - funcPrt(input); - callbackQueue_.pop_front(); - } -} - -bool DmCommonEventManager::SubscribeServiceEvent(const std::string &event, const CommomEventCallback callback) -{ - LOGI("Subscribe event: %s", event.c_str()); - if (dmEventSubscriber_.find(event) != dmEventSubscriber_.end() || callback == nullptr) { - LOGE("Subscribe event:%s has been exist or callback is nullptr", event.c_str()); - return false; - } - - MatchingSkills matchingSkills; - matchingSkills.AddEvent(event); - CommonEventSubscribeInfo subscriberInfo(matchingSkills); - std::shared_ptr subscriber = - std::make_shared(subscriberInfo, callback, event); - if (subscriber == nullptr) { - LOGE("subscriber is nullptr %s", event.c_str()); - return false; - } +// std::mutex DmCommonEventManager::callbackQueueMutex_; +// std::mutex DmCommonEventManager::eventSubscriberMutex_; +// std::condition_variable DmCommonEventManager::notEmpty_; +// std::list DmCommonEventManager::callbackQueue_; + +// DmCommonEventManager &DmCommonEventManager::GetInstance() +// { +// static DmCommonEventManager instance; +// return instance; +// } + +// DmCommonEventManager::DmCommonEventManager() +// { +// std::thread th(DealCallback); +// th.detach(); +// } + +// DmCommonEventManager::~DmCommonEventManager() +// { +// std::unique_lock mutexLock(eventSubscriberMutex_); +// for (auto iter = dmEventSubscriber_.begin(); iter != dmEventSubscriber_.end(); iter++) { +// if (!CommonEventManager::UnSubscribeCommonEvent(iter->second)) { +// LOGI("Unsubscribe service event failed: %s", iter->first.c_str()); +// } +// } +// } + +// void DmCommonEventManager::DealCallback(void) +// { +// while (1) { +// std::unique_lock callbackQueueMutexLock(callbackQueueMutex_); +// notEmpty_.wait(callbackQueueMutexLock, [] { return !callbackQueue_.empty(); }); +// CommomEventCallbackNode node = callbackQueue_.front(); +// int32_t input = node.input_; +// CommomEventCallback funcPrt = node.callback_; +// funcPrt(input); +// callbackQueue_.pop_front(); +// } +// } + +// bool DmCommonEventManager::SubscribeServiceEvent(const std::string &event, const CommomEventCallback callback) +// { +// LOGI("Subscribe event: %s", event.c_str()); +// if (dmEventSubscriber_.find(event) != dmEventSubscriber_.end() || callback == nullptr) { +// LOGE("Subscribe event:%s has been exist or callback is nullptr", event.c_str()); +// return false; +// } + +// MatchingSkills matchingSkills; +// matchingSkills.AddEvent(event); +// CommonEventSubscribeInfo subscriberInfo(matchingSkills); +// std::shared_ptr subscriber = +// std::make_shared(subscriberInfo, callback, event); +// if (subscriber == nullptr) { +// LOGE("subscriber is nullptr %s", event.c_str()); +// return false; +// } - if (!CommonEventManager::SubscribeCommonEvent(subscriber)) { - LOGE("Subscribe service event failed: %s", event.c_str()); - return false; - } - - std::unique_lock mutexLock(eventSubscriberMutex_); - dmEventSubscriber_[event] = subscriber; - return true; -} - -bool DmCommonEventManager::UnsubscribeServiceEvent(const std::string &event) -{ - LOGI("UnSubscribe event: %s", event.c_str()); - if (dmEventSubscriber_.find(event) == dmEventSubscriber_.end()) { - LOGE("UnSubscribe event: %s not been exist", event.c_str()); - return false; - } - - if (!CommonEventManager::UnSubscribeCommonEvent(dmEventSubscriber_[event])) { - LOGE("Unsubscribe service event failed: %s", event.c_str()); - return false; - } - - std::unique_lock mutexLock(eventSubscriberMutex_); - dmEventSubscriber_.erase(event); - return true; -} - -void DmCommonEventManager::EventSubscriber::OnReceiveEvent(const CommonEventData &data) -{ - std::string receiveEvent = data.GetWant().GetAction(); - LOGI("Received event: %s", receiveEvent.c_str()); - if (receiveEvent != event_) { - LOGE("Received event is error"); - return; - } - - int32_t userId = data.GetCode(); - if (userId <= 0) { - LOGE("userId is less zero"); - return; - } +// if (!CommonEventManager::SubscribeCommonEvent(subscriber)) { +// LOGE("Subscribe service event failed: %s", event.c_str()); +// return false; +// } + +// std::unique_lock mutexLock(eventSubscriberMutex_); +// dmEventSubscriber_[event] = subscriber; +// return true; +// } + +// bool DmCommonEventManager::UnsubscribeServiceEvent(const std::string &event) +// { +// LOGI("UnSubscribe event: %s", event.c_str()); +// if (dmEventSubscriber_.find(event) == dmEventSubscriber_.end()) { +// LOGE("UnSubscribe event: %s not been exist", event.c_str()); +// return false; +// } + +// if (!CommonEventManager::UnSubscribeCommonEvent(dmEventSubscriber_[event])) { +// LOGE("Unsubscribe service event failed: %s", event.c_str()); +// return false; +// } + +// std::unique_lock mutexLock(eventSubscriberMutex_); +// dmEventSubscriber_.erase(event); +// return true; +// } + +// void DmCommonEventManager::EventSubscriber::OnReceiveEvent(const CommonEventData &data) +// { +// std::string receiveEvent = data.GetWant().GetAction(); +// LOGI("Received event: %s", receiveEvent.c_str()); +// if (receiveEvent != event_) { +// LOGE("Received event is error"); +// return; +// } + +// int32_t userId = data.GetCode(); +// if (userId <= 0) { +// LOGE("userId is less zero"); +// return; +// } - std::unique_lock callbackQueueMutexLock(callbackQueueMutex_); - if (callbackQueue_.size() > COMMON_CALLBACK_MAX_SIZE) { - LOGE("event callback Queue is too long"); - return; - } - - CommomEventCallbackNode node {userId, callback_}; - callbackQueue_.push_back(node); - notEmpty_.notify_one(); -} +// std::unique_lock callbackQueueMutexLock(callbackQueueMutex_); +// if (callbackQueue_.size() > COMMON_CALLBACK_MAX_SIZE) { +// LOGE("event callback Queue is too long"); +// return; +// } + +// CommomEventCallbackNode node {userId, callback_}; +// callbackQueue_.push_back(node); +// notEmpty_.notify_one(); +// } } // namespace DistributedHardware } // namespace OHOS \ No newline at end of file diff --git a/services/devicemanagerservice/src/dependency/hichain/hichain_connector.cpp b/services/devicemanagerservice/src/dependency/hichain/hichain_connector.cpp index dd4afeb86..5c739f292 100644 --- a/services/devicemanagerservice/src/dependency/hichain/hichain_connector.cpp +++ b/services/devicemanagerservice/src/dependency/hichain/hichain_connector.cpp @@ -60,7 +60,7 @@ std::shared_ptr HiChainConnector::hiChainConnectorCal HiChainConnector::HiChainConnector() { LOGI("HiChainConnector::constructor"); - deviceAuthCallback_ = {.onTransmit = nullptr, + deviceAuthCallback_ = DeviceAuthCallback {.onTransmit = nullptr, .onFinish = HiChainConnector::onFinish, .onError = HiChainConnector::onError, .onRequest = HiChainConnector::onRequest}; @@ -250,7 +250,7 @@ int32_t HiChainConnector::AddMember(std::string deviceId, std::string &connectIn return ret; } -void HiChainConnector::onFinish(int64_t requestId, int32_t operationCode, const char *returnData) +void HiChainConnector::onFinish(int64_t requestId, int operationCode, const char *returnData) { std::string data = ""; if (returnData != nullptr) { @@ -273,7 +273,7 @@ void HiChainConnector::onFinish(int64_t requestId, int32_t operationCode, const } } -void HiChainConnector::onError(int64_t requestId, int32_t operationCode, int32_t errorCode, const char *errorReturn) +void HiChainConnector::onError(int64_t requestId, int operationCode, int errorCode, const char *errorReturn) { (void)errorReturn; LOGI("HichainAuthenCallBack::onError reqId:%lld, operation:%d, errorCode:%d.", requestId, operationCode, errorCode); @@ -293,7 +293,7 @@ void HiChainConnector::onError(int64_t requestId, int32_t operationCode, int32_t } } -char *HiChainConnector::onRequest(int64_t requestId, int32_t operationCode, const char *reqParams) +char *HiChainConnector::onRequest(int64_t requestId, int operationCode, const char *reqParams) { if (operationCode != GroupOperationCode::MEMBER_JOIN) { LOGE("HiChainAuthCallBack::onRequest operationCode %d", operationCode); diff --git a/services/devicemanagerservice/src/dependency/multipleuser/multiple_user_connector.cpp b/services/devicemanagerservice/src/dependency/multipleuser/multiple_user_connector.cpp index 4168ce99e..934374ffc 100644 --- a/services/devicemanagerservice/src/dependency/multipleuser/multiple_user_connector.cpp +++ b/services/devicemanagerservice/src/dependency/multipleuser/multiple_user_connector.cpp @@ -17,9 +17,9 @@ #include "dm_constants.h" #include "dm_log.h" -#include "os_account_manager.h" +// #include "os_account_manager.h" -using namespace OHOS::AccountSA; +// using namespace OHOS::AccountSA; namespace OHOS { namespace DistributedHardware { @@ -27,12 +27,13 @@ int32_t MultipleUserConnector::oldUserId_ = -1; int32_t MultipleUserConnector::GetCurrentAccountUserID(void) { - std::vector ids; - ErrCode ret = OsAccountManager::QueryActiveOsAccountIds(ids); - if (ret != ERR_OK || ids.empty()) { - return -1; - } - return ids[0]; + // std::vector ids; + // ErrCode ret = OsAccountManager::QueryActiveOsAccountIds(ids); + // if (ret != ERR_OK || ids.empty()) { + // return -1; + // } + // return ids[0]; + return 0; } void MultipleUserConnector::SetSwitchOldUserId(int32_t userId) diff --git a/services/devicemanagerservice/src/dependency/softbus/softbus_connector.cpp b/services/devicemanagerservice/src/dependency/softbus/softbus_connector.cpp index f3278fe8e..ec4c3f369 100644 --- a/services/devicemanagerservice/src/dependency/softbus/softbus_connector.cpp +++ b/services/devicemanagerservice/src/dependency/softbus/softbus_connector.cpp @@ -17,8 +17,12 @@ #include #include +#if (defined(__LINUX__) || defined(__LITEOS_A__)) #include #include +#else +#include +#endif #include "dm_anonymous.h" #include "dm_constants.h" @@ -27,6 +31,9 @@ #include "nlohmann/json.hpp" #include "parameter.h" #include "system_ability_definition.h" +#if defined(__LITEOS_M__) +#include "get_trustdevice_rsp.h" +#endif namespace OHOS { namespace DistributedHardware { @@ -49,6 +56,7 @@ INodeStateCb SoftbusConnector::softbusNodeStateCb_ = { .onNodeOffline = SoftbusConnector::OnSoftbusDeviceOffline, .onNodeBasicInfoChanged = SoftbusConnector::OnSoftbusDeviceInfoChanged}; +#if (defined(__LINUX__) || defined(__LITEOS_A__)) void DeviceOnLine(std::map> stateCallbackMap, DmDeviceInfo deviceInfo) { @@ -72,6 +80,67 @@ void DeviceOffLine(std::map> } LOGI("Device off line end"); } +#else +void DeviceOnLine(std::map> stateCallbackMap, + DmDeviceInfo deviceInfo) +{ + LOGI("Device on line start"); + pthread_mutex_t lockDeviceOnLine; + uint32_t ret = pthread_mutex_init(&lockDeviceOnLine, NULL); + if (ret != 0) { + LOGI("init mutex lock failed: %d.",ret); + } + pthread_mutex_lock(&lockDeviceOnLine); + for (auto &iter : stateCallbackMap) { + iter.second->OnDeviceOnline(iter.first, deviceInfo); + } + pthread_mutex_unlock(&lockDeviceOnLine); + ret = pthread_mutex_destroy(&lockDeviceOnLine); + if (ret != 0) { + LOGI("destroy mutex lock failed: %d.",ret); + } + LOGI("Device on line end"); +} + +void DeviceOffLine(std::map> stateCallbackMap, + DmDeviceInfo deviceInfo) +{ + LOGI("Device off line start"); + pthread_mutex_t lockDeviceOffLine; + uint32_t ret = pthread_mutex_init(&lockDeviceOffLine, NULL); + if (ret != 0) { + LOGI("init mutex lock failed: %d.",ret); + } + pthread_mutex_lock(&lockDeviceOffLine); + for (auto &iter : stateCallbackMap) { + iter.second->OnDeviceOffline(iter.first, deviceInfo); + } + pthread_mutex_unlock(&lockDeviceOffLine); + ret = pthread_mutex_destroy(&lockDeviceOffLine); + if (ret != 0) { + LOGI("destroy mutex lock failed: %d.",ret); + } + LOGI("Device off line end"); +} +struct PthreadCallbackParameter{ + std::map> CallbackMap; + DmDeviceInfo dmDeviceInfo; +}; + +void* PthreadDeviceOnLine(void* parameterInfo) +{ + PthreadCallbackParameter *parameterStruct; + parameterStruct = static_cast(parameterInfo); + DeviceOnLine(parameterStruct->CallbackMap, parameterStruct->dmDeviceInfo); +} + +void* PthreadDeviceOffLine(void* parameterInfo) +{ + PthreadCallbackParameter *parameterStruct; + parameterStruct = static_cast(parameterInfo); + DeviceOffLine(parameterStruct->CallbackMap, parameterStruct->dmDeviceInfo); +} +#endif SoftbusConnector::SoftbusConnector() { @@ -132,7 +201,7 @@ int32_t SoftbusConnector::Init() LOGI("service unpublish result is : %d", ret); } - ret = WatchParameter(DISCOVER_STATUS_KEY.c_str(), &SoftbusConnector::OnParameterChgCallback, nullptr); + // ret = WatchParameter(DISCOVER_STATUS_KEY.c_str(), &SoftbusConnector::OnParameterChgCallback, nullptr); LOGI("register Watch Parameter result is : %d"); return ret; } @@ -166,6 +235,10 @@ int32_t SoftbusConnector::UnRegisterSoftbusStateCallback(const std::string &pkgN int32_t SoftbusConnector::GetTrustedDeviceList(std::vector &deviceInfoList) { LOGI("SoftbusConnector::GetTrustDevices start"); +#if defined(__LITEOS_M__) + std::shared_ptr prsp = std::make_shared(); + std::vector deviceInfoVec; +#endif int32_t infoNum = 0; NodeBasicInfo *nodeInfo = nullptr; int32_t ret = GetAllNodeDeviceInfo(DM_PKG_NAME.c_str(), &nodeInfo, &infoNum); @@ -185,6 +258,9 @@ int32_t SoftbusConnector::GetTrustedDeviceList(std::vector &device CovertNodeBasicInfoToDmDevice(*nodeBasicInfo, *deviceInfo); deviceInfoList.push_back(*deviceInfo); } +#if defined(__LITEOS_M__) + prsp->SetDeviceVec(deviceInfoVec); +#endif FreeNodeInfo(nodeInfo); free(info); LOGI("SoftbusConnector::GetTrustDevices success, deviceCount %d", infoNum); @@ -451,12 +527,12 @@ void SoftbusConnector::CovertDeviceInfoToDmDevice(const DeviceInfo &deviceInfo, dmDeviceInfo.deviceTypeId = deviceInfo.devType; } -void SoftbusConnector::OnPublishSuccess(int32_t publishId) +void SoftbusConnector::OnPublishSuccess(int publishId) { LOGI("SoftbusConnector::OnPublishSuccess, publishId: %d", publishId); } -void SoftbusConnector::OnPublishFail(int32_t publishId, PublishFailReason reason) +void SoftbusConnector::OnPublishFail(int publishId, PublishFailReason reason) { LOGI("SoftbusConnector::OnPublishFail failed, publishId: %d, reason: %d", publishId, reason); } @@ -469,10 +545,21 @@ void SoftbusConnector::OnSoftBusDeviceOnline(NodeBasicInfo *info) return; } +#if (defined(__LINUX__) || defined(__LITEOS_A__)) DmDeviceInfo dmDeviceInfo; CovertNodeBasicInfoToDmDevice(*info, dmDeviceInfo); std::thread deviceOnLine(DeviceOnLine, stateCallbackMap_, dmDeviceInfo); deviceOnLine.detach(); +#else + PthreadCallbackParameter parameterStruct; + parameterStruct.CallbackMap = stateCallbackMap_; + CovertNodeBasicInfoToDmDevice(*info, parameterStruct.dmDeviceInfo); + pthread_t tid; + pthread_attr_t attr; + pthread_attr_init(&attr); + pthread_attr_setdetachstate(&attr,PTHREAD_CREATE_DETACHED); + pthread_create(&tid, &attr, PthreadDeviceOnLine, static_cast(¶meterStruct)); +#endif if (discoveryDeviceInfoMap_.empty()) { return; @@ -496,10 +583,21 @@ void SoftbusConnector::OnSoftbusDeviceOffline(NodeBasicInfo *info) LOGE("OnSoftbusDeviceOffline NodeBasicInfo is nullptr"); return; } +#if (defined(__LINUX__) || defined(__LITEOS_A__)) DmDeviceInfo dmDeviceInfo; CovertNodeBasicInfoToDmDevice(*info, dmDeviceInfo); std::thread deviceOffLine(DeviceOffLine, stateCallbackMap_, dmDeviceInfo); deviceOffLine.detach(); +#else + PthreadCallbackParameter parameterStruct; + parameterStruct.CallbackMap = stateCallbackMap_; + CovertNodeBasicInfoToDmDevice(*info, parameterStruct.dmDeviceInfo); + pthread_t tid; + pthread_attr_t attr; + pthread_attr_init(&attr); + pthread_attr_setdetachstate(&attr,PTHREAD_CREATE_DETACHED); + pthread_create(&tid, &attr, PthreadDeviceOffLine, static_cast(¶meterStruct)); +#endif } void SoftbusConnector::OnSoftbusDeviceInfoChanged(NodeBasicInfoType type, NodeBasicInfo *info) @@ -537,7 +635,7 @@ void SoftbusConnector::OnSoftbusDeviceFound(const DeviceInfo *device) } } -void SoftbusConnector::OnSoftbusDiscoveryFailed(int32_t subscribeId, DiscoveryFailReason failReason) +void SoftbusConnector::OnSoftbusDiscoveryFailed(int subscribeId, DiscoveryFailReason failReason) { LOGI("In, subscribeId %d, failReason %d", subscribeId, (int32_t)failReason); uint16_t originId = (uint16_t)(((uint32_t)subscribeId) & SOFTBUS_SUBSCRIBE_ID_MASK); @@ -546,7 +644,7 @@ void SoftbusConnector::OnSoftbusDiscoveryFailed(int32_t subscribeId, DiscoveryFa } } -void SoftbusConnector::OnSoftbusDiscoverySuccess(int32_t subscribeId) +void SoftbusConnector::OnSoftbusDiscoverySuccess(int subscribeId) { LOGI("In, subscribeId %d", subscribeId); uint16_t originId = (uint16_t)(((uint32_t)subscribeId) & SOFTBUS_SUBSCRIBE_ID_MASK); diff --git a/services/devicemanagerservice/src/dependency/softbus/softbus_session.cpp b/services/devicemanagerservice/src/dependency/softbus/softbus_session.cpp index 8d4b55795..df6fb2fb0 100644 --- a/services/devicemanagerservice/src/dependency/softbus/softbus_session.cpp +++ b/services/devicemanagerservice/src/dependency/softbus/softbus_session.cpp @@ -119,7 +119,7 @@ int32_t SoftbusSession::SendData(int32_t sessionId, std::string &message) return DM_OK; } -int32_t SoftbusSession::OnSessionOpened(int32_t sessionId, int32_t result) +int SoftbusSession::OnSessionOpened(int sessionId, int result) { int32_t sessionSide = GetSessionSide(sessionId); sessionCallback_->OnSessionOpened(sessionId, sessionSide, result); @@ -127,12 +127,12 @@ int32_t SoftbusSession::OnSessionOpened(int32_t sessionId, int32_t result) return DM_OK; } -void SoftbusSession::OnSessionClosed(int32_t sessionId) +void SoftbusSession::OnSessionClosed(int sessionId) { LOGI("OnSessionClosed, sessionId:%d", sessionId); } -void SoftbusSession::OnBytesReceived(int32_t sessionId, const void *data, uint32_t dataLen) +void SoftbusSession::OnBytesReceived(int sessionId, const void *data, unsigned int dataLen) { LOGI("OnBytesReceived, sessionId:%d, dataLen:%d", sessionId, dataLen); if (sessionId < 0 || data == nullptr || dataLen <= 0) { diff --git a/services/devicemanagerservice/src/dependency/timer/mini/dm_timer.cpp b/services/devicemanagerservice/src/dependency/timer/mini/dm_timer.cpp new file mode 100644 index 000000000..b14a07695 --- /dev/null +++ b/services/devicemanagerservice/src/dependency/timer/mini/dm_timer.cpp @@ -0,0 +1,75 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "dm_timer.h" + +namespace OHOS { +namespace DistributedHardware { +namespace { +const int32_t MILL_SECONDS_PER_SECOND = 1000; +} +DmTimer::DmTimer(const std::string &name) +{ + if (name.empty()) { + LOGI("DmTimer name is null"); + return; + } + + LOGI("DmTimer %s Construct", name.c_str()); +} + +DmTimer::~DmTimer() +{ + if (mTimerName_.empty()) { + LOGI("DmTimer is not init"); + return; + } + LOGI("DmTimer %s Destroy in", mTimerName_.c_str()); +} + +DmTimerStatus DmTimer::Start(uint32_t timeOut, TimeoutHandle handle, void *data) +{ + LOGI("DmTimer start timeout(%d)", timeOut); + mStatus_ = DmTimerStatus::DM_STATUS_RUNNING; + return mStatus_; +} + +void DmTimer::Stop(int32_t code) +{ + LOGI("DmTimer Stop code (%d)", code); + return; +} + +void DmTimer::WaitForTimeout() +{ + +} + +int32_t DmTimer::CreateTimeFd() +{ + return 0; +} + +void DmTimer::Release() +{ + +} + +std::string DmTimer::GetTimerName() +{ + return mTimerName_; +} +} // namespace DistributedHardware +} // namespace OHOS diff --git a/services/devicemanagerservice/src/device_manager_service.cpp b/services/devicemanagerservice/src/device_manager_service.cpp index a0d03611e..bbb1c9ace 100644 --- a/services/devicemanagerservice/src/device_manager_service.cpp +++ b/services/devicemanagerservice/src/device_manager_service.cpp @@ -19,12 +19,12 @@ // #include "common_event_support.h" #include "device_manager_service_listener.h" -// #include "dm_common_event_manager.h" +#include "dm_common_event_manager.h" #include "dm_constants.h" -// #include "dm_device_info_manager.h" +#include "dm_device_info_manager.h" #include "dm_log.h" #include "multiple_user_connector.h" -// #include "permission_manager.h" +#include "permission_manager.h" // using namespace OHOS::EventFwk; @@ -39,8 +39,8 @@ DeviceManagerService::~DeviceManagerService() // if (dmCommonEventManager.UnsubscribeServiceEvent(CommonEventSupport::COMMON_EVENT_USER_STOPPED)) { // LOGI("subscribe service event success"); // } - // softbusConnector_->GetSoftbusSession()->UnRegisterSessionCallback(); - // hiChainConnector_->UnRegisterHiChainCallback(); + softbusConnector_->GetSoftbusSession()->UnRegisterSessionCallback(); + hiChainConnector_->UnRegisterHiChainCallback(); } int32_t DeviceManagerService::Init() @@ -50,69 +50,69 @@ int32_t DeviceManagerService::Init() return DM_INT_MULTIPLE; } - // if (!PermissionManager::GetInstance().CheckPermission()) { - // LOGI("The caller does not have permission to call"); - // return DM_NO_PERMISSION; - // } + if (!PermissionManager::GetInstance().CheckPermission()) { + LOGI("The caller does not have permission to call"); + return DM_NO_PERMISSION; + } - // if (softbusConnector_ == nullptr) { - // softbusConnector_ = std::make_shared(); - // if (softbusConnector_ == nullptr) { - // LOGE("Init failed, softbusConnector_ apply for failure"); - // return DM_MAKE_SHARED_FAIL; - // } - // } - // if (listener_ == nullptr) { - // listener_ = std::make_shared(); - // if (softbusConnector_ == nullptr) { - // LOGE("Init failed, listener_ apply for failure"); - // return DM_MAKE_SHARED_FAIL; - // } - // } - // if (hiChainConnector_ == nullptr) { - // hiChainConnector_ = std::make_shared(); - // if (hiChainConnector_ == nullptr) { - // LOGE("Init failed, hiChainConnector_ apply for failure"); - // return DM_MAKE_SHARED_FAIL; - // } - // } - // if (deviceInfoMgr_ == nullptr) { - // deviceInfoMgr_ = std::make_shared(softbusConnector_); - // if (deviceInfoMgr_ == nullptr) { - // LOGE("Init failed, deviceInfoMgr_ apply for failure"); - // return DM_MAKE_SHARED_FAIL; - // } - // } - // if (deviceStateMgr_ == nullptr) { - // deviceStateMgr_ = std::make_shared(softbusConnector_, listener_, hiChainConnector_); - // if (deviceStateMgr_ == nullptr) { - // LOGE("Init failed, deviceStateMgr_ apply for failure"); - // return DM_MAKE_SHARED_FAIL; - // } - // deviceStateMgr_->RegisterSoftbusStateCallback(); - // } - // if (discoveryMgr_ == nullptr) { - // discoveryMgr_ = std::make_shared(softbusConnector_, listener_); - // if (discoveryMgr_ == nullptr) { - // LOGE("Init failed, discoveryMgr_ apply for failure"); - // return DM_MAKE_SHARED_FAIL; - // } - // } - // if (authMgr_ == nullptr) { - // authMgr_ = std::make_shared(softbusConnector_, listener_, hiChainConnector_); - // if (authMgr_ == nullptr) { - // LOGE("Init failed, authMgr_ apply for failure"); - // return DM_MAKE_SHARED_FAIL; - // } - // softbusConnector_->GetSoftbusSession()->RegisterSessionCallback(authMgr_); - // hiChainConnector_->RegisterHiChainCallback(authMgr_); - // } + if (softbusConnector_ == nullptr) { + softbusConnector_ = std::make_shared(); + if (softbusConnector_ == nullptr) { + LOGE("Init failed, softbusConnector_ apply for failure"); + return DM_MAKE_SHARED_FAIL; + } + } + if (listener_ == nullptr) { + listener_ = std::make_shared(); + if (softbusConnector_ == nullptr) { + LOGE("Init failed, listener_ apply for failure"); + return DM_MAKE_SHARED_FAIL; + } + } + if (hiChainConnector_ == nullptr) { + hiChainConnector_ = std::make_shared(); + if (hiChainConnector_ == nullptr) { + LOGE("Init failed, hiChainConnector_ apply for failure"); + return DM_MAKE_SHARED_FAIL; + } + } + if (deviceInfoMgr_ == nullptr) { + deviceInfoMgr_ = std::make_shared(softbusConnector_); + if (deviceInfoMgr_ == nullptr) { + LOGE("Init failed, deviceInfoMgr_ apply for failure"); + return DM_MAKE_SHARED_FAIL; + } + } + if (deviceStateMgr_ == nullptr) { + deviceStateMgr_ = std::make_shared(softbusConnector_, listener_, hiChainConnector_); + if (deviceStateMgr_ == nullptr) { + LOGE("Init failed, deviceStateMgr_ apply for failure"); + return DM_MAKE_SHARED_FAIL; + } + deviceStateMgr_->RegisterSoftbusStateCallback(); + } + if (discoveryMgr_ == nullptr) { + discoveryMgr_ = std::make_shared(softbusConnector_, listener_); + if (discoveryMgr_ == nullptr) { + LOGE("Init failed, discoveryMgr_ apply for failure"); + return DM_MAKE_SHARED_FAIL; + } + } + if (authMgr_ == nullptr) { + authMgr_ = std::make_shared(softbusConnector_, listener_, hiChainConnector_); + if (authMgr_ == nullptr) { + LOGE("Init failed, authMgr_ apply for failure"); + return DM_MAKE_SHARED_FAIL; + } + softbusConnector_->GetSoftbusSession()->RegisterSessionCallback(authMgr_); + hiChainConnector_->RegisterHiChainCallback(authMgr_); + } - // int32_t userId = MultipleUserConnector::GetCurrentAccountUserID(); - // if (userId > 0) { - // LOGI("get current account user id success"); - // MultipleUserConnector::SetSwitchOldUserId(userId); - // } + int32_t userId = MultipleUserConnector::GetCurrentAccountUserID(); + if (userId > 0) { + LOGI("get current account user id success"); + MultipleUserConnector::SetSwitchOldUserId(userId); + } // DmCommonEventManager &dmCommonEventManager = DmCommonEventManager::GetInstance(); // CommomEventCallback callback = std::bind(&DmAuthManager::UserSwitchEventCallback, *authMgr_.get(), @@ -129,10 +129,10 @@ int32_t DeviceManagerService::Init() int32_t DeviceManagerService::GetTrustedDeviceList(const std::string &pkgName, const std::string &extra, std::vector &deviceList) { - // if (!PermissionManager::GetInstance().CheckPermission()) { - // LOGI("The caller does not have permission to call"); - // return DM_NO_PERMISSION; - // } + if (!PermissionManager::GetInstance().CheckPermission()) { + LOGI("The caller does not have permission to call"); + return DM_NO_PERMISSION; + } if (!intFlag_) { LOGE("GetTrustedDeviceList failed, singleton not init or init fail"); return DM_NOT_INIT; @@ -141,22 +141,20 @@ int32_t DeviceManagerService::GetTrustedDeviceList(const std::string &pkgName, c LOGE("GetTrustedDeviceList failed, pkgName is empty"); return DM_INPUT_PARA_EMPTY; } - // return deviceInfoMgr_->GetTrustedDeviceList(pkgName, extra, deviceList); - return 0; + return deviceInfoMgr_->GetTrustedDeviceList(pkgName, extra, deviceList); } int32_t DeviceManagerService::GetLocalDeviceInfo(DmDeviceInfo &info) { - // if (!PermissionManager::GetInstance().CheckPermission()) { - // LOGI("The caller does not have permission to call"); - // return DM_NO_PERMISSION; - // } + if (!PermissionManager::GetInstance().CheckPermission()) { + LOGI("The caller does not have permission to call"); + return DM_NO_PERMISSION; + } if (!intFlag_) { LOGE("GetLocalDeviceInfo failed, singleton not init or init fail"); return DM_NOT_INIT; } - // return deviceInfoMgr_->GetLocalDeviceInfo(info); - return 0; + return deviceInfoMgr_->GetLocalDeviceInfo(info); } int32_t DeviceManagerService::GetUdidByNetworkId(const std::string &pkgName, const std::string &netWorkId, @@ -171,7 +169,7 @@ int32_t DeviceManagerService::GetUdidByNetworkId(const std::string &pkgName, con LOGE("StartDeviceDiscovery failed, pkgName is empty"); return DM_INPUT_PARA_EMPTY; } - // SoftbusConnector::GetUdidByNetworkId(netWorkId.c_str(), udid); + SoftbusConnector::GetUdidByNetworkId(netWorkId.c_str(), udid); return DM_OK; } @@ -187,17 +185,17 @@ int32_t DeviceManagerService::GetUuidByNetworkId(const std::string &pkgName, con LOGE("StartDeviceDiscovery failed, pkgName is empty"); return DM_INPUT_PARA_EMPTY; } - // SoftbusConnector::GetUuidByNetworkId(netWorkId.c_str(), uuid); + SoftbusConnector::GetUuidByNetworkId(netWorkId.c_str(), uuid); return DM_OK; } int32_t DeviceManagerService::StartDeviceDiscovery(const std::string &pkgName, const DmSubscribeInfo &subscribeInfo, const std::string &extra) { - // if (!PermissionManager::GetInstance().CheckPermission()) { - // LOGI("The caller does not have permission to call"); - // return DM_NO_PERMISSION; - // } + if (!PermissionManager::GetInstance().CheckPermission()) { + LOGI("The caller does not have permission to call"); + return DM_NO_PERMISSION; + } if (!intFlag_) { LOGE("StartDeviceDiscovery failed, singleton not init or init fail"); return DM_NOT_INIT; @@ -206,16 +204,15 @@ int32_t DeviceManagerService::StartDeviceDiscovery(const std::string &pkgName, c LOGE("StartDeviceDiscovery failed, pkgName is empty"); return DM_INPUT_PARA_EMPTY; } - // return discoveryMgr_->StartDeviceDiscovery(pkgName, subscribeInfo, extra); - return 0; + return discoveryMgr_->StartDeviceDiscovery(pkgName, subscribeInfo, extra); } int32_t DeviceManagerService::StopDeviceDiscovery(const std::string &pkgName, uint16_t subscribeId) { - // if (!PermissionManager::GetInstance().CheckPermission()) { - // LOGI("The caller does not have permission to call"); - // return DM_NO_PERMISSION; - // } + if (!PermissionManager::GetInstance().CheckPermission()) { + LOGI("The caller does not have permission to call"); + return DM_NO_PERMISSION; + } if (!intFlag_) { LOGE("StopDeviceDiscovery failed, singleton not init or init fail"); return DM_NOT_INIT; @@ -224,17 +221,16 @@ int32_t DeviceManagerService::StopDeviceDiscovery(const std::string &pkgName, ui LOGE("StopDeviceDiscovery failed, pkgName is empty"); return DM_INPUT_PARA_EMPTY; } - // return discoveryMgr_->StopDeviceDiscovery(pkgName, subscribeId); - return 0; + return discoveryMgr_->StopDeviceDiscovery(pkgName, subscribeId); } int32_t DeviceManagerService::AuthenticateDevice(const std::string &pkgName, int32_t authType, const std::string &deviceId, const std::string &extra) { - // if (!PermissionManager::GetInstance().CheckPermission()) { - // LOGI("The caller does not have permission to call"); - // return DM_NO_PERMISSION; - // } + if (!PermissionManager::GetInstance().CheckPermission()) { + LOGI("The caller does not have permission to call"); + return DM_NO_PERMISSION; + } if (!intFlag_) { LOGE("AuthenticateDevice failed, singleton not init or init fail"); return DM_NOT_INIT; @@ -247,16 +243,15 @@ int32_t DeviceManagerService::AuthenticateDevice(const std::string &pkgName, int LOGE("AuthenticateDevice failed, deviceId is empty"); return DM_INPUT_PARA_EMPTY; } - // return authMgr_->AuthenticateDevice(pkgName, authType, deviceId, extra); - return 0; + return authMgr_->AuthenticateDevice(pkgName, authType, deviceId, extra); } int32_t DeviceManagerService::UnAuthenticateDevice(const std::string &pkgName, const std::string &deviceId) { - // if (!PermissionManager::GetInstance().CheckPermission()) { - // LOGI("The caller does not have permission to call"); - // return DM_NO_PERMISSION; - // } + if (!PermissionManager::GetInstance().CheckPermission()) { + LOGI("The caller does not have permission to call"); + return DM_NO_PERMISSION; + } if (!intFlag_) { LOGE("UnAuthenticateDevice failed, singleton not init or init fail"); return DM_NOT_INIT; @@ -269,22 +264,20 @@ int32_t DeviceManagerService::UnAuthenticateDevice(const std::string &pkgName, c LOGE("UnAuthenticateDevice failed, deviceId is empty"); return DM_INPUT_PARA_EMPTY; } - // return authMgr_->UnAuthenticateDevice(pkgName, deviceId); - return 0; + return authMgr_->UnAuthenticateDevice(pkgName, deviceId); } int32_t DeviceManagerService::VerifyAuthentication(const std::string &authParam) { - // if (!PermissionManager::GetInstance().CheckPermission()) { - // LOGI("The caller does not have permission to call"); - // return DM_NO_PERMISSION; - // } + if (!PermissionManager::GetInstance().CheckPermission()) { + LOGI("The caller does not have permission to call"); + return DM_NO_PERMISSION; + } if (!intFlag_) { LOGE("VerifyAuthentication failed, singleton not init or init fail"); return DM_NOT_INIT; } - // return authMgr_->VerifyAuthentication(authParam); - return 0; + return authMgr_->VerifyAuthentication(authParam); } int32_t DeviceManagerService::GetFaParam(std::string &pkgName, DmAuthParam &authParam) @@ -293,7 +286,7 @@ int32_t DeviceManagerService::GetFaParam(std::string &pkgName, DmAuthParam &auth LOGE("GetFaParam failed, pkgName is empty"); return DM_INPUT_PARA_EMPTY; } - // authMgr_->GetAuthenticationParam(authParam); + authMgr_->GetAuthenticationParam(authParam); return DM_OK; } @@ -303,19 +296,19 @@ int32_t DeviceManagerService::SetUserOperation(std::string &pkgName, int32_t act LOGE("SetUserOperation failed, pkgName is empty"); return DM_INPUT_PARA_EMPTY; } - // authMgr_->OnUserOperation(action); + authMgr_->OnUserOperation(action); return DM_OK; } int32_t DeviceManagerService::RegisterDevStateCallback(const std::string &pkgName, const std::string &extra) { - // deviceStateMgr_->RegisterDevStateCallback(pkgName, extra); + deviceStateMgr_->RegisterDevStateCallback(pkgName, extra); return DM_OK; } int32_t DeviceManagerService::UnRegisterDevStateCallback(const std::string &pkgName, const std::string &extra) { - // deviceStateMgr_->UnRegisterDevStateCallback(pkgName, extra); + deviceStateMgr_->UnRegisterDevStateCallback(pkgName, extra); return DM_OK; } } // namespace DistributedHardware diff --git a/services/devicemanagerservice/src/devicestate/dm_device_state_manager.cpp b/services/devicemanagerservice/src/devicestate/dm_device_state_manager.cpp index 8c182fa9a..6d951fd21 100755 --- a/services/devicemanagerservice/src/devicestate/dm_device_state_manager.cpp +++ b/services/devicemanagerservice/src/devicestate/dm_device_state_manager.cpp @@ -39,6 +39,12 @@ DmDeviceStateManager::DmDeviceStateManager(std::shared_ptr sof std::shared_ptr listener, std::shared_ptr hiChainConnector) : softbusConnector_(softbusConnector), listener_(listener), hiChainConnector_(hiChainConnector) { +#if defined(__LITEOS_M__) + uint32_t ret = pthread_mutex_init(&lock_, NULL); + if (ret != 0) { + LOGI("init mutex lock failed: %d.",ret); + } +#endif profileSoName_ = "libdevicemanagerext_profile.z.so"; LOGI("DmDeviceStateManager constructor"); } @@ -46,6 +52,12 @@ DmDeviceStateManager::DmDeviceStateManager(std::shared_ptr sof DmDeviceStateManager::~DmDeviceStateManager() { LOGI("DmDeviceStateManager destructor"); +#if defined(__LITEOS_M__) + uint32_t ret = pthread_mutex_destroy(&lock_); + if (ret != 0) { + LOGI("destroy mutex lock failed: %d.",ret); + } +#endif if (softbusConnector_ != nullptr) { softbusConnector_->UnRegisterSoftbusStateCallback("DM_PKG_NAME"); } @@ -64,8 +76,14 @@ int32_t DmDeviceStateManager::RegisterProfileListener(const std::string &pkgName DmDeviceInfo saveInfo = info; SoftbusConnector::GetUuidByNetworkId(info.deviceId, uuid); { +#if (defined(__LINUX__) || defined(__LITEOS_A__)) std::lock_guard mutexLock(remoteDeviceInfosMutex_); remoteDeviceInfos_[uuid] = saveInfo; +#else + pthread_mutex_lock(&lock_); + remoteDeviceInfos_[uuid] = saveInfo; + pthread_mutex_unlock(&lock_); +#endif } std::string deviceUdid = (char *)udid; LOGI("RegisterProfileListener in, deviceId = %s, deviceUdid = %s, uuid = %s", @@ -85,10 +103,19 @@ int32_t DmDeviceStateManager::UnRegisterProfileListener(const std::string &pkgNa profileAdapter->UnRegisterProfileListener(pkgName); } { + +#if (defined(__LINUX__) || defined(__LITEOS_A__)) std::lock_guard mutexLock(remoteDeviceInfosMutex_); if (remoteDeviceInfos_.find(std::string(info.deviceId)) != remoteDeviceInfos_.end()) { remoteDeviceInfos_.erase(std::string(info.deviceId)); } +#else + pthread_mutex_lock(&lock_); + if (remoteDeviceInfos_.find(std::string(info.deviceId)) != remoteDeviceInfos_.end()) { + remoteDeviceInfos_.erase(std::string(info.deviceId)); + } + pthread_mutex_unlock(&lock_); +#endif } return DM_OK; } @@ -194,6 +221,7 @@ void DmDeviceStateManager::OnProfileReady(const std::string &pkgName, const std: } DmDeviceInfo saveInfo; { +#if (defined(__LINUX__) || defined(__LITEOS_A__)) std::lock_guard mutexLock(remoteDeviceInfosMutex_); auto iter = remoteDeviceInfos_.find(deviceId); if (iter == remoteDeviceInfos_.end()) { @@ -201,6 +229,16 @@ void DmDeviceStateManager::OnProfileReady(const std::string &pkgName, const std: return; } saveInfo = iter->second; +#else + pthread_mutex_lock(&lock_); + auto iter = remoteDeviceInfos_.find(deviceId); + if (iter == remoteDeviceInfos_.end()) { + LOGE("OnProfileReady complete not find deviceId: %s", GetAnonyString(deviceId).c_str()); + return; + } + saveInfo = iter->second; + pthread_mutex_unlock(&lock_); +#endif } if (listener_ != nullptr) { DmDeviceState state = DEVICE_INFO_READY; @@ -243,7 +281,8 @@ void DmDeviceStateManager::RegisterOffLineTimer(const DmDeviceInfo &deviceInfo) return; } LOGI("Register OffLine Timer with device: %s", GetAnonyString(deviceId).c_str()); - + +#if (defined(__LINUX__) || defined(__LITEOS_A__)) std::lock_guard mutexLock(timerMapMutex_); auto iter = timerMap_.find(deviceId); if (iter != timerMap_.end()) { @@ -254,6 +293,19 @@ void DmDeviceStateManager::RegisterOffLineTimer(const DmDeviceInfo &deviceInfo) if (offLineTimer != nullptr) { timerMap_[deviceId] = offLineTimer; } +#else + pthread_mutex_lock(&lock_); + auto iter = timerMap_.find(deviceId); + if (iter != timerMap_.end()) { + iter->second->Stop(SESSION_CANCEL_TIMEOUT); + return; + } + std::shared_ptr offLineTimer = std::make_shared(deviceId); + if (offLineTimer != nullptr) { + timerMap_[deviceId] = offLineTimer; + } + pthread_mutex_unlock(&lock_); +#endif } void DmDeviceStateManager::StartOffLineTimer(const DmDeviceInfo &deviceInfo) @@ -266,12 +318,22 @@ void DmDeviceStateManager::StartOffLineTimer(const DmDeviceInfo &deviceInfo) } LOGI("start offline timer with device: %s", GetAnonyString(deviceId).c_str()); +#if (defined(__LINUX__) || defined(__LITEOS_A__)) std::lock_guard mutexLock(timerMapMutex_); for (auto &iter : timerMap_) { if (iter.first == deviceId) { iter.second->Start(OFFLINE_TIMEOUT, TimeOut, this); } } +#else + pthread_mutex_lock(&lock_); + for (auto &iter : timerMap_) { + if (iter.first == deviceId) { + iter.second->Start(OFFLINE_TIMEOUT, TimeOut, this); + } + } + pthread_mutex_unlock(&lock_); +#endif } void DmDeviceStateManager::DeleteTimeOutGroup(std::string deviceId) -- Gitee From 3a599920dfc3dd4c8592044802869bea7c18e8ca Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=85=9A=E6=B3=BD=E8=BE=89?= Date: Wed, 9 Mar 2022 12:41:18 +0000 Subject: [PATCH 05/19] =?UTF-8?q?!28=20services=E7=9B=AE=E5=BD=95=E4=BF=AE?= =?UTF-8?q?=E6=94=B9=20*=20services=E7=9B=AE=E5=BD=95=E4=BF=AE=E6=94=B9?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../include/authentication/auth_ui.h | 2 +- .../include/config/dm_config_manager.h | 4 + .../include/config/mini/pin_auth.h | 42 ++++ .../commonevent/dm_common_event_manager.h | 78 +++--- .../dependency/hichain/hichain_connector.h | 6 +- .../dependency/softbus/softbus_connector.h | 8 +- .../dependency/softbus/softbus_session.h | 6 +- .../include/dependency/timer/dm_timer.h | 12 +- .../include/device_manager_service.h | 28 +-- .../devicestate/dm_device_state_manager.h | 9 +- .../src/authentication/dm_auth_manager.cpp | 40 ++-- .../src/config/mini/dm_config_manager.cpp | 67 ++++++ .../src/config/mini/pin_auth.cpp | 82 +++++++ .../commonevent/dm_common_event_manager.cpp | 222 +++++++++--------- .../dependency/hichain/hichain_connector.cpp | 8 +- .../multipleuser/multiple_user_connector.cpp | 17 +- .../dependency/softbus/softbus_connector.cpp | 108 ++++++++- .../dependency/softbus/softbus_session.cpp | 6 +- .../src/dependency/timer/mini/dm_timer.cpp | 75 ++++++ .../src/device_manager_service.cpp | 221 +++++++++-------- .../devicestate/dm_device_state_manager.cpp | 64 ++++- 21 files changed, 771 insertions(+), 334 deletions(-) create mode 100644 services/devicemanagerservice/include/config/mini/pin_auth.h create mode 100644 services/devicemanagerservice/src/config/mini/dm_config_manager.cpp create mode 100644 services/devicemanagerservice/src/config/mini/pin_auth.cpp create mode 100644 services/devicemanagerservice/src/dependency/timer/mini/dm_timer.cpp diff --git a/services/devicemanagerservice/include/authentication/auth_ui.h b/services/devicemanagerservice/include/authentication/auth_ui.h index 4ba96cb50..e7473332c 100644 --- a/services/devicemanagerservice/include/authentication/auth_ui.h +++ b/services/devicemanagerservice/include/authentication/auth_ui.h @@ -17,7 +17,7 @@ #define OHOS_DM_AUTH_UI_H #include - +#include #include "dm_ability_manager.h" namespace OHOS { diff --git a/services/devicemanagerservice/include/config/dm_config_manager.h b/services/devicemanagerservice/include/config/dm_config_manager.h index 4a410a1e7..d2082a7b7 100644 --- a/services/devicemanagerservice/include/config/dm_config_manager.h +++ b/services/devicemanagerservice/include/config/dm_config_manager.h @@ -19,7 +19,9 @@ #include #include #include +#if (defined(__LINUX__) || defined(__LITEOS_A__)) #include +#endif #include #include #include @@ -66,10 +68,12 @@ private: DmConfigManager(); private: +#if (defined(__LINUX__) || defined(__LITEOS_A__)) std::mutex authAdapterMutex_; std::mutex cryptoAdapterMutex_; std::mutex decisionAdapterMutex_; std::mutex profileAdapterMutex_; +#endif std::map soAuthLoadInfo_; std::map soAdapterLoadInfo_; std::map> decisionAdapterPtr_; diff --git a/services/devicemanagerservice/include/config/mini/pin_auth.h b/services/devicemanagerservice/include/config/mini/pin_auth.h new file mode 100644 index 000000000..9b4edfbcc --- /dev/null +++ b/services/devicemanagerservice/include/config/mini/pin_auth.h @@ -0,0 +1,42 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef OHOS_DM_PIN_AUTH_H +#define OHOS_DM_PIN_AUTH_H + +#include +#include + +#include "authentication.h" +#include "dm_auth_manager.h" +#include "dm_ability_manager.h" + +namespace OHOS { +namespace DistributedHardware { +class PinAuth : public IAuthentication { +public: + PinAuth(); + ~PinAuth(); + int32_t ShowAuthInfo(std::string &authToken, std::shared_ptr authManager) override; + int32_t StartAuth(std::string &authToken, std::shared_ptr authManager) override; + int32_t VerifyAuthentication(std::string &authToken, const std::string &authParam) override; + +private: + int32_t times_ = 0; + // std::shared_ptr pinAuthUi_; +}; +} // namespace DistributedHardware +} // namespace OHOS +#endif // OHOS_DM_PIN_AUTH_H diff --git a/services/devicemanagerservice/include/dependency/commonevent/dm_common_event_manager.h b/services/devicemanagerservice/include/dependency/commonevent/dm_common_event_manager.h index 81d51bb2a..850e861d3 100644 --- a/services/devicemanagerservice/include/dependency/commonevent/dm_common_event_manager.h +++ b/services/devicemanagerservice/include/dependency/commonevent/dm_common_event_manager.h @@ -18,53 +18,53 @@ #include #include -#include +// #include -#include "common_event.h" -#include "common_event_data.h" -#include "common_event_manager.h" -#include "common_event_subscribe_info.h" -#include "common_event_subscriber.h" +// #include "common_event.h" +// #include "common_event_data.h" +// #include "common_event_manager.h" +// #include "common_event_subscribe_info.h" +// #include "common_event_subscriber.h" #include "dm_log.h" -#include "matching_skills.h" +// #include "matching_skills.h" #include "single_instance.h" namespace OHOS { namespace DistributedHardware { -using CommomEventCallback = std::function; +// using CommomEventCallback = std::function; -struct CommomEventCallbackNode { - int32_t input_; - CommomEventCallback callback_; -}; +// struct CommomEventCallbackNode { +// int32_t input_; +// CommomEventCallback callback_; +// }; -class DmCommonEventManager { -DECLARE_SINGLE_INSTANCE_BASE(DmCommonEventManager); -public: - bool SubscribeServiceEvent(const std::string &event, const CommomEventCallback callback); - bool UnsubscribeServiceEvent(const std::string &event); - class EventSubscriber : public EventFwk::CommonEventSubscriber { - public: - EventSubscriber(const EventFwk::CommonEventSubscribeInfo &subscribeInfo, const CommomEventCallback &callback, - const std::string &event) : EventFwk::CommonEventSubscriber(subscribeInfo), - callback_(callback), event_(event) {} - void OnReceiveEvent(const EventFwk::CommonEventData &data); - private: - CommomEventCallback callback_; - std::string event_; - }; -private: - DmCommonEventManager(); - ~DmCommonEventManager(); -private: - static void DealCallback(void); -private: - static std::mutex callbackQueueMutex_; - static std::mutex eventSubscriberMutex_; - static std::condition_variable notEmpty_; - static std::list callbackQueue_; - std::map> dmEventSubscriber_; -}; +// class DmCommonEventManager { +// DECLARE_SINGLE_INSTANCE_BASE(DmCommonEventManager); +// public: +// bool SubscribeServiceEvent(const std::string &event, const CommomEventCallback callback); +// bool UnsubscribeServiceEvent(const std::string &event); + // class EventSubscriber : public EventFwk::CommonEventSubscriber { + // public: + // EventSubscriber(const EventFwk::CommonEventSubscribeInfo &subscribeInfo, const CommomEventCallback &callback, + // const std::string &event) : EventFwk::CommonEventSubscriber(subscribeInfo), + // callback_(callback), event_(event) {} + // void OnReceiveEvent(const EventFwk::CommonEventData &data); + // private: + // CommomEventCallback callback_; + // std::string event_; + // }; +// private: +// DmCommonEventManager(); +// ~DmCommonEventManager(); +// private: +// static void DealCallback(void); +// private: + // static std::mutex callbackQueueMutex_; + // static std::mutex eventSubscriberMutex_; + // static std::condition_variable notEmpty_; + // static std::list callbackQueue_; + // std::map> dmEventSubscriber_; +// }; } // namespace DistributedHardware } // namespace OHOS #endif // OHOS_EVENT_MANAGER_ADAPT_H \ No newline at end of file diff --git a/services/devicemanagerservice/include/dependency/hichain/hichain_connector.h b/services/devicemanagerservice/include/dependency/hichain/hichain_connector.h index 6c19fe3fd..b8aa3708c 100644 --- a/services/devicemanagerservice/include/dependency/hichain/hichain_connector.h +++ b/services/devicemanagerservice/include/dependency/hichain/hichain_connector.h @@ -46,9 +46,9 @@ void from_json(const nlohmann::json &jsonObject, GroupInfo &groupInfo); class HiChainConnector { public: static bool onTransmit(int64_t requestId, const uint8_t *data, uint32_t dataLen); - static void onFinish(int64_t requestId, int32_t operationCode, const char *returnData); - static void onError(int64_t requestId, int32_t operationCode, int32_t errorCode, const char *errorReturn); - static char *onRequest(int64_t requestId, int32_t operationCode, const char *reqParams); + static void onFinish(int64_t requestId, int operationCode, const char *returnData); + static void onError(int64_t requestId, int operationCode, int errorCode, const char *errorReturn); + static char *onRequest(int64_t requestId, int operationCode, const char *reqParams); public: HiChainConnector(); diff --git a/services/devicemanagerservice/include/dependency/softbus/softbus_connector.h b/services/devicemanagerservice/include/dependency/softbus/softbus_connector.h index a7f5f3aa7..3ffc59eb4 100644 --- a/services/devicemanagerservice/include/dependency/softbus/softbus_connector.h +++ b/services/devicemanagerservice/include/dependency/softbus/softbus_connector.h @@ -34,14 +34,14 @@ namespace OHOS { namespace DistributedHardware { class SoftbusConnector { public: - static void OnPublishSuccess(int32_t publishId); - static void OnPublishFail(int32_t publishId, PublishFailReason reason); + static void OnPublishSuccess(int publishId); + static void OnPublishFail(int publishId, PublishFailReason reason); static void OnSoftBusDeviceOnline(NodeBasicInfo *info); static void OnSoftbusDeviceOffline(NodeBasicInfo *info); static void OnSoftbusDeviceInfoChanged(NodeBasicInfoType type, NodeBasicInfo *info); static void OnSoftbusDeviceFound(const DeviceInfo *device); - static void OnSoftbusDiscoveryFailed(int32_t subscribeId, DiscoveryFailReason failReason); - static void OnSoftbusDiscoverySuccess(int32_t subscribeId); + static void OnSoftbusDiscoveryFailed(int subscribeId, DiscoveryFailReason failReason); + static void OnSoftbusDiscoverySuccess(int subscribeId); static void OnParameterChgCallback(const char *key, const char *value, void *context); static int32_t GetConnectionIpAddress(const std::string &deviceId, std::string &ipAddress); static ConnectionAddr *GetConnectAddr(const std::string &deviceId, std::string &connectAddr); diff --git a/services/devicemanagerservice/include/dependency/softbus/softbus_session.h b/services/devicemanagerservice/include/dependency/softbus/softbus_session.h index 2eab337e6..a62cbc037 100644 --- a/services/devicemanagerservice/include/dependency/softbus/softbus_session.h +++ b/services/devicemanagerservice/include/dependency/softbus/softbus_session.h @@ -30,9 +30,9 @@ namespace OHOS { namespace DistributedHardware { class SoftbusSession { public: - static int32_t OnSessionOpened(int32_t sessionId, int32_t result); - static void OnSessionClosed(int32_t sessionId); - static void OnBytesReceived(int32_t sessionId, const void *data, uint32_t dataLen); + static int OnSessionOpened(int sessionId, int result); + static void OnSessionClosed(int sessionId); + static void OnBytesReceived(int sessionId, const void *data, unsigned int dataLen); public: SoftbusSession(); diff --git a/services/devicemanagerservice/include/dependency/timer/dm_timer.h b/services/devicemanagerservice/include/dependency/timer/dm_timer.h index a4ffec0fd..09d9e596b 100644 --- a/services/devicemanagerservice/include/dependency/timer/dm_timer.h +++ b/services/devicemanagerservice/include/dependency/timer/dm_timer.h @@ -18,12 +18,15 @@ #include #include #include +#if (defined(__LINUX__) || defined(__LITEOS_A__)) #include +#include #include - +#endif #include #include -#include +#include "dm_log.h" + #include "dm_log.h" @@ -60,10 +63,13 @@ private: TimeoutHandle mHandle_; void *mHandleData_; int32_t mTimeFd_[2]; +#if (defined(__LINUX__) || defined(__LITEOS_A__)) struct epoll_event mEv_; struct epoll_event mEvents_[MAX_EVENTS]; - int32_t mEpFd_; std::thread mThread_; + int32_t mEpFd_; +#endif + std::string mTimerName_; }; } // namespace DistributedHardware diff --git a/services/devicemanagerservice/include/device_manager_service.h b/services/devicemanagerservice/include/device_manager_service.h index a810768fe..ab093c9c3 100644 --- a/services/devicemanagerservice/include/device_manager_service.h +++ b/services/devicemanagerservice/include/device_manager_service.h @@ -19,14 +19,14 @@ #include #include -// #include "dm_ability_manager.h" -// #include "dm_auth_manager.h" +#include "dm_ability_manager.h" +#include "dm_auth_manager.h" #include "dm_device_info.h" -// #include "dm_device_info_manager.h" -// #include "dm_device_state_manager.h" -// #include "dm_discovery_manager.h" +#include "dm_device_info_manager.h" +#include "dm_device_state_manager.h" +#include "dm_discovery_manager.h" #include "single_instance.h" -// #include "softbus_connector.h" +#include "softbus_connector.h" #include "dm_subscribe_info.h" @@ -56,14 +56,14 @@ public: private: DeviceManagerService() = default; bool intFlag_ = false; - // std::shared_ptr authMgr_; - // std::shared_ptr deviceInfoMgr_; - // std::shared_ptr deviceStateMgr_; - // std::shared_ptr discoveryMgr_; - // std::shared_ptr softbusConnector_; - // std::shared_ptr listener_; - // std::shared_ptr abilityMgr_; - // std::shared_ptr hiChainConnector_; + std::shared_ptr authMgr_; + std::shared_ptr deviceInfoMgr_; + std::shared_ptr deviceStateMgr_; + std::shared_ptr discoveryMgr_; + std::shared_ptr softbusConnector_; + std::shared_ptr listener_; + std::shared_ptr abilityMgr_; + std::shared_ptr hiChainConnector_; }; } // namespace DistributedHardware } // namespace OHOS diff --git a/services/devicemanagerservice/include/devicestate/dm_device_state_manager.h b/services/devicemanagerservice/include/devicestate/dm_device_state_manager.h index f34198c37..1b5d910c2 100755 --- a/services/devicemanagerservice/include/devicestate/dm_device_state_manager.h +++ b/services/devicemanagerservice/include/devicestate/dm_device_state_manager.h @@ -18,8 +18,11 @@ #include #include +#if (defined(__LINUX__) || defined(__LITEOS_A__)) #include - +#else +#include +#endif #include "device_manager_service_listener.h" #include "dm_adapter_manager.h" #include "softbus_connector.h" @@ -54,8 +57,12 @@ public: private: std::string profileSoName_; +#if (defined(__LINUX__) || defined(__LITEOS_A__)) std::mutex timerMapMutex_; std::mutex remoteDeviceInfosMutex_; +#else + pthread_mutex_t lock_; +#endif std::shared_ptr softbusConnector_; std::shared_ptr listener_; std::map remoteDeviceInfos_; diff --git a/services/devicemanagerservice/src/authentication/dm_auth_manager.cpp b/services/devicemanagerservice/src/authentication/dm_auth_manager.cpp index 359721a01..2bc633f99 100644 --- a/services/devicemanagerservice/src/authentication/dm_auth_manager.cpp +++ b/services/devicemanagerservice/src/authentication/dm_auth_manager.cpp @@ -25,9 +25,9 @@ #include "multiple_user_connector.h" #include "nlohmann/json.hpp" #include "parameter.h" -#include "ui_service_mgr_client.h" -#include "dialog_callback_stub.h" -#include "dialog_callback.h" +// #include "ui_service_mgr_client.h" +// #include "dialog_callback_stub.h" +// #include "dialog_callback.h" namespace OHOS { namespace DistributedHardware { @@ -540,7 +540,7 @@ int32_t DmAuthManager::AddMember(const std::string &deviceId) return DM_FAILED; } LOGI("DmAuthManager::authRequestContext CancelDisplay start"); - Ace::UIServiceMgrClient::GetInstance()->CancelDialog(authResponseContext_->pageId); + // Ace::UIServiceMgrClient::GetInstance()->CancelDialog(authResponseContext_->pageId); return DM_OK; } @@ -569,9 +569,9 @@ void DmAuthManager::AuthenticateFinish() { LOGI("DmAuthManager::AuthenticateFinish start"); if (authResponseState_ != nullptr) { - if (authResponseState_->GetStateType() == AuthState::AUTH_RESPONSE_FINISH) { - Ace::UIServiceMgrClient::GetInstance()->CancelDialog(authResponseContext_->pageId); - } + // if (authResponseState_->GetStateType() == AuthState::AUTH_RESPONSE_FINISH) { + // Ace::UIServiceMgrClient::GetInstance()->CancelDialog(authResponseContext_->pageId); + // } if (authResponseState_->GetStateType() == AuthState::AUTH_RESPONSE_SHOW && authResponseContext_->authType != 1) { authMessageProcessor_->SetResponseContext(authResponseContext_); @@ -597,9 +597,9 @@ void DmAuthManager::AuthenticateFinish() authResponseContext_->state = AuthState::AUTH_REQUEST_INIT; } - if (authResponseContext_->state == AuthState::AUTH_REQUEST_INPUT) { - Ace::UIServiceMgrClient::GetInstance()->CancelDialog(authResponseContext_->pageId); - } + // if (authResponseContext_->state == AuthState::AUTH_REQUEST_INPUT) { + // Ace::UIServiceMgrClient::GetInstance()->CancelDialog(authResponseContext_->pageId); + // } listener_->OnAuthResult(authRequestContext_->hostPkgName, authRequestContext_->deviceId, authRequestContext_->token, authResponseContext_->state, authRequestContext_->reason); @@ -698,16 +698,16 @@ void DmAuthManager::ShowConfigDialog() const std::string params = jsonObj.dump(); std::shared_ptr authMgr_ = shared_from_this(); - Ace::UIServiceMgrClient::GetInstance()->ShowDialog( - "config_dialog_service", - params, - OHOS::Rosen::WindowType::WINDOW_TYPE_SYSTEM_ALARM_WINDOW, - ACE_X, ACE_Y, ACE_WIDTH, ACE_HEIGHT, - [authMgr_](int32_t id, const std::string& event, const std::string& params) { - Ace::UIServiceMgrClient::GetInstance()->CancelDialog(id); - LOGI("CancelDialog start id:%d,event:%s,parms:%s", id, event.c_str(), params.c_str()); - authMgr_->StartAuthProcess(atoi(params.c_str())); - }); + // Ace::UIServiceMgrClient::GetInstance()->ShowDialog( + // "config_dialog_service", + // params, + // OHOS::Rosen::WindowType::WINDOW_TYPE_SYSTEM_ALARM_WINDOW, + // ACE_X, ACE_Y, ACE_WIDTH, ACE_HEIGHT, + // [authMgr_](int32_t id, const std::string& event, const std::string& params) { + // Ace::UIServiceMgrClient::GetInstance()->CancelDialog(id); + // LOGI("CancelDialog start id:%d,event:%s,parms:%s", id, event.c_str(), params.c_str()); + // authMgr_->StartAuthProcess(atoi(params.c_str())); + // }); LOGI("ShowConfigDialog end"); } diff --git a/services/devicemanagerservice/src/config/mini/dm_config_manager.cpp b/services/devicemanagerservice/src/config/mini/dm_config_manager.cpp new file mode 100644 index 000000000..63bc1df57 --- /dev/null +++ b/services/devicemanagerservice/src/config/mini/dm_config_manager.cpp @@ -0,0 +1,67 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +#include "dm_config_manager.h" +#include "dm_constants.h" +#include "dm_log.h" +#include "pin_auth.h" + +namespace OHOS { +namespace DistributedHardware { + + +DmConfigManager &DmConfigManager::GetInstance() +{ + static DmConfigManager instance; + return instance; +} + +DmConfigManager::DmConfigManager() +{ + LOGI("DmConfigManager constructor"); +} + +DmConfigManager::~DmConfigManager() +{ + LOGI("DmAdapterManager destructor"); +} + +std::shared_ptr DmConfigManager::GetDecisionAdapter(const std::string &soName) +{ + return nullptr; +} + +std::shared_ptr DmConfigManager::GetProfileAdapter(const std::string &soName) +{ + return nullptr; +} + +std::shared_ptr DmConfigManager::GetCryptoAdapter(const std::string &soName) +{ + return nullptr; +} + +extern "C" IAuthentication *CreatePinAuthObject(void) +{ + return new PinAuth; +} + +void DmConfigManager::GetAuthAdapter(std::map> &authAdapter) +{ + authAdapter.clear(); + std::shared_ptr iAuthentication(CreatePinAuthObject()); + authAdapter[1] = iAuthentication; +} +} // namespace DistributedHardware +} // namespace OHOS \ No newline at end of file diff --git a/services/devicemanagerservice/src/config/mini/pin_auth.cpp b/services/devicemanagerservice/src/config/mini/pin_auth.cpp new file mode 100644 index 000000000..ffdf88c0b --- /dev/null +++ b/services/devicemanagerservice/src/config/mini/pin_auth.cpp @@ -0,0 +1,82 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "pin_auth.h" + +#include + +#include "dm_constants.h" +#include "dm_log.h" +#include "nlohmann/json.hpp" + +namespace OHOS { +namespace DistributedHardware { +const int32_t MAX_VERIFY_TIMES = 3; +PinAuth::PinAuth() +{ + LOGI("PinAuth constructor"); +} + +PinAuth::~PinAuth() +{ +} + +int32_t PinAuth::ShowAuthInfo(std::string &authToken, std::shared_ptr authManager) +{ + LOGI("ShowConfigDialog end"); + return DM_OK; +} + +int32_t PinAuth::StartAuth(std::string &authToken, std::shared_ptr authManager) +{ + LOGI("StartAuth end"); + return DM_OK; +} + +int32_t PinAuth::VerifyAuthentication(std::string &authToken, const std::string &authParam) +{ + times_ += 1; + nlohmann::json authParamJson = nlohmann::json::parse(authParam, nullptr, false); + if (authParamJson.is_discarded()) { + LOGE("DecodeRequestAuth jsonStr error"); + return DM_FAILED; + } + nlohmann::json authTokenJson = nlohmann::json::parse(authToken, nullptr, false); + if (authParamJson.is_discarded()) { + LOGE("DecodeRequestAuth jsonStr error"); + return DM_FAILED; + } + if (!authParamJson.contains(PIN_CODE_KEY) && !authParamJson.contains(PIN_TOKEN)) { + if (authParam == "0") { + return DM_OK; + } + LOGE("err json string, first time"); + return DM_FAILED; + } + int32_t code = authTokenJson[PIN_CODE_KEY]; + int32_t pinToken = authTokenJson[PIN_TOKEN]; + int32_t inputPinCode = authParamJson[PIN_CODE_KEY]; + int32_t inputPinToken = authParamJson[PIN_TOKEN]; + if (code == inputPinCode && pinToken == inputPinToken) { + return DM_OK; + } else if (code != inputPinCode && times_ < MAX_VERIFY_TIMES) { + return DM_AUTH_INPUT_FAILED; + } else { + return DM_FAILED; + } +} + +} // namespace DistributedHardware +} // namespace OHOS diff --git a/services/devicemanagerservice/src/dependency/commonevent/dm_common_event_manager.cpp b/services/devicemanagerservice/src/dependency/commonevent/dm_common_event_manager.cpp index 798174abe..c25038d00 100644 --- a/services/devicemanagerservice/src/dependency/commonevent/dm_common_event_manager.cpp +++ b/services/devicemanagerservice/src/dependency/commonevent/dm_common_event_manager.cpp @@ -15,124 +15,124 @@ #include "dm_common_event_manager.h" -#include +// #include #include "dm_constants.h" -using namespace OHOS::EventFwk; +// using namespace OHOS::EventFwk; namespace OHOS { namespace DistributedHardware { -std::mutex DmCommonEventManager::callbackQueueMutex_; -std::mutex DmCommonEventManager::eventSubscriberMutex_; -std::condition_variable DmCommonEventManager::notEmpty_; -std::list DmCommonEventManager::callbackQueue_; - -DmCommonEventManager &DmCommonEventManager::GetInstance() -{ - static DmCommonEventManager instance; - return instance; -} - -DmCommonEventManager::DmCommonEventManager() -{ - std::thread th(DealCallback); - th.detach(); -} - -DmCommonEventManager::~DmCommonEventManager() -{ - std::unique_lock mutexLock(eventSubscriberMutex_); - for (auto iter = dmEventSubscriber_.begin(); iter != dmEventSubscriber_.end(); iter++) { - if (!CommonEventManager::UnSubscribeCommonEvent(iter->second)) { - LOGI("Unsubscribe service event failed: %s", iter->first.c_str()); - } - } -} - -void DmCommonEventManager::DealCallback(void) -{ - while (1) { - std::unique_lock callbackQueueMutexLock(callbackQueueMutex_); - notEmpty_.wait(callbackQueueMutexLock, [] { return !callbackQueue_.empty(); }); - CommomEventCallbackNode node = callbackQueue_.front(); - int32_t input = node.input_; - CommomEventCallback funcPrt = node.callback_; - funcPrt(input); - callbackQueue_.pop_front(); - } -} - -bool DmCommonEventManager::SubscribeServiceEvent(const std::string &event, const CommomEventCallback callback) -{ - LOGI("Subscribe event: %s", event.c_str()); - if (dmEventSubscriber_.find(event) != dmEventSubscriber_.end() || callback == nullptr) { - LOGE("Subscribe event:%s has been exist or callback is nullptr", event.c_str()); - return false; - } - - MatchingSkills matchingSkills; - matchingSkills.AddEvent(event); - CommonEventSubscribeInfo subscriberInfo(matchingSkills); - std::shared_ptr subscriber = - std::make_shared(subscriberInfo, callback, event); - if (subscriber == nullptr) { - LOGE("subscriber is nullptr %s", event.c_str()); - return false; - } +// std::mutex DmCommonEventManager::callbackQueueMutex_; +// std::mutex DmCommonEventManager::eventSubscriberMutex_; +// std::condition_variable DmCommonEventManager::notEmpty_; +// std::list DmCommonEventManager::callbackQueue_; + +// DmCommonEventManager &DmCommonEventManager::GetInstance() +// { +// static DmCommonEventManager instance; +// return instance; +// } + +// DmCommonEventManager::DmCommonEventManager() +// { +// std::thread th(DealCallback); +// th.detach(); +// } + +// DmCommonEventManager::~DmCommonEventManager() +// { +// std::unique_lock mutexLock(eventSubscriberMutex_); +// for (auto iter = dmEventSubscriber_.begin(); iter != dmEventSubscriber_.end(); iter++) { +// if (!CommonEventManager::UnSubscribeCommonEvent(iter->second)) { +// LOGI("Unsubscribe service event failed: %s", iter->first.c_str()); +// } +// } +// } + +// void DmCommonEventManager::DealCallback(void) +// { +// while (1) { +// std::unique_lock callbackQueueMutexLock(callbackQueueMutex_); +// notEmpty_.wait(callbackQueueMutexLock, [] { return !callbackQueue_.empty(); }); +// CommomEventCallbackNode node = callbackQueue_.front(); +// int32_t input = node.input_; +// CommomEventCallback funcPrt = node.callback_; +// funcPrt(input); +// callbackQueue_.pop_front(); +// } +// } + +// bool DmCommonEventManager::SubscribeServiceEvent(const std::string &event, const CommomEventCallback callback) +// { +// LOGI("Subscribe event: %s", event.c_str()); +// if (dmEventSubscriber_.find(event) != dmEventSubscriber_.end() || callback == nullptr) { +// LOGE("Subscribe event:%s has been exist or callback is nullptr", event.c_str()); +// return false; +// } + +// MatchingSkills matchingSkills; +// matchingSkills.AddEvent(event); +// CommonEventSubscribeInfo subscriberInfo(matchingSkills); +// std::shared_ptr subscriber = +// std::make_shared(subscriberInfo, callback, event); +// if (subscriber == nullptr) { +// LOGE("subscriber is nullptr %s", event.c_str()); +// return false; +// } - if (!CommonEventManager::SubscribeCommonEvent(subscriber)) { - LOGE("Subscribe service event failed: %s", event.c_str()); - return false; - } - - std::unique_lock mutexLock(eventSubscriberMutex_); - dmEventSubscriber_[event] = subscriber; - return true; -} - -bool DmCommonEventManager::UnsubscribeServiceEvent(const std::string &event) -{ - LOGI("UnSubscribe event: %s", event.c_str()); - if (dmEventSubscriber_.find(event) == dmEventSubscriber_.end()) { - LOGE("UnSubscribe event: %s not been exist", event.c_str()); - return false; - } - - if (!CommonEventManager::UnSubscribeCommonEvent(dmEventSubscriber_[event])) { - LOGE("Unsubscribe service event failed: %s", event.c_str()); - return false; - } - - std::unique_lock mutexLock(eventSubscriberMutex_); - dmEventSubscriber_.erase(event); - return true; -} - -void DmCommonEventManager::EventSubscriber::OnReceiveEvent(const CommonEventData &data) -{ - std::string receiveEvent = data.GetWant().GetAction(); - LOGI("Received event: %s", receiveEvent.c_str()); - if (receiveEvent != event_) { - LOGE("Received event is error"); - return; - } - - int32_t userId = data.GetCode(); - if (userId <= 0) { - LOGE("userId is less zero"); - return; - } +// if (!CommonEventManager::SubscribeCommonEvent(subscriber)) { +// LOGE("Subscribe service event failed: %s", event.c_str()); +// return false; +// } + +// std::unique_lock mutexLock(eventSubscriberMutex_); +// dmEventSubscriber_[event] = subscriber; +// return true; +// } + +// bool DmCommonEventManager::UnsubscribeServiceEvent(const std::string &event) +// { +// LOGI("UnSubscribe event: %s", event.c_str()); +// if (dmEventSubscriber_.find(event) == dmEventSubscriber_.end()) { +// LOGE("UnSubscribe event: %s not been exist", event.c_str()); +// return false; +// } + +// if (!CommonEventManager::UnSubscribeCommonEvent(dmEventSubscriber_[event])) { +// LOGE("Unsubscribe service event failed: %s", event.c_str()); +// return false; +// } + +// std::unique_lock mutexLock(eventSubscriberMutex_); +// dmEventSubscriber_.erase(event); +// return true; +// } + +// void DmCommonEventManager::EventSubscriber::OnReceiveEvent(const CommonEventData &data) +// { +// std::string receiveEvent = data.GetWant().GetAction(); +// LOGI("Received event: %s", receiveEvent.c_str()); +// if (receiveEvent != event_) { +// LOGE("Received event is error"); +// return; +// } + +// int32_t userId = data.GetCode(); +// if (userId <= 0) { +// LOGE("userId is less zero"); +// return; +// } - std::unique_lock callbackQueueMutexLock(callbackQueueMutex_); - if (callbackQueue_.size() > COMMON_CALLBACK_MAX_SIZE) { - LOGE("event callback Queue is too long"); - return; - } - - CommomEventCallbackNode node {userId, callback_}; - callbackQueue_.push_back(node); - notEmpty_.notify_one(); -} +// std::unique_lock callbackQueueMutexLock(callbackQueueMutex_); +// if (callbackQueue_.size() > COMMON_CALLBACK_MAX_SIZE) { +// LOGE("event callback Queue is too long"); +// return; +// } + +// CommomEventCallbackNode node {userId, callback_}; +// callbackQueue_.push_back(node); +// notEmpty_.notify_one(); +// } } // namespace DistributedHardware } // namespace OHOS \ No newline at end of file diff --git a/services/devicemanagerservice/src/dependency/hichain/hichain_connector.cpp b/services/devicemanagerservice/src/dependency/hichain/hichain_connector.cpp index dd4afeb86..5c739f292 100644 --- a/services/devicemanagerservice/src/dependency/hichain/hichain_connector.cpp +++ b/services/devicemanagerservice/src/dependency/hichain/hichain_connector.cpp @@ -60,7 +60,7 @@ std::shared_ptr HiChainConnector::hiChainConnectorCal HiChainConnector::HiChainConnector() { LOGI("HiChainConnector::constructor"); - deviceAuthCallback_ = {.onTransmit = nullptr, + deviceAuthCallback_ = DeviceAuthCallback {.onTransmit = nullptr, .onFinish = HiChainConnector::onFinish, .onError = HiChainConnector::onError, .onRequest = HiChainConnector::onRequest}; @@ -250,7 +250,7 @@ int32_t HiChainConnector::AddMember(std::string deviceId, std::string &connectIn return ret; } -void HiChainConnector::onFinish(int64_t requestId, int32_t operationCode, const char *returnData) +void HiChainConnector::onFinish(int64_t requestId, int operationCode, const char *returnData) { std::string data = ""; if (returnData != nullptr) { @@ -273,7 +273,7 @@ void HiChainConnector::onFinish(int64_t requestId, int32_t operationCode, const } } -void HiChainConnector::onError(int64_t requestId, int32_t operationCode, int32_t errorCode, const char *errorReturn) +void HiChainConnector::onError(int64_t requestId, int operationCode, int errorCode, const char *errorReturn) { (void)errorReturn; LOGI("HichainAuthenCallBack::onError reqId:%lld, operation:%d, errorCode:%d.", requestId, operationCode, errorCode); @@ -293,7 +293,7 @@ void HiChainConnector::onError(int64_t requestId, int32_t operationCode, int32_t } } -char *HiChainConnector::onRequest(int64_t requestId, int32_t operationCode, const char *reqParams) +char *HiChainConnector::onRequest(int64_t requestId, int operationCode, const char *reqParams) { if (operationCode != GroupOperationCode::MEMBER_JOIN) { LOGE("HiChainAuthCallBack::onRequest operationCode %d", operationCode); diff --git a/services/devicemanagerservice/src/dependency/multipleuser/multiple_user_connector.cpp b/services/devicemanagerservice/src/dependency/multipleuser/multiple_user_connector.cpp index 4168ce99e..934374ffc 100644 --- a/services/devicemanagerservice/src/dependency/multipleuser/multiple_user_connector.cpp +++ b/services/devicemanagerservice/src/dependency/multipleuser/multiple_user_connector.cpp @@ -17,9 +17,9 @@ #include "dm_constants.h" #include "dm_log.h" -#include "os_account_manager.h" +// #include "os_account_manager.h" -using namespace OHOS::AccountSA; +// using namespace OHOS::AccountSA; namespace OHOS { namespace DistributedHardware { @@ -27,12 +27,13 @@ int32_t MultipleUserConnector::oldUserId_ = -1; int32_t MultipleUserConnector::GetCurrentAccountUserID(void) { - std::vector ids; - ErrCode ret = OsAccountManager::QueryActiveOsAccountIds(ids); - if (ret != ERR_OK || ids.empty()) { - return -1; - } - return ids[0]; + // std::vector ids; + // ErrCode ret = OsAccountManager::QueryActiveOsAccountIds(ids); + // if (ret != ERR_OK || ids.empty()) { + // return -1; + // } + // return ids[0]; + return 0; } void MultipleUserConnector::SetSwitchOldUserId(int32_t userId) diff --git a/services/devicemanagerservice/src/dependency/softbus/softbus_connector.cpp b/services/devicemanagerservice/src/dependency/softbus/softbus_connector.cpp index f3278fe8e..ec4c3f369 100644 --- a/services/devicemanagerservice/src/dependency/softbus/softbus_connector.cpp +++ b/services/devicemanagerservice/src/dependency/softbus/softbus_connector.cpp @@ -17,8 +17,12 @@ #include #include +#if (defined(__LINUX__) || defined(__LITEOS_A__)) #include #include +#else +#include +#endif #include "dm_anonymous.h" #include "dm_constants.h" @@ -27,6 +31,9 @@ #include "nlohmann/json.hpp" #include "parameter.h" #include "system_ability_definition.h" +#if defined(__LITEOS_M__) +#include "get_trustdevice_rsp.h" +#endif namespace OHOS { namespace DistributedHardware { @@ -49,6 +56,7 @@ INodeStateCb SoftbusConnector::softbusNodeStateCb_ = { .onNodeOffline = SoftbusConnector::OnSoftbusDeviceOffline, .onNodeBasicInfoChanged = SoftbusConnector::OnSoftbusDeviceInfoChanged}; +#if (defined(__LINUX__) || defined(__LITEOS_A__)) void DeviceOnLine(std::map> stateCallbackMap, DmDeviceInfo deviceInfo) { @@ -72,6 +80,67 @@ void DeviceOffLine(std::map> } LOGI("Device off line end"); } +#else +void DeviceOnLine(std::map> stateCallbackMap, + DmDeviceInfo deviceInfo) +{ + LOGI("Device on line start"); + pthread_mutex_t lockDeviceOnLine; + uint32_t ret = pthread_mutex_init(&lockDeviceOnLine, NULL); + if (ret != 0) { + LOGI("init mutex lock failed: %d.",ret); + } + pthread_mutex_lock(&lockDeviceOnLine); + for (auto &iter : stateCallbackMap) { + iter.second->OnDeviceOnline(iter.first, deviceInfo); + } + pthread_mutex_unlock(&lockDeviceOnLine); + ret = pthread_mutex_destroy(&lockDeviceOnLine); + if (ret != 0) { + LOGI("destroy mutex lock failed: %d.",ret); + } + LOGI("Device on line end"); +} + +void DeviceOffLine(std::map> stateCallbackMap, + DmDeviceInfo deviceInfo) +{ + LOGI("Device off line start"); + pthread_mutex_t lockDeviceOffLine; + uint32_t ret = pthread_mutex_init(&lockDeviceOffLine, NULL); + if (ret != 0) { + LOGI("init mutex lock failed: %d.",ret); + } + pthread_mutex_lock(&lockDeviceOffLine); + for (auto &iter : stateCallbackMap) { + iter.second->OnDeviceOffline(iter.first, deviceInfo); + } + pthread_mutex_unlock(&lockDeviceOffLine); + ret = pthread_mutex_destroy(&lockDeviceOffLine); + if (ret != 0) { + LOGI("destroy mutex lock failed: %d.",ret); + } + LOGI("Device off line end"); +} +struct PthreadCallbackParameter{ + std::map> CallbackMap; + DmDeviceInfo dmDeviceInfo; +}; + +void* PthreadDeviceOnLine(void* parameterInfo) +{ + PthreadCallbackParameter *parameterStruct; + parameterStruct = static_cast(parameterInfo); + DeviceOnLine(parameterStruct->CallbackMap, parameterStruct->dmDeviceInfo); +} + +void* PthreadDeviceOffLine(void* parameterInfo) +{ + PthreadCallbackParameter *parameterStruct; + parameterStruct = static_cast(parameterInfo); + DeviceOffLine(parameterStruct->CallbackMap, parameterStruct->dmDeviceInfo); +} +#endif SoftbusConnector::SoftbusConnector() { @@ -132,7 +201,7 @@ int32_t SoftbusConnector::Init() LOGI("service unpublish result is : %d", ret); } - ret = WatchParameter(DISCOVER_STATUS_KEY.c_str(), &SoftbusConnector::OnParameterChgCallback, nullptr); + // ret = WatchParameter(DISCOVER_STATUS_KEY.c_str(), &SoftbusConnector::OnParameterChgCallback, nullptr); LOGI("register Watch Parameter result is : %d"); return ret; } @@ -166,6 +235,10 @@ int32_t SoftbusConnector::UnRegisterSoftbusStateCallback(const std::string &pkgN int32_t SoftbusConnector::GetTrustedDeviceList(std::vector &deviceInfoList) { LOGI("SoftbusConnector::GetTrustDevices start"); +#if defined(__LITEOS_M__) + std::shared_ptr prsp = std::make_shared(); + std::vector deviceInfoVec; +#endif int32_t infoNum = 0; NodeBasicInfo *nodeInfo = nullptr; int32_t ret = GetAllNodeDeviceInfo(DM_PKG_NAME.c_str(), &nodeInfo, &infoNum); @@ -185,6 +258,9 @@ int32_t SoftbusConnector::GetTrustedDeviceList(std::vector &device CovertNodeBasicInfoToDmDevice(*nodeBasicInfo, *deviceInfo); deviceInfoList.push_back(*deviceInfo); } +#if defined(__LITEOS_M__) + prsp->SetDeviceVec(deviceInfoVec); +#endif FreeNodeInfo(nodeInfo); free(info); LOGI("SoftbusConnector::GetTrustDevices success, deviceCount %d", infoNum); @@ -451,12 +527,12 @@ void SoftbusConnector::CovertDeviceInfoToDmDevice(const DeviceInfo &deviceInfo, dmDeviceInfo.deviceTypeId = deviceInfo.devType; } -void SoftbusConnector::OnPublishSuccess(int32_t publishId) +void SoftbusConnector::OnPublishSuccess(int publishId) { LOGI("SoftbusConnector::OnPublishSuccess, publishId: %d", publishId); } -void SoftbusConnector::OnPublishFail(int32_t publishId, PublishFailReason reason) +void SoftbusConnector::OnPublishFail(int publishId, PublishFailReason reason) { LOGI("SoftbusConnector::OnPublishFail failed, publishId: %d, reason: %d", publishId, reason); } @@ -469,10 +545,21 @@ void SoftbusConnector::OnSoftBusDeviceOnline(NodeBasicInfo *info) return; } +#if (defined(__LINUX__) || defined(__LITEOS_A__)) DmDeviceInfo dmDeviceInfo; CovertNodeBasicInfoToDmDevice(*info, dmDeviceInfo); std::thread deviceOnLine(DeviceOnLine, stateCallbackMap_, dmDeviceInfo); deviceOnLine.detach(); +#else + PthreadCallbackParameter parameterStruct; + parameterStruct.CallbackMap = stateCallbackMap_; + CovertNodeBasicInfoToDmDevice(*info, parameterStruct.dmDeviceInfo); + pthread_t tid; + pthread_attr_t attr; + pthread_attr_init(&attr); + pthread_attr_setdetachstate(&attr,PTHREAD_CREATE_DETACHED); + pthread_create(&tid, &attr, PthreadDeviceOnLine, static_cast(¶meterStruct)); +#endif if (discoveryDeviceInfoMap_.empty()) { return; @@ -496,10 +583,21 @@ void SoftbusConnector::OnSoftbusDeviceOffline(NodeBasicInfo *info) LOGE("OnSoftbusDeviceOffline NodeBasicInfo is nullptr"); return; } +#if (defined(__LINUX__) || defined(__LITEOS_A__)) DmDeviceInfo dmDeviceInfo; CovertNodeBasicInfoToDmDevice(*info, dmDeviceInfo); std::thread deviceOffLine(DeviceOffLine, stateCallbackMap_, dmDeviceInfo); deviceOffLine.detach(); +#else + PthreadCallbackParameter parameterStruct; + parameterStruct.CallbackMap = stateCallbackMap_; + CovertNodeBasicInfoToDmDevice(*info, parameterStruct.dmDeviceInfo); + pthread_t tid; + pthread_attr_t attr; + pthread_attr_init(&attr); + pthread_attr_setdetachstate(&attr,PTHREAD_CREATE_DETACHED); + pthread_create(&tid, &attr, PthreadDeviceOffLine, static_cast(¶meterStruct)); +#endif } void SoftbusConnector::OnSoftbusDeviceInfoChanged(NodeBasicInfoType type, NodeBasicInfo *info) @@ -537,7 +635,7 @@ void SoftbusConnector::OnSoftbusDeviceFound(const DeviceInfo *device) } } -void SoftbusConnector::OnSoftbusDiscoveryFailed(int32_t subscribeId, DiscoveryFailReason failReason) +void SoftbusConnector::OnSoftbusDiscoveryFailed(int subscribeId, DiscoveryFailReason failReason) { LOGI("In, subscribeId %d, failReason %d", subscribeId, (int32_t)failReason); uint16_t originId = (uint16_t)(((uint32_t)subscribeId) & SOFTBUS_SUBSCRIBE_ID_MASK); @@ -546,7 +644,7 @@ void SoftbusConnector::OnSoftbusDiscoveryFailed(int32_t subscribeId, DiscoveryFa } } -void SoftbusConnector::OnSoftbusDiscoverySuccess(int32_t subscribeId) +void SoftbusConnector::OnSoftbusDiscoverySuccess(int subscribeId) { LOGI("In, subscribeId %d", subscribeId); uint16_t originId = (uint16_t)(((uint32_t)subscribeId) & SOFTBUS_SUBSCRIBE_ID_MASK); diff --git a/services/devicemanagerservice/src/dependency/softbus/softbus_session.cpp b/services/devicemanagerservice/src/dependency/softbus/softbus_session.cpp index 8d4b55795..df6fb2fb0 100644 --- a/services/devicemanagerservice/src/dependency/softbus/softbus_session.cpp +++ b/services/devicemanagerservice/src/dependency/softbus/softbus_session.cpp @@ -119,7 +119,7 @@ int32_t SoftbusSession::SendData(int32_t sessionId, std::string &message) return DM_OK; } -int32_t SoftbusSession::OnSessionOpened(int32_t sessionId, int32_t result) +int SoftbusSession::OnSessionOpened(int sessionId, int result) { int32_t sessionSide = GetSessionSide(sessionId); sessionCallback_->OnSessionOpened(sessionId, sessionSide, result); @@ -127,12 +127,12 @@ int32_t SoftbusSession::OnSessionOpened(int32_t sessionId, int32_t result) return DM_OK; } -void SoftbusSession::OnSessionClosed(int32_t sessionId) +void SoftbusSession::OnSessionClosed(int sessionId) { LOGI("OnSessionClosed, sessionId:%d", sessionId); } -void SoftbusSession::OnBytesReceived(int32_t sessionId, const void *data, uint32_t dataLen) +void SoftbusSession::OnBytesReceived(int sessionId, const void *data, unsigned int dataLen) { LOGI("OnBytesReceived, sessionId:%d, dataLen:%d", sessionId, dataLen); if (sessionId < 0 || data == nullptr || dataLen <= 0) { diff --git a/services/devicemanagerservice/src/dependency/timer/mini/dm_timer.cpp b/services/devicemanagerservice/src/dependency/timer/mini/dm_timer.cpp new file mode 100644 index 000000000..b14a07695 --- /dev/null +++ b/services/devicemanagerservice/src/dependency/timer/mini/dm_timer.cpp @@ -0,0 +1,75 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "dm_timer.h" + +namespace OHOS { +namespace DistributedHardware { +namespace { +const int32_t MILL_SECONDS_PER_SECOND = 1000; +} +DmTimer::DmTimer(const std::string &name) +{ + if (name.empty()) { + LOGI("DmTimer name is null"); + return; + } + + LOGI("DmTimer %s Construct", name.c_str()); +} + +DmTimer::~DmTimer() +{ + if (mTimerName_.empty()) { + LOGI("DmTimer is not init"); + return; + } + LOGI("DmTimer %s Destroy in", mTimerName_.c_str()); +} + +DmTimerStatus DmTimer::Start(uint32_t timeOut, TimeoutHandle handle, void *data) +{ + LOGI("DmTimer start timeout(%d)", timeOut); + mStatus_ = DmTimerStatus::DM_STATUS_RUNNING; + return mStatus_; +} + +void DmTimer::Stop(int32_t code) +{ + LOGI("DmTimer Stop code (%d)", code); + return; +} + +void DmTimer::WaitForTimeout() +{ + +} + +int32_t DmTimer::CreateTimeFd() +{ + return 0; +} + +void DmTimer::Release() +{ + +} + +std::string DmTimer::GetTimerName() +{ + return mTimerName_; +} +} // namespace DistributedHardware +} // namespace OHOS diff --git a/services/devicemanagerservice/src/device_manager_service.cpp b/services/devicemanagerservice/src/device_manager_service.cpp index a0d03611e..bbb1c9ace 100644 --- a/services/devicemanagerservice/src/device_manager_service.cpp +++ b/services/devicemanagerservice/src/device_manager_service.cpp @@ -19,12 +19,12 @@ // #include "common_event_support.h" #include "device_manager_service_listener.h" -// #include "dm_common_event_manager.h" +#include "dm_common_event_manager.h" #include "dm_constants.h" -// #include "dm_device_info_manager.h" +#include "dm_device_info_manager.h" #include "dm_log.h" #include "multiple_user_connector.h" -// #include "permission_manager.h" +#include "permission_manager.h" // using namespace OHOS::EventFwk; @@ -39,8 +39,8 @@ DeviceManagerService::~DeviceManagerService() // if (dmCommonEventManager.UnsubscribeServiceEvent(CommonEventSupport::COMMON_EVENT_USER_STOPPED)) { // LOGI("subscribe service event success"); // } - // softbusConnector_->GetSoftbusSession()->UnRegisterSessionCallback(); - // hiChainConnector_->UnRegisterHiChainCallback(); + softbusConnector_->GetSoftbusSession()->UnRegisterSessionCallback(); + hiChainConnector_->UnRegisterHiChainCallback(); } int32_t DeviceManagerService::Init() @@ -50,69 +50,69 @@ int32_t DeviceManagerService::Init() return DM_INT_MULTIPLE; } - // if (!PermissionManager::GetInstance().CheckPermission()) { - // LOGI("The caller does not have permission to call"); - // return DM_NO_PERMISSION; - // } + if (!PermissionManager::GetInstance().CheckPermission()) { + LOGI("The caller does not have permission to call"); + return DM_NO_PERMISSION; + } - // if (softbusConnector_ == nullptr) { - // softbusConnector_ = std::make_shared(); - // if (softbusConnector_ == nullptr) { - // LOGE("Init failed, softbusConnector_ apply for failure"); - // return DM_MAKE_SHARED_FAIL; - // } - // } - // if (listener_ == nullptr) { - // listener_ = std::make_shared(); - // if (softbusConnector_ == nullptr) { - // LOGE("Init failed, listener_ apply for failure"); - // return DM_MAKE_SHARED_FAIL; - // } - // } - // if (hiChainConnector_ == nullptr) { - // hiChainConnector_ = std::make_shared(); - // if (hiChainConnector_ == nullptr) { - // LOGE("Init failed, hiChainConnector_ apply for failure"); - // return DM_MAKE_SHARED_FAIL; - // } - // } - // if (deviceInfoMgr_ == nullptr) { - // deviceInfoMgr_ = std::make_shared(softbusConnector_); - // if (deviceInfoMgr_ == nullptr) { - // LOGE("Init failed, deviceInfoMgr_ apply for failure"); - // return DM_MAKE_SHARED_FAIL; - // } - // } - // if (deviceStateMgr_ == nullptr) { - // deviceStateMgr_ = std::make_shared(softbusConnector_, listener_, hiChainConnector_); - // if (deviceStateMgr_ == nullptr) { - // LOGE("Init failed, deviceStateMgr_ apply for failure"); - // return DM_MAKE_SHARED_FAIL; - // } - // deviceStateMgr_->RegisterSoftbusStateCallback(); - // } - // if (discoveryMgr_ == nullptr) { - // discoveryMgr_ = std::make_shared(softbusConnector_, listener_); - // if (discoveryMgr_ == nullptr) { - // LOGE("Init failed, discoveryMgr_ apply for failure"); - // return DM_MAKE_SHARED_FAIL; - // } - // } - // if (authMgr_ == nullptr) { - // authMgr_ = std::make_shared(softbusConnector_, listener_, hiChainConnector_); - // if (authMgr_ == nullptr) { - // LOGE("Init failed, authMgr_ apply for failure"); - // return DM_MAKE_SHARED_FAIL; - // } - // softbusConnector_->GetSoftbusSession()->RegisterSessionCallback(authMgr_); - // hiChainConnector_->RegisterHiChainCallback(authMgr_); - // } + if (softbusConnector_ == nullptr) { + softbusConnector_ = std::make_shared(); + if (softbusConnector_ == nullptr) { + LOGE("Init failed, softbusConnector_ apply for failure"); + return DM_MAKE_SHARED_FAIL; + } + } + if (listener_ == nullptr) { + listener_ = std::make_shared(); + if (softbusConnector_ == nullptr) { + LOGE("Init failed, listener_ apply for failure"); + return DM_MAKE_SHARED_FAIL; + } + } + if (hiChainConnector_ == nullptr) { + hiChainConnector_ = std::make_shared(); + if (hiChainConnector_ == nullptr) { + LOGE("Init failed, hiChainConnector_ apply for failure"); + return DM_MAKE_SHARED_FAIL; + } + } + if (deviceInfoMgr_ == nullptr) { + deviceInfoMgr_ = std::make_shared(softbusConnector_); + if (deviceInfoMgr_ == nullptr) { + LOGE("Init failed, deviceInfoMgr_ apply for failure"); + return DM_MAKE_SHARED_FAIL; + } + } + if (deviceStateMgr_ == nullptr) { + deviceStateMgr_ = std::make_shared(softbusConnector_, listener_, hiChainConnector_); + if (deviceStateMgr_ == nullptr) { + LOGE("Init failed, deviceStateMgr_ apply for failure"); + return DM_MAKE_SHARED_FAIL; + } + deviceStateMgr_->RegisterSoftbusStateCallback(); + } + if (discoveryMgr_ == nullptr) { + discoveryMgr_ = std::make_shared(softbusConnector_, listener_); + if (discoveryMgr_ == nullptr) { + LOGE("Init failed, discoveryMgr_ apply for failure"); + return DM_MAKE_SHARED_FAIL; + } + } + if (authMgr_ == nullptr) { + authMgr_ = std::make_shared(softbusConnector_, listener_, hiChainConnector_); + if (authMgr_ == nullptr) { + LOGE("Init failed, authMgr_ apply for failure"); + return DM_MAKE_SHARED_FAIL; + } + softbusConnector_->GetSoftbusSession()->RegisterSessionCallback(authMgr_); + hiChainConnector_->RegisterHiChainCallback(authMgr_); + } - // int32_t userId = MultipleUserConnector::GetCurrentAccountUserID(); - // if (userId > 0) { - // LOGI("get current account user id success"); - // MultipleUserConnector::SetSwitchOldUserId(userId); - // } + int32_t userId = MultipleUserConnector::GetCurrentAccountUserID(); + if (userId > 0) { + LOGI("get current account user id success"); + MultipleUserConnector::SetSwitchOldUserId(userId); + } // DmCommonEventManager &dmCommonEventManager = DmCommonEventManager::GetInstance(); // CommomEventCallback callback = std::bind(&DmAuthManager::UserSwitchEventCallback, *authMgr_.get(), @@ -129,10 +129,10 @@ int32_t DeviceManagerService::Init() int32_t DeviceManagerService::GetTrustedDeviceList(const std::string &pkgName, const std::string &extra, std::vector &deviceList) { - // if (!PermissionManager::GetInstance().CheckPermission()) { - // LOGI("The caller does not have permission to call"); - // return DM_NO_PERMISSION; - // } + if (!PermissionManager::GetInstance().CheckPermission()) { + LOGI("The caller does not have permission to call"); + return DM_NO_PERMISSION; + } if (!intFlag_) { LOGE("GetTrustedDeviceList failed, singleton not init or init fail"); return DM_NOT_INIT; @@ -141,22 +141,20 @@ int32_t DeviceManagerService::GetTrustedDeviceList(const std::string &pkgName, c LOGE("GetTrustedDeviceList failed, pkgName is empty"); return DM_INPUT_PARA_EMPTY; } - // return deviceInfoMgr_->GetTrustedDeviceList(pkgName, extra, deviceList); - return 0; + return deviceInfoMgr_->GetTrustedDeviceList(pkgName, extra, deviceList); } int32_t DeviceManagerService::GetLocalDeviceInfo(DmDeviceInfo &info) { - // if (!PermissionManager::GetInstance().CheckPermission()) { - // LOGI("The caller does not have permission to call"); - // return DM_NO_PERMISSION; - // } + if (!PermissionManager::GetInstance().CheckPermission()) { + LOGI("The caller does not have permission to call"); + return DM_NO_PERMISSION; + } if (!intFlag_) { LOGE("GetLocalDeviceInfo failed, singleton not init or init fail"); return DM_NOT_INIT; } - // return deviceInfoMgr_->GetLocalDeviceInfo(info); - return 0; + return deviceInfoMgr_->GetLocalDeviceInfo(info); } int32_t DeviceManagerService::GetUdidByNetworkId(const std::string &pkgName, const std::string &netWorkId, @@ -171,7 +169,7 @@ int32_t DeviceManagerService::GetUdidByNetworkId(const std::string &pkgName, con LOGE("StartDeviceDiscovery failed, pkgName is empty"); return DM_INPUT_PARA_EMPTY; } - // SoftbusConnector::GetUdidByNetworkId(netWorkId.c_str(), udid); + SoftbusConnector::GetUdidByNetworkId(netWorkId.c_str(), udid); return DM_OK; } @@ -187,17 +185,17 @@ int32_t DeviceManagerService::GetUuidByNetworkId(const std::string &pkgName, con LOGE("StartDeviceDiscovery failed, pkgName is empty"); return DM_INPUT_PARA_EMPTY; } - // SoftbusConnector::GetUuidByNetworkId(netWorkId.c_str(), uuid); + SoftbusConnector::GetUuidByNetworkId(netWorkId.c_str(), uuid); return DM_OK; } int32_t DeviceManagerService::StartDeviceDiscovery(const std::string &pkgName, const DmSubscribeInfo &subscribeInfo, const std::string &extra) { - // if (!PermissionManager::GetInstance().CheckPermission()) { - // LOGI("The caller does not have permission to call"); - // return DM_NO_PERMISSION; - // } + if (!PermissionManager::GetInstance().CheckPermission()) { + LOGI("The caller does not have permission to call"); + return DM_NO_PERMISSION; + } if (!intFlag_) { LOGE("StartDeviceDiscovery failed, singleton not init or init fail"); return DM_NOT_INIT; @@ -206,16 +204,15 @@ int32_t DeviceManagerService::StartDeviceDiscovery(const std::string &pkgName, c LOGE("StartDeviceDiscovery failed, pkgName is empty"); return DM_INPUT_PARA_EMPTY; } - // return discoveryMgr_->StartDeviceDiscovery(pkgName, subscribeInfo, extra); - return 0; + return discoveryMgr_->StartDeviceDiscovery(pkgName, subscribeInfo, extra); } int32_t DeviceManagerService::StopDeviceDiscovery(const std::string &pkgName, uint16_t subscribeId) { - // if (!PermissionManager::GetInstance().CheckPermission()) { - // LOGI("The caller does not have permission to call"); - // return DM_NO_PERMISSION; - // } + if (!PermissionManager::GetInstance().CheckPermission()) { + LOGI("The caller does not have permission to call"); + return DM_NO_PERMISSION; + } if (!intFlag_) { LOGE("StopDeviceDiscovery failed, singleton not init or init fail"); return DM_NOT_INIT; @@ -224,17 +221,16 @@ int32_t DeviceManagerService::StopDeviceDiscovery(const std::string &pkgName, ui LOGE("StopDeviceDiscovery failed, pkgName is empty"); return DM_INPUT_PARA_EMPTY; } - // return discoveryMgr_->StopDeviceDiscovery(pkgName, subscribeId); - return 0; + return discoveryMgr_->StopDeviceDiscovery(pkgName, subscribeId); } int32_t DeviceManagerService::AuthenticateDevice(const std::string &pkgName, int32_t authType, const std::string &deviceId, const std::string &extra) { - // if (!PermissionManager::GetInstance().CheckPermission()) { - // LOGI("The caller does not have permission to call"); - // return DM_NO_PERMISSION; - // } + if (!PermissionManager::GetInstance().CheckPermission()) { + LOGI("The caller does not have permission to call"); + return DM_NO_PERMISSION; + } if (!intFlag_) { LOGE("AuthenticateDevice failed, singleton not init or init fail"); return DM_NOT_INIT; @@ -247,16 +243,15 @@ int32_t DeviceManagerService::AuthenticateDevice(const std::string &pkgName, int LOGE("AuthenticateDevice failed, deviceId is empty"); return DM_INPUT_PARA_EMPTY; } - // return authMgr_->AuthenticateDevice(pkgName, authType, deviceId, extra); - return 0; + return authMgr_->AuthenticateDevice(pkgName, authType, deviceId, extra); } int32_t DeviceManagerService::UnAuthenticateDevice(const std::string &pkgName, const std::string &deviceId) { - // if (!PermissionManager::GetInstance().CheckPermission()) { - // LOGI("The caller does not have permission to call"); - // return DM_NO_PERMISSION; - // } + if (!PermissionManager::GetInstance().CheckPermission()) { + LOGI("The caller does not have permission to call"); + return DM_NO_PERMISSION; + } if (!intFlag_) { LOGE("UnAuthenticateDevice failed, singleton not init or init fail"); return DM_NOT_INIT; @@ -269,22 +264,20 @@ int32_t DeviceManagerService::UnAuthenticateDevice(const std::string &pkgName, c LOGE("UnAuthenticateDevice failed, deviceId is empty"); return DM_INPUT_PARA_EMPTY; } - // return authMgr_->UnAuthenticateDevice(pkgName, deviceId); - return 0; + return authMgr_->UnAuthenticateDevice(pkgName, deviceId); } int32_t DeviceManagerService::VerifyAuthentication(const std::string &authParam) { - // if (!PermissionManager::GetInstance().CheckPermission()) { - // LOGI("The caller does not have permission to call"); - // return DM_NO_PERMISSION; - // } + if (!PermissionManager::GetInstance().CheckPermission()) { + LOGI("The caller does not have permission to call"); + return DM_NO_PERMISSION; + } if (!intFlag_) { LOGE("VerifyAuthentication failed, singleton not init or init fail"); return DM_NOT_INIT; } - // return authMgr_->VerifyAuthentication(authParam); - return 0; + return authMgr_->VerifyAuthentication(authParam); } int32_t DeviceManagerService::GetFaParam(std::string &pkgName, DmAuthParam &authParam) @@ -293,7 +286,7 @@ int32_t DeviceManagerService::GetFaParam(std::string &pkgName, DmAuthParam &auth LOGE("GetFaParam failed, pkgName is empty"); return DM_INPUT_PARA_EMPTY; } - // authMgr_->GetAuthenticationParam(authParam); + authMgr_->GetAuthenticationParam(authParam); return DM_OK; } @@ -303,19 +296,19 @@ int32_t DeviceManagerService::SetUserOperation(std::string &pkgName, int32_t act LOGE("SetUserOperation failed, pkgName is empty"); return DM_INPUT_PARA_EMPTY; } - // authMgr_->OnUserOperation(action); + authMgr_->OnUserOperation(action); return DM_OK; } int32_t DeviceManagerService::RegisterDevStateCallback(const std::string &pkgName, const std::string &extra) { - // deviceStateMgr_->RegisterDevStateCallback(pkgName, extra); + deviceStateMgr_->RegisterDevStateCallback(pkgName, extra); return DM_OK; } int32_t DeviceManagerService::UnRegisterDevStateCallback(const std::string &pkgName, const std::string &extra) { - // deviceStateMgr_->UnRegisterDevStateCallback(pkgName, extra); + deviceStateMgr_->UnRegisterDevStateCallback(pkgName, extra); return DM_OK; } } // namespace DistributedHardware diff --git a/services/devicemanagerservice/src/devicestate/dm_device_state_manager.cpp b/services/devicemanagerservice/src/devicestate/dm_device_state_manager.cpp index 8c182fa9a..6d951fd21 100755 --- a/services/devicemanagerservice/src/devicestate/dm_device_state_manager.cpp +++ b/services/devicemanagerservice/src/devicestate/dm_device_state_manager.cpp @@ -39,6 +39,12 @@ DmDeviceStateManager::DmDeviceStateManager(std::shared_ptr sof std::shared_ptr listener, std::shared_ptr hiChainConnector) : softbusConnector_(softbusConnector), listener_(listener), hiChainConnector_(hiChainConnector) { +#if defined(__LITEOS_M__) + uint32_t ret = pthread_mutex_init(&lock_, NULL); + if (ret != 0) { + LOGI("init mutex lock failed: %d.",ret); + } +#endif profileSoName_ = "libdevicemanagerext_profile.z.so"; LOGI("DmDeviceStateManager constructor"); } @@ -46,6 +52,12 @@ DmDeviceStateManager::DmDeviceStateManager(std::shared_ptr sof DmDeviceStateManager::~DmDeviceStateManager() { LOGI("DmDeviceStateManager destructor"); +#if defined(__LITEOS_M__) + uint32_t ret = pthread_mutex_destroy(&lock_); + if (ret != 0) { + LOGI("destroy mutex lock failed: %d.",ret); + } +#endif if (softbusConnector_ != nullptr) { softbusConnector_->UnRegisterSoftbusStateCallback("DM_PKG_NAME"); } @@ -64,8 +76,14 @@ int32_t DmDeviceStateManager::RegisterProfileListener(const std::string &pkgName DmDeviceInfo saveInfo = info; SoftbusConnector::GetUuidByNetworkId(info.deviceId, uuid); { +#if (defined(__LINUX__) || defined(__LITEOS_A__)) std::lock_guard mutexLock(remoteDeviceInfosMutex_); remoteDeviceInfos_[uuid] = saveInfo; +#else + pthread_mutex_lock(&lock_); + remoteDeviceInfos_[uuid] = saveInfo; + pthread_mutex_unlock(&lock_); +#endif } std::string deviceUdid = (char *)udid; LOGI("RegisterProfileListener in, deviceId = %s, deviceUdid = %s, uuid = %s", @@ -85,10 +103,19 @@ int32_t DmDeviceStateManager::UnRegisterProfileListener(const std::string &pkgNa profileAdapter->UnRegisterProfileListener(pkgName); } { + +#if (defined(__LINUX__) || defined(__LITEOS_A__)) std::lock_guard mutexLock(remoteDeviceInfosMutex_); if (remoteDeviceInfos_.find(std::string(info.deviceId)) != remoteDeviceInfos_.end()) { remoteDeviceInfos_.erase(std::string(info.deviceId)); } +#else + pthread_mutex_lock(&lock_); + if (remoteDeviceInfos_.find(std::string(info.deviceId)) != remoteDeviceInfos_.end()) { + remoteDeviceInfos_.erase(std::string(info.deviceId)); + } + pthread_mutex_unlock(&lock_); +#endif } return DM_OK; } @@ -194,6 +221,7 @@ void DmDeviceStateManager::OnProfileReady(const std::string &pkgName, const std: } DmDeviceInfo saveInfo; { +#if (defined(__LINUX__) || defined(__LITEOS_A__)) std::lock_guard mutexLock(remoteDeviceInfosMutex_); auto iter = remoteDeviceInfos_.find(deviceId); if (iter == remoteDeviceInfos_.end()) { @@ -201,6 +229,16 @@ void DmDeviceStateManager::OnProfileReady(const std::string &pkgName, const std: return; } saveInfo = iter->second; +#else + pthread_mutex_lock(&lock_); + auto iter = remoteDeviceInfos_.find(deviceId); + if (iter == remoteDeviceInfos_.end()) { + LOGE("OnProfileReady complete not find deviceId: %s", GetAnonyString(deviceId).c_str()); + return; + } + saveInfo = iter->second; + pthread_mutex_unlock(&lock_); +#endif } if (listener_ != nullptr) { DmDeviceState state = DEVICE_INFO_READY; @@ -243,7 +281,8 @@ void DmDeviceStateManager::RegisterOffLineTimer(const DmDeviceInfo &deviceInfo) return; } LOGI("Register OffLine Timer with device: %s", GetAnonyString(deviceId).c_str()); - + +#if (defined(__LINUX__) || defined(__LITEOS_A__)) std::lock_guard mutexLock(timerMapMutex_); auto iter = timerMap_.find(deviceId); if (iter != timerMap_.end()) { @@ -254,6 +293,19 @@ void DmDeviceStateManager::RegisterOffLineTimer(const DmDeviceInfo &deviceInfo) if (offLineTimer != nullptr) { timerMap_[deviceId] = offLineTimer; } +#else + pthread_mutex_lock(&lock_); + auto iter = timerMap_.find(deviceId); + if (iter != timerMap_.end()) { + iter->second->Stop(SESSION_CANCEL_TIMEOUT); + return; + } + std::shared_ptr offLineTimer = std::make_shared(deviceId); + if (offLineTimer != nullptr) { + timerMap_[deviceId] = offLineTimer; + } + pthread_mutex_unlock(&lock_); +#endif } void DmDeviceStateManager::StartOffLineTimer(const DmDeviceInfo &deviceInfo) @@ -266,12 +318,22 @@ void DmDeviceStateManager::StartOffLineTimer(const DmDeviceInfo &deviceInfo) } LOGI("start offline timer with device: %s", GetAnonyString(deviceId).c_str()); +#if (defined(__LINUX__) || defined(__LITEOS_A__)) std::lock_guard mutexLock(timerMapMutex_); for (auto &iter : timerMap_) { if (iter.first == deviceId) { iter.second->Start(OFFLINE_TIMEOUT, TimeOut, this); } } +#else + pthread_mutex_lock(&lock_); + for (auto &iter : timerMap_) { + if (iter.first == deviceId) { + iter.second->Start(OFFLINE_TIMEOUT, TimeOut, this); + } + } + pthread_mutex_unlock(&lock_); +#endif } void DmDeviceStateManager::DeleteTimeOutGroup(std::string deviceId) -- Gitee From d5b3d3bda772012615fc84749c2a98bdcad8d709 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E8=94=A1=E9=98=94?= Date: Thu, 10 Mar 2022 03:53:12 +0000 Subject: [PATCH 06/19] =?UTF-8?q?!29=20=E4=BF=AE=E6=94=B9DM=E5=AD=90?= =?UTF-8?q?=E6=A8=A1=E5=9D=97build.gn=E6=96=87=E4=BB=B6=20*=20=E4=BF=AE?= =?UTF-8?q?=E6=94=B9DM=E5=AD=90=E6=A8=A1=E5=9D=97build.gn=E6=96=87?= =?UTF-8?q?=E4=BB=B6?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- BUILD.gn | 11 ++ .../inner_kits/native_cpp/BUILD.gn | 115 ++++++------------ interfaces_mini/kits/js/BUILD.gn | 114 +++++------------ services/devicemanagerservice/BUILD.gn | 108 +++++++++++++++- utils/BUILD.gn | 47 ++++++- 5 files changed, 228 insertions(+), 167 deletions(-) diff --git a/BUILD.gn b/BUILD.gn index 7e5dfc76c..a81ffc487 100644 --- a/BUILD.gn +++ b/BUILD.gn @@ -14,10 +14,21 @@ import("//build/lite/config/component/lite_component.gni") if (defined(ohos_lite)) { +if (ohos_kernel_type == "liteos_m") { + lite_component("devicemanager_mini") { + features = [ + "utils:devicemanagerutils_mini", + "services/devicemanagerservice:devicemanagerservice_mini", + "interfaces_mini/inner_kits/native_cpp:devicemanagersdk_mini", + "interfaces_mini/kits/js:devicemanager_native_js", + ] + } + } else { lite_component("devicemanager_lite") { if (ohos_kernel_type == "liteos_m") { } else { features = [] } } + } } diff --git a/interfaces_mini/inner_kits/native_cpp/BUILD.gn b/interfaces_mini/inner_kits/native_cpp/BUILD.gn index fbb4f13b7..343788b11 100644 --- a/interfaces_mini/inner_kits/native_cpp/BUILD.gn +++ b/interfaces_mini/inner_kits/native_cpp/BUILD.gn @@ -11,100 +11,53 @@ # See the License for the specific language governing permissions and # limitations under the License. + if (defined(ohos_lite)) { import("//build/lite/config/component/lite_component.gni") } else { import("//build/ohos.gni") } import("//foundation/distributedhardware/devicemanager/devicemanager.gni") +innerkits_path_mini = "${devicemanager_path}/interfaces_mini/inner_kits" if (defined(ohos_lite)) { if (ohos_kernel_type == "liteos_m") { static_library("devicemanagersdk_mini") { - include_dirs = [ - "include", - "include/notify", - "${utils_path}/include/log", - "${common_path}/include", - "//foundation/distributedhardware/devicemanager/services/devicemanagerservice/include/dispatch", - ] - include_dirs += [ - "//utils/native/lite/include", - "//base/hiviewdfx/hilog_lite/interfaces/native/innerkits/hilog", - "//third_party/bounds_checking_function/include", - "//foundation/distributedschedule/samgr_lite/interfaces/kits/samgr", - "//third_party/json/include", - ] - - sources = [ - "src/device_manager.cpp", - "src/device_manager_impl.cpp", - "src/notify/device_manager_notify.cpp", - ] - - defines = [ - "LITE_DEVICE", - "HI_LOG_ENABLE", - "DH_LOG_TAG=\"devicemanagerkit\"", - "LOG_DOMAIN=0xD004100", - ] - - deps = [ - "${utils_path}:devicemanagerutils_mini", - "//base/hiviewdfx/hilog_lite/frameworks/featured:hilog_static", - "//foundation/distributedschedule/samgr_lite/samgr", - "//third_party/bounds_checking_function:libsec_static", - "//utils/native/lite:utils", - ] - } - } else { - shared_library("devicemanagersdk") { - include_dirs = [ - "include", - "include/ipc", - "include/ipc/lite", - "include/notify", - "${utils_path}/include/log", - "${utils_path}/include/ipc/lite", - "${common_path}/include/ipc", - "${common_path}/include/ipc/model", - "${common_path}/include", - ] - include_dirs += [ - "//utils/native/lite/include", - "//base/hiviewdfx/hilog_lite/interfaces/native/innerkits/hilog", - "//third_party/bounds_checking_function/include", - "//foundation/communication/ipc_lite/interfaces/kits", - "//foundation/distributedschedule/samgr_lite/interfaces/kits/samgr", - "//third_party/json/include", - ] + include_dirs = [ + "${innerkits_path_mini}/native_cpp/include", + "${innerkits_path_mini}/native_cpp/include/notify", + "${utils_path}/include", + "${common_path}/include", + "${services_path}/include/dispatch", + ] + include_dirs += [ + "//utils/native/lite/include", + "//base/hiviewdfx/hilog_lite/interfaces/native/innerkits/hilog", + "//third_party/bounds_checking_function/include", + "//foundation/distributedschedule/samgr_lite/interfaces/kits/samgr", + "//third_party/json/include", + ] - sources = [ - "src/device_manager.cpp", - "src/device_manager_impl.cpp", - "src/ipc/ipc_client_proxy.cpp", - "src/ipc/lite/ipc_client_manager.cpp", - "src/ipc/lite/ipc_client_server_proxy.cpp", - "src/ipc/lite/ipc_client_stub.cpp", - "src/ipc/lite/ipc_cmd_parser.cpp", - "src/notify/device_manager_notify.cpp", - ] + sources = [ + "${innerkits_path_mini}/native_cpp/src/device_manager.cpp", + "${innerkits_path_mini}/native_cpp/src/device_manager_impl.cpp", + "${innerkits_path_mini}/native_cpp/src/notify/device_manager_notify.cpp", + ] - defines = [ - "LITE_DEVICE", - "HI_LOG_ENABLE", - "DH_LOG_TAG=\"devicemanagerkit\"", - "LOG_DOMAIN=0xD004100", - ] + defines = [ + "LITE_DEVICE", + "HI_LOG_ENABLE", + "DH_LOG_TAG=\"devicemanagerkit\"", + "LOG_DOMAIN=0xD004100", + ] - deps = [ - "${utils_path}:devicemanagerutils", - "//base/hiviewdfx/hilog_lite/frameworks/featured:hilog_shared", - "//foundation/communication/ipc_lite:liteipc_adapter", - "//foundation/distributedschedule/samgr_lite/samgr:samgr", - "//third_party/bounds_checking_function:libsec_shared", - "//utils/native/lite:utils", - ] + deps = [ + "${utils_path}:devicemanagerutils_mini", + "//base/hiviewdfx/hilog_lite/frameworks/featured:hilog_static", + "//foundation/distributedschedule/samgr_lite/samgr", + "//third_party/bounds_checking_function:libsec_static", + "//utils/native/lite:utils", + ] } } } else { diff --git a/interfaces_mini/kits/js/BUILD.gn b/interfaces_mini/kits/js/BUILD.gn index fd6f6c1c4..e5d0c5a6a 100644 --- a/interfaces_mini/kits/js/BUILD.gn +++ b/interfaces_mini/kits/js/BUILD.gn @@ -11,6 +11,7 @@ # See the License for the specific language governing permissions and # limitations under the License. + if (defined(ohos_lite)) { import("//build/lite/config/component/lite_component.gni") } else { @@ -18,88 +19,39 @@ if (defined(ohos_lite)) { } import("//foundation/distributedhardware/devicemanager/devicemanager.gni") +innerkits_path_mini = "${devicemanager_path}/interfaces_mini/inner_kits" +kits_path = "${devicemanager_path}/interfaces_mini/kits" if (ohos_kernel_type == "liteos_m") { - static_library("devicemanager") { - include_dirs = [ - "//third_party/node/src", - "//third_party/json/include", - "${common_path}/include", - "//utils/native/base/include", - "include", - "${utils_path}/include/log", - "//foundation/ace/ace_engine_lite/interfaces/innerkits/builtin/base", - "//foundation/ace/ace_engine_lite/interfaces/innerkits/builtin/jsi", - "//foundation/ace/ace_engine_lite/interfaces/innerkits/builtin/async", - "//foundation/ace/ace_engine_lite/frameworks/src/core/context/js_app_context.h", - "${innerkits_path}/native_cpp/include", - ] - - sources = [ - "src/dm_native_event.cpp", - "src/native_devicemanager_js.cpp", - ] - - deps = [ - "${utils_path}:devicemanagerutils_mini", - "//foundation/distributedhardware/devicemanager/interfaces_small/inner_kits/native_cpp:devicemanagersdk_mini", - ] - - defines = [ - "HI_LOG_ENABLE", - "DH_LOG_TAG=\"devicemanagerkit_js\"", - "LOG_DOMAIN=0xD004100", - ] + static_library("devicemanager_native_js") { + include_dirs = [ + "//third_party/node/src", + "//third_party/json/include", + "${common_path}/include", + "//utils/native/base/include", + "${kits_path}/js/include", + "${utils_path}/include", + "//foundation/ace/ace_engine_lite/interfaces/innerkits/builtin/base", + "//foundation/ace/ace_engine_lite/interfaces/innerkits/builtin/jsi", + "//foundation/ace/ace_engine_lite/interfaces/innerkits/builtin/async", + "//foundation/ace/ace_engine_lite/frameworks/include/context", + "${innerkits_path_mini}/native_cpp/include", + ] + + sources = [ + "${kits_path}/js/src/dm_native_event.cpp", + "${kits_path}/js/src/native_devicemanager_js.cpp", + ] + + deps = [ + "${innerkits_path_mini}/native_cpp:devicemanagersdk_mini", + "${utils_path}:devicemanagerutils_mini", + ] + + defines = [ + "HI_LOG_ENABLE", + "DH_LOG_TAG=\"devicemanagerkit_js\"", + "LOG_DOMAIN=0xD004100", + ] } -} else { - ohos_shared_library("devicemanager") { - include_dirs = [ - "//third_party/node/src", - "//third_party/json/include", - "${common_path}/include", - "//foundation/ace/napi/native_engine", - "//foundation/ace/napi/interfaces/kits", - "//utils/native/base/include", - "include", - "${utils_path}/include/log", - "${common_path}/include/ipc", - "${innerkits_path}/native_cpp/include", - "${innerkits_path}/native_cpp/include/standard", - ] - - sources = [ - "src/dm_native_event.cpp", - "src/native_devicemanager_js.cpp", - ] - - deps = [ - "${utils_path}:devicemanagerutils", - "//foundation/ace/napi:ace_napi", - "//foundation/distributedhardware/devicemanager/interfaces/inner_kits/native_cpp:devicemanagersdk", - "//utils/native/base:utils", - ] - - defines = [ - "HI_LOG_ENABLE", - "DH_LOG_TAG=\"devicemanagerkit_js\"", - "LOG_DOMAIN=0xD004100", - ] - - external_deps = [ - "appexecfwk_standard:appexecfwk_base", - "appexecfwk_standard:appexecfwk_core", - "hiviewdfx_hilog_native:libhilog", - "ipc:ipc_core", - "safwk:system_ability_fwk", - "samgr_standard:samgr_proxy", - ] - - subsystem_name = "distributedhardware" - relative_install_dir = "module/distributedhardware" - part_name = "device_manager_base" - } -} - -group("devicemanager_native_js") { - deps = [ ":devicemanager" ] } diff --git a/services/devicemanagerservice/BUILD.gn b/services/devicemanagerservice/BUILD.gn index ba6da08e0..3bf249efe 100755 --- a/services/devicemanagerservice/BUILD.gn +++ b/services/devicemanagerservice/BUILD.gn @@ -2,15 +2,16 @@ # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at -# +# # http://www.apache.org/licenses/LICENSE-2.0 -# +# # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. + if (defined(ohos_lite)) { import("//build/lite/config/component/lite_component.gni") } else { @@ -18,10 +19,109 @@ if (defined(ohos_lite)) { } import("//foundation/distributedhardware/devicemanager/devicemanager.gni") +innerkits_path_mini = "${devicemanager_path}/interfaces_mini/inner_kits" if (defined(ohos_lite)) { - executable("devicemanagerservice") { - sources = [ "src/ipc/lite/ipc_server_main.cpp" ] + if (ohos_kernel_type == "liteos_m") { + static_library("devicemanagerservice_mini") { + include_dirs = [ + "${innerkits_path_mini}/native_cpp/include", + "${innerkits_path_mini}/native_cpp/include/notify", + "${services_path}/include", + "${services_path}/include/config", + "${services_path}/include/config/mini", + "${services_path}/include/adapter", + "${services_path}/include/authentication", + "${services_path}/include/ability", + "${services_path}/include/deviceinfo", + "${services_path}/include/devicestate", + "${services_path}/include/discovery", + "${services_path}/include/dependency/commonevent", + "${services_path}/include/dependency/multipleuser", + "${services_path}/include/dependency/hichain", + "${services_path}/include/dependency/softbus", + "${services_path}/include/dependency/timer", + "${services_path}/include/eventbus", + "${common_path}/include", + "//base/security/deviceauth/interfaces/innerkits", + "//third_party/json/include", + "//base/account/os_account/interfaces/innerkits/osaccount/native/include", + "${utils_path}/include", + "${utils_path}/include/permission/lite", + "foundation/multimedia/image_standard/mock/native/include", + "${services_path}/include/dispatch", + ] + + include_dirs += [ + "//base/security/deviceauth/interfaces/innerkits", + "//base/startup/syspara_lite/interfaces/innerkits/native/syspara/include", + "//utils/native/lite/include", + "//utils/system/safwk/native/include", + "//third_party/json/include", + "//base/hiviewdfx/hilog_lite/interfaces/native/innerkits/hilog", + "//third_party/bounds_checking_function/include", + "//foundation/communication/ipc_lite/interfaces/kits", + "//foundation/communication/dsoftbus/interfaces/kits/bus_center", + "//foundation/communication/dsoftbus/interfaces/kits/common", + "//foundation/communication/dsoftbus/interfaces/kits/discovery", + "//foundation/communication/dsoftbus/interfaces/kits/transport", + "//foundation/communication/dsoftbus/interfaces/inner_kits/transport", + "//foundation/distributedhardware/devicemanager/services/devicemanagerservice/include/dependency/multipleuser", + "//foundation/distributedschedule/samgr_lite/interfaces/kits/samgr", + "//foundation/distributedschedule/samgr/interfaces/innerkits/samgr_proxy/include", + ] + + sources = [ + "${services_path}/src/ability/lite/dm_ability_manager.cpp", + "${services_path}/src/adapter/standard/dm_adapter_manager.cpp", + "${services_path}/src/authentication/auth_message_processor.cpp", + "${services_path}/src/authentication/auth_request_state.cpp", + "${services_path}/src/authentication/auth_response_state.cpp", + "${services_path}/src/authentication/auth_ui.cpp", + "${services_path}/src/authentication/dm_auth_manager.cpp", + "${services_path}/src/config/mini/dm_config_manager.cpp", + "${services_path}/src/config/mini/pin_auth.cpp", + "${services_path}/src/dependency/commonevent/dm_common_event_manager.cpp", + "${services_path}/src/dependency/hichain/hichain_connector.cpp", + "${services_path}/src/dependency/multipleuser/multiple_user_connector.cpp", + "${services_path}/src/dependency/softbus/softbus_connector.cpp", + "${services_path}/src/dependency/softbus/softbus_session.cpp", + "${services_path}/src/dependency/timer/mini/dm_timer.cpp", + "${services_path}/src/device_manager_service.cpp", + "${services_path}/src/deviceinfo/dm_device_info_manager.cpp", + "${services_path}/src/devicestate/dm_device_state_manager.cpp", + "${services_path}/src/discovery/dm_discovery_manager.cpp", + "${services_path}/src/dispatch/command_dispatch.cpp", + "${services_path}/src/dispatch/server_stub.cpp", + "${services_path}/src/dispatch/device_manager_service_listener_mini.cpp", + ] + + defines = [ + "LITE_DEVICE", + "HI_LOG_ENABLE", + "DH_LOG_TAG=\"devicemanagerservice\"", + "LOG_DOMAIN=0xD004100", + ] + + ldflags = dm_ldflags + + deps = [ + "${innerkits_path_mini}/native_cpp:devicemanagersdk_mini", + "${utils_path}:devicemanagerutils_mini", + "//base/hiviewdfx/hilog_lite/frameworks/featured:hilog_static", + "//base/security/deviceauth/services:deviceauth", + "//base/startup/syspara_lite/frameworks/parameter/src:sysparam", + "//foundation/communication/dsoftbus/sdk:softbus_client", + "//foundation/distributedschedule/samgr_lite/samgr", + "//third_party/bounds_checking_function:libsec_static", + "//third_party/mbedtls", + "//utils/native/lite:utils", + ] + } + } else { + executable("devicemanagerservice") { + sources = [ "src/ipc/lite/ipc_server_main.cpp" ] + } } } else if (!support_jsapi) { group("devicemanagerservice") { diff --git a/utils/BUILD.gn b/utils/BUILD.gn index f1c17e3ee..c7a8ee64f 100644 --- a/utils/BUILD.gn +++ b/utils/BUILD.gn @@ -20,7 +20,52 @@ if (defined(ohos_lite)) { import("//foundation/distributedhardware/devicemanager/devicemanager.gni") if (defined(ohos_lite)) { - shared_library("devicemanagerutils") { + if (ohos_kernel_type == "liteos_m") { + static_library("devicemanagerutils_mini") { + include_dirs = [ + "${utils_path}/include", + "${utils_path}/include/permission/lite", + "${common_path}/include", + ] + + include_dirs += [ + "//base/security/deviceauth/interfaces/innerkits", + "//base/startup/syspara_lite/interfaces/innerkits/native/syspara/include", + "//utils/native/lite/include", + "//utils/system/safwk/native/include", + "//third_party/json/include", + "//base/hiviewdfx/hilog_lite/interfaces/native/innerkits", + "//third_party/bounds_checking_function/include", + "//foundation/distributedschedule/samgr_lite/interfaces/kits/samgr", + ] + + sources = [ + "${utils_path}/src/dm_anonymous.cpp", + "${utils_path}/src/dm_log.cpp", + "${utils_path}/src/dm_random.cpp", + "${utils_path}/src/permission/lite/permission_manager.cpp", + ] + + defines = [ + "HI_LOG_ENABLE", + "DH_LOG_TAG=\"devicemanagerutils\"", + "LOG_DOMAIN=0xD004100", + ] + + deps = [ + "//base/hiviewdfx/hilog_lite/frameworks/featured:hilog_static", + "//base/startup/syspara_lite/frameworks/parameter/src:sysparam", + "//foundation/distributedschedule/samgr_lite/samgr", + "//third_party/bounds_checking_function:libsec_static", + "//third_party/mbedtls", + "//utils/native/lite:utils", + "//third_party/mbedtls:mbedtls_shared", + ] + } + } + else { + shared_library("devicemanagerutils") { + } } } else { config("devicemanagerutils_config") { -- Gitee From 0c38f35d3abca252306d3b94e1aaaef0488e94fc Mon Sep 17 00:00:00 2001 From: dangzehui Date: Thu, 10 Mar 2022 14:26:31 +0800 Subject: [PATCH 07/19] =?UTF-8?q?L0=E5=A4=9A=E7=94=A8=E6=88=B7=E4=BF=AE?= =?UTF-8?q?=E6=94=B9?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- services/devicemanagerservice/BUILD.gn | 3 +- .../commonevent/dm_common_event_manager.h | 78 +++--- .../commonevent/dm_common_event_manager.cpp | 222 +++++++++--------- .../dependency/hichain/hichain_connector.cpp | 2 +- .../mini/multiple_user_connector.cpp | 37 +++ .../multipleuser/multiple_user_connector.cpp | 16 +- .../src/device_manager_service.cpp | 36 +-- 7 files changed, 217 insertions(+), 177 deletions(-) create mode 100644 services/devicemanagerservice/src/dependency/multipleuser/mini/multiple_user_connector.cpp diff --git a/services/devicemanagerservice/BUILD.gn b/services/devicemanagerservice/BUILD.gn index 3bf249efe..febb8e3a5 100755 --- a/services/devicemanagerservice/BUILD.gn +++ b/services/devicemanagerservice/BUILD.gn @@ -81,9 +81,8 @@ if (defined(ohos_lite)) { "${services_path}/src/authentication/dm_auth_manager.cpp", "${services_path}/src/config/mini/dm_config_manager.cpp", "${services_path}/src/config/mini/pin_auth.cpp", - "${services_path}/src/dependency/commonevent/dm_common_event_manager.cpp", "${services_path}/src/dependency/hichain/hichain_connector.cpp", - "${services_path}/src/dependency/multipleuser/multiple_user_connector.cpp", + "${services_path}/src/dependency/multipleuser/mini/multiple_user_connector.cpp", "${services_path}/src/dependency/softbus/softbus_connector.cpp", "${services_path}/src/dependency/softbus/softbus_session.cpp", "${services_path}/src/dependency/timer/mini/dm_timer.cpp", diff --git a/services/devicemanagerservice/include/dependency/commonevent/dm_common_event_manager.h b/services/devicemanagerservice/include/dependency/commonevent/dm_common_event_manager.h index 850e861d3..81d51bb2a 100644 --- a/services/devicemanagerservice/include/dependency/commonevent/dm_common_event_manager.h +++ b/services/devicemanagerservice/include/dependency/commonevent/dm_common_event_manager.h @@ -18,53 +18,53 @@ #include #include -// #include +#include -// #include "common_event.h" -// #include "common_event_data.h" -// #include "common_event_manager.h" -// #include "common_event_subscribe_info.h" -// #include "common_event_subscriber.h" +#include "common_event.h" +#include "common_event_data.h" +#include "common_event_manager.h" +#include "common_event_subscribe_info.h" +#include "common_event_subscriber.h" #include "dm_log.h" -// #include "matching_skills.h" +#include "matching_skills.h" #include "single_instance.h" namespace OHOS { namespace DistributedHardware { -// using CommomEventCallback = std::function; +using CommomEventCallback = std::function; -// struct CommomEventCallbackNode { -// int32_t input_; -// CommomEventCallback callback_; -// }; +struct CommomEventCallbackNode { + int32_t input_; + CommomEventCallback callback_; +}; -// class DmCommonEventManager { -// DECLARE_SINGLE_INSTANCE_BASE(DmCommonEventManager); -// public: -// bool SubscribeServiceEvent(const std::string &event, const CommomEventCallback callback); -// bool UnsubscribeServiceEvent(const std::string &event); - // class EventSubscriber : public EventFwk::CommonEventSubscriber { - // public: - // EventSubscriber(const EventFwk::CommonEventSubscribeInfo &subscribeInfo, const CommomEventCallback &callback, - // const std::string &event) : EventFwk::CommonEventSubscriber(subscribeInfo), - // callback_(callback), event_(event) {} - // void OnReceiveEvent(const EventFwk::CommonEventData &data); - // private: - // CommomEventCallback callback_; - // std::string event_; - // }; -// private: -// DmCommonEventManager(); -// ~DmCommonEventManager(); -// private: -// static void DealCallback(void); -// private: - // static std::mutex callbackQueueMutex_; - // static std::mutex eventSubscriberMutex_; - // static std::condition_variable notEmpty_; - // static std::list callbackQueue_; - // std::map> dmEventSubscriber_; -// }; +class DmCommonEventManager { +DECLARE_SINGLE_INSTANCE_BASE(DmCommonEventManager); +public: + bool SubscribeServiceEvent(const std::string &event, const CommomEventCallback callback); + bool UnsubscribeServiceEvent(const std::string &event); + class EventSubscriber : public EventFwk::CommonEventSubscriber { + public: + EventSubscriber(const EventFwk::CommonEventSubscribeInfo &subscribeInfo, const CommomEventCallback &callback, + const std::string &event) : EventFwk::CommonEventSubscriber(subscribeInfo), + callback_(callback), event_(event) {} + void OnReceiveEvent(const EventFwk::CommonEventData &data); + private: + CommomEventCallback callback_; + std::string event_; + }; +private: + DmCommonEventManager(); + ~DmCommonEventManager(); +private: + static void DealCallback(void); +private: + static std::mutex callbackQueueMutex_; + static std::mutex eventSubscriberMutex_; + static std::condition_variable notEmpty_; + static std::list callbackQueue_; + std::map> dmEventSubscriber_; +}; } // namespace DistributedHardware } // namespace OHOS #endif // OHOS_EVENT_MANAGER_ADAPT_H \ No newline at end of file diff --git a/services/devicemanagerservice/src/dependency/commonevent/dm_common_event_manager.cpp b/services/devicemanagerservice/src/dependency/commonevent/dm_common_event_manager.cpp index c25038d00..798174abe 100644 --- a/services/devicemanagerservice/src/dependency/commonevent/dm_common_event_manager.cpp +++ b/services/devicemanagerservice/src/dependency/commonevent/dm_common_event_manager.cpp @@ -15,124 +15,124 @@ #include "dm_common_event_manager.h" -// #include +#include #include "dm_constants.h" -// using namespace OHOS::EventFwk; +using namespace OHOS::EventFwk; namespace OHOS { namespace DistributedHardware { -// std::mutex DmCommonEventManager::callbackQueueMutex_; -// std::mutex DmCommonEventManager::eventSubscriberMutex_; -// std::condition_variable DmCommonEventManager::notEmpty_; -// std::list DmCommonEventManager::callbackQueue_; - -// DmCommonEventManager &DmCommonEventManager::GetInstance() -// { -// static DmCommonEventManager instance; -// return instance; -// } - -// DmCommonEventManager::DmCommonEventManager() -// { -// std::thread th(DealCallback); -// th.detach(); -// } - -// DmCommonEventManager::~DmCommonEventManager() -// { -// std::unique_lock mutexLock(eventSubscriberMutex_); -// for (auto iter = dmEventSubscriber_.begin(); iter != dmEventSubscriber_.end(); iter++) { -// if (!CommonEventManager::UnSubscribeCommonEvent(iter->second)) { -// LOGI("Unsubscribe service event failed: %s", iter->first.c_str()); -// } -// } -// } - -// void DmCommonEventManager::DealCallback(void) -// { -// while (1) { -// std::unique_lock callbackQueueMutexLock(callbackQueueMutex_); -// notEmpty_.wait(callbackQueueMutexLock, [] { return !callbackQueue_.empty(); }); -// CommomEventCallbackNode node = callbackQueue_.front(); -// int32_t input = node.input_; -// CommomEventCallback funcPrt = node.callback_; -// funcPrt(input); -// callbackQueue_.pop_front(); -// } -// } - -// bool DmCommonEventManager::SubscribeServiceEvent(const std::string &event, const CommomEventCallback callback) -// { -// LOGI("Subscribe event: %s", event.c_str()); -// if (dmEventSubscriber_.find(event) != dmEventSubscriber_.end() || callback == nullptr) { -// LOGE("Subscribe event:%s has been exist or callback is nullptr", event.c_str()); -// return false; -// } - -// MatchingSkills matchingSkills; -// matchingSkills.AddEvent(event); -// CommonEventSubscribeInfo subscriberInfo(matchingSkills); -// std::shared_ptr subscriber = -// std::make_shared(subscriberInfo, callback, event); -// if (subscriber == nullptr) { -// LOGE("subscriber is nullptr %s", event.c_str()); -// return false; -// } +std::mutex DmCommonEventManager::callbackQueueMutex_; +std::mutex DmCommonEventManager::eventSubscriberMutex_; +std::condition_variable DmCommonEventManager::notEmpty_; +std::list DmCommonEventManager::callbackQueue_; + +DmCommonEventManager &DmCommonEventManager::GetInstance() +{ + static DmCommonEventManager instance; + return instance; +} + +DmCommonEventManager::DmCommonEventManager() +{ + std::thread th(DealCallback); + th.detach(); +} + +DmCommonEventManager::~DmCommonEventManager() +{ + std::unique_lock mutexLock(eventSubscriberMutex_); + for (auto iter = dmEventSubscriber_.begin(); iter != dmEventSubscriber_.end(); iter++) { + if (!CommonEventManager::UnSubscribeCommonEvent(iter->second)) { + LOGI("Unsubscribe service event failed: %s", iter->first.c_str()); + } + } +} + +void DmCommonEventManager::DealCallback(void) +{ + while (1) { + std::unique_lock callbackQueueMutexLock(callbackQueueMutex_); + notEmpty_.wait(callbackQueueMutexLock, [] { return !callbackQueue_.empty(); }); + CommomEventCallbackNode node = callbackQueue_.front(); + int32_t input = node.input_; + CommomEventCallback funcPrt = node.callback_; + funcPrt(input); + callbackQueue_.pop_front(); + } +} + +bool DmCommonEventManager::SubscribeServiceEvent(const std::string &event, const CommomEventCallback callback) +{ + LOGI("Subscribe event: %s", event.c_str()); + if (dmEventSubscriber_.find(event) != dmEventSubscriber_.end() || callback == nullptr) { + LOGE("Subscribe event:%s has been exist or callback is nullptr", event.c_str()); + return false; + } + + MatchingSkills matchingSkills; + matchingSkills.AddEvent(event); + CommonEventSubscribeInfo subscriberInfo(matchingSkills); + std::shared_ptr subscriber = + std::make_shared(subscriberInfo, callback, event); + if (subscriber == nullptr) { + LOGE("subscriber is nullptr %s", event.c_str()); + return false; + } -// if (!CommonEventManager::SubscribeCommonEvent(subscriber)) { -// LOGE("Subscribe service event failed: %s", event.c_str()); -// return false; -// } - -// std::unique_lock mutexLock(eventSubscriberMutex_); -// dmEventSubscriber_[event] = subscriber; -// return true; -// } - -// bool DmCommonEventManager::UnsubscribeServiceEvent(const std::string &event) -// { -// LOGI("UnSubscribe event: %s", event.c_str()); -// if (dmEventSubscriber_.find(event) == dmEventSubscriber_.end()) { -// LOGE("UnSubscribe event: %s not been exist", event.c_str()); -// return false; -// } - -// if (!CommonEventManager::UnSubscribeCommonEvent(dmEventSubscriber_[event])) { -// LOGE("Unsubscribe service event failed: %s", event.c_str()); -// return false; -// } - -// std::unique_lock mutexLock(eventSubscriberMutex_); -// dmEventSubscriber_.erase(event); -// return true; -// } - -// void DmCommonEventManager::EventSubscriber::OnReceiveEvent(const CommonEventData &data) -// { -// std::string receiveEvent = data.GetWant().GetAction(); -// LOGI("Received event: %s", receiveEvent.c_str()); -// if (receiveEvent != event_) { -// LOGE("Received event is error"); -// return; -// } - -// int32_t userId = data.GetCode(); -// if (userId <= 0) { -// LOGE("userId is less zero"); -// return; -// } + if (!CommonEventManager::SubscribeCommonEvent(subscriber)) { + LOGE("Subscribe service event failed: %s", event.c_str()); + return false; + } + + std::unique_lock mutexLock(eventSubscriberMutex_); + dmEventSubscriber_[event] = subscriber; + return true; +} + +bool DmCommonEventManager::UnsubscribeServiceEvent(const std::string &event) +{ + LOGI("UnSubscribe event: %s", event.c_str()); + if (dmEventSubscriber_.find(event) == dmEventSubscriber_.end()) { + LOGE("UnSubscribe event: %s not been exist", event.c_str()); + return false; + } + + if (!CommonEventManager::UnSubscribeCommonEvent(dmEventSubscriber_[event])) { + LOGE("Unsubscribe service event failed: %s", event.c_str()); + return false; + } + + std::unique_lock mutexLock(eventSubscriberMutex_); + dmEventSubscriber_.erase(event); + return true; +} + +void DmCommonEventManager::EventSubscriber::OnReceiveEvent(const CommonEventData &data) +{ + std::string receiveEvent = data.GetWant().GetAction(); + LOGI("Received event: %s", receiveEvent.c_str()); + if (receiveEvent != event_) { + LOGE("Received event is error"); + return; + } + + int32_t userId = data.GetCode(); + if (userId <= 0) { + LOGE("userId is less zero"); + return; + } -// std::unique_lock callbackQueueMutexLock(callbackQueueMutex_); -// if (callbackQueue_.size() > COMMON_CALLBACK_MAX_SIZE) { -// LOGE("event callback Queue is too long"); -// return; -// } - -// CommomEventCallbackNode node {userId, callback_}; -// callbackQueue_.push_back(node); -// notEmpty_.notify_one(); -// } + std::unique_lock callbackQueueMutexLock(callbackQueueMutex_); + if (callbackQueue_.size() > COMMON_CALLBACK_MAX_SIZE) { + LOGE("event callback Queue is too long"); + return; + } + + CommomEventCallbackNode node {userId, callback_}; + callbackQueue_.push_back(node); + notEmpty_.notify_one(); +} } // namespace DistributedHardware } // namespace OHOS \ No newline at end of file diff --git a/services/devicemanagerservice/src/dependency/hichain/hichain_connector.cpp b/services/devicemanagerservice/src/dependency/hichain/hichain_connector.cpp index 5c739f292..6fa2e8420 100644 --- a/services/devicemanagerservice/src/dependency/hichain/hichain_connector.cpp +++ b/services/devicemanagerservice/src/dependency/hichain/hichain_connector.cpp @@ -60,7 +60,7 @@ std::shared_ptr HiChainConnector::hiChainConnectorCal HiChainConnector::HiChainConnector() { LOGI("HiChainConnector::constructor"); - deviceAuthCallback_ = DeviceAuthCallback {.onTransmit = nullptr, + deviceAuthCallback_ = {.onTransmit = nullptr, .onFinish = HiChainConnector::onFinish, .onError = HiChainConnector::onError, .onRequest = HiChainConnector::onRequest}; diff --git a/services/devicemanagerservice/src/dependency/multipleuser/mini/multiple_user_connector.cpp b/services/devicemanagerservice/src/dependency/multipleuser/mini/multiple_user_connector.cpp new file mode 100644 index 000000000..ebb38c73e --- /dev/null +++ b/services/devicemanagerservice/src/dependency/multipleuser/mini/multiple_user_connector.cpp @@ -0,0 +1,37 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "multiple_user_connector.h" + +namespace OHOS { +namespace DistributedHardware { +int32_t MultipleUserConnector::oldUserId_ = -1; + +int32_t MultipleUserConnector::GetCurrentAccountUserID(void) +{ + return 0; +} + +void MultipleUserConnector::SetSwitchOldUserId(int32_t userId) +{ + oldUserId_ = userId; +} + +int32_t MultipleUserConnector::GetSwitchOldUserId(void) +{ + return oldUserId_; +} +} // namespace DistributedHardware +} // namespace OHOS diff --git a/services/devicemanagerservice/src/dependency/multipleuser/multiple_user_connector.cpp b/services/devicemanagerservice/src/dependency/multipleuser/multiple_user_connector.cpp index 934374ffc..11ed7fb2e 100644 --- a/services/devicemanagerservice/src/dependency/multipleuser/multiple_user_connector.cpp +++ b/services/devicemanagerservice/src/dependency/multipleuser/multiple_user_connector.cpp @@ -17,9 +17,9 @@ #include "dm_constants.h" #include "dm_log.h" -// #include "os_account_manager.h" +#include "os_account_manager.h" -// using namespace OHOS::AccountSA; +using namespace OHOS::AccountSA; namespace OHOS { namespace DistributedHardware { @@ -27,12 +27,12 @@ int32_t MultipleUserConnector::oldUserId_ = -1; int32_t MultipleUserConnector::GetCurrentAccountUserID(void) { - // std::vector ids; - // ErrCode ret = OsAccountManager::QueryActiveOsAccountIds(ids); - // if (ret != ERR_OK || ids.empty()) { - // return -1; - // } - // return ids[0]; + std::vector ids; + ErrCode ret = OsAccountManager::QueryActiveOsAccountIds(ids); + if (ret != ERR_OK || ids.empty()) { + return -1; + } + return ids[0]; return 0; } diff --git a/services/devicemanagerservice/src/device_manager_service.cpp b/services/devicemanagerservice/src/device_manager_service.cpp index bbb1c9ace..ae5891e38 100644 --- a/services/devicemanagerservice/src/device_manager_service.cpp +++ b/services/devicemanagerservice/src/device_manager_service.cpp @@ -17,16 +17,18 @@ #include -// #include "common_event_support.h" + #include "device_manager_service_listener.h" -#include "dm_common_event_manager.h" #include "dm_constants.h" #include "dm_device_info_manager.h" #include "dm_log.h" #include "multiple_user_connector.h" #include "permission_manager.h" - -// using namespace OHOS::EventFwk; +#if (defined(__LINUX__) || defined(__LITEOS_A__)) +#include "dm_common_event_manager.h" +#include "common_event_support.h" +using namespace OHOS::EventFwk; +#endif namespace OHOS { namespace DistributedHardware { @@ -35,10 +37,12 @@ IMPLEMENT_SINGLE_INSTANCE(DeviceManagerService); DeviceManagerService::~DeviceManagerService() { LOGI("DeviceManagerService destructor"); - // DmCommonEventManager &dmCommonEventManager = DmCommonEventManager::GetInstance(); - // if (dmCommonEventManager.UnsubscribeServiceEvent(CommonEventSupport::COMMON_EVENT_USER_STOPPED)) { - // LOGI("subscribe service event success"); - // } +#if (defined(__LINUX__) || defined(__LITEOS_A__)) + DmCommonEventManager &dmCommonEventManager = DmCommonEventManager::GetInstance(); + if (dmCommonEventManager.UnsubscribeServiceEvent(CommonEventSupport::COMMON_EVENT_USER_STOPPED)) { + LOGI("subscribe service event success"); + } +#endif softbusConnector_->GetSoftbusSession()->UnRegisterSessionCallback(); hiChainConnector_->UnRegisterHiChainCallback(); } @@ -113,14 +117,14 @@ int32_t DeviceManagerService::Init() LOGI("get current account user id success"); MultipleUserConnector::SetSwitchOldUserId(userId); } - - // DmCommonEventManager &dmCommonEventManager = DmCommonEventManager::GetInstance(); - // CommomEventCallback callback = std::bind(&DmAuthManager::UserSwitchEventCallback, *authMgr_.get(), - // std::placeholders::_1); - // if (dmCommonEventManager.SubscribeServiceEvent(CommonEventSupport::COMMON_EVENT_USER_SWITCHED, callback)) { - // LOGI("subscribe service user switch common event success"); - // } - +#if (defined(__LINUX__) || defined(__LITEOS_A__)) + DmCommonEventManager &dmCommonEventManager = DmCommonEventManager::GetInstance(); + CommomEventCallback callback = std::bind(&DmAuthManager::UserSwitchEventCallback, *authMgr_.get(), + std::placeholders::_1); + if (dmCommonEventManager.SubscribeServiceEvent(CommonEventSupport::COMMON_EVENT_USER_SWITCHED, callback)) { + LOGI("subscribe service user switch common event success"); + } +#endif LOGI("Init success, singleton initialized"); intFlag_ = true; return DM_OK; -- Gitee From fcb0ed7bcbae93c1a86a7e56650abcae25ec50b4 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E8=94=A1=E9=98=94?= Date: Mon, 14 Mar 2022 06:51:54 +0000 Subject: [PATCH 08/19] =?UTF-8?q?!32=20=E5=A2=9E=E5=8A=A0=E5=88=9D?= =?UTF-8?q?=E5=A7=8B=E5=8C=96=E5=87=BD=E6=95=B0=E5=92=8C=E4=BF=AE=E6=94=B9?= =?UTF-8?q?=E7=BC=96=E7=A8=8B=E8=A7=84=E8=8C=83=E9=97=AE=E9=A2=98=20*=20?= =?UTF-8?q?=E5=88=A0=E9=99=A4=E5=86=97=E4=BD=99=E4=BB=A3=E7=A0=81=20*=20?= =?UTF-8?q?=E5=A2=9E=E5=8A=A0=E5=88=9D=E5=A7=8B=E5=8C=96=E6=93=8D=E4=BD=9C?= =?UTF-8?q?=E5=92=8C=E4=BF=AE=E6=94=B9=E7=BC=96=E7=A8=8B=E8=A7=84=E8=8C=83?= =?UTF-8?q?=E9=97=AE=E9=A2=98?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../native_cpp/src/device_manager_impl.cpp | 1 - .../include/dispatch/command_dispatch.h | 3 +- .../include/dispatch/message_processing.h | 48 ---- .../include/dispatch/server_init.h | 22 -- .../src/dispatch/command_dispatch.cpp | 8 +- .../src/dispatch/message_processing.cpp | 244 ------------------ .../src/dispatch/server_init.cpp | 46 ---- .../src/dispatch/server_stub.cpp | 16 +- 8 files changed, 7 insertions(+), 381 deletions(-) delete mode 100644 services/devicemanagerservice/include/dispatch/message_processing.h delete mode 100644 services/devicemanagerservice/include/dispatch/server_init.h delete mode 100644 services/devicemanagerservice/src/dispatch/message_processing.cpp delete mode 100644 services/devicemanagerservice/src/dispatch/server_init.cpp diff --git a/interfaces_mini/inner_kits/native_cpp/src/device_manager_impl.cpp b/interfaces_mini/inner_kits/native_cpp/src/device_manager_impl.cpp index 0c59d44e3..5ed9361c1 100644 --- a/interfaces_mini/inner_kits/native_cpp/src/device_manager_impl.cpp +++ b/interfaces_mini/inner_kits/native_cpp/src/device_manager_impl.cpp @@ -14,7 +14,6 @@ */ #include "command_dispatch.h" #include "device_manager_impl.h" -#include "message_processing.h" #include "dm_log.h" #include "device_manager_notify.h" #include "dm_constants.h" diff --git a/services/devicemanagerservice/include/dispatch/command_dispatch.h b/services/devicemanagerservice/include/dispatch/command_dispatch.h index efe52f3b9..f4683e737 100644 --- a/services/devicemanagerservice/include/dispatch/command_dispatch.h +++ b/services/devicemanagerservice/include/dispatch/command_dispatch.h @@ -19,8 +19,7 @@ #include #include #include -#include "single_instance.h" -#include "message_processing.h" +#include "single_instance.h" #include "message_req.h" #include "message_rsp.h" diff --git a/services/devicemanagerservice/include/dispatch/message_processing.h b/services/devicemanagerservice/include/dispatch/message_processing.h deleted file mode 100644 index 03e3d6af1..000000000 --- a/services/devicemanagerservice/include/dispatch/message_processing.h +++ /dev/null @@ -1,48 +0,0 @@ -/* - * Copyright (c) 2021 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef OHOS_DEVICE_MANAGER_MESSAGE_PROCESSING_H -#define OHOS_DEVICE_MANAGER_MESSAGE_PROCESSING_H - -#include - -#include "dm_app_image_info.h" -#include "dm_device_info.h" -#include "dm_subscribe_info.h" -#include "nlohmann/json.hpp" -#include "get_authenticationparam_rsp.h" -#include "get_trustdevice_rsp.h" -#include "single_instance.h" - -namespace OHOS { -namespace DistributedHardware { -class MessageProcessing { -DECLARE_SINGLE_INSTANCE(MessageProcessing); -public: - int32_t ModuleInit(); - int32_t GetTrustedDeviceList(std::string &pkgName, std::string &extra, DmDeviceInfo **info, int32_t *infoNum, std::shared_ptr prsp); - int32_t StartDeviceDiscovery(std::string &pkgName, const DmSubscribeInfo &dmSubscribeInfo); - int32_t StopDiscovery(std::string &pkgName, uint16_t subscribeId); - int32_t AuthenticateDevice(std::string &pkgName, const DmDeviceInfo &deviceInfo, - const DmAppImageInfo &imageInfo, std::string &extra); - int32_t CheckAuthentication(std::string &authPara); - int32_t SetUserOperation(std::string &pkgName, int32_t action); - static int32_t GenRandInt(int32_t minPinToken, int32_t maxPinToken); -private: - int32_t CheckParamValid(nlohmann::json &extraJson, const DmAppImageInfo &imageInfo); -}; -} // namespace DistributedHardware -} // namespace OHOS -#endif // OHOS_DEVICE_MANAGER_MESSAGE_PROCESSING_H diff --git a/services/devicemanagerservice/include/dispatch/server_init.h b/services/devicemanagerservice/include/dispatch/server_init.h deleted file mode 100644 index 9d0ac1e24..000000000 --- a/services/devicemanagerservice/include/dispatch/server_init.h +++ /dev/null @@ -1,22 +0,0 @@ -/* - * Copyright (c) 2021 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef OHOS_DEVICE_MANAGER_SERVER_INIT_H -#define OHOS_DEVICE_MANAGER_SERVER_INIT_H - - -void Server_Init(); - -#endif // OHOS_DEVICE_MANAGER_SERVER_INIT_H diff --git a/services/devicemanagerservice/src/dispatch/command_dispatch.cpp b/services/devicemanagerservice/src/dispatch/command_dispatch.cpp index 47a0a0815..3fa229dcd 100644 --- a/services/devicemanagerservice/src/dispatch/command_dispatch.cpp +++ b/services/devicemanagerservice/src/dispatch/command_dispatch.cpp @@ -12,7 +12,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -#include "message_processing.h" + #include "command_dispatch.h" #include "dm_log.h" #include "message_def.h" @@ -74,7 +74,7 @@ int32_t CommandDispatch::CmdProcessing(int32_t cmdCode, std::shared_ptr pRsp = std::static_pointer_cast(rsp); DmDeviceInfo dmDeviceInfo = {0}; - int32_t ret = DeviceManagerService::GetInstance().GetLocalDeviceInfo(dmDeviceInfo); + ret = DeviceManagerService::GetInstance().GetLocalDeviceInfo(dmDeviceInfo); DmDeviceInfo *Info = &dmDeviceInfo; if (Info != nullptr) { pRsp->SetLocalDeviceInfo(dmDeviceInfo); @@ -101,7 +101,7 @@ int32_t CommandDispatch::CmdProcessing(int32_t cmdCode, std::shared_ptrGetNetWorkId(); std::string uuid; - int32_t ret = DeviceManagerService::GetInstance().GetUuidByNetworkId(pkgName, netWorkId, uuid); + ret = DeviceManagerService::GetInstance().GetUuidByNetworkId(pkgName, netWorkId, uuid); pRsp->SetUuid(uuid); pRsp->SetErrCode(ret); break; @@ -113,7 +113,7 @@ int32_t CommandDispatch::CmdProcessing(int32_t cmdCode, std::shared_ptrGetSubscribeInfo(); LOGI("StartDeviceDiscovery service"); - int32_t ret = DeviceManagerService::GetInstance().StartDeviceDiscovery(pkgName, dmSubscribeInfo, extra); + ret = DeviceManagerService::GetInstance().StartDeviceDiscovery(pkgName, dmSubscribeInfo, extra); rsp->SetErrCode(ret); break; } diff --git a/services/devicemanagerservice/src/dispatch/message_processing.cpp b/services/devicemanagerservice/src/dispatch/message_processing.cpp deleted file mode 100644 index f6652b912..000000000 --- a/services/devicemanagerservice/src/dispatch/message_processing.cpp +++ /dev/null @@ -1,244 +0,0 @@ -/* - * Copyright (c) 2021 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -#include - -#include "securec.h" -#include "softbus_bus_center.h" -// #include "softbus_adapter.h" -// #include "anonymous_string.h" -#include "dm_anonymous.h" -// #include "auth_manager.h" -#include "dm_constants.h" -// #include "device_manager_errno.h" -// #include "device_manager_log.h" -#include "dm_log.h" -#include "dm_ability_manager.h" -// #include "encrypt_utils.h" -#include "message_processing.h" -#include "get_trustdevice_rsp.h" -#include "get_authenticationparam_rsp.h" - - - -namespace OHOS { -namespace DistributedHardware { - -IMPLEMENT_SINGLE_INSTANCE(MessageProcessing); - -int32_t MessageProcessing::CheckParamValid(nlohmann::json &extraJson, const DmAppImageInfo &imageInfo) -{ - if (!extraJson.contains(APP_NAME_KEY) || - !extraJson.contains(APP_DESCRIPTION_KEY) || - !extraJson.contains(AUTH_TYPE)) { - DMLOG(DM_LOG_ERROR, "Invalid para"); - return DM_INVALID_VALUE; - } - - std::string appName = extraJson[APP_NAME_KEY]; - std::string appDescription = extraJson[APP_DESCRIPTION_KEY]; - - if (appName.empty() || appDescription.empty()) { - DMLOG(DM_LOG_ERROR, "Invalid app image info"); - return DM_INVALID_VALUE; - } - if (extraJson[AUTH_TYPE] != AUTH_TYPE_PIN) { - DMLOG(DM_LOG_ERROR, "invalid auth type, only support pin auth"); - return DM_INVALID_VALUE; - } - return DM_OK; -} - -int32_t MessageProcessing::GenRandInt(int32_t randMin, int32_t randMax) -{ - std::random_device randDevice; - std::mt19937 genRand(randDevice()); - std::uniform_int_distribution disRand(randMin, randMax); - return disRand(genRand); -} - -int32_t MessageProcessing::GetTrustedDeviceList(std::string &pkgName, std::string &extra, - DmDeviceInfo **info, int32_t *infoNum, std::shared_ptr prsp) -{ - if (info == nullptr || infoNum == nullptr) { - return DM_INVALID_VALUE; - } - DMLOG(DM_LOG_INFO, "In, pkgName: %s", pkgName.c_str()); - - std::vector deviceInfoVec; - - NodeBasicInfo *nodeInfo = nullptr; - *info = nullptr; - *infoNum = 0; - - int32_t ret = SoftbusAdapter::GetTrustDevices(pkgName, &nodeInfo, infoNum); - if (ret != DM_OK || *infoNum <= 0 || nodeInfo == nullptr) { - DMLOG(DM_LOG_ERROR, "GetTrustDevices errCode:%d, num:%d", ret, *infoNum); - return ret; - } - - *info = (DmDeviceInfo *)malloc(sizeof(DmDeviceInfo) * (*infoNum)); - if (*info == nullptr) { - FreeNodeInfo(nodeInfo); - return DM_MALLOC_ERROR; - } - - for (int32_t i = 0; i < *infoNum; ++i) { - NodeBasicInfo *nodeBasicInfo = nodeInfo + i; - DmDeviceInfo *deviceInfo = *info + i; - if (memcpy_s(deviceInfo->deviceId, sizeof(deviceInfo->deviceId), nodeBasicInfo->networkId, - std::min(sizeof(deviceInfo->deviceId), sizeof(nodeBasicInfo->networkId))) != DM_OK) { - DMLOG(DM_LOG_ERROR, "memcpy failed"); - } - if (memcpy_s(deviceInfo->deviceName, sizeof(deviceInfo->deviceName), nodeBasicInfo->deviceName, - std::min(sizeof(deviceInfo->deviceName), sizeof(nodeBasicInfo->deviceName))) != DM_OK) { - DMLOG(DM_LOG_ERROR, "memcpy failed"); - } - deviceInfo->deviceTypeId = (DMDeviceType)nodeBasicInfo->deviceTypeId; - deviceInfoVec.emplace_back(*deviceInfo); - } - prsp->SetDeviceVec(deviceInfoVec); - - FreeNodeInfo(nodeInfo); - free(info); - DMLOG(DM_LOG_INFO, "success, pkgName:%s, deviceCount %d", pkgName.c_str(), *infoNum); - return DM_OK; -} - -int32_t MessageProcessing::StartDeviceDiscovery(std::string &pkgName,const DmSubscribeInfo &dmSubscribeInfo) -{ - DMLOG(DM_LOG_INFO, "In, pkgName: %s, subscribeId %d", pkgName.c_str(), - (int32_t)dmSubscribeInfo.subscribeId); - - DMLOG(DM_LOG_INFO, "capability: %s", dmSubscribeInfo.capability); - SubscribeInfo subscribeInfo; - - subscribeInfo.subscribeId = dmSubscribeInfo.subscribeId; - subscribeInfo.mode = (DiscoverMode)dmSubscribeInfo.mode; - subscribeInfo.medium = (ExchanageMedium)dmSubscribeInfo.medium; - subscribeInfo.freq = (ExchangeFreq)dmSubscribeInfo.freq; - subscribeInfo.isSameAccount = dmSubscribeInfo.isSameAccount; - subscribeInfo.isWakeRemote = dmSubscribeInfo.isWakeRemote; - subscribeInfo.capability = dmSubscribeInfo.capability; - subscribeInfo.capabilityData = nullptr; - subscribeInfo.dataLen = 0; - return SoftbusAdapter::StartDiscovery(pkgName, &subscribeInfo); -} - -int32_t MessageProcessing::StopDiscovery(std::string &pkgName, uint16_t subscribeId) -{ - DMLOG(DM_LOG_INFO, "In, pkgName: %s, subscribeId %d", pkgName.c_str(), (int32_t)subscribeId); - return SoftbusAdapter::StopDiscovery(pkgName, subscribeId); -} - -int32_t MessageProcessing::SetUserOperation(std::string &pkgName, int32_t action) -{ - if (pkgName.empty()) { - DMLOG(DM_LOG_ERROR, "invalid para"); - return DM_INVALID_VALUE; - } - - AuthManager::GetInstance().OnUserOperate(action); - return SUCCESS; -} - -int32_t MessageProcessing::GetAuthenticationParam(std::string &pkgName, DmAuthParam &authParam, std::shared_ptr prsp) -{ - DmAuthParam authParamside = { - .packageName = "", - .appName = "", - .appDescription = "", - .authType = 0, - .business = 0, - .pincode = 0, - .direction = 0, - .pinToken = 0 - }; - - if (pkgName.empty()) { - DMLOG(DM_LOG_ERROR, "invalid para"); - return DM_INVALID_VALUE; - } - - DmAbilityManager::GetInstance().StartAbilityDone(); - AuthManager::GetInstance().GetAuthenticationParam(authParam); - - authParamside.direction = authParam.direction; - authParamside.authType = authParam.authType; - if (authParamside.direction == AUTH_SESSION_SIDE_CLIENT) { - authParamside.pinToken = authParam.pinToken; - prsp->SetAuthParam(authParamside); - - DMLOG(DM_LOG_DEBUG, "DeviceManagerStub::is Client so just return direction"); - return DM_OK; - } - - authParamside.packageName = authParam.packageName; - authParamside.appName = authParam.appName; - authParamside.appDescription = authParam.appDescription; - authParamside.business = authParam.business; - authParamside.pincode = authParam.pincode; - - int32_t appIconLen = authParam.imageinfo.GetAppIconLen(); - int32_t appThumbnailLen = authParam.imageinfo.GetAppThumbnailLen(); - uint8_t *appIconBuffer = nullptr; - uint8_t *appThumbBuffer = nullptr; - if (appIconLen > 0 && authParam.imageinfo.GetAppIcon() != nullptr) { - appIconBuffer = const_cast(authParam.imageinfo.GetAppIcon()); - } - if (appThumbnailLen > 0 && authParam.imageinfo.GetAppThumbnail() != nullptr) { - appThumbBuffer = const_cast(authParam.imageinfo.GetAppThumbnail()); - } - - authParamside.imageinfo.Reset(appIconBuffer, appIconLen, appThumbBuffer, appThumbnailLen); - prsp->SetAuthParam(authParamside); - return DM_OK; -} - -int32_t MessageProcessing::AuthenticateDevice(std::string &pkgName, const DmDeviceInfo &deviceInfo, - const DmAppImageInfo &imageInfo, std::string &extra) -{ - if (pkgName.empty() || extra.empty()) { - DMLOG(DM_LOG_ERROR, "invalid para"); - return DM_INVALID_VALUE; - } - nlohmann::json jsonObject = nlohmann::json::parse(extra, nullptr, false); - if (jsonObject.is_discarded()) { - DMLOG(DM_LOG_ERROR, "AuthenticateDevice extra jsonStr error"); - return DM_INVALID_VALUE; - } - int32_t ret = CheckParamValid(jsonObject, imageInfo); - if (ret != DM_OK) { - DMLOG(DM_LOG_ERROR, "AuthenticateDevice para invalid, ret %d", ret); - return ret; - } - DMLOG(DM_LOG_INFO, "AuthenticateDevice In, pkgName: %s, deviceId %s", pkgName.c_str(), - GetAnonyString(deviceInfo.deviceId).c_str()); - - AuthManager::GetInstance().AuthDeviceGroup(pkgName, deviceInfo, imageInfo, extra); - return DM_OK; -} - -int32_t MessageProcessing::CheckAuthentication(std::string &authPara) -{ - if (authPara.empty()) { - DMLOG(DM_LOG_INFO, " DeviceManagerIpcAdapter::CheckAuthentication check authPara failed"); - return DM_INVALID_VALUE; - } - DMLOG(DM_LOG_INFO, " DeviceManagerIpcAdapter::CheckAuthentication"); - return AuthManager::GetInstance().CheckAuthentication(authPara); -} - -} // namespace DistributedHardware -} // namespace OHOS diff --git a/services/devicemanagerservice/src/dispatch/server_init.cpp b/services/devicemanagerservice/src/dispatch/server_init.cpp deleted file mode 100644 index 62f333481..000000000 --- a/services/devicemanagerservice/src/dispatch/server_init.cpp +++ /dev/null @@ -1,46 +0,0 @@ -/* - * Copyright (c) 2021 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#include -#include - -#include "dm_log.h" -// #include "device_manager_errno.h" -#include "hichain_connector.h" -#include "server_stub.h" -#include "server_init.h" -#include "samgr_lite.h" -// #include "softbus_adapter.h" - -using namespace OHOS::DistributedHardware; - -void Server_Init() -{ - const int32_t DM_SERVICE_INIT_DELAY = 2; - - sleep(DM_SERVICE_INIT_DELAY); - SAMGR_Bootstrap(); - - if (SoftbusAdapter::Init() != DEVICEMANAGER_OK) { - DMLOG(DM_LOG_ERROR, "softbus adapter init failed"); - return; - } - if (HichainConnector::GetInstance().Init() != DEVICEMANAGER_OK) { - DMLOG(DM_LOG_ERROR, "hichain connector init failed"); - return; - } - - DMLOG(DM_LOG_INFO, "DM server Init success"); -} diff --git a/services/devicemanagerservice/src/dispatch/server_stub.cpp b/services/devicemanagerservice/src/dispatch/server_stub.cpp index 7ee28253e..6953f93ef 100644 --- a/services/devicemanagerservice/src/dispatch/server_stub.cpp +++ b/services/devicemanagerservice/src/dispatch/server_stub.cpp @@ -14,21 +14,15 @@ */ #include "server_stub.h" -#include "server_init.h" - #include "securec.h" - - #include "ohos_init.h" #include "samgr_lite.h" #include "iproxy_server.h" - #include "dm_log.h" -// #include "device_manager_errno.h" #include "dm_subscribe_info.h" #include "message_def.h" - +#include "device_manager_service.h" namespace { const int32_t WAIT_FOR_SERVER = 2; @@ -61,13 +55,7 @@ static BOOL Initialize(Service *service, Identity identity) LOGW("Initialize invalid param"); return FALSE; } - // static int8_t InitFlag = 0; - // if (InitFlag == 0) { - // Server_Init(); - // InitFlag ++; - // LOGI("DevMgrSvcInit InitFlag is : %d", InitFlag); - // } - + DeviceManagerService::GetInstance().Init(); DeviceManagerSamgrService *mgrService = (DeviceManagerSamgrService *)service; mgrService->identity = identity; -- Gitee From 3f605c94c46c20b59fbb525169b2efaff7c8ccc9 Mon Sep 17 00:00:00 2001 From: wenfei Date: Mon, 14 Mar 2022 16:42:21 +0800 Subject: [PATCH 09/19] =?UTF-8?q?fix:=E8=A7=A3=E5=86=B3=E5=90=AF=E5=8A=A8?= =?UTF-8?q?=E8=AE=BE=E5=A4=87=E5=8F=91=E7=8E=B0=EF=BC=8C=E4=B8=8D=E4=B8=8A?= =?UTF-8?q?=E6=8A=A5OnDeviceFound?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../src/dependency/softbus/softbus_connector.cpp | 9 +++++++-- .../devicemanagerservice/src/dispatch/server_stub.cpp | 5 +++++ 2 files changed, 12 insertions(+), 2 deletions(-) diff --git a/services/devicemanagerservice/src/dependency/softbus/softbus_connector.cpp b/services/devicemanagerservice/src/dependency/softbus/softbus_connector.cpp index ec4c3f369..aa597b420 100644 --- a/services/devicemanagerservice/src/dependency/softbus/softbus_connector.cpp +++ b/services/devicemanagerservice/src/dependency/softbus/softbus_connector.cpp @@ -176,6 +176,7 @@ int32_t SoftbusConnector::Init() dmPublishInfo.capabilityData = nullptr; dmPublishInfo.dataLen = 0; +#if (defined(__LINUX__) || defined(__LITEOS_A__)) char discoverStatus[DISCOVER_STATUS_LEN + 1] = {0}; ret = GetParameter(DISCOVER_STATUS_KEY.c_str(), "not exist", discoverStatus, DISCOVER_STATUS_LEN); if (strcmp(discoverStatus, "not exist") == 0) { @@ -201,8 +202,12 @@ int32_t SoftbusConnector::Init() LOGI("service unpublish result is : %d", ret); } - // ret = WatchParameter(DISCOVER_STATUS_KEY.c_str(), &SoftbusConnector::OnParameterChgCallback, nullptr); - LOGI("register Watch Parameter result is : %d"); + ret = WatchParameter(DISCOVER_STATUS_KEY.c_str(), &SoftbusConnector::OnParameterChgCallback, nullptr); + LOGI("register Watch Parameter result is : %d", ret); +#else + ret = PublishService(DM_PKG_NAME.c_str(), &dmPublishInfo, &softbusPublishCallback_); + LOGI("service publish result is : %d", ret); +#endif return ret; } diff --git a/services/devicemanagerservice/src/dispatch/server_stub.cpp b/services/devicemanagerservice/src/dispatch/server_stub.cpp index 6953f93ef..92a03cf86 100644 --- a/services/devicemanagerservice/src/dispatch/server_stub.cpp +++ b/services/devicemanagerservice/src/dispatch/server_stub.cpp @@ -55,6 +55,11 @@ static BOOL Initialize(Service *service, Identity identity) LOGW("Initialize invalid param"); return FALSE; } + + const int32_t DM_SERVICE_INIT_DELAY = 2; + sleep(DM_SERVICE_INIT_DELAY); + SAMGR_Bootstrap(); + DeviceManagerService::GetInstance().Init(); DeviceManagerSamgrService *mgrService = (DeviceManagerSamgrService *)service; -- Gitee From 56a9f7560e36dec95e88154fd9ef499a5577dd87 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E8=94=A1=E9=98=94?= Date: Mon, 14 Mar 2022 11:41:17 +0000 Subject: [PATCH 10/19] =?UTF-8?q?!33=20=E4=BF=AE=E6=94=B9=E7=BC=96?= =?UTF-8?q?=E7=A8=8B=E8=A7=84=E8=8C=83=20*=20=E4=BF=AE=E6=94=B9=E7=BC=96?= =?UTF-8?q?=E7=A8=8B=E8=A7=84=E8=8C=83?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../src/dependency/softbus/softbus_connector.cpp | 13 +++---------- .../src/dispatch/command_dispatch.cpp | 1 + 2 files changed, 4 insertions(+), 10 deletions(-) diff --git a/services/devicemanagerservice/src/dependency/softbus/softbus_connector.cpp b/services/devicemanagerservice/src/dependency/softbus/softbus_connector.cpp index aa597b420..80f911526 100644 --- a/services/devicemanagerservice/src/dependency/softbus/softbus_connector.cpp +++ b/services/devicemanagerservice/src/dependency/softbus/softbus_connector.cpp @@ -31,9 +31,7 @@ #include "nlohmann/json.hpp" #include "parameter.h" #include "system_ability_definition.h" -#if defined(__LITEOS_M__) -#include "get_trustdevice_rsp.h" -#endif + namespace OHOS { namespace DistributedHardware { @@ -240,10 +238,7 @@ int32_t SoftbusConnector::UnRegisterSoftbusStateCallback(const std::string &pkgN int32_t SoftbusConnector::GetTrustedDeviceList(std::vector &deviceInfoList) { LOGI("SoftbusConnector::GetTrustDevices start"); -#if defined(__LITEOS_M__) - std::shared_ptr prsp = std::make_shared(); - std::vector deviceInfoVec; -#endif + int32_t infoNum = 0; NodeBasicInfo *nodeInfo = nullptr; int32_t ret = GetAllNodeDeviceInfo(DM_PKG_NAME.c_str(), &nodeInfo, &infoNum); @@ -263,9 +258,7 @@ int32_t SoftbusConnector::GetTrustedDeviceList(std::vector &device CovertNodeBasicInfoToDmDevice(*nodeBasicInfo, *deviceInfo); deviceInfoList.push_back(*deviceInfo); } -#if defined(__LITEOS_M__) - prsp->SetDeviceVec(deviceInfoVec); -#endif + FreeNodeInfo(nodeInfo); free(info); LOGI("SoftbusConnector::GetTrustDevices success, deviceCount %d", infoNum); diff --git a/services/devicemanagerservice/src/dispatch/command_dispatch.cpp b/services/devicemanagerservice/src/dispatch/command_dispatch.cpp index 3fa229dcd..328ca5aa1 100644 --- a/services/devicemanagerservice/src/dispatch/command_dispatch.cpp +++ b/services/devicemanagerservice/src/dispatch/command_dispatch.cpp @@ -68,6 +68,7 @@ int32_t CommandDispatch::CmdProcessing(int32_t cmdCode, std::shared_ptr deviceList; ret = DeviceManagerService::GetInstance().GetTrustedDeviceList(pkgName, extra, deviceList); + prsp->SetDeviceVec(deviceList); prsp->SetErrCode(ret); break; } -- Gitee From 1496a738664060df907775b4cdf230b90d1ba3e6 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E8=94=A1=E9=98=94?= Date: Tue, 15 Mar 2022 14:06:15 +0000 Subject: [PATCH 11/19] =?UTF-8?q?!35=20=E4=BF=AE=E6=94=B9codecheck?= =?UTF-8?q?=E5=92=8C=E5=A2=9E=E5=8A=A0=E9=9A=8F=E6=9C=BA=E5=87=BD=E6=95=B0?= =?UTF-8?q?=20*=20=E4=BF=AE=E6=94=B9codecheck=E4=B8=ADmutex=E9=97=AE?= =?UTF-8?q?=E9=A2=98=20*=20=E4=BF=AE=E6=94=B9codecheck=E4=B8=ADmutex?= =?UTF-8?q?=E9=97=AE=E9=A2=98=20*=20=E4=BF=AE=E6=94=B9interfaces=5Fmini=20?= =?UTF-8?q?codecheck=E5=92=8C=E5=A2=9E=E5=8A=A0=E9=9A=8F=E6=9C=BA=E5=87=BD?= =?UTF-8?q?=E6=95=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../native_cpp/include/device_manager.h | 1 - .../native_cpp/include/device_manager_impl.h | 7 ++--- .../native_cpp/include/dm_app_image_info.h | 6 ++-- .../include/notify/device_manager_notify.h | 4 +-- .../native_cpp/src/device_manager_impl.cpp | 29 +++++++++---------- .../src/notify/device_manager_notify.cpp | 29 +++++-------------- utils/src/dm_random.cpp | 4 +++ 7 files changed, 32 insertions(+), 48 deletions(-) diff --git a/interfaces_mini/inner_kits/native_cpp/include/device_manager.h b/interfaces_mini/inner_kits/native_cpp/include/device_manager.h index 75d750993..5a75aac6c 100644 --- a/interfaces_mini/inner_kits/native_cpp/include/device_manager.h +++ b/interfaces_mini/inner_kits/native_cpp/include/device_manager.h @@ -22,7 +22,6 @@ #include "device_manager_callback.h" #include "dm_subscribe_info.h" -#include "dm_app_image_info.h" namespace OHOS { namespace DistributedHardware { diff --git a/interfaces_mini/inner_kits/native_cpp/include/device_manager_impl.h b/interfaces_mini/inner_kits/native_cpp/include/device_manager_impl.h index 8611ac4cf..b26dfc5fa 100644 --- a/interfaces_mini/inner_kits/native_cpp/include/device_manager_impl.h +++ b/interfaces_mini/inner_kits/native_cpp/include/device_manager_impl.h @@ -25,10 +25,8 @@ namespace OHOS { namespace DistributedHardware { class DeviceManagerImpl : public DeviceManager { -#define DEVICEMANAGER_MESSAGE_FAILED -1 -DECLARE_SINGLE_INSTANCE(DeviceManagerImpl); - - +#define DEVICEMANAGER_MESSAGE_FAILED (-1) +DECLARE_SINGLE_INSTANCE(DeviceManagerImpl); public: virtual int32_t InitDeviceManager(const std::string &pkgName, std::shared_ptr dmInitCallback) override; @@ -39,7 +37,6 @@ public: virtual int32_t RegisterDevStateCallback(const std::string &pkgName, const std::string &extra, std::shared_ptr callback) override; virtual int32_t UnRegisterDevStateCallback(const std::string &pkgName) override; - virtual int32_t StartDeviceDiscovery(const std::string &pkgName, const DmSubscribeInfo &subscribeInfo, const std::string &extra, std::shared_ptr callback) override; diff --git a/interfaces_mini/inner_kits/native_cpp/include/dm_app_image_info.h b/interfaces_mini/inner_kits/native_cpp/include/dm_app_image_info.h index 9fbccd7d6..927de61df 100644 --- a/interfaces_mini/inner_kits/native_cpp/include/dm_app_image_info.h +++ b/interfaces_mini/inner_kits/native_cpp/include/dm_app_image_info.h @@ -68,7 +68,7 @@ public: return -1; } - if (memcpy_s(appThumbnail + copyIndex, appThumbnailLen - copyIndex, srcBuffer, copyLen) != 0) { + if (memcpy_s(appThumbnail + copyIndex, appThumbnailLen - copyIndex, srcBuffer, (uint32_t)copyLen) != 0) { return -1; } @@ -144,7 +144,7 @@ private: } if (appIcon != nullptr) { appIconLen = appIconLen_; - if (memcpy_s(appIcon, appIconLen, appIcon_, appIconLen_) != 0) { + if (memcpy_s(appIcon, (uint32_t)appIconLen, appIcon_, appIconLen_) != 0) { return; } } @@ -164,7 +164,7 @@ private: } if (appThumbnail != nullptr) { appThumbnailLen = appThumbnailLen_; - if (memcpy_s(appThumbnail, appThumbnailLen, appThumbnail_, appThumbnailLen_) != 0) { + if (memcpy_s(appThumbnail, (uint32_t)appThumbnailLen, appThumbnail_, appThumbnailLen_) != 0) { return; } } diff --git a/interfaces_mini/inner_kits/native_cpp/include/notify/device_manager_notify.h b/interfaces_mini/inner_kits/native_cpp/include/notify/device_manager_notify.h index 5379a14a5..5aea5f48a 100644 --- a/interfaces_mini/inner_kits/native_cpp/include/notify/device_manager_notify.h +++ b/interfaces_mini/inner_kits/native_cpp/include/notify/device_manager_notify.h @@ -61,13 +61,13 @@ public: void OnDiscoverySuccess(const std::string &pkgName, uint16_t subscribeId); void OnAuthResult(const std::string &pkgName, const std::string &deviceId, const std::string &token, uint32_t status, uint32_t reason); - void OnVerifyAuthResult(const std::string &pkgName, const std::string &deviceId, int32_t resultCode, const std::string flag); + void OnVerifyAuthResult(const std::string &pkgName, const std::string &deviceId, + int32_t resultCode, const std::string flag); void OnFaCall(std::string &pkgName, std::string ¶mJson); void AddPkgName(const std::string &pkgName); void DeletePkgName(const std::string &pkgName); const std::list& GetPkgNameList() const; private: -// std::mutex lock_; std::map> deviceStateCallback_; std::map>> deviceDiscoveryCallbacks_; std::map>> authenticateCallback_; diff --git a/interfaces_mini/inner_kits/native_cpp/src/device_manager_impl.cpp b/interfaces_mini/inner_kits/native_cpp/src/device_manager_impl.cpp index 5ed9361c1..218c1575c 100644 --- a/interfaces_mini/inner_kits/native_cpp/src/device_manager_impl.cpp +++ b/interfaces_mini/inner_kits/native_cpp/src/device_manager_impl.cpp @@ -13,7 +13,6 @@ * limitations under the License. */ #include "command_dispatch.h" -#include "device_manager_impl.h" #include "dm_log.h" #include "device_manager_notify.h" #include "dm_constants.h" @@ -31,7 +30,7 @@ #include "get_info_by_network_req.h" #include "unauthenticate_device_req.h" #include "get_dmfaparam_rsp.h" - +#include "device_manager_impl.h" namespace OHOS { namespace DistributedHardware { @@ -80,7 +79,7 @@ int32_t DeviceManagerImpl::GetTrustedDeviceList(const std::string &pkgName, cons req->SetExtra(extra); if (CommandDispatch::GetInstance().MessageSendCmd(GET_TRUST_DEVICE_LIST, req, rsp) != DM_OK) { - return DEVICEMANAGER_MESSAGE_FAILED; + return DEVICEMANAGER_MESSAGE_FAILED; } int32_t ret = rsp->GetErrCode(); @@ -98,7 +97,7 @@ int32_t DeviceManagerImpl::GetLocalDeviceInfo(const std::string &pkgName, DmDevi { LOGI("DeviceManager::GetLocalDeviceInfo start, pkgName: %s", pkgName.c_str()); if (pkgName.empty()) { - LOGE("GetLocalDeviceInfo error: Invalid para"); + LOGE("GetLocalDeviceInfo error: Invalid para"); return DM_INVALID_VALUE; } @@ -107,7 +106,7 @@ int32_t DeviceManagerImpl::GetLocalDeviceInfo(const std::string &pkgName, DmDevi req->SetPkgName(pkgName); if (CommandDispatch::GetInstance().MessageSendCmd(GET_LOCAL_DEVICE_INFO, req, rsp) != DM_OK) { - return DEVICEMANAGER_MESSAGE_FAILED; + return DEVICEMANAGER_MESSAGE_FAILED; } if (rsp->GetErrCode() != DM_OK) { @@ -165,7 +164,7 @@ int32_t DeviceManagerImpl::StartDeviceDiscovery(const std::string &pkgName, cons req->SetSubscribeInfo(subscribeInfo); if (CommandDispatch::GetInstance().MessageSendCmd(START_DEVICE_DISCOVER, req, rsp) != DM_OK) { - return DEVICEMANAGER_MESSAGE_FAILED; + return DEVICEMANAGER_MESSAGE_FAILED; } int32_t ret = rsp->GetErrCode(); if (ret != DM_OK) { @@ -190,7 +189,7 @@ int32_t DeviceManagerImpl::StopDeviceDiscovery(const std::string &pkgName, uint1 req->SetSubscribeId(subscribeId); if (CommandDispatch::GetInstance().MessageSendCmd(STOP_DEVICE_DISCOVER, req, rsp) != DM_OK) { - return DEVICEMANAGER_MESSAGE_FAILED; + return DEVICEMANAGER_MESSAGE_FAILED; } int32_t ret = rsp->GetErrCode(); if (ret != DM_OK) { @@ -223,12 +222,12 @@ int32_t DeviceManagerImpl::AuthenticateDevice(const std::string &pkgName, int32_ req->SetDeviceInfo(deviceInfo); if (CommandDispatch::GetInstance().MessageSendCmd(AUTHENTICATE_DEVICE, req, rsp) != DM_OK) { - return DEVICEMANAGER_MESSAGE_FAILED; + return DEVICEMANAGER_MESSAGE_FAILED; } int32_t ret = rsp->GetErrCode(); if (ret != DM_OK) { - LOGE("AuthenticateDevice error: Failed with ret %d", ret); + LOGE("AuthenticateDevice error: Failed with ret %d", ret); return ret; } @@ -252,7 +251,7 @@ int32_t DeviceManagerImpl::UnAuthenticateDevice(const std::string &pkgName, cons req->SetDeviceInfo(deviceInfo); if (CommandDispatch::GetInstance().MessageSendCmd(UNAUTHENTICATE_DEVICE, req, rsp) != DM_OK) { - return DEVICEMANAGER_MESSAGE_FAILED; + return DEVICEMANAGER_MESSAGE_FAILED; } int32_t ret = rsp->GetErrCode(); @@ -308,7 +307,7 @@ int32_t DeviceManagerImpl::VerifyAuthentication(const std::string &pkgName, cons req->SetAuthPara(authPara); if (CommandDispatch::GetInstance().MessageSendCmd(VERIFY_AUTHENTICATION, req, rsp) != DM_OK) { - return DEVICEMANAGER_MESSAGE_FAILED; + return DEVICEMANAGER_MESSAGE_FAILED; } int32_t ret = rsp->GetErrCode(); @@ -334,7 +333,7 @@ int32_t DeviceManagerImpl::GetFaParam(const std::string &pkgName, DmAuthParam &d req->SetPkgName(pkgName); if (CommandDispatch::GetInstance().MessageSendCmd(SERVER_GET_DMFA_INFO, req, rsp) != DM_OK) { - return DEVICEMANAGER_MESSAGE_FAILED; + return DEVICEMANAGER_MESSAGE_FAILED; } dmFaParam = rsp->GetDmAuthParam(); @@ -358,7 +357,7 @@ int32_t DeviceManagerImpl::SetUserOperation(const std::string &pkgName, int32_t req->SetOperation(action); if (CommandDispatch::GetInstance().MessageSendCmd(SERVER_USER_AUTH_OPERATION, req, rsp) != DM_OK) { - return DEVICEMANAGER_MESSAGE_FAILED; + return DEVICEMANAGER_MESSAGE_FAILED; } int32_t ret = rsp->GetErrCode(); if (ret != DM_OK) { @@ -384,7 +383,7 @@ int32_t DeviceManagerImpl::GetUdidByNetworkId(const std::string &pkgName, const req->SetNetWorkId(netWorkId); if (CommandDispatch::GetInstance().MessageSendCmd(GET_UDID_BY_NETWORK, req, rsp) != DM_OK) { - return DEVICEMANAGER_MESSAGE_FAILED; + return DEVICEMANAGER_MESSAGE_FAILED; } int32_t ret = rsp->GetErrCode(); @@ -411,7 +410,7 @@ int32_t DeviceManagerImpl::GetUuidByNetworkId(const std::string &pkgName, const req->SetNetWorkId(netWorkId); if (CommandDispatch::GetInstance().MessageSendCmd(GET_UUID_BY_NETWORK, req, rsp) != DM_OK) { - return DEVICEMANAGER_MESSAGE_FAILED; + return DEVICEMANAGER_MESSAGE_FAILED; } int32_t ret = rsp->GetErrCode(); diff --git a/interfaces_mini/inner_kits/native_cpp/src/notify/device_manager_notify.cpp b/interfaces_mini/inner_kits/native_cpp/src/notify/device_manager_notify.cpp index 5765a5467..a665978c0 100644 --- a/interfaces_mini/inner_kits/native_cpp/src/notify/device_manager_notify.cpp +++ b/interfaces_mini/inner_kits/native_cpp/src/notify/device_manager_notify.cpp @@ -26,33 +26,28 @@ IMPLEMENT_SINGLE_INSTANCE(DeviceManagerNotify); void DeviceManagerNotify::RegisterDeathRecipientCallback(const std::string &pkgName, std::shared_ptr dmInitCallback) { - //std::lock_guard autoLock(lock_); dmInitCallback_[pkgName] = dmInitCallback; } void DeviceManagerNotify::UnRegisterDeathRecipientCallback(const std::string &pkgName) { - //std::lock_guard autoLock(lock_); dmInitCallback_.erase(pkgName); } void DeviceManagerNotify::RegisterDeviceStateCallback(const std::string &pkgName, std::shared_ptr callback) { - //std::lock_guard autoLock(lock_); deviceStateCallback_[pkgName] = callback; } void DeviceManagerNotify::UnRegisterDeviceStateCallback(const std::string &pkgName) { - //std::lock_guard autoLock(lock_); deviceStateCallback_.erase(pkgName); } void DeviceManagerNotify::RegisterDiscoveryCallback(const std::string &pkgName, uint16_t subscribeId, std::shared_ptr callback) { - //std::lock_guard autoLock(lock_); if (deviceDiscoveryCallbacks_.count(pkgName) == 0) { deviceDiscoveryCallbacks_[pkgName] = std::map>(); } @@ -61,7 +56,6 @@ void DeviceManagerNotify::RegisterDiscoveryCallback(const std::string &pkgName, void DeviceManagerNotify::UnRegisterDiscoveryCallback(const std::string &pkgName, uint16_t subscribeId) { - //std::lock_guard autoLock(lock_); if (deviceDiscoveryCallbacks_.count(pkgName) > 0) { deviceDiscoveryCallbacks_[pkgName].erase(subscribeId); if (deviceDiscoveryCallbacks_[pkgName].empty()) { @@ -73,7 +67,6 @@ void DeviceManagerNotify::UnRegisterDiscoveryCallback(const std::string &pkgName void DeviceManagerNotify::RegisterAuthenticateCallback(const std::string &pkgName, const std::string &deviceId, std::shared_ptr callback) { - //std::lock_guard autoLock(lock_); if (authenticateCallback_.count(pkgName) == 0) { authenticateCallback_[pkgName] = std::map>(); } @@ -82,7 +75,6 @@ void DeviceManagerNotify::RegisterAuthenticateCallback(const std::string &pkgNam void DeviceManagerNotify::UnRegisterAuthenticateCallback(const std::string &pkgName, const std::string &deviceId) { - //std::lock_guard autoLock(lock_); if (authenticateCallback_.count(pkgName) > 0) { authenticateCallback_[pkgName].erase(deviceId); if (authenticateCallback_[pkgName].empty()) { @@ -93,7 +85,6 @@ void DeviceManagerNotify::UnRegisterAuthenticateCallback(const std::string &pkgN void DeviceManagerNotify::UnRegisterPackageCallback(const std::string &pkgName) { - //std::lock_guard autoLock(lock_); deviceStateCallback_.erase(pkgName); deviceDiscoveryCallbacks_.erase(pkgName); authenticateCallback_.erase(pkgName); @@ -103,26 +94,22 @@ void DeviceManagerNotify::UnRegisterPackageCallback(const std::string &pkgName) void DeviceManagerNotify::RegisterVerifyAuthenticationCallback(const std::string &pkgName, const std::string &authPara, std::shared_ptr callback) { - //std::lock_guard autoLock(lock_); verifyAuthCallback_[pkgName] = callback; } void DeviceManagerNotify::UnRegisterVerifyAuthenticationCallback(const std::string &pkgName) { - //std::lock_guard autoLock(lock_); verifyAuthCallback_.erase(pkgName); } void DeviceManagerNotify::RegisterDeviceManagerFaCallback(const std::string &pkgName, std::shared_ptr callback) { - //std::lock_guard autoLock(lock_); dmFaCallback_[pkgName] = callback; } void DeviceManagerNotify::UnRegisterDeviceManagerFaCallback(const std::string &pkgName) { - //std::lock_guard autoLock(lock_); if (dmFaCallback_.count(pkgName) == 0) { LOGE("DeviceManager UnRegisterDeviceManagerFaCallback not register"); return; @@ -142,7 +129,6 @@ void DeviceManagerNotify::OnRemoteDied() void DeviceManagerNotify::OnDeviceOnline(const std::string &pkgName, const DmDeviceInfo &deviceInfo) { LOGI("DeviceManager OnDeviceOnline pkgName:%s", pkgName.c_str()); - //std::lock_guard autoLock(lock_); if (deviceStateCallback_.count(pkgName) == 0) { LOGE("DeviceManager OnDeviceOnlinecallback not register"); return; @@ -153,7 +139,7 @@ void DeviceManagerNotify::OnDeviceOnline(const std::string &pkgName, const DmDev void DeviceManagerNotify::OnDeviceOffline(const std::string &pkgName, const DmDeviceInfo &deviceInfo) { LOGI("DeviceManager OnDeviceOffline pkgName:%s", pkgName.c_str()); - // std::lock_guard autoLock(lock_); + if (deviceStateCallback_.count(pkgName) == 0) { LOGE("DeviceManager OnDeviceOfflinecallback not register"); return; @@ -164,7 +150,7 @@ void DeviceManagerNotify::OnDeviceOffline(const std::string &pkgName, const DmDe void DeviceManagerNotify::OnDeviceChanged(const std::string &pkgName, const DmDeviceInfo &deviceInfo) { LOGI("DeviceManager OnDeviceChanged pkgName:%s", pkgName.c_str()); - // std::lock_guard autoLock(lock_); + if (deviceStateCallback_.count(pkgName) == 0) { LOGE("DeviceManager OnDeviceChangedcallback not register"); return; @@ -176,7 +162,6 @@ void DeviceManagerNotify::OnDeviceFound(const std::string &pkgName, uint16_t sub const DmDeviceInfo &deviceInfo) { LOGI("DeviceManager OnDeviceFound pkgName:%s, subscribeId:%d.", pkgName.c_str(), (int32_t)subscribeId); - //std::lock_guard autoLock(lock_); if (deviceDiscoveryCallbacks_.count(pkgName) == 0) { LOGE("DeviceManager OnDeviceFound: no register DiscoveryCallback for this package"); return; @@ -194,7 +179,7 @@ void DeviceManagerNotify::OnDiscoveryFailed(const std::string &pkgName, uint16_t { LOGI("DeviceManager OnDiscoveryFailed pkgName:%s, subscribeId %d, reason %d", pkgName.c_str(), subscribeId, failedReason); - //std::lock_guard autoLock(lock_); + if (deviceDiscoveryCallbacks_.count(pkgName) == 0) { LOGE("DeviceManager OnDiscoveryFailed: no register DiscoveryCallback for this package"); return; @@ -211,7 +196,7 @@ void DeviceManagerNotify::OnDiscoveryFailed(const std::string &pkgName, uint16_t void DeviceManagerNotify::OnDiscoverySuccess(const std::string &pkgName, uint16_t subscribeId) { LOGI("DeviceManager OnDiscoverySuccess pkgName:%s, subscribeId:%d.", pkgName.c_str(), subscribeId); - //std::lock_guard autoLock(lock_); + if (deviceDiscoveryCallbacks_.count(pkgName) == 0) { LOGE("DeviceManager OnDiscoverySuccess: no register DiscoveryCallback for this package"); return; @@ -229,7 +214,7 @@ void DeviceManagerNotify::OnAuthResult(const std::string &pkgName, const std::st const std::string &token, uint32_t status, uint32_t reason) { LOGI("DeviceManagerNotify::OnAuthResult pkgName:%s, status:%d, reason:%d", pkgName.c_str(), status, reason); - //std::lock_guard autoLock(lock_); + if (authenticateCallback_.count(pkgName) == 0) { LOGE("DeviceManager OnAuthResult: no register authCallback for this package"); return; @@ -252,7 +237,7 @@ void DeviceManagerNotify::OnVerifyAuthResult(const std::string &pkgName, const s { LOGI("DeviceManagerNotify::OnCheckAuthResult pkgName:%s, resultCode:%d, flag:%d", pkgName.c_str(), resultCode, flag); - //std::lock_guard autoLock(lock_); + if (verifyAuthCallback_.count(pkgName) == 0) { LOGE("DeviceManager OnCheckAuthResult: no register authCallback for this package"); return; @@ -264,7 +249,7 @@ void DeviceManagerNotify::OnVerifyAuthResult(const std::string &pkgName, const s void DeviceManagerNotify::OnFaCall(std::string &pkgName, std::string ¶mJson) { LOGI("DeviceManager OnFaCallback pkgName:%s", pkgName.c_str()); - //std::lock_guard autoLock(lock_); + if (dmFaCallback_.count(pkgName) == 0) { LOGE("DeviceManager DmFaCallback not register"); return; diff --git a/utils/src/dm_random.cpp b/utils/src/dm_random.cpp index 738d33442..08f61c1aa 100644 --- a/utils/src/dm_random.cpp +++ b/utils/src/dm_random.cpp @@ -28,10 +28,14 @@ namespace OHOS { namespace DistributedHardware { int32_t GenRandInt(int32_t randMin, int32_t randMax) { +#if (defined(__LINUX__) || defined(__LITEOS_A__)) std::random_device randDevice; std::mt19937 genRand(randDevice()); std::uniform_int_distribution disRand(randMin, randMax); return disRand(genRand); +#else + return (randMin + random() % (randMax - randMin)); +#endif } int64_t GenRandLongLong(int64_t randMin, int64_t randMax) -- Gitee From ba12d8b10e666e3270854b17681b359e19fea367 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=85=9A=E6=B3=BD=E8=BE=89?= Date: Tue, 15 Mar 2022 14:17:08 +0000 Subject: [PATCH 12/19] =?UTF-8?q?!37=20mutex=E5=92=8Cthread=E5=B7=A5?= =?UTF-8?q?=E5=85=B7=E7=B1=BB=E4=BF=AE=E6=94=B9=20*=20mutex=E5=92=8Cthread?= =?UTF-8?q?=E5=B7=A5=E5=85=B7=E7=B1=BB=E4=BF=AE=E6=94=B9?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- services/devicemanagerservice/BUILD.gn | 3 + .../include/dependency/mini/dm_mutex.h | 34 +++++++ .../include/dependency/mini/dm_thread.h | 51 ++++++++++ .../devicestate/dm_device_state_manager.h | 4 +- .../src/dependency/mini/dm_mutex.cpp | 42 ++++++++ .../src/dependency/mini/dm_thread.cpp | 53 ++++++++++ .../dependency/softbus/softbus_connector.cpp | 96 ++++--------------- .../devicestate/dm_device_state_manager.cpp | 64 +++---------- 8 files changed, 211 insertions(+), 136 deletions(-) create mode 100644 services/devicemanagerservice/include/dependency/mini/dm_mutex.h create mode 100644 services/devicemanagerservice/include/dependency/mini/dm_thread.h create mode 100644 services/devicemanagerservice/src/dependency/mini/dm_mutex.cpp create mode 100644 services/devicemanagerservice/src/dependency/mini/dm_thread.cpp diff --git a/services/devicemanagerservice/BUILD.gn b/services/devicemanagerservice/BUILD.gn index e26b6230b..f80fb520c 100755 --- a/services/devicemanagerservice/BUILD.gn +++ b/services/devicemanagerservice/BUILD.gn @@ -38,6 +38,7 @@ if (defined(ohos_lite)) { "${services_path}/include/dependency/multipleuser", "${services_path}/include/dependency/hichain", "${services_path}/include/dependency/softbus", + "${services_path}/include/dependency/mini", "${services_path}/include/dependency/timer", "${services_path}/include/eventbus", "${common_path}/include", @@ -83,6 +84,8 @@ if (defined(ohos_lite)) { "${services_path}/src/dependency/multipleuser/mini/multiple_user_connector.cpp", "${services_path}/src/dependency/softbus/softbus_connector.cpp", "${services_path}/src/dependency/softbus/softbus_session.cpp", + "${services_path}/src/dependency/mini/dm_mutex.cpp", + "${services_path}/src/dependency/mini/dm_thread.cpp", "${services_path}/src/dependency/timer/mini/dm_timer.cpp", "${services_path}/src/device_manager_service.cpp", "${services_path}/src/deviceinfo/dm_device_info_manager.cpp", diff --git a/services/devicemanagerservice/include/dependency/mini/dm_mutex.h b/services/devicemanagerservice/include/dependency/mini/dm_mutex.h new file mode 100644 index 000000000..7fe0aac3f --- /dev/null +++ b/services/devicemanagerservice/include/dependency/mini/dm_mutex.h @@ -0,0 +1,34 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef OHOS_DM_MUTEX_H +#define OHOS_DM_MUTEX_H + +#include + +namespace OHOS { +namespace DistributedHardware { + +class DmMutex { +public: + DmMutex(); + ~DmMutex(); +private: +pthread_mutex_t lock_; +}; + +} // namespace DistributedHardware +} // namespace OHOS +#endif // OHOS_DM_MUTEX_H \ No newline at end of file diff --git a/services/devicemanagerservice/include/dependency/mini/dm_thread.h b/services/devicemanagerservice/include/dependency/mini/dm_thread.h new file mode 100644 index 000000000..5dc89f4a4 --- /dev/null +++ b/services/devicemanagerservice/include/dependency/mini/dm_thread.h @@ -0,0 +1,51 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef OHOS_DM_THREAD_H +#define OHOS_DM_THREAD_H + +#include +#include +#include +#include +#include "dm_device_info.h" +#include "softbus_state_callback.h" + +namespace OHOS { +namespace DistributedHardware { + +class DmThread { +typedef void (*funcstr)(std::map>, DmDeviceInfo); +public: + DmThread(funcstr funcname,\ + std::map> parameter1,\ + DmDeviceInfo parameter2); + static void* PthreadDeviceStart(void* parameterInfo); + void DmCreatThread(); + +private: + struct PthreadCallbackParameter{ + std::map> member1; + DmDeviceInfo member2; + }; + static funcstr funcName_; + static std::map> parameter1_; + static DmDeviceInfo parameter2_; + PthreadCallbackParameter parameterGroup_; +}; + +} // namespace DistributedHardware +} // namespace OHOS +#endif // OHOS_DM_THREAD_H diff --git a/services/devicemanagerservice/include/devicestate/dm_device_state_manager.h b/services/devicemanagerservice/include/devicestate/dm_device_state_manager.h index b814324c1..c2dcd3cfb 100755 --- a/services/devicemanagerservice/include/devicestate/dm_device_state_manager.h +++ b/services/devicemanagerservice/include/devicestate/dm_device_state_manager.h @@ -21,7 +21,7 @@ #if (defined(__LINUX__) || defined(__LITEOS_A__)) #include #else -#include +#include "dm_mutex.h" #endif #include "device_manager_service_listener.h" #include "dm_adapter_manager.h" @@ -60,8 +60,6 @@ private: #if (defined(__LINUX__) || defined(__LITEOS_A__)) std::mutex timerMapMutex_; std::mutex remoteDeviceInfosMutex_; -#else - pthread_mutex_t lock_; #endif std::shared_ptr softbusConnector_; std::shared_ptr listener_; diff --git a/services/devicemanagerservice/src/dependency/mini/dm_mutex.cpp b/services/devicemanagerservice/src/dependency/mini/dm_mutex.cpp new file mode 100644 index 000000000..8e27b3618 --- /dev/null +++ b/services/devicemanagerservice/src/dependency/mini/dm_mutex.cpp @@ -0,0 +1,42 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "dm_mutex.h" +#include "dm_log.h" +#include + +namespace OHOS { +namespace DistributedHardware { + +DmMutex::DmMutex() +{ +uint32_t ret = pthread_mutex_init(&lock_, NULL); +if (ret != 0) { + LOGE("init mutex lock failed: %d.",ret); +} +pthread_mutex_lock(&lock_); +} + +DmMutex::~DmMutex() +{ + pthread_mutex_unlock(&lock_); + uint32_t ret = pthread_mutex_destroy(&lock_); + if (ret != 0) { + LOGI("destroy mutex lock failed: %d.",ret); + } +} + +}// namespace DistributedHardware +}// namespace OHOS \ No newline at end of file diff --git a/services/devicemanagerservice/src/dependency/mini/dm_thread.cpp b/services/devicemanagerservice/src/dependency/mini/dm_thread.cpp new file mode 100644 index 000000000..507689ab2 --- /dev/null +++ b/services/devicemanagerservice/src/dependency/mini/dm_thread.cpp @@ -0,0 +1,53 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +#include "dm_thread.h" + +namespace OHOS { +namespace DistributedHardware { +typedef void (*funcstr)(std::map>, DmDeviceInfo); + +funcstr DmThread::funcName_; +std::map> DmThread::parameter1_ = {}; +DmDeviceInfo DmThread::parameter2_; + +DmThread::DmThread(funcstr funcname,\ + std::map> parameter1,\ + DmDeviceInfo parameter2) +{ + funcName_ = funcname; + parameter1_ = parameter1; + parameter2_ = parameter2; + parameterGroup_.member1 = parameter1; + parameterGroup_.member2 = parameter2; +} + +void* DmThread::PthreadDeviceStart(void* parameterInfo) +{ + PthreadCallbackParameter *parameterStruct; + parameterStruct = static_cast(parameterInfo); + funcName_(parameterStruct->member1, parameterStruct->member2); + return nullptr; +} + +void DmThread::DmCreatThread() +{ + pthread_t tid; + pthread_attr_t attr; + pthread_attr_init(&attr); + pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED); + pthread_create(&tid, &attr, PthreadDeviceStart, static_cast(¶meterGroup_)); +} +} // namespace DistributedHardware +} // namespace OHOS diff --git a/services/devicemanagerservice/src/dependency/softbus/softbus_connector.cpp b/services/devicemanagerservice/src/dependency/softbus/softbus_connector.cpp index 9449d8182..25f6f4dec 100644 --- a/services/devicemanagerservice/src/dependency/softbus/softbus_connector.cpp +++ b/services/devicemanagerservice/src/dependency/softbus/softbus_connector.cpp @@ -21,7 +21,8 @@ #include #include #else -#include +#include "dm_mutex.h" +#include "dm_thread.h" #endif #include "dm_anonymous.h" @@ -53,13 +54,17 @@ INodeStateCb SoftbusConnector::softbusNodeStateCb_ = { .onNodeOffline = SoftbusConnector::OnSoftbusDeviceOffline, .onNodeBasicInfoChanged = SoftbusConnector::OnSoftbusDeviceInfoChanged}; -#if (defined(__LINUX__) || defined(__LITEOS_A__)) + void DeviceOnLine(std::map> stateCallbackMap, DmDeviceInfo deviceInfo) { LOGI("Device on line start"); +#if (defined(__LINUX__) || defined(__LITEOS_A__)) std::mutex lockDeviceOnLine; std::lock_guard lock(lockDeviceOnLine); +#else + DmMutex lockDeviceOnLine; +#endif for (auto &iter : stateCallbackMap) { iter.second->OnDeviceOnline(iter.first, deviceInfo); } @@ -70,74 +75,17 @@ void DeviceOffLine(std::map> DmDeviceInfo deviceInfo) { LOGI("Device off line start"); +#if (defined(__LINUX__) || defined(__LITEOS_A__)) std::mutex lockDeviceOffLine; std::lock_guard lock(lockDeviceOffLine); - for (auto &iter : stateCallbackMap) { - iter.second->OnDeviceOffline(iter.first, deviceInfo); - } - LOGI("Device off line end"); -} #else -void DeviceOnLine(std::map> stateCallbackMap, - DmDeviceInfo deviceInfo) -{ - LOGI("Device on line start"); - pthread_mutex_t lockDeviceOnLine; - uint32_t ret = pthread_mutex_init(&lockDeviceOnLine, NULL); - if (ret != 0) { - LOGI("init mutex lock failed: %d.",ret); - } - pthread_mutex_lock(&lockDeviceOnLine); - for (auto &iter : stateCallbackMap) { - iter.second->OnDeviceOnline(iter.first, deviceInfo); - } - pthread_mutex_unlock(&lockDeviceOnLine); - ret = pthread_mutex_destroy(&lockDeviceOnLine); - if (ret != 0) { - LOGI("destroy mutex lock failed: %d.",ret); - } - LOGI("Device on line end"); -} - -void DeviceOffLine(std::map> stateCallbackMap, - DmDeviceInfo deviceInfo) -{ - LOGI("Device off line start"); - pthread_mutex_t lockDeviceOffLine; - uint32_t ret = pthread_mutex_init(&lockDeviceOffLine, NULL); - if (ret != 0) { - LOGI("init mutex lock failed: %d.",ret); - } - pthread_mutex_lock(&lockDeviceOffLine); + DmMutex lockDeviceOffLine; +#endif for (auto &iter : stateCallbackMap) { iter.second->OnDeviceOffline(iter.first, deviceInfo); } - pthread_mutex_unlock(&lockDeviceOffLine); - ret = pthread_mutex_destroy(&lockDeviceOffLine); - if (ret != 0) { - LOGI("destroy mutex lock failed: %d.",ret); - } LOGI("Device off line end"); } -struct PthreadCallbackParameter{ - std::map> CallbackMap; - DmDeviceInfo dmDeviceInfo; -}; - -void* PthreadDeviceOnLine(void* parameterInfo) -{ - PthreadCallbackParameter *parameterStruct; - parameterStruct = static_cast(parameterInfo); - DeviceOnLine(parameterStruct->CallbackMap, parameterStruct->dmDeviceInfo); -} - -void* PthreadDeviceOffLine(void* parameterInfo) -{ - PthreadCallbackParameter *parameterStruct; - parameterStruct = static_cast(parameterInfo); - DeviceOffLine(parameterStruct->CallbackMap, parameterStruct->dmDeviceInfo); -} -#endif SoftbusConnector::SoftbusConnector() { @@ -537,20 +485,14 @@ void SoftbusConnector::OnSoftBusDeviceOnline(NodeBasicInfo *info) return; } -#if (defined(__LINUX__) || defined(__LITEOS_A__)) DmDeviceInfo dmDeviceInfo; CovertNodeBasicInfoToDmDevice(*info, dmDeviceInfo); +#if (defined(__LINUX__) || defined(__LITEOS_A__)) std::thread deviceOnLine(DeviceOnLine, stateCallbackMap_, dmDeviceInfo); deviceOnLine.detach(); #else - PthreadCallbackParameter parameterStruct; - parameterStruct.CallbackMap = stateCallbackMap_; - CovertNodeBasicInfoToDmDevice(*info, parameterStruct.dmDeviceInfo); - pthread_t tid; - pthread_attr_t attr; - pthread_attr_init(&attr); - pthread_attr_setdetachstate(&attr,PTHREAD_CREATE_DETACHED); - pthread_create(&tid, &attr, PthreadDeviceOnLine, static_cast(¶meterStruct)); + DmThread deviceOnLine(DeviceOnLine, stateCallbackMap_, dmDeviceInfo); + deviceOnLine.DmCreatThread(); #endif if (discoveryDeviceInfoMap_.empty()) { @@ -575,20 +517,14 @@ void SoftbusConnector::OnSoftbusDeviceOffline(NodeBasicInfo *info) LOGE("OnSoftbusDeviceOffline NodeBasicInfo is nullptr"); return; } -#if (defined(__LINUX__) || defined(__LITEOS_A__)) DmDeviceInfo dmDeviceInfo; CovertNodeBasicInfoToDmDevice(*info, dmDeviceInfo); +#if (defined(__LINUX__) || defined(__LITEOS_A__)) std::thread deviceOffLine(DeviceOffLine, stateCallbackMap_, dmDeviceInfo); deviceOffLine.detach(); #else - PthreadCallbackParameter parameterStruct; - parameterStruct.CallbackMap = stateCallbackMap_; - CovertNodeBasicInfoToDmDevice(*info, parameterStruct.dmDeviceInfo); - pthread_t tid; - pthread_attr_t attr; - pthread_attr_init(&attr); - pthread_attr_setdetachstate(&attr,PTHREAD_CREATE_DETACHED); - pthread_create(&tid, &attr, PthreadDeviceOffLine, static_cast(¶meterStruct)); + DmThread deviceOffLine(DeviceOffLine, stateCallbackMap_, dmDeviceInfo); + deviceOffLine.DmCreatThread(); #endif } diff --git a/services/devicemanagerservice/src/devicestate/dm_device_state_manager.cpp b/services/devicemanagerservice/src/devicestate/dm_device_state_manager.cpp index f6361e3dc..5fefe6962 100755 --- a/services/devicemanagerservice/src/devicestate/dm_device_state_manager.cpp +++ b/services/devicemanagerservice/src/devicestate/dm_device_state_manager.cpp @@ -39,12 +39,6 @@ DmDeviceStateManager::DmDeviceStateManager(std::shared_ptr sof std::shared_ptr listener, std::shared_ptr hiChainConnector) : softbusConnector_(softbusConnector), listener_(listener), hiChainConnector_(hiChainConnector) { -#if defined(__LITEOS_M__) - uint32_t ret = pthread_mutex_init(&lock_, NULL); - if (ret != 0) { - LOGI("init mutex lock failed: %d.",ret); - } -#endif profileSoName_ = "libdevicemanagerext_profile.z.so"; decisionSoName_ = "libdevicemanagerext_decision.z.so"; LOGI("DmDeviceStateManager constructor"); @@ -53,12 +47,6 @@ DmDeviceStateManager::DmDeviceStateManager(std::shared_ptr sof DmDeviceStateManager::~DmDeviceStateManager() { LOGI("DmDeviceStateManager destructor"); -#if defined(__LITEOS_M__) - uint32_t ret = pthread_mutex_destroy(&lock_); - if (ret != 0) { - LOGI("destroy mutex lock failed: %d.",ret); - } -#endif if (softbusConnector_ != nullptr) { softbusConnector_->UnRegisterSoftbusStateCallback("DM_PKG_NAME"); } @@ -78,12 +66,10 @@ int32_t DmDeviceStateManager::RegisterProfileListener(const std::string &pkgName { #if (defined(__LINUX__) || defined(__LITEOS_A__)) std::lock_guard mutexLock(remoteDeviceInfosMutex_); - remoteDeviceInfos_[uuid] = saveInfo; #else - pthread_mutex_lock(&lock_); - remoteDeviceInfos_[uuid] = saveInfo; - pthread_mutex_unlock(&lock_); + DmMutex mutexLock; #endif + remoteDeviceInfos_[uuid] = saveInfo; } LOGI("RegisterProfileListener in, deviceId = %s, deviceUdid = %s, uuid = %s", info.deviceId, deviceUdid.c_str(), uuid.c_str()); @@ -105,16 +91,12 @@ int32_t DmDeviceStateManager::UnRegisterProfileListener(const std::string &pkgNa #if (defined(__LINUX__) || defined(__LITEOS_A__)) std::lock_guard mutexLock(remoteDeviceInfosMutex_); - if (remoteDeviceInfos_.find(std::string(info.deviceId)) != remoteDeviceInfos_.end()) { - remoteDeviceInfos_.erase(std::string(info.deviceId)); - } #else - pthread_mutex_lock(&lock_); + DmMutex mutexLock; +#endif if (remoteDeviceInfos_.find(std::string(info.deviceId)) != remoteDeviceInfos_.end()) { remoteDeviceInfos_.erase(std::string(info.deviceId)); } - pthread_mutex_unlock(&lock_); -#endif } return DM_OK; } @@ -222,22 +204,15 @@ void DmDeviceStateManager::OnProfileReady(const std::string &pkgName, const std: { #if (defined(__LINUX__) || defined(__LITEOS_A__)) std::lock_guard mutexLock(remoteDeviceInfosMutex_); - auto iter = remoteDeviceInfos_.find(deviceId); - if (iter == remoteDeviceInfos_.end()) { - LOGE("OnProfileReady complete not find deviceId: %s", GetAnonyString(deviceId).c_str()); - return; - } - saveInfo = iter->second; #else - pthread_mutex_lock(&lock_); + DmMutex mutexLock; +#endif auto iter = remoteDeviceInfos_.find(deviceId); if (iter == remoteDeviceInfos_.end()) { LOGE("OnProfileReady complete not find deviceId: %s", GetAnonyString(deviceId).c_str()); return; } saveInfo = iter->second; - pthread_mutex_unlock(&lock_); -#endif } if (listener_ != nullptr) { DmDeviceState state = DEVICE_INFO_READY; @@ -283,20 +258,11 @@ void DmDeviceStateManager::RegisterOffLineTimer(const DmDeviceInfo &deviceInfo) #if (defined(__LINUX__) || defined(__LITEOS_A__)) std::lock_guard mutexLock(timerMapMutex_); - deviceinfoMap_[deviceInfo.deviceId] = deviceId; - auto iter = timerMap_.find(deviceId); - if (iter != timerMap_.end()) { - iter->second->Stop(SESSION_CANCEL_TIMEOUT); - return; - } - std::shared_ptr offLineTimer = std::make_shared(deviceId); - if (offLineTimer != nullptr) { - timerMap_[deviceId] = offLineTimer; - } #else - pthread_mutex_lock(&lock_); - auto iter = timerMap_.find(deviceId); + DmMutex mutexLock; +#endif deviceinfoMap_[deviceInfo.deviceId] = deviceId; + auto iter = timerMap_.find(deviceId); if (iter != timerMap_.end()) { iter->second->Stop(SESSION_CANCEL_TIMEOUT); return; @@ -305,8 +271,6 @@ void DmDeviceStateManager::RegisterOffLineTimer(const DmDeviceInfo &deviceInfo) if (offLineTimer != nullptr) { timerMap_[deviceId] = offLineTimer; } - pthread_mutex_unlock(&lock_); -#endif } void DmDeviceStateManager::StartOffLineTimer(const DmDeviceInfo &deviceInfo) @@ -320,20 +284,14 @@ void DmDeviceStateManager::StartOffLineTimer(const DmDeviceInfo &deviceInfo) LOGI("start offline timer with device: %s", GetAnonyString(deviceinfoMap_[deviceInfo.deviceId]).c_str()); #if (defined(__LINUX__) || defined(__LITEOS_A__)) std::lock_guard mutexLock(timerMapMutex_); - for (auto &iter : timerMap_) { - if (iter.first == deviceinfoMap_[deviceInfo.deviceId]) { - iter.second->Start(OFFLINE_TIMEOUT, TimeOut, this); - } - } #else - pthread_mutex_lock(&lock_); + DmMutex mutexLock; +#endif for (auto &iter : timerMap_) { if (iter.first == deviceinfoMap_[deviceInfo.deviceId]) { iter.second->Start(OFFLINE_TIMEOUT, TimeOut, this); } } - pthread_mutex_unlock(&lock_); -#endif deviceinfoMap_.erase(deviceInfo.deviceId); } -- Gitee From d2247fb9c70db144a8f0a566c79cb4ac52bdb1f6 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Convert=2EToInt32=28=E9=98=BF=E4=BC=A6=29?= <619269320@qq.com> Date: Tue, 15 Mar 2022 14:17:58 +0000 Subject: [PATCH 13/19] =?UTF-8?q?!36=20fix:JSI=E4=BB=A3=E7=A0=81=E8=A7=84?= =?UTF-8?q?=E8=8C=83=E5=8C=96=E4=BF=AE=E6=94=B9=20*=20fix:=E4=BB=A3?= =?UTF-8?q?=E7=A0=81=E8=A7=84=E8=8C=83=E5=8C=96=E4=BF=AE=E6=94=B9?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../kits/js/include/dm_native_event.h | 10 +- .../kits/js/include/native_devicemanager_js.h | 36 +-- .../kits/js/src/dm_native_event.cpp | 29 +- .../kits/js/src/native_devicemanager_js.cpp | 283 +++++++++--------- 4 files changed, 168 insertions(+), 190 deletions(-) diff --git a/interfaces_mini/kits/js/include/dm_native_event.h b/interfaces_mini/kits/js/include/dm_native_event.h index d2975263a..c5987b3bf 100644 --- a/interfaces_mini/kits/js/include/dm_native_event.h +++ b/interfaces_mini/kits/js/include/dm_native_event.h @@ -12,7 +12,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -// #ifndef OHOS_DEVICE_MANAGER_NATIVE_EVENT_H #define OHOS_DEVICE_MANAGER_NATIVE_EVENT_H @@ -22,12 +21,9 @@ #include "jsi.h" #include "dm_device_info.h" -using namespace std; - namespace OHOS { namespace ACELite { - -struct DmEventListener{ +struct DmEventListener { std::string eventType; JSIValue handlerRef = JSI::CreateUndefined(); JSIValue thisVarRef_ = JSI::CreateUndefined(); @@ -40,8 +36,7 @@ struct FuncParams { uint8_t argsSize = 0; }; - -class DmNativeEvent{ +class DmNativeEvent { public: DmNativeEvent(); DmNativeEvent(JSIValue thisVar); @@ -53,7 +48,6 @@ public: protected: static std::map> eventMap_; }; - } } diff --git a/interfaces_mini/kits/js/include/native_devicemanager_js.h b/interfaces_mini/kits/js/include/native_devicemanager_js.h index 1d914c94b..0923117eb 100644 --- a/interfaces_mini/kits/js/include/native_devicemanager_js.h +++ b/interfaces_mini/kits/js/include/native_devicemanager_js.h @@ -18,6 +18,7 @@ #include #include +#include #include "device_manager_callback.h" #include "dm_native_event.h" #include "dm_device_info.h" @@ -25,13 +26,11 @@ #include "nlohmann/json.hpp" #include "dm_device_info.h" #include "jsi.h" -#include #include "js_ability.h" #include "dm_app_image_info.h" namespace OHOS { namespace ACELite { - #define DM_JSI_BUF_LENGTH (256) struct AuthFuncParams { @@ -126,10 +125,10 @@ private: std::string bundleName_; }; -class DeviceManagerModule final : public MemoryHeap,DmNativeEvent{ +class DeviceManagerModule final : public MemoryHeap,DmNativeEvent { public: - explicit DeviceManagerModule(); - virtual ~DeviceManagerModule(); + explicit DeviceManagerModule(); + virtual ~DeviceManagerModule(); static JSIValue CreateDeviceManager(const JSIValue thisVal, const JSIValue *args, uint8_t argsSize); static JSIValue ReleaseDeviceManager(const JSIValue thisVal, const JSIValue *args, uint8_t argsSize); static JSIValue GetTrustedDeviceListSync(const JSIValue thisVal, const JSIValue *args, uint8_t argsSize); @@ -141,43 +140,44 @@ public: static JSIValue JsOff(const JSIValue thisVal, const JSIValue *args, uint8_t argsSize); static JSIValue SetUserOperationSync(const JSIValue thisVal, const JSIValue *args, uint8_t argsSize); static JSIValue GetAuthenticationParamSync(const JSIValue thisVal, const JSIValue *args, uint8_t argsSize); - //add new static JSIValue GetLocalDeviceInfoSync(const JSIValue thisVal, const JSIValue *args, uint8_t argsSize); static JSIValue UnAuthenticateDevice(const JSIValue thisVal, const JSIValue *args, uint8_t argsSize); static DeviceManagerModule *GetDeviceManagerJSI(std::string &bundleName); static void AuthRsultVerifyInfoAsyncWorkFunc(void *data); static char *GetJSIAppBundleName(); - static void DmAuthParamToJsAuthParamy(const OHOS::DistributedHardware::DmAuthParam &authParam, JSIValue ¶mResult); + static void DmAuthParamToJsAuthParamy(const OHOS::DistributedHardware::DmAuthParam &authParam, + JSIValue ¶mResult); void OnDmfaCall(const std::string ¶mJson); - //... void OnVerifyResult(const std::string &deviceId, int32_t resultCode, const std::string flag); - //.... void OnAuthResult(const std::string &deviceId, const std::string &token, int32_t status, int32_t reason); void OnDiscoverFailed(uint16_t subscribeId, int32_t failedReason); void OnDeviceFound(uint16_t subscribeId, const OHOS::DistributedHardware::DmDeviceInfo &deviceInfo); - void OnDeviceStateChange(DmJSIDevStateChangeAction action,const OHOS::DistributedHardware::DmDeviceInfo &deviceInfo); + void OnDeviceStateChange(DmJSIDevStateChangeAction action, + const OHOS::DistributedHardware::DmDeviceInfo &deviceInfo); void OnRemoteDied(); static void JsToDmAuthExtra(const JSIValue ¶m, nlohmann::json &jsonObj); - static void JsToDmTokenInfo(const JSIValue &object,const std::string &fieldStr, nlohmann::json &jsonObj); + static void JsToDmTokenInfo(const JSIValue &object, const std::string &fieldStr, nlohmann::json &jsonObj); static void JsToJsonObject(const JSIValue &object, const std::string &fieldStr, nlohmann::json &jsonObj); - static void JsToDmBuffer(const JSIValue &object, const std::string &fieldStr, uint8_t **bufferPtr, int32_t &bufferLen); + static void JsToDmBuffer(const JSIValue &object, + const std::string &fieldStr, uint8_t **bufferPtr, int32_t &bufferLen); static void JsToDmAuthInfo(const JSIValue &object, std::string &extra); - static void JsToDmAppImageInfoAndDmExtra(const JSIValue &object, OHOS::DistributedHardware::DmAppImageInfo& appImageInfo, std::string &extra, int32_t &authType); + static void JsToDmAppImageInfoAndDmExtra(const JSIValue &object, OHOS::DistributedHardware::DmAppImageInfo& appImageInfo, + std::string &extra, int32_t &authType); static void JsToDmDeviceInfo(const JSIValue &object, OHOS::DistributedHardware::DmDeviceInfo& info); static int32_t JsToDmSubscribeInfo(const JSIValue &object, OHOS::DistributedHardware::DmSubscribeInfo& info); static char *JsObjectToString(const JSIValue &object, const std::string &fieldStr); static bool JsObjectToBool(const JSIValue &object, const std::string &fieldStr); static int32_t JsObjectToInt(const JSIValue &object, const std::string &fieldStr); - static void DmAuthParamToJsAuthParam(const OHOS::DistributedHardware::DmAuthParam &authParam, JSIValue ¶mResult); + static void DmAuthParamToJsAuthParam(const OHOS::DistributedHardware::DmAuthParam &authParam, + JSIValue ¶mResult); static void CreateDmCallback(std::string &bundleName, std::string &eventType); static void ReleaseDmCallback(std::string &bundleName, std::string &eventType); - static void DeviceInfoToJsArray(const std::vector &vecDevInfo, const int32_t idx, JSIValue &arrayResult); - + static void DeviceInfoToJsArray(const std::vector &vecDevInfo, + const int32_t idx, JSIValue &arrayResult); private: - std::string bundleName_; static AuthAsyncCallbackInfo authAsyncCallbackInfo_; - static AuthAsyncCallbackInfo verifyAsyncCallbackInfo_; + static AuthAsyncCallbackInfo verifyAsyncCallbackInfo_; }; void InitDeviceManagerModule(JSIValue exports); } diff --git a/interfaces_mini/kits/js/src/dm_native_event.cpp b/interfaces_mini/kits/js/src/dm_native_event.cpp index 7adf9de28..c63e0a9f7 100644 --- a/interfaces_mini/kits/js/src/dm_native_event.cpp +++ b/interfaces_mini/kits/js/src/dm_native_event.cpp @@ -19,38 +19,37 @@ #include "js_async_work.h" using namespace OHOS::DistributedHardware; +using namespace std; namespace OHOS { namespace ACELite { - std::map> DmNativeEvent::eventMap_; DmNativeEvent::DmNativeEvent() -{ - LOGI("DmNativeEvent::DmNativeEvent() in"); +{ + LOGI("DmNativeEvent::DmNativeEvent() in"); } DmNativeEvent::DmNativeEvent(JSIValue thisVar) -{ - LOGI("DmNativeEvent::DmNativeEvent(JSIValue thisVar) in"); +{ + LOGI("DmNativeEvent::DmNativeEvent(JSIValue thisVar) in"); } DmNativeEvent::~DmNativeEvent() { - LOGI("DmNativeEvent::~DmNativeEvent() in"); + LOGI("DmNativeEvent::~DmNativeEvent() in"); } - void DmNativeEvent::On(std::string &eventType, JSIValue handle, JSIValue thisVal) { - LOGI("DmNativeEvent On in for event: %s", eventType.c_str()); + LOGI("DmNativeEvent On in for event: %s", eventType.c_str()); std::shared_ptr listener= std::make_shared(); listener->eventType = eventType; listener->handlerRef = JSI::AcquireValue(handle); listener->thisVarRef_ = JSI::AcquireValue(thisVal); - eventMap_[eventType] = listener; + eventMap_[eventType] = listener; } void DmNativeEvent::Off(std::string &eventType) @@ -78,28 +77,26 @@ void DmNativeEvent::OnEvent(const std::string &eventType, uint8_t argsSize, cons return; } auto listener = iter->second; - if (!JSI::ValueIsFunction(listener->handlerRef)){ - LOGI("OnEvent for %s handlerRef is null", eventType.c_str()); - return; + if (!JSI::ValueIsFunction(listener->handlerRef)) { + LOGI("OnEvent for %s handlerRef is null", eventType.c_str()); + return; } FuncParams* params = new FuncParams(); params->handlerRef = listener->handlerRef; - params->thisVarRef_ = listener->thisVarRef_; + params->thisVarRef_ = listener->thisVarRef_; params->args = data; params->argsSize = argsSize; LOGI("OnEventAsyncWorkFunc for %s in", eventType.c_str()); JsAsyncWork::DispatchAsyncWork(OnEventAsyncWorkFunc, reinterpret_cast(params)); - } void DmNativeEvent::OnEventAsyncWorkFunc(void *data) { LOGI("OnEventAsyncWorkFunc in "); FuncParams* params = reinterpret_cast(data); - JSI::CallFunction(params->handlerRef, params->thisVarRef_, params->args, params->argsSize); + JSI::CallFunction(params->handlerRef, params->thisVarRef_, params->args, params->argsSize); } - } } \ No newline at end of file diff --git a/interfaces_mini/kits/js/src/native_devicemanager_js.cpp b/interfaces_mini/kits/js/src/native_devicemanager_js.cpp index ea12fe80c..5c0cbc447 100644 --- a/interfaces_mini/kits/js/src/native_devicemanager_js.cpp +++ b/interfaces_mini/kits/js/src/native_devicemanager_js.cpp @@ -14,7 +14,6 @@ */ #include "native_devicemanager_js.h" -#include "jsi.h" #include #include "nlohmann/json.hpp" #include "device_manager.h" @@ -24,13 +23,11 @@ #include "dm_log.h" #include "dm_device_info.h" - using namespace OHOS::DistributedHardware; using namespace std; namespace OHOS { namespace ACELite { - const std::string DM_JSI_EVENT_DEVICE_STATE_CHANGE = "deviceStateChange"; const std::string DM_JSI_EVENT_DEVICE_FOUND = "deviceFound"; const std::string DM_JSI_EVENT_DEVICE_DISCOVER_FAIL = "discoverFail"; @@ -38,7 +35,6 @@ const std::string DM_JSI_EVENT_DMFA_CALLBACK = "dmFaCallback"; const std::string DM_JSI_EVENT_DEVICE_SERVICE_DIE = "serviceDie"; const std::string DEVICE_MANAGER_JSI_CLASS_NAME = "DeviceManager"; -//int32->uint8_t const uint8_t DM_JSI_ARGS_ONE = 1; const uint8_t DM_JSI_ARGS_TWO = 2; const uint8_t DM_JSI_ARGS_THREE = 3; @@ -62,7 +58,7 @@ std::map> g_dmfaCallb AuthAsyncCallbackInfo DeviceManagerModule::authAsyncCallbackInfo_; AuthAsyncCallbackInfo DeviceManagerModule::verifyAsyncCallbackInfo_; -DeviceManagerModule *DeviceManagerModule::GetDeviceManagerJSI(std::string &bundleName) +DeviceManagerModule *DeviceManagerModule::GetDeviceManagerJSI(std::string &bundleName) { auto iter = g_deviceManagerMap.find(bundleName); if (iter == g_deviceManagerMap.end()) { @@ -79,11 +75,10 @@ DeviceManagerModule::DeviceManagerModule() : DmNativeEvent() DeviceManagerModule::~DeviceManagerModule() { - } void DmJSIInitCallback::OnRemoteDied() -{ +{ DeviceManagerModule *deviceManagerJSI = DeviceManagerModule::GetDeviceManagerJSI(bundleName_); if (deviceManagerJSI == nullptr) { LOGE("OnRemoteDied, deviceManagerJSI not find for bunderName %s", bundleName_.c_str()); @@ -94,13 +89,12 @@ void DmJSIInitCallback::OnRemoteDied() void DeviceManagerModule::OnRemoteDied() { - OnEvent("serviceDie", 0, nullptr); + OnEvent("serviceDie", 0, nullptr); } - void DmJSIDeviceStateCallback::OnDeviceOnline(const DmDeviceInfo &deviceInfo) { - DeviceManagerModule *deviceManagerJSI = DeviceManagerModule::GetDeviceManagerJSI(bundleName_); + DeviceManagerModule *deviceManagerJSI = DeviceManagerModule::GetDeviceManagerJSI(bundleName_); if (deviceManagerJSI == nullptr) { LOGE("OnDeviceOnline, deviceManagerJSI not find for bunderName %s", bundleName_.c_str()); return; @@ -149,7 +143,7 @@ void DmJSIDiscoverCallback::OnDeviceFound(uint16_t subscribeId, const DmDeviceI LOGI("OnDeviceFound for %s, subscribeId %d", bundleName_.c_str(), (int32_t)subscribeId); deviceManagerJSI->OnDeviceFound(subscribeId, deviceInfo); } -//OnDiscoveryFailed + void DmJSIDiscoverCallback::OnDiscoveryFailed(uint16_t subscribeId, int32_t failedReason) { DeviceManagerModule *deviceManagerJSI = DeviceManagerModule::GetDeviceManagerJSI(bundleName_); @@ -171,7 +165,8 @@ void DmJSIDiscoverCallback::OnDiscoverySuccess(uint16_t subscribeId) LOGI("DiscoverySuccess for %s, subscribeId %d", bundleName_.c_str(), (int32_t)subscribeId); } -void DmJSIAuthenticateCallback::OnAuthResult(const std::string &deviceId, const std::string &token, int32_t status, int32_t reason) +void DmJSIAuthenticateCallback::OnAuthResult(const std::string &deviceId, const std::string &token, + int32_t status, int32_t reason) { DeviceManagerModule *deviceManagerJSI = DeviceManagerModule::GetDeviceManagerJSI(bundleName_); if (deviceManagerJSI == nullptr) { @@ -240,18 +235,18 @@ int32_t DmJSIDiscoverCallback::GetRefCount() } void DeviceManagerModule::OnDeviceStateChange(DmJSIDevStateChangeAction action, const DmDeviceInfo &deviceInfo) -{ - JSIValue result = JSI::CreateObject(); - JSI::SetNumberProperty(result, "action", (double)action); - - JSIValue device = JSI::CreateObject(); - JSI::SetStringProperty(device, "deviceId", deviceInfo.deviceId); - JSI::SetStringProperty(device, "deviceName", deviceInfo.deviceName); - JSI::SetNumberProperty(device, "deviceTypeId", (double)deviceInfo.deviceTypeId); - - JSIValue param[2] = {result, device}; - OnEvent("deviceStateChange", DM_JSI_ARGS_TWO, param); - JSI::ReleaseValueList(result, device, ARGS_END); +{ + JSIValue result = JSI::CreateObject(); + JSI::SetNumberProperty(result, "action", (double)action); + + JSIValue device = JSI::CreateObject(); + JSI::SetStringProperty(device, "deviceId", deviceInfo.deviceId); + JSI::SetStringProperty(device, "deviceName", deviceInfo.deviceName); + JSI::SetNumberProperty(device, "deviceTypeId", (double)deviceInfo.deviceTypeId); + + JSIValue param[2] = {result, device}; + OnEvent("deviceStateChange", DM_JSI_ARGS_TWO, param); + JSI::ReleaseValueList(result, device, ARGS_END); } void DeviceManagerModule::OnDeviceFound(uint16_t subscribeId, const DmDeviceInfo &deviceInfo) @@ -259,16 +254,16 @@ void DeviceManagerModule::OnDeviceFound(uint16_t subscribeId, const DmDeviceInfo LOGI("OnDeviceFound for subscribeId %d", (int32_t)subscribeId); JSIValue result = JSI::CreateObject(); JSI::SetNumberProperty(result, "subscribeId", (double)subscribeId); - + JSIValue device = JSI::CreateObject(); JSI::SetStringProperty(device, "deviceId", deviceInfo.deviceId); JSI::SetStringProperty(device, "deviceName", deviceInfo.deviceName); JSI::SetNumberProperty(device, "deviceTypeId", (double)deviceInfo.deviceTypeId); - LOGI("OnDeviceFound subscribeId %ld ", subscribeId); - LOGI("OnDeviceFound deviceId %s ", deviceInfo.deviceId); - LOGI("OnDeviceFound deviceName %s ", deviceInfo.deviceName); - LOGI("OnDeviceFound deviceTypeId %x ", deviceInfo.deviceTypeId); - + LOGI("OnDeviceFound subscribeId %ld ", subscribeId); + LOGI("OnDeviceFound deviceId %s ", deviceInfo.deviceId); + LOGI("OnDeviceFound deviceName %s ", deviceInfo.deviceName); + LOGI("OnDeviceFound deviceTypeId %x ", deviceInfo.deviceTypeId); + JSIValue param[2] = {result, device}; OnEvent("deviceFound", DM_JSI_ARGS_TWO, param); JSI::ReleaseValueList(result, device, ARGS_END); @@ -298,7 +293,8 @@ void DeviceManagerModule::OnDmfaCall(const std::string ¶mJson) JSI::ReleaseValueList(result, ARGS_END); } -void DeviceManagerModule::OnAuthResult(const std::string &deviceId, const std::string &token, int32_t status, int32_t reason) +void DeviceManagerModule::OnAuthResult(const std::string &deviceId, const std::string &token, + int32_t status, int32_t reason) { LOGI("OnAuthResult for status: %d, reason: %d", status, reason); JSIValue thisVar = authAsyncCallbackInfo_.thisVal_; @@ -316,7 +312,7 @@ void DeviceManagerModule::OnAuthResult(const std::string &deviceId, const std::s JSIValue param[1] = {successOne}; AuthFuncParams* params =new AuthFuncParams(); params->handlerRef = success; - params->thisVarRef_ = thisVar; + params->thisVarRef_ = thisVar; params->args = param; params->argsSize = DM_JSI_ARGS_ONE; LOGI("OnAuthResult SuccessCallBack in."); @@ -328,15 +324,15 @@ void DeviceManagerModule::OnAuthResult(const std::string &deviceId, const std::s JSIValue param[2] = {errOne, errTwo}; AuthFuncParams* params =new AuthFuncParams(); params->handlerRef = fail; - params->thisVarRef_ = thisVar; + params->thisVarRef_ = thisVar; params->args = param; params->argsSize = DM_JSI_ARGS_TWO; LOGI("OnAuthResult FailCallBack in."); JsAsyncWork::DispatchAsyncWork(AuthRsultVerifyInfoAsyncWorkFunc, reinterpret_cast(params)); - } g_authCallbackMap.erase(bundleName_); - JSI::ReleaseValueList(thisVar, success, fail, errOne, errTwo, successOne, successTwo, authAsyncCallbackInfo_.thisVal_, authAsyncCallbackInfo_.callback, ARGS_END); + JSI::ReleaseValueList(thisVar, success, fail, errOne, errTwo, successOne, successTwo, + authAsyncCallbackInfo_.thisVal_, authAsyncCallbackInfo_.callback, ARGS_END); } void DeviceManagerModule::OnVerifyResult(const std::string &deviceId, int32_t resultCode, const std::string flag) @@ -357,12 +353,11 @@ void DeviceManagerModule::OnVerifyResult(const std::string &deviceId, int32_t re JSIValue param[2] = {successOne, successTwo}; AuthFuncParams* params =new AuthFuncParams(); params->handlerRef = success; - params->thisVarRef_ = thisVar; + params->thisVarRef_ = thisVar; params->args = param; params->argsSize = DM_JSI_ARGS_TWO; LOGI("OnVerifyResult SuccessCallBack in."); JsAsyncWork::DispatchAsyncWork(AuthRsultVerifyInfoAsyncWorkFunc, reinterpret_cast(params)); - } else { LOGI("OnVerifyResult failed"); JSI::SetNumberProperty(errOne, "code", (double)resultCode); @@ -373,15 +368,17 @@ void DeviceManagerModule::OnVerifyResult(const std::string &deviceId, int32_t re params->args = param; params->argsSize = DM_JSI_ARGS_ONE; LOGI("OnVerifyResult FailCallBack in."); - JsAsyncWork::DispatchAsyncWork(AuthRsultVerifyInfoAsyncWorkFunc, reinterpret_cast(params)); + JsAsyncWork::DispatchAsyncWork(AuthRsultVerifyInfoAsyncWorkFunc, reinterpret_cast(params)); } g_checkAuthCallbackMap.erase(bundleName_); - JSI::ReleaseValueList(thisVar, success, fail, successOne, successTwo, errOne, verifyAsyncCallbackInfo_.thisVal_, verifyAsyncCallbackInfo_.callback, ARGS_END); + JSI::ReleaseValueList(thisVar, success, fail, successOne, successTwo, errOne, + verifyAsyncCallbackInfo_.thisVal_, verifyAsyncCallbackInfo_.callback, ARGS_END); } -void DeviceManagerModule::DeviceInfoToJsArray(const std::vector &vecDevInfo, const int32_t idx, JSIValue &arrayResult) -{ +void DeviceManagerModule::DeviceInfoToJsArray(const std::vector &vecDevInfo, + const int32_t idx, JSIValue &arrayResult) +{ bool status = false; JSIValue result = JSI::CreateObject(); char *deviceId = const_cast(vecDevInfo[idx].deviceId); @@ -391,36 +388,36 @@ void DeviceManagerModule::DeviceInfoToJsArray(const std::vector &v JSI::SetStringProperty(result, "deviceName", deviceName); JSI::SetNumberProperty(result, "deviceTypeId", (double)vecDevInfo[idx].deviceTypeId); - status = JSI::SetPropertyByIndex(arrayResult,idx,result); + status = JSI::SetPropertyByIndex(arrayResult, idx, result); if (status == false) { LOGE("DmDeviceInfo To JsArray set element error"); } - JSI::ReleaseValue(result); + JSI::ReleaseValue(result); } void DeviceManagerModule::DmAuthParamToJsAuthParamy(const DmAuthParam &authParam, JSIValue ¶mResult) { - LOGI("DmAuthParamToJsAuthParamy in"); - JSI::SetNumberProperty(paramResult,"authType",(double)authParam.authType); - + LOGI("DmAuthParamToJsAuthParamy in"); + JSI::SetNumberProperty(paramResult, "authType", (double)authParam.authType); + JSIValue extraInfo = JSI::CreateObject(); - JSI::SetNumberProperty(extraInfo,"direction",(double)authParam.direction); - JSI::SetNumberProperty(extraInfo,"pinToken",(double)authParam.pinToken); + JSI::SetNumberProperty(extraInfo, "direction", (double)authParam.direction); + JSI::SetNumberProperty(extraInfo, "pinToken", (double)authParam.pinToken); if (authParam.direction == DM_AUTH_DIRECTION_CLIENT) { - JSI::SetNamedProperty(paramResult,"extraInfo",extraInfo); + JSI::SetNamedProperty(paramResult, "extraInfo", extraInfo); return; } - JSI::SetStringProperty(extraInfo, "packageName",authParam.packageName.c_str()); - JSI::SetStringProperty(extraInfo, "appName",authParam.appName.c_str()); - JSI::SetStringProperty(extraInfo, "appDescription",authParam.appDescription.c_str()); - JSI::SetNumberProperty(extraInfo,"business",(double)authParam.business); - JSI::SetNumberProperty(extraInfo,"pincode",(double)authParam.pincode); - JSI::SetNamedProperty(paramResult,"extraInfo",extraInfo); + JSI::SetStringProperty(extraInfo, "packageName", authParam.packageName.c_str()); + JSI::SetStringProperty(extraInfo, "appName", authParam.appName.c_str()); + JSI::SetStringProperty(extraInfo, "appDescription", authParam.appDescription.c_str()); + JSI::SetNumberProperty(extraInfo, "business", (double)authParam.business); + JSI::SetNumberProperty(extraInfo, "pincode", (double)authParam.pincode); + JSI::SetNamedProperty(paramResult, "extraInfo", extraInfo); LOGI("DeviceManagerModule::DmAuthParamToJsAuthParamy, packageName: %s", authParam.packageName.c_str()); - LOGI("DeviceManagerModule::DmAuthParamToJsAuthParamy, appName: %s", authParam.appName.c_str()); - LOGI("DeviceManagerModule::DmAuthParamToJsAuthParamy, appDescription: %s", authParam.appDescription.c_str()); - LOGI("DeviceManagerModule::DmAuthParamToJsAuthParamy, business: %d",authParam.business); - LOGI("DeviceManagerModule::DmAuthParamToJsAuthParamy, pincode: %d", authParam.pincode); + LOGI("DeviceManagerModule::DmAuthParamToJsAuthParamy, appName: %s", authParam.appName.c_str()); + LOGI("DeviceManagerModule::DmAuthParamToJsAuthParamy, appDescription: %s", authParam.appDescription.c_str()); + LOGI("DeviceManagerModule::DmAuthParamToJsAuthParamy, business: %d", authParam.business); + LOGI("DeviceManagerModule::DmAuthParamToJsAuthParamy, pincode: %d", authParam.pincode); LOGI("DeviceManagerModule::DmAuthParamToJsAuthParamy, pinToken: %d", authParam.pinToken); size_t appIconLen = (size_t)authParam.imageinfo.GetAppIconLen(); @@ -430,8 +427,9 @@ void DeviceManagerModule::DmAuthParamToJsAuthParamy(const DmAuthParam &authParam if (appIcon != nullptr && memcpy_s(appIcon, appIconLen, reinterpret_cast(authParam.imageinfo.GetAppIcon()), appIconLen) == 0) { - JSIValue appIconArray = JSI::CreateTypedArray(TypedArrayType::JSI_UINT8_ARRAY, appIconLen, appIconBuffer, 0); - JSI::SetNamedProperty(paramResult,"appIcon",appIconArray); + JSIValue appIconArray = JSI::CreateTypedArray(TypedArrayType::JSI_UINT8_ARRAY, + appIconLen, appIconBuffer, 0); + JSI::SetNamedProperty(paramResult, "appIcon", appIconArray); } } @@ -439,8 +437,10 @@ void DeviceManagerModule::DmAuthParamToJsAuthParamy(const DmAuthParam &authParam if (appThumbnailLen > 0) { uint8_t *appThumbnail = nullptr; JSIValue appThumbnailBuffer = JSI::CreateArrayBuffer(appThumbnailLen, appThumbnail); - if (appThumbnail != nullptr && memcpy_s(appThumbnail, appThumbnailLen, reinterpret_cast(authParam.imageinfo.GetAppThumbnail()), appThumbnailLen) == 0) { - JSIValue appThumbnailArray = JSI::CreateTypedArray(TypedArrayType::JSI_UINT8_ARRAY, appThumbnailLen, appThumbnailBuffer, 0); + if (appThumbnail != nullptr && memcpy_s(appThumbnail, appThumbnailLen, + reinterpret_cast(authParam.imageinfo.GetAppThumbnail()), appThumbnailLen) == 0) { + JSIValue appThumbnailArray = JSI::CreateTypedArray(TypedArrayType::JSI_UINT8_ARRAY, + appThumbnailLen, appThumbnailBuffer, 0); JSI::SetNamedProperty(paramResult,"appThumbnail", appThumbnailArray); } } @@ -449,28 +449,28 @@ void DeviceManagerModule::DmAuthParamToJsAuthParamy(const DmAuthParam &authParam int32_t DeviceManagerModule::JsObjectToInt(const JSIValue &object, const std::string &fieldStr) { - double result = JSI::GetNumberProperty(object,fieldStr.c_str()); - return (int32_t)result; + double result = JSI::GetNumberProperty(object, fieldStr.c_str()); + return (int32_t)result; } bool DeviceManagerModule::JsObjectToBool(const JSIValue &object, const std::string &fieldStr) { - bool result = JSI::GetBooleanProperty(object,fieldStr.c_str()); - return result; + bool result = JSI::GetBooleanProperty(object, fieldStr.c_str()); + return result; } char *DeviceManagerModule::JsObjectToString(const JSIValue &object, const std::string &fieldStr) { char* str = JSI::GetStringProperty(object, fieldStr.c_str()); - return str; + return str; } -int32_t DeviceManagerModule::JsToDmSubscribeInfo(const JSIValue &object,DmSubscribeInfo &info) +int32_t DeviceManagerModule::JsToDmSubscribeInfo(const JSIValue &object, DmSubscribeInfo &info) { int32_t subscribeId = -1; - subscribeId = JsObjectToInt(object,"subscribeId"); + subscribeId = JsObjectToInt(object, "subscribeId"); if (subscribeId < 0 || subscribeId > DM_JSI_SUB_ID_MAX) { LOGE("DeviceManagerModule::JsToDmSubscribeInfo, subscribeId error, subscribeId: %d ", subscribeId); return -1; @@ -500,11 +500,11 @@ int32_t DeviceManagerModule::JsToDmSubscribeInfo(const JSIValue &object,DmSubscr return 0; } -void DeviceManagerModule::JsToDmDeviceInfo( const JSIValue &object, - DmDeviceInfo &info) -{ - std::strcpy(info.deviceId, JsObjectToString(object, "deviceId")); - std::strcpy(info.deviceName, JsObjectToString(object, "deviceName")); +void DeviceManagerModule::JsToDmDeviceInfo(const JSIValue &object, + DmDeviceInfo &info) +{ + strcpy_s(info.deviceId, DM_MAX_DEVICE_ID_LEN, JsObjectToString(object, "deviceId")); + strcpy_s(info.deviceName, DM_MAX_DEVICE_NAME_LEN, JsObjectToString(object, "deviceName")); uint16_t deviceTypeId = -1; deviceTypeId = (uint16_t)JsObjectToInt(object, "deviceTypeId"); info.deviceTypeId = deviceTypeId; @@ -551,7 +551,7 @@ void DeviceManagerModule::JsToDmBuffer(const JSIValue &object, LOGI("JsToDmBuffer in."); JSIValue field = JSI::GetNamedProperty(object, fieldStr.c_str()); - if (field == JSI::CreateUndefined() || field == JSI::CreateNull()){ + if (field == JSI::CreateUndefined() || field == JSI::CreateNull()) { LOGE("devicemanager JSI js to str no property: %s", fieldStr.c_str()); return; } @@ -586,7 +586,7 @@ void DeviceManagerModule::JsToJsonObject(const JSIValue &object, { LOGI("JsToJsonObject in."); JSIValue jsonField = JSI::GetNamedProperty(object, fieldStr.c_str()); - if (jsonField == JSI::CreateUndefined() || jsonField == JSI::CreateNull()){ + if (jsonField == JSI::CreateUndefined() || jsonField == JSI::CreateNull()) { LOGE("devicemanager JSI js to str no property: %s", fieldStr.c_str()); return; } @@ -605,19 +605,19 @@ void DeviceManagerModule::JsToJsonObject(const JSIValue &object, std::string strProName = JSI::ValueToString(jsProName); jsProValue = JSI::GetNamedProperty(jsonField, strProName.c_str()); - if (JSI::ValueIsString(jsProValue)){ + if (JSI::ValueIsString(jsProValue)) { std::string natValue = JSI::ValueToString(jsProValue); LOGI("Property name=%s, string, value=%s", strProName.c_str(), natValue.c_str()); - jsonObj[strProName] = natValue; + jsonObj[strProName] = natValue; } - if (JSI::ValueIsBoolean(jsProValue)){ + if (JSI::ValueIsBoolean(jsProValue)) { bool elementValue = JSI::ValueToBoolean(jsProValue); LOGI("Property name=%s, boolean, value=%d.", strProName.c_str(), elementValue); jsonObj[strProName] = elementValue; } - if (JSI::ValueIsNumber(jsProValue)){ + if (JSI::ValueIsNumber(jsProValue)) { int32_t elementValue = 0; elementValue = (int32_t)JSI::ValueToNumber(jsProValue); jsonObj[strProName] = elementValue; @@ -654,7 +654,8 @@ void DeviceManagerModule::CreateDmCallback(std::string &bundleName, std::string if (iter == g_deviceStateCallbackMap.end()) { auto callback = std::make_shared(bundleName); std::string extra = ""; - int32_t ret = OHOS::DistributedHardware::DeviceManager::GetInstance().RegisterDevStateCallback(bundleName, extra, callback); + int32_t ret = OHOS::DistributedHardware::DeviceManager::GetInstance().RegisterDevStateCallback( + bundleName, extra, callback); if (ret != 0) { LOGE("RegisterDevStateCallback failed for bunderName %s", bundleName.c_str()); return; @@ -683,7 +684,8 @@ void DeviceManagerModule::CreateDmCallback(std::string &bundleName, std::string auto iter = g_dmfaCallbackMap.find(bundleName); if (iter == g_dmfaCallbackMap.end()) { auto callback = std::make_shared(bundleName); - int32_t ret = OHOS::DistributedHardware::DeviceManager::GetInstance().RegisterDeviceManagerFaCallback(bundleName, callback); + int32_t ret = OHOS::DistributedHardware::DeviceManager::GetInstance().RegisterDeviceManagerFaCallback( + bundleName, callback); if (ret != 0) { LOGE("RegisterDeviceManagerFaCallback failed for bunderName %s", bundleName.c_str()); return; @@ -746,10 +748,9 @@ void DeviceManagerModule::AuthRsultVerifyInfoAsyncWorkFunc(void *data) { LOGI("AuthRsultVerifyInfoAsyncWorkFunc in ............"); AuthFuncParams* params = reinterpret_cast(data); - JSI::CallFunction(params->handlerRef, params->thisVarRef_, params->args, params->argsSize); + JSI::CallFunction(params->handlerRef, params->thisVarRef_, params->args, params->argsSize); } -//add new JSIValue DeviceManagerModule::UnAuthenticateDevice(const JSIValue thisVal, const JSIValue *args, uint8_t argsSize) { LOGI("UnAuthenticateDevice in"); @@ -757,20 +758,18 @@ JSIValue DeviceManagerModule::UnAuthenticateDevice(const JSIValue thisVal, const LOGE("1 argument is required."); return JSI::CreateNull(); } - if (!JSI::ValueIsObject(args[0])){ + if (!JSI::ValueIsObject(args[0])) { LOGE("a object is required."); return JSI::CreateNull(); } std::string bundleName = GetJSIAppBundleName(); - std::string deviceId = JSI::GetStringProperty(args[0], "deviceId"); + std::string deviceId = JSI::GetStringProperty(args[0], "deviceId"); LOGI("UnAuthenticateDevice deviceId=%s", deviceId.c_str()); int32_t ret = 0; - #if 1 ret = OHOS::DistributedHardware::DeviceManager::GetInstance().UnAuthenticateDevice(bundleName, deviceId); if (ret != 0) { LOGI("UnAuthenticateDevice for bunderName %s failed, ret %d", bundleName.c_str(), ret); } - #endif JSIValue result = JSI::CreateObject(); JSI::SetNumberProperty(result, "ret", (double)ret); @@ -783,13 +782,11 @@ JSIValue DeviceManagerModule::GetLocalDeviceInfoSync(const JSIValue thisVal, con std::string bundleName = GetJSIAppBundleName(); DmDeviceInfo deviceInfo; - #if 1 int32_t ret = OHOS::DistributedHardware::DeviceManager::GetInstance().GetLocalDeviceInfo(bundleName, deviceInfo); if (ret != 0) { LOGE("GetLocalDeviceInfoSync for failed, ret %d", ret); return JSI::CreateNull(); } - #endif LOGI("DeviceManager::GetLocalDeviceInfoSync deviceId:%s deviceName:%s deviceTypeId:%d ", deviceInfo.deviceId, deviceInfo.deviceName, deviceInfo.deviceTypeId); JSIValue result = JSI::CreateObject(); @@ -810,7 +807,7 @@ JSIValue DeviceManagerModule::SetUserOperationSync(const JSIValue thisVal, const return JSI::CreateNull(); } - if (!JSI::ValueIsNumber(args[0])){ + if (!JSI::ValueIsNumber(args[0])) { LOGE("a Number is required."); return JSI::CreateNull(); } @@ -837,19 +834,17 @@ JSIValue DeviceManagerModule::GetAuthenticationParamSync(const JSIValue thisVal, std::string bundleName = GetJSIAppBundleName(); JSIValue resultParam = JSI::CreateObject(); DmAuthParam authParam; - //add new - #if 1 int32_t ret = OHOS::DistributedHardware::DeviceManager::GetInstance().GetFaParam(bundleName, authParam); if (ret != 0) { LOGE("GetAuthenticationParam for %s failed, ret %d", bundleName.c_str(), ret); return JSI::CreateNull(); } - #endif - DmAuthParamToJsAuthParamy(authParam,resultParam); + + DmAuthParamToJsAuthParamy(authParam, resultParam); return resultParam; } - + JSIValue DeviceManagerModule::GetTrustedDeviceListSync(const JSIValue thisVal, const JSIValue *args, uint8_t argsSize) { LOGI("GetTrustedDeviceList in"); @@ -866,7 +861,7 @@ JSIValue DeviceManagerModule::GetTrustedDeviceListSync(const JSIValue thisVal, c } if (devList.size() > 0) { bool isArray = false; - array = JSI::CreateArray(devList.size()); + array = JSI::CreateArray(devList.size()); isArray = JSI::ValueIsArray(array); if (isArray == false) { LOGE("JSI_create_array fail"); @@ -887,12 +882,12 @@ JSIValue DeviceManagerModule::StartDeviceDiscoverSync(const JSIValue thisVal, co LOGI("StartDeviceDiscoverSync in"); std::string bundleName = GetJSIAppBundleName(); - if (argsSize < 1){ + if (argsSize < 1) { LOGE("1 argument is required."); return JSI::CreateNull(); } - if (!JSI::ValueIsObject(args[0])){ + if (!JSI::ValueIsObject(args[0])) { LOGE("a object is required."); return JSI::CreateNull(); } @@ -907,21 +902,18 @@ JSIValue DeviceManagerModule::StartDeviceDiscoverSync(const JSIValue thisVal, co } DmSubscribeInfo subInfo; int32_t res = JsToDmSubscribeInfo(args[0], subInfo); - if (res != 0){ + if (res != 0) { LOGE("Wrong subscribeId."); return JSI::CreateNull(); } - LOGI("subInfo %d , %d, %d, %d, %d , %d, %s", - subInfo.subscribeId, - subInfo.mode, - subInfo.medium, - subInfo.freq, - subInfo.isSameAccount, - subInfo.isWakeRemote, - subInfo.capability); - //add extra - #if 1 + LOGI("subInfo %d , %d, %d, %d, %d , %d, %s", subInfo.subscribeId, + subInfo.mode, + subInfo.medium, + subInfo.freq, + subInfo.isSameAccount, + subInfo.isWakeRemote, + subInfo.capability); std::string extra = ""; int32_t ret = OHOS::DistributedHardware::DeviceManager::GetInstance().StartDeviceDiscovery(bundleName, subInfo, extra, discoverCallback); @@ -930,8 +922,7 @@ JSIValue DeviceManagerModule::StartDeviceDiscoverSync(const JSIValue thisVal, co bundleName.c_str(), ret); return JSI::CreateNull(); } - #endif - return JSI::CreateNull(); + return JSI::CreateNull(); } JSIValue DeviceManagerModule::StopDeviceDiscoverSync(const JSIValue thisVal, const JSIValue *args, uint8_t argsSize) @@ -939,16 +930,16 @@ JSIValue DeviceManagerModule::StopDeviceDiscoverSync(const JSIValue thisVal, con LOGI("StopDeviceDiscoverSync in"); std::string bundleName = GetJSIAppBundleName(); - if (argsSize < 1){ + if (argsSize < 1) { LOGE("1 argument is required."); return JSI::CreateNull(); } - if (!JSI::ValueIsNumber(args[0])){ + if (!JSI::ValueIsNumber(args[0])) { LOGE("a Number is required."); return JSI::CreateNull(); } - //add new + int16_t subscribeId = 0; subscribeId = static_cast(JSI::ValueToNumber(args[0])); LOGI("subscribeId %d ", subscribeId); @@ -967,23 +958,23 @@ JSIValue DeviceManagerModule::AuthenticateDevice(const JSIValue thisVal, const J { LOGI("AuthenticateDevice in"); std::string bundleName = GetJSIAppBundleName(); - if (argsSize < 3){ + if (argsSize < DM_JSI_ARGS_THREE) { LOGE("3 argument is required."); return JSI::CreateNull(); } - if (!JSI::ValueIsObject(args[0])){ + if (!JSI::ValueIsObject(args[0])) { LOGE("a object is required."); return JSI::CreateNull(); } - if (!JSI::ValueIsObject(args[1])){ + if (!JSI::ValueIsObject(args[1])) { LOGE("a object is required."); return JSI::CreateNull(); } authAsyncCallbackInfo_.thisVal_ = JSI::AcquireValue(thisVal); - authAsyncCallbackInfo_.callback = JSI::AcquireValue(args[2]); + authAsyncCallbackInfo_.callback = JSI::AcquireValue(args[DM_JSI_ARGS_TWO]); std::shared_ptr authCallback = nullptr; auto iter = g_authCallbackMap.find(bundleName); @@ -996,11 +987,9 @@ JSIValue DeviceManagerModule::AuthenticateDevice(const JSIValue thisVal, const J DmDeviceInfo deviceInfo; JsToDmDeviceInfo(args[0], deviceInfo); - LOGI("deviceInfo %s , %s, %d", - deviceInfo.deviceId, - deviceInfo.deviceName, - deviceInfo.deviceTypeId); - + LOGI("deviceInfo %s , %s, %d", deviceInfo.deviceId, + deviceInfo.deviceName, + deviceInfo.deviceTypeId); DmAppImageInfo appImageInfo(nullptr, 0, nullptr, 0); std::string extra; JsToDmAppImageInfoAndDmExtra(args[1], appImageInfo, extra, authAsyncCallbackInfo_.authType); @@ -1019,12 +1008,12 @@ JSIValue DeviceManagerModule::VerifyAuthInfo(const JSIValue thisVal, const JSIVa { LOGI("VerifyAuthInfo in"); std::string bundleName = GetJSIAppBundleName(); - if (argsSize < 2){ + if (argsSize < DM_JSI_ARGS_TWO) { LOGE("2 argument is required."); return JSI::CreateNull(); } - if (!JSI::ValueIsObject(args[0])){ + if (!JSI::ValueIsObject(args[0])) { LOGE("a object is required."); return JSI::CreateNull(); } @@ -1047,34 +1036,34 @@ JSIValue DeviceManagerModule::VerifyAuthInfo(const JSIValue thisVal, const JSIVa if (ret != 0) { LOGE("VerifyAuthInfo for bunderName %s failed, ret %d", bundleName.c_str(), ret); - } + } return JSI::CreateUndefined(); } JSIValue DeviceManagerModule::JsOn(const JSIValue thisVal, const JSIValue *args, uint8_t argsSize) { LOGI("JsOn in"); - std::string bundleName = GetJSIAppBundleName(); - if (argsSize < 2){ + std::string bundleName = GetJSIAppBundleName(); + if (argsSize < DM_JSI_ARGS_TWO) { LOGE("2 argument is required."); return JSI::CreateNull(); } - if (!JSI::ValueIsString(args[0])){ + if (!JSI::ValueIsString(args[0])) { LOGE("a string is required."); - return JSI::CreateNull(); + return JSI::CreateNull(); } - if (!JSI::ValueIsFunction(args[1])){ + if (!JSI::ValueIsFunction(args[1])) { LOGE("a FUNC is required."); return JSI::CreateNull(); } std::string eventType = JSI::ValueToString(args[0]); LOGI("JsOn for bunderName %s, eventType %s ", bundleName.c_str(), - eventType.c_str()); - std::shared_ptr DmNativeEventobj = std::make_shared(thisVal); - DmNativeEventobj->On(eventType, args[1], thisVal); + eventType.c_str()); + std::shared_ptr DmNativeEventobj = std::make_shared(thisVal); + DmNativeEventobj->On(eventType, args[1], thisVal); CreateDmCallback(bundleName, eventType); - + return JSI::CreateUndefined(); } @@ -1083,11 +1072,11 @@ JSIValue DeviceManagerModule::JsOff(const JSIValue thisVal, const JSIValue *args LOGI("JsOff in"); std::string bundleName = GetJSIAppBundleName(); - if (!JSI::ValueIsString(args[0])){ + if (!JSI::ValueIsString(args[0])) { LOGE("a string is required."); return JSI::CreateNull(); } - + std::string eventType = JSI::ValueToString(args[0]); LOGI("JsOff for bunderName %s, eventType %s ", bundleName.c_str(), @@ -1137,8 +1126,7 @@ JSIValue DeviceManagerModule::CreateDeviceManager(const JSIValue thisVal, const return JSI::CreateNull(); } std::string bundleName = GetJSIAppBundleName(); - - LOGI("CreateDeviceManager for bunderName is %s", bundleName.c_str()); + LOGI("CreateDeviceManager for bunderName is %s", bundleName.c_str()); if (DeviceManagerModule::GetDeviceManagerJSI(bundleName) != nullptr) { LOGI("CreateDeviceManager repeat for bunderName %s", bundleName.c_str()); @@ -1152,15 +1140,15 @@ JSIValue DeviceManagerModule::CreateDeviceManager(const JSIValue thisVal, const int32_t ret = 0; std::shared_ptr initCallback = std::make_shared(bundleName); ret = OHOS::DistributedHardware::DeviceManager::GetInstance().InitDeviceManager(bundleName, initCallback); - if ( ret == 0 ){ + if (ret == 0) { LOGI("InitDeviceManager for bunderName %s success", bundleName.c_str()); JSIValue success = JSI::GetNamedProperty(args[1], CB_SUCCESS); JSIValue data = JSI::CreateObject(); std::string str = "InitDeviceManager success"; JSI::SetStringProperty(data, "data", str.c_str()); JSI::CallFunction(success, thisVal, &data, 1); - } - if (ret != 0){ + } + if (ret != 0) { LOGI("InitDeviceManager for bunderName %s fail", bundleName.c_str()); JSIValue fail = JSI::GetNamedProperty(args[1], CB_FAIL); JSIValue err = JSI::CreateObject(); @@ -1168,7 +1156,6 @@ JSIValue DeviceManagerModule::CreateDeviceManager(const JSIValue thisVal, const JSI::SetStringProperty(err, "err", str.c_str()); JSI::CallFunction(fail, thisVal, &err, 1); } - return JSI::CreateNull(); } @@ -1177,7 +1164,7 @@ char *DeviceManagerModule::GetJSIAppBundleName() JSAbility *g_targetJSAbility = new JSAbility(); const char *pname = g_targetJSAbility->GetPackageName(); char *packageName = new char[strlen(pname)+1]; - strcpy(packageName, pname); + strcpy_s(packageName, strlen(pname)+1, pname); delete(g_targetJSAbility); return packageName; } @@ -1195,8 +1182,8 @@ void InitDeviceManagerModule(JSIValue exports) JSI::SetModuleAPI(exports, "getAuthenticationParam", DeviceManagerModule::GetAuthenticationParamSync); JSI::SetModuleAPI(exports, "on", DeviceManagerModule::JsOn); JSI::SetModuleAPI(exports, "off", DeviceManagerModule::JsOff); - JSI::SetModuleAPI(exports, "GetLocalDeviceInfoSync", DeviceManagerModule::GetLocalDeviceInfoSync); - JSI::SetModuleAPI(exports, "UnAuthenticateDevice", DeviceManagerModule::UnAuthenticateDevice); + JSI::SetModuleAPI(exports, "getLocalDeviceInfoSync", DeviceManagerModule::GetLocalDeviceInfoSync); + JSI::SetModuleAPI(exports, "unAuthenticateDevice", DeviceManagerModule::UnAuthenticateDevice); } } -- Gitee From a2298ccedaa93b65e2ab2f62083e26ebe9e5f22f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Convert=2EToInt32=28=E9=98=BF=E4=BC=A6=29?= <619269320@qq.com> Date: Wed, 16 Mar 2022 03:46:06 +0000 Subject: [PATCH 14/19] =?UTF-8?q?!39=20fix:=E4=BA=8C=E6=AC=A1=E4=BB=A3?= =?UTF-8?q?=E7=A0=81=E8=A7=84=E8=8C=83=E5=8C=96=E6=95=B4=E6=94=B9=20*=20fi?= =?UTF-8?q?x:=E4=BB=A3=E7=A0=81=E4=B8=89=E6=AC=A1=E4=BB=A3=E7=A0=81?= =?UTF-8?q?=E8=A7=84=E8=8C=83=E5=8C=96=E6=95=B4=E6=94=B9=20*=20fix:?= =?UTF-8?q?=E4=BA=8C=E6=AC=A1=E4=BB=A3=E7=A0=81=E8=A7=84=E8=8C=83=E4=BF=AE?= =?UTF-8?q?=E6=94=B9?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../native_cpp/include/device_manager.h | 4 +- .../native_cpp/include/device_manager_impl.h | 2 +- .../kits/js/include/native_devicemanager_js.h | 5 +- .../kits/js/src/native_devicemanager_js.cpp | 90 +++++++++---------- 4 files changed, 46 insertions(+), 55 deletions(-) diff --git a/interfaces_mini/inner_kits/native_cpp/include/device_manager.h b/interfaces_mini/inner_kits/native_cpp/include/device_manager.h index 5a75aac6c..c2d27b166 100644 --- a/interfaces_mini/inner_kits/native_cpp/include/device_manager.h +++ b/interfaces_mini/inner_kits/native_cpp/include/device_manager.h @@ -19,10 +19,8 @@ #include #include #include - -#include "device_manager_callback.h" #include "dm_subscribe_info.h" - +#include "device_manager_callback.h" namespace OHOS { namespace DistributedHardware { class DeviceManager { diff --git a/interfaces_mini/inner_kits/native_cpp/include/device_manager_impl.h b/interfaces_mini/inner_kits/native_cpp/include/device_manager_impl.h index b26dfc5fa..64d1982e5 100644 --- a/interfaces_mini/inner_kits/native_cpp/include/device_manager_impl.h +++ b/interfaces_mini/inner_kits/native_cpp/include/device_manager_impl.h @@ -26,7 +26,7 @@ namespace OHOS { namespace DistributedHardware { class DeviceManagerImpl : public DeviceManager { #define DEVICEMANAGER_MESSAGE_FAILED (-1) -DECLARE_SINGLE_INSTANCE(DeviceManagerImpl); +DECLARE_SINGLE_INSTANCE(DeviceManagerImpl); public: virtual int32_t InitDeviceManager(const std::string &pkgName, std::shared_ptr dmInitCallback) override; diff --git a/interfaces_mini/kits/js/include/native_devicemanager_js.h b/interfaces_mini/kits/js/include/native_devicemanager_js.h index 0923117eb..de8469189 100644 --- a/interfaces_mini/kits/js/include/native_devicemanager_js.h +++ b/interfaces_mini/kits/js/include/native_devicemanager_js.h @@ -125,7 +125,7 @@ private: std::string bundleName_; }; -class DeviceManagerModule final : public MemoryHeap,DmNativeEvent { +class DeviceManagerModule final : public MemoryHeap, DmNativeEvent { public: explicit DeviceManagerModule(); virtual ~DeviceManagerModule(); @@ -161,7 +161,8 @@ public: static void JsToDmBuffer(const JSIValue &object, const std::string &fieldStr, uint8_t **bufferPtr, int32_t &bufferLen); static void JsToDmAuthInfo(const JSIValue &object, std::string &extra); - static void JsToDmAppImageInfoAndDmExtra(const JSIValue &object, OHOS::DistributedHardware::DmAppImageInfo& appImageInfo, + static void JsToDmAppImageInfoAndDmExtra(const JSIValue &object, + OHOS::DistributedHardware::DmAppImageInfo& appImageInfo, std::string &extra, int32_t &authType); static void JsToDmDeviceInfo(const JSIValue &object, OHOS::DistributedHardware::DmDeviceInfo& info); static int32_t JsToDmSubscribeInfo(const JSIValue &object, OHOS::DistributedHardware::DmSubscribeInfo& info); diff --git a/interfaces_mini/kits/js/src/native_devicemanager_js.cpp b/interfaces_mini/kits/js/src/native_devicemanager_js.cpp index 5c0cbc447..c3ac92d6e 100644 --- a/interfaces_mini/kits/js/src/native_devicemanager_js.cpp +++ b/interfaces_mini/kits/js/src/native_devicemanager_js.cpp @@ -67,7 +67,6 @@ DeviceManagerModule *DeviceManagerModule::GetDeviceManagerJSI(std::string &bundl return iter->second; } - DeviceManagerModule::DeviceManagerModule() : DmNativeEvent() { LOGI("new DeviceManagerModule is success"); @@ -310,7 +309,7 @@ void DeviceManagerModule::OnAuthResult(const std::string &deviceId, const std::s LOGI("OnAuthResult success"); JSI::SetStringProperty(successOne, "deviceId", deviceId.c_str()); JSIValue param[1] = {successOne}; - AuthFuncParams* params =new AuthFuncParams(); + AuthFuncParams* params = new AuthFuncParams(); params->handlerRef = success; params->thisVarRef_ = thisVar; params->args = param; @@ -322,7 +321,7 @@ void DeviceManagerModule::OnAuthResult(const std::string &deviceId, const std::s JSI::SetNumberProperty(errOne, "code", (double)status); JSI::SetNumberProperty(errTwo, "reason", (double)reason); JSIValue param[2] = {errOne, errTwo}; - AuthFuncParams* params =new AuthFuncParams(); + AuthFuncParams* params = new AuthFuncParams(); params->handlerRef = fail; params->thisVarRef_ = thisVar; params->args = param; @@ -351,7 +350,7 @@ void DeviceManagerModule::OnVerifyResult(const std::string &deviceId, int32_t re JSI::SetStringProperty(successOne, "deviceId", deviceId.c_str()); JSI::SetStringProperty(successTwo, "level", flag.c_str()); JSIValue param[2] = {successOne, successTwo}; - AuthFuncParams* params =new AuthFuncParams(); + AuthFuncParams* params = new AuthFuncParams(); params->handlerRef = success; params->thisVarRef_ = thisVar; params->args = param; @@ -362,9 +361,9 @@ void DeviceManagerModule::OnVerifyResult(const std::string &deviceId, int32_t re LOGI("OnVerifyResult failed"); JSI::SetNumberProperty(errOne, "code", (double)resultCode); JSIValue param[1] = {errOne}; - AuthFuncParams* params =new AuthFuncParams(); + AuthFuncParams* params = new AuthFuncParams(); params->handlerRef = fail; - params->thisVarRef_ = thisVar; + params->thisVarRef_ = thisVar; params->args = param; params->argsSize = DM_JSI_ARGS_ONE; LOGI("OnVerifyResult FailCallBack in."); @@ -426,7 +425,7 @@ void DeviceManagerModule::DmAuthParamToJsAuthParamy(const DmAuthParam &authParam JSIValue appIconBuffer = JSI::CreateArrayBuffer(appIconLen, appIcon); if (appIcon != nullptr && memcpy_s(appIcon, appIconLen, reinterpret_cast(authParam.imageinfo.GetAppIcon()), - appIconLen) == 0) { + appIconLen) == 0) { JSIValue appIconArray = JSI::CreateTypedArray(TypedArrayType::JSI_UINT8_ARRAY, appIconLen, appIconBuffer, 0); JSI::SetNamedProperty(paramResult, "appIcon", appIconArray); @@ -440,8 +439,9 @@ void DeviceManagerModule::DmAuthParamToJsAuthParamy(const DmAuthParam &authParam if (appThumbnail != nullptr && memcpy_s(appThumbnail, appThumbnailLen, reinterpret_cast(authParam.imageinfo.GetAppThumbnail()), appThumbnailLen) == 0) { JSIValue appThumbnailArray = JSI::CreateTypedArray(TypedArrayType::JSI_UINT8_ARRAY, - appThumbnailLen, appThumbnailBuffer, 0); - JSI::SetNamedProperty(paramResult,"appThumbnail", appThumbnailArray); + appThumbnailLen, + appThumbnailBuffer, 0); + JSI::SetNamedProperty(paramResult, "appThumbnail", appThumbnailArray); } } } @@ -503,8 +503,14 @@ int32_t DeviceManagerModule::JsToDmSubscribeInfo(const JSIValue &object, DmSubsc void DeviceManagerModule::JsToDmDeviceInfo(const JSIValue &object, DmDeviceInfo &info) { - strcpy_s(info.deviceId, DM_MAX_DEVICE_ID_LEN, JsObjectToString(object, "deviceId")); - strcpy_s(info.deviceName, DM_MAX_DEVICE_NAME_LEN, JsObjectToString(object, "deviceName")); + int ret = strcpy_s(info.deviceId, DM_MAX_DEVICE_ID_LEN, JsObjectToString(object, "deviceId")); + if (ret != DM_OK) { + LOGE("JsToDmDeviceInfo error: copy deviceId failed"); + } + ret = strcpy_s(info.deviceName, DM_MAX_DEVICE_NAME_LEN, JsObjectToString(object, "deviceName")); + if (ret != DM_OK) { + LOGE("JsToDmDeviceInfo error: copy deviceName failed"); + } uint16_t deviceTypeId = -1; deviceTypeId = (uint16_t)JsObjectToInt(object, "deviceTypeId"); info.deviceTypeId = deviceTypeId; @@ -549,20 +555,17 @@ void DeviceManagerModule::JsToDmBuffer(const JSIValue &object, const std::string &fieldStr, uint8_t **bufferPtr, int32_t &bufferLen) { LOGI("JsToDmBuffer in."); - JSIValue field = JSI::GetNamedProperty(object, fieldStr.c_str()); if (field == JSI::CreateUndefined() || field == JSI::CreateNull()) { LOGE("devicemanager JSI js to str no property: %s", fieldStr.c_str()); return; } - OHOS::ACELite::TypedArrayType type = TypedArrayType::JSI_UINT8_ARRAY; size_t length = 0; JSIValue buffer = nullptr; size_t offset = 0; uint8_t *data = nullptr; data = JSI::GetTypedArrayInfo(field, type, length, buffer, offset); - if (type != TypedArrayType::JSI_UINT8_ARRAY || length == 0 || data == nullptr) { LOGE("Invaild AppIconInfo"); return; @@ -601,22 +604,18 @@ void DeviceManagerModule::JsToJsonObject(const JSIValue &object, JSIValue jsProValue = nullptr; for (uint32_t index = 0; index < jsProCount; index++) { jsProName = JSI::GetPropertyByIndex(jsProNameList, index); - std::string strProName = JSI::ValueToString(jsProName); jsProValue = JSI::GetNamedProperty(jsonField, strProName.c_str()); - if (JSI::ValueIsString(jsProValue)) { std::string natValue = JSI::ValueToString(jsProValue); LOGI("Property name=%s, string, value=%s", strProName.c_str(), natValue.c_str()); jsonObj[strProName] = natValue; } - if (JSI::ValueIsBoolean(jsProValue)) { bool elementValue = JSI::ValueToBoolean(jsProValue); LOGI("Property name=%s, boolean, value=%d.", strProName.c_str(), elementValue); jsonObj[strProName] = elementValue; } - if (JSI::ValueIsNumber(jsProValue)) { int32_t elementValue = 0; elementValue = (int32_t)JSI::ValueToNumber(jsProValue); @@ -655,7 +654,7 @@ void DeviceManagerModule::CreateDmCallback(std::string &bundleName, std::string auto callback = std::make_shared(bundleName); std::string extra = ""; int32_t ret = OHOS::DistributedHardware::DeviceManager::GetInstance().RegisterDevStateCallback( - bundleName, extra, callback); + bundleName, extra, callback); if (ret != 0) { LOGE("RegisterDevStateCallback failed for bunderName %s", bundleName.c_str()); return; @@ -685,7 +684,7 @@ void DeviceManagerModule::CreateDmCallback(std::string &bundleName, std::string if (iter == g_dmfaCallbackMap.end()) { auto callback = std::make_shared(bundleName); int32_t ret = OHOS::DistributedHardware::DeviceManager::GetInstance().RegisterDeviceManagerFaCallback( - bundleName, callback); + bundleName, callback); if (ret != 0) { LOGE("RegisterDeviceManagerFaCallback failed for bunderName %s", bundleName.c_str()); return; @@ -734,7 +733,8 @@ void DeviceManagerModule::ReleaseDmCallback(std::string &bundleName, std::string LOGE("cannot find dmFaCallback for bunderName %s", bundleName.c_str()); return; } - int32_t ret = OHOS::DistributedHardware::DeviceManager::GetInstance().UnRegisterDeviceManagerFaCallback(bundleName); + int32_t ret = OHOS::DistributedHardware::DeviceManager::GetInstance().UnRegisterDeviceManagerFaCallback( + bundleName); if (ret != 0) { LOGE("RegisterDevStateCallback failed for bunderName %s", bundleName.c_str()); return; @@ -821,10 +821,9 @@ JSIValue DeviceManagerModule::SetUserOperationSync(const JSIValue thisVal, const int32_t ret = OHOS::DistributedHardware::DeviceManager::GetInstance().SetUserOperation(bundleName, action); if (ret != 0) { LOGE("SetUserOperation for bunderName %s failed, ret %d", - bundleName.c_str(), ret); + bundleName.c_str(), ret); return JSI::CreateNull(); } - return JSI::CreateNull(); } @@ -853,10 +852,11 @@ JSIValue DeviceManagerModule::GetTrustedDeviceListSync(const JSIValue thisVal, c std::vector devList; std::string bundleName = GetJSIAppBundleName(); - int32_t ret = OHOS::DistributedHardware::DeviceManager::GetInstance().GetTrustedDeviceList(bundleName, extra, devList); + int32_t ret = OHOS::DistributedHardware::DeviceManager::GetInstance().GetTrustedDeviceList( + bundleName, extra, devList); if (ret != 0) { LOGE("GetTrustedDeviceList for bunderName %s failed, ret %d", - bundleName.c_str(), ret); + bundleName.c_str(), ret); return array; } if (devList.size() > 0) { @@ -908,12 +908,8 @@ JSIValue DeviceManagerModule::StartDeviceDiscoverSync(const JSIValue thisVal, co } LOGI("subInfo %d , %d, %d, %d, %d , %d, %s", subInfo.subscribeId, - subInfo.mode, - subInfo.medium, - subInfo.freq, - subInfo.isSameAccount, - subInfo.isWakeRemote, - subInfo.capability); + subInfo.mode, subInfo.medium, subInfo.freq, subInfo.isSameAccount, + subInfo.isWakeRemote, subInfo.capability); std::string extra = ""; int32_t ret = OHOS::DistributedHardware::DeviceManager::GetInstance().StartDeviceDiscovery(bundleName, subInfo, extra, discoverCallback); @@ -931,26 +927,24 @@ JSIValue DeviceManagerModule::StopDeviceDiscoverSync(const JSIValue thisVal, con std::string bundleName = GetJSIAppBundleName(); if (argsSize < 1) { - LOGE("1 argument is required."); - return JSI::CreateNull(); + LOGE("1 argument is required."); + return JSI::CreateNull(); } if (!JSI::ValueIsNumber(args[0])) { - LOGE("a Number is required."); - return JSI::CreateNull(); + LOGE("a Number is required."); + return JSI::CreateNull(); } int16_t subscribeId = 0; subscribeId = static_cast(JSI::ValueToNumber(args[0])); - LOGI("subscribeId %d ", subscribeId); - + LOGI("subscribeId %d", subscribeId); int32_t ret = OHOS::DistributedHardware::DeviceManager::GetInstance().StopDeviceDiscovery(bundleName, subscribeId); if (ret != 0) { LOGE("StopDeviceDiscovery for bunderName %s failed, ret %d", bundleName.c_str(), ret); return JSI::CreateNull(); } - return JSI::CreateNull(); } @@ -988,14 +982,13 @@ JSIValue DeviceManagerModule::AuthenticateDevice(const JSIValue thisVal, const J JsToDmDeviceInfo(args[0], deviceInfo); LOGI("deviceInfo %s , %s, %d", deviceInfo.deviceId, - deviceInfo.deviceName, - deviceInfo.deviceTypeId); + deviceInfo.deviceName, deviceInfo.deviceTypeId); DmAppImageInfo appImageInfo(nullptr, 0, nullptr, 0); std::string extra; JsToDmAppImageInfoAndDmExtra(args[1], appImageInfo, extra, authAsyncCallbackInfo_.authType); - int32_t ret = OHOS::DistributedHardware::DeviceManager::GetInstance().AuthenticateDevice(bundleName, 1, deviceInfo, - extra, authCallback); + int32_t ret = OHOS::DistributedHardware::DeviceManager::GetInstance().AuthenticateDevice( + bundleName, 1, deviceInfo, extra, authCallback); if (ret != 0) { LOGE("AuthenticateDevice for bunderName %s failed, ret %d", bundleName.c_str(), ret); @@ -1164,13 +1157,16 @@ char *DeviceManagerModule::GetJSIAppBundleName() JSAbility *g_targetJSAbility = new JSAbility(); const char *pname = g_targetJSAbility->GetPackageName(); char *packageName = new char[strlen(pname)+1]; - strcpy_s(packageName, strlen(pname)+1, pname); + int ret = strcpy_s(packageName, strlen(pname)+1, pname); + if (ret != DM_OK) { + LOGE("GetJSIAppBundleName error: copy BundleName failed"); + } delete(g_targetJSAbility); return packageName; } void InitDeviceManagerModule(JSIValue exports) -{ +{ JSI::SetModuleAPI(exports, "createDeviceManager", DeviceManagerModule::CreateDeviceManager); JSI::SetModuleAPI(exports, "getTrustedDeviceListSync", DeviceManagerModule::GetTrustedDeviceListSync); JSI::SetModuleAPI(exports, "release", DeviceManagerModule::ReleaseDeviceManager); @@ -1185,9 +1181,5 @@ void InitDeviceManagerModule(JSIValue exports) JSI::SetModuleAPI(exports, "getLocalDeviceInfoSync", DeviceManagerModule::GetLocalDeviceInfoSync); JSI::SetModuleAPI(exports, "unAuthenticateDevice", DeviceManagerModule::UnAuthenticateDevice); } - -} } - - - +} \ No newline at end of file -- Gitee From af8cd48fd8b18c4f78757330fc806f2b872e65cd Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=85=9A=E6=B3=BD=E8=BE=89?= Date: Wed, 16 Mar 2022 03:46:54 +0000 Subject: [PATCH 15/19] =?UTF-8?q?!38=20codeCheck=E4=BF=AE=E6=94=B9=20*=20c?= =?UTF-8?q?odeCheck=E4=BF=AE=E6=94=B9?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../include/dependency/mini/dm_mutex.h | 2 -- .../include/dependency/mini/dm_thread.h | 6 ++--- .../src/config/mini/dm_config_manager.cpp | 2 -- .../src/config/mini/pin_auth.cpp | 1 - .../src/dependency/mini/dm_mutex.cpp | 25 +++++++++---------- .../src/dependency/mini/dm_thread.cpp | 5 ++-- .../src/dependency/timer/mini/dm_timer.cpp | 2 -- .../devicestate/dm_device_state_manager.cpp | 4 --- 8 files changed, 16 insertions(+), 31 deletions(-) diff --git a/services/devicemanagerservice/include/dependency/mini/dm_mutex.h b/services/devicemanagerservice/include/dependency/mini/dm_mutex.h index 7fe0aac3f..209d405e9 100644 --- a/services/devicemanagerservice/include/dependency/mini/dm_mutex.h +++ b/services/devicemanagerservice/include/dependency/mini/dm_mutex.h @@ -20,7 +20,6 @@ namespace OHOS { namespace DistributedHardware { - class DmMutex { public: DmMutex(); @@ -28,7 +27,6 @@ public: private: pthread_mutex_t lock_; }; - } // namespace DistributedHardware } // namespace OHOS #endif // OHOS_DM_MUTEX_H \ No newline at end of file diff --git a/services/devicemanagerservice/include/dependency/mini/dm_thread.h b/services/devicemanagerservice/include/dependency/mini/dm_thread.h index 5dc89f4a4..bc980d9d5 100644 --- a/services/devicemanagerservice/include/dependency/mini/dm_thread.h +++ b/services/devicemanagerservice/include/dependency/mini/dm_thread.h @@ -25,9 +25,8 @@ namespace OHOS { namespace DistributedHardware { - class DmThread { -typedef void (*funcstr)(std::map>, DmDeviceInfo); +using funcstr = void (*)(std::map>, DmDeviceInfo); public: DmThread(funcstr funcname,\ std::map> parameter1,\ @@ -36,7 +35,7 @@ public: void DmCreatThread(); private: - struct PthreadCallbackParameter{ + struct PthreadCallbackParameter { std::map> member1; DmDeviceInfo member2; }; @@ -45,7 +44,6 @@ private: static DmDeviceInfo parameter2_; PthreadCallbackParameter parameterGroup_; }; - } // namespace DistributedHardware } // namespace OHOS #endif // OHOS_DM_THREAD_H diff --git a/services/devicemanagerservice/src/config/mini/dm_config_manager.cpp b/services/devicemanagerservice/src/config/mini/dm_config_manager.cpp index 63bc1df57..f3cdba395 100644 --- a/services/devicemanagerservice/src/config/mini/dm_config_manager.cpp +++ b/services/devicemanagerservice/src/config/mini/dm_config_manager.cpp @@ -19,8 +19,6 @@ namespace OHOS { namespace DistributedHardware { - - DmConfigManager &DmConfigManager::GetInstance() { static DmConfigManager instance; diff --git a/services/devicemanagerservice/src/config/mini/pin_auth.cpp b/services/devicemanagerservice/src/config/mini/pin_auth.cpp index 37a6b8c3f..f832a9d84 100644 --- a/services/devicemanagerservice/src/config/mini/pin_auth.cpp +++ b/services/devicemanagerservice/src/config/mini/pin_auth.cpp @@ -50,6 +50,5 @@ int32_t PinAuth::VerifyAuthentication(std::string &authToken, const std::string LOGI("VerifyAuthentication end"); return DM_OK; } - } // namespace DistributedHardware } // namespace OHOS diff --git a/services/devicemanagerservice/src/dependency/mini/dm_mutex.cpp b/services/devicemanagerservice/src/dependency/mini/dm_mutex.cpp index 8e27b3618..c8bfdfea3 100644 --- a/services/devicemanagerservice/src/dependency/mini/dm_mutex.cpp +++ b/services/devicemanagerservice/src/dependency/mini/dm_mutex.cpp @@ -13,20 +13,20 @@ * limitations under the License. */ -#include "dm_mutex.h" -#include "dm_log.h" #include +#include "dm_log.h" +#include "dm_mutex.h" + namespace OHOS { -namespace DistributedHardware { - +namespace DistributedHardware { DmMutex::DmMutex() { -uint32_t ret = pthread_mutex_init(&lock_, NULL); -if (ret != 0) { - LOGE("init mutex lock failed: %d.",ret); -} -pthread_mutex_lock(&lock_); + uint32_t ret = pthread_mutex_init(&lock_, NULL); + if (ret != 0) { + LOGE("init mutex lock failed: %d.", ret); + } + pthread_mutex_lock(&lock_); } DmMutex::~DmMutex() @@ -34,9 +34,8 @@ DmMutex::~DmMutex() pthread_mutex_unlock(&lock_); uint32_t ret = pthread_mutex_destroy(&lock_); if (ret != 0) { - LOGI("destroy mutex lock failed: %d.",ret); + LOGI("destroy mutex lock failed: %d.", ret); } } - -}// namespace DistributedHardware -}// namespace OHOS \ No newline at end of file +} // namespace DistributedHardware +} // namespace OHOS \ No newline at end of file diff --git a/services/devicemanagerservice/src/dependency/mini/dm_thread.cpp b/services/devicemanagerservice/src/dependency/mini/dm_thread.cpp index 507689ab2..ff2bd4e91 100644 --- a/services/devicemanagerservice/src/dependency/mini/dm_thread.cpp +++ b/services/devicemanagerservice/src/dependency/mini/dm_thread.cpp @@ -16,7 +16,7 @@ namespace OHOS { namespace DistributedHardware { -typedef void (*funcstr)(std::map>, DmDeviceInfo); +using funcstr = void (*)(std::map>, DmDeviceInfo); funcstr DmThread::funcName_; std::map> DmThread::parameter1_ = {}; @@ -35,8 +35,7 @@ DmThread::DmThread(funcstr funcname,\ void* DmThread::PthreadDeviceStart(void* parameterInfo) { - PthreadCallbackParameter *parameterStruct; - parameterStruct = static_cast(parameterInfo); + PthreadCallbackParameter *parameterStruct = static_cast(parameterInfo); funcName_(parameterStruct->member1, parameterStruct->member2); return nullptr; } diff --git a/services/devicemanagerservice/src/dependency/timer/mini/dm_timer.cpp b/services/devicemanagerservice/src/dependency/timer/mini/dm_timer.cpp index b14a07695..b224c7968 100644 --- a/services/devicemanagerservice/src/dependency/timer/mini/dm_timer.cpp +++ b/services/devicemanagerservice/src/dependency/timer/mini/dm_timer.cpp @@ -54,7 +54,6 @@ void DmTimer::Stop(int32_t code) void DmTimer::WaitForTimeout() { - } int32_t DmTimer::CreateTimeFd() @@ -64,7 +63,6 @@ int32_t DmTimer::CreateTimeFd() void DmTimer::Release() { - } std::string DmTimer::GetTimerName() diff --git a/services/devicemanagerservice/src/devicestate/dm_device_state_manager.cpp b/services/devicemanagerservice/src/devicestate/dm_device_state_manager.cpp index 5fefe6962..fdba2a0d3 100755 --- a/services/devicemanagerservice/src/devicestate/dm_device_state_manager.cpp +++ b/services/devicemanagerservice/src/devicestate/dm_device_state_manager.cpp @@ -88,7 +88,6 @@ int32_t DmDeviceStateManager::UnRegisterProfileListener(const std::string &pkgNa profileAdapter->UnRegisterProfileListener(pkgName); } { - #if (defined(__LINUX__) || defined(__LITEOS_A__)) std::lock_guard mutexLock(remoteDeviceInfosMutex_); #else @@ -255,7 +254,6 @@ void DmDeviceStateManager::RegisterOffLineTimer(const DmDeviceInfo &deviceInfo) return; } LOGI("Register OffLine Timer with device: %s", GetAnonyString(deviceId).c_str()); - #if (defined(__LINUX__) || defined(__LITEOS_A__)) std::lock_guard mutexLock(timerMapMutex_); #else @@ -279,8 +277,6 @@ void DmDeviceStateManager::StartOffLineTimer(const DmDeviceInfo &deviceInfo) LOGE("fail to get udid by networkId"); return; } - - LOGI("start offline timer with device: %s", GetAnonyString(deviceinfoMap_[deviceInfo.deviceId]).c_str()); #if (defined(__LINUX__) || defined(__LITEOS_A__)) std::lock_guard mutexLock(timerMapMutex_); -- Gitee From ff3a2b905348c33adf35e80435cf18e45460f621 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=86=AF=E4=BF=8A=E9=9D=92?= Date: Wed, 16 Mar 2022 07:37:36 +0000 Subject: [PATCH 16/19] =?UTF-8?q?!40=20=E6=9B=B4=E6=96=B0=E5=AE=9A?= =?UTF-8?q?=E6=97=B6=E5=99=A8=20*=20update=20dm=5Ftimer?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../include/dependency/timer/dm_timer.h | 5 +- .../src/dependency/timer/mini/dm_timer.cpp | 73 ++++++++++++++----- 2 files changed, 60 insertions(+), 18 deletions(-) diff --git a/services/devicemanagerservice/include/dependency/timer/dm_timer.h b/services/devicemanagerservice/include/dependency/timer/dm_timer.h index 1c8bd1680..361bbbc70 100644 --- a/services/devicemanagerservice/include/dependency/timer/dm_timer.h +++ b/services/devicemanagerservice/include/dependency/timer/dm_timer.h @@ -61,12 +61,15 @@ private: TimeoutHandle mHandle_; void *mHandleData_; int32_t mTimeFd_[2]; -#if (defined(__LINUX__) || defined(__LITEOS_A__)) +#if (defined(__LITEOS_M__)) + void *g_timerId = NULL; +#else struct epoll_event mEv_; struct epoll_event mEvents_[MAX_EVENTS]; int32_t mEpFd_; std::thread mThread_; #endif + std::string mTimerName_; }; } // namespace DistributedHardware diff --git a/services/devicemanagerservice/src/dependency/timer/mini/dm_timer.cpp b/services/devicemanagerservice/src/dependency/timer/mini/dm_timer.cpp index b224c7968..6406f57af 100644 --- a/services/devicemanagerservice/src/dependency/timer/mini/dm_timer.cpp +++ b/services/devicemanagerservice/src/dependency/timer/mini/dm_timer.cpp @@ -14,6 +14,8 @@ */ #include "dm_timer.h" +#include "cmsis_os2.h" +#include "securec.h" namespace OHOS { namespace DistributedHardware { @@ -26,8 +28,9 @@ DmTimer::DmTimer(const std::string &name) LOGI("DmTimer name is null"); return; } - - LOGI("DmTimer %s Construct", name.c_str()); + mStatus_ = DmTimerStatus::DM_STATUS_INIT; + mTimeOutSec_ = 0; + mTimerName_ = name; } DmTimer::~DmTimer() @@ -39,30 +42,66 @@ DmTimer::~DmTimer() LOGI("DmTimer %s Destroy in", mTimerName_.c_str()); } -DmTimerStatus DmTimer::Start(uint32_t timeOut, TimeoutHandle handle, void *data) -{ - LOGI("DmTimer start timeout(%d)", timeOut); - mStatus_ = DmTimerStatus::DM_STATUS_RUNNING; - return mStatus_; -} +struct DmTimst { + TimeoutHandle handle; + DmTimer *dmtimer; + void *data; +}; -void DmTimer::Stop(int32_t code) +static void handler(void *data) { - LOGI("DmTimer Stop code (%d)", code); - return; + struct DmTimst *myTimer = (struct DmTimst *)data; + myTimer->handle(myTimer->data, *(myTimer->dmtimer)); } -void DmTimer::WaitForTimeout() +DmTimerStatus DmTimer::Start(uint32_t timeOut, TimeoutHandle handle, void *data) { -} + if (mTimerName_.empty() || handle == nullptr || data == nullptr) { + LOGI("DmTimer is not init or param empty"); + return DmTimerStatus::DM_STATUS_FINISH; + } + LOGI("DmTimer %s start timeout(%d)", mTimerName_.c_str(), timeOut); + if (mStatus_ != DmTimerStatus::DM_STATUS_INIT) { + return DmTimerStatus::DM_STATUS_BUSY; + } -int32_t DmTimer::CreateTimeFd() -{ - return 0; + static struct DmTimst myTimer = { + .handle = handle, + .dmtimer = this, + .data = data, + }; + mTimeOutSec_ = timeOut; + + void *id = osTimerNew((osTimerFunc_t)handler, osTimerType_t::osTimerOnce, (void *)&myTimer, NULL); + if (id != NULL) { + LOGI("Get name of a timer success "); + } else { + LOGI("Get name of a timer failed"); + return DmTimerStatus::DM_STATUS_CREATE_ERROR; + } + + g_timerId = id; + int stOk = osTimerStart(g_timerId, timeOut * osKernelGetTickFreq()); + if (stOk == 0) { + LOGI("DmTimer %s start timer at (%d)s", mTimerName_.c_str(), mTimeOutSec_); + mStatus_ = DmTimerStatus::DM_STATUS_RUNNING; + } else { + LOGI("Start a timer failed"); + (void)osTimerDelete(g_timerId); + } + + return mStatus_; } -void DmTimer::Release() +void DmTimer::Stop(int32_t code) { + LOGI("DmTimer Stop code (%d)", code); + if (g_timerId != NULL) { + osTimerDelete(g_timerId); + g_timerId = NULL; + } + LOGI("DmTimer %s end timer at (%d)s", mTimerName_.c_str(), mTimeOutSec_); + return; } std::string DmTimer::GetTimerName() -- Gitee From eec975e9c0c2c60ffbd9683c4cf47c3fc9fdd092 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=85=9A=E6=B3=BD=E8=BE=89?= Date: Wed, 16 Mar 2022 08:00:20 +0000 Subject: [PATCH 17/19] =?UTF-8?q?!42=20=E7=94=A8=E6=9D=A5=E5=8C=BA?= =?UTF-8?q?=E5=88=86L0=E3=80=81L1=E3=80=81L2=E7=9A=84=E5=AE=8F=E5=AE=9A?= =?UTF-8?q?=E4=B9=89=E4=BF=AE=E6=94=B9=20*=20=E7=94=A8=E6=9D=A5=E5=8C=BA?= =?UTF-8?q?=E5=88=86L0=E3=80=81L1=E3=80=81L2=E7=9A=84=E5=AE=8F=E5=AE=9A?= =?UTF-8?q?=E4=B9=89=E4=BF=AE=E6=94=B9=20*=20=E7=94=A8=E6=9D=A5=E5=8C=BA?= =?UTF-8?q?=E5=88=86L0=E3=80=81L1=E3=80=81L2=E7=9A=84=E5=AE=8F=E5=AE=9A?= =?UTF-8?q?=E4=B9=89=E4=BF=AE=E6=94=B9?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../include/config/dm_config_manager.h | 4 +- .../include/device_manager_service_listener.h | 4 +- .../devicestate/dm_device_state_manager.h | 8 ++-- .../src/dependency/mini/dm_mutex.cpp | 2 +- .../dependency/softbus/softbus_connector.cpp | 45 +++++++++---------- .../src/device_manager_service.cpp | 6 +-- .../devicestate/dm_device_state_manager.cpp | 30 ++++++------- utils/src/dm_random.cpp | 6 +-- 8 files changed, 52 insertions(+), 53 deletions(-) diff --git a/services/devicemanagerservice/include/config/dm_config_manager.h b/services/devicemanagerservice/include/config/dm_config_manager.h index d2082a7b7..266e0044a 100644 --- a/services/devicemanagerservice/include/config/dm_config_manager.h +++ b/services/devicemanagerservice/include/config/dm_config_manager.h @@ -19,7 +19,7 @@ #include #include #include -#if (defined(__LINUX__) || defined(__LITEOS_A__)) +#if !defined(__LITEOS_M__) #include #endif #include @@ -68,7 +68,7 @@ private: DmConfigManager(); private: -#if (defined(__LINUX__) || defined(__LITEOS_A__)) +#if !defined(__LITEOS_M__) std::mutex authAdapterMutex_; std::mutex cryptoAdapterMutex_; std::mutex decisionAdapterMutex_; diff --git a/services/devicemanagerservice/include/device_manager_service_listener.h b/services/devicemanagerservice/include/device_manager_service_listener.h index 0c989491f..baf81e7ee 100644 --- a/services/devicemanagerservice/include/device_manager_service_listener.h +++ b/services/devicemanagerservice/include/device_manager_service_listener.h @@ -20,7 +20,7 @@ #include #include "dm_device_info.h" -#if (defined(__LINUX__) || defined(__LITEOS_A__)) +#if !defined(__LITEOS_M__) #include "ipc_notify_dmfa_result_req.h" #include "ipc_server_listener.h" #endif @@ -41,7 +41,7 @@ public: void OnFaCall(std::string &pkgName, std::string ¶mJson); private: -#if (defined(__LINUX__) || defined(__LITEOS_A__)) +#if !defined(__LITEOS_M__) IpcServerListener ipcServerListener_; #endif }; diff --git a/services/devicemanagerservice/include/devicestate/dm_device_state_manager.h b/services/devicemanagerservice/include/devicestate/dm_device_state_manager.h index c2dcd3cfb..b2b3f5b47 100755 --- a/services/devicemanagerservice/include/devicestate/dm_device_state_manager.h +++ b/services/devicemanagerservice/include/devicestate/dm_device_state_manager.h @@ -18,10 +18,10 @@ #include #include -#if (defined(__LINUX__) || defined(__LITEOS_A__)) -#include -#else +#if defined(__LITEOS_M__) #include "dm_mutex.h" +#else +#include #endif #include "device_manager_service_listener.h" #include "dm_adapter_manager.h" @@ -57,7 +57,7 @@ public: private: std::string profileSoName_; -#if (defined(__LINUX__) || defined(__LITEOS_A__)) +#if !defined(__LITEOS_M__) std::mutex timerMapMutex_; std::mutex remoteDeviceInfosMutex_; #endif diff --git a/services/devicemanagerservice/src/dependency/mini/dm_mutex.cpp b/services/devicemanagerservice/src/dependency/mini/dm_mutex.cpp index c8bfdfea3..bccb94abf 100644 --- a/services/devicemanagerservice/src/dependency/mini/dm_mutex.cpp +++ b/services/devicemanagerservice/src/dependency/mini/dm_mutex.cpp @@ -26,7 +26,7 @@ DmMutex::DmMutex() if (ret != 0) { LOGE("init mutex lock failed: %d.", ret); } - pthread_mutex_lock(&lock_); + pthread_mutex_lock(&lock_); } DmMutex::~DmMutex() diff --git a/services/devicemanagerservice/src/dependency/softbus/softbus_connector.cpp b/services/devicemanagerservice/src/dependency/softbus/softbus_connector.cpp index 25f6f4dec..b1965714e 100644 --- a/services/devicemanagerservice/src/dependency/softbus/softbus_connector.cpp +++ b/services/devicemanagerservice/src/dependency/softbus/softbus_connector.cpp @@ -17,12 +17,12 @@ #include #include -#if (defined(__LINUX__) || defined(__LITEOS_A__)) -#include -#include -#else +#if defined(__LITEOS_M__) #include "dm_mutex.h" #include "dm_thread.h" +#else +#include +#include #endif #include "dm_anonymous.h" @@ -59,11 +59,11 @@ void DeviceOnLine(std::map> DmDeviceInfo deviceInfo) { LOGI("Device on line start"); -#if (defined(__LINUX__) || defined(__LITEOS_A__)) +#if defined(__LITEOS_M__) + DmMutex lockDeviceOnLine; +#else std::mutex lockDeviceOnLine; std::lock_guard lock(lockDeviceOnLine); -#else - DmMutex lockDeviceOnLine; #endif for (auto &iter : stateCallbackMap) { iter.second->OnDeviceOnline(iter.first, deviceInfo); @@ -75,11 +75,11 @@ void DeviceOffLine(std::map> DmDeviceInfo deviceInfo) { LOGI("Device off line start"); -#if (defined(__LINUX__) || defined(__LITEOS_A__)) +#if defined(__LITEOS_M__) + DmMutex lockDeviceOffLine; +#else std::mutex lockDeviceOffLine; std::lock_guard lock(lockDeviceOffLine); -#else - DmMutex lockDeviceOffLine; #endif for (auto &iter : stateCallbackMap) { iter.second->OnDeviceOffline(iter.first, deviceInfo); @@ -120,8 +120,10 @@ int32_t SoftbusConnector::Init() dmPublishInfo.capability = DM_CAPABILITY_OSD; dmPublishInfo.capabilityData = nullptr; dmPublishInfo.dataLen = 0; - -#if (defined(__LINUX__) || defined(__LITEOS_A__)) +#if defined(__LITEOS_M__) + ret = PublishService(DM_PKG_NAME.c_str(), &dmPublishInfo, &softbusPublishCallback_); + LOGI("service publish result is : %d", ret); +#else char discoverStatus[DISCOVER_STATUS_LEN + 1] = {0}; ret = GetParameter(DISCOVER_STATUS_KEY.c_str(), "not exist", discoverStatus, DISCOVER_STATUS_LEN); if (strcmp(discoverStatus, "not exist") == 0) { @@ -149,9 +151,6 @@ int32_t SoftbusConnector::Init() ret = WatchParameter(DISCOVER_STATUS_KEY.c_str(), &SoftbusConnector::OnParameterChgCallback, nullptr); LOGI("register Watch Parameter result is : %d", ret); -#else - ret = PublishService(DM_PKG_NAME.c_str(), &dmPublishInfo, &softbusPublishCallback_); - LOGI("service publish result is : %d", ret); #endif return ret; } @@ -487,12 +486,12 @@ void SoftbusConnector::OnSoftBusDeviceOnline(NodeBasicInfo *info) DmDeviceInfo dmDeviceInfo; CovertNodeBasicInfoToDmDevice(*info, dmDeviceInfo); -#if (defined(__LINUX__) || defined(__LITEOS_A__)) - std::thread deviceOnLine(DeviceOnLine, stateCallbackMap_, dmDeviceInfo); - deviceOnLine.detach(); -#else +#if defined(__LITEOS_M__) DmThread deviceOnLine(DeviceOnLine, stateCallbackMap_, dmDeviceInfo); deviceOnLine.DmCreatThread(); +#else + std::thread deviceOnLine(DeviceOnLine, stateCallbackMap_, dmDeviceInfo); + deviceOnLine.detach(); #endif if (discoveryDeviceInfoMap_.empty()) { @@ -519,12 +518,12 @@ void SoftbusConnector::OnSoftbusDeviceOffline(NodeBasicInfo *info) } DmDeviceInfo dmDeviceInfo; CovertNodeBasicInfoToDmDevice(*info, dmDeviceInfo); -#if (defined(__LINUX__) || defined(__LITEOS_A__)) - std::thread deviceOffLine(DeviceOffLine, stateCallbackMap_, dmDeviceInfo); - deviceOffLine.detach(); -#else +#if defined(__LITEOS_M__) DmThread deviceOffLine(DeviceOffLine, stateCallbackMap_, dmDeviceInfo); deviceOffLine.DmCreatThread(); +#else + std::thread deviceOffLine(DeviceOffLine, stateCallbackMap_, dmDeviceInfo); + deviceOffLine.detach(); #endif } diff --git a/services/devicemanagerservice/src/device_manager_service.cpp b/services/devicemanagerservice/src/device_manager_service.cpp index ae5891e38..51cb6232b 100644 --- a/services/devicemanagerservice/src/device_manager_service.cpp +++ b/services/devicemanagerservice/src/device_manager_service.cpp @@ -24,7 +24,7 @@ #include "dm_log.h" #include "multiple_user_connector.h" #include "permission_manager.h" -#if (defined(__LINUX__) || defined(__LITEOS_A__)) +#if !defined(__LITEOS_M__) #include "dm_common_event_manager.h" #include "common_event_support.h" using namespace OHOS::EventFwk; @@ -37,7 +37,7 @@ IMPLEMENT_SINGLE_INSTANCE(DeviceManagerService); DeviceManagerService::~DeviceManagerService() { LOGI("DeviceManagerService destructor"); -#if (defined(__LINUX__) || defined(__LITEOS_A__)) +#if !defined(__LITEOS_M__) DmCommonEventManager &dmCommonEventManager = DmCommonEventManager::GetInstance(); if (dmCommonEventManager.UnsubscribeServiceEvent(CommonEventSupport::COMMON_EVENT_USER_STOPPED)) { LOGI("subscribe service event success"); @@ -117,7 +117,7 @@ int32_t DeviceManagerService::Init() LOGI("get current account user id success"); MultipleUserConnector::SetSwitchOldUserId(userId); } -#if (defined(__LINUX__) || defined(__LITEOS_A__)) +#if !defined(__LITEOS_M__) DmCommonEventManager &dmCommonEventManager = DmCommonEventManager::GetInstance(); CommomEventCallback callback = std::bind(&DmAuthManager::UserSwitchEventCallback, *authMgr_.get(), std::placeholders::_1); diff --git a/services/devicemanagerservice/src/devicestate/dm_device_state_manager.cpp b/services/devicemanagerservice/src/devicestate/dm_device_state_manager.cpp index fdba2a0d3..6f02cffdb 100755 --- a/services/devicemanagerservice/src/devicestate/dm_device_state_manager.cpp +++ b/services/devicemanagerservice/src/devicestate/dm_device_state_manager.cpp @@ -64,10 +64,10 @@ int32_t DmDeviceStateManager::RegisterProfileListener(const std::string &pkgName DmDeviceInfo saveInfo = info; SoftbusConnector::GetUuidByNetworkId(info.deviceId, uuid); { -#if (defined(__LINUX__) || defined(__LITEOS_A__)) - std::lock_guard mutexLock(remoteDeviceInfosMutex_); -#else +#if defined(__LITEOS_M__) DmMutex mutexLock; +#else + std::lock_guard mutexLock(remoteDeviceInfosMutex_); #endif remoteDeviceInfos_[uuid] = saveInfo; } @@ -88,10 +88,10 @@ int32_t DmDeviceStateManager::UnRegisterProfileListener(const std::string &pkgNa profileAdapter->UnRegisterProfileListener(pkgName); } { -#if (defined(__LINUX__) || defined(__LITEOS_A__)) - std::lock_guard mutexLock(remoteDeviceInfosMutex_); -#else +#if defined(__LITEOS_M__) DmMutex mutexLock; +#else + std::lock_guard mutexLock(remoteDeviceInfosMutex_); #endif if (remoteDeviceInfos_.find(std::string(info.deviceId)) != remoteDeviceInfos_.end()) { remoteDeviceInfos_.erase(std::string(info.deviceId)); @@ -201,10 +201,10 @@ void DmDeviceStateManager::OnProfileReady(const std::string &pkgName, const std: } DmDeviceInfo saveInfo; { -#if (defined(__LINUX__) || defined(__LITEOS_A__)) - std::lock_guard mutexLock(remoteDeviceInfosMutex_); -#else +#if defined(__LITEOS_M__) DmMutex mutexLock; +#else + std::lock_guard mutexLock(remoteDeviceInfosMutex_); #endif auto iter = remoteDeviceInfos_.find(deviceId); if (iter == remoteDeviceInfos_.end()) { @@ -254,10 +254,10 @@ void DmDeviceStateManager::RegisterOffLineTimer(const DmDeviceInfo &deviceInfo) return; } LOGI("Register OffLine Timer with device: %s", GetAnonyString(deviceId).c_str()); -#if (defined(__LINUX__) || defined(__LITEOS_A__)) - std::lock_guard mutexLock(timerMapMutex_); -#else +#if defined(__LITEOS_M__) DmMutex mutexLock; +#else + std::lock_guard mutexLock(timerMapMutex_); #endif deviceinfoMap_[deviceInfo.deviceId] = deviceId; auto iter = timerMap_.find(deviceId); @@ -278,10 +278,10 @@ void DmDeviceStateManager::StartOffLineTimer(const DmDeviceInfo &deviceInfo) return; } LOGI("start offline timer with device: %s", GetAnonyString(deviceinfoMap_[deviceInfo.deviceId]).c_str()); -#if (defined(__LINUX__) || defined(__LITEOS_A__)) - std::lock_guard mutexLock(timerMapMutex_); -#else +#if defined(__LITEOS_M__) DmMutex mutexLock; +#else + std::lock_guard mutexLock(timerMapMutex_); #endif for (auto &iter : timerMap_) { if (iter.first == deviceinfoMap_[deviceInfo.deviceId]) { diff --git a/utils/src/dm_random.cpp b/utils/src/dm_random.cpp index 08f61c1aa..9deb04c38 100644 --- a/utils/src/dm_random.cpp +++ b/utils/src/dm_random.cpp @@ -28,13 +28,13 @@ namespace OHOS { namespace DistributedHardware { int32_t GenRandInt(int32_t randMin, int32_t randMax) { -#if (defined(__LINUX__) || defined(__LITEOS_A__)) +#if defined(__LITEOS_M__) + return (randMin + random() % (randMax - randMin)); +#else std::random_device randDevice; std::mt19937 genRand(randDevice()); std::uniform_int_distribution disRand(randMin, randMax); return disRand(genRand); -#else - return (randMin + random() % (randMax - randMin)); #endif } -- Gitee From 4d66daa0c0a0282c8df709fa01fd8c773670eac5 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E8=94=A1=E9=98=94?= Date: Wed, 16 Mar 2022 08:01:18 +0000 Subject: [PATCH 18/19] =?UTF-8?q?!43=20service=20codecheck=E4=BF=AE?= =?UTF-8?q?=E6=94=B9=20*=20service=20codecheck=E4=BF=AE=E6=94=B9?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../native_cpp/src/device_manager_impl.cpp | 5 +-- .../include/dispatch/command_dispatch.h | 4 +- .../dispatch/get_authenticationparam_rsp.h | 41 ------------------- ...peration_req.h => get_useroperation_req.h} | 4 +- .../include/dispatch/message_def.h | 22 +++++----- .../include/dispatch/message_rsp.h | 2 - .../include/dispatch/server_stub.h | 2 - .../include/dispatch/stop_discovery_req.h | 2 - .../src/dispatch/command_dispatch.cpp | 21 +++++----- .../device_manager_service_listener_mini.cpp | 4 +- .../src/dispatch/server_stub.cpp | 8 ++-- 11 files changed, 32 insertions(+), 83 deletions(-) delete mode 100644 services/devicemanagerservice/include/dispatch/get_authenticationparam_rsp.h rename services/devicemanagerservice/include/dispatch/{set_useroperation_req.h => get_useroperation_req.h} (92%) diff --git a/interfaces_mini/inner_kits/native_cpp/src/device_manager_impl.cpp b/interfaces_mini/inner_kits/native_cpp/src/device_manager_impl.cpp index 218c1575c..a79a97134 100644 --- a/interfaces_mini/inner_kits/native_cpp/src/device_manager_impl.cpp +++ b/interfaces_mini/inner_kits/native_cpp/src/device_manager_impl.cpp @@ -21,8 +21,7 @@ #include "get_trustdevice_rsp.h" #include "start_discovery_req.h" #include "stop_discovery_req.h" -#include "set_useroperation_req.h" -#include "get_authenticationparam_rsp.h" +#include "get_useroperation_req.h" #include "authenticate_device_req.h" #include "verify_authenticate_req.h" #include "get_local_device_info_rsp.h" @@ -350,7 +349,7 @@ int32_t DeviceManagerImpl::SetUserOperation(const std::string &pkgName, int32_t return DM_INVALID_VALUE; } - std::shared_ptr req = std::make_shared(); + std::shared_ptr req = std::make_shared(); std::shared_ptr rsp = std::make_shared(); req->SetPkgName(pkgName); diff --git a/services/devicemanagerservice/include/dispatch/command_dispatch.h b/services/devicemanagerservice/include/dispatch/command_dispatch.h index f4683e737..3960e2c0c 100644 --- a/services/devicemanagerservice/include/dispatch/command_dispatch.h +++ b/services/devicemanagerservice/include/dispatch/command_dispatch.h @@ -19,12 +19,10 @@ #include #include #include -#include "single_instance.h" +#include "single_instance.h" #include "message_req.h" #include "message_rsp.h" - - namespace OHOS { namespace DistributedHardware { diff --git a/services/devicemanagerservice/include/dispatch/get_authenticationparam_rsp.h b/services/devicemanagerservice/include/dispatch/get_authenticationparam_rsp.h deleted file mode 100644 index b66e73d02..000000000 --- a/services/devicemanagerservice/include/dispatch/get_authenticationparam_rsp.h +++ /dev/null @@ -1,41 +0,0 @@ -/* - * Copyright (c) 2021 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef OHOS_DEVICE_MANAGER_GET_AUTH_PARAM_RSP_H -#define OHOS_DEVICE_MANAGER_GET_AUTH_PARAM_RSP_H - -#include "message_rsp.h" -#include "dm_device_info.h" - -namespace OHOS { -namespace DistributedHardware { -class GetAuthParamRsp : public MessageRsp { -DECLARE_MESSAGE_MODEL(GetAuthParamRsp); -public: - const DmAuthParam& GetAuthParam() const - { - return authParam_; - } - - void SetAuthParam(DmAuthParam &authParam) - { - authParam_ = authParam; - } -private: - DmAuthParam authParam_; -}; -} // namespace DistributedHardware -} // namespace OHOS -#endif // OHOS_DEVICE_MANAGER_GET_AUTH_PARAM_RSP_H \ No newline at end of file diff --git a/services/devicemanagerservice/include/dispatch/set_useroperation_req.h b/services/devicemanagerservice/include/dispatch/get_useroperation_req.h similarity index 92% rename from services/devicemanagerservice/include/dispatch/set_useroperation_req.h rename to services/devicemanagerservice/include/dispatch/get_useroperation_req.h index c60e61d0a..5b2f2679c 100644 --- a/services/devicemanagerservice/include/dispatch/set_useroperation_req.h +++ b/services/devicemanagerservice/include/dispatch/get_useroperation_req.h @@ -20,8 +20,8 @@ namespace OHOS { namespace DistributedHardware { -class GetOperationReq : public MessageReq { -DECLARE_MESSAGE_MODEL(GetOperationReq); +class GetUserOperationReq : public MessageReq { +DECLARE_MESSAGE_MODEL(GetUserOperationReq); public: int32_t GetOperation() const { diff --git a/services/devicemanagerservice/include/dispatch/message_def.h b/services/devicemanagerservice/include/dispatch/message_def.h index 06e443a7d..a5efbeb5e 100644 --- a/services/devicemanagerservice/include/dispatch/message_def.h +++ b/services/devicemanagerservice/include/dispatch/message_def.h @@ -21,18 +21,18 @@ namespace DistributedHardware { #define DEVICE_MANAGER_SERVICE_NAME "dev_mgr_svc" #define MAX_DM_IPC_LEN 2048 -#define DECLARE_MESSAGE_MODEL(className) \ -public: \ - className() = default; \ - virtual ~className() = default; \ -public: \ - className(const className&) = delete; \ - className& operator= (const className&) = delete; \ - className(className&&) = delete; \ - className& operator= (className&&) = delete \ +#define DECLARE_MESSAGE_MODEL(className) \ +public: \ + className() = default; \ + virtual ~className() = default; \ + \ +public: \ + className(const className &) = delete; \ + className &operator=(const className &) = delete; \ + className(className &&) = delete; \ + className &operator=(className &&) = delete -#define DECLARE_MESSAGE_INTERFACE(className) \ - DECLARE_MESSAGE_MODEL(className) +#define DECLARE_MESSAGE_INTERFACE(className) DECLARE_MESSAGE_MODEL(className) enum DispatchCmdID { REGISTER_DEVICE_MANAGER_LISTENER = 0, diff --git a/services/devicemanagerservice/include/dispatch/message_rsp.h b/services/devicemanagerservice/include/dispatch/message_rsp.h index ab2c2f070..6a5be6708 100644 --- a/services/devicemanagerservice/include/dispatch/message_rsp.h +++ b/services/devicemanagerservice/include/dispatch/message_rsp.h @@ -16,8 +16,6 @@ #ifndef OHOS_DEVICE_MANAGER_MESSAGE_RSP_H #define OHOS_DEVICE_MANAGER_MESSAGE_RSP_H -#include - #include "message_def.h" namespace OHOS { diff --git a/services/devicemanagerservice/include/dispatch/server_stub.h b/services/devicemanagerservice/include/dispatch/server_stub.h index 9667dba08..86e5c79d6 100644 --- a/services/devicemanagerservice/include/dispatch/server_stub.h +++ b/services/devicemanagerservice/include/dispatch/server_stub.h @@ -16,8 +16,6 @@ #ifndef OHOS_DEVICE_MANAGER_SERVER_STUB_H #define OHOS_DEVICE_MANAGER_SERVER_STUB_H -#include #include -#include #endif // OHOS_DEVICE_MANAGER_IPC_SERVER_STUB_H diff --git a/services/devicemanagerservice/include/dispatch/stop_discovery_req.h b/services/devicemanagerservice/include/dispatch/stop_discovery_req.h index 16afa9333..4ce6703ac 100644 --- a/services/devicemanagerservice/include/dispatch/stop_discovery_req.h +++ b/services/devicemanagerservice/include/dispatch/stop_discovery_req.h @@ -16,8 +16,6 @@ #ifndef OHOS_DEVICE_MANAGER_STOP_DISCOVERY_REQ_H #define OHOS_DEVICE_MANAGER_STOP_DISCOVERY_REQ_H -#include - #include "message_req.h" namespace OHOS { diff --git a/services/devicemanagerservice/src/dispatch/command_dispatch.cpp b/services/devicemanagerservice/src/dispatch/command_dispatch.cpp index 328ca5aa1..374ad7dfa 100644 --- a/services/devicemanagerservice/src/dispatch/command_dispatch.cpp +++ b/services/devicemanagerservice/src/dispatch/command_dispatch.cpp @@ -24,13 +24,11 @@ #include "get_trustdevice_req.h" #include "start_discovery_req.h" #include "stop_discovery_req.h" -#include "set_useroperation_req.h" +#include "get_useroperation_req.h" #include "authenticate_device_req.h" #include "verify_authenticate_req.h" -#include "get_authenticationparam_rsp.h" #include "get_trustdevice_rsp.h" #include "device_manager_service.h" - #include "get_local_device_info_rsp.h" #include "get_info_by_network_rsp.h" #include "get_info_by_network_req.h" @@ -38,9 +36,11 @@ #include "get_dmfaparam_rsp.h" namespace OHOS { -namespace DistributedHardware{ +namespace DistributedHardware { IMPLEMENT_SINGLE_INSTANCE(CommandDispatch); -int32_t CommandDispatch::MessageSendCmd(int32_t cmdCode, std::shared_ptr req, std::shared_ptr rsp) + +int32_t CommandDispatch::MessageSendCmd(int32_t cmdCode, std::shared_ptr req, + std::shared_ptr rsp) { if (req == nullptr || rsp == nullptr) { LOGE("Message req or rsp is null."); @@ -54,7 +54,8 @@ int32_t CommandDispatch::MessageSendCmd(int32_t cmdCode, std::shared_ptr req, std::shared_ptr rsp) +int32_t CommandDispatch::CmdProcessing(int32_t cmdCode, std::shared_ptr req, + std::shared_ptr rsp) { int32_t ret = 1; LOGI("SendCmd:%d", cmdCode); @@ -116,7 +117,7 @@ int32_t CommandDispatch::CmdProcessing(int32_t cmdCode, std::shared_ptrSetErrCode(ret); - break; + break; } case STOP_DEVICE_DISCOVER: { LOGI("StopDeviceDiscovery service"); @@ -128,10 +129,10 @@ int32_t CommandDispatch::CmdProcessing(int32_t cmdCode, std::shared_ptrSetErrCode(ret); break; - } + } case SERVER_USER_AUTH_OPERATION: { - std::shared_ptr pReq = std::static_pointer_cast(req); - std::string pkgName= pReq->GetPkgName(); + std::shared_ptr pReq = std::static_pointer_cast(req); + std::string pkgName = pReq->GetPkgName(); int32_t action = pReq->GetOperation(); LOGI("enter server user authorization operation."); diff --git a/services/devicemanagerservice/src/dispatch/device_manager_service_listener_mini.cpp b/services/devicemanagerservice/src/dispatch/device_manager_service_listener_mini.cpp index 7cee13f5e..4fd39a3ec 100644 --- a/services/devicemanagerservice/src/dispatch/device_manager_service_listener_mini.cpp +++ b/services/devicemanagerservice/src/dispatch/device_manager_service_listener_mini.cpp @@ -28,7 +28,7 @@ void DeviceManagerServiceListener::OnDeviceStateChange(const std::string &pkgNam { LOGI("call OnDeviceStateChange, state=%d", state); std::list pkgNameList = DeviceManagerNotify::GetInstance().GetPkgNameList(); - for( auto pkgName : pkgNameList) { + for(auto pkgName : pkgNameList) { DmDeviceState deviceState = static_cast(state); if (pkgName == "") { LOGE("OnDeviceOnline, get para failed"); @@ -84,7 +84,7 @@ void DeviceManagerServiceListener::OnVerifyAuthResult(const std::string &pkgName { LOGI("call OnVerifyAuthResult"); std::list pkgNameList = DeviceManagerNotify::GetInstance().GetPkgNameList(); - for( auto pkgName : pkgNameList) { + for(auto pkgName : pkgNameList) { DeviceManagerNotify::GetInstance().OnVerifyAuthResult(pkgName, deviceId, resultCode, flag); } } diff --git a/services/devicemanagerservice/src/dispatch/server_stub.cpp b/services/devicemanagerservice/src/dispatch/server_stub.cpp index 92a03cf86..9b38baa53 100644 --- a/services/devicemanagerservice/src/dispatch/server_stub.cpp +++ b/services/devicemanagerservice/src/dispatch/server_stub.cpp @@ -33,7 +33,7 @@ namespace { using namespace OHOS::DistributedHardware; struct DefaultFeatureApi { - INHERIT_SERVER_IPROXY; + INHERIT_SERVER_IPROXY; }; struct DeviceManagerSamgrService { @@ -83,9 +83,6 @@ static TaskConfig GetTaskConfig(Service *service) return config; } - - - static void DevMgrSvcInit(void) { sleep(WAIT_FOR_SERVER); @@ -95,7 +92,7 @@ static void DevMgrSvcInit(void) .MessageHandle = MessageHandle, .GetTaskConfig = GetTaskConfig, SERVER_IPROXY_IMPL_BEGIN, - .Invoke = NULL, + .Invoke = NULL, IPROXY_END, }; @@ -109,4 +106,5 @@ static void DevMgrSvcInit(void) } LOGI("%s, init success", DEVICE_MANAGER_SERVICE_NAME); } + SYSEX_SERVICE_INIT(DevMgrSvcInit); -- Gitee From 4903c1fdbc7b1e004e96c5751e2dc634870f14b1 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Convert=2EToInt32=28=E9=98=BF=E4=BC=A6=29?= <619269320@qq.com> Date: Wed, 16 Mar 2022 08:27:53 +0000 Subject: [PATCH 19/19] =?UTF-8?q?!41=20fix:codecheck=E4=BF=AE=E6=94=B9=20*?= =?UTF-8?q?=20fix:=20codeCheck=E4=BF=AE=E6=94=B9?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../kits/js/src/native_devicemanager_js.cpp | 18 ++++++++++++------ 1 file changed, 12 insertions(+), 6 deletions(-) diff --git a/interfaces_mini/kits/js/src/native_devicemanager_js.cpp b/interfaces_mini/kits/js/src/native_devicemanager_js.cpp index c3ac92d6e..bd211991c 100644 --- a/interfaces_mini/kits/js/src/native_devicemanager_js.cpp +++ b/interfaces_mini/kits/js/src/native_devicemanager_js.cpp @@ -505,11 +505,13 @@ void DeviceManagerModule::JsToDmDeviceInfo(const JSIValue &object, { int ret = strcpy_s(info.deviceId, DM_MAX_DEVICE_ID_LEN, JsObjectToString(object, "deviceId")); if (ret != DM_OK) { - LOGE("JsToDmDeviceInfo error: copy deviceId failed"); + LOGE("JsToDmDeviceInfo error: copy deviceId failed %d", ret); + return; } ret = strcpy_s(info.deviceName, DM_MAX_DEVICE_NAME_LEN, JsObjectToString(object, "deviceName")); if (ret != DM_OK) { - LOGE("JsToDmDeviceInfo error: copy deviceName failed"); + LOGE("JsToDmDeviceInfo error: copy deviceName failed %d", ret); + return; } uint16_t deviceTypeId = -1; deviceTypeId = (uint16_t)JsObjectToInt(object, "deviceTypeId"); @@ -907,9 +909,11 @@ JSIValue DeviceManagerModule::StartDeviceDiscoverSync(const JSIValue thisVal, co return JSI::CreateNull(); } - LOGI("subInfo %d , %d, %d, %d, %d , %d, %s", subInfo.subscribeId, - subInfo.mode, subInfo.medium, subInfo.freq, subInfo.isSameAccount, - subInfo.isWakeRemote, subInfo.capability); + LOGI("subInfo %d , %d, %d, %d, %d , %d, %s", + subInfo.subscribeId, + subInfo.mode, + subInfo.medium, subInfo.freq, subInfo.isSameAccount, + subInfo.isWakeRemote, subInfo.capability); std::string extra = ""; int32_t ret = OHOS::DistributedHardware::DeviceManager::GetInstance().StartDeviceDiscovery(bundleName, subInfo, extra, discoverCallback); @@ -1159,7 +1163,9 @@ char *DeviceManagerModule::GetJSIAppBundleName() char *packageName = new char[strlen(pname)+1]; int ret = strcpy_s(packageName, strlen(pname)+1, pname); if (ret != DM_OK) { - LOGE("GetJSIAppBundleName error: copy BundleName failed"); + LOGE("GetJSIAppBundleName error: copy BundleName failed %d", ret); + delete(g_targetJSAbility); + return nullptr; } delete(g_targetJSAbility); return packageName; -- Gitee