• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (c) 2022-2023 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 "devicestatus_service.h"
17 
18 #include <unistd.h>
19 #include <vector>
20 
21 #include <ipc_skeleton.h>
22 
23 #include "hitrace_meter.h"
24 #include "hisysevent.h"
25 #include "if_system_ability_manager.h"
26 #include "iservice_registry.h"
27 #include "string_ex.h"
28 #include "system_ability_definition.h"
29 
30 #ifdef OHOS_BUILD_ENABLE_COORDINATION
31 #include "coordination_device_manager.h"
32 #include "coordination_event_manager.h"
33 #include "coordination_sm.h"
34 #endif // OHOS_BUILD_ENABLE_COORDINATION
35 #include "devicestatus_common.h"
36 #include "devicestatus_hisysevent.h"
37 
38 namespace OHOS {
39 namespace Msdp {
40 namespace DeviceStatus {
41 namespace {
42 constexpr OHOS::HiviewDFX::HiLogLabel LABEL { LOG_CORE, MSDP_DOMAIN_ID, "DeviceStatusService" };
43 constexpr int32_t DEFAULT_WAIT_TIME_MS { 1000 };
44 constexpr int32_t WAIT_FOR_ONCE { 1 };
45 constexpr int32_t MAX_N_RETRIES { 100 };
46 
47 struct device_status_epoll_event {
48     int32_t fd { 0 };
49     EpollEventType event_type { EPOLL_EVENT_BEGIN };
50 };
51 
52 #ifndef OHOS_BUILD_ENABLE_RUST_IMPL
53 const bool REGISTER_RESULT =
54     SystemAbility::MakeAndRegisterAbility(DelayedSpSingleton<DeviceStatusService>::GetInstance().GetRefPtr());
55 #endif // OHOS_BUILD_ENABLE_RUST_IMPL
56 } // namespace
57 
DeviceStatusService()58 DeviceStatusService::DeviceStatusService() : SystemAbility(MSDP_DEVICESTATUS_SERVICE_ID, true)
59 {}
60 
~DeviceStatusService()61 DeviceStatusService::~DeviceStatusService()
62 {}
63 
OnDump()64 void DeviceStatusService::OnDump()
65 {}
66 
OnStart()67 void DeviceStatusService::OnStart()
68 {
69     CALL_INFO_TRACE;
70     if (ready_) {
71         FI_HILOGE("On start is ready, nothing to do");
72         return;
73     }
74 
75     uint64_t tid = GetThisThreadId();
76     delegateTasks_.SetWorkerThreadId(tid);
77 
78     if (!Init()) {
79         FI_HILOGE("On start call init fail");
80         return;
81     }
82 #ifndef OHOS_BUILD_ENABLE_RUST_IMPL
83     if (!Publish(DelayedSpSingleton<DeviceStatusService>::GetInstance())) {
84         FI_HILOGE("On start register to system ability manager failed");
85         return;
86     }
87 #endif // OHOS_BUILD_ENABLE_RUST_IMPL
88     state_ = ServiceRunningState::STATE_RUNNING;
89     ready_ = true;
90     worker_ = std::thread(std::bind(&DeviceStatusService::OnThread, this));
91 }
92 
OnStop()93 void DeviceStatusService::OnStop()
94 {
95     CALL_INFO_TRACE;
96     if (!ready_) {
97         return;
98     }
99     ready_ = false;
100     state_ = ServiceRunningState::STATE_EXIT;
101 
102     delegateTasks_.PostAsyncTask([]() -> int32_t {
103         FI_HILOGD("No op");
104         return RET_OK;
105     });
106     if (worker_.joinable()) {
107         worker_.join();
108     }
109 }
110 
GetDelegateTasks()111 IDelegateTasks& DeviceStatusService::GetDelegateTasks()
112 {
113     return delegateTasks_;
114 }
115 
GetDeviceManager()116 IDeviceManager& DeviceStatusService::GetDeviceManager()
117 {
118     return devMgr_;
119 }
120 
GetTimerManager()121 ITimerManager& DeviceStatusService::GetTimerManager()
122 {
123     return timerMgr_;
124 }
125 
GetDragManager()126 IDragManager& DeviceStatusService::GetDragManager()
127 {
128     return dragMgr_;
129 }
130 
Dump(int32_t fd,const std::vector<std::u16string> & args)131 int32_t DeviceStatusService::Dump(int32_t fd, const std::vector<std::u16string>& args)
132 {
133     CALL_DEBUG_ENTER;
134     if (fd < 0) {
135         FI_HILOGE("fd is invalid");
136         return RET_NG;
137     }
138     if (args.empty()) {
139         FI_HILOGE("param cannot be empty");
140         dprintf(fd, "param cannot be empty\n");
141         DS_DUMPER->DumpHelpInfo(fd);
142         return RET_NG;
143     }
144     std::vector<std::string> argList;
145     std::transform(args.begin(), args.end(), std::back_inserter(argList),
146         [](const std::u16string &arg) {
147         return Str16ToStr8(arg);
148     });
149 
150     std::vector<Data> datas;
151     for (auto type = TYPE_ABSOLUTE_STILL; type <= TYPE_LID_OPEN; type = static_cast<Type>(type + 1)) {
152         Data data = GetCache(type);
153         if (data.value != OnChangedValue::VALUE_INVALID) {
154             datas.emplace_back(data);
155         }
156     }
157     DS_DUMPER->ParseCommand(fd, argList, datas);
158     return RET_OK;
159 }
160 
Init()161 bool DeviceStatusService::Init()
162 {
163     CALL_DEBUG_ENTER;
164     if (devicestatusManager_ == nullptr) {
165         FI_HILOGW("devicestatusManager_ is nullptr");
166         auto ms = DelayedSpSingleton<DeviceStatusService>::GetInstance();
167         devicestatusManager_ = std::make_shared<DeviceStatusManager>(ms);
168     }
169     if (!devicestatusManager_->Init()) {
170         FI_HILOGE("OnStart init fail");
171         return false;
172     }
173     if (EpollCreate(MAX_EVENT_SIZE) < 0) {
174         FI_HILOGE("Create epoll failed");
175         return false;
176     }
177 
178     if (InitDelegateTasks() != RET_OK) {
179         FI_HILOGE("Delegate tasks init failed");
180         goto INIT_FAIL;
181     }
182     if (InitTimerMgr() != RET_OK) {
183         FI_HILOGE("TimerMgr init failed");
184         goto INIT_FAIL;
185     }
186     if (devMgr_.Init(this) != RET_OK) {
187         FI_HILOGE("DevMgr init failed");
188         goto INIT_FAIL;
189     }
190     if (dragMgr_.Init(this) != RET_OK) {
191         FI_HILOGE("Drag manager init failed");
192         goto INIT_FAIL;
193     }
194 #ifdef OHOS_BUILD_ENABLE_MOTION_DRAG
195     if (motionDrag_.Init(this) != RET_OK) {
196         FI_HILOGE("Drag adapter init failed");
197         goto INIT_FAIL;
198     }
199 #endif // OHOS_BUILD_ENABLE_MOTION_DRAG
200     if (DS_DUMPER->Init(this) != RET_OK) {
201         FI_HILOGE("Dump init failed");
202         goto INIT_FAIL;
203     }
204 
205 #ifdef OHOS_BUILD_ENABLE_COORDINATION
206     COOR_EVENT_MGR->SetIContext(this);
207     COOR_SM->Init();
208 #endif // OHOS_BUILD_ENABLE_COORDINATION
209     return true;
210 
211 INIT_FAIL:
212     EpollClose();
213     return false;
214 }
215 
IsServiceReady() const216 bool DeviceStatusService::IsServiceReady() const
217 {
218     return ready_;
219 }
220 
GetDeviceStatusManager() const221 std::shared_ptr<DeviceStatusManager> DeviceStatusService::GetDeviceStatusManager() const
222 {
223     return devicestatusManager_;
224 }
225 
Subscribe(Type type,ActivityEvent event,ReportLatencyNs latency,sptr<IRemoteDevStaCallback> callback)226 void DeviceStatusService::Subscribe(Type type, ActivityEvent event, ReportLatencyNs latency,
227     sptr<IRemoteDevStaCallback> callback)
228 {
229     FI_HILOGI("Enter event:%{public}d, latency:%{public}d", event, latency);
230     CHKPV(devicestatusManager_);
231     auto appInfo = std::make_shared<AppInfo>();
232     appInfo->uid = GetCallingUid();
233     appInfo->pid = GetCallingPid();
234     appInfo->tokenId = GetCallingTokenID();
235     devicestatusManager_->GetPackageName(appInfo->tokenId, appInfo->packageName);
236     appInfo->type = type;
237     appInfo->callback = callback;
238     DS_DUMPER->SaveAppInfo(appInfo);
239     devicestatusManager_->Subscribe(type, event, latency, callback);
240     FinishTrace(HITRACE_TAG_MSDP);
241     ReportSensorSysEvent(type, true);
242     WriteSubscribeHiSysEvent(appInfo->uid, appInfo->packageName, type);
243 }
244 
Unsubscribe(Type type,ActivityEvent event,sptr<IRemoteDevStaCallback> callback)245 void DeviceStatusService::Unsubscribe(Type type, ActivityEvent event, sptr<IRemoteDevStaCallback> callback)
246 {
247     FI_HILOGE("EnterUNevent:%{public}d", event);
248     CHKPV(devicestatusManager_);
249     auto appInfo = std::make_shared<AppInfo>();
250     appInfo->uid = IPCSkeleton::GetCallingUid();
251     appInfo->pid = IPCSkeleton::GetCallingPid();
252     appInfo->tokenId = IPCSkeleton::GetCallingTokenID();
253     appInfo->packageName = DS_DUMPER->GetPackageName(appInfo->tokenId);
254     appInfo->type = type;
255     appInfo->callback = callback;
256     DS_DUMPER->RemoveAppInfo(appInfo);
257     StartTrace(HITRACE_TAG_MSDP, "serviceUnSubscribeStart");
258     devicestatusManager_->Unsubscribe(type, event, callback);
259     FinishTrace(HITRACE_TAG_MSDP);
260     ReportSensorSysEvent(type, false);
261     WriteUnSubscribeHiSysEvent(appInfo->uid, appInfo->packageName, type);
262 }
263 
GetCache(const Type & type)264 Data DeviceStatusService::GetCache(const Type& type)
265 {
266     CALL_DEBUG_ENTER;
267     if (devicestatusManager_ == nullptr) {
268         Data data = {type, OnChangedValue::VALUE_EXIT};
269         data.value = OnChangedValue::VALUE_INVALID;
270         FI_HILOGI("Get latest device status data func is nullptr, return default!");
271         return data;
272     }
273     return devicestatusManager_->GetLatestDeviceStatusData(type);
274 }
275 
ReportSensorSysEvent(int32_t type,bool enable)276 void DeviceStatusService::ReportSensorSysEvent(int32_t type, bool enable)
277 {
278     auto callerToken = GetCallingTokenID();
279     std::string packageName;
280     CHKPV(devicestatusManager_);
281     devicestatusManager_->GetPackageName(callerToken, packageName);
282     auto uid = GetCallingUid();
283     std::string str = enable ? "Subscribe" : "Unsubscribe";
284     int32_t ret = HiSysEventWrite(
285         OHOS::HiviewDFX::HiSysEvent::Domain::MSDP,
286         str,
287         OHOS::HiviewDFX::HiSysEvent::EventType::STATISTIC,
288         "UID", uid,
289         "PKGNAME", packageName,
290         "TYPE", type);
291     if (ret != 0) {
292         FI_HILOGE("HiviewDFX write failed, ret:%{public}d", ret);
293     }
294 }
295 
AllocSocketFd(const std::string & programName,int32_t moduleType,int32_t & toReturnClientFd,int32_t & tokenType)296 int32_t DeviceStatusService::AllocSocketFd(const std::string &programName, int32_t moduleType,
297     int32_t &toReturnClientFd, int32_t &tokenType)
298 {
299     FI_HILOGD("Enter, programName:%{public}s, moduleType:%{public}d", programName.c_str(), moduleType);
300 
301     toReturnClientFd = -1;
302     int32_t serverFd = -1;
303     int32_t pid = GetCallingPid();
304     int32_t uid = GetCallingUid();
305     int32_t ret = delegateTasks_.PostSyncTask(std::bind(&StreamServer::AddSocketPairInfo, this,
306         programName, moduleType, uid, pid, serverFd, std::ref(toReturnClientFd), tokenType));
307     if (ret != RET_OK) {
308         FI_HILOGE("Call Add socket pair info failed, return:%{public}d", ret);
309         return RET_ERR;
310     }
311     FI_HILOGD("Leave, programName:%{public}s, moduleType:%{public}d, alloc success",
312         programName.c_str(), moduleType);
313     return RET_OK;
314 }
315 
OnConnected(SessionPtr s)316 void DeviceStatusService::OnConnected(SessionPtr s)
317 {
318     CHKPV(s);
319     FI_HILOGI("fd:%{public}d", s->GetFd());
320 }
321 
OnDisconnected(SessionPtr s)322 void DeviceStatusService::OnDisconnected(SessionPtr s)
323 {
324     CHKPV(s);
325     FI_HILOGW("Enter, session desc:%{public}s, fd:%{public}d", s->GetDescript().c_str(), s->GetFd());
326 }
327 
AddEpoll(EpollEventType type,int32_t fd)328 int32_t DeviceStatusService::AddEpoll(EpollEventType type, int32_t fd)
329 {
330     if (!(type >= EPOLL_EVENT_BEGIN && type < EPOLL_EVENT_END)) {
331         FI_HILOGE("Invalid type:%{public}d", type);
332         return RET_ERR;
333     }
334     if (fd < 0) {
335         FI_HILOGE("Invalid fd:%{public}d", fd);
336         return RET_ERR;
337     }
338     auto eventData = static_cast<device_status_epoll_event*>(malloc(sizeof(device_status_epoll_event)));
339     if (!eventData) {
340         FI_HILOGE("Malloc failed");
341         return RET_ERR;
342     }
343     eventData->fd = fd;
344     eventData->event_type = type;
345     FI_HILOGD("userdata:[fd:%{public}d, type:%{public}d]", eventData->fd, eventData->event_type);
346 
347     struct epoll_event ev {};
348     ev.events = EPOLLIN;
349     ev.data.ptr = eventData;
350     if (EpollCtl(fd, EPOLL_CTL_ADD, ev, -1) < 0) {
351         free(eventData);
352         eventData = nullptr;
353         ev.data.ptr = nullptr;
354         FI_HILOGE("EpollCtl failed");
355         return RET_ERR;
356     }
357     return RET_OK;
358 }
359 
DelEpoll(EpollEventType type,int32_t fd)360 int32_t DeviceStatusService::DelEpoll(EpollEventType type, int32_t fd)
361 {
362     if (!(type >= EPOLL_EVENT_BEGIN && type < EPOLL_EVENT_END)) {
363         FI_HILOGE("Invalid type:%{public}d", type);
364         return RET_ERR;
365     }
366     if (fd < 0) {
367         FI_HILOGE("Invalid fd:%{public}d", fd);
368         return RET_ERR;
369     }
370     struct epoll_event ev {};
371     if (EpollCtl(fd, EPOLL_CTL_DEL, ev, -1) < 0) {
372         FI_HILOGE("DelEpoll failed");
373         return RET_ERR;
374     }
375     return RET_OK;
376 }
377 
IsRunning() const378 bool DeviceStatusService::IsRunning() const
379 {
380     return (state_ == ServiceRunningState::STATE_RUNNING);
381 }
382 
InitDelegateTasks()383 int32_t DeviceStatusService::InitDelegateTasks()
384 {
385     CALL_INFO_TRACE;
386     if (!delegateTasks_.Init()) {
387         FI_HILOGE("The delegate task init failed");
388         return RET_ERR;
389     }
390     int32_t ret = AddEpoll(EPOLL_EVENT_ETASK, delegateTasks_.GetReadFd());
391     if (ret != RET_OK) {
392         FI_HILOGE("AddEpoll error ret:%{public}d", ret);
393     }
394     FI_HILOGI("AddEpoll, epollfd:%{public}d, fd:%{public}d", epollFd_, delegateTasks_.GetReadFd());
395     return ret;
396 }
397 
398 
InitTimerMgr()399 int32_t DeviceStatusService::InitTimerMgr()
400 {
401     CALL_INFO_TRACE;
402     int32_t ret = timerMgr_.Init(this);
403     if (ret != RET_OK) {
404         FI_HILOGE("TimerMgr init failed");
405         return ret;
406     }
407     ret = AddEpoll(EPOLL_EVENT_TIMER, timerMgr_.GetTimerFd());
408     if (ret != RET_OK) {
409         FI_HILOGE("AddEpoll for timer fail");
410     }
411     return ret;
412 }
413 
OnThread()414 void DeviceStatusService::OnThread()
415 {
416     SetThreadName(std::string("device_status_service"));
417     uint64_t tid = GetThisThreadId();
418     delegateTasks_.SetWorkerThreadId(tid);
419     FI_HILOGD("Main worker thread start, tid:%{public}" PRId64 "", tid);
420     EnableDevMgr(MAX_N_RETRIES);
421 
422     while (state_ == ServiceRunningState::STATE_RUNNING) {
423         epoll_event ev[MAX_EVENT_SIZE] {};
424         int32_t count = EpollWait(MAX_EVENT_SIZE, -1, ev[0]);
425         for (int32_t i = 0; i < count && state_ == ServiceRunningState::STATE_RUNNING; i++) {
426             auto epollEvent = reinterpret_cast<device_status_epoll_event*>(ev[i].data.ptr);
427             CHKPC(epollEvent);
428             if (epollEvent->event_type == EPOLL_EVENT_SOCKET) {
429                 OnEpollEvent(ev[i]);
430             } else if (epollEvent->event_type == EPOLL_EVENT_ETASK) {
431                 OnDelegateTask(ev[i]);
432             } else if (epollEvent->event_type == EPOLL_EVENT_TIMER) {
433                 OnTimeout(ev[i]);
434             } else if (epollEvent->event_type == EPOLL_EVENT_DEVICE_MGR) {
435                 OnDeviceMgr(ev[i]);
436             } else {
437                 FI_HILOGW("Unknown epoll event type:%{public}d", epollEvent->event_type);
438             }
439         }
440     }
441     FI_HILOGD("Main worker thread stop, tid:%{public}" PRId64 "", tid);
442 }
443 
OnDelegateTask(const epoll_event & ev)444 void DeviceStatusService::OnDelegateTask(const epoll_event &ev)
445 {
446     if ((ev.events & EPOLLIN) == 0) {
447         FI_HILOGW("Not epollin");
448         return;
449     }
450     DelegateTasks::TaskData data {};
451     ssize_t res = read(delegateTasks_.GetReadFd(), &data, sizeof(data));
452     if (res == -1) {
453         FI_HILOGW("Read failed erron:%{public}d", errno);
454     }
455     FI_HILOGD("RemoteRequest notify td:%{public}" PRId64 ", std:%{public}" PRId64 ""
456         ", taskId:%{public}d", GetThisThreadId(), data.tid, data.taskId);
457     delegateTasks_.ProcessTasks();
458 }
459 
OnTimeout(const epoll_event & ev)460 void DeviceStatusService::OnTimeout(const epoll_event &ev)
461 {
462     CALL_INFO_TRACE;
463     if ((ev.events & EPOLLIN) == EPOLLIN) {
464         uint64_t expiration {};
465         ssize_t ret = read(timerMgr_.GetTimerFd(), &expiration, sizeof(expiration));
466         if (ret < 0) {
467             FI_HILOGE("Read expiration failed:%{public}s", strerror(errno));
468         }
469         timerMgr_.ProcessTimers();
470     } else if ((ev.events & (EPOLLHUP | EPOLLERR)) != 0) {
471         FI_HILOGE("Epoll hangup:%{public}s", strerror(errno));
472     }
473 }
474 
OnDeviceMgr(const epoll_event & ev)475 void DeviceStatusService::OnDeviceMgr(const epoll_event &ev)
476 {
477     CALL_INFO_TRACE;
478     if ((ev.events & EPOLLIN) == EPOLLIN) {
479         devMgr_.Dispatch(ev);
480     } else if ((ev.events & (EPOLLHUP | EPOLLERR)) != 0) {
481         FI_HILOGE("Epoll hangup:%{public}s", strerror(errno));
482     }
483 }
484 
EnableDevMgr(int32_t nRetries)485 int32_t DeviceStatusService::EnableDevMgr(int32_t nRetries)
486 {
487     CALL_INFO_TRACE;
488     static int32_t timerId { -1 };
489     int32_t ret = devMgr_.Enable();
490     if (ret != RET_OK) {
491         FI_HILOGE("Failed to enable device manager");
492         if (nRetries > 0) {
493             timerId = timerMgr_.AddTimer(DEFAULT_WAIT_TIME_MS, WAIT_FOR_ONCE,
494                 std::bind(&DeviceStatusService::EnableDevMgr, this, nRetries - 1));
495             if (timerId < 0) {
496                 FI_HILOGE("AddTimer failed, Failed to enable device manager");
497             }
498         } else {
499             FI_HILOGE("Maximum number of retries exceeded, Failed to enable device manager");
500         }
501         return ret;
502     }
503     AddEpoll(EPOLL_EVENT_DEVICE_MGR, devMgr_.GetFd());
504     if (timerId >= 0) {
505         timerMgr_.RemoveTimer(timerId);
506         timerId = -1;
507     }
508     return RET_OK;
509 }
510 
DisableDevMgr()511 void DeviceStatusService::DisableDevMgr()
512 {
513     DelEpoll(EPOLL_EVENT_DEVICE_MGR, devMgr_.GetFd());
514     devMgr_.Disable();
515 }
516 
RegisterCoordinationListener()517 int32_t DeviceStatusService::RegisterCoordinationListener()
518 {
519     CALL_DEBUG_ENTER;
520 #ifdef OHOS_BUILD_ENABLE_COORDINATION
521     int32_t pid = GetCallingPid();
522     int32_t ret = delegateTasks_.PostSyncTask(
523         std::bind(&DeviceStatusService::OnRegisterCoordinationListener, this, pid));
524     if (ret != RET_OK) {
525         FI_HILOGE("On register coordination listener failed, ret:%{public}d", ret);
526         return RET_ERR;
527     }
528 #endif // OHOS_BUILD_ENABLE_COORDINATION
529     return RET_OK;
530 }
531 
UnregisterCoordinationListener()532 int32_t DeviceStatusService::UnregisterCoordinationListener()
533 {
534     CALL_DEBUG_ENTER;
535 #ifdef OHOS_BUILD_ENABLE_COORDINATION
536     int32_t pid = GetCallingPid();
537     int32_t ret = delegateTasks_.PostSyncTask(
538         std::bind(&DeviceStatusService::OnUnregisterCoordinationListener, this, pid));
539     if (ret != RET_OK) {
540         FI_HILOGE("On unregister coordination listener failed, ret:%{public}d", ret);
541         return RET_ERR;
542     }
543 #endif // OHOS_BUILD_ENABLE_COORDINATION
544     return RET_OK;
545 }
546 
PrepareCoordination(int32_t userData)547 int32_t DeviceStatusService::PrepareCoordination(int32_t userData)
548 {
549     CALL_DEBUG_ENTER;
550 #ifdef OHOS_BUILD_ENABLE_COORDINATION
551     int32_t pid = GetCallingPid();
552     AddSessionDeletedCallback(pid, std::bind(&CoordinationSM::OnSessionLost, COOR_SM, std::placeholders::_1));
553     int32_t ret = delegateTasks_.PostSyncTask(
554         std::bind(&DeviceStatusService::OnPrepareCoordination, this, pid, userData));
555     if (ret != RET_OK) {
556         FI_HILOGE("On prepare coordination failed, ret:%{public}d", ret);
557         return ret;
558     }
559 #else
560     (void)(userData);
561 #endif // OHOS_BUILD_ENABLE_COORDINATION
562     return RET_OK;
563 }
564 
UnprepareCoordination(int32_t userData)565 int32_t DeviceStatusService::UnprepareCoordination(int32_t userData)
566 {
567     CALL_DEBUG_ENTER;
568 #ifdef OHOS_BUILD_ENABLE_COORDINATION
569     int32_t pid = GetCallingPid();
570     int32_t ret = delegateTasks_.PostSyncTask(
571         std::bind(&DeviceStatusService::OnUnprepareCoordination, this, pid, userData));
572     if (ret != RET_OK) {
573         FI_HILOGE("OnUnprepareCoordination failed, ret:%{public}d", ret);
574         return ret;
575     }
576 #else
577     (void)(userData);
578 #endif // OHOS_BUILD_ENABLE_COORDINATION
579     return RET_OK;
580 }
581 
ActivateCoordination(int32_t userData,const std::string & remoteNetworkId,int32_t startDeviceId)582 int32_t DeviceStatusService::ActivateCoordination(int32_t userData,
583     const std::string &remoteNetworkId, int32_t startDeviceId)
584 {
585     CALL_DEBUG_ENTER;
586 #ifdef OHOS_BUILD_ENABLE_COORDINATION
587     int32_t pid = GetCallingPid();
588     int32_t ret = delegateTasks_.PostSyncTask(
589         std::bind(&DeviceStatusService::OnActivateCoordination,
590         this, pid, userData, remoteNetworkId, startDeviceId));
591     if (ret != RET_OK) {
592         FI_HILOGE("On activate coordination failed, ret:%{public}d", ret);
593         return ret;
594     }
595 #else
596     (void)(userData);
597     (void)(remoteNetworkId);
598     (void)(startDeviceId);
599 #endif // OHOS_BUILD_ENABLE_COORDINATION
600     return RET_OK;
601 }
602 
DeactivateCoordination(int32_t userData,bool isUnchained)603 int32_t DeviceStatusService::DeactivateCoordination(int32_t userData, bool isUnchained)
604 {
605     CALL_DEBUG_ENTER;
606 #ifdef OHOS_BUILD_ENABLE_COORDINATION
607     int32_t pid = GetCallingPid();
608     int32_t ret = delegateTasks_.PostSyncTask(
609         std::bind(&DeviceStatusService::OnDeactivateCoordination, this, pid, userData, isUnchained));
610     if (ret != RET_OK) {
611         FI_HILOGE("On deactivate coordination failed, ret:%{public}d", ret);
612         return ret;
613     }
614 #else
615     (void)(userData);
616     (void)(isUnchained);
617 #endif // OHOS_BUILD_ENABLE_COORDINATION
618     return RET_OK;
619 }
620 
GetCoordinationState(int32_t userData,const std::string & deviceId)621 int32_t DeviceStatusService::GetCoordinationState(int32_t userData, const std::string &deviceId)
622 {
623     CALL_DEBUG_ENTER;
624 #ifdef OHOS_BUILD_ENABLE_COORDINATION
625     int32_t pid = GetCallingPid();
626     int32_t ret = delegateTasks_.PostSyncTask(
627         std::bind(&DeviceStatusService::OnGetCoordinationState, this, pid, userData, deviceId));
628     if (ret != RET_OK) {
629         FI_HILOGE("On get coordination state failed, ret:%{public}d", ret);
630         return ret;
631     }
632 #else
633     (void)(userData);
634     (void)(deviceId);
635     FI_HILOGW("Get coordination state does not support");
636 #endif // OHOS_BUILD_ENABLE_COORDINATION
637     return RET_OK;
638 }
639 
AddDraglistener()640 int32_t DeviceStatusService::AddDraglistener()
641 {
642     CALL_DEBUG_ENTER;
643     int32_t pid = GetCallingPid();
644     auto session = GetSession(GetClientFd(pid));
645     CHKPR(session, RET_ERR);
646     int32_t ret = delegateTasks_.PostSyncTask(
647         std::bind(&DragManager::AddListener, &dragMgr_, session));
648     if (ret != RET_OK) {
649         FI_HILOGE("AddListener failed, ret:%{public}d", ret);
650     }
651     return ret;
652 }
653 
RemoveDraglistener()654 int32_t DeviceStatusService::RemoveDraglistener()
655 {
656     CALL_DEBUG_ENTER;
657     int32_t pid = GetCallingPid();
658     auto session = GetSession(GetClientFd(pid));
659     if (session == nullptr) {
660         FI_HILOGW("Session is nullptr");
661         return RET_OK;
662     }
663     int32_t ret = delegateTasks_.PostSyncTask(
664         std::bind(&DragManager::RemoveListener, &dragMgr_, session));
665     if (ret != RET_OK) {
666         FI_HILOGE("Remove listener failed, ret:%{public}d", ret);
667     }
668     return ret;
669 }
670 
StartDrag(const DragData & dragData)671 int32_t DeviceStatusService::StartDrag(const DragData &dragData)
672 {
673     CALL_DEBUG_ENTER;
674     int32_t pid = GetCallingPid();
675     AddSessionDeletedCallback(pid, std::bind(&DragManager::OnSessionLost, &dragMgr_, std::placeholders::_1));
676     int32_t ret = delegateTasks_.PostSyncTask(
677         std::bind(&DeviceStatusService::OnStartDrag, this, std::cref(dragData), pid));
678     if (ret != RET_OK) {
679         FI_HILOGE("On start drag failed, ret:%{public}d", ret);
680     }
681     return ret;
682 }
683 
StopDrag(DragResult result,bool hasCustomAnimation)684 int32_t DeviceStatusService::StopDrag(DragResult result, bool hasCustomAnimation)
685 {
686     CALL_DEBUG_ENTER;
687     int32_t ret = delegateTasks_.PostSyncTask(
688         std::bind(&DeviceStatusService::OnStopDrag, this, result, hasCustomAnimation));
689     if (ret != RET_OK) {
690         FI_HILOGE("On stop drag failed, ret:%{public}d", ret);
691     }
692     return ret;
693 }
694 
SetDragWindowVisible(bool visible)695 int32_t DeviceStatusService::SetDragWindowVisible(bool visible)
696 {
697     CALL_DEBUG_ENTER;
698     int32_t ret = delegateTasks_.PostSyncTask(
699         std::bind(&DragManager::OnSetDragWindowVisible, &dragMgr_, visible));
700     if (ret != RET_OK) {
701         FI_HILOGE("On set drag window visible failed, ret:%{public}d", ret);
702     }
703     return ret;
704 }
705 
GetShadowOffset(int32_t & offsetX,int32_t & offsetY,int32_t & width,int32_t & height)706 int32_t DeviceStatusService::GetShadowOffset(int32_t& offsetX, int32_t& offsetY, int32_t& width, int32_t& height)
707 {
708     CALL_DEBUG_ENTER;
709     int32_t ret = delegateTasks_.PostSyncTask(std::bind(&DragManager::OnGetShadowOffset, &dragMgr_,
710         std::ref(offsetX), std::ref(offsetY), std::ref(width), std::ref(height)));
711     if (ret != RET_OK) {
712         FI_HILOGE("Get shadow offset failed, ret:%{public}d", ret);
713     }
714     return ret;
715 }
716 
UpdateShadowPic(const ShadowInfo & shadowInfo)717 int32_t DeviceStatusService::UpdateShadowPic(const ShadowInfo &shadowInfo)
718 {
719     CALL_DEBUG_ENTER;
720     int32_t ret = delegateTasks_.PostSyncTask(
721         std::bind(&DragManager::UpdateShadowPic, &dragMgr_, std::cref(shadowInfo)));
722     if (ret != RET_OK) {
723         FI_HILOGE("Update shadow picture failed, ret:%{public}d", ret);
724     }
725     return ret;
726 }
727 
UpdateDragStyle(DragCursorStyle style)728 int32_t DeviceStatusService::UpdateDragStyle(DragCursorStyle style)
729 {
730     CALL_DEBUG_ENTER;
731     int32_t tid = static_cast<int32_t>(GetCallingTokenID());
732     int32_t pid = GetCallingPid();
733     int32_t ret = delegateTasks_.PostSyncTask(
734         std::bind(&DragManager::UpdateDragStyle, &dragMgr_, style, pid, tid));
735     if (ret != RET_OK) {
736         FI_HILOGE("Update drag style failed, ret:%{public}d", ret);
737     }
738     return ret;
739 }
740 
GetUdKey(std::string & udKey)741 int32_t DeviceStatusService::GetUdKey(std::string &udKey)
742 {
743     CALL_DEBUG_ENTER;
744     int32_t ret = delegateTasks_.PostSyncTask(
745         std::bind(&DragManager::GetUdKey, &dragMgr_, std::ref(udKey)));
746     if (ret != RET_OK) {
747         FI_HILOGE("Get udkey failed, ret:%{public}d", ret);
748     }
749     return ret;
750 }
751 
GetDragTargetPid()752 int32_t DeviceStatusService::GetDragTargetPid()
753 {
754     CALL_DEBUG_ENTER;
755     int32_t ret = delegateTasks_.PostSyncTask(
756         std::bind(&DragManager::GetDragTargetPid, &dragMgr_));
757     if (ret != RET_OK) {
758         FI_HILOGE("Get drag target pid failed, ret:%{public}d", ret);
759     }
760     return ret;
761 }
762 
763 #ifdef OHOS_BUILD_ENABLE_COORDINATION
OnRegisterCoordinationListener(int32_t pid)764 int32_t DeviceStatusService::OnRegisterCoordinationListener(int32_t pid)
765 {
766     CALL_DEBUG_ENTER;
767     auto sess = GetSession(GetClientFd(pid));
768     CHKPR(sess, RET_ERR);
769     sptr<CoordinationEventManager::EventInfo> event = new (std::nothrow) CoordinationEventManager::EventInfo();
770     CHKPR(event, RET_ERR);
771     event->type = CoordinationEventManager::EventType::LISTENER;
772     event->sess = sess;
773     event->msgId = MessageId::COORDINATION_ADD_LISTENER;
774     COOR_EVENT_MGR->AddCoordinationEvent(event);
775     return RET_OK;
776 }
777 
OnUnregisterCoordinationListener(int32_t pid)778 int32_t DeviceStatusService::OnUnregisterCoordinationListener(int32_t pid)
779 {
780     CALL_DEBUG_ENTER;
781     auto sess = GetSession(GetClientFd(pid));
782     sptr<CoordinationEventManager::EventInfo> event = new (std::nothrow) CoordinationEventManager::EventInfo();
783     CHKPR(event, RET_ERR);
784     event->type = CoordinationEventManager::EventType::LISTENER;
785     event->sess = sess;
786     COOR_EVENT_MGR->RemoveCoordinationEvent(event);
787     return RET_OK;
788 }
789 
OnPrepareCoordination(int32_t pid,int32_t userData)790 int32_t DeviceStatusService::OnPrepareCoordination(int32_t pid, int32_t userData)
791 {
792     CALL_DEBUG_ENTER;
793     COOR_SM->PrepareCoordination();
794     std::string deviceId;
795     CoordinationMessage msg = CoordinationMessage::PREPARE;
796     NetPacket pkt(MessageId::COORDINATION_MESSAGE);
797     pkt << userData << deviceId << static_cast<int32_t>(msg);
798     if (pkt.ChkRWError()) {
799         FI_HILOGE("Packet write data failed");
800         return RET_ERR;
801     }
802     auto sess = GetSession(GetClientFd(pid));
803     CHKPR(sess, RET_ERR);
804     if (!sess->SendMsg(pkt)) {
805         FI_HILOGE("Sending failed");
806         return MSG_SEND_FAIL;
807     }
808 #ifdef OHOS_BUILD_ENABLE_MOTION_DRAG
809     motionDrag_.RegisterCallback();
810 #endif // OHOS_BUILD_ENABLE_MOTION_DRAG
811     return RET_OK;
812 }
813 
OnUnprepareCoordination(int32_t pid,int32_t userData)814 int32_t DeviceStatusService::OnUnprepareCoordination(int32_t pid, int32_t userData)
815 {
816     CALL_DEBUG_ENTER;
817     COOR_SM->UnprepareCoordination();
818     std::string deviceId;
819     CoordinationMessage msg = CoordinationMessage::UNPREPARE;
820     NetPacket pkt(MessageId::COORDINATION_MESSAGE);
821     pkt << userData << deviceId << static_cast<int32_t>(msg);
822     if (pkt.ChkRWError()) {
823         FI_HILOGE("Packet write data failed");
824         return RET_ERR;
825     }
826     auto sess = GetSession(GetClientFd(pid));
827     CHKPR(sess, RET_ERR);
828     if (!sess->SendMsg(pkt)) {
829         FI_HILOGE("Sending failed");
830         return MSG_SEND_FAIL;
831     }
832     return RET_OK;
833 }
834 
OnActivateCoordination(int32_t pid,int32_t userData,const std::string & remoteNetworkId,int32_t startDeviceId)835 int32_t DeviceStatusService::OnActivateCoordination(int32_t pid,
836     int32_t userData, const std::string &remoteNetworkId, int32_t startDeviceId)
837 {
838     CALL_DEBUG_ENTER;
839     auto sess = GetSession(GetClientFd(pid));
840     CHKPR(sess, RET_ERR);
841     sptr<CoordinationEventManager::EventInfo> event = new (std::nothrow) CoordinationEventManager::EventInfo();
842     CHKPR(event, RET_ERR);
843     event->type = CoordinationEventManager::EventType::START;
844     event->sess = sess;
845     event->msgId = MessageId::COORDINATION_MESSAGE;
846     event->userData = userData;
847     if (COOR_SM->GetCurrentCoordinationState() == CoordinationState::STATE_OUT ||
848         (COOR_SM->GetCurrentCoordinationState() == CoordinationState::STATE_FREE &&
849         !COOR_DEV_MGR->HasLocalPointerDevice())) {
850         FI_HILOGW("It is currently worn out");
851         NetPacket pkt(event->msgId);
852         pkt << userData << "" << static_cast<int32_t>(CoordinationMessage::ACTIVATE_SUCCESS);
853         if (pkt.ChkRWError()) {
854             FI_HILOGE("Packet write data failed");
855             return RET_ERR;
856         }
857         if (!sess->SendMsg(pkt)) {
858             FI_HILOGE("Sending failed");
859             return RET_ERR;
860         }
861         return RET_OK;
862     }
863     COOR_EVENT_MGR->AddCoordinationEvent(event);
864     int32_t ret = COOR_SM->ActivateCoordination(remoteNetworkId, startDeviceId);
865     if (ret != RET_OK) {
866         FI_HILOGE("On activate coordination failed, ret:%{public}d", ret);
867     }
868     return ret;
869 }
870 
OnDeactivateCoordination(int32_t pid,int32_t userData,bool isUnchained)871 int32_t DeviceStatusService::OnDeactivateCoordination(int32_t pid, int32_t userData, bool isUnchained)
872 {
873     CALL_DEBUG_ENTER;
874     auto sess = GetSession(GetClientFd(pid));
875     CHKPR(sess, RET_ERR);
876     sptr<CoordinationEventManager::EventInfo> event = new (std::nothrow) CoordinationEventManager::EventInfo();
877     CHKPR(event, RET_ERR);
878     event->type = CoordinationEventManager::EventType::STOP;
879     event->sess = sess;
880     event->msgId = MessageId::COORDINATION_MESSAGE;
881     event->userData = userData;
882     COOR_EVENT_MGR->AddCoordinationEvent(event);
883     int32_t ret = COOR_SM->DeactivateCoordination(isUnchained);
884     if (ret != RET_OK) {
885         FI_HILOGE("On deactivate coordination failed, ret:%{public}d", ret);
886         COOR_EVENT_MGR->OnErrorMessage(event->type, CoordinationMessage(ret));
887     }
888     return ret;
889 }
890 
OnGetCoordinationState(int32_t pid,int32_t userData,const std::string & deviceId)891 int32_t DeviceStatusService::OnGetCoordinationState(
892     int32_t pid, int32_t userData, const std::string &deviceId)
893 {
894     CALL_DEBUG_ENTER;
895     auto sess = GetSession(GetClientFd(pid));
896     CHKPR(sess, RET_ERR);
897     sptr<CoordinationEventManager::EventInfo> event = new (std::nothrow) CoordinationEventManager::EventInfo();
898     CHKPR(event, RET_ERR);
899     event->type = CoordinationEventManager::EventType::STATE;
900     event->sess = sess;
901     event->msgId = MessageId::COORDINATION_GET_STATE;
902     event->userData = userData;
903     COOR_EVENT_MGR->AddCoordinationEvent(event);
904     int32_t ret = COOR_SM->GetCoordinationState(deviceId);
905     if (ret != RET_OK) {
906         FI_HILOGE("Get coordination state failed");
907     }
908     return ret;
909 }
910 #endif // OHOS_BUILD_ENABLE_COORDINATION
911 
OnStartDrag(const DragData & dragData,int32_t pid)912 int32_t DeviceStatusService::OnStartDrag(const DragData &dragData, int32_t pid)
913 {
914     CALL_DEBUG_ENTER;
915     auto sess = GetSession(GetClientFd(pid));
916     CHKPR(sess, RET_ERR);
917     int32_t ret = dragMgr_.StartDrag(dragData, sess);
918     if (ret != RET_OK) {
919         FI_HILOGE("StartDrag failed, ret:%{public}d", ret);
920     }
921     return ret;
922 }
923 
OnStopDrag(DragResult result,bool hasCustomAnimation)924 int32_t DeviceStatusService::OnStopDrag(DragResult result, bool hasCustomAnimation)
925 {
926     CALL_DEBUG_ENTER;
927     int32_t ret = dragMgr_.StopDrag(result, hasCustomAnimation);
928     if (ret != RET_OK) {
929         FI_HILOGE("StopDrag failed, ret:%{public}d", ret);
930     }
931     return ret;
932 }
933 } // namespace DeviceStatus
934 } // namespace Msdp
935 } // namespace OHOS
936