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 #ifndef POWERMGR_POWER_MGR_SERVICE_H
17 #define POWERMGR_POWER_MGR_SERVICE_H
18 
19 #include <iremote_object.h>
20 #include <system_ability.h>
21 
22 #include "actions/idevice_power_action.h"
23 #include "ipower_mgr.h"
24 #include "power_mgr_notify.h"
25 #include "power_mgr_stub.h"
26 #include "power_mode_module.h"
27 #include "power_save_mode.h"
28 #include "power_state_machine.h"
29 #include "running_lock_mgr.h"
30 #include "screen_off_pre_controller.h"
31 #include "shutdown_controller.h"
32 #include "shutdown_dialog.h"
33 #include "sp_singleton.h"
34 #include "suspend_controller.h"
35 #include "wakeup_controller.h"
36 
37 #include "common_event_subscriber.h"
38 
39 #ifdef POWER_MANAGER_WAKEUP_ACTION
40 #include "wakeup_action_controller.h"
41 #endif
42 
43 namespace OHOS {
44 namespace PowerMgr {
45 #ifdef POWER_MANAGER_ENABLE_CHARGING_TYPE_SETTING
46 typedef enum {
47     POWER_CONNECT_INVALID = -1,
48     POWER_CONNECT_DC = 0, // DC for Direct Current, means battery supply
49     POWER_CONNECT_AC = 1, // AC for Alternating Current, means charing supply
50 } PowerConnectStatus;
51 #endif
52 class RunningLockMgr;
53 class PowerMgrService final : public SystemAbility, public PowerMgrStub {
54     DECLARE_SYSTEM_ABILITY(PowerMgrService)
55     DECLARE_DELAYED_SP_SINGLETON(PowerMgrService);
56 
57 public:
58     virtual void OnStart() override;
59     virtual void OnStop() override;
60     virtual void OnRemoveSystemAbility(int32_t systemAbilityId, const std::string& deviceId) override;
61     virtual void OnAddSystemAbility(int32_t systemAbilityId, const std::string& deviceId) override;
62     int32_t Dump(int32_t fd, const std::vector<std::u16string>& args) override;
63     virtual PowerErrors RebootDevice(const std::string& reason) override;
64     virtual PowerErrors RebootDeviceForDeprecated(const std::string& reason) override;
65     virtual PowerErrors ShutDownDevice(const std::string& reason) override;
66     virtual PowerErrors SetSuspendTag(const std::string& tag) override;
67     virtual PowerErrors SuspendDevice(int64_t callTimeMs, SuspendDeviceType reason, bool suspendImmed) override;
68     virtual PowerErrors WakeupDevice(int64_t callTimeMs, WakeupDeviceType reason, const std::string& details) override;
WakeupDeviceAsync(int64_t callTimeMs,WakeupDeviceType reason,const std::string & details)69     virtual void WakeupDeviceAsync(int64_t callTimeMs, WakeupDeviceType reason, const std::string& details) override {};
70     virtual bool RefreshActivity(int64_t callTimeMs, UserActivityType type, bool needChangeBacklight) override;
71     bool RefreshActivityInner(int64_t callTimeMs, UserActivityType type, bool needChangeBacklight);
72     virtual PowerErrors OverrideScreenOffTime(int64_t timeout) override;
73     virtual PowerErrors RestoreScreenOffTime() override;
74     virtual PowerState GetState() override;
75     virtual bool IsScreenOn(bool needPrintLog = true) override;
76     virtual bool IsFoldScreenOn() override;
77     virtual bool IsCollaborationScreenOn() override;
78     virtual PowerErrors ForceSuspendDevice(int64_t callTimeMs) override;
79     virtual PowerErrors Hibernate(bool clearMemory) override;
80     virtual PowerErrors CreateRunningLock(
81         const sptr<IRemoteObject>& remoteObj, const RunningLockInfo& runningLockInfo) override;
82     virtual bool ReleaseRunningLock(const sptr<IRemoteObject>& remoteObj, const std::string& name = "") override;
83     virtual bool IsRunningLockTypeSupported(RunningLockType type) override;
84     virtual bool UpdateWorkSource(const sptr<IRemoteObject>& remoteObj,
85         const std::map<int32_t, std::string>& workSources) override;
86     virtual PowerErrors Lock(const sptr<IRemoteObject>& remoteObj, int32_t timeOutMs = -1) override;
87     virtual PowerErrors UnLock(const sptr<IRemoteObject>& remoteObj, const std::string& name = "") override;
88     virtual bool QueryRunningLockLists(std::map<std::string, RunningLockInfo>& runningLockLists) override;
89     virtual void ForceUnLock(const sptr<IRemoteObject>& remoteObj);
90     virtual bool IsUsed(const sptr<IRemoteObject>& remoteObj) override;
91     virtual bool ProxyRunningLock(bool isProxied, pid_t pid, pid_t uid) override;
92     virtual bool ProxyRunningLocks(bool isProxied,
93         const std::vector<std::pair<pid_t, pid_t>>& processInfos) override;
94     virtual bool ResetRunningLocks() override;
95     virtual bool RegisterPowerStateCallback(const sptr<IPowerStateCallback>& callback, bool isSync = true) override;
96     virtual bool UnRegisterPowerStateCallback(const sptr<IPowerStateCallback>& callback) override;
97 
98     virtual bool RegisterSyncSleepCallback(const sptr<ISyncSleepCallback>& callback, SleepPriority priority) override;
99     virtual bool UnRegisterSyncSleepCallback(const sptr<ISyncSleepCallback>& callback) override;
100     virtual bool RegisterSyncHibernateCallback(const sptr<ISyncHibernateCallback>& callback) override;
101     virtual bool UnRegisterSyncHibernateCallback(const sptr<ISyncHibernateCallback>& callback) override;
102 
103     virtual bool RegisterPowerModeCallback(const sptr<IPowerModeCallback>& callback) override;
104     virtual bool UnRegisterPowerModeCallback(const sptr<IPowerModeCallback>& callback) override;
105 
106     virtual bool RegisterScreenStateCallback(int32_t remainTime, const sptr<IScreenOffPreCallback>& callback) override;
107     virtual bool UnRegisterScreenStateCallback(const sptr<IScreenOffPreCallback>& callback) override;
108 
109     virtual bool RegisterRunningLockCallback(const sptr<IPowerRunninglockCallback>& callback) override;
110     virtual bool UnRegisterRunningLockCallback(const sptr<IPowerRunninglockCallback>& callback) override;
111     virtual bool SetDisplaySuspend(bool enable) override;
112     virtual PowerErrors SetDeviceMode(const PowerMode& mode) override;
113     virtual PowerMode GetDeviceMode() override;
114     virtual std::string ShellDump(const std::vector<std::string>& args, uint32_t argc) override;
115     virtual PowerErrors IsStandby(bool& isStandby) override;
116     virtual PowerErrors SetForceTimingOut(bool enabled, const sptr<IRemoteObject>& token) override;
117     virtual PowerErrors LockScreenAfterTimingOut(
118         bool enabledLockScreen, bool checkLock, bool sendScreenOffEvent, const sptr<IRemoteObject>& token) override;
119 
120     void RegisterShutdownCallback(const sptr<ITakeOverShutdownCallback>& callback, ShutdownPriority priority) override;
121     void UnRegisterShutdownCallback(const sptr<ITakeOverShutdownCallback>& callback) override;
122 
123     void RegisterShutdownCallback(const sptr<IAsyncShutdownCallback>& callback, ShutdownPriority priority) override;
124     void UnRegisterShutdownCallback(const sptr<IAsyncShutdownCallback>& callback) override;
125     void RegisterShutdownCallback(const sptr<ISyncShutdownCallback>& callback, ShutdownPriority priority) override;
126     void UnRegisterShutdownCallback(const sptr<ISyncShutdownCallback>& callback) override;
127 
128     void HandleKeyEvent(int32_t keyCode);
129     void HandlePointEvent(int32_t type);
130     void KeyMonitorCancel();
131     void SwitchSubscriberInit();
132     void SwitchSubscriberCancel();
133     void HallSensorSubscriberInit();
134     void HallSensorSubscriberCancel();
135     bool CheckDialogFlag();
136     void InputMonitorInit();
137     void InputMonitorCancel();
138     bool CheckDialogAndShuttingDown();
139     void SuspendControllerInit();
140     void WakeupControllerInit();
141 #ifdef POWER_MANAGER_POWER_ENABLE_S4
142     void HibernateControllerInit();
143 #endif
144     bool IsCollaborationState();
145     void QueryRunningLockListsInner(std::map<std::string, RunningLockInfo>& runningLockLists);
146     static void RegisterSettingWakeupPickupGestureObserver();
147     static void WakeupPickupGestureSettingUpdateFunc(const std::string& key);
148     static void RegisterSettingWakeupDoubleClickObservers();
149     static void WakeupDoubleClickSettingUpdateFunc(const std::string& key);
150     static bool GetSettingWakeupDoubleClick(const std::string& key = SETTING_POWER_WAKEUP_DOUBLE_KEY);
151     static void RegisterSettingPowerModeObservers();
152     static void PowerModeSettingUpdateFunc(const std::string& key);
153     static void RegisterSettingWakeUpLidObserver();
154     static void WakeupLidSettingUpdateFunc(const std::string& key);
155 #ifdef POWER_MANAGER_WAKEUP_ACTION
156     void WakeupActionControllerInit();
157 #endif
158     void VibratorInit();
159     void Reset();
160     void KeepScreenOnInit();
161     void KeepScreenOn(bool isOpenOn);
162     void UnregisterAllSettingObserver();
163     void RegisterAllSettingObserver();
164     int64_t GetSettingDisplayOffTime(int64_t defaultTime);
165 #ifdef POWER_MANAGER_ENABLE_CHARGING_TYPE_SETTING
GetPowerConnectStatus()166     PowerConnectStatus GetPowerConnectStatus() const
167     {
168         return powerConnectStatus_;
169     }
SetPowerConnectStatus(PowerConnectStatus status)170     void SetPowerConnectStatus(PowerConnectStatus status)
171     {
172         powerConnectStatus_ = status;
173     }
174     void PowerConnectStatusInit();
175     bool IsPowerConnected();
176     void UpdateSettingInvalidDisplayOffTime();
177 #endif
178 
GetRunningLockMgr()179     std::shared_ptr<RunningLockMgr> GetRunningLockMgr() const
180     {
181         return runningLockMgr_;
182     }
183 
GetPowerStateMachine()184     std::shared_ptr<PowerStateMachine> GetPowerStateMachine() const
185     {
186         return powerStateMachine_;
187     }
188 
GetPowerMgrNotify()189     std::shared_ptr<PowerMgrNotify> GetPowerMgrNotify() const
190     {
191         return powerMgrNotify_;
192     }
193 
GetSuspendController()194     std::shared_ptr<SuspendController> GetSuspendController() const
195     {
196         return suspendController_;
197     }
198 #ifdef POWER_MANAGER_POWER_ENABLE_S4
GetHibernateController()199     std::shared_ptr<HibernateController> GetHibernateController() const
200     {
201         return hibernateController_;
202     }
203 #endif
GetWakeupController()204     std::shared_ptr<WakeupController> GetWakeupController() const
205     {
206         return wakeupController_;
207     }
GetScreenOffPreController()208     std::shared_ptr<ScreenOffPreController> GetScreenOffPreController() const
209     {
210         return screenOffPreController_;
211     }
212 #ifdef POWER_MANAGER_WAKEUP_ACTION
GetWakeupActionController()213     std::shared_ptr<WakeupActionController> GetWakeupActionController() const
214     {
215         return wakeupActionController_;
216     }
217 #endif
GetShutdownDialog()218     ShutdownDialog& GetShutdownDialog()
219     {
220         return shutdownDialog_;
221     }
IsServiceReady()222     bool IsServiceReady() const
223     {
224         return ready_;
225     }
SetDisplayOffTime(int64_t time)226     void SetDisplayOffTime(int64_t time)
227     {
228         powerStateMachine_->SetDisplayOffTime(time);
229     }
SetSleepTime(int64_t time)230     void SetSleepTime(int64_t time)
231     {
232         powerStateMachine_->SetSleepTime(time);
233     }
234 
EnableMock(IDeviceStateAction * powerState,IDeviceStateAction * shutdownState,IDevicePowerAction * powerAction,IRunningLockAction * lockAction)235     void EnableMock(IDeviceStateAction* powerState, IDeviceStateAction* shutdownState, IDevicePowerAction* powerAction,
236         IRunningLockAction* lockAction)
237     {
238         POWER_HILOGI(LABEL_TEST, "Service EnableMock:%{public}d", mockCount_++);
239         runningLockMgr_->EnableMock(lockAction);
240         powerStateMachine_->EnableMock(powerState);
241         shutdownController_->EnableMock(powerAction, shutdownState);
242     }
243 
EnableShutdownMock(ShutdownController * shutdownAction)244     void EnableShutdownMock(ShutdownController* shutdownAction)
245     {
246         POWER_HILOGI(LABEL_TEST, "need to mock shutdownController");
247         std::unique_ptr<ShutdownController> mock(shutdownAction);
248         shutdownController_.reset();
249         shutdownController_ = std::move(mock);
250     }
251 
MockProximity(uint32_t status)252     void MockProximity(uint32_t status)
253     {
254         POWER_HILOGI(LABEL_TEST, "MockProximity: fun is start");
255         runningLockMgr_->SetProximity(status);
256         POWER_HILOGI(LABEL_TEST, "MockProximity: fun is end");
257     }
MockSystemWakeup()258     void MockSystemWakeup()
259     {
260         PowerStateMachine::onWakeup();
261     }
GetShutdownController()262     std::shared_ptr<ShutdownController> GetShutdownController()
263     {
264         return shutdownController_;
265     }
266 
267     std::shared_ptr<SuspendController> suspendController_ = nullptr;
268     std::shared_ptr<WakeupController> wakeupController_ = nullptr;
269 #ifdef POWER_MANAGER_POWER_ENABLE_S4
270     std::shared_ptr<HibernateController> hibernateController_ = nullptr;
271 #endif
272     std::shared_ptr<ScreenOffPreController> screenOffPreController_ = nullptr;
273 #ifdef POWER_MANAGER_WAKEUP_ACTION
274     std::shared_ptr<WakeupActionController> wakeupActionController_ = nullptr;
275 #endif
276 #ifdef HAS_SENSORS_SENSOR_PART
277     static bool isInLidMode_;
278 #endif
279 
280 private:
281     class WakeupRunningLock {
282     public:
283         WakeupRunningLock();
284         ~WakeupRunningLock();
285     private:
286         sptr<IRemoteObject> token_;
287     };
288 
289     class InvokerDeathRecipient : public DeathRecipient {
290         using CallbackType = std::function<void(const sptr<PowerMgrService>&)>;
291 
292     public:
InvokerDeathRecipient(std::string interfaceName,CallbackType callback)293         InvokerDeathRecipient(std::string interfaceName, CallbackType callback)
294             : interfaceName_(interfaceName), callback_(callback) {};
295         virtual ~InvokerDeathRecipient() = default;
296         virtual void OnRemoteDied(const wptr<IRemoteObject>& remote) override;
297 
298     private:
299         std::string interfaceName_;
300         CallbackType callback_;
301     };
302 
303     static constexpr int32_t POWER_KEY_PRESS_DELAY_MS = 10000;
304     static constexpr int32_t INIT_KEY_MONITOR_DELAY_MS = 1000;
305     static constexpr int32_t HALL_REPORT_INTERVAL = 0;
306     static constexpr uint32_t HALL_SAMPLING_RATE = 100000000;
307     static constexpr const char* SETTING_POWER_WAKEUP_DOUBLE_KEY {"settings.power.wakeup_double_click"};
308     bool Init();
309     bool PowerStateMachineInit();
310     std::string GetBundleNameByUid(const int32_t uid);
311     RunningLockParam FillRunningLockParam(const RunningLockInfo& info, const uint64_t lockid,
312         int32_t timeOutMS = -1);
313     static void RegisterBootCompletedCallback();
314     static bool IsDeveloperMode();
315 #ifdef MSDP_MOVEMENT_ENABLE
316     void RegisterMovementCallback();
317     void UnRegisterMovementCallback();
318     void ResetMovementState();
319 #endif
320 
GetPowerModeModule()321     inline PowerModeModule& GetPowerModeModule()
322     {
323         return powerModeModule_;
324     }
325 
326 #ifdef HAS_SENSORS_SENSOR_PART
327     bool IsSupportSensor(SensorTypeId);
328     static void HallSensorCallback(SensorEvent* event);
329     SensorUser sensorUser_{};
330 #endif
331 
332     bool ready_ {false};
333     static std::atomic_bool isBootCompleted_;
334     std::mutex wakeupMutex_;
335     std::mutex suspendMutex_;
336 #ifdef POWER_MANAGER_POWER_ENABLE_S4
337     std::mutex hibernateMutex_;
338 #endif
339     std::mutex stateMutex_;
340     std::mutex shutdownMutex_;
341     std::mutex modeMutex_;
342     std::mutex screenOffPreMutex_;
343     std::mutex screenMutex_;
344     std::mutex dumpMutex_;
345     std::mutex lockMutex_;
346     std::shared_ptr<RunningLockMgr> runningLockMgr_;
347     std::shared_ptr<PowerStateMachine> powerStateMachine_;
348     std::shared_ptr<PowerMgrNotify> powerMgrNotify_;
349     std::shared_ptr<ShutdownController> shutdownController_;
350     PowerModeModule powerModeModule_;
351     ShutdownDialog shutdownDialog_;
352     uint32_t mockCount_ {0};
353     int32_t switchId_ {0};
354     int32_t doubleClickId_ {0};
355     int32_t monitorId_ {0};
356     int32_t inputMonitorId_ {-1};
357     sptr<IRemoteObject> ptoken_;
358 #ifdef POWER_MANAGER_ENABLE_CHARGING_TYPE_SETTING
359     PowerConnectStatus powerConnectStatus_ {PowerConnectStatus::POWER_CONNECT_INVALID};
360 #endif
361     void SubscribeCommonEvent();
362     std::shared_ptr<EventFwk::CommonEventSubscriber> subscriberPtr_;
363 };
364 
365 #ifdef HAS_MULTIMODALINPUT_INPUT_PART
366 class PowerMgrInputMonitor : public IInputEventConsumer {
367 public:
368     virtual void OnInputEvent(std::shared_ptr<KeyEvent> keyEvent) const;
369     virtual void OnInputEvent(std::shared_ptr<PointerEvent> pointerEvent) const;
370     virtual void OnInputEvent(std::shared_ptr<AxisEvent> axisEvent) const;
371 };
372 #endif
373 
374 class PowerCommonEventSubscriber : public EventFwk::CommonEventSubscriber {
375 public:
PowerCommonEventSubscriber(const EventFwk::CommonEventSubscribeInfo & subscribeInfo)376     explicit PowerCommonEventSubscriber(const EventFwk::CommonEventSubscribeInfo& subscribeInfo)
377         : EventFwk::CommonEventSubscriber(subscribeInfo) {}
~PowerCommonEventSubscriber()378     virtual ~PowerCommonEventSubscriber() {}
379     void OnReceiveEvent(const EventFwk::CommonEventData &data) override;
380 private:
381 #ifdef POWER_MANAGER_ENABLE_CHARGING_TYPE_SETTING
382     void OnPowerConnectStatusChanged(PowerConnectStatus status);
383 #endif
384 };
385 
386 } // namespace PowerMgr
387 } // namespace OHOS
388 #endif // POWERMGR_POWER_MGR_SERVICE_H
389