• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (c) 2021-2023 Huawei Device Co., Ltd.
3  * Licensed under the Apache License, Version 2.0 (the "License");
4  * you may not use this file except in compliance with the License.
5  * You may obtain a copy of the License at
6  *
7  *     http://www.apache.org/licenses/LICENSE-2.0
8  *
9  * Unless required by applicable law or agreed to in writing, software
10  * distributed under the License is distributed on an "AS IS" BASIS,
11  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12  * See the License for the specific language governing permissions and
13  * limitations under the License.
14  */
15 
16 #ifndef POWERMGR_POWER_STATE_MACHINE_H
17 #define POWERMGR_POWER_STATE_MACHINE_H
18 
19 #include <set>
20 #include <map>
21 #include <singleton.h>
22 
23 #include "actions/idevice_state_action.h"
24 #include "ffrt_utils.h"
25 #ifdef POWER_MANAGER_POWER_ENABLE_S4
26 #include "hibernate_controller.h"
27 #endif
28 #include "ipower_state_callback.h"
29 #include "power_common.h"
30 #include "power_state_machine_info.h"
31 #include "running_lock_info.h"
32 #include "power_mgr_notify.h"
33 #include "proximity_controller_base.h"
34 
35 namespace OHOS {
36 namespace PowerMgr {
37 class RunningLockMgr;
38 class PowerMgrService;
39 
40 struct ScreenState {
41     DisplayState state;
42     int64_t lastOnTime;
43     int64_t lastOffTime;
44 };
45 
46 struct DevicePowerState {
47     ScreenState screenState;
48     // record the last time when get wakeup event from A side
49     int64_t lastWakeupEventTime;
50     // record the last time when calling func RefreshActivityInner
51     int64_t lastRefreshActivityTime;
52     // record the last time when calling func WakeupDeviceInner
53     int64_t lastWakeupDeviceTime;
54     // record the last time when calling func SuspendDeviceInner
55     int64_t lastSuspendDeviceTime;
56 };
57 
58 enum class TransitResult {
59     SUCCESS = 0,
60     ALREADY_IN_STATE = 1,
61     LOCKING = 2,
62     HDI_ERR = 3,
63     DISPLAY_ON_ERR = 4,
64     DISPLAY_OFF_ERR = 5,
65     FORBID_TRANSIT = 6,
66     PRE_BRIGHT_ERR = 7,
67     OTHER_ERR = 99
68 };
69 
70 class PowerStateMachine : public std::enable_shared_from_this<PowerStateMachine> {
71 public:
72     PowerStateMachine(const wptr<PowerMgrService>& pms, const std::shared_ptr<FFRTTimer>& ffrtTimer = nullptr);
73     ~PowerStateMachine();
74 
75     enum {
76         CHECK_USER_ACTIVITY_TIMEOUT_MSG = 0,
77         CHECK_USER_ACTIVITY_OFF_TIMEOUT_MSG,
78         CHECK_PRE_BRIGHT_AUTH_TIMEOUT_MSG,
79         CHECK_PROXIMITY_SCREEN_OFF_MSG,
80     };
81 
82     class PowerStateCallbackDeathRecipient : public IRemoteObject::DeathRecipient {
83     public:
84         PowerStateCallbackDeathRecipient() = default;
85         virtual void OnRemoteDied(const wptr<IRemoteObject>& remote);
86         virtual ~PowerStateCallbackDeathRecipient() = default;
87     };
88 
89 #ifdef POWER_MANAGER_ENABLE_CHARGING_TYPE_SETTING
90     static constexpr int32_t DEFAULT_AC_DISPLAY_OFF_TIME_MS = 600000;
91     static constexpr int32_t DEFAULT_DC_DISPLAY_OFF_TIME_MS = 300000;
92     static constexpr int32_t DEFAULT_DISPLAY_OFF_TIME_MS = DEFAULT_DC_DISPLAY_OFF_TIME_MS;
93 #else
94     static constexpr int32_t DEFAULT_DISPLAY_OFF_TIME_MS = 30000;
95 #endif
96     static constexpr int32_t DEFAULT_SLEEP_TIME_MS = 5000;
97     static constexpr int64_t OFF_TIMEOUT_FACTOR = 5;
98     static constexpr int64_t MAX_DIM_TIME_MS = 7500;
99     static constexpr int64_t COORDINATED_STATE_SCREEN_OFF_TIME_MS = 10000;
100     static constexpr uint32_t SCREEN_CHANGE_TIMEOUT_MS = 10000;
101     static constexpr uint32_t SCREEN_CHANGE_REPORT_INTERVAL_MS = 600000;
102 
103     static void onSuspend();
104     static void onWakeup();
105     static void DisplayOffTimeUpdateFunc();
106     static void RegisterDisplayOffTimeObserver();
107     static void UnregisterDisplayOffTimeObserver();
108 
109     bool Init();
110     void InitState();
111     void SuspendDeviceInner(
112         pid_t pid, int64_t callTimeMs, SuspendDeviceType type, bool suspendImmed, bool ignoreScreenState = false);
113     void WakeupDeviceInner(
114         pid_t pid, int64_t callTimeMs, WakeupDeviceType type, const std::string& details, const std::string& pkgName);
115     void HandlePreBrightWakeUp(int64_t callTimeMs, WakeupDeviceType type, const std::string& details,
116         const std::string& pkgName, bool timeoutTriggered = false);
117     void RefreshActivityInner(pid_t pid, int64_t callTimeMs, UserActivityType type, bool needChangeBacklight);
118     bool CheckRefreshTime();
119     bool OverrideScreenOffTimeInner(int64_t timeout);
120     bool RestoreScreenOffTimeInner();
121     void ReceiveScreenEvent(bool isScreenOn);
122     bool IsScreenOn(bool needPrintLog = true);
123     bool IsFoldScreenOn();
124     bool IsCollaborationScreenOn();
125     bool CheckFFRTTaskAvailability(PowerState state, StateChangeReason reason) const;
126     bool IsTimeoutReason(StateChangeReason reason) const;
127     void Reset();
128     int64_t GetSleepTime();
129 #ifdef MSDP_MOVEMENT_ENABLE
130     bool IsMovementStateOn();
131 #endif
132 
GetState()133     PowerState GetState()
134     {
135         return currentState_;
136     };
GetStateAction()137     const std::shared_ptr<IDeviceStateAction>& GetStateAction()
138     {
139         return stateAction_;
140     };
141     bool ForceSuspendDeviceInner(pid_t pid, int64_t callTimeMs);
142 #ifdef POWER_MANAGER_POWER_ENABLE_S4
143     bool HibernateInner(bool clearMemory);
144 #endif
145     void RegisterPowerStateCallback(const sptr<IPowerStateCallback>& callback, bool isSync = true);
146     void UnRegisterPowerStateCallback(const sptr<IPowerStateCallback>& callback);
147     void SetDelayTimer(int64_t delayTime, int32_t event);
148     void CancelDelayTimer(int32_t event);
149     void ResetInactiveTimer(bool needPrintLog = true);
150     void ResetSleepTimer();
151     void SetAutoSuspend(SuspendDeviceType type, uint32_t delay);
152     bool SetState(PowerState state, StateChangeReason reason, bool force = false);
153     bool TryToCancelScreenOff();
154     void BeginPowerkeyScreenOff();
155     void EndPowerkeyScreenOff();
156     void SetDisplaySuspend(bool enable);
157     void WriteHiSysEvent(TransitResult ret, StateChangeReason reason, int32_t beginTimeMs, PowerState state);
158     bool IsTransitFailed(TransitResult ret);
159     StateChangeReason GetReasonByWakeType(WakeupDeviceType type);
160     StateChangeReason GetReasonBySuspendType(SuspendDeviceType type);
161 #ifdef POWER_MANAGER_ENABLE_EXTERNAL_SCREEN_MANAGEMENT
GetExternalScreenNumber()162     int32_t GetExternalScreenNumber() const
163     {
164         return externalScreenNumber_;
165     }
SetExternalScreenNumber(int32_t exScreenNumber)166     void SetExternalScreenNumber(int32_t exScreenNumber)
167     {
168         externalScreenNumber_ = exScreenNumber;
169     }
170 #endif
171 
172     // only use for test
GetLastSuspendDeviceTime()173     int64_t GetLastSuspendDeviceTime() const
174     {
175         return mDeviceState_.lastSuspendDeviceTime;
176     }
GetLastWakeupDeviceTime()177     int64_t GetLastWakeupDeviceTime() const
178     {
179         return mDeviceState_.lastWakeupDeviceTime;
180     }
GetLastRefreshActivityTime()181     int64_t GetLastRefreshActivityTime() const
182     {
183         return mDeviceState_.lastRefreshActivityTime;
184     }
GetLastWakeupEventTime()185     int64_t GetLastWakeupEventTime() const
186     {
187         return mDeviceState_.lastWakeupEventTime;
188     }
SetSwitchAction(uint32_t value)189     void SetSwitchAction(uint32_t value)
190     {
191         switchActionValue_ = value;
192     }
GetSwitchAction()193     uint32_t GetSwitchAction()
194     {
195         return switchActionValue_;
196     }
SetSwitchState(bool switchOpen)197     void SetSwitchState(bool switchOpen)
198     {
199         switchOpen_ = switchOpen;
200     }
IsSwitchOpen()201     bool IsSwitchOpen() const
202     {
203         return switchOpen_;
204     }
205 #ifdef POWER_MANAGER_POWER_ENABLE_S4
IsHibernating()206     bool IsHibernating() const
207     {
208         return hibernating_;
209     }
210 #endif
GetLastOnTime()211     int64_t GetLastOnTime() const
212     {
213         return mDeviceState_.screenState.lastOnTime;
214     }
215 
216     void DumpInfo(std::string& result);
217     void EnableMock(IDeviceStateAction* mockAction);
218     int64_t GetDisplayOffTime();
219     int64_t GetDimTime(int64_t displayOffTime);
220     void SetDisplayOffTime(int64_t time, bool needUpdateSetting = true);
221     void SetSleepTime(int64_t time);
222     bool IsRunningLockEnabled(RunningLockType type);
223     void SetForceTimingOut(bool enabled);
224     void LockScreenAfterTimingOut(bool enabled, bool checkScreenOnLock, bool sendScreenOffEvent);
225     bool IsSettingState(PowerState state);
226     void SetEnableDoze(bool enable);
227     bool SetDozeMode(DisplayState state);
228 
229 private:
230     enum PreBrightState : uint32_t {
231         PRE_BRIGHT_UNSTART = 0,
232         PRE_BRIGHT_STARTED,
233         PRE_BRIGHT_FINISHED,
234     };
235 
236     class SettingStateFlag {
237     public:
SettingStateFlag(PowerState state,std::shared_ptr<PowerStateMachine> owner,StateChangeReason reason)238         SettingStateFlag(PowerState state, std::shared_ptr<PowerStateMachine> owner, StateChangeReason reason)
239             : owner_(owner)
240         {
241             std::shared_ptr<PowerStateMachine> stateMachine = owner_.lock();
242             int64_t flag;
243             if (state == PowerState::DIM && reason == StateChangeReason::STATE_CHANGE_REASON_COORDINATION) {
244                 flag = static_cast<int64_t>(StateFlag::FORCE_SETTING_DIM);
245             } else {
246                 flag = static_cast<int64_t>(state);
247             }
248             stateMachine->settingStateFlag_ = flag;
249         }
250         SettingStateFlag(const SettingStateFlag&) = delete;
251         SettingStateFlag& operator=(const SettingStateFlag&) = delete;
252         SettingStateFlag(SettingStateFlag&&) = delete;
253         SettingStateFlag& operator=(SettingStateFlag&&) = delete;
~SettingStateFlag()254         ~SettingStateFlag()
255         {
256             std::shared_ptr<PowerStateMachine> stateMachine = owner_.lock();
257             stateMachine->settingStateFlag_ = static_cast<int64_t>(StateFlag::NONE);
258         }
259         enum class StateFlag : int64_t {
260             FORCE_SETTING_DIM = -3,
261             SETTING_DIM_INTERRUPTED = -2,
262             NONE = -1
263         };
264     protected:
265         std::weak_ptr<PowerStateMachine> owner_;
266     };
267     class StateController {
268     public:
StateController(PowerState state,std::shared_ptr<PowerStateMachine> owner,std::function<TransitResult (StateChangeReason)> action)269         StateController(PowerState state, std::shared_ptr<PowerStateMachine> owner,
270             std::function<TransitResult(StateChangeReason)> action)
271             : state_(state),
272             owner_(owner), action_(action)
273         {
274         }
275         ~StateController() = default;
GetState()276         PowerState GetState()
277         {
278             return state_;
279         }
280         TransitResult TransitTo(StateChangeReason reason, bool ignoreLock = false);
281         void RecordFailure(PowerState from, StateChangeReason trigger, TransitResult failReason);
282         static bool IsReallyFailed(StateChangeReason reason);
283         StateChangeReason lastReason_;
284         int64_t lastTime_ {0};
285         PowerState failFrom_;
286         StateChangeReason failTrigger_;
287         std::string failReason_;
288         int64_t failTime_ {0};
289 
290     protected:
291         bool CheckState();
292         bool NeedNotify(PowerState currentState);
293         void MatchState(PowerState& currentState, DisplayState state);
294         void CorrectState(PowerState& currentState, PowerState correctState, DisplayState state);
295         PowerState state_;
296         std::weak_ptr<PowerStateMachine> owner_;
297         std::function<TransitResult(StateChangeReason)> action_;
298     };
299 
300     struct classcomp {
operatorclasscomp301         bool operator()(const sptr<IPowerStateCallback>& l, const sptr<IPowerStateCallback>& r) const
302         {
303             return l->AsObject() < r->AsObject();
304         }
305     };
306 
307     class ScreenChangeCheck {
308     public:
309         ScreenChangeCheck(std::shared_ptr<FFRTTimer> ffrtTimer, PowerState state, StateChangeReason reason);
310         ~ScreenChangeCheck() noexcept;
311         void SetReportTimerStartFlag(bool flag) const;
312         void ReportSysEvent(const std::string& msg) const;
313 
314     private:
315         pid_t pid_ {-1};
316         pid_t uid_ {-1};
317         mutable bool isReportTimerStarted_ {false};
318         std::shared_ptr<FFRTTimer> ffrtTimer_ {nullptr};
319         PowerState state_;
320         StateChangeReason reason_;
321     };
322 
323     static std::string GetTransitResultString(TransitResult result);
324 
325     void UpdateSettingStateFlag(PowerState state, StateChangeReason reason);
326     void RestoreSettingStateFlag();
327     void InitStateMap();
328     void EmplaceAwake();
329     void EmplaceFreeze();
330     void EmplaceInactive();
331     void EmplaceStandBy();
332     void EmplaceDoze();
333     void EmplaceSleep();
334     void EmplaceHibernate();
335     void EmplaceShutdown();
336     void EmplaceDim();
337     void InitTransitMap();
338     bool CanTransitTo(PowerState from, PowerState to, StateChangeReason reason);
339     void NotifyPowerStateChanged(PowerState state,
340         StateChangeReason reason = StateChangeReason::STATE_CHANGE_REASON_APPLICATION);
341     void SendEventToPowerMgrNotify(PowerState state, int64_t callTime);
342     bool CheckRunningLock(PowerState state);
343     void HandleActivityTimeout();
344     void HandleActivitySleepTimeout();
345     void HandleSystemWakeup();
346     void AppendDumpInfo(std::string& result, std::string& reason, std::string& time);
347     std::shared_ptr<StateController> GetStateController(PowerState state);
348     void ResetScreenOffPreTimeForSwing(int64_t displayOffTime);
349     void ShowCurrentScreenLocks();
350     void HandleProximityScreenOffTimer(PowerState state, StateChangeReason reason);
351     bool HandlePreBrightState(PowerState targetState, StateChangeReason reason);
352     bool IsPreBrightAuthReason(StateChangeReason reason);
353     bool IsPreBrightWakeUp(WakeupDeviceType type);
354     bool NeedShowScreenLocks(PowerState state);
355 #ifdef POWER_MANAGER_POWER_ENABLE_S4
356     bool PrepareHibernate(bool clearMemory);
357     bool PrepareHibernateWithTimeout(bool clearMemory);
358     void RestoreHibernate(bool clearMemory, HibernateStatus status,
359         const std::shared_ptr<HibernateController>& hibernateController, const std::shared_ptr<PowerMgrNotify>& notify);
360     void RollbackHibernate(PowerState originalState, bool clearMemory, const sptr<PowerMgrService>& pms);
361     uint32_t GetPreHibernateDelay();
362 #endif
363 #ifdef HAS_SENSORS_SENSOR_PART
364     bool IsProximityClose();
365 #endif
366     void StartSleepTimer(PowerState from);
367 
368     const wptr<PowerMgrService> pms_;
369     std::shared_ptr<FFRTTimer> ffrtTimer_ {nullptr};
370     PowerState currentState_;
371     std::map<PowerState, std::shared_ptr<std::vector<RunningLockType>>> lockMap_;
372     std::map<PowerState, std::shared_ptr<StateController>> controllerMap_;
373     std::mutex mutex_;
374     // all change to currentState_ should be inside stateMutex_
375     std::mutex stateMutex_;
376     DevicePowerState mDeviceState_;
377     sptr<IRemoteObject::DeathRecipient> powerStateCBDeathRecipient_;
378     std::set<const sptr<IPowerStateCallback>, classcomp> syncPowerStateListeners_;
379     std::set<const sptr<IPowerStateCallback>, classcomp> asyncPowerStateListeners_;
380     std::shared_ptr<IDeviceStateAction> stateAction_;
381 
382     std::atomic<int64_t> displayOffTime_ {DEFAULT_DISPLAY_OFF_TIME_MS};
383     int64_t sleepTime_ {DEFAULT_SLEEP_TIME_MS};
384     bool enableDisplaySuspend_ {false};
385     bool isScreenOffTimeOverride_ {false};
386     std::unordered_map<PowerState, std::set<PowerState>> forbidMap_;
387     uint32_t switchActionValue_ {2}; // default value is 2 (stand for ACTION_FORCE_SUSPEND)
388     std::atomic<bool> switchOpen_ {true};
389 #ifdef POWER_MANAGER_POWER_ENABLE_S4
390     std::atomic<bool> hibernating_ {false};
391 #endif
392     std::unordered_map<StateChangeReason, std::unordered_map<PowerState, std::set<PowerState>>> allowMapByReason_;
393     std::atomic<bool> forceTimingOut_ {false};
394     std::atomic<bool> enabledTimingOutLockScreen_ {true};
395     std::atomic<bool> enabledTimingOutLockScreenCheckLock_ {false};
396     std::atomic<bool> enabledScreenOffEvent_{true};
397     std::atomic<int64_t> settingStateFlag_ {-1};
398     std::atomic<bool> settingOnStateFlag_ {false};
399     std::atomic<bool> settingOffStateFlag_ {false};
400     std::atomic<bool> isAwakeNotified_ {false};
401     std::atomic<PreBrightState> preBrightState_ {PRE_BRIGHT_UNSTART};
402     std::atomic<bool> proximityScreenOffTimerStarted_ {false};
403     std::atomic<bool> isDozeEnabled_ {false};
404 #ifdef POWER_MANAGER_ENABLE_EXTERNAL_SCREEN_MANAGEMENT
405     std::atomic<int32_t> externalScreenNumber_ {0};
406 #endif
407     ProximityNormalController proximityNormalController_;
408 };
409 } // namespace PowerMgr
410 } // namespace OHOS
411 #endif // POWERMGR_POWER_STATE_MACHINE_H
412