• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (c) 2024 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 #include "device_manager_impl.h"
16 
17 #include <memory>
18 #include <vector>
19 
20 #include "cj_lambda.h"
21 #include "ipc_skeleton.h"
22 
23 #include "device_manager.h"
24 #include "dm_anonymous.h"
25 #include "dm_constants.h"
26 #include "dm_error_message.h"
27 #include "dm_log.h"
28 
29 namespace OHOS::DistributedHardware {
30 
31 namespace {
32 std::map<std::string, DeviceManagerFfiImpl *> g_deviceManagerMap;
33 std::map<std::string, std::shared_ptr<DmFfiInitCallback>> g_initCallbackMap;
34 std::map<std::string, std::shared_ptr<DmFfiDeviceStatusCallback>> g_deviceStatusCallbackMap;
35 std::map<std::string, std::shared_ptr<DmFfiDiscoveryCallback>> g_DiscoveryCallbackMap;
36 std::map<std::string, std::shared_ptr<DmFfiPublishCallback>> g_publishCallbackMap;
37 std::map<std::string, std::shared_ptr<DmFfiAuthenticateCallback>> g_authCallbackMap;
38 std::map<std::string, std::shared_ptr<DmFfiBindTargetCallback>> g_bindCallbackMap;
39 std::map<std::string, std::shared_ptr<DmFfiDeviceManagerUiCallback>> g_dmUiCallbackMap;
40 
41 std::mutex g_deviceManagerMapMutex;
42 std::mutex g_initCallbackMapMutex;
43 std::mutex g_deviceStatusCallbackMapMutex;
44 std::mutex g_discoveryCallbackMapMutex;
45 std::mutex g_publishCallbackMapMutex;
46 std::mutex g_authCallbackMapMutex;
47 std::mutex g_bindCallbackMapMutex;
48 std::mutex g_dmUiCallbackMapMutex;
49 
50 const int32_t DM_AUTH_REQUEST_SUCCESS_STATUS = 7;
51 const int32_t DM_FFI_BUF_LENGTH = 256;
52 
53 constexpr const char* DM_FFI_EVENT_DEVICE_STATE_CHANGE = "deviceStateChange";
54 constexpr const char* DM_FFI_EVENT_DEVICE_DISCOVER_SUCCESS = "discoverSuccess";
55 constexpr const char* DM_FFI_EVENT_DEVICE_DISCOVER_FAIL = "discoverFailure";
56 constexpr const char* DM_FFI_EVENT_DEVICE_NAME_CHANGE = "deviceNameChange";
57 
58 enum ErrorCode {
59     // OK
60     ERR_OK = 0,
61     // Permission verify failed.
62     ERR_NO_PERMISSION = 201,
63     // The caller is not a system application.
64     ERR_NOT_SYSTEM_APP = 202,
65     // Input parameter error.
66     ERR_INVALID_PARAMS = 401,
67     // Failed to execute the function.
68     DM_ERR_FAILED = 11600101,
69     // Failed to obtain the service.
70     DM_ERR_OBTAIN_SERVICE = 11600102,
71     // Authentication invalid.
72     DM_ERR_AUTHENTICALTION_INVALID = 11600103,
73     // Discovery invalid.
74     DM_ERR_DISCOVERY_INVALID = 11600104,
75     // Publish invalid.
76     DM_ERR_PUBLISH_INVALID = 11600105,
77 };
78 
StringCheck(const std::string & str)79 inline int32_t StringCheck(const std::string &str)
80 {
81     if (str.size() == 0 || str.size() >= DM_FFI_BUF_LENGTH) {
82         return ERR_INVALID_PARAMS;
83     }
84     return ERR_OK;
85 }
86 
TransformErrCode(const int32_t errCode)87 int32_t TransformErrCode(const int32_t errCode)
88 {
89     switch (errCode) {
90         case ERR_DM_NO_PERMISSION:
91             return ERR_NO_PERMISSION;
92         case ERR_DM_DISCOVERY_REPEATED:
93             return DM_ERR_DISCOVERY_INVALID;
94         case ERR_DM_PUBLISH_REPEATED:
95             return DM_ERR_PUBLISH_INVALID;
96         case ERR_DM_AUTH_BUSINESS_BUSY:
97             return DM_ERR_AUTHENTICALTION_INVALID;
98         case ERR_DM_INPUT_PARA_INVALID:
99         case ERR_DM_UNSUPPORTED_AUTH_TYPE:
100             return ERR_INVALID_PARAMS;
101         case ERR_DM_INIT_FAILED:
102             return DM_ERR_OBTAIN_SERVICE;
103         case ERR_NOT_SYSTEM_APP:
104             return ERR_NOT_SYSTEM_APP;
105         default:
106             return DM_ERR_FAILED;
107     }
108     return 0;
109 }
110 
InsertIntItem(JsonObject & jsonObj,std::map<std::string,std::string> & jsonMap,const std::string & searchKey,const std::string & insertKey)111 inline void InsertIntItem(JsonObject &jsonObj, std::map<std::string, std::string> &jsonMap,
112     const std::string &searchKey, const std::string &insertKey)
113 {
114     if (IsInt32(jsonObj, searchKey)) {
115         int32_t value = jsonObj[searchKey].Get<int32_t>();
116         jsonMap.insert(std::pair<std::string, std::string>(insertKey, std::to_string(value)));
117     }
118 }
119 
InsertStringItem(JsonObject & jsonObj,std::map<std::string,std::string> & jsonMap,const std::string & searchKey,const std::string & insertKey)120 inline void InsertStringItem(JsonObject &jsonObj, std::map<std::string, std::string> &jsonMap,
121     const std::string &searchKey, const std::string &insertKey)
122 {
123     if (IsString(jsonObj, searchKey)) {
124         std::string value = jsonObj[searchKey].Get<std::string>();
125         jsonMap.insert(std::pair<std::string, std::string>(insertKey, value));
126     }
127 }
128 
InsertJsonParamesToMap(JsonObject & bindParamObj,std::map<std::string,std::string> & bindParamMap)129 void InsertJsonParamesToMap(JsonObject &bindParamObj, std::map<std::string, std::string> &bindParamMap)
130 {
131     LOGI("Insert map parames start");
132     InsertIntItem(bindParamObj, bindParamMap, AUTH_TYPE, PARAM_KEY_AUTH_TYPE);
133     InsertStringItem(bindParamObj, bindParamMap, APP_OPERATION, PARAM_KEY_APP_OPER);
134     InsertStringItem(bindParamObj, bindParamMap, CUSTOM_DESCRIPTION, PARAM_KEY_APP_DESC);
135     InsertStringItem(bindParamObj, bindParamMap, PARAM_KEY_TARGET_PKG_NAME, PARAM_KEY_TARGET_PKG_NAME);
136     InsertStringItem(bindParamObj, bindParamMap, PARAM_KEY_META_TYPE, PARAM_KEY_META_TYPE);
137     InsertStringItem(bindParamObj, bindParamMap, PARAM_KEY_PIN_CODE, PARAM_KEY_PIN_CODE);
138     InsertStringItem(bindParamObj, bindParamMap, PARAM_KEY_AUTH_TOKEN, PARAM_KEY_AUTH_TOKEN);
139     InsertIntItem(bindParamObj, bindParamMap, BIND_LEVEL, BIND_LEVEL);
140 }
141 } // namespace
142 
DeviceManagerFfiImpl(const std::string & bundleName,int32_t * errCode)143 DeviceManagerFfiImpl::DeviceManagerFfiImpl(const std::string &bundleName, int32_t *errCode) : bundleName_(bundleName)
144 {
145     *errCode = StringCheck(bundleName);
146     if (*errCode != 0) {
147         LOGE("CreateDeviceManager for bundleName %{public}s failed, ret %{public}d.", bundleName_.c_str(), *errCode);
148         return;
149     }
150     std::shared_ptr<DmFfiInitCallback> initCallback = std::make_shared<DmFfiInitCallback>(bundleName_);
151     *errCode = DeviceManager::GetInstance().InitDeviceManager(bundleName_, initCallback);
152     if (*errCode != 0) {
153         *errCode = TransformErrCode(*errCode);
154         LOGE("CreateDeviceManager for bundleName %{public}s failed, ret %{public}d.", bundleName_.c_str(), *errCode);
155         return;
156     }
157     {
158         std::lock_guard<std::mutex> autoLock(g_initCallbackMapMutex);
159         CHECK_SIZE_VOID(g_initCallbackMap);
160         g_initCallbackMap[bundleName_] = initCallback;
161     }
162 
163     std::lock_guard<std::mutex> autoLock(g_deviceManagerMapMutex);
164     CHECK_SIZE_VOID(g_deviceManagerMap);
165     g_deviceManagerMap[bundleName_] = this;
166 }
167 
ReleaseDeviceManager()168 int32_t DeviceManagerFfiImpl::ReleaseDeviceManager()
169 {
170     if (DeviceManager::GetInstance().CheckNewAPIAccessPermission() != 0) {
171         return ERR_NO_PERMISSION;
172     }
173     int ret = DeviceManager::GetInstance().UnInitDeviceManager(bundleName_);
174     if (ret != 0) {
175         ret = TransformErrCode(ret);
176         LOGE("ReleaseDeviceManager for bundleName %{public}s failed, ret %{public}d", bundleName_.c_str(), ret);
177         return ret;
178     }
179     ClearBundleCallbacks();
180     return ERR_OK;
181 }
182 
GetAvailableDeviceList(FfiDeviceBasicInfoArray & deviceInfoList)183 int32_t DeviceManagerFfiImpl::GetAvailableDeviceList(FfiDeviceBasicInfoArray &deviceInfoList)
184 {
185     int32_t ret = DeviceManager::GetInstance().CheckNewAPIAccessPermission();
186     if (ret != 0) {
187         return TransformErrCode(ret);
188     }
189     std::vector<DmDeviceBasicInfo> result;
190     ret = DeviceManager::GetInstance().GetAvailableDeviceList(bundleName_, result);
191     if (ret != 0) {
192         ret = TransformErrCode(ret);
193         LOGE("GetTrustedDeviceList for bundleName %{public}s failed, ret %{public}d", bundleName_.c_str(), ret);
194         return ret;
195     }
196 
197     if (result.size() == 0) {
198         return ERR_OK;
199     }
200 
201     deviceInfoList.head = static_cast<FfiDeviceBasicInfo *>(malloc(sizeof(FfiDeviceBasicInfo) * result.size()));
202     if (deviceInfoList.head == nullptr) {
203         LOGE("Malloc failed");
204         return DM_ERR_FAILED;
205     }
206     deviceInfoList.size = static_cast<int64_t>(result.size());
207     for (decltype(result.size()) i = 0; i < result.size(); ++i) {
208         ret = Transform2FfiDeviceBasicInfo(result[i], deviceInfoList.head[i]);
209         if (ret != 0) {
210             DeviceListFree(deviceInfoList, i);
211             return ret;
212         }
213     }
214     return ERR_OK;
215 }
216 
DeviceListFree(FfiDeviceBasicInfoArray & deviceInfoList,int64_t size)217 void DeviceManagerFfiImpl::DeviceListFree(FfiDeviceBasicInfoArray &deviceInfoList, int64_t size)
218 {
219     if (size == -1) {
220         size = deviceInfoList.size;
221     }
222     for (int32_t i = 0; i < size; ++i) {
223         FreeDeviceInfo(deviceInfoList.head[i]);
224     }
225     free(deviceInfoList.head);
226     deviceInfoList.head = nullptr;
227     deviceInfoList.size = 0;
228 }
229 
Transform2FfiDeviceBasicInfo(const DmDeviceBasicInfo & in,FfiDeviceBasicInfo & out)230 int32_t DeviceManagerFfiImpl::Transform2FfiDeviceBasicInfo(const DmDeviceBasicInfo &in, FfiDeviceBasicInfo &out)
231 {
232     out.deviceId = MallocCStr(in.deviceId);
233     out.deviceName = MallocCStr(in.deviceName);
234     out.deviceType = in.deviceTypeId;
235     out.networkId = MallocCStr(in.networkId);
236     if (out.deviceId == nullptr || out.deviceName == nullptr || out.networkId == nullptr) {
237         FreeDeviceInfo(out);
238         return DM_ERR_FAILED;
239     }
240     return ERR_OK;
241 }
242 
GetLocalDeviceNetworkId(const char * & networkId)243 int32_t DeviceManagerFfiImpl::GetLocalDeviceNetworkId(const char *&networkId)
244 {
245     if (DeviceManager::GetInstance().CheckNewAPIAccessPermission() != 0) {
246         return ERR_NO_PERMISSION;
247     }
248 
249     std::string result;
250     int32_t ret = DeviceManager::GetInstance().GetLocalDeviceNetWorkId(bundleName_, result);
251     if (ret != 0) {
252         ret = TransformErrCode(ret);
253         LOGE("GetLocalDeviceNetworkId for failed, ret %{public}d", ret);
254         return ret;
255     }
256     LOGI("DeviceManager::GetLocalDeviceNetworkId networkId:%{public}s", GetAnonyString(result).c_str());
257 
258     networkId = MallocCStr(result.c_str());
259     if (networkId == nullptr) {
260         return DM_ERR_FAILED;
261     }
262     return ERR_OK;
263 }
264 
GetLocalDeviceName(const char * & deviceName)265 int32_t DeviceManagerFfiImpl::GetLocalDeviceName(const char *&deviceName)
266 {
267     if (DeviceManager::GetInstance().CheckNewAPIAccessPermission() != 0) {
268         return ERR_NO_PERMISSION;
269     }
270 
271     std::string result;
272     int32_t ret = DeviceManager::GetInstance().GetLocalDeviceName(bundleName_, result);
273     if (ret != 0) {
274         ret = TransformErrCode(ret);
275         LOGE("GetLocalDeviceName for failed, ret %{public}d", ret);
276         return ret;
277     }
278     LOGI("DeviceManager::GetLocalDeviceName deviceName:%{public}s", GetAnonyString(result).c_str());
279 
280     deviceName = MallocCStr(result.c_str());
281     if (deviceName == nullptr) {
282         return DM_ERR_FAILED;
283     }
284     return ERR_OK;
285 }
286 
GetLocalDeviceType(int32_t & deviceType)287 int32_t DeviceManagerFfiImpl::GetLocalDeviceType(int32_t &deviceType)
288 {
289     if (DeviceManager::GetInstance().CheckNewAPIAccessPermission() != 0) {
290         return ERR_NO_PERMISSION;
291     }
292 
293     int32_t ret = DeviceManager::GetInstance().GetLocalDeviceType(bundleName_, deviceType);
294     if (ret != 0) {
295         ret = TransformErrCode(ret);
296         LOGE("GetLocalDeviceType for failed, ret %{public}d", ret);
297         return ret;
298     }
299     LOGI("DeviceManager::GetLocalDeviceType deviceType:%{public}d", deviceType);
300     return ERR_OK;
301 }
302 
GetLocalDeviceId(const char * & deviceId)303 int32_t DeviceManagerFfiImpl::GetLocalDeviceId(const char *&deviceId)
304 {
305     if (DeviceManager::GetInstance().CheckNewAPIAccessPermission() != 0) {
306         return ERR_NO_PERMISSION;
307     }
308 
309     std::string result;
310     int32_t ret = DeviceManager::GetInstance().GetLocalDeviceId(bundleName_, result);
311     if (ret != 0) {
312         ret = TransformErrCode(ret);
313         LOGE("GetLocalDeviceId for failed, ret %{public}d", ret);
314         return ret;
315     }
316     LOGI("DeviceManager::GetLocalDeviceId deviceId:%{public}s", GetAnonyString(result).c_str());
317 
318     deviceId = MallocCStr(result.c_str());
319     if (deviceId == nullptr) {
320         return DM_ERR_FAILED;
321     }
322     return ERR_OK;
323 }
324 
GetDeviceName(const std::string & networkId,const char * & deviceName)325 int32_t DeviceManagerFfiImpl::GetDeviceName(const std::string &networkId, const char *&deviceName)
326 {
327     int32_t ret = StringCheck(networkId);
328     if (ret != 0) {
329         return ret;
330     }
331     std::string result;
332     ret = DeviceManager::GetInstance().GetDeviceName(bundleName_, networkId, result);
333     LOGI("DeviceManager::GetDeviceName getinstance return.");
334     if (ret != 0) {
335         ret = TransformErrCode(ret);
336         LOGE("GetDeviceName for failed, ret %{public}d", ret);
337         return ret;
338     }
339     LOGI("DeviceManager::GetDeviceName deviceName:%{public}s", GetAnonyString(result).c_str());
340 
341     deviceName = MallocCStr(result.c_str());
342     if (deviceName == nullptr) {
343         return DM_ERR_FAILED;
344     }
345     return ERR_OK;
346 }
347 
GetDeviceType(const std::string & networkId,int32_t & deviceType)348 int32_t DeviceManagerFfiImpl::GetDeviceType(const std::string &networkId, int32_t &deviceType)
349 {
350     int32_t ret = StringCheck(networkId);
351     if (ret != 0) {
352         return ret;
353     }
354     ret = DeviceManager::GetInstance().GetDeviceType(bundleName_, networkId, deviceType);
355     if (ret != 0) {
356         ret = TransformErrCode(ret);
357         LOGE("GetDeviceType for failed, ret %{public}d", ret);
358         return ret;
359     }
360     LOGI("DeviceManager::GetDeviceType deviceType:%{public}d", deviceType);
361     return ERR_OK;
362 }
363 
StartDiscovering(const std::string & extra)364 int32_t DeviceManagerFfiImpl::StartDiscovering(const std::string &extra)
365 {
366     if (DeviceManager::GetInstance().CheckNewAPIAccessPermission() != 0) {
367         return ERR_NO_PERMISSION;
368     }
369     std::shared_ptr<DmFfiDiscoveryCallback> discoveryCallback = nullptr;
370     {
371         std::lock_guard<std::mutex> autoLock(g_discoveryCallbackMapMutex);
372         auto iter = g_DiscoveryCallbackMap.find(bundleName_);
373         if (iter == g_DiscoveryCallbackMap.end()) {
374             CHECK_SIZE_RETURN(g_DiscoveryCallbackMap, DM_ERR_FAILED);
375             discoveryCallback = std::make_shared<DmFfiDiscoveryCallback>(bundleName_);
376             g_DiscoveryCallbackMap[bundleName_] = discoveryCallback;
377         } else {
378             discoveryCallback = iter->second;
379         }
380     }
381     uint64_t tokenId = OHOS::IPCSkeleton::GetSelfTokenID();
382     int32_t ret = DeviceManager::GetInstance().StartDeviceDiscovery(bundleName_, tokenId, extra, discoveryCallback);
383     if (ret != 0) {
384         ret = TransformErrCode(ret);
385         LOGE("Discovery failed, bundleName %{public}s, ret %{public}d", bundleName_.c_str(), ret);
386         discoveryCallback->OnDiscoveryFailed(static_cast<uint16_t>(0), ret);
387         return ret;
388     }
389     return ERR_OK;
390 }
391 
StopDiscovering()392 int32_t DeviceManagerFfiImpl::StopDiscovering()
393 {
394     if (DeviceManager::GetInstance().CheckNewAPIAccessPermission() != 0) {
395         return ERR_NO_PERMISSION;
396     }
397     uint64_t tokenId = OHOS::IPCSkeleton::GetSelfTokenID();
398     int32_t ret = DeviceManager::GetInstance().StopDeviceDiscovery(tokenId, bundleName_);
399     if (ret != 0) {
400         ret = TransformErrCode(ret);
401         LOGE("StopDeviceDiscovery for bundleName %{public}s failed, ret %{public}d", bundleName_.c_str(), ret);
402         return ret;
403     }
404     return ERR_OK;
405 }
406 
BindDevice(const std::string & deviceId,const std::string & bindParam)407 int32_t DeviceManagerFfiImpl::BindDevice(const std::string &deviceId, const std::string &bindParam)
408 {
409     std::shared_ptr<DmFfiAuthenticateCallback> bindDeviceCallback = nullptr;
410     {
411         std::lock_guard<std::mutex> autoLock(g_authCallbackMapMutex);
412         auto iter = g_authCallbackMap.find(bundleName_);
413         if (iter == g_authCallbackMap.end()) {
414             CHECK_SIZE_RETURN(g_authCallbackMap, DM_ERR_FAILED);
415             bindDeviceCallback = std::make_shared<DmFfiAuthenticateCallback>(bundleName_);
416             g_authCallbackMap[bundleName_] = bindDeviceCallback;
417         } else {
418             bindDeviceCallback = iter->second;
419         }
420     }
421     constexpr int32_t bindType = 1;
422     int32_t ret = DeviceManager::GetInstance().BindDevice(bundleName_, bindType, deviceId,
423         bindParam, bindDeviceCallback);
424     if (ret != 0) {
425         ret = TransformErrCode(ret);
426         LOGE("BindDevice for bundleName %{public}s failed, ret %{public}d", bundleName_.c_str(), ret);
427         return ret;
428     }
429     return WaitForCallbackCv();
430 }
431 
BindTarget(const std::string & deviceId,const std::string & bindParam,const bool isMetaType)432 int32_t DeviceManagerFfiImpl::BindTarget(const std::string &deviceId,
433     const std::string &bindParam, const bool isMetaType)
434 {
435     if (DeviceManager::GetInstance().CheckNewAPIAccessPermission() != 0) {
436         return ERR_NO_PERMISSION;
437     }
438     int32_t ret = StringCheck(deviceId);
439     if (ret != 0) {
440         return ret;
441     }
442 
443     callbackFinished = false;
444     if (isMetaType) {
445         std::shared_ptr<DmFfiBindTargetCallback> bindTargetCallback = nullptr;
446         {
447             std::lock_guard<std::mutex> autoLock(g_bindCallbackMapMutex);
448             auto iter = g_bindCallbackMap.find(bundleName_);
449             if (iter == g_bindCallbackMap.end()) {
450                 CHECK_SIZE_RETURN(g_bindCallbackMap, DM_ERR_FAILED);
451                 bindTargetCallback = std::make_shared<DmFfiBindTargetCallback>(bundleName_);
452                 g_bindCallbackMap[bundleName_] = bindTargetCallback;
453             } else {
454                 bindTargetCallback = iter->second;
455             }
456         }
457         int32_t ret = BindTargetWarpper(deviceId, bindParam, bindTargetCallback);
458         if (ret != 0) {
459             ret = TransformErrCode(ret);
460             LOGE("BindTarget for bundleName %{public}s failed, ret %{public}d", bundleName_.c_str(), ret);
461             return ret;
462         }
463         return WaitForCallbackCv();
464     }
465 
466     return BindDevice(deviceId, bindParam);
467 }
468 
WaitForCallbackCv()469 int32_t DeviceManagerFfiImpl::WaitForCallbackCv()
470 {
471     std::unique_lock<std::mutex> autoLock(callbackFinishedMutex);
472     callbackFinishedCv.wait(autoLock, [this] { return this->callbackFinished; });
473     LOGI("WaitForCallbackCv got notified, errCode is %{public}d", errCode_.load());
474     return errCode_.load();
475 }
476 
UnbindTarget(const std::string & deviceId)477 int32_t DeviceManagerFfiImpl::UnbindTarget(const std::string &deviceId)
478 {
479     if (DeviceManager::GetInstance().CheckNewAPIAccessPermission() != 0) {
480         return ERR_NO_PERMISSION;
481     }
482     int32_t ret = StringCheck(deviceId);
483     if (ret != 0) {
484         return ret;
485     }
486     LOGI("UnBindDevice deviceId = %{public}s", GetAnonyString(deviceId).c_str());
487     ret = DeviceManager::GetInstance().UnBindDevice(bundleName_, deviceId);
488     if (ret != 0) {
489         ret = TransformErrCode(ret);
490         LOGE("UnBindDevice for bundleName %{public}s failed, ret %{public}d", bundleName_.c_str(), ret);
491         return ret;
492     }
493     return ERR_OK;
494 }
495 
EventOn(const std::string & type,void * callback)496 int32_t DeviceManagerFfiImpl::EventOn(const std::string &type, void *callback)
497 {
498     int32_t ret = DeviceManager::GetInstance().CheckNewAPIAccessPermission();
499     if (ret != 0) {
500         return TransformErrCode(ret);
501     }
502 
503     LOGI("EventOn for bundleName %{public}s, eventType %{public}s ", bundleName_.c_str(), type.c_str());
504     RegisterCallbackByType(type, callback);
505 
506     if (type == DM_FFI_EVENT_DEVICE_STATE_CHANGE || type == DM_FFI_EVENT_DEVICE_NAME_CHANGE) {
507         return RegisterDevStatusCallback();
508     } else if (type == DM_FFI_EVENT_DEVICE_DISCOVER_SUCCESS || type == DM_FFI_EVENT_DEVICE_DISCOVER_FAIL) {
509         return RegisterDiscoveryCallback();
510     }
511 
512     return ERR_INVALID_PARAMS;
513 }
514 
EventOff(const std::string & type)515 int32_t DeviceManagerFfiImpl::EventOff(const std::string &type)
516 {
517     int32_t ret = DeviceManager::GetInstance().CheckNewAPIAccessPermission();
518     if (ret != 0) {
519         return ret;
520     }
521 
522     LOGI("EventOff for bundleName %{public}s, eventType %{public}s ", bundleName_.c_str(), type.c_str());
523     Off(type);
524     if (type == DM_FFI_EVENT_DEVICE_STATE_CHANGE || type == DM_FFI_EVENT_DEVICE_NAME_CHANGE) {
525         if (!deviceStateChangedCallback && !deviceNameChangedCallback) {
526             return ReleaseDevStatusCallback();
527         }
528         return ERR_OK;
529     } else if (type == DM_FFI_EVENT_DEVICE_DISCOVER_SUCCESS || type == DM_FFI_EVENT_DEVICE_DISCOVER_FAIL) {
530         return ReleaseDiscoveryCallback();
531     }
532     return ERR_INVALID_PARAMS;
533 }
534 
535 
OnDeviceStatusChange(int32_t action,const DmDeviceBasicInfo & deviceBasicInfo)536 void DeviceManagerFfiImpl::OnDeviceStatusChange(int32_t action, const DmDeviceBasicInfo &deviceBasicInfo)
537 {
538     std::lock_guard<std::mutex> autoLock(callbackLock);
539     if (deviceStateChangedCallback) {
540         auto ptr = static_cast<FfiDeviceBasicInfo *>(malloc(sizeof(FfiDeviceBasicInfo)));
541         if (ptr == nullptr) {
542             LOGE("OnDeviceStatusChange malloc FfiDeviceBasicInfo failed.");
543             return;
544         }
545         int32_t ret = Transform2FfiDeviceBasicInfo(deviceBasicInfo, *ptr);
546         if (ret != 0) {
547             LOGE("OnDeviceStatusChange failed to transform DmDeviceBasicInfo.");
548             free(ptr);
549             ptr = nullptr;
550             return;
551         }
552         deviceStateChangedCallback(action, ptr);
553         FreeDeviceInfo(*ptr);
554         free(ptr);
555         ptr = nullptr;
556     }
557 }
558 
OnDeviceNameChange(const std::string & deviceName)559 void DeviceManagerFfiImpl::OnDeviceNameChange(const std::string &deviceName)
560 {
561     std::lock_guard<std::mutex> autoLock(callbackLock);
562     if (deviceNameChangedCallback) {
563         char *cDeviceName = MallocCStr(deviceName.c_str());
564         if (cDeviceName == nullptr) {
565             LOGE("OnDeviceNameChange malloc deviname failed.");
566             return;
567         }
568         deviceNameChangedCallback(cDeviceName);
569         free(cDeviceName);
570         cDeviceName = nullptr;
571     }
572 }
573 
OnDeviceFound(uint16_t subscribeId,const DmDeviceBasicInfo & deviceBasicInfo)574 void DeviceManagerFfiImpl::OnDeviceFound(uint16_t subscribeId, const DmDeviceBasicInfo &deviceBasicInfo)
575 {
576     std::lock_guard<std::mutex> autoLock(callbackLock);
577     if (discoverSuccessCallback) {
578         auto ptr = static_cast<FfiDeviceBasicInfo *>(malloc(sizeof(FfiDeviceBasicInfo)));
579         if (ptr == nullptr) {
580             LOGE("OnDeviceStatusChange malloc FfiDeviceBasicInfo failed.");
581             return;
582         }
583         int32_t ret = Transform2FfiDeviceBasicInfo(deviceBasicInfo, *ptr);
584         if (ret != 0) {
585             LOGE("OnDeviceStatusChange failed to transform DmDeviceBasicInfo.");
586             free(ptr);
587             ptr = nullptr;
588             return;
589         }
590         discoverSuccessCallback(ptr);
591         FreeDeviceInfo(*ptr);
592         free(ptr);
593         ptr = nullptr;
594     }
595 }
596 
OnDiscoveryFailed(uint16_t subscribeId,int32_t failedReason)597 void DeviceManagerFfiImpl::OnDiscoveryFailed(uint16_t subscribeId, int32_t failedReason)
598 {
599     std::lock_guard<std::mutex> autoLock(callbackLock);
600     LOGI("OnDiscoveryFailed for subscribeId %{public}d", (int32_t)subscribeId);
601     if (deviceDiscoverFailedCallback) {
602         deviceDiscoverFailedCallback(failedReason);
603     }
604 }
605 
OnPublishResult(int32_t publishId,int32_t publishResult)606 void DeviceManagerFfiImpl::OnPublishResult(int32_t publishId, int32_t publishResult)
607 {
608     LOGI("OnPublishResult for publishId %{public}d, publishResult %{public}d", publishId, publishResult);
609 }
610 
OnAuthResult(const std::string & deviceId,const std::string & token,int32_t status,int32_t reason)611 void DeviceManagerFfiImpl::OnAuthResult(const std::string &deviceId, const std::string &token, int32_t status,
612     int32_t reason)
613 {
614     LOGI("OnAuthResult for status: %{public}d, reason: %{public}d", status, reason);
615     if (reason == DM_OK && (status <= STATUS_DM_CLOSE_PIN_INPUT_UI && status >= STATUS_DM_SHOW_AUTHORIZE_UI)) {
616         LOGI("update ui change, status: %{public}d, reason: %{public}d", status, reason);
617         return;
618     }
619 
620     if (status == DM_AUTH_REQUEST_SUCCESS_STATUS && reason == 0) {
621         LOGI("OnAuthResult success");
622         errCode_ = ERR_OK;
623     } else {
624         LOGI("OnAuthResult failed");
625         errCode_ = reason;
626     }
627 
628     std::lock_guard<std::mutex> autoLock(g_authCallbackMapMutex);
629     g_authCallbackMap.erase(bundleName_);
630     callbackFinished = true;
631     callbackFinishedCv.notify_one();
632 }
633 
OnDmUiCall(const std::string & paramJson)634 void DeviceManagerFfiImpl::OnDmUiCall(const std::string &paramJson)
635 {
636     LOGI("OnCall for paramJson");
637 }
638 
GetDeviceManagerFfi(std::string & bundleName)639 DeviceManagerFfiImpl *DeviceManagerFfiImpl::GetDeviceManagerFfi(std::string &bundleName)
640 {
641     std::lock_guard<std::mutex> autoLock(g_deviceManagerMapMutex);
642     auto iter = g_deviceManagerMap.find(bundleName);
643     if (iter == g_deviceManagerMap.end()) {
644         return nullptr;
645     }
646     return iter->second;
647 }
648 
ClearBundleCallbacks()649 void DeviceManagerFfiImpl::ClearBundleCallbacks()
650 {
651     LOGI("ClearBundleCallbacks start for bundleName %{public}s", bundleName_.c_str());
652     {
653         std::lock_guard<std::mutex> autoLock(g_deviceManagerMapMutex);
654         g_deviceManagerMap.erase(bundleName_);
655     }
656     {
657         std::lock_guard<std::mutex> autoLock(g_initCallbackMapMutex);
658         g_initCallbackMap.erase(bundleName_);
659     }
660     {
661         std::lock_guard<std::mutex> autoLock(g_deviceStatusCallbackMapMutex);
662         g_deviceStatusCallbackMap.erase(bundleName_);
663     }
664     {
665         std::lock_guard<std::mutex> autoLock(g_discoveryCallbackMapMutex);
666         g_DiscoveryCallbackMap.erase(bundleName_);
667     }
668     {
669         std::lock_guard<std::mutex> autoLock(g_publishCallbackMapMutex);
670         g_publishCallbackMap.erase(bundleName_);
671     }
672     {
673         std::lock_guard<std::mutex> autoLock(g_authCallbackMapMutex);
674         g_authCallbackMap.erase(bundleName_);
675     }
676     {
677         std::lock_guard<std::mutex> autoLock(g_bindCallbackMapMutex);
678         g_bindCallbackMap.erase(bundleName_);
679     }
680     return;
681 }
682 
BindTargetWarpper(const std::string & deviceId,const std::string & bindParam,std::shared_ptr<DmFfiBindTargetCallback> callback)683 int32_t DeviceManagerFfiImpl::BindTargetWarpper(const std::string &deviceId,
684     const std::string &bindParam, std::shared_ptr<DmFfiBindTargetCallback> callback)
685 {
686     if (bindParam.empty()) {
687         return ERR_INVALID_PARAMS;
688     }
689     JsonObject bindParamObj(bindParam);
690     if (bindParamObj.IsDiscarded()) {
691         return ERR_INVALID_PARAMS;
692     }
693     PeerTargetId targetId;
694     targetId.deviceId = deviceId;
695     if (IsString(bindParamObj, PARAM_KEY_BR_MAC)) {
696         targetId.brMac = bindParamObj[PARAM_KEY_BR_MAC].Get<std::string>();
697     }
698     if (IsString(bindParamObj, PARAM_KEY_BLE_MAC)) {
699         targetId.bleMac = bindParamObj[PARAM_KEY_BLE_MAC].Get<std::string>();
700     }
701     if (IsString(bindParamObj, PARAM_KEY_WIFI_IP)) {
702         targetId.wifiIp = bindParamObj[PARAM_KEY_WIFI_IP].Get<std::string>();
703     }
704     if (IsInt32(bindParamObj, PARAM_KEY_WIFI_PORT)) {
705         targetId.wifiPort = (uint16_t)(bindParamObj[PARAM_KEY_WIFI_PORT].Get<int32_t>());
706     }
707 
708     std::map<std::string, std::string> bindParamMap;
709     InsertJsonParamesToMap(bindParamObj, bindParamMap);
710     return DeviceManager::GetInstance().BindTarget(bundleName_, targetId, bindParamMap, callback);
711 }
712 
713 
RegisterDevStatusCallback()714 int32_t DeviceManagerFfiImpl::RegisterDevStatusCallback()
715 {
716     LOGI("RegisterDevStatusCallback start for bundleName %{public}s", bundleName_.c_str());
717     {
718         std::lock_guard<std::mutex> autoLock(g_deviceStatusCallbackMapMutex);
719         if (g_deviceStatusCallbackMap.find(bundleName_) != g_deviceStatusCallbackMap.end()) {
720             LOGI("bundleName already register.");
721             return ERR_OK;
722         }
723     }
724     auto callback = std::make_shared<DmFfiDeviceStatusCallback>(bundleName_);
725     int32_t ret = DeviceManager::GetInstance().RegisterDevStatusCallback(bundleName_, "", callback);
726     if (ret != 0) {
727         ret = TransformErrCode(ret);
728         LOGE("RegisterDevStatusCallback failed for bundleName %{public}s", bundleName_.c_str());
729         return ret;
730     }
731     {
732         std::lock_guard<std::mutex> autoLock(g_deviceStatusCallbackMapMutex);
733         CHECK_SIZE_RETURN(g_deviceStatusCallbackMap, DM_ERR_FAILED);
734         g_deviceStatusCallbackMap[bundleName_] = callback;
735     }
736     return ERR_OK;
737 }
738 
RegisterDiscoveryCallback()739 int32_t DeviceManagerFfiImpl::RegisterDiscoveryCallback()
740 {
741     auto discoveryCallback = std::make_shared<DmFfiDiscoveryCallback>(bundleName_);
742     {
743         std::lock_guard<std::mutex> autoLock(g_discoveryCallbackMapMutex);
744         CHECK_SIZE_RETURN(g_DiscoveryCallbackMap, DM_ERR_FAILED);
745         g_DiscoveryCallbackMap[bundleName_] = discoveryCallback;
746     }
747     discoveryCallback->IncreaseRefCount();
748     return ERR_OK;
749 }
750 
RegisterPublishCallback()751 int32_t DeviceManagerFfiImpl::RegisterPublishCallback()
752 {
753     auto publishCallback = std::make_shared<DmFfiPublishCallback>(bundleName_);
754     {
755         std::lock_guard<std::mutex> autoLock(g_publishCallbackMapMutex);
756         CHECK_SIZE_RETURN(g_publishCallbackMap, DM_ERR_FAILED);
757         g_publishCallbackMap[bundleName_] = publishCallback;
758     }
759     publishCallback->IncreaseRefCount();
760     return ERR_OK;
761 }
762 
RegisterReplyCallback()763 int32_t DeviceManagerFfiImpl::RegisterReplyCallback()
764 {
765     auto dmUiCallback = std::make_shared<DmFfiDeviceManagerUiCallback>(bundleName_);
766     int32_t ret = DeviceManager::GetInstance().RegisterDeviceManagerFaCallback(bundleName_, dmUiCallback);
767     if (ret != 0) {
768         ret = TransformErrCode(ret);
769         LOGE("RegisterDeviceManagerFaCallback failed for bundleName %{public}s", bundleName_.c_str());
770         return ret;
771     }
772     {
773         std::lock_guard<std::mutex> autoLock(g_dmUiCallbackMapMutex);
774         CHECK_SIZE_RETURN(g_dmUiCallbackMap, DM_ERR_FAILED);
775         g_dmUiCallbackMap[bundleName_] = dmUiCallback;
776     }
777     return ERR_OK;
778 }
779 
ReleaseDevStatusCallback()780 int32_t DeviceManagerFfiImpl::ReleaseDevStatusCallback()
781 {
782     {
783         std::lock_guard<std::mutex> autoLock(g_deviceStatusCallbackMapMutex);
784         auto iter = g_deviceStatusCallbackMap.find(bundleName_);
785         if (iter == g_deviceStatusCallbackMap.end()) {
786             LOGE("ReleaseDmCallback: cannot find statusCallback for bundleName %{public}s", bundleName_.c_str());
787             return ERR_INVALID_PARAMS;
788         }
789     }
790     int32_t ret = DeviceManager::GetInstance().UnRegisterDevStatusCallback(bundleName_);
791     if (ret != 0) {
792         ret = TransformErrCode(ret);
793         LOGE("UnRegisterDevStatusCallback failed for bundleName %{public}s", bundleName_.c_str());
794         return ret;
795     }
796     {
797         std::lock_guard<std::mutex> autoLock(g_deviceStatusCallbackMapMutex);
798         g_deviceStatusCallbackMap.erase(bundleName_);
799     }
800     return ERR_OK;
801 }
802 
ReleaseDiscoveryCallback()803 int32_t DeviceManagerFfiImpl::ReleaseDiscoveryCallback()
804 {
805     LOGI("ReleaseDiscoveryCallback for bundleName %{public}s", bundleName_.c_str());
806     std::shared_ptr<DmFfiDiscoveryCallback> DiscoveryCallback = nullptr;
807     {
808         std::lock_guard<std::mutex> autoLock(g_discoveryCallbackMapMutex);
809         auto iter = g_DiscoveryCallbackMap.find(bundleName_);
810         if (iter == g_DiscoveryCallbackMap.end()) {
811             return ERR_OK;
812         }
813         DiscoveryCallback = iter->second;
814     }
815     DiscoveryCallback->DecreaseRefCount();
816     if (DiscoveryCallback->GetRefCount() == 0) {
817         std::lock_guard<std::mutex> autoLock(g_discoveryCallbackMapMutex);
818         g_DiscoveryCallbackMap.erase(bundleName_);
819     }
820     return ERR_OK;
821 }
822 
ReleasePublishCallback()823 int32_t DeviceManagerFfiImpl::ReleasePublishCallback()
824 {
825     LOGI("ReleasePublishCallback for bundleName %{public}s", bundleName_.c_str());
826     std::shared_ptr<DmFfiPublishCallback> publishCallback = nullptr;
827     {
828         std::lock_guard<std::mutex> autoLock(g_publishCallbackMapMutex);
829         auto iter = g_publishCallbackMap.find(bundleName_);
830         if (iter == g_publishCallbackMap.end()) {
831             return ERR_OK;
832         }
833         publishCallback = iter->second;
834     }
835     publishCallback->DecreaseRefCount();
836     if (publishCallback->GetRefCount() == 0) {
837         std::lock_guard<std::mutex> autoLock(g_publishCallbackMapMutex);
838         g_publishCallbackMap.erase(bundleName_);
839     }
840     return ERR_OK;
841 }
842 
ReleaseReplyCallback()843 int32_t DeviceManagerFfiImpl::ReleaseReplyCallback()
844 {
845     {
846         std::lock_guard<std::mutex> autoLock(g_dmUiCallbackMapMutex);
847         auto iter = g_dmUiCallbackMap.find(bundleName_);
848         if (iter == g_dmUiCallbackMap.end()) {
849             LOGE("cannot find dmFaCallback for bundleName %{public}s", bundleName_.c_str());
850             return ERR_INVALID_PARAMS;
851         }
852     }
853     int32_t ret = DeviceManager::GetInstance().UnRegisterDeviceManagerFaCallback(bundleName_);
854     if (ret != 0) {
855         ret = TransformErrCode(ret);
856         LOGE("UnRegisterDeviceManagerFaCallback failed for bundleName %{public}s", bundleName_.c_str());
857         return ret;
858     }
859     {
860         std::lock_guard<std::mutex> autoLock(g_dmUiCallbackMapMutex);
861         g_dmUiCallbackMap.erase(bundleName_);
862     }
863     return ERR_OK;
864 }
865 
866 
RegisterCallbackByType(const std::string & type,void * callback)867 void DeviceManagerFfiImpl::RegisterCallbackByType(const std::string &type, void *callback)
868 {
869     std::lock_guard<std::mutex> autoLock(callbackLock);
870     if (type == DM_FFI_EVENT_DEVICE_STATE_CHANGE) {
871         deviceStateChangedCallback = CJLambda::Create(
872             reinterpret_cast<void (*)(int32_t, FfiDeviceBasicInfo *)>(callback));
873     } else if (type == DM_FFI_EVENT_DEVICE_DISCOVER_SUCCESS) {
874         discoverSuccessCallback = CJLambda::Create(reinterpret_cast<void (*)(FfiDeviceBasicInfo *)>(callback));
875     } else if (type == DM_FFI_EVENT_DEVICE_NAME_CHANGE) {
876         deviceNameChangedCallback = CJLambda::Create(reinterpret_cast<void (*)(const char *)>(callback));
877     } else if (type == DM_FFI_EVENT_DEVICE_DISCOVER_FAIL) {
878         deviceDiscoverFailedCallback = CJLambda::Create(reinterpret_cast<void (*)(int32_t)>(callback));
879     } else {
880         LOGE("RegisterCallbackByType call with wrong type.");
881     }
882 }
883 
Off(const std::string & type)884 void DeviceManagerFfiImpl::Off(const std::string &type)
885 {
886     std::lock_guard<std::mutex> autoLock(callbackLock);
887     if (type == DM_FFI_EVENT_DEVICE_STATE_CHANGE) {
888         deviceStateChangedCallback = nullptr;
889     } else if (type == DM_FFI_EVENT_DEVICE_DISCOVER_SUCCESS) {
890         discoverSuccessCallback = nullptr;
891     } else if (type == DM_FFI_EVENT_DEVICE_NAME_CHANGE) {
892         deviceNameChangedCallback = nullptr;
893     } else if (type == DM_FFI_EVENT_DEVICE_DISCOVER_FAIL) {
894         deviceDiscoverFailedCallback = nullptr;
895     } else {
896         LOGE("Off call with wrong type.");
897     }
898 }
899 } // namespace OHOS::DistributedHardware
900