• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (c) 2021-2022 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 "power_mgr_service.h"
17 
18 #include <datetime_ex.h>
19 #include <file_ex.h>
20 #include <hisysevent.h>
21 #include <if_system_ability_manager.h>
22 #include <input_manager.h>
23 #include <ipc_skeleton.h>
24 #include <iservice_registry.h>
25 #include <securec.h>
26 #include <string_ex.h>
27 #include <system_ability_definition.h>
28 #include <unistd.h>
29 
30 #include "ability_manager_client.h"
31 #include "permission.h"
32 #include "power_common.h"
33 #include "power_mgr_dumper.h"
34 #include "system_suspend_controller.h"
35 #include "ui_service_mgr_client.h"
36 #include "sysparam.h"
37 #include "watchdog.h"
38 
39 using namespace OHOS::AppExecFwk;
40 using namespace OHOS::AAFwk;
41 
42 namespace OHOS {
43 namespace PowerMgr {
44 namespace {
45 const std::string POWERMGR_SERVICE_NAME = "PowerMgrService";
46 const std::string TASK_RUNNINGLOCK_UNLOCK = "RunningLock_UnLock";
47 const std::string REASON_POWER_KEY = "power_key";
48 auto pms = DelayedSpSingleton<PowerMgrService>::GetInstance();
49 const bool G_REGISTER_RESULT = SystemAbility::MakeAndRegisterAbility(pms.GetRefPtr());
50 SysParam::BootCompletedCallback g_bootCompletedCallback;
51 }
52 
53 using namespace MMI;
54 
PowerMgrService()55 PowerMgrService::PowerMgrService() : SystemAbility(POWER_MANAGER_SERVICE_ID, true) {}
56 
~PowerMgrService()57 PowerMgrService::~PowerMgrService() {}
58 
OnStart()59 void PowerMgrService::OnStart()
60 {
61     POWER_HILOGD(COMP_SVC, "Power Management startup");
62     if (ready_) {
63         POWER_HILOGW(COMP_SVC, "OnStart is ready, nothing to do");
64         return;
65     }
66 
67     if (!Init()) {
68         POWER_HILOGE(COMP_SVC, "Call init fail");
69         return;
70     }
71     SystemSuspendController::GetInstance().RegisterHdiStatusListener(handler_);
72     if (!Publish(DelayedSpSingleton<PowerMgrService>::GetInstance())) {
73         POWER_HILOGE(COMP_SVC, "Register to system ability manager failed");
74         return;
75     }
76     ready_ = true;
77     POWER_HILOGI(COMP_SVC, "Add system ability success");
78 }
79 
Init()80 bool PowerMgrService::Init()
81 {
82     POWER_HILOGI(COMP_SVC, "Init start");
83 
84     if (!eventRunner_) {
85         eventRunner_ = AppExecFwk::EventRunner::Create(POWERMGR_SERVICE_NAME);
86         if (eventRunner_ == nullptr) {
87             POWER_HILOGE(COMP_SVC, "Init failed due to create EventRunner");
88             return false;
89         }
90     }
91 
92     if (!handler_) {
93         handler_ = std::make_shared<PowermsEventHandler>(eventRunner_, pms);
94         std::string handlerName("PowerMgrEventHandler");
95         HiviewDFX::Watchdog::GetInstance().AddThread(handlerName, handler_);
96     }
97 
98     if (!runningLockMgr_) {
99         runningLockMgr_ = std::make_shared<RunningLockMgr>(pms);
100     }
101     if (!runningLockMgr_->Init()) {
102         POWER_HILOGE(COMP_SVC, "Running lock init fail");
103         return false;
104     }
105     if (!PowerStateMachineInit()) {
106         POWER_HILOGE(COMP_SVC, "Power state machine init fail");
107     }
108 
109     RegisterBootCompletedCallback();
110     POWER_HILOGI(COMP_SVC, "Init success");
111     return true;
112 }
RegisterBootCompletedCallback()113 void PowerMgrService::RegisterBootCompletedCallback()
114 {
115     g_bootCompletedCallback = []() {
116         POWER_HILOGI(COMP_SVC, "BootCompletedCallback triggered");
117         auto power = DelayedSpSingleton<PowerMgrService>::GetInstance();
118         if (DelayedSpSingleton<PowerSaveMode>::GetInstance()) {
119             auto& powerModeModule = power->GetPowerModeModule();
120             powerModeModule.EnableMode(powerModeModule.GetModeItem(), true);
121         }
122         auto powerStateMachine = power->GetPowerStateMachine();
123         powerStateMachine->RegisterDisplayOffTimeObserver();
124         powerStateMachine->InitState();
125         auto powerHandler = power->GetHandler();
126         powerHandler->SendEvent(PowermsEventHandler::INIT_KEY_MONITOR_MSG, 0, INIT_KEY_MONITOR_DELAY_MS);
127     };
128     SysParam::RegisterBootCompletedCallback(g_bootCompletedCallback);
129 }
130 
PowerStateMachineInit()131 bool PowerMgrService::PowerStateMachineInit()
132 {
133     if (powerStateMachine_ == nullptr) {
134         powerStateMachine_ = std::make_shared<PowerStateMachine>(pms);
135         if (!(powerStateMachine_->Init())) {
136             POWER_HILOGE(COMP_SVC, "Power state machine start fail!");
137             return false;
138         }
139     }
140     if (powerMgrNotify_ == nullptr) {
141         powerMgrNotify_ = std::make_shared<PowerMgrNotify>();
142         powerMgrNotify_->RegisterPublishEvents();
143     }
144     return true;
145 }
146 
147 class InputCallback : public IInputEventConsumer {
148     virtual void OnInputEvent(std::shared_ptr<KeyEvent> keyEvent) const;
149     virtual void OnInputEvent(std::shared_ptr<PointerEvent> pointerEvent) const;
150     virtual void OnInputEvent(std::shared_ptr<AxisEvent> axisEvent) const;
151 };
152 
OnInputEvent(std::shared_ptr<KeyEvent> keyEvent) const153 void InputCallback::OnInputEvent(std::shared_ptr<KeyEvent> keyEvent) const
154 {
155     POWER_HILOGD(FEATURE_INPUT, "KeyEvent");
156     auto pms = DelayedSpSingleton<PowerMgrService>::GetInstance();
157     if (pms == nullptr) {
158         return;
159     }
160     pms->HandleKeyEvent(keyEvent->GetKeyCode());
161 }
162 
OnInputEvent(std::shared_ptr<PointerEvent> pointerEvent) const163 void InputCallback::OnInputEvent(std::shared_ptr<PointerEvent> pointerEvent) const
164 {
165     POWER_HILOGD(FEATURE_INPUT, "PointerEvent");
166     auto pms = DelayedSpSingleton<PowerMgrService>::GetInstance();
167     if (pms == nullptr) {
168         return;
169     }
170     int32_t type = pointerEvent->GetSourceType();
171     pms->HandlePointEvent(type);
172 }
173 
OnInputEvent(std::shared_ptr<AxisEvent> axisEvent) const174 void InputCallback::OnInputEvent(std::shared_ptr<AxisEvent> axisEvent) const
175 {
176     POWER_HILOGD(FEATURE_INPUT, "AxisEvent");
177     auto pms = DelayedSpSingleton<PowerMgrService>::GetInstance();
178     if (pms == nullptr) {
179         return;
180     }
181 }
182 
KeyMonitorInit()183 void PowerMgrService::KeyMonitorInit()
184 {
185     POWER_HILOGD(FEATURE_INPUT, "Initialize the subscription key");
186     std::shared_ptr<OHOS::MMI::KeyOption> keyOption = std::make_shared<OHOS::MMI::KeyOption>();
187     std::set<int32_t> preKeys;
188 
189     keyOption->SetPreKeys(preKeys);
190     keyOption->SetFinalKey(OHOS::MMI::KeyEvent::KEYCODE_POWER);
191     keyOption->SetFinalKeyDown(true);
192     keyOption->SetFinalKeyDownDuration(LONG_PRESS_DELAY_MS);
193     powerkeyLongPressId_ = InputManager::GetInstance()->SubscribeKeyEvent(keyOption,
194         [this](std::shared_ptr<OHOS::MMI::KeyEvent> keyEvent) {
195             POWER_HILOGI(FEATURE_INPUT, "Receive long press powerkey");
196             handler_->SendEvent(PowermsEventHandler::SHUTDOWN_REQUEST_MSG);
197     });
198     if (powerkeyLongPressId_ >= 0) {
199         keyOption.reset();
200         keyOption = std::make_shared<OHOS::MMI::KeyOption>();
201         keyOption->SetPreKeys(preKeys);
202         keyOption->SetFinalKey(OHOS::MMI::KeyEvent::KEYCODE_POWER);
203         keyOption->SetFinalKeyDown(true);
204         keyOption->SetFinalKeyDownDuration(0);
205         powerkeyShortPressId_ = InputManager::GetInstance()->SubscribeKeyEvent(keyOption,
206             [this](std::shared_ptr<OHOS::MMI::KeyEvent> keyEvent) {
207                 POWER_HILOGI(FEATURE_INPUT, "Receive short press powerkey");
208                 powerkeyPressed_ = true;
209                 if (!IsScreenOn()) {
210                     handler_->SendEvent(PowermsEventHandler::SCREEN_ON_TIMEOUT_MSG, 0, POWER_KEY_PRESS_DELAY_MS);
211                 }
212         });
213 
214         keyOption.reset();
215         keyOption = std::make_shared<OHOS::MMI::KeyOption>();
216         keyOption->SetPreKeys(preKeys);
217         keyOption->SetFinalKey(OHOS::MMI::KeyEvent::KEYCODE_POWER);
218         keyOption->SetFinalKeyDown(false);
219         keyOption->SetFinalKeyDownDuration(0);
220         powerkeyReleaseId_ = InputManager::GetInstance()->SubscribeKeyEvent(keyOption,
221             [this](std::shared_ptr<OHOS::MMI::KeyEvent> keyEvent) {
222                 powerkeyPressed_ = false;
223                 this->HandlePowerKeyUp();
224         });
225 
226         keyOption.reset();
227         keyOption = std::make_shared<OHOS::MMI::KeyOption>();
228         keyOption->SetPreKeys(preKeys);
229         keyOption->SetFinalKey(OHOS::MMI::KeyEvent::KEYCODE_F1);
230         keyOption->SetFinalKeyDown(true);
231         keyOption->SetFinalKeyDownDuration(0);
232         doubleClickId_ = InputManager::GetInstance()->SubscribeKeyEvent(keyOption,
233             [this](std::shared_ptr<OHOS::MMI::KeyEvent> keyEvent) {
234                 POWER_HILOGI(FEATURE_INPUT, "Receive double click");
235                 this->HandleKeyEvent(keyEvent->GetKeyCode());
236         });
237     } else if (powerkeyLongPressId_ != ERROR_UNSUPPORT) {
238         POWER_HILOGI(FEATURE_INPUT, "SubscribeKeyEvent failed: %{public}d", powerkeyLongPressId_);
239         handler_->SendEvent(PowermsEventHandler::INIT_KEY_MONITOR_MSG, 0, INIT_KEY_MONITOR_DELAY_MS);
240         return;
241     }
242 
243     std::shared_ptr<InputCallback> callback = std::make_shared<InputCallback>();
244     monitorId_ = InputManager::GetInstance()->AddMonitor(std::static_pointer_cast<IInputEventConsumer>(callback));
245 }
246 
KeyMonitorCancel()247 void PowerMgrService::KeyMonitorCancel()
248 {
249     POWER_HILOGI(FEATURE_INPUT, "Unsubscribe key information");
250     InputManager* inputManager = InputManager::GetInstance();
251     if (inputManager == nullptr) {
252         POWER_HILOGI(FEATURE_INPUT, "InputManager is null");
253         return;
254     }
255     if (powerkeyLongPressId_ >= 0) {
256         inputManager->UnsubscribeKeyEvent(powerkeyLongPressId_);
257     }
258     if (powerkeyShortPressId_ >= 0) {
259         inputManager->UnsubscribeKeyEvent(powerkeyShortPressId_);
260     }
261     if (powerkeyReleaseId_ >= 0) {
262         inputManager->UnsubscribeKeyEvent(powerkeyReleaseId_);
263     }
264     if (doubleClickId_ >= 0) {
265         inputManager->UnsubscribeKeyEvent(doubleClickId_);
266     }
267     if (monitorId_ >= 0) {
268         inputManager->RemoveMonitor(monitorId_);
269     }
270 }
271 
HallSensorSubscriberInit()272 void PowerMgrService::HallSensorSubscriberInit()
273 {
274     if (!IsSupportSensor(SENSOR_TYPE_ID_HALL)) {
275         POWER_HILOGW(FEATURE_INPUT, "SENSOR_TYPE_ID_HALL sensor not support");
276         return;
277     }
278     if (strcpy_s(sensorUser_.name, sizeof(sensorUser_.name), "PowerManager") != EOK) {
279         POWER_HILOGW(FEATURE_INPUT, "strcpy_s error");
280         return;
281     }
282     sensorUser_.userData = nullptr;
283     sensorUser_.callback = &HallSensorCallback;
284     SubscribeSensor(SENSOR_TYPE_ID_HALL, &sensorUser_);
285     SetBatch(SENSOR_TYPE_ID_HALL, &sensorUser_, HALL_SAMPLING_RATE, HALL_REPORT_INTERVAL);
286     ActivateSensor(SENSOR_TYPE_ID_HALL, &sensorUser_);
287 }
288 
IsSupportSensor(SensorTypeId typeId)289 bool PowerMgrService::IsSupportSensor(SensorTypeId typeId)
290 {
291     bool isSupport = false;
292     SensorInfo* sensorInfo = nullptr;
293     int32_t count;
294     int32_t ret = GetAllSensors(&sensorInfo, &count);
295     if (ret != 0 || sensorInfo == nullptr) {
296         POWER_HILOGW(FEATURE_INPUT, "Get sensors fail, ret=%{public}d", ret);
297         return isSupport;
298     }
299     for (int32_t i = 0; i < count; i++) {
300         if (sensorInfo[i].sensorTypeId == typeId) {
301             isSupport = true;
302             break;
303         }
304     }
305     return isSupport;
306 }
307 
HallSensorCallback(SensorEvent * event)308 void PowerMgrService::HallSensorCallback(SensorEvent* event)
309 {
310     if (event == nullptr || event->sensorTypeId != SENSOR_TYPE_ID_HALL || event->data == nullptr) {
311         POWER_HILOGW(FEATURE_INPUT, "Hall sensor event is invalid");
312         return;
313     }
314     const uint32_t LID_CLOSED_HALL_FLAG = 0x1;
315     auto now = static_cast<int64_t>(time(nullptr));
316     auto data = (HallData*)event->data;
317     auto status = static_cast<uint32_t>(data->status);
318     if (status & LID_CLOSED_HALL_FLAG) {
319         POWER_HILOGI(FEATURE_SUSPEND, "Lid close event received, begin to suspend");
320         pms->SuspendDevice(now, SuspendDeviceType::SUSPEND_DEVICE_REASON_LID_SWITCH, false);
321     } else {
322         POWER_HILOGI(FEATURE_WAKEUP, "Lid open event received, begin to wakeup");
323         std::string reason = "lid open";
324         pms->WakeupDevice(now, WakeupDeviceType::WAKEUP_DEVICE_LID, reason);
325     }
326 }
327 
HallSensorSubscriberCancel()328 void PowerMgrService::HallSensorSubscriberCancel()
329 {
330     if (IsSupportSensor(SENSOR_TYPE_ID_HALL)) {
331         DeactivateSensor(SENSOR_TYPE_ID_HALL, &sensorUser_);
332         UnsubscribeSensor(SENSOR_TYPE_ID_HALL, &sensorUser_);
333     }
334 }
335 
ShowPowerDialog()336 bool PowerMgrService::ShowPowerDialog()
337 {
338     POWER_HILOGD(COMP_SVC, "PowerMgrService::ShowPowerDialog start.");
339     auto client = AbilityManagerClient::GetInstance();
340     if (client == nullptr) {
341         return false;
342     }
343     AAFwk::Want want;
344     want.SetElementName("com.ohos.powerdialog", "PowerServiceExtAbility");
345     int32_t result = client->StartAbility(want);
346     if (result != 0) {
347         POWER_HILOGE(COMP_SVC, "ShowPowerDialog failed, result = %{public}d", result);
348         return false;
349     }
350     isDialogstatus_ = true;
351     POWER_HILOGD(COMP_SVC, "ShowPowerDialog success.");
352     return true;
353 }
354 
HandleShutdownRequest()355 void PowerMgrService::HandleShutdownRequest()
356 {
357     POWER_HILOGD(FEATURE_SHUTDOWN, "HandleShutdown");
358     bool showSuccess = ShowPowerDialog();
359     if (!showSuccess) {
360         return;
361     }
362     int64_t now = static_cast<int64_t>(time(0));
363     this->RefreshActivity(now, UserActivityType::USER_ACTIVITY_TYPE_ATTENTION, false);
364     if (!IsScreenOn()) {
365         POWER_HILOGI(FEATURE_SHUTDOWN, "Wakeup when display off");
366         this->WakeupDevice(now, WakeupDeviceType::WAKEUP_DEVICE_POWER_BUTTON, REASON_POWER_KEY);
367     }
368 }
369 
HandlePowerKeyUp()370 void PowerMgrService::HandlePowerKeyUp()
371 {
372     POWER_HILOGI(FEATURE_INPUT, "Receive release powerkey");
373 
374     if (isDialogstatus_ || this->shutdownService_.IsShuttingDown()) {
375         POWER_HILOGW(FEATURE_INPUT, "System is shutting down");
376         isDialogstatus_ = false;
377         return;
378     }
379     int64_t now = static_cast<int64_t>(time(0));
380     if (this->IsScreenOn()) {
381         this->SuspendDevice(now, SuspendDeviceType::SUSPEND_DEVICE_REASON_POWER_BUTTON, false);
382     } else {
383         this->WakeupDevice(now, WakeupDeviceType::WAKEUP_DEVICE_POWER_BUTTON, REASON_POWER_KEY);
384     }
385 }
386 
HandleKeyEvent(int32_t keyCode)387 void PowerMgrService::HandleKeyEvent(int32_t keyCode)
388 {
389     POWER_HILOGD(FEATURE_INPUT, "keyCode: %{public}d", keyCode);
390     int64_t now = static_cast<int64_t>(time(0));
391     if (IsScreenOn()) {
392         this->RefreshActivity(now, UserActivityType::USER_ACTIVITY_TYPE_BUTTON, false);
393     } else {
394         if (keyCode == KeyEvent::KEYCODE_F1) {
395             POWER_HILOGI(FEATURE_WAKEUP, "Wakeup by double click");
396             std::string reason = "double click";
397             reason.append(std::to_string(keyCode));
398             this->WakeupDevice(now, WakeupDeviceType::WAKEUP_DEVICE_DOUBLE_CLICK, reason);
399         } else if (keyCode >= KeyEvent::KEYCODE_0
400             && keyCode <= KeyEvent::KEYCODE_NUMPAD_RIGHT_PAREN) {
401             POWER_HILOGI(FEATURE_WAKEUP, "Wakeup by keyboard");
402             std::string reason = "keyboard:";
403             reason.append(std::to_string(keyCode));
404             this->WakeupDevice(now, WakeupDeviceType::WAKEUP_DEVICE_KEYBOARD, reason);
405         }
406     }
407 }
408 
HandlePointEvent(int32_t type)409 void PowerMgrService::HandlePointEvent(int32_t type)
410 {
411     POWER_HILOGD(FEATURE_INPUT, "type: %{public}d", type);
412     int64_t now = static_cast<int64_t>(time(0));
413     if (this->IsScreenOn()) {
414         this->RefreshActivity(now, UserActivityType::USER_ACTIVITY_TYPE_ATTENTION, false);
415     } else {
416         if (type == PointerEvent::SOURCE_TYPE_MOUSE) {
417             std::string reason = "mouse click";
418             POWER_HILOGI(FEATURE_WAKEUP, "Wakeup by mouse");
419             this->WakeupDevice(now, WakeupDeviceType::WAKEUP_DEVICE_MOUSE, reason);
420         }
421     }
422 }
423 
NotifyDisplayActionDone(uint32_t event)424 void PowerMgrService::NotifyDisplayActionDone(uint32_t event)
425 {
426     POWER_HILOGI(COMP_SVC, "NotifyDisplayActionDone: %{public}d", event);
427     handler_->RemoveEvent(PowermsEventHandler::SCREEN_ON_TIMEOUT_MSG);
428 }
429 
HandleScreenOnTimeout()430 void PowerMgrService::HandleScreenOnTimeout()
431 {
432     POWER_HILOGD(FEATURE_INPUT, "PowerKey press timeout");
433     std::string message = "POWER KEY TIMEOUT ";
434     if (powerkeyPressed_) {
435         message.append("WITHOUT KEY UP");
436     } else {
437         message.append("BUT DISPLAY NOT FINISHED");
438     }
439     HiviewDFX::HiSysEvent::Write("POWER", "SCREEN_ON_TIMEOUT",
440         HiviewDFX::HiSysEvent::EventType::FAULT,
441         "PID", IPCSkeleton::GetCallingPid(), "UID", IPCSkeleton::GetCallingUid(),
442         "PACKAGE_NAME", "", "PROCESS_NAME", "", "MSG", message.c_str());
443     POWER_HILOGD(FEATURE_INPUT, "Send HiSysEvent msg end");
444 }
445 
OnStop()446 void PowerMgrService::PowerMgrService::OnStop()
447 {
448     POWER_HILOGW(COMP_SVC, "Stop service");
449     if (!ready_) {
450         return;
451     }
452     powerStateMachine_->CancelDelayTimer(
453         PowermsEventHandler::CHECK_USER_ACTIVITY_TIMEOUT_MSG);
454     powerStateMachine_->CancelDelayTimer(
455         PowermsEventHandler::CHECK_USER_ACTIVITY_OFF_TIMEOUT_MSG);
456     powerStateMachine_->CancelDelayTimer(
457         PowermsEventHandler::CHECK_USER_ACTIVITY_SLEEP_TIMEOUT_MSG);
458     powerStateMachine_->UnregisterDisplayOffTimeObserver();
459     SystemSuspendController::GetInstance().UnRegisterPowerHdiCallback();
460     handler_->RemoveEvent(PowermsEventHandler::SCREEN_ON_TIMEOUT_MSG);
461 
462     KeyMonitorCancel();
463     HallSensorSubscriberCancel();
464     eventRunner_.reset();
465     handler_.reset();
466     ready_ = false;
467 }
468 
Dump(int32_t fd,const std::vector<std::u16string> & args)469 int32_t PowerMgrService::Dump(int32_t fd, const std::vector<std::u16string>& args)
470 {
471     POWER_HILOGI(COMP_SVC, "Dump service");
472     std::vector<std::string> argsInStr;
473     std::transform(args.begin(), args.end(), std::back_inserter(argsInStr),
474         [](const std::u16string &arg) {
475         std::string ret = Str16ToStr8(arg);
476         POWER_HILOGI(COMP_SVC, "arg: %{public}s", ret.c_str());
477         return ret;
478     });
479     std::string result;
480     PowerMgrDumper::Dump(argsInStr, result);
481     if (!SaveStringToFd(fd, result)) {
482         POWER_HILOGE(COMP_SVC, "Dump failed, save to fd failed.");
483         POWER_HILOGE(COMP_SVC, "Dump Info:\n");
484         POWER_HILOGE(COMP_SVC, "%{public}s", result.c_str());
485         return ERR_OK;
486     }
487     return ERR_OK;
488 }
489 
RebootDevice(const std::string & reason)490 PowerErrors PowerMgrService::RebootDevice(const std::string& reason)
491 {
492     if (!Permission::IsSystem()) {
493         return PowerErrors::ERR_PERMISSION_DENIED;
494     }
495     return RebootDeviceForDeprecated(reason);
496 }
497 
RebootDeviceForDeprecated(const std::string & reason)498 PowerErrors PowerMgrService::RebootDeviceForDeprecated(const std::string& reason)
499 {
500     std::lock_guard lock(mutex_);
501     pid_t pid = IPCSkeleton::GetCallingPid();
502     auto uid = IPCSkeleton::GetCallingUid();
503     if (!Permission::IsPermissionGranted("ohos.permission.REBOOT")) {
504         return PowerErrors::ERR_PERMISSION_DENIED;
505     }
506     POWER_HILOGI(FEATURE_SHUTDOWN, "Cancel auto sleep timer");
507     powerStateMachine_->CancelDelayTimer(
508         PowermsEventHandler::CHECK_USER_ACTIVITY_TIMEOUT_MSG);
509     powerStateMachine_->CancelDelayTimer(
510         PowermsEventHandler::CHECK_USER_ACTIVITY_OFF_TIMEOUT_MSG);
511     powerStateMachine_->CancelDelayTimer(
512         PowermsEventHandler::CHECK_USER_ACTIVITY_SLEEP_TIMEOUT_MSG);
513 
514     POWER_HILOGI(FEATURE_SHUTDOWN, "Do reboot, called pid: %{public}d, uid: %{public}d", pid, uid);
515     shutdownService_.Reboot(reason);
516     return PowerErrors::ERR_OK;
517 }
518 
ShutDownDevice(const std::string & reason)519 PowerErrors PowerMgrService::ShutDownDevice(const std::string& reason)
520 {
521     std::lock_guard lock(mutex_);
522     pid_t pid  = IPCSkeleton::GetCallingPid();
523     auto uid = IPCSkeleton::GetCallingUid();
524     if (!Permission::IsSystemApl() && !Permission::IsSystemHapPermGranted("ohos.permission.REBOOT")) {
525         return PowerErrors::ERR_PERMISSION_DENIED;
526     }
527     POWER_HILOGI(FEATURE_SHUTDOWN, "Cancel auto sleep timer");
528     powerStateMachine_->CancelDelayTimer(
529         PowermsEventHandler::CHECK_USER_ACTIVITY_TIMEOUT_MSG);
530     powerStateMachine_->CancelDelayTimer(
531         PowermsEventHandler::CHECK_USER_ACTIVITY_OFF_TIMEOUT_MSG);
532     powerStateMachine_->CancelDelayTimer(
533         PowermsEventHandler::CHECK_USER_ACTIVITY_SLEEP_TIMEOUT_MSG);
534 
535     POWER_HILOGI(FEATURE_SHUTDOWN, "Do shutdown, called pid: %{public}d, uid: %{public}d", pid, uid);
536     shutdownService_.Shutdown(reason);
537     return PowerErrors::ERR_OK;
538 }
539 
SuspendDevice(int64_t callTimeMs,SuspendDeviceType reason,bool suspendImmed)540 PowerErrors PowerMgrService::SuspendDevice(int64_t callTimeMs,
541     SuspendDeviceType reason,
542     bool suspendImmed)
543 {
544     std::lock_guard lock(mutex_);
545     pid_t pid  = IPCSkeleton::GetCallingPid();
546     auto uid = IPCSkeleton::GetCallingUid();
547     if (!Permission::IsSystem()) {
548         return PowerErrors::ERR_PERMISSION_DENIED;
549     }
550     if (shutdownService_.IsShuttingDown()) {
551         POWER_HILOGW(FEATURE_SUSPEND, "System is shutting down, can't suspend");
552         return PowerErrors::ERR_OK;
553     }
554     POWER_HILOGI(FEATURE_SUSPEND, "Try to suspend device, pid: %{public}d, uid: %{public}d", pid, uid);
555     powerStateMachine_->SuspendDeviceInner(pid, callTimeMs, reason, suspendImmed);
556     return PowerErrors::ERR_OK;
557 }
558 
WakeupDevice(int64_t callTimeMs,WakeupDeviceType reason,const std::string & details)559 PowerErrors PowerMgrService::WakeupDevice(int64_t callTimeMs,
560     WakeupDeviceType reason,
561     const std::string& details)
562 {
563     std::lock_guard lock(mutex_);
564     pid_t pid  = IPCSkeleton::GetCallingPid();
565     auto uid = IPCSkeleton::GetCallingUid();
566     if (!Permission::IsSystem()) {
567         return PowerErrors::ERR_PERMISSION_DENIED;
568     }
569     POWER_HILOGI(FEATURE_WAKEUP, "Try to wakeup device, pid: %{public}d, uid: %{public}d", pid, uid);
570     powerStateMachine_->WakeupDeviceInner(pid, callTimeMs, reason, details, "OHOS");
571     return PowerErrors::ERR_OK;
572 }
573 
RefreshActivity(int64_t callTimeMs,UserActivityType type,bool needChangeBacklight)574 bool PowerMgrService::RefreshActivity(int64_t callTimeMs,
575     UserActivityType type,
576     bool needChangeBacklight)
577 {
578     std::lock_guard lock(mutex_);
579     if (powerStateMachine_->CheckRefreshTime()) {
580         return false;
581     }
582     pid_t pid  = IPCSkeleton::GetCallingPid();
583     auto uid = IPCSkeleton::GetCallingUid();
584     if (!Permission::IsSystem() && !Permission::IsPermissionGranted("ohos.permission.REFRESH_USER_ACTION")) {
585         return false;
586     }
587     POWER_HILOGD(FEATURE_ACTIVITY, "Try to refresh activity, pid: %{public}d, uid: %{public}d", pid, uid);
588     powerStateMachine_->RefreshActivityInner(pid, callTimeMs, type, needChangeBacklight);
589     return true;
590 }
591 
OverrideScreenOffTime(int64_t timeout)592 bool PowerMgrService::OverrideScreenOffTime(int64_t timeout)
593 {
594     std::lock_guard lock(mutex_);
595     if (!Permission::IsSystem()) {
596         return false;
597     }
598     POWER_HILOGD(COMP_SVC, "Try to override screen off time");
599     return powerStateMachine_->OverrideScreenOffTimeInner(timeout);
600 }
601 
RestoreScreenOffTime()602 bool PowerMgrService::RestoreScreenOffTime()
603 {
604     std::lock_guard lock(mutex_);
605     if (!Permission::IsSystem()) {
606         return false;
607     }
608     POWER_HILOGD(COMP_SVC, "Try to restore screen off time");
609     return powerStateMachine_->RestoreScreenOffTimeInner();
610 }
611 
612 
GetState()613 PowerState PowerMgrService::GetState()
614 {
615     std::lock_guard lock(mutex_);
616     auto state = powerStateMachine_->GetState();
617     POWER_HILOGD(FEATURE_POWER_STATE, "state: %{public}d", state);
618     return state;
619 }
620 
IsScreenOn()621 bool PowerMgrService::IsScreenOn()
622 {
623     std::lock_guard lock(mutex_);
624     auto isScreenOn = powerStateMachine_->IsScreenOn();
625     POWER_HILOGI(COMP_SVC, "isScreenOn: %{public}d", isScreenOn);
626     return isScreenOn;
627 }
628 
ForceSuspendDevice(int64_t callTimeMs)629 bool PowerMgrService::ForceSuspendDevice(int64_t callTimeMs)
630 {
631     std::lock_guard lock(mutex_);
632     pid_t pid  = IPCSkeleton::GetCallingPid();
633     auto uid = IPCSkeleton::GetCallingUid();
634     if (!Permission::IsSystem()) {
635         return false;
636     }
637     if (shutdownService_.IsShuttingDown()) {
638         POWER_HILOGI(FEATURE_SUSPEND, "System is shutting down, can't force suspend");
639         return false;
640     }
641     POWER_HILOGI(FEATURE_SUSPEND, "Try to force suspend device, pid: %{public}d, uid: %{public}d", pid, uid);
642     return powerStateMachine_->ForceSuspendDeviceInner(pid, callTimeMs);
643 }
644 
FillUserIPCInfo(UserIPCInfo & userIPCinfo)645 inline void PowerMgrService::FillUserIPCInfo(UserIPCInfo &userIPCinfo)
646 {
647     userIPCinfo.pid = IPCSkeleton::GetCallingPid();
648     userIPCinfo.uid = IPCSkeleton::GetCallingUid();
649 }
650 
CreateRunningLock(const sptr<IRemoteObject> & remoteObj,const RunningLockInfo & runningLockInfo)651 PowerErrors PowerMgrService::CreateRunningLock(const sptr<IRemoteObject>& remoteObj,
652     const RunningLockInfo& runningLockInfo)
653 {
654     std::lock_guard lock(lockMutex_);
655     if (!Permission::IsSystem() && !Permission::IsPermissionGranted("ohos.permission.RUNNING_LOCK")) {
656         return PowerErrors::ERR_PERMISSION_DENIED;
657     }
658 
659     POWER_HILOGI(FEATURE_RUNNING_LOCK, "name: %{public}s, type: %{public}d",
660         runningLockInfo.name.c_str(), runningLockInfo.type);
661 
662     UserIPCInfo userIPCInfo;
663     FillUserIPCInfo(userIPCInfo);
664     runningLockMgr_->CreateRunningLock(remoteObj, runningLockInfo, userIPCInfo);
665     return PowerErrors::ERR_OK;
666 }
667 
ReleaseRunningLock(const sptr<IRemoteObject> & remoteObj)668 bool PowerMgrService::ReleaseRunningLock(const sptr<IRemoteObject>& remoteObj)
669 {
670     std::lock_guard lock(lockMutex_);
671     bool result = false;
672     if (!Permission::IsSystem() && !Permission::IsPermissionGranted("ohos.permission.RUNNING_LOCK")) {
673         return result;
674     }
675 
676     result = runningLockMgr_->ReleaseLock(remoteObj);
677     return result;
678 }
679 
IsRunningLockTypeSupported(uint32_t type)680 bool PowerMgrService::IsRunningLockTypeSupported(uint32_t type)
681 {
682     std::lock_guard lock(lockMutex_);
683     if (type >= static_cast<uint32_t>(RunningLockType::RUNNINGLOCK_BUTT)) {
684         return false;
685     }
686     return true;
687 }
688 
Lock(const sptr<IRemoteObject> & remoteObj,const RunningLockInfo & runningLockInfo,uint32_t timeOutMS)689 bool PowerMgrService::Lock(const sptr<IRemoteObject>& remoteObj,
690     const RunningLockInfo& runningLockInfo,
691     uint32_t timeOutMS)
692 {
693     std::lock_guard lock(lockMutex_);
694     if (!Permission::IsSystem() && !Permission::IsPermissionGranted("ohos.permission.RUNNING_LOCK")) {
695         return false;
696     }
697 
698     POWER_HILOGI(FEATURE_RUNNING_LOCK,
699         "timeOutMS: %{public}d, name: %{public}s, type: %{public}d",
700         timeOutMS,
701         runningLockInfo.name.c_str(),
702         runningLockInfo.type);
703 
704     UserIPCInfo userIPCInfo;
705     FillUserIPCInfo(userIPCInfo);
706     runningLockMgr_->Lock(remoteObj, runningLockInfo, userIPCInfo, timeOutMS);
707     return true;
708 }
709 
UnLock(const sptr<IRemoteObject> & remoteObj)710 bool PowerMgrService::UnLock(const sptr<IRemoteObject>& remoteObj)
711 {
712     std::lock_guard lock(lockMutex_);
713     if (!Permission::IsSystem() && !Permission::IsPermissionGranted("ohos.permission.RUNNING_LOCK")) {
714         return false;
715     }
716     runningLockMgr_->UnLock(remoteObj);
717     return true;
718 }
719 
ForceUnLock(const sptr<IRemoteObject> & remoteObj)720 void PowerMgrService::ForceUnLock(const sptr<IRemoteObject>& remoteObj)
721 {
722     std::lock_guard lock(lockMutex_);
723     runningLockMgr_->UnLock(remoteObj);
724     runningLockMgr_->ReleaseLock(remoteObj);
725 }
726 
IsUsed(const sptr<IRemoteObject> & remoteObj)727 bool PowerMgrService::IsUsed(const sptr<IRemoteObject>& remoteObj)
728 {
729     std::lock_guard lock(lockMutex_);
730     auto isUsed = runningLockMgr_->IsUsed(remoteObj);
731     POWER_HILOGD(FEATURE_RUNNING_LOCK, "RunningLock is Used: %{public}d", isUsed);
732     return isUsed;
733 }
734 
NotifyRunningLockChanged(bool isUnLock)735 void PowerMgrService::NotifyRunningLockChanged(bool isUnLock)
736 {
737     if (isUnLock) {
738         // When unlock we try to suspend
739         if (!runningLockMgr_->ExistValidRunningLock()
740             && !powerStateMachine_->IsScreenOn()) {
741             // runninglock is empty and Screen is off,
742             // so we try to suspend device from Z side.
743             POWER_HILOGI(FEATURE_RUNNING_LOCK, "RunningLock is empty, try to suspend");
744             powerStateMachine_->SuspendDeviceInner(getpid(), GetTickCount(),
745                 SuspendDeviceType::SUSPEND_DEVICE_REASON_MIN, true, true);
746         }
747     }
748 }
749 
SetWorkTriggerList(const sptr<IRemoteObject> & remoteObj,const WorkTriggerList & workTriggerList)750 bool PowerMgrService::SetWorkTriggerList(const sptr<IRemoteObject>& remoteObj,
751     const WorkTriggerList& workTriggerList)
752 {
753     std::lock_guard lock(lockMutex_);
754     if (!Permission::IsSystem() && !Permission::IsPermissionGranted("ohos.permission.RUNNING_LOCK")) {
755         return false;
756     }
757 
758     runningLockMgr_->SetWorkTriggerList(remoteObj, workTriggerList);
759     return true;
760 }
761 
ProxyRunningLock(bool proxyLock,pid_t uid,pid_t pid)762 bool PowerMgrService::ProxyRunningLock(bool proxyLock, pid_t uid, pid_t pid)
763 {
764     std::lock_guard lock(lockMutex_);
765     if (!Permission::IsSystem()) {
766         return false;
767     }
768     runningLockMgr_->ProxyRunningLock(proxyLock, uid, pid);
769     return true;
770 }
771 
RegisterPowerStateCallback(const sptr<IPowerStateCallback> & callback)772 bool PowerMgrService::RegisterPowerStateCallback(const sptr<IPowerStateCallback>& callback)
773 {
774     std::lock_guard lock(mutex_);
775     pid_t pid  = IPCSkeleton::GetCallingPid();
776     auto uid = IPCSkeleton::GetCallingUid();
777     if (!Permission::IsSystem() && !Permission::IsPermissionGranted("ohos.permission.POWER_MANAGER")) {
778         return false;
779     }
780     POWER_HILOGI(FEATURE_POWER_STATE, "pid: %{public}d, uid: %{public}d", pid, uid);
781     powerStateMachine_->RegisterPowerStateCallback(callback);
782     return true;
783 }
784 
UnRegisterPowerStateCallback(const sptr<IPowerStateCallback> & callback)785 bool PowerMgrService::UnRegisterPowerStateCallback(const sptr<IPowerStateCallback>& callback)
786 {
787     std::lock_guard lock(mutex_);
788     pid_t pid  = IPCSkeleton::GetCallingPid();
789     auto uid = IPCSkeleton::GetCallingUid();
790     if (!Permission::IsSystem() && !Permission::IsPermissionGranted("ohos.permission.POWER_MANAGER")) {
791         return false;
792     }
793     POWER_HILOGI(FEATURE_POWER_STATE, "pid: %{public}d, uid: %{public}d", pid, uid);
794     powerStateMachine_->UnRegisterPowerStateCallback(callback);
795     return true;
796 }
797 
RegisterShutdownCallback(IShutdownCallback::ShutdownPriority priority,const sptr<IShutdownCallback> & callback)798 bool PowerMgrService::RegisterShutdownCallback(IShutdownCallback::ShutdownPriority priority,
799     const sptr<IShutdownCallback>& callback)
800 {
801     std::lock_guard lock(mutex_);
802     pid_t pid  = IPCSkeleton::GetCallingPid();
803     auto uid = IPCSkeleton::GetCallingUid();
804     if (!Permission::IsSystem()) {
805         return false;
806     }
807     POWER_HILOGI(FEATURE_SHUTDOWN, "pid: %{public}d, uid: %{public}d, priority: %{public}d",
808         pid, uid, priority);
809     shutdownService_.AddShutdownCallback(priority, callback);
810     return true;
811 }
812 
UnRegisterShutdownCallback(const sptr<IShutdownCallback> & callback)813 bool PowerMgrService::UnRegisterShutdownCallback(const sptr<IShutdownCallback>& callback)
814 {
815     std::lock_guard lock(mutex_);
816     pid_t pid  = IPCSkeleton::GetCallingPid();
817     auto uid = IPCSkeleton::GetCallingUid();
818     if (!Permission::IsSystem()) {
819         return false;
820     }
821     POWER_HILOGI(FEATURE_SHUTDOWN, "pid: %{public}d, uid: %{public}d", pid, uid);
822     shutdownService_.DelShutdownCallback(callback);
823     return true;
824 }
825 
RegisterPowerModeCallback(const sptr<IPowerModeCallback> & callback)826 bool PowerMgrService::RegisterPowerModeCallback(const sptr<IPowerModeCallback>& callback)
827 {
828     std::lock_guard lock(mutex_);
829     pid_t pid  = IPCSkeleton::GetCallingPid();
830     auto uid = IPCSkeleton::GetCallingUid();
831     if (!Permission::IsSystem()) {
832         return false;
833     }
834     POWER_HILOGI(FEATURE_POWER_MODE, "pid: %{public}d, uid: %{public}d", pid, uid);
835     powerModeModule_.AddPowerModeCallback(callback);
836     return true;
837 }
838 
UnRegisterPowerModeCallback(const sptr<IPowerModeCallback> & callback)839 bool PowerMgrService::UnRegisterPowerModeCallback(const sptr<IPowerModeCallback>& callback)
840 {
841     std::lock_guard lock(mutex_);
842     pid_t pid  = IPCSkeleton::GetCallingPid();
843     auto uid = IPCSkeleton::GetCallingUid();
844     if (!Permission::IsSystem()) {
845         return false;
846     }
847     POWER_HILOGI(FEATURE_POWER_MODE, "pid: %{public}d, uid: %{public}d", pid, uid);
848     powerModeModule_.DelPowerModeCallback(callback);
849     return true;
850 }
851 
SetDisplaySuspend(bool enable)852 bool PowerMgrService::SetDisplaySuspend(bool enable)
853 {
854     std::lock_guard lock(mutex_);
855     pid_t pid  = IPCSkeleton::GetCallingPid();
856     auto uid = IPCSkeleton::GetCallingUid();
857     if (!Permission::IsSystem()) {
858         return false;
859     }
860     POWER_HILOGI(FEATURE_SUSPEND, "pid: %{public}d, uid: %{public}d, enable: %{public}d", pid, uid, enable);
861     powerStateMachine_->SetDisplaySuspend(enable);
862     return true;
863 }
864 
SetDeviceMode(const PowerMode & mode)865 PowerErrors PowerMgrService::SetDeviceMode(const PowerMode& mode)
866 {
867     std::lock_guard lock(mutex_);
868     pid_t pid = IPCSkeleton::GetCallingPid();
869     auto uid = IPCSkeleton::GetCallingUid();
870     POWER_HILOGI(FEATURE_POWER_MODE, "pid: %{public}d, uid: %{public}d, mode: %{public}u", pid, uid, mode);
871     if (!Permission::IsSystemApl() && !Permission::IsSystemHapPermGranted("ohos.permission.POWER_OPTIMIZATION")) {
872         return PowerErrors::ERR_PERMISSION_DENIED;
873     }
874     powerModeModule_.SetModeItem(mode);
875     return PowerErrors::ERR_OK;
876 }
877 
GetDeviceMode()878 PowerMode PowerMgrService::GetDeviceMode()
879 {
880     std::lock_guard lock(mutex_);
881     pid_t pid = IPCSkeleton::GetCallingPid();
882     auto uid = IPCSkeleton::GetCallingUid();
883     auto mode = powerModeModule_.GetModeItem();
884     POWER_HILOGI(FEATURE_POWER_MODE, "pid: %{public}d, uid: %{public}d, mode: %{public}u", pid, uid, mode);
885     return mode;
886 }
887 
ShellDump(const std::vector<std::string> & args,uint32_t argc)888 std::string PowerMgrService::ShellDump(const std::vector<std::string>& args, uint32_t argc)
889 {
890     if (!Permission::IsSystem()) {
891         return "";
892     }
893     std::lock_guard lock(mutex_);
894     pid_t pid = IPCSkeleton::GetCallingPid();
895     auto uid = IPCSkeleton::GetCallingUid();
896     POWER_HILOGI(COMP_SVC, "pid: %{public}d, uid: %{public}d", pid, uid);
897 
898     std::string result;
899     bool ret = PowerMgrDumper::Dump(args, result);
900     POWER_HILOGI(COMP_SVC, "ret :%{public}d", ret);
901     return result;
902 }
903 } // namespace PowerMgr
904 } // namespace OHOS
905