• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (c) 2025 Huawei Device Co., Ltd.
3  * Licensed under the Apache License, Version 2.0 (the "License");
4  * you may not use this file except in compliance with the License.
5  * You may obtain a copy of the License at
6  *
7  *     http://www.apache.org/licenses/LICENSE-2.0
8  *
9  * Unless required by applicable law or agreed to in writing, software
10  * distributed under the License is distributed on an "AS IS" BASIS,
11  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12  * See the License for the specific language governing permissions and
13  * limitations under the License.
14  */
15 
16 #include "dm_client.h"
17 
18 #include "app_manager.h"
19 #include "device_manager.h"
20 #include "dm_error_type.h"
21 #include "dm_log.h"
22 #include "oh_device_manager_err_code.h"
23 
24 namespace OHOS {
25 namespace DistributedHardware {
GetInstance()26 DmClient &DmClient::GetInstance()
27 {
28     static DmClient instance;
29     return instance;
30 }
31 
Init()32 int32_t DmClient::Init()
33 {
34     std::lock_guard<std::mutex> lck(initMtx_);
35     if (pkgName_.empty()) {
36         std::string bundleName = "";
37         int32_t ret = AppManager::GetInstance().GetBundleNameForSelf(bundleName);
38         if (ret != DM_OK || bundleName.empty()) {
39             LOGE("Get bundle name failed, ret=%{public}d", ret);
40             return DM_ERR_OBTAIN_BUNDLE_NAME;
41         }
42         pkgName_ = bundleName;
43     }
44     if (dmInitCallback_ == nullptr) {
45         dmInitCallback_ = std::make_shared<DmClient::InitCallback>();
46     }
47     int32_t ret = DeviceManager::GetInstance().InitDeviceManager(pkgName_, dmInitCallback_);
48     if (ret != DM_OK) {
49         LOGE("Init DeviceManager failed, ret=%{public}d", ret);
50         return DM_ERR_OBTAIN_SERVICE;
51     }
52     return ERR_OK;
53 }
54 
UnInit()55 int32_t DmClient::UnInit()
56 {
57     std::lock_guard<std::mutex> lck(initMtx_);
58     if (dmInitCallback_ != nullptr) {
59         DeviceManager::GetInstance().UnInitDeviceManager(pkgName_);
60     }
61     pkgName_ = "";
62     return ERR_OK;
63 }
64 
ReInit()65 int32_t DmClient::ReInit()
66 {
67     UnInit();
68     return Init();
69 }
70 
GetLocalDeviceName(std::string & deviceName)71 int32_t DmClient::GetLocalDeviceName(std::string &deviceName)
72 {
73     int32_t ret = Init();
74     if (ret != ERR_OK) {
75         LOGE("Init dm client failed, ret=%{public}d", ret);
76         return ret;
77     }
78     ret = DeviceManager::GetInstance().GetLocalDeviceName(deviceName);
79     if (ret != DM_OK) {
80         LOGE("Get local device name failed, ret=%{public}d", ret);
81         return DM_ERR_FAILED;
82     }
83     return ERR_OK;
84 }
85 
OnRemoteDied()86 void DmClient::InitCallback::OnRemoteDied()
87 {
88     DmClient::GetInstance().ReInit();
89 }
90 } // namespace DistributedHardware
91 } // namespace OHOS
92