• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (c) 2021-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 "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 #ifdef HAS_MULTIMODALINPUT_INPUT_PART
23 #include <input_manager.h>
24 #endif
25 #include <ipc_skeleton.h>
26 #include <iservice_registry.h>
27 #include <securec.h>
28 #include <string_ex.h>
29 #include <system_ability_definition.h>
30 #include <sys_mgr_client.h>
31 #include <bundle_mgr_client.h>
32 #include <unistd.h>
33 #include "ability_connect_callback_stub.h"
34 #include "ability_manager_client.h"
35 #include "ffrt_utils.h"
36 #include "permission.h"
37 #include "power_ext_intf_wrapper.h"
38 #include "power_common.h"
39 #include "power_mgr_dumper.h"
40 #include "power_vibrator.h"
41 #include "power_xcollie.h"
42 #include "setting_helper.h"
43 #include "running_lock_timer_handler.h"
44 #include "sysparam.h"
45 #include "system_suspend_controller.h"
46 #include "xcollie/watchdog.h"
47 #include "errors.h"
48 #include "parameters.h"
49 #ifdef HAS_DEVICE_STANDBY_PART
50 #include "standby_service_client.h"
51 #endif
52 #ifdef MSDP_MOVEMENT_ENABLE
53 #include <dlfcn.h>
54 #endif
55 #ifdef POWER_MANAGER_ENABLE_CHARGING_TYPE_SETTING
56 #include "battery_srv_client.h"
57 #endif
58 
59 using namespace OHOS::AppExecFwk;
60 using namespace OHOS::AAFwk;
61 namespace OHOS {
62 namespace PowerMgr {
63 namespace {
64 const std::string POWERMGR_SERVICE_NAME = "PowerMgrService";
65 const std::string REASON_POWER_KEY = "power_key";
66 static std::string g_wakeupReason = "";
67 const std::string POWER_VIBRATOR_CONFIG_FILE = "etc/power_config/power_vibrator.json";
68 const std::string VENDOR_POWER_VIBRATOR_CONFIG_FILE = "/vendor/etc/power_config/power_vibrator.json";
69 const std::string SYSTEM_POWER_VIBRATOR_CONFIG_FILE = "/system/etc/power_config/power_vibrator.json";
70 constexpr int32_t WAKEUP_LOCK_TIMEOUT_MS = 5000;
71 constexpr int32_t COLLABORATION_REMOTE_DEVICE_ID = 0xAAAAAAFF;
72 auto pms = DelayedSpSingleton<PowerMgrService>::GetInstance();
73 const bool G_REGISTER_RESULT = SystemAbility::MakeAndRegisterAbility(pms.GetRefPtr());
74 SysParam::BootCompletedCallback g_bootCompletedCallback;
75 #ifdef POWER_WAKEUPDOUBLE_OR_PICKUP_ENABLE
76 bool g_isPickUpOpen = false;
77 #endif
78 } // namespace
79 
80 std::atomic_bool PowerMgrService::isBootCompleted_ = false;
81 #ifdef HAS_SENSORS_SENSOR_PART
82     bool PowerMgrService::isInLidMode_ = false;
83 #endif
84 using namespace MMI;
85 
PowerMgrService()86 PowerMgrService::PowerMgrService() : SystemAbility(POWER_MANAGER_SERVICE_ID, true) {}
87 
~PowerMgrService()88 PowerMgrService::~PowerMgrService() {}
89 
OnStart()90 void PowerMgrService::OnStart()
91 {
92     POWER_HILOGD(COMP_SVC, "Power Management startup");
93     if (ready_) {
94         POWER_HILOGW(COMP_SVC, "OnStart is ready, nothing to do");
95         return;
96     }
97     if (!Init()) {
98         POWER_HILOGE(COMP_SVC, "Call init fail");
99         return;
100     }
101     AddSystemAbilityListener(SUSPEND_MANAGER_SYSTEM_ABILITY_ID);
102     AddSystemAbilityListener(DEVICE_STANDBY_SERVICE_SYSTEM_ABILITY_ID);
103     AddSystemAbilityListener(DISPLAY_MANAGER_SERVICE_ID);
104     AddSystemAbilityListener(DISTRIBUTED_KV_DATA_SERVICE_ABILITY_ID);
105 #ifdef MSDP_MOVEMENT_ENABLE
106     AddSystemAbilityListener(MSDP_MOVEMENT_SERVICE_ID);
107 #endif
108 #ifdef POWER_WAKEUPDOUBLE_OR_PICKUP_ENABLE
109     AddSystemAbilityListener(MSDP_MOTION_SERVICE_ID);
110 #endif
111     SystemSuspendController::GetInstance().RegisterHdiStatusListener();
112     if (!Publish(DelayedSpSingleton<PowerMgrService>::GetInstance())) {
113         POWER_HILOGE(COMP_SVC, "Register to system ability manager failed");
114         return;
115     }
116     ready_ = true;
117     system::SetParameter("bootevent.powermgr.ready", "true");
118     POWER_HILOGI(COMP_SVC, "Add system ability success");
119 }
120 
Init()121 bool PowerMgrService::Init()
122 {
123     POWER_HILOGI(COMP_SVC, "Init start");
124     if (!runningLockMgr_) {
125         runningLockMgr_ = std::make_shared<RunningLockMgr>(pms);
126     }
127     if (!runningLockMgr_->Init()) {
128         POWER_HILOGE(COMP_SVC, "Running lock init fail");
129         return false;
130     }
131     if (!shutdownController_) {
132         shutdownController_ = std::make_shared<ShutdownController>();
133     }
134     if (!PowerStateMachineInit()) {
135         POWER_HILOGE(COMP_SVC, "Power state machine init fail");
136     }
137     if (!screenOffPreController_) {
138         screenOffPreController_ = std::make_shared<ScreenOffPreController>(powerStateMachine_);
139         screenOffPreController_->Init();
140     }
141     POWER_HILOGI(COMP_SVC, "Init success");
142     return true;
143 }
144 
RegisterBootCompletedCallback()145 void PowerMgrService::RegisterBootCompletedCallback()
146 {
147     g_bootCompletedCallback = []() {
148         POWER_HILOGI(COMP_SVC, "BootCompletedCallback triggered");
149         auto power = DelayedSpSingleton<PowerMgrService>::GetInstance();
150         if (power == nullptr) {
151             POWER_HILOGI(COMP_SVC, "get PowerMgrService fail");
152             return;
153         }
154         PowerExtIntfWrapper::Instance().Init();
155         auto powerStateMachine = power->GetPowerStateMachine();
156         SettingHelper::UpdateCurrentUserId(); // update setting user id before get setting values
157 #ifdef POWER_MANAGER_ENABLE_CHARGING_TYPE_SETTING
158         power->PowerConnectStatusInit();
159 #endif
160         powerStateMachine->RegisterDisplayOffTimeObserver();
161         powerStateMachine->InitState();
162 #ifdef POWER_MANAGER_POWER_DIALOG
163         power->GetShutdownDialog().LoadDialogConfig();
164         power->GetShutdownDialog().KeyMonitorInit();
165 #endif
166 #ifndef CONFIG_FACTORY_MODE
167         power->RegisterSettingWakeUpLidObserver();
168         POWER_HILOGI(COMP_SVC, "Allow subscribe Hall sensor");
169 #else
170         POWER_HILOGI(COMP_SVC, "Not allow subscribe Hall sensor");
171 #endif
172         power->SwitchSubscriberInit();
173         power->InputMonitorInit();
174 #ifdef POWER_WAKEUPDOUBLE_OR_PICKUP_ENABLE
175         SettingHelper::CopyDataForUpdateScene();
176 #endif
177         SettingHelper::UpdateCurrentUserId();
178         power->SuspendControllerInit();
179         power->WakeupControllerInit();
180         power->SubscribeCommonEvent();
181 #ifdef POWER_MANAGER_WAKEUP_ACTION
182         power->WakeupActionControllerInit();
183 #endif
184         power->VibratorInit();
185 #ifdef POWER_WAKEUPDOUBLE_OR_PICKUP_ENABLE
186         power->RegisterSettingWakeupDoubleClickObservers();
187         power->RegisterSettingWakeupPickupGestureObserver();
188 #endif
189         power->RegisterSettingPowerModeObservers();
190         power->KeepScreenOnInit();
191         isBootCompleted_ = true;
192     };
193     SysParam::RegisterBootCompletedCallback(g_bootCompletedCallback);
194 }
195 
RegisterSettingPowerModeObservers()196 void PowerMgrService::RegisterSettingPowerModeObservers()
197 {
198     SettingObserver::UpdateFunc updateFunc = [&](const std::string &key) { PowerModeSettingUpdateFunc(key); };
199     SettingHelper::RegisterSettingPowerModeObserver(updateFunc);
200 }
201 
PowerModeSettingUpdateFunc(const std::string & key)202 void PowerMgrService::PowerModeSettingUpdateFunc(const std::string &key)
203 {
204     auto power = DelayedSpSingleton<PowerMgrService>::GetInstance();
205     int32_t currMode = static_cast<int32_t>(power->GetDeviceMode());
206     int32_t saveMode = SettingHelper::ReadCurrentMode(currMode);
207     if (currMode == saveMode) {
208         return;
209     }
210     POWER_HILOGI(COMP_SVC, "PowerModeSettingUpdateFunc curr:%{public}d, saveMode:%{public}d", currMode, saveMode);
211     power->SetDeviceMode(static_cast<PowerMode>(saveMode));
212 }
213 
IsDeveloperMode()214 bool PowerMgrService::IsDeveloperMode()
215 {
216     return OHOS::system::GetBoolParameter("const.security.developermode.state", true);
217 }
218 
KeepScreenOnInit()219 void PowerMgrService::KeepScreenOnInit()
220 {
221     if (ptoken_ != nullptr) {
222         POWER_HILOGI(COMP_SVC, "runninglock token is not null");
223         return;
224     }
225     ptoken_ = new (std::nothrow) RunningLockTokenStub();
226     if (ptoken_ == nullptr) {
227         POWER_HILOGI(COMP_SVC, "create runninglock token failed");
228         return;
229     }
230     RunningLockInfo info = {"PowerMgrKeepOnLock", OHOS::PowerMgr::RunningLockType::RUNNINGLOCK_SCREEN};
231     PowerErrors ret = pms->CreateRunningLock(ptoken_, info);
232     if (ret != PowerErrors::ERR_OK) {
233         POWER_HILOGI(COMP_SVC, "create runninglock failed");
234     }
235     return;
236 }
237 
KeepScreenOn(bool isOpenOn)238 void PowerMgrService::KeepScreenOn(bool isOpenOn)
239 {
240     if (!IsDeveloperMode()) {
241         POWER_HILOGI(COMP_SVC, "not developer mode");
242         return;
243     }
244     if (ptoken_ == nullptr) {
245         POWER_HILOGI(COMP_SVC, "runninglock token is null");
246         return;
247     }
248     if (isOpenOn) {
249         POWER_HILOGI(COMP_SVC, "try lock RUNNINGLOCK_SCREEN");
250         pms->Lock(ptoken_);
251     } else {
252         POWER_HILOGI(COMP_SVC, "try unlock RUNNINGLOCK_SCREEN");
253         pms->UnLock(ptoken_);
254     }
255     return;
256 }
257 
258 #ifdef POWER_WAKEUPDOUBLE_OR_PICKUP_ENABLE
RegisterSettingWakeupDoubleClickObservers()259 void PowerMgrService::RegisterSettingWakeupDoubleClickObservers()
260 {
261     SettingObserver::UpdateFunc updateFunc = [&](const std::string& key) {WakeupDoubleClickSettingUpdateFunc(key); };
262     SettingHelper::RegisterSettingWakeupDoubleObserver(updateFunc);
263 }
264 
WakeupDoubleClickSettingUpdateFunc(const std::string & key)265 void PowerMgrService::WakeupDoubleClickSettingUpdateFunc(const std::string& key)
266 {
267     bool isSettingEnable = GetSettingWakeupDoubleClick(key);
268     WakeupController::ChangeWakeupSourceConfig(isSettingEnable);
269     WakeupController::SetWakeupDoubleClickSensor(isSettingEnable);
270     POWER_HILOGI(COMP_SVC, "WakeupDoubleClickSettingUpdateFunc isSettingEnable=%{public}d", isSettingEnable);
271 }
272 
GetSettingWakeupDoubleClick(const std::string & key)273 bool PowerMgrService::GetSettingWakeupDoubleClick(const std::string& key)
274 {
275     return SettingHelper::GetSettingWakeupDouble(key);
276 }
277 
RegisterSettingWakeupPickupGestureObserver()278 void PowerMgrService::RegisterSettingWakeupPickupGestureObserver()
279 {
280     SettingObserver::UpdateFunc updateFunc = [&](const std::string& key) {WakeupPickupGestureSettingUpdateFunc(key);};
281     SettingHelper::RegisterSettingWakeupPickupObserver(updateFunc);
282 }
283 
WakeupPickupGestureSettingUpdateFunc(const std::string & key)284 void PowerMgrService::WakeupPickupGestureSettingUpdateFunc(const std::string& key)
285 {
286     bool isSettingEnable = SettingHelper::GetSettingWakeupPickup(key);
287     g_isPickUpOpen = isSettingEnable;
288     WakeupController::PickupConnectMotionConfig(isSettingEnable);
289     POWER_HILOGI(COMP_SVC, "PickupConnectMotionConfig done, isSettingEnable=%{public}d", isSettingEnable);
290     WakeupController::ChangePickupWakeupSourceConfig(isSettingEnable);
291     POWER_HILOGI(COMP_SVC, "ChangePickupWakeupSourceConfig done");
292 }
293 #endif
294 
PowerStateMachineInit()295 bool PowerMgrService::PowerStateMachineInit()
296 {
297     if (powerStateMachine_ == nullptr) {
298         powerStateMachine_ = std::make_shared<PowerStateMachine>(pms);
299         if (!(powerStateMachine_->Init())) {
300             POWER_HILOGE(COMP_SVC, "Power state machine start fail!");
301             return false;
302         }
303     }
304     if (powerMgrNotify_ == nullptr) {
305         powerMgrNotify_ = std::make_shared<PowerMgrNotify>();
306         powerMgrNotify_->RegisterPublishEvents();
307     }
308     return true;
309 }
310 
KeyMonitorCancel()311 void PowerMgrService::KeyMonitorCancel()
312 {
313 #ifdef HAS_MULTIMODALINPUT_INPUT_PART
314     POWER_HILOGI(FEATURE_INPUT, "Unsubscribe key information");
315     InputManager* inputManager = InputManager::GetInstance();
316     if (inputManager == nullptr) {
317         POWER_HILOGI(FEATURE_INPUT, "InputManager is null");
318         return;
319     }
320     shutdownDialog_.KeyMonitorCancel();
321     if (doubleClickId_ >= 0) {
322         inputManager->UnsubscribeKeyEvent(doubleClickId_);
323     }
324     if (monitorId_ >= 0) {
325         inputManager->RemoveMonitor(monitorId_);
326     }
327 #endif
328 }
329 
WakeupLidSettingUpdateFunc(const std::string & key)330 void PowerMgrService::WakeupLidSettingUpdateFunc(const std::string& key)
331 {
332     POWER_HILOGI(COMP_SVC, "Receive lid wakeup setting update.");
333     bool enable = SettingHelper::GetSettingWakeupLid(key);
334     if (enable) {
335         pms->HallSensorSubscriberInit();
336     } else {
337         pms->HallSensorSubscriberCancel();
338     }
339     std::shared_ptr<WakeupController> wakeupController = pms->GetWakeupController();
340     if (wakeupController == nullptr) {
341         POWER_HILOGE(FEATURE_INPUT, "wakeupController is not init");
342         return;
343     }
344     wakeupController->ChangeLidWakeupSourceConfig(enable);
345     POWER_HILOGI(COMP_SVC, "ChangeLidWakeupSourceConfig done");
346 }
347 
RegisterSettingWakeUpLidObserver()348 void PowerMgrService::RegisterSettingWakeUpLidObserver()
349 {
350     pms->HallSensorSubscriberInit();
351     POWER_HILOGI(COMP_SVC, "Start to registerSettingWakeUpLidObserver");
352     if (!SettingHelper::IsWakeupLidSettingValid()) {
353         POWER_HILOGE(COMP_UTILS, "settings.power.wakeup_lid is valid.");
354         return;
355     }
356     SettingObserver::UpdateFunc updateFunc = [&](const std::string& key) {WakeupLidSettingUpdateFunc(key);};
357     SettingHelper::RegisterSettingWakeupLidObserver(updateFunc);
358 }
359 
HallSensorSubscriberInit()360 void PowerMgrService::HallSensorSubscriberInit()
361 {
362 #ifdef HAS_SENSORS_SENSOR_PART
363     POWER_HILOGI(COMP_SVC, "Start to subscribe hall sensor");
364     if (!IsSupportSensor(SENSOR_TYPE_ID_HALL)) {
365         POWER_HILOGW(FEATURE_INPUT, "SENSOR_TYPE_ID_HALL sensor not support");
366         return;
367     }
368     if (strcpy_s(sensorUser_.name, sizeof(sensorUser_.name), "PowerManager") != EOK) {
369         POWER_HILOGW(FEATURE_INPUT, "strcpy_s error");
370         return;
371     }
372     isInLidMode_ = false;
373     sensorUser_.userData = nullptr;
374     sensorUser_.callback = &HallSensorCallback;
375     SubscribeSensor(SENSOR_TYPE_ID_HALL, &sensorUser_);
376     SetBatch(SENSOR_TYPE_ID_HALL, &sensorUser_, HALL_SAMPLING_RATE, HALL_REPORT_INTERVAL);
377     ActivateSensor(SENSOR_TYPE_ID_HALL, &sensorUser_);
378 #endif
379 }
380 
381 #ifdef HAS_SENSORS_SENSOR_PART
IsSupportSensor(SensorTypeId typeId)382 bool PowerMgrService::IsSupportSensor(SensorTypeId typeId)
383 {
384     bool isSupport = false;
385     SensorInfo* sensorInfo = nullptr;
386     int32_t count;
387     int32_t ret = GetAllSensors(&sensorInfo, &count);
388     if (ret != 0 || sensorInfo == nullptr) {
389         POWER_HILOGW(FEATURE_INPUT, "Get sensors fail, ret=%{public}d", ret);
390         return isSupport;
391     }
392     for (int32_t i = 0; i < count; i++) {
393         if (sensorInfo[i].sensorTypeId == typeId) {
394             isSupport = true;
395             break;
396         }
397     }
398     return isSupport;
399 }
400 
HallSensorCallback(SensorEvent * event)401 void PowerMgrService::HallSensorCallback(SensorEvent* event)
402 {
403     if (event == nullptr || event->sensorTypeId != SENSOR_TYPE_ID_HALL || event->data == nullptr) {
404         POWER_HILOGW(FEATURE_INPUT, "Hall sensor event is invalid");
405         return;
406     }
407 
408     std::shared_ptr<SuspendController> suspendController = pms->GetSuspendController();
409     if (suspendController == nullptr) {
410         POWER_HILOGE(FEATURE_INPUT, "get suspendController instance error");
411         return;
412     }
413 
414     std::shared_ptr<WakeupController> wakeupController = pms->GetWakeupController();
415     if (wakeupController == nullptr) {
416         POWER_HILOGE(FEATURE_INPUT, "wakeupController is not init");
417         return;
418     }
419     const uint32_t LID_CLOSED_HALL_FLAG = 0x1;
420     auto data = reinterpret_cast<HallData*>(event->data);
421     auto status = static_cast<uint32_t>(data->status);
422 
423     if (status & LID_CLOSED_HALL_FLAG) {
424         POWER_HILOGI(FEATURE_SUSPEND, "[UL_POWER] Lid close event received, begin to suspend");
425         isInLidMode_ = true;
426         SuspendDeviceType reason = SuspendDeviceType::SUSPEND_DEVICE_REASON_LID;
427         suspendController->ExecSuspendMonitorByReason(reason);
428     } else {
429         if (!isInLidMode_) {
430             return;
431         }
432         POWER_HILOGI(FEATURE_WAKEUP, "[UL_POWER] Lid open event received, begin to wakeup");
433         isInLidMode_ = false;
434         WakeupDeviceType reason = WakeupDeviceType::WAKEUP_DEVICE_LID;
435         wakeupController->ExecWakeupMonitorByReason(reason);
436     }
437 }
438 #endif
439 
HallSensorSubscriberCancel()440 void PowerMgrService::HallSensorSubscriberCancel()
441 {
442 #ifdef HAS_SENSORS_SENSOR_PART
443     POWER_HILOGI(COMP_SVC, "Start to cancel the subscribe of hall sensor");
444     if (IsSupportSensor(SENSOR_TYPE_ID_HALL)) {
445         DeactivateSensor(SENSOR_TYPE_ID_HALL, &sensorUser_);
446         UnsubscribeSensor(SENSOR_TYPE_ID_HALL, &sensorUser_);
447     }
448     isInLidMode_ = false;
449 #endif
450 }
451 
CheckDialogFlag()452 bool PowerMgrService::CheckDialogFlag()
453 {
454     bool isLongPress = shutdownDialog_.IsLongPress();
455     if (isLongPress) {
456         shutdownDialog_.ResetLongPressFlag();
457     }
458     return true;
459 }
460 
CheckDialogAndShuttingDown()461 bool PowerMgrService::CheckDialogAndShuttingDown()
462 {
463     bool isShuttingDown = shutdownController_->IsShuttingDown();
464     bool isLongPress = shutdownDialog_.IsLongPress();
465     if (isLongPress || isShuttingDown) {
466         POWER_HILOGW(
467             FEATURE_INPUT, "isLongPress: %{public}d, isShuttingDown: %{public}d", isLongPress, isShuttingDown);
468         shutdownDialog_.ResetLongPressFlag();
469         return true;
470     }
471     return false;
472 }
473 
SwitchSubscriberInit()474 void PowerMgrService::SwitchSubscriberInit()
475 {
476 #ifdef HAS_MULTIMODALINPUT_INPUT_PART
477     POWER_HILOGW(FEATURE_INPUT, "Initialize the subscription switch");
478     switchId_ =
479         InputManager::GetInstance()->SubscribeSwitchEvent([this](std::shared_ptr<OHOS::MMI::SwitchEvent> switchEvent) {
480             POWER_HILOGI(FEATURE_WAKEUP, "switch event received");
481             std::shared_ptr<SuspendController> suspendController = pms->GetSuspendController();
482             if (suspendController == nullptr) {
483                 POWER_HILOGE(FEATURE_INPUT, "get suspendController instance error");
484                 return;
485             }
486             std::shared_ptr<WakeupController> wakeupController = pms->GetWakeupController();
487             if (wakeupController == nullptr) {
488                 POWER_HILOGE(FEATURE_INPUT, "wakeupController is not init");
489                 return;
490             }
491             if (switchEvent->GetSwitchValue() == SwitchEvent::SWITCH_OFF) {
492                 POWER_HILOGI(FEATURE_SUSPEND, "[UL_POWER] Switch close event received, begin to suspend");
493                 powerStateMachine_->SetSwitchState(false);
494                 SuspendDeviceType reason = SuspendDeviceType::SUSPEND_DEVICE_REASON_SWITCH;
495                 suspendController->ExecSuspendMonitorByReason(reason);
496             } else {
497                 POWER_HILOGI(FEATURE_WAKEUP, "[UL_POWER] Switch open event received, begin to wakeup");
498                 powerStateMachine_->SetSwitchState(true);
499                 WakeupDeviceType reason = WakeupDeviceType::WAKEUP_DEVICE_SWITCH;
500                 wakeupController->ExecWakeupMonitorByReason(reason);
501             }
502         });
503 #endif
504 }
505 
SwitchSubscriberCancel()506 void PowerMgrService::SwitchSubscriberCancel()
507 {
508 #ifdef HAS_MULTIMODALINPUT_INPUT_PART
509     POWER_HILOGI(FEATURE_INPUT, "Unsubscribe switch information");
510     if (switchId_ >= 0) {
511         InputManager::GetInstance()->UnsubscribeSwitchEvent(switchId_);
512         switchId_ = -1;
513     }
514 #endif
515 }
516 
InputMonitorInit()517 void PowerMgrService::InputMonitorInit()
518 {
519 #ifdef HAS_MULTIMODALINPUT_INPUT_PART
520     POWER_HILOGI(FEATURE_INPUT, "PowerMgr service input monitor init");
521     std::shared_ptr<PowerMgrInputMonitor> inputMonitor = std::make_shared<PowerMgrInputMonitor>();
522     if (inputMonitorId_ < 0) {
523         inputMonitorId_ =
524             InputManager::GetInstance()->AddMonitor(std::static_pointer_cast<IInputEventConsumer>(inputMonitor));
525     }
526 #endif
527 }
528 
InputMonitorCancel()529 void PowerMgrService::InputMonitorCancel()
530 {
531 #ifdef HAS_MULTIMODALINPUT_INPUT_PART
532     POWER_HILOGI(FEATURE_INPUT, "PowerMgr service input monitor cancel");
533     InputManager* inputManager = InputManager::GetInstance();
534     if (inputMonitorId_ >= 0) {
535         inputManager->RemoveMonitor(inputMonitorId_);
536         inputMonitorId_ = -1;
537     }
538 #endif
539 }
540 
HandleKeyEvent(int32_t keyCode)541 void PowerMgrService::HandleKeyEvent(int32_t keyCode)
542 {
543 #ifdef HAS_MULTIMODALINPUT_INPUT_PART
544     POWER_HILOGD(FEATURE_INPUT, "keyCode: %{public}d", keyCode);
545     int64_t now = static_cast<int64_t>(time(nullptr));
546     if (IsScreenOn()) {
547         this->RefreshActivityInner(now, UserActivityType::USER_ACTIVITY_TYPE_BUTTON, false);
548     } else {
549         if (keyCode == KeyEvent::KEYCODE_F1) {
550             POWER_HILOGI(FEATURE_WAKEUP, "[UL_POWER] Wakeup by double click");
551             std::string reason = "double click";
552             reason.append(std::to_string(keyCode));
553             this->WakeupDevice(now, WakeupDeviceType::WAKEUP_DEVICE_DOUBLE_CLICK, reason);
554         } else if (keyCode >= KeyEvent::KEYCODE_0 && keyCode <= KeyEvent::KEYCODE_NUMPAD_RIGHT_PAREN) {
555             POWER_HILOGI(FEATURE_WAKEUP, "[UL_POWER] Wakeup by keyboard");
556             std::string reason = "keyboard:";
557             reason.append(std::to_string(keyCode));
558             this->WakeupDevice(now, WakeupDeviceType::WAKEUP_DEVICE_KEYBOARD, reason);
559         }
560     }
561 #endif
562 }
563 
HandlePointEvent(int32_t type)564 void PowerMgrService::HandlePointEvent(int32_t type)
565 {
566 #ifdef HAS_MULTIMODALINPUT_INPUT_PART
567     POWER_HILOGD(FEATURE_INPUT, "type: %{public}d", type);
568     int64_t now = static_cast<int64_t>(time(nullptr));
569     if (this->IsScreenOn()) {
570         this->RefreshActivityInner(now, UserActivityType::USER_ACTIVITY_TYPE_ATTENTION, false);
571     } else {
572         if (type == PointerEvent::SOURCE_TYPE_MOUSE) {
573             std::string reason = "mouse click";
574             POWER_HILOGI(FEATURE_WAKEUP, "[UL_POWER] Wakeup by mouse");
575             this->WakeupDevice(now, WakeupDeviceType::WAKEUP_DEVICE_MOUSE, reason);
576         }
577     }
578 #endif
579 }
580 
OnStop()581 void PowerMgrService::OnStop()
582 {
583     POWER_HILOGW(COMP_SVC, "Stop service");
584     if (!ready_) {
585         return;
586     }
587     powerStateMachine_->CancelDelayTimer(PowerStateMachine::CHECK_USER_ACTIVITY_TIMEOUT_MSG);
588     powerStateMachine_->CancelDelayTimer(PowerStateMachine::CHECK_USER_ACTIVITY_OFF_TIMEOUT_MSG);
589     powerStateMachine_->UnregisterDisplayOffTimeObserver();
590     if (suspendController_) {
591         suspendController_->StopSleep();
592     }
593 
594     SystemSuspendController::GetInstance().UnRegisterPowerHdiCallback();
595     KeyMonitorCancel();
596     HallSensorSubscriberCancel();
597     SwitchSubscriberCancel();
598     InputMonitorCancel();
599     ready_ = false;
600     isBootCompleted_ = false;
601     RemoveSystemAbilityListener(SUSPEND_MANAGER_SYSTEM_ABILITY_ID);
602     RemoveSystemAbilityListener(DEVICE_STANDBY_SERVICE_SYSTEM_ABILITY_ID);
603     RemoveSystemAbilityListener(DISPLAY_MANAGER_SERVICE_ID);
604 #ifdef MSDP_MOVEMENT_ENABLE
605     RemoveSystemAbilityListener(MSDP_MOVEMENT_SERVICE_ID);
606 #endif
607 #ifdef POWER_WAKEUPDOUBLE_OR_PICKUP_ENABLE
608     RemoveSystemAbilityListener(MSDP_MOTION_SERVICE_ID);
609     SettingHelper::UnregisterSettingWakeupDoubleObserver();
610     SettingHelper::UnregisterSettingWakeupPickupObserver();
611 #endif
612     SettingHelper::UnRegisterSettingWakeupLidObserver();
613     SettingHelper::UnRegisterSettingPowerModeObserver();
614     if (!OHOS::EventFwk::CommonEventManager::UnSubscribeCommonEvent(subscriberPtr_)) {
615         POWER_HILOGE(COMP_SVC, "Power Onstop unregister to commonevent manager failed!");
616     }
617 #ifdef MSDP_MOVEMENT_ENABLE
618     UnRegisterMovementCallback();
619 #endif
620     PowerExtIntfWrapper::Instance().DeInit();
621 }
622 
Reset()623 void PowerMgrService::Reset()
624 {
625     POWER_HILOGW(COMP_SVC, "start destruct ffrt_queue");
626     if (powerStateMachine_) {
627         powerStateMachine_->Reset();
628     }
629     if (suspendController_) {
630         suspendController_->Reset();
631     }
632     if (screenOffPreController_) {
633         screenOffPreController_->Reset();
634     }
635 }
636 
OnRemoveSystemAbility(int32_t systemAbilityId,const std::string & deviceId)637 void PowerMgrService::OnRemoveSystemAbility(int32_t systemAbilityId, const std::string& deviceId)
638 {
639     POWER_HILOGI(COMP_SVC, "systemAbilityId=%{public}d, deviceId=%{private}s", systemAbilityId, deviceId.c_str());
640     if (systemAbilityId == SUSPEND_MANAGER_SYSTEM_ABILITY_ID ||
641         systemAbilityId == DEVICE_STANDBY_SERVICE_SYSTEM_ABILITY_ID) {
642         std::lock_guard lock(lockMutex_);
643         runningLockMgr_->ResetRunningLocks();
644     }
645 #ifdef MSDP_MOVEMENT_ENABLE
646     if (systemAbilityId == MSDP_MOVEMENT_SERVICE_ID) {
647         auto power = DelayedSpSingleton<PowerMgrService>::GetInstance();
648         if (power == nullptr) {
649             POWER_HILOGI(COMP_SVC, "get PowerMgrService fail");
650             return;
651         }
652         power->ResetMovementState();
653     }
654 #endif
655 }
656 
OnAddSystemAbility(int32_t systemAbilityId,const std::string & deviceId)657 void PowerMgrService::OnAddSystemAbility(int32_t systemAbilityId, const std::string& deviceId)
658 {
659     POWER_HILOGI(COMP_SVC, "systemAbilityId=%{public}d, deviceId=%{private}s Add",
660         systemAbilityId, deviceId.c_str());
661     if (systemAbilityId == DISTRIBUTED_KV_DATA_SERVICE_ABILITY_ID) {
662         if (DelayedSpSingleton<PowerSaveMode>::GetInstance()) {
663             this->GetPowerModeModule().InitPowerMode();
664         }
665     }
666     if (systemAbilityId == DISPLAY_MANAGER_SERVICE_ID) {
667         RegisterBootCompletedCallback();
668     }
669 #ifdef MSDP_MOVEMENT_ENABLE
670     if (systemAbilityId == MSDP_MOVEMENT_SERVICE_ID) {
671         auto power = DelayedSpSingleton<PowerMgrService>::GetInstance();
672         if (power == nullptr) {
673             POWER_HILOGI(COMP_SVC, "get PowerMgrService fail");
674             return;
675         }
676         power->UnRegisterMovementCallback();
677         power->RegisterMovementCallback();
678     }
679 #endif
680 #ifdef POWER_WAKEUPDOUBLE_OR_PICKUP_ENABLE
681     if (systemAbilityId == MSDP_MOTION_SERVICE_ID && g_isPickUpOpen == true) {
682         WakeupController::PickupConnectMotionConfig(false);
683         WakeupController::PickupConnectMotionConfig(true);
684     }
685 #endif
686 }
687 
688 #ifdef MSDP_MOVEMENT_ENABLE
689 static const char* MOVEMENT_SUBSCRIBER_CONFIG = "RegisterMovementCallback";
690 static const char* MOVEMENT_UNSUBSCRIBER_CONFIG = "UnRegisterMovementCallback";
691 static const char* RESET_MOVEMENT_STATE_CONFIG = "ResetMovementState";
692 static const char* POWER_MANAGER_EXT_PATH = "/system/lib64/libpower_manager_ext.z.so";
693 typedef void(*FuncMovementSubscriber)();
694 typedef void(*FuncMovementUnsubscriber)();
695 typedef void(*FuncResetMovementState)();
696 
RegisterMovementCallback()697 void PowerMgrService::RegisterMovementCallback()
698 {
699     POWER_HILOGI(COMP_SVC, "Start to RegisterMovementCallback");
700     void *subscriberHandler = dlopen(POWER_MANAGER_EXT_PATH, RTLD_LAZY | RTLD_NODELETE);
701     if (subscriberHandler == nullptr) {
702         POWER_HILOGE(COMP_SVC, "Dlopen RegisterMovementCallback failed, reason : %{public}s", dlerror());
703         return;
704     }
705 
706     FuncMovementSubscriber MovementSubscriberFlag =
707         reinterpret_cast<FuncMovementSubscriber>(dlsym(subscriberHandler, MOVEMENT_SUBSCRIBER_CONFIG));
708     if (MovementSubscriberFlag == nullptr) {
709         POWER_HILOGE(COMP_SVC, "RegisterMovementCallback is null, reason : %{public}s", dlerror());
710         dlclose(subscriberHandler);
711         subscriberHandler = nullptr;
712         return;
713     }
714     MovementSubscriberFlag();
715     POWER_HILOGI(COMP_SVC, "RegisterMovementCallback Success");
716     dlclose(subscriberHandler);
717     subscriberHandler = nullptr;
718     return;
719 }
720 
UnRegisterMovementCallback()721 void PowerMgrService::UnRegisterMovementCallback()
722 {
723     POWER_HILOGI(COMP_SVC, "Start to UnRegisterMovementCallback");
724     void *unSubscriberHandler = dlopen(POWER_MANAGER_EXT_PATH, RTLD_LAZY | RTLD_NODELETE);
725     if (unSubscriberHandler == nullptr) {
726         POWER_HILOGE(COMP_SVC, "Dlopen UnRegisterMovementCallback failed, reason : %{public}s", dlerror());
727         return;
728     }
729 
730     FuncMovementUnsubscriber MovementUnsubscriberFlag =
731         reinterpret_cast<FuncMovementUnsubscriber>(dlsym(unSubscriberHandler, MOVEMENT_UNSUBSCRIBER_CONFIG));
732     if (MovementUnsubscriberFlag == nullptr) {
733         POWER_HILOGE(COMP_SVC, "UnRegisterMovementCallback is null, reason : %{public}s", dlerror());
734         dlclose(unSubscriberHandler);
735         unSubscriberHandler = nullptr;
736         return;
737     }
738     MovementUnsubscriberFlag();
739     POWER_HILOGI(COMP_SVC, "UnRegisterMovementCallback Success");
740     dlclose(unSubscriberHandler);
741     unSubscriberHandler = nullptr;
742     return;
743 }
744 
ResetMovementState()745 void PowerMgrService::ResetMovementState()
746 {
747     POWER_HILOGI(COMP_SVC, "Start to ResetMovementState");
748     void *resetMovementStateHandler = dlopen(POWER_MANAGER_EXT_PATH, RTLD_LAZY | RTLD_NODELETE);
749     if (resetMovementStateHandler == nullptr) {
750         POWER_HILOGE(COMP_SVC, "Dlopen ResetMovementState failed, reason : %{public}s", dlerror());
751         return;
752     }
753 
754     FuncResetMovementState ResetMovementStateFlag =
755         reinterpret_cast<FuncResetMovementState>(dlsym(resetMovementStateHandler, RESET_MOVEMENT_STATE_CONFIG));
756     if (ResetMovementStateFlag == nullptr) {
757         POWER_HILOGE(COMP_SVC, "ResetMovementState is null, reason : %{public}s", dlerror());
758         dlclose(resetMovementStateHandler);
759         resetMovementStateHandler = nullptr;
760         return;
761     }
762     ResetMovementStateFlag();
763     POWER_HILOGI(COMP_SVC, "ResetMovementState Success");
764     dlclose(resetMovementStateHandler);
765     resetMovementStateHandler = nullptr;
766     return;
767 }
768 #endif
769 
Dump(int32_t fd,const std::vector<std::u16string> & args)770 int32_t PowerMgrService::Dump(int32_t fd, const std::vector<std::u16string>& args)
771 {
772     if (!isBootCompleted_) {
773         return ERR_NO_INIT;
774     }
775     if (!Permission::IsSystem()) {
776         return ERR_PERMISSION_DENIED;
777     }
778     std::vector<std::string> argsInStr;
779     std::transform(args.begin(), args.end(), std::back_inserter(argsInStr), [](const std::u16string& arg) {
780         std::string ret = Str16ToStr8(arg);
781         POWER_HILOGD(COMP_SVC, "arg: %{public}s", ret.c_str());
782         return ret;
783     });
784     std::string result;
785     PowerMgrDumper::Dump(argsInStr, result);
786     if (!SaveStringToFd(fd, result)) {
787         POWER_HILOGE(COMP_SVC, "Dump failed, save to fd failed.");
788         POWER_HILOGE(COMP_SVC, "Dump Info:\n");
789         POWER_HILOGE(COMP_SVC, "%{public}s", result.c_str());
790         return ERR_OK;
791     }
792     return ERR_OK;
793 }
794 
RebootDevice(const std::string & reason)795 PowerErrors PowerMgrService::RebootDevice(const std::string& reason)
796 {
797     if (!Permission::IsSystem()) {
798         return PowerErrors::ERR_SYSTEM_API_DENIED;
799     }
800     return RebootDeviceForDeprecated(reason);
801 }
802 
RebootDeviceForDeprecated(const std::string & reason)803 PowerErrors PowerMgrService::RebootDeviceForDeprecated(const std::string& reason)
804 {
805     std::lock_guard lock(shutdownMutex_);
806     pid_t pid = IPCSkeleton::GetCallingPid();
807     auto uid = IPCSkeleton::GetCallingUid();
808     if (!Permission::IsPermissionGranted("ohos.permission.REBOOT")) {
809         return PowerErrors::ERR_PERMISSION_DENIED;
810     }
811     POWER_HILOGI(FEATURE_SHUTDOWN, "Cancel auto sleep timer");
812     powerStateMachine_->CancelDelayTimer(PowerStateMachine::CHECK_USER_ACTIVITY_TIMEOUT_MSG);
813     powerStateMachine_->CancelDelayTimer(PowerStateMachine::CHECK_USER_ACTIVITY_OFF_TIMEOUT_MSG);
814     if (suspendController_) {
815         suspendController_->StopSleep();
816     }
817     POWER_KHILOGI(FEATURE_SHUTDOWN, "Do reboot, called pid: %{public}d, uid: %{public}d", pid, uid);
818     shutdownController_->Reboot(reason);
819     return PowerErrors::ERR_OK;
820 }
821 
ShutDownDevice(const std::string & reason)822 PowerErrors PowerMgrService::ShutDownDevice(const std::string& reason)
823 {
824     auto now = static_cast<int64_t>(time(nullptr));
825     if (!Permission::IsSystem()) {
826         return PowerErrors::ERR_SYSTEM_API_DENIED;
827     }
828     if (!Permission::IsPermissionGranted("ohos.permission.REBOOT")) {
829         return PowerErrors::ERR_PERMISSION_DENIED;
830     }
831     if (reason == SHUTDOWN_FAST_REASON) {
832         g_wakeupReason = reason;
833         POWER_HILOGD(FEATURE_SHUTDOWN, "Calling Fast ShutDownDevice success");
834         return SuspendDevice(now, SuspendDeviceType::SUSPEND_DEVICE_REASON_STR, true);
835     }
836     g_wakeupReason = "";
837     std::lock_guard lock(shutdownMutex_);
838     pid_t pid = IPCSkeleton::GetCallingPid();
839     auto uid = IPCSkeleton::GetCallingUid();
840     POWER_HILOGI(FEATURE_SHUTDOWN, "Cancel auto sleep timer");
841     powerStateMachine_->CancelDelayTimer(PowerStateMachine::CHECK_USER_ACTIVITY_TIMEOUT_MSG);
842     powerStateMachine_->CancelDelayTimer(PowerStateMachine::CHECK_USER_ACTIVITY_OFF_TIMEOUT_MSG);
843     if (suspendController_) {
844         suspendController_->StopSleep();
845     }
846 
847     POWER_KHILOGI(FEATURE_SHUTDOWN, "[UL_POWER] Do shutdown, called pid: %{public}d, uid: %{public}d", pid, uid);
848     shutdownController_->Shutdown(reason);
849     return PowerErrors::ERR_OK;
850 }
851 
SetSuspendTag(const std::string & tag)852 PowerErrors PowerMgrService::SetSuspendTag(const std::string& tag)
853 {
854     std::lock_guard lock(suspendMutex_);
855     pid_t pid = IPCSkeleton::GetCallingPid();
856     auto uid = IPCSkeleton::GetCallingUid();
857     if (!Permission::IsSystem()) {
858         return PowerErrors::ERR_SYSTEM_API_DENIED;
859     }
860     POWER_HILOGI(FEATURE_SUSPEND, "pid: %{public}d, uid: %{public}d, tag: %{public}s", pid, uid, tag.c_str());
861     SystemSuspendController::GetInstance().SetSuspendTag(tag);
862     return PowerErrors::ERR_OK;
863 }
864 
SuspendDevice(int64_t callTimeMs,SuspendDeviceType reason,bool suspendImmed)865 PowerErrors PowerMgrService::SuspendDevice(int64_t callTimeMs, SuspendDeviceType reason, bool suspendImmed)
866 {
867     std::lock_guard lock(suspendMutex_);
868     pid_t pid = IPCSkeleton::GetCallingPid();
869     auto uid = IPCSkeleton::GetCallingUid();
870     if (!Permission::IsSystem()) {
871         return PowerErrors::ERR_SYSTEM_API_DENIED;
872     }
873     if (shutdownController_->IsShuttingDown()) {
874         POWER_HILOGW(FEATURE_SUSPEND, "System is shutting down, can't suspend");
875         return PowerErrors::ERR_OK;
876     }
877     POWER_HILOGI(FEATURE_SUSPEND, "[UL_POWER] Try to suspend device, pid: %{public}d, uid: %{public}d", pid, uid);
878     powerStateMachine_->SuspendDeviceInner(pid, callTimeMs, reason, suspendImmed);
879     return PowerErrors::ERR_OK;
880 }
881 
WakeupDevice(int64_t callTimeMs,WakeupDeviceType reason,const std::string & details)882 PowerErrors PowerMgrService::WakeupDevice(int64_t callTimeMs, WakeupDeviceType reason, const std::string& details)
883 {
884     std::lock_guard lock(wakeupMutex_);
885     if (!Permission::IsSystem()) {
886         return PowerErrors::ERR_SYSTEM_API_DENIED;
887     }
888     pid_t pid = IPCSkeleton::GetCallingPid();
889     auto uid = IPCSkeleton::GetCallingUid();
890     POWER_HILOGI(FEATURE_WAKEUP, "[UL_POWER] Try to wakeup device, pid: %{public}d, uid: %{public}d", pid, uid);
891     WakeupRunningLock wakeupRunningLock;
892     powerStateMachine_->WakeupDeviceInner(pid, callTimeMs, reason, details, "OHOS");
893     return PowerErrors::ERR_OK;
894 }
895 
RefreshActivity(int64_t callTimeMs,UserActivityType type,bool needChangeBacklight)896 bool PowerMgrService::RefreshActivity(int64_t callTimeMs, UserActivityType type, bool needChangeBacklight)
897 {
898     if (!Permission::IsPermissionGranted("ohos.permission.REFRESH_USER_ACTION") || !Permission::IsSystem()) {
899         return false;
900     }
901     pid_t pid = IPCSkeleton::GetCallingPid();
902     auto uid = IPCSkeleton::GetCallingUid();
903     POWER_HILOGI(FEATURE_ACTIVITY, "Try to refresh activity, pid: %{public}d, uid: %{public}d", pid, uid);
904     return RefreshActivityInner(callTimeMs, type, needChangeBacklight);
905 }
906 
RefreshActivityInner(int64_t callTimeMs,UserActivityType type,bool needChangeBacklight)907 bool PowerMgrService::RefreshActivityInner(int64_t callTimeMs, UserActivityType type, bool needChangeBacklight)
908 {
909     std::lock_guard lock(screenMutex_);
910     if (powerStateMachine_->CheckRefreshTime()) {
911         return false;
912     }
913     pid_t pid = IPCSkeleton::GetCallingPid();
914     powerStateMachine_->RefreshActivityInner(pid, callTimeMs, type, needChangeBacklight);
915     return true;
916 }
917 
OverrideScreenOffTime(int64_t timeout)918 PowerErrors PowerMgrService::OverrideScreenOffTime(int64_t timeout)
919 {
920     std::lock_guard lock(screenMutex_);
921     pid_t pid = IPCSkeleton::GetCallingPid();
922     auto uid = IPCSkeleton::GetCallingUid();
923     POWER_HILOGI(COMP_SVC,
924         "Try to override screenOffTime, timeout=%{public}" PRId64 ", pid: %{public}d, uid: %{public}d",
925         timeout, pid, uid);
926     if (!Permission::IsSystem()) {
927         POWER_HILOGI(COMP_SVC, "OverrideScreenOffTime failed, System permission intercept");
928         return PowerErrors::ERR_SYSTEM_API_DENIED;
929     }
930     return powerStateMachine_->OverrideScreenOffTimeInner(timeout) ?
931         PowerErrors::ERR_OK : PowerErrors::ERR_FAILURE;
932 }
933 
RestoreScreenOffTime()934 PowerErrors PowerMgrService::RestoreScreenOffTime()
935 {
936     std::lock_guard lock(screenMutex_);
937     if (!Permission::IsSystem()) {
938         POWER_HILOGI(COMP_SVC, "RestoreScreenOffTime failed, System permission intercept");
939         return PowerErrors::ERR_SYSTEM_API_DENIED;
940     }
941     POWER_HILOGD(COMP_SVC, "Try to restore screen off time");
942     return powerStateMachine_->RestoreScreenOffTimeInner() ?
943         PowerErrors::ERR_OK : PowerErrors::ERR_FAILURE;
944 }
945 
GetState()946 PowerState PowerMgrService::GetState()
947 {
948     std::lock_guard lock(stateMutex_);
949     auto state = powerStateMachine_->GetState();
950     POWER_HILOGD(FEATURE_POWER_STATE, "state: %{public}d", state);
951     return state;
952 }
953 
IsScreenOn(bool needPrintLog)954 bool PowerMgrService::IsScreenOn(bool needPrintLog)
955 {
956     std::lock_guard lock(stateMutex_);
957     auto isScreenOn = powerStateMachine_->IsScreenOn();
958     if (needPrintLog) {
959         POWER_HILOGD(COMP_SVC, "isScreenOn: %{public}d", isScreenOn);
960     }
961     return isScreenOn;
962 }
963 
IsFoldScreenOn()964 bool PowerMgrService::IsFoldScreenOn()
965 {
966     std::lock_guard lock(stateMutex_);
967     auto isFoldScreenOn = powerStateMachine_->IsFoldScreenOn();
968     POWER_HILOGI(COMP_SVC, "isFoldScreenOn: %{public}d", isFoldScreenOn);
969     return isFoldScreenOn;
970 }
971 
IsCollaborationScreenOn()972 bool PowerMgrService::IsCollaborationScreenOn()
973 {
974     std::lock_guard lock(stateMutex_);
975     auto isCollaborationScreenOn = powerStateMachine_->IsCollaborationScreenOn();
976     POWER_HILOGI(COMP_SVC, "isCollaborationScreenOn: %{public}d", isCollaborationScreenOn);
977     return isCollaborationScreenOn;
978 }
979 
ForceSuspendDevice(int64_t callTimeMs)980 PowerErrors PowerMgrService::ForceSuspendDevice(int64_t callTimeMs)
981 {
982     std::lock_guard lock(suspendMutex_);
983     pid_t pid = IPCSkeleton::GetCallingPid();
984     auto uid = IPCSkeleton::GetCallingUid();
985     if (!Permission::IsSystem()) {
986         POWER_HILOGI(FEATURE_SUSPEND, "ForceSuspendDevice failed, System permission intercept");
987         return PowerErrors::ERR_SYSTEM_API_DENIED;
988     }
989     if (shutdownController_->IsShuttingDown()) {
990         POWER_HILOGI(FEATURE_SUSPEND, "System is shutting down, can't force suspend");
991         return PowerErrors::ERR_FAILURE;
992     }
993     POWER_HILOGI(FEATURE_SUSPEND, "[UL_POWER] Try to force suspend device, pid: %{public}d, uid: %{public}d", pid, uid);
994     powerStateMachine_->ForceSuspendDeviceInner(pid, callTimeMs);
995     return PowerErrors::ERR_OK;
996 }
997 
Hibernate(bool clearMemory)998 PowerErrors PowerMgrService::Hibernate(bool clearMemory)
999 {
1000     POWER_HILOGI(FEATURE_SUSPEND, "power mgr service hibernate begin.");
1001     if (!Permission::IsSystem()) {
1002         POWER_HILOGI(FEATURE_SUSPEND, "Hibernate failed, System permission intercept");
1003         return PowerErrors::ERR_SYSTEM_API_DENIED;
1004     }
1005 #ifdef POWER_MANAGER_POWER_ENABLE_S4
1006     std::lock_guard lock(hibernateMutex_);
1007     pid_t pid = IPCSkeleton::GetCallingPid();
1008     auto uid = IPCSkeleton::GetCallingUid();
1009     if (shutdownController_->IsShuttingDown()) {
1010         POWER_HILOGI(FEATURE_SUSPEND, "System is shutting down, can't hibernate");
1011         return PowerErrors::ERR_FAILURE;
1012     }
1013     POWER_HILOGI(FEATURE_SUSPEND,
1014         "[UL_POWER] Try to hibernate, pid: %{public}d, uid: %{public}d, clearMemory: %{public}d",
1015         pid, uid, static_cast<int>(clearMemory));
1016     HibernateControllerInit();
1017     bool ret = powerStateMachine_->HibernateInner(clearMemory);
1018     return ret ? PowerErrors::ERR_OK : PowerErrors::ERR_FAILURE;
1019 #else
1020     POWER_HILOGI(FEATURE_SUSPEND, "Hibernate interface not supported.");
1021     return PowerErrors::ERR_FAILURE;
1022 #endif
1023 }
1024 
GetBundleNameByUid(const int32_t uid)1025 std::string PowerMgrService::GetBundleNameByUid(const int32_t uid)
1026 {
1027     std::string tempBundleName = "";
1028     if (uid < OHOS::AppExecFwk::Constants::BASE_APP_UID) {
1029         return tempBundleName;
1030     }
1031     BundleMgrClient bundleObj;
1032 
1033     std::string identity = IPCSkeleton::ResetCallingIdentity();
1034     ErrCode res = bundleObj.GetNameForUid(uid, tempBundleName);
1035     IPCSkeleton::SetCallingIdentity(identity);
1036     if (res != ERR_OK) {
1037         POWER_HILOGE(FEATURE_RUNNING_LOCK, "Failed to get bundle name for uid=%{public}d, ErrCode=%{public}d",
1038             uid, static_cast<int32_t>(res));
1039     }
1040     POWER_HILOGI(FEATURE_RUNNING_LOCK, "bundle name for uid=%{public}d, name=%{public}s", uid, tempBundleName.c_str());
1041     return tempBundleName;
1042 }
1043 
FillRunningLockParam(const RunningLockInfo & info,const uint64_t lockid,int32_t timeOutMS)1044 RunningLockParam PowerMgrService::FillRunningLockParam(const RunningLockInfo& info,
1045     const uint64_t lockid, int32_t timeOutMS)
1046 {
1047     RunningLockParam filledParam {};
1048     filledParam.lockid = lockid;
1049     filledParam.name = info.name;
1050     filledParam.type = info.type;
1051     if (filledParam.type == RunningLockType::RUNNINGLOCK_BACKGROUND) {
1052         filledParam.type = RunningLockType::RUNNINGLOCK_BACKGROUND_TASK;
1053     }
1054     filledParam.timeoutMs = timeOutMS;
1055     filledParam.pid = IPCSkeleton::GetCallingPid();
1056     filledParam.uid = IPCSkeleton::GetCallingUid();
1057     filledParam.bundleName = GetBundleNameByUid(filledParam.uid);
1058     return filledParam;
1059 }
1060 
CreateRunningLock(const sptr<IRemoteObject> & remoteObj,const RunningLockInfo & runningLockInfo)1061 PowerErrors PowerMgrService::CreateRunningLock(
1062     const sptr<IRemoteObject>& remoteObj, const RunningLockInfo& runningLockInfo)
1063 {
1064     PowerXCollie powerXCollie("PowerMgrService::CreateRunningLock", true);
1065     std::lock_guard lock(lockMutex_);
1066     if (!Permission::IsPermissionGranted("ohos.permission.RUNNING_LOCK")) {
1067         return PowerErrors::ERR_PERMISSION_DENIED;
1068     }
1069     if (!IsRunningLockTypeSupported(runningLockInfo.type)) {
1070         POWER_HILOGW(FEATURE_RUNNING_LOCK,
1071             "runninglock type is not supported, name=%{public}s, type=%{public}d",
1072             runningLockInfo.name.c_str(), runningLockInfo.type);
1073         return PowerErrors::ERR_PARAM_INVALID;
1074     }
1075 
1076     uintptr_t remoteObjPtr = reinterpret_cast<uintptr_t>(remoteObj.GetRefPtr());
1077     uint64_t lockid = std::hash<uintptr_t>()(remoteObjPtr);
1078     RunningLockParam runningLockParam = FillRunningLockParam(runningLockInfo, lockid);
1079     runningLockMgr_->CreateRunningLock(remoteObj, runningLockParam);
1080     return PowerErrors::ERR_OK;
1081 }
1082 
ReleaseRunningLock(const sptr<IRemoteObject> & remoteObj,const std::string & name)1083 bool PowerMgrService::ReleaseRunningLock(const sptr<IRemoteObject>& remoteObj, const std::string& name)
1084 {
1085     PowerXCollie powerXCollie("PowerMgrService::ReleaseRunningLock", true);
1086     std::lock_guard lock(lockMutex_);
1087     bool result = false;
1088     if (!Permission::IsPermissionGranted("ohos.permission.RUNNING_LOCK")) {
1089         return result;
1090     }
1091 
1092     result = runningLockMgr_->ReleaseLock(remoteObj, name);
1093     return result;
1094 }
1095 
IsRunningLockTypeSupported(RunningLockType type)1096 bool PowerMgrService::IsRunningLockTypeSupported(RunningLockType type)
1097 {
1098     if (Permission::IsHap()) {
1099         if (Permission::IsSystem()) {
1100             return type <= RunningLockType::RUNNINGLOCK_PROXIMITY_SCREEN_CONTROL;
1101         }
1102         return type == RunningLockType::RUNNINGLOCK_BACKGROUND ||
1103             type == RunningLockType::RUNNINGLOCK_PROXIMITY_SCREEN_CONTROL;
1104     }
1105     return type == RunningLockType::RUNNINGLOCK_SCREEN ||
1106         type == RunningLockType::RUNNINGLOCK_BACKGROUND || // this will be instead by BACKGROUND_XXX types.
1107         type == RunningLockType::RUNNINGLOCK_PROXIMITY_SCREEN_CONTROL ||
1108         type == RunningLockType::RUNNINGLOCK_COORDINATION ||
1109         type == RunningLockType::RUNNINGLOCK_BACKGROUND_PHONE ||
1110         type == RunningLockType::RUNNINGLOCK_BACKGROUND_NOTIFICATION ||
1111         type == RunningLockType::RUNNINGLOCK_BACKGROUND_AUDIO ||
1112         type == RunningLockType::RUNNINGLOCK_BACKGROUND_SPORT ||
1113         type == RunningLockType::RUNNINGLOCK_BACKGROUND_NAVIGATION ||
1114         type == RunningLockType::RUNNINGLOCK_BACKGROUND_TASK;
1115 }
1116 
UpdateWorkSource(const sptr<IRemoteObject> & remoteObj,const std::map<int32_t,std::string> & workSources)1117 bool PowerMgrService::UpdateWorkSource(const sptr<IRemoteObject>& remoteObj,
1118     const std::map<int32_t, std::string>& workSources)
1119 {
1120     PowerXCollie powerXCollie("PowerMgrService::UpdateWorkSource", true);
1121     if (!Permission::IsPermissionGranted("ohos.permission.RUNNING_LOCK")) {
1122         return false;
1123     }
1124     std::lock_guard lock(lockMutex_);
1125     runningLockMgr_->UpdateWorkSource(remoteObj, workSources);
1126     return true;
1127 }
1128 
Lock(const sptr<IRemoteObject> & remoteObj,int32_t timeOutMs)1129 PowerErrors PowerMgrService::Lock(const sptr<IRemoteObject>& remoteObj, int32_t timeOutMs)
1130 {
1131 #ifdef HAS_HIVIEWDFX_HISYSEVENT_PART
1132     constexpr int32_t RUNNINGLOCK_TIMEOUT_MS = 50;
1133     int32_t beginTimeMs = GetTickCount();
1134     pid_t pid = IPCSkeleton::GetCallingPid();
1135     auto uid = IPCSkeleton::GetCallingUid();
1136 #endif
1137     PowerXCollie powerXCollie("PowerMgrService::Lock", true);
1138     if (!Permission::IsPermissionGranted("ohos.permission.RUNNING_LOCK")) {
1139         return PowerErrors::ERR_PERMISSION_DENIED;
1140     }
1141     std::lock_guard lock(lockMutex_);
1142     runningLockMgr_->Lock(remoteObj);
1143     if (timeOutMs > 0) {
1144         std::function<void()> task = [this, remoteObj, timeOutMs]() {
1145             std::lock_guard lock(lockMutex_);
1146             RunningLockTimerHandler::GetInstance().UnregisterRunningLockTimer(remoteObj);
1147             runningLockMgr_->UpdateWorkSource(remoteObj, {});
1148             runningLockMgr_->UnLock(remoteObj);
1149         };
1150         RunningLockTimerHandler::GetInstance().RegisterRunningLockTimer(remoteObj, task, timeOutMs);
1151     }
1152 #ifdef HAS_HIVIEWDFX_HISYSEVENT_PART
1153     int32_t endTimeMs = GetTickCount();
1154     if (endTimeMs - beginTimeMs > RUNNINGLOCK_TIMEOUT_MS) {
1155         POWER_HILOGI(FEATURE_RUNNING_LOCK, "Lock interface timeout=%{public}d", (endTimeMs - beginTimeMs));
1156         HiSysEventWrite(HiviewDFX::HiSysEvent::Domain::POWER, "INTERFACE_CONSUMING_TIMEOUT",
1157             HiviewDFX::HiSysEvent::EventType::BEHAVIOR, "PID", pid, "UID", uid, "TYPE",
1158             static_cast<int32_t>(InterfaceTimeoutType::INTERFACE_TIMEOUT_TYPE_RUNNINGLOCK_LOCK), "REASON", "",
1159             "TIME", (endTimeMs - beginTimeMs));
1160     }
1161 #endif
1162     return PowerErrors::ERR_OK;
1163 }
1164 
UnLock(const sptr<IRemoteObject> & remoteObj,const std::string & name)1165 PowerErrors PowerMgrService::UnLock(const sptr<IRemoteObject>& remoteObj, const std::string& name)
1166 {
1167 #ifdef HAS_HIVIEWDFX_HISYSEVENT_PART
1168     constexpr int32_t RUNNINGLOCK_TIMEOUT_MS = 50;
1169     int32_t beginTimeMs = GetTickCount();
1170     pid_t pid = IPCSkeleton::GetCallingPid();
1171     auto uid = IPCSkeleton::GetCallingUid();
1172 #endif
1173     PowerXCollie powerXCollie("PowerMgrService::UnLock", true);
1174     if (!Permission::IsPermissionGranted("ohos.permission.RUNNING_LOCK")) {
1175         return PowerErrors::ERR_PERMISSION_DENIED;
1176     }
1177     std::lock_guard lock(lockMutex_);
1178     RunningLockTimerHandler::GetInstance().UnregisterRunningLockTimer(remoteObj);
1179     runningLockMgr_->UnLock(remoteObj, name);
1180 #ifdef HAS_HIVIEWDFX_HISYSEVENT_PART
1181     int32_t endTimeMs = GetTickCount();
1182     if (endTimeMs - beginTimeMs > RUNNINGLOCK_TIMEOUT_MS) {
1183         POWER_HILOGI(FEATURE_RUNNING_LOCK, "UnLock interface timeout=%{public}d", (endTimeMs - beginTimeMs));
1184         HiSysEventWrite(HiviewDFX::HiSysEvent::Domain::POWER, "INTERFACE_CONSUMING_TIMEOUT",
1185             HiviewDFX::HiSysEvent::EventType::BEHAVIOR, "PID", pid, "UID", uid, "TYPE",
1186             static_cast<int32_t>(InterfaceTimeoutType::INTERFACE_TIMEOUT_TYPE_RUNNINGLOCK_UNLOCK), "REASON", "",
1187             "TIME", (endTimeMs - beginTimeMs));
1188     }
1189 #endif
1190     return PowerErrors::ERR_OK;
1191 }
1192 
QueryRunningLockLists(std::map<std::string,RunningLockInfo> & runningLockLists)1193 bool PowerMgrService::QueryRunningLockLists(std::map<std::string, RunningLockInfo>& runningLockLists)
1194 {
1195     PowerXCollie powerXCollie("PowerMgrService::QueryRunningLockLists", true);
1196     std::lock_guard lock(lockMutex_);
1197     if (!Permission::IsPermissionGranted("ohos.permission.RUNNING_LOCK")) {
1198         return false;
1199     }
1200     QueryRunningLockListsInner(runningLockLists);
1201     return true;
1202 }
1203 
QueryRunningLockListsInner(std::map<std::string,RunningLockInfo> & runningLockLists)1204 void PowerMgrService::QueryRunningLockListsInner(std::map<std::string, RunningLockInfo>& runningLockLists)
1205 {
1206     runningLockMgr_->QueryRunningLockLists(runningLockLists);
1207 }
1208 
RegisterRunningLockCallback(const sptr<IPowerRunninglockCallback> & callback)1209 bool PowerMgrService::RegisterRunningLockCallback(const sptr<IPowerRunninglockCallback>& callback)
1210 {
1211     std::lock_guard lock(lockMutex_);
1212     pid_t pid = IPCSkeleton::GetCallingPid();
1213     auto uid = IPCSkeleton::GetCallingUid();
1214     if (!Permission::IsPermissionGranted("ohos.permission.POWER_MANAGER")) {
1215         return false;
1216     }
1217     POWER_HILOGI(FEATURE_RUNNING_LOCK, "%{public}s: pid: %{public}d, uid: %{public}d", __func__, pid, uid);
1218     runningLockMgr_->RegisterRunningLockCallback(callback);
1219     return true;
1220 }
1221 
UnRegisterRunningLockCallback(const sptr<IPowerRunninglockCallback> & callback)1222 bool PowerMgrService::UnRegisterRunningLockCallback(const sptr<IPowerRunninglockCallback>& callback)
1223 {
1224     std::lock_guard lock(lockMutex_);
1225     pid_t pid = IPCSkeleton::GetCallingPid();
1226     auto uid = IPCSkeleton::GetCallingUid();
1227     if (!Permission::IsPermissionGranted("ohos.permission.POWER_MANAGER")) {
1228         return false;
1229     }
1230     POWER_HILOGI(FEATURE_RUNNING_LOCK, "%{public}s: pid: %{public}d, uid: %{public}d", __func__, pid, uid);
1231     runningLockMgr_->RegisterRunningLockCallback(callback);
1232     return true;
1233 }
1234 
ForceUnLock(const sptr<IRemoteObject> & remoteObj)1235 void PowerMgrService::ForceUnLock(const sptr<IRemoteObject>& remoteObj)
1236 {
1237     PowerXCollie powerXCollie("PowerMgrService::ForceUnLock", true);
1238     std::lock_guard lock(lockMutex_);
1239     runningLockMgr_->UnLock(remoteObj);
1240     runningLockMgr_->ReleaseLock(remoteObj);
1241 }
1242 
IsUsed(const sptr<IRemoteObject> & remoteObj)1243 bool PowerMgrService::IsUsed(const sptr<IRemoteObject>& remoteObj)
1244 {
1245     PowerXCollie powerXCollie("PowerMgrService::IsUsed", true);
1246     std::lock_guard lock(lockMutex_);
1247     auto isUsed = runningLockMgr_->IsUsed(remoteObj);
1248     POWER_HILOGD(FEATURE_RUNNING_LOCK, "RunningLock is Used: %{public}d", isUsed);
1249     return isUsed;
1250 }
1251 
ProxyRunningLock(bool isProxied,pid_t pid,pid_t uid)1252 bool PowerMgrService::ProxyRunningLock(bool isProxied, pid_t pid, pid_t uid)
1253 {
1254     PowerXCollie powerXCollie("PowerMgrService::ProxyRunningLock", true);
1255     std::lock_guard lock(lockMutex_);
1256     if (!Permission::IsSystem()) {
1257         return false;
1258     }
1259     return runningLockMgr_->ProxyRunningLock(isProxied, pid, uid);
1260 }
1261 
ProxyRunningLocks(bool isProxied,const std::vector<std::pair<pid_t,pid_t>> & processInfos)1262 bool PowerMgrService::ProxyRunningLocks(bool isProxied, const std::vector<std::pair<pid_t, pid_t>>& processInfos)
1263 {
1264     PowerXCollie powerXCollie("PowerMgrService::ProxyRunningLocks", true);
1265     if (!Permission::IsSystem()) {
1266         return false;
1267     }
1268     std::lock_guard lock(lockMutex_);
1269     runningLockMgr_->ProxyRunningLocks(isProxied, processInfos);
1270     return true;
1271 }
1272 
ResetRunningLocks()1273 bool PowerMgrService::ResetRunningLocks()
1274 {
1275     PowerXCollie powerXCollie("PowerMgrService::ResetRunningLocks", true);
1276     if (!Permission::IsSystem()) {
1277         return false;
1278     }
1279     std::lock_guard lock(lockMutex_);
1280     runningLockMgr_->ResetRunningLocks();
1281     return true;
1282 }
1283 
RegisterPowerStateCallback(const sptr<IPowerStateCallback> & callback,bool isSync)1284 bool PowerMgrService::RegisterPowerStateCallback(const sptr<IPowerStateCallback>& callback, bool isSync)
1285 {
1286     std::lock_guard lock(stateMutex_);
1287     pid_t pid = IPCSkeleton::GetCallingPid();
1288     auto uid = IPCSkeleton::GetCallingUid();
1289     if (!Permission::IsPermissionGranted("ohos.permission.POWER_MANAGER")) {
1290         return false;
1291     }
1292     POWER_HILOGI(FEATURE_POWER_STATE, "%{public}s: pid: %{public}d, uid: %{public}d, isSync: %{public}u", __func__, pid,
1293         uid, static_cast<uint32_t>(isSync));
1294     powerStateMachine_->RegisterPowerStateCallback(callback, isSync);
1295     return true;
1296 }
1297 
UnRegisterPowerStateCallback(const sptr<IPowerStateCallback> & callback)1298 bool PowerMgrService::UnRegisterPowerStateCallback(const sptr<IPowerStateCallback>& callback)
1299 {
1300     std::lock_guard lock(stateMutex_);
1301     pid_t pid = IPCSkeleton::GetCallingPid();
1302     auto uid = IPCSkeleton::GetCallingUid();
1303     if (!Permission::IsPermissionGranted("ohos.permission.POWER_MANAGER")) {
1304         return false;
1305     }
1306     POWER_HILOGI(FEATURE_POWER_STATE, "%{public}s: pid: %{public}d, uid: %{public}d", __func__, pid, uid);
1307     powerStateMachine_->UnRegisterPowerStateCallback(callback);
1308     return true;
1309 }
1310 
RegisterSyncSleepCallback(const sptr<ISyncSleepCallback> & callback,SleepPriority priority)1311 bool PowerMgrService::RegisterSyncSleepCallback(const sptr<ISyncSleepCallback>& callback, SleepPriority priority)
1312 {
1313     std::lock_guard lock(suspendMutex_);
1314     pid_t pid = IPCSkeleton::GetCallingPid();
1315     auto uid = IPCSkeleton::GetCallingUid();
1316     if (!Permission::IsPermissionGranted("ohos.permission.POWER_MANAGER")) {
1317         return false;
1318     }
1319     POWER_HILOGI(FEATURE_SUSPEND, "%{public}s: pid: %{public}d, uid: %{public}d", __func__, pid, uid);
1320     suspendController_->AddCallback(callback, priority);
1321     return true;
1322 }
1323 
UnRegisterSyncSleepCallback(const sptr<ISyncSleepCallback> & callback)1324 bool PowerMgrService::UnRegisterSyncSleepCallback(const sptr<ISyncSleepCallback>& callback)
1325 {
1326     std::lock_guard lock(suspendMutex_);
1327     pid_t pid = IPCSkeleton::GetCallingPid();
1328     auto uid = IPCSkeleton::GetCallingUid();
1329     if (!Permission::IsPermissionGranted("ohos.permission.POWER_MANAGER")) {
1330         return false;
1331     }
1332     POWER_HILOGI(FEATURE_SUSPEND, "%{public}s: pid: %{public}d, uid: %{public}d", __func__, pid, uid);
1333     suspendController_->RemoveCallback(callback);
1334     return true;
1335 }
1336 
RegisterSyncHibernateCallback(const sptr<ISyncHibernateCallback> & callback)1337 bool PowerMgrService::RegisterSyncHibernateCallback(const sptr<ISyncHibernateCallback>& callback)
1338 {
1339 #ifdef POWER_MANAGER_POWER_ENABLE_S4
1340     POWER_HILOGI(FEATURE_SUSPEND, "RegisterSyncHibernateCallback begin.");
1341     HibernateControllerInit();
1342     hibernateController_->RegisterSyncHibernateCallback(callback);
1343     return true;
1344 #else
1345     POWER_HILOGI(FEATURE_SUSPEND, "RegisterSyncHibernateCallback interface not supported.");
1346     return false;
1347 #endif
1348 }
1349 
UnRegisterSyncHibernateCallback(const sptr<ISyncHibernateCallback> & callback)1350 bool PowerMgrService::UnRegisterSyncHibernateCallback(const sptr<ISyncHibernateCallback>& callback)
1351 {
1352 #ifdef POWER_MANAGER_POWER_ENABLE_S4
1353     POWER_HILOGI(FEATURE_SUSPEND, "UnRegisterSyncHibernateCallback begin.");
1354     HibernateControllerInit();
1355     hibernateController_->UnregisterSyncHibernateCallback(callback);
1356     return true;
1357 #else
1358     POWER_HILOGI(FEATURE_SUSPEND, "UnRegisterSyncHibernateCallback interface not supported.");
1359     return false;
1360 #endif
1361 }
1362 
RegisterPowerModeCallback(const sptr<IPowerModeCallback> & callback)1363 bool PowerMgrService::RegisterPowerModeCallback(const sptr<IPowerModeCallback>& callback)
1364 {
1365     std::lock_guard lock(modeMutex_);
1366     pid_t pid = IPCSkeleton::GetCallingPid();
1367     auto uid = IPCSkeleton::GetCallingUid();
1368     if (!Permission::IsSystem()) {
1369         return false;
1370     }
1371     POWER_HILOGI(FEATURE_POWER_MODE, "%{public}s: pid: %{public}d, uid: %{public}d", __func__, pid, uid);
1372     powerModeModule_.AddPowerModeCallback(callback);
1373     return true;
1374 }
1375 
UnRegisterPowerModeCallback(const sptr<IPowerModeCallback> & callback)1376 bool PowerMgrService::UnRegisterPowerModeCallback(const sptr<IPowerModeCallback>& callback)
1377 {
1378     std::lock_guard lock(modeMutex_);
1379     pid_t pid = IPCSkeleton::GetCallingPid();
1380     auto uid = IPCSkeleton::GetCallingUid();
1381     if (!Permission::IsSystem()) {
1382         return false;
1383     }
1384     POWER_HILOGI(FEATURE_POWER_MODE, "%{public}s: pid: %{public}d, uid: %{public}d", __func__, pid, uid);
1385     powerModeModule_.DelPowerModeCallback(callback);
1386     return true;
1387 }
1388 
RegisterScreenStateCallback(int32_t remainTime,const sptr<IScreenOffPreCallback> & callback)1389 bool PowerMgrService::RegisterScreenStateCallback(int32_t remainTime, const sptr<IScreenOffPreCallback>& callback)
1390 {
1391     std::lock_guard lock(screenOffPreMutex_);
1392     pid_t pid = IPCSkeleton::GetCallingPid();
1393     auto uid = IPCSkeleton::GetCallingUid();
1394     if (!Permission::IsSystem()) {
1395         return false;
1396     }
1397     POWER_HILOGI(FEATURE_SCREEN_OFF_PRE, "%{public}s: pid: %{public}d, uid: %{public}d", __func__, pid, uid);
1398     screenOffPreController_->AddScreenStateCallback(remainTime, callback);
1399     return true;
1400 }
1401 
UnRegisterScreenStateCallback(const sptr<IScreenOffPreCallback> & callback)1402 bool PowerMgrService::UnRegisterScreenStateCallback(const sptr<IScreenOffPreCallback>& callback)
1403 {
1404     std::lock_guard lock(screenOffPreMutex_);
1405     pid_t pid = IPCSkeleton::GetCallingPid();
1406     auto uid = IPCSkeleton::GetCallingUid();
1407     if (!Permission::IsSystem()) {
1408         return false;
1409     }
1410     POWER_HILOGI(FEATURE_SCREEN_OFF_PRE, "%{public}s: pid: %{public}d, uid: %{public}d", __func__, pid, uid);
1411     screenOffPreController_->DelScreenStateCallback(callback);
1412     return true;
1413 }
1414 
SetDisplaySuspend(bool enable)1415 bool PowerMgrService::SetDisplaySuspend(bool enable)
1416 {
1417     std::lock_guard lock(screenMutex_);
1418     pid_t pid = IPCSkeleton::GetCallingPid();
1419     auto uid = IPCSkeleton::GetCallingUid();
1420     if (!Permission::IsSystem()) {
1421         return false;
1422     }
1423     POWER_HILOGI(FEATURE_SUSPEND, "%{public}s: pid: %{public}d, uid: %{public}d, enable: %{public}d",
1424         __func__, pid, uid, enable);
1425     powerStateMachine_->SetDisplaySuspend(enable);
1426     return true;
1427 }
1428 
SetDeviceMode(const PowerMode & mode)1429 PowerErrors PowerMgrService::SetDeviceMode(const PowerMode& mode)
1430 {
1431     std::lock_guard lock(modeMutex_);
1432     pid_t pid = IPCSkeleton::GetCallingPid();
1433     auto uid = IPCSkeleton::GetCallingUid();
1434     POWER_HILOGI(FEATURE_POWER_MODE, "%{public}s: pid: %{public}d, uid: %{public}d, mode: %{public}u",
1435         __func__, pid, uid, mode);
1436     if (!Permission::IsSystem()) {
1437         return PowerErrors::ERR_SYSTEM_API_DENIED;
1438     }
1439     if (!Permission::IsPermissionGranted("ohos.permission.POWER_OPTIMIZATION")) {
1440         return PowerErrors::ERR_PERMISSION_DENIED;
1441     }
1442     powerModeModule_.SetModeItem(mode);
1443     return PowerErrors::ERR_OK;
1444 }
1445 
GetDeviceMode()1446 PowerMode PowerMgrService::GetDeviceMode()
1447 {
1448     std::lock_guard lock(modeMutex_);
1449     pid_t pid = IPCSkeleton::GetCallingPid();
1450     auto uid = IPCSkeleton::GetCallingUid();
1451     auto mode = powerModeModule_.GetModeItem();
1452     POWER_HILOGI(FEATURE_POWER_MODE, "%{public}s: pid: %{public}d, uid: %{public}d, mode: %{public}u",
1453         __func__, pid, uid, mode);
1454     return mode;
1455 }
1456 
ShellDump(const std::vector<std::string> & args,uint32_t argc)1457 std::string PowerMgrService::ShellDump(const std::vector<std::string>& args, uint32_t argc)
1458 {
1459     if (!Permission::IsSystem() || !isBootCompleted_) {
1460         return "";
1461     }
1462     std::lock_guard lock(dumpMutex_);
1463     pid_t pid = IPCSkeleton::GetCallingPid();
1464     auto uid = IPCSkeleton::GetCallingUid();
1465 
1466     std::string result;
1467     bool ret = PowerMgrDumper::Dump(args, result);
1468     POWER_HILOGI(COMP_SVC, "%{public}s: pid: %{public}d, uid: %{public}d ret :%{public}d", __func__, pid, uid, ret);
1469     return result;
1470 }
1471 
RegisterShutdownCallback(const sptr<ITakeOverShutdownCallback> & callback,ShutdownPriority priority)1472 void PowerMgrService::RegisterShutdownCallback(
1473     const sptr<ITakeOverShutdownCallback>& callback, ShutdownPriority priority)
1474 {
1475     RETURN_IF (callback == nullptr);
1476     RETURN_IF (!Permission::IsSystem());
1477 
1478     std::lock_guard lock(shutdownMutex_);
1479     shutdownController_->AddCallback(callback, priority);
1480 }
1481 
UnRegisterShutdownCallback(const sptr<ITakeOverShutdownCallback> & callback)1482 void PowerMgrService::UnRegisterShutdownCallback(const sptr<ITakeOverShutdownCallback>& callback)
1483 {
1484     RETURN_IF (callback == nullptr);
1485     RETURN_IF (!Permission::IsSystem());
1486 
1487     std::lock_guard lock(shutdownMutex_);
1488     shutdownController_->RemoveCallback(callback);
1489 }
1490 
RegisterShutdownCallback(const sptr<IAsyncShutdownCallback> & callback,ShutdownPriority priority)1491 void PowerMgrService::RegisterShutdownCallback(
1492     const sptr<IAsyncShutdownCallback>& callback, ShutdownPriority priority)
1493 {
1494     RETURN_IF (callback == nullptr);
1495     RETURN_IF (!Permission::IsSystem());
1496 
1497     std::lock_guard lock(shutdownMutex_);
1498     shutdownController_->AddCallback(callback, priority);
1499 }
1500 
UnRegisterShutdownCallback(const sptr<IAsyncShutdownCallback> & callback)1501 void PowerMgrService::UnRegisterShutdownCallback(const sptr<IAsyncShutdownCallback>& callback)
1502 {
1503     RETURN_IF (callback == nullptr);
1504     RETURN_IF (!Permission::IsSystem());
1505 
1506     std::lock_guard lock(shutdownMutex_);
1507     shutdownController_->RemoveCallback(callback);
1508 }
1509 
RegisterShutdownCallback(const sptr<ISyncShutdownCallback> & callback,ShutdownPriority priority)1510 void PowerMgrService::RegisterShutdownCallback(
1511     const sptr<ISyncShutdownCallback>& callback, ShutdownPriority priority)
1512 {
1513     RETURN_IF (callback == nullptr);
1514     RETURN_IF (!Permission::IsSystem());
1515 
1516     std::lock_guard lock(shutdownMutex_);
1517     shutdownController_->AddCallback(callback, priority);
1518 }
1519 
UnRegisterShutdownCallback(const sptr<ISyncShutdownCallback> & callback)1520 void PowerMgrService::UnRegisterShutdownCallback(const sptr<ISyncShutdownCallback>& callback)
1521 {
1522     RETURN_IF (callback == nullptr);
1523     RETURN_IF (!Permission::IsSystem());
1524 
1525     std::lock_guard lock(shutdownMutex_);
1526     shutdownController_->RemoveCallback(callback);
1527 }
1528 
WakeupRunningLock()1529 PowerMgrService::WakeupRunningLock::WakeupRunningLock()
1530 {
1531     token_ = new (std::nothrow) RunningLockTokenStub();
1532     if (token_ == nullptr) {
1533         POWER_HILOGE(COMP_SVC, "create runninglock token failed");
1534         return;
1535     }
1536     RunningLockInfo info = {"PowerMgrWakeupLock", OHOS::PowerMgr::RunningLockType::RUNNINGLOCK_BACKGROUND};
1537     pms->CreateRunningLock(token_, info);
1538     pms->Lock(token_, WAKEUP_LOCK_TIMEOUT_MS);
1539 }
1540 
~WakeupRunningLock()1541 PowerMgrService::WakeupRunningLock::~WakeupRunningLock()
1542 {
1543     if (token_ == nullptr) {
1544         POWER_HILOGE(COMP_SVC, "token_ is nullptr");
1545         return;
1546     }
1547     pms->ReleaseRunningLock(token_);
1548 }
1549 
SuspendControllerInit()1550 void PowerMgrService::SuspendControllerInit()
1551 {
1552     if (!suspendController_) {
1553         suspendController_ = std::make_shared<SuspendController>(shutdownController_, powerStateMachine_);
1554     }
1555     suspendController_->Init();
1556 }
1557 
WakeupControllerInit()1558 void PowerMgrService::WakeupControllerInit()
1559 {
1560     if (!wakeupController_) {
1561         wakeupController_ = std::make_shared<WakeupController>(powerStateMachine_);
1562     }
1563     wakeupController_->Init();
1564 }
1565 
1566 #ifdef POWER_MANAGER_POWER_ENABLE_S4
HibernateControllerInit()1567 void PowerMgrService::HibernateControllerInit()
1568 {
1569     if (!hibernateController_) {
1570         hibernateController_ = std::make_shared<HibernateController>();
1571     }
1572 }
1573 #endif
1574 
IsCollaborationState()1575 bool PowerMgrService::IsCollaborationState()
1576 {
1577     bool collaborationState = false;
1578     auto pms = DelayedSpSingleton<PowerMgrService>::GetInstance();
1579     if (pms == nullptr) {
1580         return collaborationState;
1581     }
1582     auto stateMachine = pms->GetPowerStateMachine();
1583     if (stateMachine == nullptr) {
1584         return collaborationState;
1585     }
1586     collaborationState = stateMachine->IsRunningLockEnabled(RunningLockType::RUNNINGLOCK_COORDINATION);
1587     return collaborationState;
1588 }
1589 
1590 #ifdef POWER_MANAGER_WAKEUP_ACTION
WakeupActionControllerInit()1591 void PowerMgrService::WakeupActionControllerInit()
1592 {
1593     if (!wakeupActionController_) {
1594         wakeupActionController_ = std::make_shared<WakeupActionController>(shutdownController_, powerStateMachine_);
1595     }
1596     wakeupActionController_->Init();
1597 }
1598 #endif
1599 
1600 #ifdef POWER_MANAGER_ENABLE_CHARGING_TYPE_SETTING
PowerConnectStatusInit()1601 void PowerMgrService::PowerConnectStatusInit()
1602 {
1603     auto pluggedType = BatterySrvClient::GetInstance().GetPluggedType();
1604     if (pluggedType == BatteryPluggedType::PLUGGED_TYPE_BUTT) {
1605         POWER_HILOGE(COMP_SVC, "BatterySrvClient GetPluggedType error");
1606         SetPowerConnectStatus(PowerConnectStatus::POWER_CONNECT_INVALID);
1607     } else if ((pluggedType == BatteryPluggedType::PLUGGED_TYPE_AC) ||
1608         (pluggedType == BatteryPluggedType::PLUGGED_TYPE_USB) ||
1609         (pluggedType == BatteryPluggedType::PLUGGED_TYPE_WIRELESS)) {
1610         SetPowerConnectStatus(PowerConnectStatus::POWER_CONNECT_AC);
1611     } else {
1612         SetPowerConnectStatus(PowerConnectStatus::POWER_CONNECT_DC);
1613     }
1614 }
1615 
IsPowerConnected()1616 bool PowerMgrService::IsPowerConnected()
1617 {
1618     if (GetPowerConnectStatus() == PowerConnectStatus::POWER_CONNECT_INVALID) {
1619         PowerConnectStatusInit(); // try to init again if invalid
1620     }
1621     return GetPowerConnectStatus() == PowerConnectStatus::POWER_CONNECT_AC;
1622 }
1623 #endif
1624 
VibratorInit()1625 void PowerMgrService::VibratorInit()
1626 {
1627     std::shared_ptr<PowerVibrator> vibrator = PowerVibrator::GetInstance();
1628     vibrator->LoadConfig(POWER_VIBRATOR_CONFIG_FILE,
1629         VENDOR_POWER_VIBRATOR_CONFIG_FILE, SYSTEM_POWER_VIBRATOR_CONFIG_FILE);
1630 }
1631 
IsStandby(bool & isStandby)1632 PowerErrors PowerMgrService::IsStandby(bool& isStandby)
1633 {
1634 #ifdef HAS_DEVICE_STANDBY_PART
1635     DevStandbyMgr::StandbyServiceClient& standbyServiceClient = DevStandbyMgr::StandbyServiceClient::GetInstance();
1636     ErrCode code = standbyServiceClient.IsDeviceInStandby(isStandby);
1637     if (code == ERR_OK) {
1638         return PowerErrors::ERR_OK;
1639     }
1640     return PowerErrors::ERR_CONNECTION_FAIL;
1641 #else
1642     return PowerErrors::ERR_OK;
1643 #endif
1644 }
1645 
OnRemoteDied(const wptr<IRemoteObject> & remote)1646 void PowerMgrService::InvokerDeathRecipient::OnRemoteDied(const wptr<IRemoteObject>& remote)
1647 {
1648     POWER_HILOGI(COMP_SVC, "OnRemoteDied Called");
1649     if (!remote.promote()) {
1650         POWER_HILOGI(COMP_SVC, "proxy no longer exists, return early");
1651         return;
1652     }
1653     POWER_HILOGI(COMP_SVC, "the last client using %{public}s has died", interfaceName_.c_str());
1654     auto pms = DelayedSpSingleton<PowerMgrService>::GetInstance();
1655     if (!pms) {
1656         POWER_HILOGE(COMP_SVC, "cannot get PowerMgrService, return early");
1657         return;
1658     }
1659     callback_(pms);
1660 }
1661 
SetForceTimingOut(bool enabled,const sptr<IRemoteObject> & token)1662 PowerErrors PowerMgrService::SetForceTimingOut(bool enabled, const sptr<IRemoteObject>& token)
1663 {
1664     static sptr<IRemoteObject> thisInterfaceInvoker = nullptr;
1665     static std::mutex localMutex;
1666     static sptr<InvokerDeathRecipient> drt =
1667         sptr<InvokerDeathRecipient>::MakeSptr(__func__, [](const sptr<PowerMgrService>& pms) {
1668             auto stateMachine = pms->GetPowerStateMachine();
1669             if (!stateMachine) {
1670                 POWER_HILOGE(COMP_SVC, "cannot get PowerStateMachine, return early");
1671                 return;
1672             }
1673             stateMachine->SetForceTimingOut(false);
1674             POWER_HILOGI(COMP_SVC, "the variables related to SetForceTimingOut has been reset");
1675         });
1676 
1677     if (!Permission::IsSystem()) {
1678         return PowerErrors::ERR_SYSTEM_API_DENIED;
1679     }
1680 
1681     // even if drt is nullptr(unlikely), it will be checked in IPCObjectProxy::SendObituary()
1682     localMutex.lock();
1683     if (token && token->IsProxyObject() && token != thisInterfaceInvoker) {
1684         // The localMutex only ensures that the "remove, assign, add" actions for THIS drt are thread safe.
1685         // AddDeathRecipient/RemoveDeathRecipient are thread safe theirselves.
1686         // Different remote objects(invokers) do not interfere wich each other
1687         // Different DeathRecipients for the same invoker do not interfere wich each other
1688         // Only one RemoteObject may hold the death recipient defined in this method and only once.
1689         if (thisInterfaceInvoker) {
1690             thisInterfaceInvoker->RemoveDeathRecipient(drt);
1691         } // removed from the old invoker
1692         thisInterfaceInvoker = token;
1693         thisInterfaceInvoker->AddDeathRecipient(drt); // added to the new invoker
1694     }
1695     localMutex.unlock();
1696     powerStateMachine_->SetForceTimingOut(enabled);
1697     return PowerErrors::ERR_OK;
1698 }
1699 
LockScreenAfterTimingOut(bool enabledLockScreen,bool checkLock,bool sendScreenOffEvent,const sptr<IRemoteObject> & token)1700 PowerErrors PowerMgrService::LockScreenAfterTimingOut(
1701     bool enabledLockScreen, bool checkLock, bool sendScreenOffEvent, const sptr<IRemoteObject>& token)
1702 {
1703     static sptr<IRemoteObject> thisInterfaceInvoker = nullptr;
1704     static std::mutex localMutex;
1705     static sptr<InvokerDeathRecipient> drt =
1706         sptr<InvokerDeathRecipient>::MakeSptr(__func__, [](sptr<PowerMgrService> pms) {
1707             auto stateMachine = pms->GetPowerStateMachine();
1708             if (!stateMachine) {
1709                 POWER_HILOGE(COMP_SVC, "cannot get PowerStateMachine, return early");
1710                 return;
1711             }
1712             stateMachine->LockScreenAfterTimingOut(true, false, true);
1713             POWER_HILOGI(COMP_SVC, "the variables related to LockScreenAfterTimingOut has been reset");
1714         });
1715 
1716     if (!Permission::IsSystem()) {
1717         return PowerErrors::ERR_SYSTEM_API_DENIED;
1718     }
1719     localMutex.lock();
1720     if (token && token->IsProxyObject() && token != thisInterfaceInvoker) {
1721         // The localMutex only ensures that the "remove, assign, add" actions are thread safe.
1722         // AddDeathRecipient/RemoveDeathRecipient are thread safe theirselves.
1723         if (thisInterfaceInvoker) {
1724             thisInterfaceInvoker->RemoveDeathRecipient(drt);
1725         } // removed from the old invoker
1726         thisInterfaceInvoker = token;
1727         thisInterfaceInvoker->AddDeathRecipient(drt); // added to the new invoker
1728     }
1729     localMutex.unlock();
1730     powerStateMachine_->LockScreenAfterTimingOut(enabledLockScreen, checkLock, sendScreenOffEvent);
1731     return PowerErrors::ERR_OK;
1732 }
1733 
1734 #ifdef HAS_MULTIMODALINPUT_INPUT_PART
OnInputEvent(std::shared_ptr<KeyEvent> keyEvent) const1735 void PowerMgrInputMonitor::OnInputEvent(std::shared_ptr<KeyEvent> keyEvent) const
1736 {
1737     auto pms = DelayedSpSingleton<PowerMgrService>::GetInstance();
1738     if (pms == nullptr) {
1739         return;
1740     }
1741     auto stateMachine = pms->GetPowerStateMachine();
1742     if (stateMachine == nullptr) {
1743         return;
1744     }
1745     if (keyEvent->GetDeviceId() == COLLABORATION_REMOTE_DEVICE_ID &&
1746         stateMachine->IsRunningLockEnabled(RunningLockType::RUNNINGLOCK_COORDINATION) &&
1747         stateMachine->GetState() == PowerState::AWAKE) {
1748         stateMachine->SetState(PowerState::DIM, StateChangeReason::STATE_CHANGE_REASON_COORDINATION, true);
1749         POWER_HILOGD(FEATURE_INPUT, "remote Key event in coordinated state, override screen off time");
1750     }
1751 }
1752 
OnInputEvent(std::shared_ptr<PointerEvent> pointerEvent) const1753 void PowerMgrInputMonitor::OnInputEvent(std::shared_ptr<PointerEvent> pointerEvent) const
1754 {
1755     auto pms = DelayedSpSingleton<PowerMgrService>::GetInstance();
1756     if (pms == nullptr) {
1757         return;
1758     }
1759     auto stateMachine = pms->GetPowerStateMachine();
1760     if (stateMachine == nullptr) {
1761         return;
1762     }
1763     auto action = pointerEvent->GetPointerAction();
1764     if (action == PointerEvent::POINTER_ACTION_ENTER_WINDOW ||
1765         action == PointerEvent::POINTER_ACTION_LEAVE_WINDOW ||
1766         action == PointerEvent::POINTER_ACTION_PULL_IN_WINDOW ||
1767         action == PointerEvent::POINTER_ACTION_PULL_OUT_WINDOW) {
1768         return;
1769     }
1770     if (pointerEvent->GetDeviceId() == COLLABORATION_REMOTE_DEVICE_ID &&
1771         stateMachine->IsRunningLockEnabled(RunningLockType::RUNNINGLOCK_COORDINATION) &&
1772         stateMachine->GetState() == PowerState::AWAKE) {
1773         stateMachine->SetState(PowerState::DIM, StateChangeReason::STATE_CHANGE_REASON_COORDINATION, true);
1774         POWER_HILOGD(FEATURE_INPUT, "remote pointer event in coordinated state, override screen off time");
1775     }
1776 }
1777 
OnInputEvent(std::shared_ptr<AxisEvent> axisEvent) const1778 void PowerMgrInputMonitor::OnInputEvent(std::shared_ptr<AxisEvent> axisEvent) const {};
1779 #endif
1780 
SubscribeCommonEvent()1781 void PowerMgrService::SubscribeCommonEvent()
1782 {
1783     using namespace OHOS::EventFwk;
1784     MatchingSkills matchingSkills;
1785     matchingSkills.AddEvent(CommonEventSupport::COMMON_EVENT_USER_SWITCHED);
1786 #ifdef POWER_MANAGER_ENABLE_CHARGING_TYPE_SETTING
1787     matchingSkills.AddEvent(CommonEventSupport::COMMON_EVENT_POWER_CONNECTED);
1788     matchingSkills.AddEvent(CommonEventSupport::COMMON_EVENT_POWER_DISCONNECTED);
1789 #endif
1790     CommonEventSubscribeInfo subscribeInfo(matchingSkills);
1791     subscribeInfo.SetThreadMode(CommonEventSubscribeInfo::ThreadMode::COMMON);
1792     if (!subscriberPtr_) {
1793         subscriberPtr_ = std::make_shared<PowerCommonEventSubscriber>(subscribeInfo);
1794     }
1795     bool result = CommonEventManager::SubscribeCommonEvent(subscriberPtr_);
1796     if (!result) {
1797         POWER_HILOGE(COMP_SVC, "Subscribe COMMON_EVENT failed");
1798     }
1799 }
1800 
UnregisterAllSettingObserver()1801 void PowerMgrService::UnregisterAllSettingObserver()
1802 {
1803     auto pms = DelayedSpSingleton<PowerMgrService>::GetInstance();
1804     if (pms == nullptr) {
1805         POWER_HILOGI(COMP_SVC, "get PowerMgrService fail");
1806         return;
1807     }
1808 
1809 #ifdef POWER_WAKEUPDOUBLE_OR_PICKUP_ENABLE
1810     SettingHelper::UnregisterSettingWakeupDoubleObserver();
1811     SettingHelper::UnregisterSettingWakeupPickupObserver();
1812 #endif
1813     pms->GetWakeupController()->UnregisterSettingsObserver();
1814 #ifdef POWER_MANAGER_ENABLE_CHARGING_TYPE_SETTING
1815     pms->GetSuspendController()->UnregisterSettingsObserver();
1816     auto stateMachine = pms->GetPowerStateMachine();
1817     if (stateMachine == nullptr) {
1818         POWER_HILOGE(COMP_SVC, "get PowerStateMachine fail");
1819         return;
1820     }
1821     stateMachine->UnregisterDisplayOffTimeObserver();
1822 #endif
1823 }
1824 
RegisterAllSettingObserver()1825 void PowerMgrService::RegisterAllSettingObserver()
1826 {
1827     auto pms = DelayedSpSingleton<PowerMgrService>::GetInstance();
1828     if (pms == nullptr) {
1829         POWER_HILOGI(COMP_SVC, "get PowerMgrService fail");
1830         return;
1831     }
1832 
1833 #ifdef POWER_WAKEUPDOUBLE_OR_PICKUP_ENABLE
1834     pms->RegisterSettingWakeupDoubleClickObservers();
1835     pms->RegisterSettingWakeupPickupGestureObserver();
1836 #endif
1837     pms->WakeupControllerInit();
1838 #ifdef POWER_MANAGER_ENABLE_CHARGING_TYPE_SETTING
1839     pms->SuspendControllerInit();
1840     pms->UpdateSettingInvalidDisplayOffTime(); // update setting value if invalid before register
1841     auto stateMachine = pms->GetPowerStateMachine();
1842     if (stateMachine == nullptr) {
1843         POWER_HILOGE(COMP_SVC, "get PowerStateMachine fail");
1844         return;
1845     }
1846     stateMachine->RegisterDisplayOffTimeObserver();
1847 #endif
1848 }
1849 
GetSettingDisplayOffTime(int64_t defaultTime)1850 int64_t PowerMgrService::GetSettingDisplayOffTime(int64_t defaultTime)
1851 {
1852     int64_t settingTime = defaultTime;
1853 #ifdef POWER_MANAGER_ENABLE_CHARGING_TYPE_SETTING
1854     auto pms = DelayedSpSingleton<PowerMgrService>::GetInstance();
1855     if (pms == nullptr) {
1856         POWER_HILOGE(FEATURE_POWER_MODE, "get PowerMgrService fail");
1857         return settingTime;
1858     }
1859     if (pms->IsPowerConnected()) {
1860         settingTime = SettingHelper::GetSettingDisplayAcScreenOffTime(defaultTime);
1861     } else {
1862         settingTime = SettingHelper::GetSettingDisplayDcScreenOffTime(defaultTime);
1863     }
1864 #else
1865     settingTime = SettingHelper::GetSettingDisplayOffTime(defaultTime);
1866 #endif
1867     return settingTime;
1868 }
1869 
1870 #ifdef POWER_MANAGER_ENABLE_CHARGING_TYPE_SETTING
UpdateSettingInvalidDisplayOffTime()1871 void PowerMgrService::UpdateSettingInvalidDisplayOffTime()
1872 {
1873     if (SettingHelper::IsSettingDisplayAcScreenOffTimeValid() &&
1874         SettingHelper::IsSettingDisplayDcScreenOffTimeValid()) {
1875         return;
1876     }
1877 
1878     auto power = DelayedSpSingleton<PowerMgrService>::GetInstance();
1879     if (power == nullptr) {
1880         POWER_HILOGE(COMP_SVC, "get PowerMgrService fail");
1881         return;
1882     }
1883     auto stateMachine = power->GetPowerStateMachine();
1884     if (stateMachine == nullptr) {
1885         POWER_HILOGE(COMP_SVC, "get PowerStateMachine fail");
1886         return;
1887     }
1888     stateMachine->SetDisplayOffTime(DEFAULT_DISPLAY_OFF_TIME, true);
1889 }
1890 
OnPowerConnectStatusChanged(PowerConnectStatus status)1891 void PowerCommonEventSubscriber::OnPowerConnectStatusChanged(PowerConnectStatus status)
1892 {
1893     auto power = DelayedSpSingleton<PowerMgrService>::GetInstance();
1894     if (power == nullptr) {
1895         POWER_HILOGE(COMP_SVC, "get PowerMgrService fail");
1896         return;
1897     }
1898     power->SetPowerConnectStatus(status);
1899 
1900     auto suspendController = power->GetSuspendController();
1901     if (suspendController == nullptr) {
1902         POWER_HILOGE(COMP_SVC, "get suspendController fail");
1903         return;
1904     }
1905     suspendController->UpdateSuspendSources();
1906 
1907     auto stateMachine = power->GetPowerStateMachine();
1908     if (stateMachine == nullptr) {
1909         POWER_HILOGE(COMP_SVC, "get PowerStateMachine fail");
1910         return;
1911     }
1912     stateMachine->DisplayOffTimeUpdateFunc();
1913 }
1914 #endif
1915 
OnReceiveEvent(const OHOS::EventFwk::CommonEventData & data)1916 void PowerCommonEventSubscriber::OnReceiveEvent(const OHOS::EventFwk::CommonEventData &data)
1917 {
1918     std::string action = data.GetWant().GetAction();
1919     auto pms = DelayedSpSingleton<PowerMgrService>::GetInstance();
1920     if (pms == nullptr) {
1921         POWER_HILOGI(COMP_SVC, "get PowerMgrService fail");
1922         return;
1923     }
1924     if (action == OHOS::EventFwk::CommonEventSupport::COMMON_EVENT_USER_SWITCHED) {
1925         pms->UnregisterAllSettingObserver();    // unregister old user observer
1926         SettingHelper::UpdateCurrentUserId();   // update user Id
1927         pms->RegisterAllSettingObserver();      // register new user observer
1928 #ifdef POWER_MANAGER_ENABLE_CHARGING_TYPE_SETTING
1929     } else if (action == OHOS::EventFwk::CommonEventSupport::COMMON_EVENT_POWER_CONNECTED) {
1930         OnPowerConnectStatusChanged(PowerConnectStatus::POWER_CONNECT_AC);
1931     } else if (action == OHOS::EventFwk::CommonEventSupport::COMMON_EVENT_POWER_DISCONNECTED) {
1932         OnPowerConnectStatusChanged(PowerConnectStatus::POWER_CONNECT_DC);
1933 #endif
1934     }
1935 }
1936 } // namespace PowerMgr
1937 } // namespace OHOS
1938