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