• 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 <algorithm>
19 #include <datetime_ex.h>
20 #include <file_ex.h>
21 #ifdef HAS_HIVIEWDFX_HISYSEVENT_PART
22 #include <hisysevent.h>
23 #endif
24 #include <if_system_ability_manager.h>
25 #ifdef HAS_MULTIMODALINPUT_INPUT_PART
26 #include <input_manager.h>
27 #endif
28 #include <ipc_skeleton.h>
29 #include <iservice_registry.h>
30 #include <modulemgr.h>
31 #include <securec.h>
32 #include <string_ex.h>
33 #include <system_ability_definition.h>
34 #include <sys_mgr_client.h>
35 #include <bundle_mgr_client.h>
36 #include <unistd.h>
37 #include "ability_connect_callback_stub.h"
38 #include "ability_manager_client.h"
39 #include "ffrt_utils.h"
40 #include "permission.h"
41 #include "power_common.h"
42 #include "power_ext_intf_wrapper.h"
43 #include "power_mgr_dumper.h"
44 #include "power_vibrator.h"
45 #include "power_xcollie.h"
46 #include "setting_helper.h"
47 #include "running_lock_timer_handler.h"
48 #include "sysparam.h"
49 #include "system_suspend_controller.h"
50 #include "xcollie/watchdog.h"
51 #include "errors.h"
52 #include "parameters.h"
53 #ifdef HAS_DEVICE_STANDBY_PART
54 #include "standby_service_client.h"
55 #endif
56 #ifdef POWER_MANAGER_ENABLE_CHARGING_TYPE_SETTING
57 #include "battery_srv_client.h"
58 #endif
59 #ifdef MSDP_MOVEMENT_ENABLE
60 #include <dlfcn.h>
61 #endif
62 
63 using namespace OHOS::AppExecFwk;
64 using namespace OHOS::AAFwk;
65 namespace OHOS {
66 namespace PowerMgr {
67 namespace {
68 MODULE_MGR *g_moduleMgr = nullptr;
69 #if (defined(__aarch64__) || defined(__x86_64__))
70 const char* POWER_PLUGIN_AUTORUN_PATH = "/system/lib64/powerplugin/autorun";
71 #else
72 const char* POWER_PLUGIN_AUTORUN_PATH = "/system/lib/powerplugin/autorun";
73 #endif
74 const std::string POWERMGR_SERVICE_NAME = "PowerMgrService";
75 const std::string REASON_POWER_KEY = "power_key";
76 static std::string g_wakeupReason = "";
77 const std::string POWER_VIBRATOR_CONFIG_FILE = "etc/power_config/power_vibrator.json";
78 const std::string VENDOR_POWER_VIBRATOR_CONFIG_FILE = "/vendor/etc/power_config/power_vibrator.json";
79 const std::string SYSTEM_POWER_VIBRATOR_CONFIG_FILE = "/system/etc/power_config/power_vibrator.json";
80 static const char* POWER_MANAGER_EXT_PATH = "libpower_manager_ext.z.so";
81 constexpr int32_t WAKEUP_LOCK_TIMEOUT_MS = 5000;
82 constexpr int32_t HIBERNATE_GUARD_TIMEOUT_MS = 40000; // PREPARE_HIBERNATE_TIMEOUT_MS + 10000
83 constexpr int32_t COLLABORATION_REMOTE_DEVICE_ID = 0xAAAAAAFF;
84 constexpr uint64_t VIRTUAL_SCREEN_START_ID = 1000;
85 auto pms = DelayedSpSingleton<PowerMgrService>::GetInstance();
86 const bool G_REGISTER_RESULT = SystemAbility::MakeAndRegisterAbility(pms.GetRefPtr());
87 SysParam::BootCompletedCallback g_bootCompletedCallback;
88 static std::mutex powerInitMutex_;
89 #ifdef POWER_PICKUP_ENABLE
90 bool g_isPickUpOpen = false;
91 #endif
92 constexpr int32_t API19 = 19;
93 } // namespace
94 
95 std::atomic_bool PowerMgrService::isBootCompleted_ = false;
96 std::atomic_bool PowerMgrService::isNeedReInit_  = false;
97 std::atomic_bool PowerMgrService::displayManagerServiceCrash_ = false;
98 #ifdef HAS_SENSORS_SENSOR_PART
99     std::atomic_bool PowerMgrService::isInLidMode_ = false;
100 #endif
101 using namespace MMI;
102 
PowerMgrService()103 PowerMgrService::PowerMgrService() : SystemAbility(POWER_MANAGER_SERVICE_ID, true) {}
104 
~PowerMgrService()105 PowerMgrService::~PowerMgrService() {}
106 
OnStart()107 void PowerMgrService::OnStart()
108 {
109     POWER_HILOGD(COMP_SVC, "Power Management startup");
110     if (ready_) {
111         POWER_HILOGW(COMP_SVC, "OnStart is ready, nothing to do");
112         return;
113     }
114 #ifndef FUZZ_TEST
115     g_moduleMgr = ModuleMgrScan(POWER_PLUGIN_AUTORUN_PATH);
116 #endif
117     if (!Init()) {
118         POWER_HILOGE(COMP_SVC, "powermgr service init fail");
119         return;
120     }
121     AddSystemAbilityListener(SUSPEND_MANAGER_SYSTEM_ABILITY_ID);
122     AddSystemAbilityListener(DEVICE_STANDBY_SERVICE_SYSTEM_ABILITY_ID);
123     AddSystemAbilityListener(DISPLAY_MANAGER_SERVICE_ID);
124     AddSystemAbilityListener(DISTRIBUTED_KV_DATA_SERVICE_ABILITY_ID);
125     AddSystemAbilityListener(DISPLAY_MANAGER_SERVICE_SA_ID);
126 #ifdef MSDP_MOVEMENT_ENABLE
127     AddSystemAbilityListener(MSDP_MOVEMENT_SERVICE_ID);
128 #endif
129 #ifdef POWER_PICKUP_ENABLE
130     AddSystemAbilityListener(MSDP_MOTION_SERVICE_ID);
131 #endif
132 #ifndef FUZZ_TEST
133     SystemSuspendController::GetInstance().RegisterHdiStatusListener();
134     PowerExtIntfWrapper::Instance().Init();
135 #endif
136 
137     if (!Publish(DelayedSpSingleton<PowerMgrService>::GetInstance())) {
138         POWER_HILOGE(COMP_SVC, "Register to system ability manager failed");
139         return;
140     }
141     ready_ = true;
142     system::SetParameter("bootevent.powermgr.ready", "true");
143     POWER_HILOGI(COMP_SVC, "Add system ability success");
144 }
145 
Init()146 bool PowerMgrService::Init()
147 {
148     POWER_HILOGI(COMP_SVC, "powermgr service init start");
149     if (!ffrtTimer_) {
150         ffrtTimer_ = std::make_shared<FFRTTimer>("power_manager_ffrt_queue");
151     }
152     if (!runningLockMgr_) {
153         runningLockMgr_ = std::make_shared<RunningLockMgr>(pms);
154     }
155     if (!runningLockMgr_->Init()) {
156         POWER_HILOGE(COMP_SVC, "Running lock init fail");
157         return false;
158     }
159     if (!shutdownController_) {
160         shutdownController_ = std::make_shared<ShutdownController>();
161     }
162     if (!PowerStateMachineInit()) {
163         POWER_HILOGE(COMP_SVC, "Power state machine init fail");
164     }
165     if (!screenOffPreController_) {
166         screenOffPreController_ = std::make_shared<ScreenOffPreController>(powerStateMachine_);
167         screenOffPreController_->Init();
168     }
169     isDuringCallStateEnable_ = system::GetBoolParameter("const.power.during_call_state_enable", false);
170     POWER_HILOGI(COMP_SVC, "powermgr service init success %{public}d", isDuringCallStateEnable_);
171     return true;
172 }
173 
RegisterBootCompletedCallback()174 void PowerMgrService::RegisterBootCompletedCallback()
175 {
176     POWER_HILOGI(COMP_SVC, "plan to RegisterBootCompletedCallback.");
177     g_bootCompletedCallback = []() {
178         std::lock_guard lock(powerInitMutex_);
179         if (!isNeedReInit_ ) {
180             POWER_HILOGW(COMP_SVC, "Power initialization is not required.");
181             return;
182         }
183         POWER_HILOGI(COMP_SVC, "BootCompletedCallback triggered");
184         isNeedReInit_  = false;
185         auto power = DelayedSpSingleton<PowerMgrService>::GetInstance();
186         if (power == nullptr) {
187             POWER_HILOGI(COMP_SVC, "get PowerMgrService fail");
188             return;
189         }
190         auto powerStateMachine = power->GetPowerStateMachine();
191 #ifdef POWER_PICKUP_ENABLE
192         SettingHelper::CopyDataForUpdateScene();
193 #endif
194         SettingHelper::UpdateCurrentUserId(); // update setting user id before get setting values
195 #ifdef POWER_MANAGER_ENABLE_CHARGING_TYPE_SETTING
196         power->PowerConnectStatusInit();
197         power->UpdateSettingInvalidDisplayOffTime(); // update setting value if invalid before register
198 #endif
199         powerStateMachine->RegisterDisplayOffTimeObserver();
200         powerStateMachine->InitState();
201         SettingHelper::RegisterAodSwitchObserver();
202 #ifdef POWER_MANAGER_POWER_DIALOG
203         power->GetShutdownDialog().LoadDialogConfig();
204         power->GetShutdownDialog().KeyMonitorInit();
205 #endif
206         power->SwitchSubscriberInit();
207         power->InputMonitorInit();
208         power->SuspendControllerInit();
209         power->WakeupControllerInit();
210         power->SubscribeCommonEvent();
211 #ifdef POWER_MANAGER_WAKEUP_ACTION
212         power->WakeupActionControllerInit();
213 #endif
214         PowerExternalAbilityInit();
215         power->KeepScreenOnInit();
216         isBootCompleted_ = true;
217     };
218     SysParam::RegisterBootCompletedCallbackForPowerSa(g_bootCompletedCallback);
219 }
220 
PowerExternalAbilityInit()221 void PowerMgrService::PowerExternalAbilityInit()
222 {
223     auto power = DelayedSpSingleton<PowerMgrService>::GetInstance();
224     if (power == nullptr) {
225         POWER_HILOGI(COMP_SVC, "get PowerMgrService fail");
226         return;
227     }
228 #ifdef POWER_MANAGER_ENABLE_EXTERNAL_SCREEN_MANAGEMENT
229     // External screen listener must be registered after SuspendControllerInit and WakeupControllerInit
230     power->UnRegisterExternalScreenListener();
231     power->RegisterExternalScreenListener();
232     power->ExternalScreenInit();
233 #endif
234     power->VibratorInit();
235 #ifdef POWER_DOUBLECLICK_ENABLE
236     power->RegisterSettingWakeupDoubleClickObservers();
237 #endif
238 #ifdef POWER_PICKUP_ENABLE
239     power->RegisterSettingWakeupPickupGestureObserver();
240 #endif
241 #ifndef CONFIG_FACTORY_MODE
242     power->RegisterSettingWakeUpLidObserver();
243     POWER_HILOGI(COMP_SVC, "Allow subscribe Hall sensor");
244 #else
245     POWER_HILOGI(COMP_SVC, "Not allow subscribe Hall sensor");
246 #endif
247     power->RegisterSettingPowerModeObservers();
248     power->RegisterSettingDuringCallObservers();
249     power->RegisterExternalCallback();
250 }
251 
RegisterSettingPowerModeObservers()252 void PowerMgrService::RegisterSettingPowerModeObservers()
253 {
254     SettingObserver::UpdateFunc updateFunc = [&](const std::string &key) { PowerModeSettingUpdateFunc(key); };
255     SettingHelper::RegisterSettingPowerModeObserver(updateFunc);
256 }
257 
PowerModeSettingUpdateFunc(const std::string & key)258 void PowerMgrService::PowerModeSettingUpdateFunc(const std::string &key)
259 {
260     auto power = DelayedSpSingleton<PowerMgrService>::GetInstance();
261     int32_t currMode = static_cast<int32_t>(power->GetDeviceMode());
262     int32_t saveMode = SettingHelper::ReadCurrentMode(currMode);
263     if (currMode == saveMode) {
264         return;
265     }
266     POWER_HILOGI(COMP_SVC, "PowerModeSettingUpdateFunc curr:%{public}d, saveMode:%{public}d", currMode, saveMode);
267     power->SetDeviceMode(static_cast<PowerMode>(saveMode));
268 }
269 
RegisterSettingDuringCallObservers()270 void PowerMgrService::RegisterSettingDuringCallObservers()
271 {
272     auto pms = DelayedSpSingleton<PowerMgrService>::GetInstance();
273     if (!pms->IsDuringCallStateEnable()) {
274         return;
275     }
276     POWER_HILOGI(COMP_SVC, "will RegisterSettingDuringCallObservers");
277     SettingObserver::UpdateFunc updateFunc = [&](const std::string &key) { DuringCallSettingUpdateFunc(key); };
278     SettingHelper::RegisterSettingDuringCallObserver(updateFunc);
279 }
280 
DuringCallSettingUpdateFunc(const std::string & key)281 void PowerMgrService::DuringCallSettingUpdateFunc(const std::string &key)
282 {
283     auto power = DelayedSpSingleton<PowerMgrService>::GetInstance();
284     bool duringCallState = SettingHelper::GetSettingDuringCallState(key);
285     POWER_HILOGI(COMP_SVC, "DuringCallState is %{public}d", duringCallState);
286     auto stateMachine = power->GetPowerStateMachine();
287     if (stateMachine == nullptr) {
288         POWER_HILOGE(FEATURE_RUNNING_LOCK, "PowerStateMachine is nullptr");
289         return;
290     }
291     stateMachine->SetDuringCallState(duringCallState);
292 }
293 
IsDeveloperMode()294 bool PowerMgrService::IsDeveloperMode()
295 {
296     return OHOS::system::GetBoolParameter("const.security.developermode.state", true);
297 }
298 
KeepScreenOnInit()299 void PowerMgrService::KeepScreenOnInit()
300 {
301     if (ptoken_ != nullptr) {
302         POWER_HILOGI(COMP_SVC, "runninglock token is not null");
303         return;
304     }
305     ptoken_ = new (std::nothrow) RunningLockTokenStub();
306     if (ptoken_ == nullptr) {
307         POWER_HILOGI(COMP_SVC, "create runninglock token failed");
308         return;
309     }
310     RunningLockInfo info = {"PowerMgrKeepOnLock", OHOS::PowerMgr::RunningLockType::RUNNINGLOCK_SCREEN};
311     PowerErrors ret = pms->CreateRunningLock(ptoken_, info);
312     if (ret != PowerErrors::ERR_OK) {
313         POWER_HILOGI(COMP_SVC, "create runninglock failed");
314     }
315     return;
316 }
317 
KeepScreenOn(bool isOpenOn)318 void PowerMgrService::KeepScreenOn(bool isOpenOn)
319 {
320     if (!IsDeveloperMode()) {
321         POWER_HILOGI(COMP_SVC, "not developer mode");
322         return;
323     }
324     if (ptoken_ == nullptr) {
325         POWER_HILOGI(COMP_SVC, "runninglock token is null");
326         return;
327     }
328     if (isOpenOn) {
329         POWER_HILOGI(COMP_SVC, "try lock RUNNINGLOCK_SCREEN");
330         pms->Lock(ptoken_);
331     } else {
332         POWER_HILOGI(COMP_SVC, "try unlock RUNNINGLOCK_SCREEN");
333         pms->UnLock(ptoken_);
334     }
335     return;
336 }
337 
338 #ifdef POWER_DOUBLECLICK_ENABLE
RegisterSettingWakeupDoubleClickObservers()339 void PowerMgrService::RegisterSettingWakeupDoubleClickObservers()
340 {
341     SettingObserver::UpdateFunc updateFunc = [&](const std::string& key) {WakeupDoubleClickSettingUpdateFunc(key); };
342     SettingHelper::RegisterSettingWakeupDoubleObserver(updateFunc);
343 }
344 
WakeupDoubleClickSettingUpdateFunc(const std::string & key)345 void PowerMgrService::WakeupDoubleClickSettingUpdateFunc(const std::string& key)
346 {
347     bool isSettingEnable = GetSettingWakeupDoubleClick(key);
348     WakeupController::ChangeWakeupSourceConfig(isSettingEnable);
349     WakeupController::SetWakeupDoubleClickSensor(isSettingEnable);
350     POWER_HILOGI(COMP_SVC, "WakeupDoubleClickSettingUpdateFunc isSettingEnable=%{public}d", isSettingEnable);
351 }
352 
GetSettingWakeupDoubleClick(const std::string & key)353 bool PowerMgrService::GetSettingWakeupDoubleClick(const std::string& key)
354 {
355     return SettingHelper::GetSettingWakeupDouble(key);
356 }
357 #endif
358 #ifdef POWER_PICKUP_ENABLE
RegisterSettingWakeupPickupGestureObserver()359 void PowerMgrService::RegisterSettingWakeupPickupGestureObserver()
360 {
361     SettingObserver::UpdateFunc updateFunc = [&](const std::string& key) {WakeupPickupGestureSettingUpdateFunc(key);};
362     SettingHelper::RegisterSettingWakeupPickupObserver(updateFunc);
363 }
364 
WakeupPickupGestureSettingUpdateFunc(const std::string & key)365 void PowerMgrService::WakeupPickupGestureSettingUpdateFunc(const std::string& key)
366 {
367     bool isSettingEnable = SettingHelper::GetSettingWakeupPickup(key);
368     g_isPickUpOpen = isSettingEnable;
369     WakeupController::PickupConnectMotionConfig(isSettingEnable);
370     POWER_HILOGI(COMP_SVC, "PickupConnectMotionConfig done, isSettingEnable=%{public}d", isSettingEnable);
371     WakeupController::ChangePickupWakeupSourceConfig(isSettingEnable);
372     POWER_HILOGI(COMP_SVC, "ChangePickupWakeupSourceConfig done");
373 }
374 #endif
375 
PowerStateMachineInit()376 bool PowerMgrService::PowerStateMachineInit()
377 {
378     if (powerStateMachine_ == nullptr) {
379         powerStateMachine_ = std::make_shared<PowerStateMachine>(pms, ffrtTimer_);
380         if (!(powerStateMachine_->Init())) {
381             POWER_HILOGE(COMP_SVC, "Power state machine start fail!");
382             return false;
383         }
384     }
385     if (powerMgrNotify_ == nullptr) {
386         powerMgrNotify_ = std::make_shared<PowerMgrNotify>();
387         powerMgrNotify_->RegisterPublishEvents();
388     }
389     return true;
390 }
391 
KeyMonitorCancel()392 void PowerMgrService::KeyMonitorCancel()
393 {
394 #ifdef HAS_MULTIMODALINPUT_INPUT_PART
395     POWER_HILOGI(FEATURE_INPUT, "Unsubscribe key information");
396     InputManager* inputManager = InputManager::GetInstance();
397     if (inputManager == nullptr) {
398         POWER_HILOGI(FEATURE_INPUT, "InputManager is null");
399         return;
400     }
401     shutdownDialog_.KeyMonitorCancel();
402     if (doubleClickId_ >= 0) {
403         inputManager->UnsubscribeKeyEvent(doubleClickId_);
404     }
405     if (monitorId_ >= 0) {
406         inputManager->RemoveMonitor(monitorId_);
407     }
408 #endif
409 }
410 
WakeupLidSettingUpdateFunc(const std::string & key)411 void PowerMgrService::WakeupLidSettingUpdateFunc(const std::string& key)
412 {
413     POWER_HILOGI(COMP_SVC, "Receive lid wakeup setting update.");
414     bool enable = SettingHelper::GetSettingWakeupLid(key);
415     if (enable) {
416         pms->HallSensorSubscriberInit();
417     } else {
418         pms->HallSensorSubscriberCancel();
419     }
420     std::shared_ptr<WakeupController> wakeupController = pms->GetWakeupController();
421     if (wakeupController == nullptr) {
422         POWER_HILOGE(FEATURE_INPUT, "wakeupController is not init");
423         return;
424     }
425     wakeupController->ChangeLidWakeupSourceConfig(enable);
426     POWER_HILOGI(COMP_SVC, "ChangeLidWakeupSourceConfig done");
427 }
428 
RegisterSettingWakeUpLidObserver()429 void PowerMgrService::RegisterSettingWakeUpLidObserver()
430 {
431     pms->HallSensorSubscriberInit();
432     POWER_HILOGI(COMP_SVC, "Start to registerSettingWakeUpLidObserver");
433     if (!SettingHelper::IsWakeupLidSettingValid()) {
434         POWER_HILOGE(COMP_UTILS, "settings.power.wakeup_lid is valid.");
435         return;
436     }
437     SettingObserver::UpdateFunc updateFunc = [&](const std::string& key) {WakeupLidSettingUpdateFunc(key);};
438     SettingHelper::RegisterSettingWakeupLidObserver(updateFunc);
439 }
440 
HallSensorSubscriberInit()441 void PowerMgrService::HallSensorSubscriberInit()
442 {
443 #ifdef HAS_SENSORS_SENSOR_PART
444     POWER_HILOGI(COMP_SVC, "Start to subscribe hall sensor");
445     if (!IsSupportSensor(SENSOR_TYPE_ID_HALL)) {
446         POWER_HILOGW(FEATURE_INPUT, "SENSOR_TYPE_ID_HALL sensor not support");
447         return;
448     }
449     if (strcpy_s(sensorUser_.name, sizeof(sensorUser_.name), "PowerManager") != EOK) {
450         POWER_HILOGW(FEATURE_INPUT, "strcpy_s error");
451         return;
452     }
453     isInLidMode_ = false;
454     sensorUser_.userData = nullptr;
455     sensorUser_.callback = &HallSensorCallback;
456     SubscribeSensor(SENSOR_TYPE_ID_HALL, &sensorUser_);
457     SetBatch(SENSOR_TYPE_ID_HALL, &sensorUser_, HALL_SAMPLING_RATE, HALL_REPORT_INTERVAL);
458     ActivateSensor(SENSOR_TYPE_ID_HALL, &sensorUser_);
459 #endif
460 }
461 
462 #ifdef HAS_SENSORS_SENSOR_PART
IsSupportSensor(SensorTypeId typeId)463 bool PowerMgrService::IsSupportSensor(SensorTypeId typeId)
464 {
465     bool isSupport = false;
466     SensorInfo* sensorInfo = nullptr;
467     int32_t count;
468     int32_t ret = GetAllSensors(&sensorInfo, &count);
469     if (ret != 0 || sensorInfo == nullptr) {
470         POWER_HILOGW(FEATURE_INPUT, "Get sensors fail, ret=%{public}d", ret);
471         return isSupport;
472     }
473     for (int32_t i = 0; i < count; i++) {
474         if (sensorInfo[i].sensorTypeId == typeId) {
475             isSupport = true;
476             break;
477         }
478     }
479     return isSupport;
480 }
481 
HallSensorCallback(SensorEvent * event)482 void PowerMgrService::HallSensorCallback(SensorEvent* event)
483 {
484     if (event == nullptr || event->sensorTypeId != SENSOR_TYPE_ID_HALL || event->data == nullptr) {
485         POWER_HILOGW(FEATURE_INPUT, "Hall sensor event is invalid");
486         return;
487     }
488 
489     std::shared_ptr<SuspendController> suspendController = pms->GetSuspendController();
490     if (suspendController == nullptr) {
491         POWER_HILOGE(FEATURE_INPUT, "get suspendController instance error");
492         return;
493     }
494 
495     std::shared_ptr<WakeupController> wakeupController = pms->GetWakeupController();
496     if (wakeupController == nullptr) {
497         POWER_HILOGE(FEATURE_INPUT, "wakeupController is not init");
498         return;
499     }
500     const uint32_t LID_CLOSED_HALL_FLAG = 0x1;
501     auto data = reinterpret_cast<HallData*>(event->data);
502     auto status = static_cast<uint32_t>(data->status);
503 
504     if (status & LID_CLOSED_HALL_FLAG) {
505         if (isInLidMode_) {
506             POWER_HILOGI(FEATURE_SUSPEND, "[UL_POWER] Lid close event received again");
507             return;
508         }
509         POWER_HILOGI(FEATURE_SUSPEND, "[UL_POWER] Lid close event received, begin to suspend");
510         isInLidMode_ = true;
511         SuspendDeviceType reason = SuspendDeviceType::SUSPEND_DEVICE_REASON_LID;
512         suspendController->ExecSuspendMonitorByReason(reason);
513     } else {
514         if (!isInLidMode_) {
515             POWER_HILOGI(FEATURE_WAKEUP, "[UL_POWER] Lid open event received again");
516             return;
517         }
518         POWER_HILOGI(FEATURE_WAKEUP, "[UL_POWER] Lid open event received, begin to wakeup");
519         isInLidMode_ = false;
520         WakeupDeviceType reason = WakeupDeviceType::WAKEUP_DEVICE_LID;
521         wakeupController->ExecWakeupMonitorByReason(reason);
522     }
523 }
524 #endif
525 
HallSensorSubscriberCancel()526 void PowerMgrService::HallSensorSubscriberCancel()
527 {
528 #ifdef HAS_SENSORS_SENSOR_PART
529     POWER_HILOGI(COMP_SVC, "Start to cancel the subscribe of hall sensor");
530     if (IsSupportSensor(SENSOR_TYPE_ID_HALL)) {
531         DeactivateSensor(SENSOR_TYPE_ID_HALL, &sensorUser_);
532         UnsubscribeSensor(SENSOR_TYPE_ID_HALL, &sensorUser_);
533     }
534     isInLidMode_ = false;
535 #endif
536 }
537 
CheckDialogFlag()538 bool PowerMgrService::CheckDialogFlag()
539 {
540     bool isLongPress = shutdownDialog_.IsLongPress();
541     if (isLongPress) {
542         shutdownDialog_.ResetLongPressFlag();
543     }
544     return true;
545 }
546 
CheckDialogAndShuttingDown()547 bool PowerMgrService::CheckDialogAndShuttingDown()
548 {
549     bool isShuttingDown = shutdownController_->IsShuttingDown();
550     bool isLongPress = shutdownDialog_.IsLongPress();
551     if (isLongPress || isShuttingDown) {
552         POWER_HILOGW(
553             FEATURE_INPUT, "isLongPress: %{public}d, isShuttingDown: %{public}d", isLongPress, isShuttingDown);
554         shutdownDialog_.ResetLongPressFlag();
555         return true;
556     }
557     return false;
558 }
559 
SwitchSubscriberInit()560 void PowerMgrService::SwitchSubscriberInit()
561 {
562 #ifdef HAS_MULTIMODALINPUT_INPUT_PART
563     POWER_HILOGW(FEATURE_INPUT, "Initialize the subscription switch");
564     auto inputManager = InputManager::GetInstance();
565     if (!inputManager) {
566         POWER_HILOGE(FEATURE_INPUT, "SwitchSubscriberInit inputManager is null");
567         return;
568     }
569     switchId_ =
570         inputManager->SubscribeSwitchEvent([this](std::shared_ptr<OHOS::MMI::SwitchEvent> switchEvent) {
571             POWER_HILOGI(FEATURE_WAKEUP, "switch event received");
572             if (switchEvent->GetSwitchValue() == SwitchEvent::SWITCH_OFF) {
573                 POWER_HILOGI(FEATURE_SUSPEND, "[UL_POWER] Switch close event received, begin to suspend");
574                 std::shared_ptr<SuspendController> suspendController = pms->GetSuspendController();
575                 if (suspendController == nullptr) {
576                     POWER_HILOGE(FEATURE_INPUT, "get suspendController instance error");
577                     return;
578                 }
579                 powerStateMachine_->SetSwitchState(false);
580                 SuspendDeviceType reason = SuspendDeviceType::SUSPEND_DEVICE_REASON_SWITCH;
581                 suspendController->ExecSuspendMonitorByReason(reason);
582             } else {
583                 POWER_HILOGI(FEATURE_WAKEUP, "[UL_POWER] Switch open event received, begin to wakeup");
584                 std::shared_ptr<WakeupController> wakeupController = pms->GetWakeupController();
585                 if (wakeupController == nullptr) {
586                     POWER_HILOGE(FEATURE_INPUT, "get wakeupController instance error");
587                     return;
588                 }
589                 powerStateMachine_->SetSwitchState(true);
590                 WakeupDeviceType reason = WakeupDeviceType::WAKEUP_DEVICE_SWITCH;
591                 wakeupController->ExecWakeupMonitorByReason(reason);
592             }
593         });
594 #endif
595 }
596 
SwitchSubscriberCancel()597 void PowerMgrService::SwitchSubscriberCancel()
598 {
599 #ifdef HAS_MULTIMODALINPUT_INPUT_PART
600     POWER_HILOGI(FEATURE_INPUT, "Unsubscribe switch information");
601     auto inputManager = InputManager::GetInstance();
602     if (!inputManager) {
603         POWER_HILOGE(FEATURE_INPUT, "SwitchSubscriberCancel inputManager is null");
604         return;
605     }
606     if (switchId_ >= 0) {
607         inputManager->UnsubscribeSwitchEvent(switchId_);
608         switchId_ = -1;
609     }
610 #endif
611 }
612 
InputMonitorInit()613 void PowerMgrService::InputMonitorInit()
614 {
615 #ifdef HAS_MULTIMODALINPUT_INPUT_PART
616     POWER_HILOGI(FEATURE_INPUT, "PowerMgr service input monitor init");
617     std::shared_ptr<PowerMgrInputMonitor> inputMonitor = std::make_shared<PowerMgrInputMonitor>();
618     auto inputManager = InputManager::GetInstance();
619     if (!inputManager) {
620         POWER_HILOGE(FEATURE_INPUT, "InputMonitorInit inputManager is null");
621         return;
622     }
623     if (inputMonitorId_ < 0) {
624         inputMonitorId_ =
625             inputManager->AddMonitor(std::static_pointer_cast<IInputEventConsumer>(inputMonitor));
626     }
627 #endif
628 }
629 
InputMonitorCancel()630 void PowerMgrService::InputMonitorCancel()
631 {
632 #ifdef HAS_MULTIMODALINPUT_INPUT_PART
633     POWER_HILOGI(FEATURE_INPUT, "PowerMgr service input monitor cancel");
634     InputManager* inputManager = InputManager::GetInstance();
635     if (!inputManager) {
636         POWER_HILOGE(FEATURE_INPUT, "InputMonitorCancel inputManager is null");
637         return;
638     }
639     if (inputMonitorId_ >= 0) {
640         inputManager->RemoveMonitor(inputMonitorId_);
641         inputMonitorId_ = -1;
642     }
643 #endif
644 }
645 
HandleKeyEvent(int32_t keyCode)646 void PowerMgrService::HandleKeyEvent(int32_t keyCode)
647 {
648 #ifdef HAS_MULTIMODALINPUT_INPUT_PART
649     POWER_HILOGD(FEATURE_INPUT, "keyCode: %{public}d", keyCode);
650     int64_t now = static_cast<int64_t>(time(nullptr));
651     if (IsScreenOn()) {
652         this->RefreshActivityInner(now, UserActivityType::USER_ACTIVITY_TYPE_BUTTON, false);
653     } else {
654         if (keyCode == KeyEvent::KEYCODE_F1) {
655             POWER_HILOGI(FEATURE_WAKEUP, "[UL_POWER] Wakeup by double click");
656             std::string reason = "double click";
657             reason.append(std::to_string(keyCode));
658             this->WakeupDevice(now, WakeupDeviceType::WAKEUP_DEVICE_DOUBLE_CLICK, reason);
659         } else if (keyCode >= KeyEvent::KEYCODE_0 && keyCode <= KeyEvent::KEYCODE_NUMPAD_RIGHT_PAREN) {
660             POWER_HILOGI(FEATURE_WAKEUP, "[UL_POWER] Wakeup by keyboard");
661             std::string reason = "keyboard:";
662             reason.append(std::to_string(keyCode));
663             this->WakeupDevice(now, WakeupDeviceType::WAKEUP_DEVICE_KEYBOARD, reason);
664         }
665     }
666 #endif
667 }
668 
HandlePointEvent(int32_t type)669 void PowerMgrService::HandlePointEvent(int32_t type)
670 {
671 #ifdef HAS_MULTIMODALINPUT_INPUT_PART
672     POWER_HILOGD(FEATURE_INPUT, "type: %{public}d", type);
673     int64_t now = static_cast<int64_t>(time(nullptr));
674     if (this->IsScreenOn()) {
675         this->RefreshActivityInner(now, UserActivityType::USER_ACTIVITY_TYPE_ATTENTION, false);
676     } else {
677         if (type == PointerEvent::SOURCE_TYPE_MOUSE) {
678             std::string reason = "mouse click";
679             POWER_HILOGI(FEATURE_WAKEUP, "[UL_POWER] Wakeup by mouse");
680             this->WakeupDevice(now, WakeupDeviceType::WAKEUP_DEVICE_MOUSE, reason);
681         }
682     }
683 #endif
684 }
685 
OnStop()686 void PowerMgrService::OnStop()
687 {
688     POWER_HILOGW(COMP_SVC, "Stop service");
689     if (!ready_) {
690         return;
691     }
692     powerStateMachine_->CancelDelayTimer(PowerStateMachine::CHECK_USER_ACTIVITY_TIMEOUT_MSG);
693     powerStateMachine_->CancelDelayTimer(PowerStateMachine::CHECK_USER_ACTIVITY_OFF_TIMEOUT_MSG);
694     powerStateMachine_->UnregisterDisplayOffTimeObserver();
695     if (suspendController_) {
696         suspendController_->StopSleep();
697     }
698 
699     SystemSuspendController::GetInstance().UnRegisterPowerHdiCallback();
700     KeyMonitorCancel();
701     HallSensorSubscriberCancel();
702 #ifdef POWER_MANAGER_ENABLE_EXTERNAL_SCREEN_MANAGEMENT
703     UnRegisterExternalScreenListener();
704 #endif
705     SwitchSubscriberCancel();
706     InputMonitorCancel();
707     ready_ = false;
708     isBootCompleted_ = false;
709     RemoveSystemAbilityListener(SUSPEND_MANAGER_SYSTEM_ABILITY_ID);
710     RemoveSystemAbilityListener(DEVICE_STANDBY_SERVICE_SYSTEM_ABILITY_ID);
711     RemoveSystemAbilityListener(DISPLAY_MANAGER_SERVICE_ID);
712 #ifdef MSDP_MOVEMENT_ENABLE
713     RemoveSystemAbilityListener(MSDP_MOVEMENT_SERVICE_ID);
714 #endif
715 #ifdef POWER_PICKUP_ENABLE
716     RemoveSystemAbilityListener(MSDP_MOTION_SERVICE_ID);
717 #endif
718 #ifdef POWER_DOUBLECLICK_ENABLE
719     SettingHelper::UnregisterSettingWakeupDoubleObserver();
720 #endif
721 #ifdef POWER_PICKUP_ENABLE
722     SettingHelper::UnregisterSettingWakeupPickupObserver();
723 #endif
724     SettingHelper::UnRegisterSettingWakeupLidObserver();
725     SettingHelper::UnRegisterSettingPowerModeObserver();
726     if (!OHOS::EventFwk::CommonEventManager::UnSubscribeCommonEvent(subscriberPtr_)) {
727         POWER_HILOGE(COMP_SVC, "Power Onstop unregister to commonevent manager failed!");
728     }
729 #ifdef MSDP_MOVEMENT_ENABLE
730     UnRegisterMovementCallback();
731 #endif
732     UnregisterExternalCallback();
733 #ifndef FUZZ_TEST
734     PowerExtIntfWrapper::Instance().DeInit();
735     ModuleMgrDestroy(g_moduleMgr);
736     g_moduleMgr = nullptr;
737 #endif
738 }
739 
Reset()740 void PowerMgrService::Reset()
741 {
742     POWER_HILOGW(COMP_SVC, "start destruct ffrt_queue");
743     if (powerStateMachine_) {
744         // release one strong reference to ffrtTimer
745         powerStateMachine_->Reset();
746     }
747     if (suspendController_) {
748         // release one strong reference to ffrtTimer
749         suspendController_->Reset();
750     }
751     ffrtTimer_.reset(); // all strong references gone, ffrtTimer will be destructed.
752     if (screenOffPreController_) {
753         // another queue without using FFRTTimer, leave it as is for now.
754         screenOffPreController_->Reset();
755     }
756 }
757 
OnRemoveSystemAbility(int32_t systemAbilityId,const std::string & deviceId)758 void PowerMgrService::OnRemoveSystemAbility(int32_t systemAbilityId, const std::string& deviceId)
759 {
760     POWER_HILOGI(COMP_SVC, "systemAbilityId=%{public}d, deviceId=%{private}s", systemAbilityId, deviceId.c_str());
761     if (systemAbilityId == SUSPEND_MANAGER_SYSTEM_ABILITY_ID ||
762         systemAbilityId == DEVICE_STANDBY_SERVICE_SYSTEM_ABILITY_ID) {
763         std::lock_guard lock(lockMutex_);
764         runningLockMgr_->ResetRunningLocks();
765     }
766 #ifdef MSDP_MOVEMENT_ENABLE
767     if (systemAbilityId == MSDP_MOVEMENT_SERVICE_ID) {
768         auto power = DelayedSpSingleton<PowerMgrService>::GetInstance();
769         if (power == nullptr) {
770             POWER_HILOGI(COMP_SVC, "get PowerMgrService fail");
771             return;
772         }
773         power->ResetMovementState();
774     }
775 #endif
776     if (systemAbilityId ==  DISPLAY_MANAGER_SERVICE_SA_ID) {
777         std::lock_guard lock(powerInitMutex_);
778         POWER_HILOGI(COMP_SVC, "get DISPLAY_MANAGER_SERVICE_SA_ID crash in PowerService.");
779         displayManagerServiceCrash_ = true;
780     }
781 }
782 
OnAddSystemAbility(int32_t systemAbilityId,const std::string & deviceId)783 void PowerMgrService::OnAddSystemAbility(int32_t systemAbilityId, const std::string& deviceId)
784 {
785     POWER_HILOGI(COMP_SVC, "systemAbilityId=%{public}d, deviceId=%{private}s Add",
786         systemAbilityId, deviceId.c_str());
787     if (systemAbilityId == DISTRIBUTED_KV_DATA_SERVICE_ABILITY_ID) {
788         if (DelayedSpSingleton<PowerSaveMode>::GetInstance()) {
789             this->GetPowerModeModule().InitPowerMode();
790         }
791     }
792     if (systemAbilityId == DISPLAY_MANAGER_SERVICE_ID) {
793         std::lock_guard lock(powerInitMutex_);
794         POWER_HILOGI(COMP_SVC, "get DISPLAY_MANAGER_SERVICE_ID in PowerService");
795         isNeedReInit_  = true;
796         RegisterBootCompletedCallback();
797     }
798 
799     if (systemAbilityId ==  DISPLAY_MANAGER_SERVICE_SA_ID) {
800         std::lock_guard lock(powerInitMutex_);
801         POWER_HILOGI(COMP_SVC, "get DISPLAY_MANAGER_SERVICE_SA_ID in PowerService");
802         if (displayManagerServiceCrash_) {
803             isNeedReInit_  = true;
804             RegisterBootCompletedCallback();
805             displayManagerServiceCrash_ = false;
806         }
807     }
808 #ifdef MSDP_MOVEMENT_ENABLE
809     if (systemAbilityId == MSDP_MOVEMENT_SERVICE_ID) {
810         auto power = DelayedSpSingleton<PowerMgrService>::GetInstance();
811         if (power == nullptr) {
812             POWER_HILOGI(COMP_SVC, "get PowerMgrService fail");
813             return;
814         }
815         power->UnRegisterMovementCallback();
816         power->RegisterMovementCallback();
817     }
818 #endif
819 #ifdef POWER_PICKUP_ENABLE
820     if (systemAbilityId == MSDP_MOTION_SERVICE_ID && g_isPickUpOpen == true) {
821         WakeupController::PickupConnectMotionConfig(false);
822         WakeupController::PickupConnectMotionConfig(true);
823     }
824 #endif
825 }
826 
827 #ifdef MSDP_MOVEMENT_ENABLE
828 static const char* MOVEMENT_SUBSCRIBER_CONFIG = "RegisterMovementCallback";
829 static const char* MOVEMENT_UNSUBSCRIBER_CONFIG = "UnRegisterMovementCallback";
830 static const char* RESET_MOVEMENT_STATE_CONFIG = "ResetMovementState";
831 typedef void(*FuncMovementSubscriber)();
832 typedef void(*FuncMovementUnsubscriber)();
833 typedef void(*FuncResetMovementState)();
834 
RegisterMovementCallback()835 void PowerMgrService::RegisterMovementCallback()
836 {
837     POWER_HILOGI(COMP_SVC, "Start to RegisterMovementCallback");
838     void *subscriberHandler = dlopen(POWER_MANAGER_EXT_PATH, RTLD_LAZY | RTLD_NODELETE);
839     if (subscriberHandler == nullptr) {
840         POWER_HILOGE(COMP_SVC, "Dlopen RegisterMovementCallback failed, reason : %{public}s", dlerror());
841         return;
842     }
843 
844     FuncMovementSubscriber MovementSubscriber =
845         reinterpret_cast<FuncMovementSubscriber>(dlsym(subscriberHandler, MOVEMENT_SUBSCRIBER_CONFIG));
846     if (MovementSubscriber == nullptr) {
847         POWER_HILOGE(COMP_SVC, "RegisterMovementCallback is null, reason : %{public}s", dlerror());
848         dlclose(subscriberHandler);
849         subscriberHandler = nullptr;
850         return;
851     }
852     MovementSubscriber();
853     POWER_HILOGI(COMP_SVC, "RegisterMovementCallback Success");
854     dlclose(subscriberHandler);
855     subscriberHandler = nullptr;
856     return;
857 }
858 
UnRegisterMovementCallback()859 void PowerMgrService::UnRegisterMovementCallback()
860 {
861     POWER_HILOGI(COMP_SVC, "Start to UnRegisterMovementCallback");
862     void *unSubscriberHandler = dlopen(POWER_MANAGER_EXT_PATH, RTLD_LAZY | RTLD_NODELETE);
863     if (unSubscriberHandler == nullptr) {
864         POWER_HILOGE(COMP_SVC, "Dlopen UnRegisterMovementCallback failed, reason : %{public}s", dlerror());
865         return;
866     }
867 
868     FuncMovementUnsubscriber MovementUnsubscriber =
869         reinterpret_cast<FuncMovementUnsubscriber>(dlsym(unSubscriberHandler, MOVEMENT_UNSUBSCRIBER_CONFIG));
870     if (MovementUnsubscriber == nullptr) {
871         POWER_HILOGE(COMP_SVC, "UnRegisterMovementCallback is null, reason : %{public}s", dlerror());
872         dlclose(unSubscriberHandler);
873         unSubscriberHandler = nullptr;
874         return;
875     }
876     MovementUnsubscriber();
877     POWER_HILOGI(COMP_SVC, "UnRegisterMovementCallback Success");
878     dlclose(unSubscriberHandler);
879     unSubscriberHandler = nullptr;
880     return;
881 }
882 
ResetMovementState()883 void PowerMgrService::ResetMovementState()
884 {
885     POWER_HILOGI(COMP_SVC, "Start to ResetMovementState");
886     void *resetMovementStateHandler = dlopen(POWER_MANAGER_EXT_PATH, RTLD_LAZY | RTLD_NODELETE);
887     if (resetMovementStateHandler == nullptr) {
888         POWER_HILOGE(COMP_SVC, "Dlopen ResetMovementState failed, reason : %{public}s", dlerror());
889         return;
890     }
891 
892     FuncResetMovementState ResetMovementState =
893         reinterpret_cast<FuncResetMovementState>(dlsym(resetMovementStateHandler, RESET_MOVEMENT_STATE_CONFIG));
894     if (ResetMovementState == nullptr) {
895         POWER_HILOGE(COMP_SVC, "ResetMovementState is null, reason : %{public}s", dlerror());
896         dlclose(resetMovementStateHandler);
897         resetMovementStateHandler = nullptr;
898         return;
899     }
900     ResetMovementState();
901     POWER_HILOGI(COMP_SVC, "ResetMovementState Success");
902     dlclose(resetMovementStateHandler);
903     resetMovementStateHandler = nullptr;
904     return;
905 }
906 #endif
907 
908 static const char* REGISTER_EXTERNAL_CONFIG = "RegisterExternalCallback";
909 static const char* UNREGISTER_EXTERNAL_CONFIG = "UnregisterExternalCallback";
910 using WakeupFunc = std::function<void(WakeupDeviceType)>;
911 using SuspendFunc = std::function<void(SuspendDeviceType)>;
912 using PowerConfigFunc = std::function<int32_t(std::string&, std::string&)>;
913 typedef void (*FuncRegisterExternalCallback)(WakeupFunc, SuspendFunc, PowerConfigFunc, PowerConfigFunc);
914 typedef void (*FuncUnregisterExternalCallback)();
915 
RegisterExternalCallback()916 void PowerMgrService::RegisterExternalCallback()
917 {
918     POWER_HILOGI(COMP_SVC, "Start to RegisterExternalCallback");
919     void* subscriberHandler = dlopen(POWER_MANAGER_EXT_PATH, RTLD_LAZY | RTLD_NODELETE);
920     if (subscriberHandler == nullptr) {
921         POWER_HILOGE(COMP_SVC, "Dlopen RegisterExternalCallback failed, reason : %{public}s", dlerror());
922         return;
923     }
924 
925     FuncRegisterExternalCallback registerExternalCallback =
926         reinterpret_cast<FuncRegisterExternalCallback>(dlsym(subscriberHandler, REGISTER_EXTERNAL_CONFIG));
927     if (registerExternalCallback == nullptr) {
928         POWER_HILOGE(COMP_SVC, "RegisterExternalCallback is null, reason : %{public}s", dlerror());
929         dlclose(subscriberHandler);
930         subscriberHandler = nullptr;
931         return;
932     }
933     registerExternalCallback(
934         [this](WakeupDeviceType reason) {
935             POWER_HILOGI(COMP_SVC, "[UL_POWER] wakeup callback triggered, reason: %{public}d", reason);
936             wakeupController_->ExecWakeupMonitorByReason(reason);
937         },
938         [this](SuspendDeviceType reason) {
939             POWER_HILOGI(COMP_SVC, "[UL_POWER] suspend callback triggered, reason: %{public}d", reason);
940             suspendController_->ExecSuspendMonitorByReason(reason);
941         },
942         [](std::string& sceneName, std::string& value) {
943             return SystemSuspendController::GetInstance().GetPowerConfig(sceneName, value);
944         },
945         [](std::string& sceneName, std::string value) {
946             return SystemSuspendController::GetInstance().SetPowerConfig(sceneName, value);
947         });
948     POWER_HILOGI(COMP_SVC, "RegisterExternalCallback Success");
949     dlclose(subscriberHandler);
950     subscriberHandler = nullptr;
951 }
952 
UnregisterExternalCallback()953 void PowerMgrService::UnregisterExternalCallback()
954 {
955     POWER_HILOGI(COMP_SVC, "Start to UnregisterExternalCallback");
956     void* unSubscriberHandler = dlopen(POWER_MANAGER_EXT_PATH, RTLD_LAZY | RTLD_NODELETE);
957     if (unSubscriberHandler == nullptr) {
958         POWER_HILOGE(COMP_SVC, "Dlopen UnregisterExternalCallback failed, reason : %{public}s", dlerror());
959         return;
960     }
961 
962     FuncUnregisterExternalCallback unregisterExternalCallback =
963         reinterpret_cast<FuncUnregisterExternalCallback>(dlsym(unSubscriberHandler, UNREGISTER_EXTERNAL_CONFIG));
964     if (unregisterExternalCallback == nullptr) {
965         POWER_HILOGE(COMP_SVC, "UnregisterExternalCallback is null, reason : %{public}s", dlerror());
966         dlclose(unSubscriberHandler);
967         unSubscriberHandler = nullptr;
968         return;
969     }
970     unregisterExternalCallback();
971     POWER_HILOGI(COMP_SVC, "UnregisterExternalCallback Success");
972     dlclose(unSubscriberHandler);
973     unSubscriberHandler = nullptr;
974 }
975 
976 static const char* ON_CHARGE_STATE_CHANGED_CONFIG = "OnChargeStateChanged";
977 typedef void (*FuncOnChargeStateChanged)();
978 
OnChargeStateChanged()979 void PowerMgrService::OnChargeStateChanged()
980 {
981     POWER_HILOGI(COMP_SVC, "Start to OnChargeStateChanged");
982     void* subscriberHandler = dlopen(POWER_MANAGER_EXT_PATH, RTLD_LAZY | RTLD_NODELETE);
983     if (subscriberHandler == nullptr) {
984         POWER_HILOGE(COMP_SVC, "Dlopen OnChargeStateChanged failed, reason : %{public}s", dlerror());
985         return;
986     }
987 
988     FuncOnChargeStateChanged onChargeStateChanged =
989         reinterpret_cast<FuncOnChargeStateChanged>(dlsym(subscriberHandler, ON_CHARGE_STATE_CHANGED_CONFIG));
990     if (onChargeStateChanged == nullptr) {
991         POWER_HILOGE(COMP_SVC, "OnChargeStateChanged is null, reason : %{public}s", dlerror());
992         dlclose(subscriberHandler);
993         subscriberHandler = nullptr;
994         return;
995     }
996     onChargeStateChanged();
997     POWER_HILOGI(COMP_SVC, "OnChargeStateChanged Success");
998     dlclose(subscriberHandler);
999     subscriberHandler = nullptr;
1000 }
1001 
Dump(int32_t fd,const std::vector<std::u16string> & args)1002 int32_t PowerMgrService::Dump(int32_t fd, const std::vector<std::u16string>& args)
1003 {
1004     if (!isBootCompleted_) {
1005         return ERR_NO_INIT;
1006     }
1007     if (!Permission::IsSystem()) {
1008         return ERR_PERMISSION_DENIED;
1009     }
1010     std::vector<std::string> argsInStr;
1011     std::transform(args.begin(), args.end(), std::back_inserter(argsInStr), [](const std::u16string& arg) {
1012         std::string ret = Str16ToStr8(arg);
1013         POWER_HILOGD(COMP_SVC, "arg: %{public}s", ret.c_str());
1014         return ret;
1015     });
1016     std::string result;
1017     PowerMgrDumper::Dump(argsInStr, result);
1018     if (!SaveStringToFd(fd, result)) {
1019         POWER_HILOGE(COMP_SVC, "Dump failed, save to fd failed.");
1020         POWER_HILOGE(COMP_SVC, "Dump Info:\n");
1021         POWER_HILOGE(COMP_SVC, "%{public}s", result.c_str());
1022         return ERR_OK;
1023     }
1024     return ERR_OK;
1025 }
1026 
RebootDevice(const std::string & reason)1027 PowerErrors PowerMgrService::RebootDevice(const std::string& reason)
1028 {
1029     if (!Permission::IsSystem()) {
1030         return PowerErrors::ERR_SYSTEM_API_DENIED;
1031     }
1032     return RebootDeviceForDeprecated(reason);
1033 }
1034 
RebootDeviceForDeprecated(const std::string & reason)1035 PowerErrors PowerMgrService::RebootDeviceForDeprecated(const std::string& reason)
1036 {
1037     std::lock_guard lock(shutdownMutex_);
1038     pid_t pid = IPCSkeleton::GetCallingPid();
1039     auto uid = IPCSkeleton::GetCallingUid();
1040     if (!Permission::IsPermissionGranted("ohos.permission.REBOOT")) {
1041         return PowerErrors::ERR_PERMISSION_DENIED;
1042     }
1043     POWER_HILOGI(FEATURE_SHUTDOWN, "Cancel auto sleep timer");
1044     powerStateMachine_->CancelDelayTimer(PowerStateMachine::CHECK_USER_ACTIVITY_TIMEOUT_MSG);
1045     powerStateMachine_->CancelDelayTimer(PowerStateMachine::CHECK_USER_ACTIVITY_OFF_TIMEOUT_MSG);
1046     if (suspendController_) {
1047         suspendController_->StopSleep();
1048     }
1049     POWER_KHILOGI(FEATURE_SHUTDOWN, "Do reboot, called pid: %{public}d, uid: %{public}d", pid, uid);
1050     shutdownController_->Reboot(reason);
1051     return PowerErrors::ERR_OK;
1052 }
1053 
ShutDownDevice(const std::string & reason)1054 PowerErrors PowerMgrService::ShutDownDevice(const std::string& reason)
1055 {
1056     auto now = static_cast<int64_t>(time(nullptr));
1057     if (!Permission::IsSystem()) {
1058         return PowerErrors::ERR_SYSTEM_API_DENIED;
1059     }
1060     if (!Permission::IsPermissionGranted("ohos.permission.REBOOT")) {
1061         return PowerErrors::ERR_PERMISSION_DENIED;
1062     }
1063     if (reason == SHUTDOWN_FAST_REASON) {
1064         g_wakeupReason = reason;
1065         POWER_HILOGD(FEATURE_SHUTDOWN, "Calling Fast ShutDownDevice success");
1066         return SuspendDevice(now, SuspendDeviceType::SUSPEND_DEVICE_REASON_STR, true);
1067     }
1068     g_wakeupReason = "";
1069     std::lock_guard lock(shutdownMutex_);
1070     pid_t pid = IPCSkeleton::GetCallingPid();
1071     auto uid = IPCSkeleton::GetCallingUid();
1072     POWER_HILOGI(FEATURE_SHUTDOWN, "Cancel auto sleep timer");
1073     powerStateMachine_->CancelDelayTimer(PowerStateMachine::CHECK_USER_ACTIVITY_TIMEOUT_MSG);
1074     powerStateMachine_->CancelDelayTimer(PowerStateMachine::CHECK_USER_ACTIVITY_OFF_TIMEOUT_MSG);
1075     if (suspendController_) {
1076         suspendController_->StopSleep();
1077     }
1078     SystemSuspendController::GetInstance().Wakeup(); // stop suspend loop
1079 
1080     POWER_KHILOGI(FEATURE_SHUTDOWN, "[UL_POWER] Do shutdown, called pid: %{public}d, uid: %{public}d", pid, uid);
1081     shutdownController_->Shutdown(reason);
1082     return PowerErrors::ERR_OK;
1083 }
1084 
SetSuspendTag(const std::string & tag)1085 PowerErrors PowerMgrService::SetSuspendTag(const std::string& tag)
1086 {
1087     std::lock_guard lock(suspendMutex_);
1088     pid_t pid = IPCSkeleton::GetCallingPid();
1089     auto uid = IPCSkeleton::GetCallingUid();
1090     if (!Permission::IsSystem()) {
1091         return PowerErrors::ERR_SYSTEM_API_DENIED;
1092     }
1093     POWER_HILOGI(FEATURE_SUSPEND, "pid: %{public}d, uid: %{public}d, tag: %{public}s", pid, uid, tag.c_str());
1094     SystemSuspendController::GetInstance().SetSuspendTag(tag);
1095     return PowerErrors::ERR_OK;
1096 }
1097 
SuspendDevice(int64_t callTimeMs,SuspendDeviceType reason,bool suspendImmed,const std::string & apiVersion)1098 PowerErrors PowerMgrService::SuspendDevice(
1099     int64_t callTimeMs, SuspendDeviceType reason, bool suspendImmed, const std::string& apiVersion)
1100 {
1101     std::lock_guard lock(suspendMutex_);
1102     pid_t pid = IPCSkeleton::GetCallingPid();
1103     auto uid = IPCSkeleton::GetCallingUid();
1104     if (!Permission::IsSystem()) {
1105         POWER_HILOGI(FEATURE_SUSPEND, "SuspendDevice failed, System permission intercept");
1106         return PowerErrors::ERR_SYSTEM_API_DENIED;
1107     }
1108     int32_t version = static_cast<int32_t>(strtol(apiVersion.c_str(), nullptr, 10));
1109     if (version >= API19 && !Permission::IsPermissionGranted("ohos.permission.POWER_MANAGER")) {
1110         POWER_HILOGI(FEATURE_SUSPEND, "SuspendDevice failed, The application does not have the permission");
1111         return PowerErrors::ERR_PERMISSION_DENIED;
1112     }
1113 
1114 #ifdef POWER_MANAGER_ENABLE_WATCH_BOOT_COMPLETED
1115     if (isBootCompleted_ == false) {
1116         POWER_HILOGI(FEATURE_SUSPEND, "SuspendDevice failed, not boot completed, pid: %{public}d, uid: %{public}d",
1117             pid, uid);
1118         return PowerErrors::ERR_FAILURE;
1119     }
1120 #endif
1121 
1122     if (shutdownController_->IsShuttingDown()) {
1123         POWER_HILOGW(FEATURE_SUSPEND, "System is shutting down, can't suspend");
1124         return PowerErrors::ERR_OK;
1125     }
1126     POWER_HILOGI(FEATURE_SUSPEND, "[UL_POWER] Try to suspend device, pid: %{public}d, uid: %{public}d", pid, uid);
1127     powerStateMachine_->SuspendDeviceInner(pid, callTimeMs, reason, suspendImmed);
1128     return PowerErrors::ERR_OK;
1129 }
1130 
WakeupDevice(int64_t callTimeMs,WakeupDeviceType reason,const std::string & details,const std::string & apiVersion)1131 PowerErrors PowerMgrService::WakeupDevice(
1132     int64_t callTimeMs, WakeupDeviceType reason, const std::string& details, const std::string& apiVersion)
1133 {
1134     std::lock_guard lock(wakeupMutex_);
1135     if (!Permission::IsSystem()) {
1136         POWER_HILOGI(FEATURE_SUSPEND, "WakeupDevice failed, System permission intercept");
1137         return PowerErrors::ERR_SYSTEM_API_DENIED;
1138     }
1139     int32_t version = static_cast<int32_t>(strtol(apiVersion.c_str(), nullptr, 10));
1140     if (version >= API19 && !Permission::IsPermissionGranted("ohos.permission.POWER_MANAGER")) {
1141         POWER_HILOGI(FEATURE_SUSPEND, "WakeupDevice failed, The application does not have the permission");
1142         return PowerErrors::ERR_PERMISSION_DENIED;
1143     }
1144     pid_t pid = IPCSkeleton::GetCallingPid();
1145     auto uid = IPCSkeleton::GetCallingUid();
1146 
1147 #ifdef POWER_MANAGER_ENABLE_WATCH_BOOT_COMPLETED
1148     if (isBootCompleted_ == false) {
1149         POWER_HILOGI(FEATURE_WAKEUP, "WakeupDevice failed, not boot completed, pid: %{public}d, uid: %{public}d",
1150             pid, uid);
1151         return PowerErrors::ERR_FAILURE;
1152     }
1153 #endif
1154 
1155     POWER_HILOGI(FEATURE_WAKEUP, "[UL_POWER] Try to wakeup device, pid: %{public}d, uid: %{public}d", pid, uid);
1156 
1157     BackgroundRunningLock wakeupRunningLock("WakeupLock", WAKEUP_LOCK_TIMEOUT_MS);
1158     if (details == "display_doze") {
1159         bool ret = powerStateMachine_->SetDozeMode(DisplayState::DISPLAY_DOZE);
1160         return ret ? PowerErrors::ERR_OK : PowerErrors::ERR_FAILURE;
1161     }
1162     if (details == "display_doze_suspend") {
1163         bool ret = powerStateMachine_->SetDozeMode(DisplayState::DISPLAY_DOZE_SUSPEND);
1164         return ret ? PowerErrors::ERR_OK : PowerErrors::ERR_FAILURE;
1165     }
1166     if (details == "display_off") {
1167         bool ret = powerStateMachine_->SetDozeMode(DisplayState::DISPLAY_OFF);
1168         return ret ? PowerErrors::ERR_OK : PowerErrors::ERR_FAILURE;
1169     }
1170     powerStateMachine_->WakeupDeviceInner(pid, callTimeMs, reason, details, "OHOS");
1171     return PowerErrors::ERR_OK;
1172 }
1173 
RefreshActivity(int64_t callTimeMs,UserActivityType type,bool needChangeBacklight)1174 bool PowerMgrService::RefreshActivity(int64_t callTimeMs, UserActivityType type, bool needChangeBacklight)
1175 {
1176     if (!Permission::IsPermissionGranted("ohos.permission.REFRESH_USER_ACTION") || !Permission::IsSystem()) {
1177         return false;
1178     }
1179     pid_t pid = IPCSkeleton::GetCallingPid();
1180     auto uid = IPCSkeleton::GetCallingUid();
1181     POWER_HILOGI(FEATURE_ACTIVITY,
1182         "Try to refresh activity, pid: %{public}d, uid: %{public}d, activity type: %{public}u", pid, uid, type);
1183     return RefreshActivityInner(callTimeMs, type, needChangeBacklight);
1184 }
1185 
RefreshActivityInner(int64_t callTimeMs,UserActivityType type,bool needChangeBacklight)1186 bool PowerMgrService::RefreshActivityInner(int64_t callTimeMs, UserActivityType type, bool needChangeBacklight)
1187 {
1188     std::lock_guard lock(screenMutex_);
1189     if (powerStateMachine_->CheckRefreshTime()) {
1190         return false;
1191     }
1192     pid_t pid = IPCSkeleton::GetCallingPid();
1193     powerStateMachine_->RefreshActivityInner(pid, callTimeMs, type, needChangeBacklight);
1194     return true;
1195 }
1196 
OverrideScreenOffTime(int64_t timeout,const std::string & apiVersion)1197 PowerErrors PowerMgrService::OverrideScreenOffTime(int64_t timeout, const std::string& apiVersion)
1198 {
1199     std::lock_guard lock(screenMutex_);
1200     pid_t pid = IPCSkeleton::GetCallingPid();
1201     auto uid = IPCSkeleton::GetCallingUid();
1202     if (!Permission::IsSystem()) {
1203         POWER_HILOGI(COMP_SVC, "OverrideScreenOffTime failed, System permission intercept");
1204         return PowerErrors::ERR_SYSTEM_API_DENIED;
1205     }
1206     int32_t version = static_cast<int32_t>(strtol(apiVersion.c_str(), nullptr, 10));
1207     if (version >= API19 && !Permission::IsPermissionGranted("ohos.permission.POWER_MANAGER")) {
1208         POWER_HILOGI(FEATURE_SUSPEND, "OverrideScreenOffTime failed, The application does not have the permission");
1209         return PowerErrors::ERR_PERMISSION_DENIED;
1210     }
1211     POWER_HILOGI(COMP_SVC,
1212         "Try to override screenOffTime, timeout=%{public}" PRId64 ", pid: %{public}d, uid: %{public}d",
1213         timeout, pid, uid);
1214     return powerStateMachine_->OverrideScreenOffTimeInner(timeout) ?
1215         PowerErrors::ERR_OK : PowerErrors::ERR_FAILURE;
1216 }
1217 
RestoreScreenOffTime(const std::string & apiVersion)1218 PowerErrors PowerMgrService::RestoreScreenOffTime(const std::string& apiVersion)
1219 {
1220     std::lock_guard lock(screenMutex_);
1221     if (!Permission::IsSystem()) {
1222         POWER_HILOGI(COMP_SVC, "RestoreScreenOffTime failed, System permission intercept");
1223         return PowerErrors::ERR_SYSTEM_API_DENIED;
1224     }
1225     int32_t version = static_cast<int32_t>(strtol(apiVersion.c_str(), nullptr, 10));
1226     if (version >= API19 && !Permission::IsPermissionGranted("ohos.permission.POWER_MANAGER")) {
1227         POWER_HILOGI(FEATURE_SUSPEND, "RestoreScreenOffTime failed, The application does not have the permission");
1228         return PowerErrors::ERR_PERMISSION_DENIED;
1229     }
1230     POWER_HILOGD(COMP_SVC, "Try to restore screen off time");
1231     return powerStateMachine_->RestoreScreenOffTimeInner() ?
1232         PowerErrors::ERR_OK : PowerErrors::ERR_FAILURE;
1233 }
1234 
GetState()1235 PowerState PowerMgrService::GetState()
1236 {
1237     std::lock_guard lock(stateMutex_);
1238     auto state = powerStateMachine_->GetState();
1239     POWER_HILOGD(FEATURE_POWER_STATE, "state: %{public}d", state);
1240     return state;
1241 }
1242 
IsScreenOn(bool needPrintLog)1243 bool PowerMgrService::IsScreenOn(bool needPrintLog)
1244 {
1245     std::lock_guard lock(stateMutex_);
1246     auto isScreenOn = powerStateMachine_->IsScreenOn();
1247     if (needPrintLog) {
1248         POWER_HILOGD(COMP_SVC, "isScreenOn: %{public}d", isScreenOn);
1249     }
1250     return isScreenOn;
1251 }
1252 
IsFoldScreenOn()1253 bool PowerMgrService::IsFoldScreenOn()
1254 {
1255     std::lock_guard lock(stateMutex_);
1256     auto isFoldScreenOn = powerStateMachine_->IsFoldScreenOn();
1257     POWER_HILOGI(COMP_SVC, "isFoldScreenOn: %{public}d", isFoldScreenOn);
1258     return isFoldScreenOn;
1259 }
1260 
IsCollaborationScreenOn()1261 bool PowerMgrService::IsCollaborationScreenOn()
1262 {
1263     std::lock_guard lock(stateMutex_);
1264     auto isCollaborationScreenOn = powerStateMachine_->IsCollaborationScreenOn();
1265     POWER_HILOGI(COMP_SVC, "isCollaborationScreenOn: %{public}d", isCollaborationScreenOn);
1266     return isCollaborationScreenOn;
1267 }
1268 
IsForceSleeping()1269 bool PowerMgrService::IsForceSleeping()
1270 {
1271     auto suspendController = pms->GetSuspendController();
1272     if (suspendController == nullptr) {
1273         POWER_HILOGE(COMP_SVC, "get suspendController fail");
1274         return false;
1275     }
1276 
1277     bool isForceSleeping = false;
1278 #ifdef POWER_MANAGER_ENABLE_FORCE_SLEEP_BROADCAST
1279     isForceSleeping = suspendController->GetForceSleepingFlag();
1280 #endif
1281     POWER_HILOGD(COMP_SVC, "isForceSleeping: %{public}d", isForceSleeping);
1282     return isForceSleeping;
1283 }
1284 
ForceSuspendDevice(int64_t callTimeMs,const std::string & apiVersion)1285 PowerErrors PowerMgrService::ForceSuspendDevice(int64_t callTimeMs, const std::string& apiVersion)
1286 {
1287     std::lock_guard lock(suspendMutex_);
1288     pid_t pid = IPCSkeleton::GetCallingPid();
1289     auto uid = IPCSkeleton::GetCallingUid();
1290     if (!Permission::IsSystem()) {
1291         POWER_HILOGI(FEATURE_SUSPEND, "ForceSuspendDevice failed, System permission intercept");
1292         return PowerErrors::ERR_SYSTEM_API_DENIED;
1293     }
1294     int32_t version = static_cast<int32_t>(strtol(apiVersion.c_str(), nullptr, 10));
1295     if (version >= API19 && !Permission::IsPermissionGranted("ohos.permission.POWER_MANAGER")) {
1296         POWER_HILOGI(FEATURE_SUSPEND, "ForceSuspendDevice failed, The application does not have the permission");
1297         return PowerErrors::ERR_PERMISSION_DENIED;
1298     }
1299     if (shutdownController_->IsShuttingDown()) {
1300         POWER_HILOGI(FEATURE_SUSPEND, "System is shutting down, can't force suspend");
1301         return PowerErrors::ERR_FAILURE;
1302     }
1303     POWER_HILOGI(FEATURE_SUSPEND, "[UL_POWER] Try to force suspend device, pid: %{public}d, uid: %{public}d", pid, uid);
1304     powerStateMachine_->ForceSuspendDeviceInner(pid, callTimeMs);
1305     return PowerErrors::ERR_OK;
1306 }
1307 
Hibernate(bool clearMemory,const std::string & reason,const std::string & apiVersion)1308 PowerErrors PowerMgrService::Hibernate(bool clearMemory, const std::string& reason, const std::string& apiVersion)
1309 {
1310     POWER_HILOGI(FEATURE_SUSPEND, "power mgr service hibernate begin.");
1311     if (!Permission::IsSystem()) {
1312         POWER_HILOGI(FEATURE_SUSPEND, "Hibernate failed, System permission intercept");
1313         return PowerErrors::ERR_SYSTEM_API_DENIED;
1314     }
1315     int32_t version = static_cast<int32_t>(strtol(apiVersion.c_str(), nullptr, 10));
1316     if (version >= API19 && !Permission::IsPermissionGranted("ohos.permission.POWER_MANAGER")) {
1317         POWER_HILOGI(FEATURE_SUSPEND, "Hibernate failed, The application does not have the permission");
1318         return PowerErrors::ERR_PERMISSION_DENIED;
1319     }
1320 #ifdef POWER_MANAGER_POWER_ENABLE_S4
1321     std::lock_guard lock(hibernateMutex_);
1322     pid_t pid = IPCSkeleton::GetCallingPid();
1323     auto uid = IPCSkeleton::GetCallingUid();
1324     if (shutdownController_->IsShuttingDown()) {
1325         POWER_HILOGI(FEATURE_SUSPEND, "System is shutting down, can't hibernate");
1326         return PowerErrors::ERR_FAILURE;
1327     }
1328     POWER_HILOGI(FEATURE_SUSPEND,
1329         "[UL_POWER] Try to hibernate, pid: %{public}d, uid: %{public}d, clearMemory: %{public}d, reason: %{public}s",
1330         pid, uid, static_cast<int>(clearMemory), reason.c_str());
1331     BackgroundRunningLock hibernateGuard(
1332         "hibernateGuard", HIBERNATE_GUARD_TIMEOUT_MS); // avoid hibernate breaked by S3/ULSR
1333     HibernateControllerInit();
1334 #ifdef HAS_HIVIEWDFX_HISYSEVENT_PART
1335     HiSysEventWrite(HiviewDFX::HiSysEvent::Domain::POWER, "HIBERNATE_START",
1336         HiviewDFX::HiSysEvent::EventType::BEHAVIOR, "CLEAR_MEMORY", static_cast<int32_t>(clearMemory));
1337 #endif
1338     bool ret = powerStateMachine_->HibernateInner(clearMemory, reason);
1339     return ret ? PowerErrors::ERR_OK : PowerErrors::ERR_FAILURE;
1340 #else
1341     POWER_HILOGI(FEATURE_SUSPEND, "Hibernate interface not supported.");
1342     return PowerErrors::ERR_FAILURE;
1343 #endif
1344 }
1345 
GetBundleNameByUid(const int32_t uid)1346 std::string PowerMgrService::GetBundleNameByUid(const int32_t uid)
1347 {
1348     std::string tempBundleName = "";
1349     if (uid < OHOS::AppExecFwk::Constants::BASE_APP_UID) {
1350         return tempBundleName;
1351     }
1352     BundleMgrClient bundleObj;
1353 
1354     std::string identity = IPCSkeleton::ResetCallingIdentity();
1355     ErrCode res = bundleObj.GetNameForUid(uid, tempBundleName);
1356     IPCSkeleton::SetCallingIdentity(identity);
1357     if (res != ERR_OK) {
1358         POWER_HILOGE(FEATURE_RUNNING_LOCK, "get B for U=%{public}d,Err:%{public}d",
1359             uid, static_cast<int32_t>(res));
1360     }
1361     POWER_HILOGD(FEATURE_RUNNING_LOCK, "U=%{public}d,B=%{public}s", uid, tempBundleName.c_str());
1362     return tempBundleName;
1363 }
1364 
FillRunningLockParam(const RunningLockInfo & info,const uint64_t lockid,int32_t timeOutMS)1365 RunningLockParam PowerMgrService::FillRunningLockParam(const RunningLockInfo& info,
1366     const uint64_t lockid, int32_t timeOutMS)
1367 {
1368     RunningLockParam filledParam {};
1369     filledParam.lockid = lockid;
1370     filledParam.name = info.name;
1371     filledParam.type = info.type;
1372     if (filledParam.type == RunningLockType::RUNNINGLOCK_BACKGROUND) {
1373         filledParam.type = RunningLockType::RUNNINGLOCK_BACKGROUND_TASK;
1374     }
1375     filledParam.timeoutMs = timeOutMS;
1376     filledParam.pid = IPCSkeleton::GetCallingPid();
1377     filledParam.uid = IPCSkeleton::GetCallingUid();
1378     filledParam.bundleName = GetBundleNameByUid(filledParam.uid);
1379     return filledParam;
1380 }
1381 
CreateRunningLock(const sptr<IRemoteObject> & remoteObj,const RunningLockInfo & runningLockInfo)1382 PowerErrors PowerMgrService::CreateRunningLock(
1383     const sptr<IRemoteObject>& remoteObj, const RunningLockInfo& runningLockInfo)
1384 {
1385     std::lock_guard lock(lockMutex_);
1386     if (!Permission::IsPermissionGranted("ohos.permission.RUNNING_LOCK")) {
1387         return PowerErrors::ERR_PERMISSION_DENIED;
1388     }
1389     if (!IsRunningLockTypeSupported(runningLockInfo.type)) {
1390         POWER_HILOGW(FEATURE_RUNNING_LOCK,
1391             "runninglock type is not supported, name=%{public}s, type=%{public}d",
1392             runningLockInfo.name.c_str(), runningLockInfo.type);
1393         return PowerErrors::ERR_PARAM_INVALID;
1394     }
1395 
1396     uintptr_t remoteObjPtr = reinterpret_cast<uintptr_t>(remoteObj.GetRefPtr());
1397     uint64_t lockid = std::hash<uintptr_t>()(remoteObjPtr);
1398     RunningLockParam runningLockParam = FillRunningLockParam(runningLockInfo, lockid);
1399     runningLockMgr_->CreateRunningLock(remoteObj, runningLockParam);
1400     return PowerErrors::ERR_OK;
1401 }
1402 
ReleaseRunningLock(const sptr<IRemoteObject> & remoteObj,const std::string & name)1403 bool PowerMgrService::ReleaseRunningLock(const sptr<IRemoteObject>& remoteObj, const std::string& name)
1404 {
1405     std::lock_guard lock(lockMutex_);
1406     bool result = false;
1407     if (!Permission::IsPermissionGranted("ohos.permission.RUNNING_LOCK")) {
1408         return result;
1409     }
1410 
1411     result = runningLockMgr_->ReleaseLock(remoteObj, name);
1412     return result;
1413 }
1414 
IsRunningLockTypeSupported(RunningLockType type)1415 bool PowerMgrService::IsRunningLockTypeSupported(RunningLockType type)
1416 {
1417     if (Permission::IsHap()) {
1418         if (Permission::IsSystem()) {
1419             return type <= RunningLockType::RUNNINGLOCK_PROXIMITY_SCREEN_CONTROL;
1420         }
1421         return type == RunningLockType::RUNNINGLOCK_BACKGROUND ||
1422             type == RunningLockType::RUNNINGLOCK_PROXIMITY_SCREEN_CONTROL;
1423     }
1424     return type == RunningLockType::RUNNINGLOCK_SCREEN ||
1425         type == RunningLockType::RUNNINGLOCK_BACKGROUND || // this will be instead by BACKGROUND_XXX types.
1426         type == RunningLockType::RUNNINGLOCK_PROXIMITY_SCREEN_CONTROL ||
1427         type == RunningLockType::RUNNINGLOCK_COORDINATION ||
1428         type == RunningLockType::RUNNINGLOCK_BACKGROUND_PHONE ||
1429         type == RunningLockType::RUNNINGLOCK_BACKGROUND_NOTIFICATION ||
1430         type == RunningLockType::RUNNINGLOCK_BACKGROUND_AUDIO ||
1431         type == RunningLockType::RUNNINGLOCK_BACKGROUND_SPORT ||
1432         type == RunningLockType::RUNNINGLOCK_BACKGROUND_NAVIGATION ||
1433         type == RunningLockType::RUNNINGLOCK_BACKGROUND_TASK;
1434 }
1435 
UpdateWorkSource(const sptr<IRemoteObject> & remoteObj,const std::vector<int32_t> & workSources)1436 bool PowerMgrService::UpdateWorkSource(const sptr<IRemoteObject>& remoteObj,
1437     const std::vector<int32_t>& workSources)
1438 {
1439     if (!Permission::IsPermissionGranted("ohos.permission.RUNNING_LOCK")) {
1440         return false;
1441     }
1442     std::map<int32_t, std::string> wks;
1443     for (const auto& uid : workSources) {
1444         std::string bundleName = GetBundleNameByUid(uid);
1445         wks.emplace(std::make_pair(uid, bundleName));
1446     }
1447     std::lock_guard lock(lockMutex_);
1448     runningLockMgr_->UpdateWorkSource(remoteObj, wks);
1449     return true;
1450 }
1451 
Lock(const sptr<IRemoteObject> & remoteObj,int32_t timeOutMs)1452 PowerErrors PowerMgrService::Lock(const sptr<IRemoteObject>& remoteObj, int32_t timeOutMs)
1453 {
1454 #ifdef HAS_HIVIEWDFX_HISYSEVENT_PART
1455     constexpr int32_t RUNNINGLOCK_TIMEOUT_MS = 50;
1456     int32_t beginTimeMs = GetTickCount();
1457     pid_t pid = IPCSkeleton::GetCallingPid();
1458     auto uid = IPCSkeleton::GetCallingUid();
1459 #endif
1460     if (!Permission::IsPermissionGranted("ohos.permission.RUNNING_LOCK")) {
1461         return PowerErrors::ERR_PERMISSION_DENIED;
1462     }
1463     std::lock_guard lock(lockMutex_);
1464     runningLockMgr_->Lock(remoteObj);
1465     if (timeOutMs > 0) {
1466         std::function<void()> task = [this, remoteObj, timeOutMs]() {
1467             std::lock_guard lock(lockMutex_);
1468             RunningLockTimerHandler::GetInstance().UnregisterRunningLockTimer(remoteObj);
1469             runningLockMgr_->UpdateWorkSource(remoteObj, {});
1470             runningLockMgr_->UnLock(remoteObj);
1471         };
1472         RunningLockTimerHandler::GetInstance().RegisterRunningLockTimer(remoteObj, task, timeOutMs);
1473     }
1474 #ifdef HAS_HIVIEWDFX_HISYSEVENT_PART
1475     int32_t endTimeMs = GetTickCount();
1476     if (endTimeMs - beginTimeMs > RUNNINGLOCK_TIMEOUT_MS) {
1477         POWER_HILOGI(FEATURE_RUNNING_LOCK, "Lock interface timeout=%{public}d", (endTimeMs - beginTimeMs));
1478         HiSysEventWrite(HiviewDFX::HiSysEvent::Domain::POWER, "INTERFACE_CONSUMING_TIMEOUT",
1479             HiviewDFX::HiSysEvent::EventType::BEHAVIOR, "PID", pid, "UID", uid, "TYPE",
1480             static_cast<int32_t>(InterfaceTimeoutType::INTERFACE_TIMEOUT_TYPE_RUNNINGLOCK_LOCK), "REASON", "",
1481             "TIME", (endTimeMs - beginTimeMs));
1482     }
1483 #endif
1484     return PowerErrors::ERR_OK;
1485 }
1486 
UnLock(const sptr<IRemoteObject> & remoteObj,const std::string & name)1487 PowerErrors PowerMgrService::UnLock(const sptr<IRemoteObject>& remoteObj, const std::string& name)
1488 {
1489 #ifdef HAS_HIVIEWDFX_HISYSEVENT_PART
1490     constexpr int32_t RUNNINGLOCK_TIMEOUT_MS = 50;
1491     int32_t beginTimeMs = GetTickCount();
1492     pid_t pid = IPCSkeleton::GetCallingPid();
1493     auto uid = IPCSkeleton::GetCallingUid();
1494 #endif
1495     if (!Permission::IsPermissionGranted("ohos.permission.RUNNING_LOCK")) {
1496         return PowerErrors::ERR_PERMISSION_DENIED;
1497     }
1498     std::lock_guard lock(lockMutex_);
1499     RunningLockTimerHandler::GetInstance().UnregisterRunningLockTimer(remoteObj);
1500     runningLockMgr_->UnLock(remoteObj, name);
1501 #ifdef HAS_HIVIEWDFX_HISYSEVENT_PART
1502     int32_t endTimeMs = GetTickCount();
1503     if (endTimeMs - beginTimeMs > RUNNINGLOCK_TIMEOUT_MS) {
1504         POWER_HILOGI(FEATURE_RUNNING_LOCK, "UnLock interface timeout=%{public}d", (endTimeMs - beginTimeMs));
1505         HiSysEventWrite(HiviewDFX::HiSysEvent::Domain::POWER, "INTERFACE_CONSUMING_TIMEOUT",
1506             HiviewDFX::HiSysEvent::EventType::BEHAVIOR, "PID", pid, "UID", uid, "TYPE",
1507             static_cast<int32_t>(InterfaceTimeoutType::INTERFACE_TIMEOUT_TYPE_RUNNINGLOCK_UNLOCK), "REASON", "",
1508             "TIME", (endTimeMs - beginTimeMs));
1509     }
1510 #endif
1511     return PowerErrors::ERR_OK;
1512 }
1513 
QueryRunningLockLists(std::map<std::string,RunningLockInfo> & runningLockLists)1514 bool PowerMgrService::QueryRunningLockLists(std::map<std::string, RunningLockInfo>& runningLockLists)
1515 {
1516     std::lock_guard lock(lockMutex_);
1517     if (!Permission::IsPermissionGranted("ohos.permission.RUNNING_LOCK")) {
1518         return false;
1519     }
1520     QueryRunningLockListsInner(runningLockLists);
1521     return true;
1522 }
1523 
QueryRunningLockListsInner(std::map<std::string,RunningLockInfo> & runningLockLists)1524 void PowerMgrService::QueryRunningLockListsInner(std::map<std::string, RunningLockInfo>& runningLockLists)
1525 {
1526     runningLockMgr_->QueryRunningLockLists(runningLockLists);
1527 }
1528 
IsExistAudioStream(pid_t uid)1529 bool PowerMgrService::IsExistAudioStream(pid_t uid)
1530 {
1531     std::lock_guard lock(lockMutex_);
1532     return runningLockMgr_->IsExistAudioStream(uid);
1533 }
1534 
RegisterRunningLockCallback(const sptr<IPowerRunninglockCallback> & callback)1535 bool PowerMgrService::RegisterRunningLockCallback(const sptr<IPowerRunninglockCallback>& callback)
1536 {
1537     std::lock_guard lock(lockMutex_);
1538     pid_t pid = IPCSkeleton::GetCallingPid();
1539     auto uid = IPCSkeleton::GetCallingUid();
1540     if (!Permission::IsPermissionGranted("ohos.permission.POWER_MANAGER")) {
1541         return false;
1542     }
1543     POWER_HILOGI(FEATURE_RUNNING_LOCK, "%{public}s: pid: %{public}d, uid: %{public}d", __func__, pid, uid);
1544     runningLockMgr_->RegisterRunningLockCallback(callback);
1545     return true;
1546 }
1547 
UnRegisterRunningLockCallback(const sptr<IPowerRunninglockCallback> & callback)1548 bool PowerMgrService::UnRegisterRunningLockCallback(const sptr<IPowerRunninglockCallback>& callback)
1549 {
1550     std::lock_guard lock(lockMutex_);
1551     pid_t pid = IPCSkeleton::GetCallingPid();
1552     auto uid = IPCSkeleton::GetCallingUid();
1553     if (!Permission::IsPermissionGranted("ohos.permission.POWER_MANAGER")) {
1554         return false;
1555     }
1556     POWER_HILOGI(FEATURE_RUNNING_LOCK, "%{public}s: pid: %{public}d, uid: %{public}d", __func__, pid, uid);
1557     runningLockMgr_->RegisterRunningLockCallback(callback);
1558     return true;
1559 }
1560 
ForceUnLock(const sptr<IRemoteObject> & remoteObj)1561 void PowerMgrService::ForceUnLock(const sptr<IRemoteObject>& remoteObj)
1562 {
1563     PowerXCollie powerXCollie("PowerMgrService::ForceUnLock", true);
1564     std::lock_guard lock(lockMutex_);
1565     runningLockMgr_->UnLock(remoteObj);
1566     runningLockMgr_->ReleaseLock(remoteObj);
1567 }
1568 
IsUsed(const sptr<IRemoteObject> & remoteObj)1569 bool PowerMgrService::IsUsed(const sptr<IRemoteObject>& remoteObj)
1570 {
1571     std::lock_guard lock(lockMutex_);
1572     auto isUsed = runningLockMgr_->IsUsed(remoteObj);
1573     POWER_HILOGD(FEATURE_RUNNING_LOCK, "RunningLock is Used: %{public}d", isUsed);
1574     return isUsed;
1575 }
1576 
ProxyRunningLock(bool isProxied,pid_t pid,pid_t uid)1577 bool PowerMgrService::ProxyRunningLock(bool isProxied, pid_t pid, pid_t uid)
1578 {
1579     std::lock_guard lock(lockMutex_);
1580     if (!Permission::IsSystem()) {
1581         return false;
1582     }
1583     return runningLockMgr_->ProxyRunningLock(isProxied, pid, uid);
1584 }
1585 
ProxyRunningLocks(bool isProxied,const std::vector<std::pair<pid_t,pid_t>> & processInfos)1586 bool PowerMgrService::ProxyRunningLocks(bool isProxied, const std::vector<std::pair<pid_t, pid_t>>& processInfos)
1587 {
1588     if (!Permission::IsSystem()) {
1589         return false;
1590     }
1591     std::lock_guard lock(lockMutex_);
1592     runningLockMgr_->ProxyRunningLocks(isProxied, processInfos);
1593     return true;
1594 }
1595 
ResetRunningLocks()1596 bool PowerMgrService::ResetRunningLocks()
1597 {
1598     if (!Permission::IsSystem()) {
1599         return false;
1600     }
1601     std::lock_guard lock(lockMutex_);
1602     runningLockMgr_->ResetRunningLocks();
1603     return true;
1604 }
1605 
RegisterPowerStateCallback(const sptr<IPowerStateCallback> & callback,bool isSync)1606 bool PowerMgrService::RegisterPowerStateCallback(const sptr<IPowerStateCallback>& callback, bool isSync)
1607 {
1608     std::lock_guard lock(stateMutex_);
1609     pid_t pid = IPCSkeleton::GetCallingPid();
1610     auto uid = IPCSkeleton::GetCallingUid();
1611     if (!Permission::IsPermissionGranted("ohos.permission.POWER_MANAGER")) {
1612         return false;
1613     }
1614     POWER_HILOGI(FEATURE_POWER_STATE, "%{public}s: pid: %{public}d, uid: %{public}d, isSync: %{public}u", __func__, pid,
1615         uid, static_cast<uint32_t>(isSync));
1616     powerStateMachine_->RegisterPowerStateCallback(callback, isSync);
1617     return true;
1618 }
1619 
UnRegisterPowerStateCallback(const sptr<IPowerStateCallback> & callback)1620 bool PowerMgrService::UnRegisterPowerStateCallback(const sptr<IPowerStateCallback>& callback)
1621 {
1622     std::lock_guard lock(stateMutex_);
1623     pid_t pid = IPCSkeleton::GetCallingPid();
1624     auto uid = IPCSkeleton::GetCallingUid();
1625     if (!Permission::IsPermissionGranted("ohos.permission.POWER_MANAGER")) {
1626         return false;
1627     }
1628     POWER_HILOGI(FEATURE_POWER_STATE, "%{public}s: pid: %{public}d, uid: %{public}d", __func__, pid, uid);
1629     powerStateMachine_->UnRegisterPowerStateCallback(callback);
1630     return true;
1631 }
1632 
RegisterSyncSleepCallback(const sptr<ISyncSleepCallback> & callback,SleepPriority priority)1633 bool PowerMgrService::RegisterSyncSleepCallback(const sptr<ISyncSleepCallback>& callback, SleepPriority priority)
1634 {
1635     std::lock_guard lock(suspendMutex_);
1636     pid_t pid = IPCSkeleton::GetCallingPid();
1637     auto uid = IPCSkeleton::GetCallingUid();
1638     if (!Permission::IsPermissionGranted("ohos.permission.POWER_MANAGER")) {
1639         return false;
1640     }
1641     POWER_HILOGI(FEATURE_SUSPEND, "%{public}s: pid: %{public}d, uid: %{public}d", __func__, pid, uid);
1642     suspendController_->AddCallback(callback, priority);
1643     return true;
1644 }
1645 
UnRegisterSyncSleepCallback(const sptr<ISyncSleepCallback> & callback)1646 bool PowerMgrService::UnRegisterSyncSleepCallback(const sptr<ISyncSleepCallback>& callback)
1647 {
1648     std::lock_guard lock(suspendMutex_);
1649     pid_t pid = IPCSkeleton::GetCallingPid();
1650     auto uid = IPCSkeleton::GetCallingUid();
1651     if (!Permission::IsPermissionGranted("ohos.permission.POWER_MANAGER")) {
1652         return false;
1653     }
1654     POWER_HILOGI(FEATURE_SUSPEND, "%{public}s: pid: %{public}d, uid: %{public}d", __func__, pid, uid);
1655     suspendController_->RemoveCallback(callback);
1656     return true;
1657 }
1658 
RegisterSuspendTakeoverCallback(const sptr<ITakeOverSuspendCallback> & callback,TakeOverSuspendPriority priority)1659 bool PowerMgrService::RegisterSuspendTakeoverCallback(
1660     const sptr<ITakeOverSuspendCallback>& callback, TakeOverSuspendPriority priority)
1661 {
1662 #ifdef POWER_MANAGER_TAKEOVER_SUSPEND
1663     std::lock_guard lock(suspendMutex_);
1664     pid_t pid = IPCSkeleton::GetCallingPid();
1665     auto uid = IPCSkeleton::GetCallingUid();
1666     if (!Permission::IsPermissionGranted("ohos.permission.POWER_MANAGER")) {
1667         POWER_HILOGE(FEATURE_SUSPEND, "Permission deny");
1668         return false;
1669     }
1670     POWER_HILOGI(FEATURE_SUSPEND, "Func %{public}s: pid: %{public}d, uid: %{public}d", __func__, pid, uid);
1671     if (suspendController_ == nullptr) {
1672         POWER_HILOGE(FEATURE_SUSPEND, "suspendController_ is nullptr");
1673         return false;
1674     }
1675     suspendController_->AddCallback(callback, priority);
1676     return true;
1677 #else
1678     return true;
1679 #endif
1680 }
1681 
UnRegisterSuspendTakeoverCallback(const sptr<ITakeOverSuspendCallback> & callback)1682 bool PowerMgrService::UnRegisterSuspendTakeoverCallback(const sptr<ITakeOverSuspendCallback>& callback)
1683 {
1684 #ifdef POWER_MANAGER_TAKEOVER_SUSPEND
1685     std::lock_guard lock(suspendMutex_);
1686     pid_t pid = IPCSkeleton::GetCallingPid();
1687     auto uid = IPCSkeleton::GetCallingUid();
1688     if (!Permission::IsPermissionGranted("ohos.permission.POWER_MANAGER")) {
1689         POWER_HILOGE(FEATURE_SUSPEND, "Permission deny");
1690         return false;
1691     }
1692     POWER_HILOGI(FEATURE_SUSPEND, "Func %{public}s: pid: %{public}d, uid: %{public}d", __func__, pid, uid);
1693     suspendController_->RemoveCallback(callback);
1694     return true;
1695 #else
1696     return true;
1697 #endif
1698 }
1699 
RegisterSyncHibernateCallback(const sptr<ISyncHibernateCallback> & callback)1700 bool PowerMgrService::RegisterSyncHibernateCallback(const sptr<ISyncHibernateCallback>& callback)
1701 {
1702 #ifdef POWER_MANAGER_POWER_ENABLE_S4
1703     POWER_HILOGI(FEATURE_SUSPEND, "RegisterSyncHibernateCallback begin.");
1704     HibernateControllerInit();
1705     hibernateController_->RegisterSyncHibernateCallback(callback);
1706     return true;
1707 #else
1708     POWER_HILOGI(FEATURE_SUSPEND, "RegisterSyncHibernateCallback interface not supported.");
1709     return false;
1710 #endif
1711 }
1712 
UnRegisterSyncHibernateCallback(const sptr<ISyncHibernateCallback> & callback)1713 bool PowerMgrService::UnRegisterSyncHibernateCallback(const sptr<ISyncHibernateCallback>& callback)
1714 {
1715 #ifdef POWER_MANAGER_POWER_ENABLE_S4
1716     POWER_HILOGI(FEATURE_SUSPEND, "UnRegisterSyncHibernateCallback begin.");
1717     HibernateControllerInit();
1718     hibernateController_->UnregisterSyncHibernateCallback(callback);
1719     return true;
1720 #else
1721     POWER_HILOGI(FEATURE_SUSPEND, "UnRegisterSyncHibernateCallback interface not supported.");
1722     return false;
1723 #endif
1724 }
1725 
RegisterPowerModeCallback(const sptr<IPowerModeCallback> & callback)1726 bool PowerMgrService::RegisterPowerModeCallback(const sptr<IPowerModeCallback>& callback)
1727 {
1728     std::lock_guard lock(modeMutex_);
1729     pid_t pid = IPCSkeleton::GetCallingPid();
1730     auto uid = IPCSkeleton::GetCallingUid();
1731     if (!Permission::IsSystem()) {
1732         return false;
1733     }
1734     POWER_HILOGI(FEATURE_POWER_MODE, "%{public}s: pid: %{public}d, uid: %{public}d", __func__, pid, uid);
1735     powerModeModule_.AddPowerModeCallback(callback);
1736     return true;
1737 }
1738 
UnRegisterPowerModeCallback(const sptr<IPowerModeCallback> & callback)1739 bool PowerMgrService::UnRegisterPowerModeCallback(const sptr<IPowerModeCallback>& callback)
1740 {
1741     std::lock_guard lock(modeMutex_);
1742     pid_t pid = IPCSkeleton::GetCallingPid();
1743     auto uid = IPCSkeleton::GetCallingUid();
1744     if (!Permission::IsSystem()) {
1745         return false;
1746     }
1747     POWER_HILOGI(FEATURE_POWER_MODE, "%{public}s: pid: %{public}d, uid: %{public}d", __func__, pid, uid);
1748     powerModeModule_.DelPowerModeCallback(callback);
1749     return true;
1750 }
1751 
RegisterScreenStateCallback(int32_t remainTime,const sptr<IScreenOffPreCallback> & callback)1752 bool PowerMgrService::RegisterScreenStateCallback(int32_t remainTime, const sptr<IScreenOffPreCallback>& callback)
1753 {
1754     std::lock_guard lock(screenOffPreMutex_);
1755     pid_t pid = IPCSkeleton::GetCallingPid();
1756     auto uid = IPCSkeleton::GetCallingUid();
1757     if (!Permission::IsSystem()) {
1758         return false;
1759     }
1760     POWER_HILOGI(FEATURE_SCREEN_OFF_PRE, "%{public}s: pid: %{public}d, uid: %{public}d", __func__, pid, uid);
1761     screenOffPreController_->AddScreenStateCallback(remainTime, callback);
1762     return true;
1763 }
1764 
UnRegisterScreenStateCallback(const sptr<IScreenOffPreCallback> & callback)1765 bool PowerMgrService::UnRegisterScreenStateCallback(const sptr<IScreenOffPreCallback>& callback)
1766 {
1767     std::lock_guard lock(screenOffPreMutex_);
1768     pid_t pid = IPCSkeleton::GetCallingPid();
1769     auto uid = IPCSkeleton::GetCallingUid();
1770     if (!Permission::IsSystem()) {
1771         return false;
1772     }
1773     POWER_HILOGI(FEATURE_SCREEN_OFF_PRE, "%{public}s: pid: %{public}d, uid: %{public}d", __func__, pid, uid);
1774     screenOffPreController_->DelScreenStateCallback(callback);
1775     return true;
1776 }
1777 
SetDisplaySuspend(bool enable)1778 bool PowerMgrService::SetDisplaySuspend(bool enable)
1779 {
1780     std::lock_guard lock(screenMutex_);
1781     pid_t pid = IPCSkeleton::GetCallingPid();
1782     auto uid = IPCSkeleton::GetCallingUid();
1783     if (!Permission::IsSystem()) {
1784         return false;
1785     }
1786     POWER_HILOGI(FEATURE_SUSPEND, "%{public}s: pid: %{public}d, uid: %{public}d, enable: %{public}d",
1787         __func__, pid, uid, enable);
1788     powerStateMachine_->SetDisplaySuspend(enable);
1789     return true;
1790 }
1791 
SetDeviceMode(const PowerMode & mode)1792 PowerErrors PowerMgrService::SetDeviceMode(const PowerMode& mode)
1793 {
1794     std::lock_guard lock(modeMutex_);
1795     pid_t pid = IPCSkeleton::GetCallingPid();
1796     auto uid = IPCSkeleton::GetCallingUid();
1797     POWER_HILOGI(FEATURE_POWER_MODE, "%{public}s: pid: %{public}d, uid: %{public}d, mode: %{public}u",
1798         __func__, pid, uid, mode);
1799     if (!Permission::IsSystem()) {
1800         return PowerErrors::ERR_SYSTEM_API_DENIED;
1801     }
1802     if (!Permission::IsPermissionGranted("ohos.permission.POWER_OPTIMIZATION")) {
1803         return PowerErrors::ERR_PERMISSION_DENIED;
1804     }
1805     powerModeModule_.SetModeItem(mode);
1806     return PowerErrors::ERR_OK;
1807 }
1808 
GetDeviceMode()1809 PowerMode PowerMgrService::GetDeviceMode()
1810 {
1811     std::lock_guard lock(modeMutex_);
1812     pid_t pid = IPCSkeleton::GetCallingPid();
1813     auto uid = IPCSkeleton::GetCallingUid();
1814     auto mode = powerModeModule_.GetModeItem();
1815     POWER_HILOGI(FEATURE_POWER_MODE, "%{public}s: pid: %{public}d, uid: %{public}d, mode: %{public}u",
1816         __func__, pid, uid, mode);
1817     return mode;
1818 }
1819 
ShellDump(const std::vector<std::string> & args,uint32_t argc)1820 std::string PowerMgrService::ShellDump(const std::vector<std::string>& args, uint32_t argc)
1821 {
1822     if (!Permission::IsSystem() || !isBootCompleted_) {
1823         return "";
1824     }
1825     std::lock_guard lock(dumpMutex_);
1826     pid_t pid = IPCSkeleton::GetCallingPid();
1827     auto uid = IPCSkeleton::GetCallingUid();
1828 
1829     std::string result;
1830     bool ret = PowerMgrDumper::Dump(args, result);
1831     POWER_HILOGI(COMP_SVC, "%{public}s: pid: %{public}d, uid: %{public}d ret :%{public}d", __func__, pid, uid, ret);
1832     return result;
1833 }
1834 
RegisterShutdownCallback(const sptr<ITakeOverShutdownCallback> & callback,ShutdownPriority priority)1835 void PowerMgrService::RegisterShutdownCallback(
1836     const sptr<ITakeOverShutdownCallback>& callback, ShutdownPriority priority)
1837 {
1838     RETURN_IF (callback == nullptr);
1839     RETURN_IF (!Permission::IsSystem());
1840 
1841     std::lock_guard lock(shutdownMutex_);
1842     shutdownController_->AddCallback(callback, priority);
1843 }
1844 
UnRegisterShutdownCallback(const sptr<ITakeOverShutdownCallback> & callback)1845 void PowerMgrService::UnRegisterShutdownCallback(const sptr<ITakeOverShutdownCallback>& callback)
1846 {
1847     RETURN_IF (callback == nullptr);
1848     RETURN_IF (!Permission::IsSystem());
1849 
1850     std::lock_guard lock(shutdownMutex_);
1851     shutdownController_->RemoveCallback(callback);
1852 }
1853 
RegisterShutdownCallback(const sptr<IAsyncShutdownCallback> & callback,ShutdownPriority priority)1854 void PowerMgrService::RegisterShutdownCallback(
1855     const sptr<IAsyncShutdownCallback>& callback, ShutdownPriority priority)
1856 {
1857     RETURN_IF (callback == nullptr);
1858     RETURN_IF (!Permission::IsSystem());
1859 
1860     std::lock_guard lock(shutdownMutex_);
1861     shutdownController_->AddCallback(callback, priority);
1862 }
1863 
UnRegisterShutdownCallback(const sptr<IAsyncShutdownCallback> & callback)1864 void PowerMgrService::UnRegisterShutdownCallback(const sptr<IAsyncShutdownCallback>& callback)
1865 {
1866     RETURN_IF (callback == nullptr);
1867     RETURN_IF (!Permission::IsSystem());
1868 
1869     std::lock_guard lock(shutdownMutex_);
1870     shutdownController_->RemoveCallback(callback);
1871 }
1872 
RegisterShutdownCallback(const sptr<ISyncShutdownCallback> & callback,ShutdownPriority priority)1873 void PowerMgrService::RegisterShutdownCallback(
1874     const sptr<ISyncShutdownCallback>& callback, ShutdownPriority priority)
1875 {
1876     RETURN_IF (callback == nullptr);
1877     RETURN_IF (!Permission::IsSystem());
1878 
1879     std::lock_guard lock(shutdownMutex_);
1880     shutdownController_->AddCallback(callback, priority);
1881 }
1882 
UnRegisterShutdownCallback(const sptr<ISyncShutdownCallback> & callback)1883 void PowerMgrService::UnRegisterShutdownCallback(const sptr<ISyncShutdownCallback>& callback)
1884 {
1885     RETURN_IF (callback == nullptr);
1886     RETURN_IF (!Permission::IsSystem());
1887 
1888     std::lock_guard lock(shutdownMutex_);
1889     shutdownController_->RemoveCallback(callback);
1890 }
1891 
BackgroundRunningLock(std::string name,int32_t timeOutMs)1892 PowerMgrService::BackgroundRunningLock::BackgroundRunningLock(std::string name, int32_t timeOutMs)
1893 {
1894     token_ = new (std::nothrow) RunningLockTokenStub();
1895     if (token_ == nullptr) {
1896         POWER_HILOGE(COMP_SVC, "create runninglock token failed");
1897         return;
1898     }
1899     RunningLockInfo info = {name, OHOS::PowerMgr::RunningLockType::RUNNINGLOCK_BACKGROUND};
1900     pms->CreateRunningLock(token_, info);
1901     pms->Lock(token_, timeOutMs);
1902 }
1903 
~BackgroundRunningLock()1904 PowerMgrService::BackgroundRunningLock::~BackgroundRunningLock()
1905 {
1906     if (token_ == nullptr) {
1907         POWER_HILOGE(COMP_SVC, "token_ is nullptr");
1908         return;
1909     }
1910     pms->ReleaseRunningLock(token_);
1911 }
1912 
SuspendControllerInit()1913 void PowerMgrService::SuspendControllerInit()
1914 {
1915     if (!suspendController_) {
1916         suspendController_ = std::make_shared<SuspendController>(shutdownController_, powerStateMachine_, ffrtTimer_);
1917     }
1918     suspendController_->Init();
1919 }
1920 
WakeupControllerInit()1921 void PowerMgrService::WakeupControllerInit()
1922 {
1923     if (!wakeupController_) {
1924         wakeupController_ = std::make_shared<WakeupController>(powerStateMachine_);
1925     }
1926     wakeupController_->Init();
1927 }
1928 
1929 #ifdef POWER_MANAGER_POWER_ENABLE_S4
HibernateControllerInit()1930 void PowerMgrService::HibernateControllerInit()
1931 {
1932     if (!hibernateController_) {
1933         hibernateController_ = std::make_shared<HibernateController>();
1934     }
1935 }
1936 #endif
1937 
IsCollaborationState()1938 bool PowerMgrService::IsCollaborationState()
1939 {
1940     bool collaborationState = false;
1941     auto pms = DelayedSpSingleton<PowerMgrService>::GetInstance();
1942     if (pms == nullptr) {
1943         return collaborationState;
1944     }
1945     auto stateMachine = pms->GetPowerStateMachine();
1946     if (stateMachine == nullptr) {
1947         return collaborationState;
1948     }
1949     collaborationState = stateMachine->IsRunningLockEnabled(RunningLockType::RUNNINGLOCK_COORDINATION);
1950     return collaborationState;
1951 }
1952 
1953 #ifdef POWER_MANAGER_WAKEUP_ACTION
WakeupActionControllerInit()1954 void PowerMgrService::WakeupActionControllerInit()
1955 {
1956     if (!wakeupActionController_) {
1957         wakeupActionController_ = std::make_shared<WakeupActionController>(shutdownController_, powerStateMachine_);
1958     }
1959     wakeupActionController_->Init();
1960 }
1961 #endif
1962 
1963 #ifdef POWER_MANAGER_ENABLE_CHARGING_TYPE_SETTING
PowerConnectStatusInit()1964 void PowerMgrService::PowerConnectStatusInit()
1965 {
1966     auto pluggedType = BatterySrvClient::GetInstance().GetPluggedType();
1967     if (pluggedType == BatteryPluggedType::PLUGGED_TYPE_BUTT) {
1968         POWER_HILOGE(COMP_SVC, "BatterySrvClient GetPluggedType error");
1969         SetPowerConnectStatus(PowerConnectStatus::POWER_CONNECT_INVALID);
1970     } else if ((pluggedType == BatteryPluggedType::PLUGGED_TYPE_AC) ||
1971         (pluggedType == BatteryPluggedType::PLUGGED_TYPE_USB) ||
1972         (pluggedType == BatteryPluggedType::PLUGGED_TYPE_WIRELESS)) {
1973         SetPowerConnectStatus(PowerConnectStatus::POWER_CONNECT_AC);
1974     } else {
1975         SetPowerConnectStatus(PowerConnectStatus::POWER_CONNECT_DC);
1976     }
1977 }
1978 
IsPowerConnected()1979 bool PowerMgrService::IsPowerConnected()
1980 {
1981     if (GetPowerConnectStatus() == PowerConnectStatus::POWER_CONNECT_INVALID) {
1982         PowerConnectStatusInit(); // try to init again if invalid
1983     }
1984     return GetPowerConnectStatus() == PowerConnectStatus::POWER_CONNECT_AC;
1985 }
1986 #endif
1987 
VibratorInit()1988 void PowerMgrService::VibratorInit()
1989 {
1990     std::shared_ptr<PowerVibrator> vibrator = PowerVibrator::GetInstance();
1991     vibrator->LoadConfig(POWER_VIBRATOR_CONFIG_FILE,
1992         VENDOR_POWER_VIBRATOR_CONFIG_FILE, SYSTEM_POWER_VIBRATOR_CONFIG_FILE);
1993 }
1994 
IsStandby(bool & isStandby)1995 PowerErrors PowerMgrService::IsStandby(bool& isStandby)
1996 {
1997 #ifdef HAS_DEVICE_STANDBY_PART
1998     DevStandbyMgr::StandbyServiceClient& standbyServiceClient = DevStandbyMgr::StandbyServiceClient::GetInstance();
1999     ErrCode code = standbyServiceClient.IsDeviceInStandby(isStandby);
2000     if (code == ERR_OK) {
2001         return PowerErrors::ERR_OK;
2002     }
2003     return PowerErrors::ERR_FAILURE;
2004 #else
2005     return PowerErrors::ERR_OK;
2006 #endif
2007 }
2008 
OnRemoteDied(const wptr<IRemoteObject> & remote)2009 void PowerMgrService::InvokerDeathRecipient::OnRemoteDied(const wptr<IRemoteObject>& remote)
2010 {
2011     POWER_HILOGI(COMP_SVC, "OnRemoteDied Called");
2012     if (!remote.promote()) {
2013         POWER_HILOGI(COMP_SVC, "proxy no longer exists, return early");
2014         return;
2015     }
2016     POWER_HILOGI(COMP_SVC, "the last client using %{public}s has died", interfaceName_.c_str());
2017     auto pms = DelayedSpSingleton<PowerMgrService>::GetInstance();
2018     if (!pms) {
2019         POWER_HILOGE(COMP_SVC, "cannot get PowerMgrService, return early");
2020         return;
2021     }
2022     callback_(pms);
2023 }
2024 
SetForceTimingOut(bool enabled,const sptr<IRemoteObject> & token)2025 PowerErrors PowerMgrService::SetForceTimingOut(bool enabled, const sptr<IRemoteObject>& token)
2026 {
2027     static sptr<IRemoteObject> thisInterfaceInvoker = nullptr;
2028     static std::mutex localMutex;
2029     static sptr<InvokerDeathRecipient> drt =
2030         sptr<InvokerDeathRecipient>::MakeSptr(__func__, [](const sptr<PowerMgrService>& pms) {
2031             auto stateMachine = pms->GetPowerStateMachine();
2032             if (!stateMachine) {
2033                 POWER_HILOGE(COMP_SVC, "cannot get PowerStateMachine, return early");
2034                 return;
2035             }
2036             stateMachine->SetForceTimingOut(false);
2037             POWER_HILOGI(COMP_SVC, "the variables related to SetForceTimingOut has been reset");
2038         });
2039 
2040     if (!Permission::IsSystem()) {
2041         return PowerErrors::ERR_SYSTEM_API_DENIED;
2042     }
2043 
2044     // even if drt is nullptr(unlikely), it will be checked in IPCObjectProxy::SendObituary()
2045     localMutex.lock();
2046     if (token && token->IsProxyObject() && token != thisInterfaceInvoker) {
2047         // The localMutex only ensures that the "remove, assign, add" actions for THIS drt are thread safe.
2048         // AddDeathRecipient/RemoveDeathRecipient are thread safe theirselves.
2049         // Different remote objects(invokers) do not interfere wich each other
2050         // Different DeathRecipients for the same invoker do not interfere wich each other
2051         // Only one RemoteObject may hold the death recipient defined in this method and only once.
2052         if (thisInterfaceInvoker) {
2053             thisInterfaceInvoker->RemoveDeathRecipient(drt);
2054         } // removed from the old invoker
2055         thisInterfaceInvoker = token;
2056         thisInterfaceInvoker->AddDeathRecipient(drt); // added to the new invoker
2057     }
2058     localMutex.unlock();
2059     powerStateMachine_->SetForceTimingOut(enabled);
2060     return PowerErrors::ERR_OK;
2061 }
2062 
LockScreenAfterTimingOut(bool enabledLockScreen,bool checkLock,bool sendScreenOffEvent,const sptr<IRemoteObject> & token)2063 PowerErrors PowerMgrService::LockScreenAfterTimingOut(
2064     bool enabledLockScreen, bool checkLock, bool sendScreenOffEvent, const sptr<IRemoteObject>& token)
2065 {
2066     static sptr<IRemoteObject> thisInterfaceInvoker = nullptr;
2067     static std::mutex localMutex;
2068     static sptr<InvokerDeathRecipient> drt =
2069         sptr<InvokerDeathRecipient>::MakeSptr(__func__, [](sptr<PowerMgrService> pms) {
2070             auto stateMachine = pms->GetPowerStateMachine();
2071             if (!stateMachine) {
2072                 POWER_HILOGE(COMP_SVC, "cannot get PowerStateMachine, return early");
2073                 return;
2074             }
2075             stateMachine->LockScreenAfterTimingOut(true, false, true);
2076             POWER_HILOGI(COMP_SVC, "the variables related to LockScreenAfterTimingOut has been reset");
2077         });
2078 
2079     if (!Permission::IsSystem()) {
2080         return PowerErrors::ERR_SYSTEM_API_DENIED;
2081     }
2082     localMutex.lock();
2083     if (token && token->IsProxyObject() && token != thisInterfaceInvoker) {
2084         // The localMutex only ensures that the "remove, assign, add" actions are thread safe.
2085         // AddDeathRecipient/RemoveDeathRecipient are thread safe theirselves.
2086         if (thisInterfaceInvoker) {
2087             thisInterfaceInvoker->RemoveDeathRecipient(drt);
2088         } // removed from the old invoker
2089         thisInterfaceInvoker = token;
2090         thisInterfaceInvoker->AddDeathRecipient(drt); // added to the new invoker
2091     }
2092     localMutex.unlock();
2093     powerStateMachine_->LockScreenAfterTimingOut(enabledLockScreen, checkLock, sendScreenOffEvent);
2094     return PowerErrors::ERR_OK;
2095 }
2096 
SetEnableDoze(bool enable)2097 void PowerMgrService::SetEnableDoze(bool enable)
2098 {
2099     auto stateMachine = pms->GetPowerStateMachine();
2100     if (stateMachine == nullptr) {
2101         return;
2102     }
2103     stateMachine->SetEnableDoze(enable);
2104 }
2105 
2106 #ifdef HAS_MULTIMODALINPUT_INPUT_PART
OnInputEvent(std::shared_ptr<KeyEvent> keyEvent) const2107 void PowerMgrInputMonitor::OnInputEvent(std::shared_ptr<KeyEvent> keyEvent) const
2108 {
2109     auto pms = DelayedSpSingleton<PowerMgrService>::GetInstance();
2110     if (pms == nullptr) {
2111         return;
2112     }
2113     auto stateMachine = pms->GetPowerStateMachine();
2114     if (stateMachine == nullptr) {
2115         return;
2116     }
2117     if (keyEvent->GetDeviceId() == COLLABORATION_REMOTE_DEVICE_ID &&
2118         stateMachine->IsRunningLockEnabled(RunningLockType::RUNNINGLOCK_COORDINATION) &&
2119         stateMachine->GetState() == PowerState::AWAKE) {
2120         stateMachine->SetState(PowerState::DIM, StateChangeReason::STATE_CHANGE_REASON_COORDINATION, true);
2121         POWER_HILOGD(FEATURE_INPUT, "remote key event in coordinated state, override screen off time");
2122     }
2123 }
2124 
OnInputEvent(std::shared_ptr<PointerEvent> pointerEvent) const2125 void PowerMgrInputMonitor::OnInputEvent(std::shared_ptr<PointerEvent> pointerEvent) const
2126 {
2127     auto pms = DelayedSpSingleton<PowerMgrService>::GetInstance();
2128     if (pms == nullptr) {
2129         return;
2130     }
2131     auto stateMachine = pms->GetPowerStateMachine();
2132     if (stateMachine == nullptr) {
2133         return;
2134     }
2135     auto action = pointerEvent->GetPointerAction();
2136     if (action == PointerEvent::POINTER_ACTION_ENTER_WINDOW ||
2137         action == PointerEvent::POINTER_ACTION_LEAVE_WINDOW ||
2138         action == PointerEvent::POINTER_ACTION_PULL_IN_WINDOW ||
2139         action == PointerEvent::POINTER_ACTION_PULL_OUT_WINDOW) {
2140         return;
2141     }
2142     if (pointerEvent->GetDeviceId() == COLLABORATION_REMOTE_DEVICE_ID &&
2143         stateMachine->IsRunningLockEnabled(RunningLockType::RUNNINGLOCK_COORDINATION) &&
2144         stateMachine->GetState() == PowerState::AWAKE) {
2145         stateMachine->SetState(PowerState::DIM, StateChangeReason::STATE_CHANGE_REASON_COORDINATION, true);
2146         POWER_HILOGD(FEATURE_INPUT, "remote pointer event in coordinated state, override screen off time");
2147     }
2148 }
2149 
OnInputEvent(std::shared_ptr<AxisEvent> axisEvent) const2150 void PowerMgrInputMonitor::OnInputEvent(std::shared_ptr<AxisEvent> axisEvent) const {};
2151 #endif
2152 
2153 #ifdef POWER_MANAGER_ENABLE_EXTERNAL_SCREEN_MANAGEMENT
ExternalScreenInit()2154 void PowerMgrService::ExternalScreenInit()
2155 {
2156     auto stateMachine = pms->GetPowerStateMachine();
2157     auto suspendController = pms->GetSuspendController();
2158     auto wakeupController = pms->GetWakeupController();
2159     if (stateMachine == nullptr || suspendController == nullptr || wakeupController == nullptr) {
2160         POWER_HILOGE(COMP_SVC, "Get important instance error");
2161         return;
2162     }
2163 
2164     std::vector<uint64_t> screenIds;
2165     auto ret = Rosen::ScreenManagerLite::GetInstance().GetPhysicalScreenIds(screenIds);
2166     if (ret != Rosen::DMError::DM_OK) {
2167         POWER_HILOGE(COMP_SVC, "Failed to get physical screen ids");
2168         return;
2169     }
2170     POWER_HILOGI(COMP_SVC, "Number of current physical screen is %{public}u", static_cast<uint32_t>(screenIds.size()));
2171     if (screenIds.size() <= 1) { // there's at least a main screen, we only care about external screen
2172         return;
2173     }
2174 
2175     bool isSwitchOpen = stateMachine->IsSwitchOpen();
2176     bool isScreenOn = stateMachine->IsScreenOn();
2177     stateMachine->SetExternalScreenNumber(static_cast<int32_t>(screenIds.size()) - 1);
2178     POWER_HILOGI(
2179         COMP_SVC, "Init external screen, isSwitchOpen: %{public}d, isScreenOn: %{public}d", isSwitchOpen, isScreenOn);
2180     if (isScreenOn) {
2181         wakeupController->PowerOnAllScreens(WakeupDeviceType::WAKEUP_DEVICE_EX_SCREEN_INIT);
2182         if (!isSwitchOpen) {
2183             suspendController->PowerOffInternalScreen(SuspendDeviceType::SUSPEND_DEVICE_REASON_SWITCH);
2184         }
2185     } else {
2186         suspendController->PowerOffAllScreens(SuspendDeviceType::SUSPEND_DEVICE_REASON_EX_SCREEN_INIT);
2187     }
2188 }
2189 
RegisterExternalScreenListener()2190 void PowerMgrService::RegisterExternalScreenListener()
2191 {
2192     auto ret = Rosen::DMError::DM_OK;
2193     if (externalScreenListener_ == nullptr) {
2194         externalScreenListener_ = sptr<ExternalScreenListener>::MakeSptr();
2195         ret = Rosen::ScreenManagerLite::GetInstance().RegisterScreenListener(externalScreenListener_);
2196         POWER_HILOGI(COMP_SVC, "Register external screen listener, ret: %{public}d", static_cast<int32_t>(ret));
2197     }
2198 
2199     if (abnormalExScreenListener_ == nullptr) {
2200         abnormalExScreenListener_ = sptr<AbnormalExternalScreenConnectListener>::MakeSptr();
2201         ret = Rosen::ScreenManagerLite::GetInstance().RegisterAbnormalScreenConnectChangeListener(
2202             abnormalExScreenListener_);
2203         POWER_HILOGI(
2204             COMP_SVC, "Register abnormal external screen listener, ret: %{public}d", static_cast<int32_t>(ret));
2205     }
2206 }
2207 
UnRegisterExternalScreenListener()2208 void PowerMgrService::UnRegisterExternalScreenListener()
2209 {
2210     auto ret = Rosen::DMError::DM_OK;
2211     if (externalScreenListener_ != nullptr) {
2212         ret = Rosen::ScreenManagerLite::GetInstance().UnregisterScreenListener(externalScreenListener_);
2213         externalScreenListener_ = nullptr;
2214         POWER_HILOGI(COMP_SVC, "Unregister external screen listener, ret: %{public}d", static_cast<int32_t>(ret));
2215     }
2216 
2217     if (abnormalExScreenListener_ != nullptr) {
2218         ret = Rosen::ScreenManagerLite::GetInstance().UnregisterAbnormalScreenConnectChangeListener(
2219             abnormalExScreenListener_);
2220         abnormalExScreenListener_ = nullptr;
2221         POWER_HILOGI(
2222             COMP_SVC, "Unregister abnormal external screen listener, ret: %{public}d", static_cast<int32_t>(ret));
2223     }
2224 }
2225 
OnConnect(uint64_t screenId)2226 void PowerMgrService::ExternalScreenListener::OnConnect(uint64_t screenId)
2227 {
2228     if (screenId >= VIRTUAL_SCREEN_START_ID) {
2229         POWER_HILOGI(
2230             COMP_SVC, "Ignore virtual screen connecting event, screenId: %{public}u", static_cast<uint32_t>(screenId));
2231         return;
2232     }
2233     auto powerStateMachine = pms->GetPowerStateMachine();
2234     auto suspendController = pms->GetSuspendController();
2235     auto wakeupController = pms->GetWakeupController();
2236     if (powerStateMachine == nullptr || suspendController == nullptr || wakeupController == nullptr) {
2237         POWER_HILOGE(COMP_SVC, "Get important instance error, screenId: %{public}u", static_cast<uint32_t>(screenId));
2238         return;
2239     }
2240 
2241     int32_t curExternalScreenNum = powerStateMachine->GetExternalScreenNumber() + 1;
2242     powerStateMachine->SetExternalScreenNumber(curExternalScreenNum);
2243     bool isSwitchOpen = powerStateMachine->IsSwitchOpen();
2244     bool isScreenOn = powerStateMachine->IsScreenOnAcqLock();
2245     POWER_HILOGI(COMP_SVC,
2246         "External screen is connected, screenId: %{public}u, externalScreenNumber: %{public}d, isSwitchOpen: "
2247         "%{public}d, isScreenOn: %{public}d",
2248         static_cast<uint32_t>(screenId), curExternalScreenNum, isSwitchOpen, isScreenOn);
2249 
2250     if (isSwitchOpen && isScreenOn) {
2251         wakeupController->PowerOnAllScreens(WakeupDeviceType::WAKEUP_DEVICE_SCREEN_CONNECT);
2252         pms->RefreshActivity(GetTickCount(), UserActivityType::USER_ACTIVITY_TYPE_CABLE, false);
2253     } else if (isSwitchOpen && !isScreenOn) {
2254         POWER_HILOGI(FEATURE_SUSPEND, "[UL_POWER] Skip wakeup by external screen connected when screen off");
2255     } else if (!isSwitchOpen && !isScreenOn) {
2256         suspendController->PowerOffAllScreens(SuspendDeviceType::SUSPEND_DEVICE_REASON_SWITCH);
2257     } else {
2258         if (curExternalScreenNum > 1) {
2259             // When the power state is ON and there are 2 external screens or more, power off closed internal screen
2260             POWER_HILOGI(FEATURE_SUSPEND, "[UL_POWER] Power on all screens except for the closed internal screen");
2261             wakeupController->PowerOnAllScreens(WakeupDeviceType::WAKEUP_DEVICE_SCREEN_CONNECT);
2262             suspendController->PowerOffInternalScreen(SuspendDeviceType::SUSPEND_DEVICE_REASON_SWITCH);
2263         }
2264     }
2265 }
2266 
OnDisconnect(uint64_t screenId)2267 void PowerMgrService::ExternalScreenListener::OnDisconnect(uint64_t screenId)
2268 {
2269     if (screenId >= VIRTUAL_SCREEN_START_ID) {
2270         POWER_HILOGI(COMP_SVC, "Ignore virtual screen disconnecting event, screenId: %{public}u",
2271             static_cast<uint32_t>(screenId));
2272         return;
2273     }
2274     auto powerStateMachine = pms->GetPowerStateMachine();
2275     auto suspendController = pms->GetSuspendController();
2276     if (powerStateMachine == nullptr || suspendController == nullptr) {
2277         POWER_HILOGE(COMP_SVC, "Get important instance error, screenId:%{public}u", static_cast<uint32_t>(screenId));
2278         return;
2279     }
2280 
2281     int32_t curExternalScreenNum = std::max(powerStateMachine->GetExternalScreenNumber() - 1, 0);
2282     powerStateMachine->SetExternalScreenNumber(curExternalScreenNum);
2283     bool isSwitchOpen = powerStateMachine->IsSwitchOpen();
2284     bool isScreenOn = powerStateMachine->IsScreenOn();
2285     POWER_HILOGI(COMP_SVC,
2286         "External screen is disconnected, screenId: %{public}u, externalScreenNumber: %{public}d, isSwitchOpen: "
2287         "%{public}d, isScreenOn: %{public}d",
2288         static_cast<uint32_t>(screenId), curExternalScreenNum, isSwitchOpen, isScreenOn);
2289 
2290     if (isSwitchOpen && isScreenOn) {
2291         pms->RefreshActivity(GetTickCount(), UserActivityType::USER_ACTIVITY_TYPE_CABLE, false);
2292     } else if (!isSwitchOpen && isScreenOn) {
2293         // When there's no external screen, we should suspend the device, oterwise do nothing
2294         if (curExternalScreenNum == 0) {
2295             POWER_HILOGI(
2296                 FEATURE_SUSPEND, "[UL_POWER] Suspend device when external screen is disconnected and switch is closed");
2297             suspendController->ExecSuspendMonitorByReason(SuspendDeviceType::SUSPEND_DEVICE_REASON_SWITCH);
2298         } else {
2299             POWER_HILOGI(FEATURE_SUSPEND,
2300                 "[UL_POWER] Refresh device rather than suspend device when there's still external screen");
2301             pms->RefreshActivity(GetTickCount(), UserActivityType::USER_ACTIVITY_TYPE_CABLE, false);
2302         }
2303     }
2304 }
2305 
NotifyAbnormalScreenConnectChange(uint64_t screenId)2306 void PowerMgrService::AbnormalExternalScreenConnectListener::NotifyAbnormalScreenConnectChange(uint64_t screenId)
2307 {
2308     if (screenId >= VIRTUAL_SCREEN_START_ID) {
2309         POWER_HILOGI(COMP_SVC, "Ignore virtual screen abnormal connecting event, screenId: %{public}u",
2310             static_cast<uint32_t>(screenId));
2311         return;
2312     }
2313     auto powerStateMachine = pms->GetPowerStateMachine();
2314     auto suspendController = pms->GetSuspendController();
2315     auto wakeupController = pms->GetWakeupController();
2316     if (powerStateMachine == nullptr || suspendController == nullptr || wakeupController == nullptr) {
2317         POWER_HILOGE(COMP_SVC, "Get important instance error, screenId: %{public}u", static_cast<uint32_t>(screenId));
2318         return;
2319     }
2320 
2321     bool isSwitchOpen = powerStateMachine->IsSwitchOpen();
2322     bool isScreenOn = powerStateMachine->IsScreenOn();
2323     POWER_HILOGI(COMP_SVC,
2324         "Received abnormal external screen connecting event, screenId: %{public}u, isSwitchOpen: %{public}d, "
2325         "isScreenOn: %{public}d",
2326         static_cast<uint32_t>(screenId), isSwitchOpen, isScreenOn);
2327     if (isScreenOn) {
2328         wakeupController->PowerOnAllScreens(WakeupDeviceType::WAKEUP_DEVICE_ABNORMAL_SCREEN_CONNECT);
2329         if (!isSwitchOpen) {
2330             suspendController->PowerOffInternalScreen(SuspendDeviceType::SUSPEND_DEVICE_REASON_SWITCH);
2331         }
2332     }
2333 }
2334 #endif
2335 
SubscribeCommonEvent()2336 void PowerMgrService::SubscribeCommonEvent()
2337 {
2338     using namespace OHOS::EventFwk;
2339     MatchingSkills matchingSkills;
2340     matchingSkills.AddEvent(CommonEventSupport::COMMON_EVENT_USER_SWITCHED);
2341 #ifdef POWER_MANAGER_ENABLE_CHARGING_TYPE_SETTING
2342     matchingSkills.AddEvent(CommonEventSupport::COMMON_EVENT_POWER_CONNECTED);
2343     matchingSkills.AddEvent(CommonEventSupport::COMMON_EVENT_POWER_DISCONNECTED);
2344 #endif
2345     CommonEventSubscribeInfo subscribeInfo(matchingSkills);
2346     subscribeInfo.SetThreadMode(CommonEventSubscribeInfo::ThreadMode::COMMON);
2347     if (!subscriberPtr_) {
2348         subscriberPtr_ = std::make_shared<PowerCommonEventSubscriber>(subscribeInfo);
2349     }
2350     bool result = CommonEventManager::SubscribeCommonEvent(subscriberPtr_);
2351     if (!result) {
2352         POWER_HILOGE(COMP_SVC, "Subscribe COMMON_EVENT failed");
2353     }
2354 }
2355 
UnregisterAllSettingObserver()2356 void PowerMgrService::UnregisterAllSettingObserver()
2357 {
2358     auto pms = DelayedSpSingleton<PowerMgrService>::GetInstance();
2359     if (pms == nullptr) {
2360         POWER_HILOGI(COMP_SVC, "get PowerMgrService fail");
2361         return;
2362     }
2363     auto stateMachine = pms->GetPowerStateMachine();
2364     auto suspendController = pms->GetSuspendController();
2365     auto wakeupController = pms->GetWakeupController();
2366     if (stateMachine == nullptr || suspendController == nullptr || wakeupController == nullptr) {
2367         POWER_HILOGE(COMP_SVC, "get stateMachine, suspendController or wakeupController fail");
2368         return;
2369     }
2370 
2371 #ifdef POWER_DOUBLECLICK_ENABLE
2372     SettingHelper::UnregisterSettingWakeupDoubleObserver();
2373 #endif
2374 #ifdef POWER_PICKUP_ENABLE
2375     SettingHelper::UnregisterSettingWakeupPickupObserver();
2376 #endif
2377     wakeupController->UnregisterSettingsObserver();
2378 #ifdef POWER_MANAGER_ENABLE_CHARGING_TYPE_SETTING
2379     suspendController->UnregisterSettingsObserver();
2380     stateMachine->UnregisterDisplayOffTimeObserver();
2381 #endif
2382 }
2383 
RegisterAllSettingObserver()2384 void PowerMgrService::RegisterAllSettingObserver()
2385 {
2386     auto pms = DelayedSpSingleton<PowerMgrService>::GetInstance();
2387     if (pms == nullptr) {
2388         POWER_HILOGI(COMP_SVC, "get PowerMgrService fail");
2389         return;
2390     }
2391 
2392 #ifdef POWER_DOUBLECLICK_ENABLE
2393     pms->RegisterSettingWakeupDoubleClickObservers();
2394 #endif
2395 #ifdef POWER_PICKUP_ENABLE
2396     pms->RegisterSettingWakeupPickupGestureObserver();
2397 #endif
2398     pms->WakeupControllerInit();
2399 #ifdef POWER_MANAGER_ENABLE_CHARGING_TYPE_SETTING
2400     pms->SuspendControllerInit();
2401     pms->UpdateSettingInvalidDisplayOffTime(); // update setting value if invalid before register
2402     auto stateMachine = pms->GetPowerStateMachine();
2403     if (stateMachine == nullptr) {
2404         POWER_HILOGE(COMP_SVC, "get PowerStateMachine fail");
2405         return;
2406     }
2407     stateMachine->RegisterDisplayOffTimeObserver();
2408 #endif
2409 }
2410 
GetSettingDisplayOffTime(int64_t defaultTime)2411 int64_t PowerMgrService::GetSettingDisplayOffTime(int64_t defaultTime)
2412 {
2413     int64_t settingTime = defaultTime;
2414 #ifdef POWER_MANAGER_ENABLE_CHARGING_TYPE_SETTING
2415     auto pms = DelayedSpSingleton<PowerMgrService>::GetInstance();
2416     if (pms == nullptr) {
2417         POWER_HILOGE(FEATURE_POWER_MODE, "get PowerMgrService fail");
2418         return settingTime;
2419     }
2420     if (pms->IsPowerConnected()) {
2421         settingTime = SettingHelper::GetSettingDisplayAcScreenOffTime(defaultTime);
2422     } else {
2423         settingTime = SettingHelper::GetSettingDisplayDcScreenOffTime(defaultTime);
2424     }
2425 #else
2426     settingTime = SettingHelper::GetSettingDisplayOffTime(defaultTime);
2427 #endif
2428     return settingTime;
2429 }
2430 
2431 #ifdef POWER_MANAGER_ENABLE_CHARGING_TYPE_SETTING
UpdateSettingInvalidDisplayOffTime()2432 void PowerMgrService::UpdateSettingInvalidDisplayOffTime()
2433 {
2434     if (!SettingHelper::IsSettingDisplayAcScreenOffTimeValid()) {
2435         SettingHelper::SetSettingDisplayAcScreenOffTime(PowerStateMachine::DEFAULT_AC_DISPLAY_OFF_TIME_MS);
2436     }
2437     if (!SettingHelper::IsSettingDisplayDcScreenOffTimeValid()) {
2438         SettingHelper::SetSettingDisplayDcScreenOffTime(PowerStateMachine::DEFAULT_DC_DISPLAY_OFF_TIME_MS);
2439     }
2440 }
2441 
OnPowerConnectStatusChanged(PowerConnectStatus status)2442 void PowerCommonEventSubscriber::OnPowerConnectStatusChanged(PowerConnectStatus status)
2443 {
2444     auto power = DelayedSpSingleton<PowerMgrService>::GetInstance();
2445     if (power == nullptr) {
2446         POWER_HILOGE(COMP_SVC, "get PowerMgrService fail");
2447         return;
2448     }
2449     power->SetPowerConnectStatus(status);
2450 
2451     auto suspendController = power->GetSuspendController();
2452     if (suspendController == nullptr) {
2453         POWER_HILOGE(COMP_SVC, "get suspendController fail");
2454         return;
2455     }
2456     suspendController->UpdateSuspendSources();
2457 
2458     auto stateMachine = power->GetPowerStateMachine();
2459     if (stateMachine == nullptr) {
2460         POWER_HILOGE(COMP_SVC, "get PowerStateMachine fail");
2461         return;
2462     }
2463     stateMachine->DisplayOffTimeUpdateFunc();
2464 
2465     power->OnChargeStateChanged(); // should be called after suspend sources settings updated
2466 }
2467 #endif
2468 
OnReceiveEvent(const OHOS::EventFwk::CommonEventData & data)2469 void PowerCommonEventSubscriber::OnReceiveEvent(const OHOS::EventFwk::CommonEventData &data)
2470 {
2471     std::string action = data.GetWant().GetAction();
2472     auto pms = DelayedSpSingleton<PowerMgrService>::GetInstance();
2473     if (pms == nullptr) {
2474         POWER_HILOGI(COMP_SVC, "get PowerMgrService fail");
2475         return;
2476     }
2477     if (action == OHOS::EventFwk::CommonEventSupport::COMMON_EVENT_USER_SWITCHED) {
2478         pms->UnregisterAllSettingObserver();    // unregister old user observer
2479         SettingHelper::UpdateCurrentUserId();   // update user Id
2480         pms->RegisterAllSettingObserver();      // register new user observer
2481 #ifdef POWER_MANAGER_ENABLE_CHARGING_TYPE_SETTING
2482     } else if (action == OHOS::EventFwk::CommonEventSupport::COMMON_EVENT_POWER_CONNECTED) {
2483         OnPowerConnectStatusChanged(PowerConnectStatus::POWER_CONNECT_AC);
2484     } else if (action == OHOS::EventFwk::CommonEventSupport::COMMON_EVENT_POWER_DISCONNECTED) {
2485         OnPowerConnectStatusChanged(PowerConnectStatus::POWER_CONNECT_DC);
2486 #endif
2487     }
2488 }
2489 
IsRunningLockEnabled(const RunningLockType type,bool & result)2490 PowerErrors PowerMgrService::IsRunningLockEnabled(const RunningLockType type, bool& result)
2491 {
2492     if (!Permission::IsPermissionGranted("ohos.permission.RUNNING_LOCK")) {
2493         return PowerErrors::ERR_PERMISSION_DENIED;
2494     }
2495     std::lock_guard lock(lockMutex_);
2496     uint32_t num = runningLockMgr_->GetValidRunningLockNum(type);
2497     POWER_HILOGI(COMP_SVC, "Hold running lock type:%{public}u, num:%{public}u", static_cast<uint32_t>(type), num);
2498     result = num > 0 ? true : false;
2499     return PowerErrors::ERR_OK;
2500 }
2501 
RefreshActivity(int64_t callTimeMs,UserActivityType type,const std::string & refreshReason)2502 PowerErrors PowerMgrService::RefreshActivity(
2503     int64_t callTimeMs, UserActivityType type, const std::string& refreshReason)
2504 {
2505     if (!Permission::IsSystem()) {
2506         POWER_HILOGI(FEATURE_ACTIVITY, "RefreshActivity failed, System permission intercept");
2507         return PowerErrors::ERR_SYSTEM_API_DENIED;
2508     }
2509     if (!Permission::IsPermissionGranted("ohos.permission.REFRESH_USER_ACTION")) {
2510         POWER_HILOGI(FEATURE_ACTIVITY, "RefreshActivity failed, The caller does not have the permission");
2511         return PowerErrors::ERR_PERMISSION_DENIED;
2512     }
2513     pid_t pid = IPCSkeleton::GetCallingPid();
2514     auto uid = IPCSkeleton::GetCallingUid();
2515     POWER_HILOGI(FEATURE_ACTIVITY,
2516         "Try to refresh activity, pid: %{public}d, uid: %{public}d, activity type: %{public}u, reason: %{public}s",
2517         pid, uid, type, refreshReason.c_str());
2518     return RefreshActivityInner(callTimeMs, type, true) ? PowerErrors::ERR_OK :
2519         PowerErrors::ERR_FREQUENT_FUNCTION_CALL;
2520 }
2521 } // namespace PowerMgr
2522 } // namespace OHOS
2523