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