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 #include "ipower_state_callback.h" 26 #include "power_common.h" 27 #include "power_state_machine_info.h" 28 #include "running_lock_info.h" 29 #ifdef POWER_MANAGER_POWER_ENABLE_S4 30 #include "hibernate_controller.h" 31 #endif 32 33 #define DEFAULT_DISPLAY_OFF_TIME 30000 34 #define DEFAULT_SLEEP_TIME 5000 35 36 namespace OHOS { 37 namespace PowerMgr { 38 class RunningLockMgr; 39 class PowerMgrService; 40 41 struct ScreenState { 42 DisplayState state; 43 int64_t lastOnTime; 44 int64_t lastOffTime; 45 }; 46 47 struct DevicePowerState { 48 ScreenState screenState; 49 // record the last time when get wakeup event from A side 50 int64_t lastWakeupEventTime; 51 // record the last time when calling func RefreshActivityInner 52 int64_t lastRefreshActivityTime; 53 // record the last time when calling func WakeupDeviceInner 54 int64_t lastWakeupDeviceTime; 55 // record the last time when calling func SuspendDeviceInner 56 int64_t lastSuspendDeviceTime; 57 }; 58 59 enum class TransitResult { 60 SUCCESS = 0, 61 ALREADY_IN_STATE = 1, 62 LOCKING = 2, 63 HDI_ERR = 3, 64 DISPLAY_ON_ERR = 4, 65 DISPLAY_OFF_ERR = 5, 66 FORBID_TRANSIT = 6, 67 PRE_BRIGHT_ERR = 7, 68 OTHER_ERR = 99 69 }; 70 71 class PowerStateMachine : public std::enable_shared_from_this<PowerStateMachine> { 72 public: 73 explicit PowerStateMachine(const wptr<PowerMgrService>& pms); 74 ~PowerStateMachine(); 75 76 enum { 77 CHECK_USER_ACTIVITY_TIMEOUT_MSG = 0, 78 CHECK_USER_ACTIVITY_OFF_TIMEOUT_MSG, 79 CHECK_PRE_BRIGHT_AUTH_TIMEOUT_MSG, 80 CHECK_PROXIMITY_SCREEN_OFF_MSG, 81 }; 82 83 static void onSuspend(); 84 static void onWakeup(); 85 86 bool Init(); 87 void InitState(); 88 void SuspendDeviceInner( 89 pid_t pid, int64_t callTimeMs, SuspendDeviceType type, bool suspendImmed, bool ignoreScreenState = false); 90 void WakeupDeviceInner( 91 pid_t pid, int64_t callTimeMs, WakeupDeviceType type, const std::string& details, const std::string& pkgName); 92 void HandlePreBrightWakeUp(int64_t callTimeMs, WakeupDeviceType type, const std::string& details, 93 const std::string& pkgName, bool timeoutTriggered = false); 94 void RefreshActivityInner(pid_t pid, int64_t callTimeMs, UserActivityType type, bool needChangeBacklight); 95 bool CheckRefreshTime(); 96 bool OverrideScreenOffTimeInner(int64_t timeout); 97 bool RestoreScreenOffTimeInner(); 98 void ReceiveScreenEvent(bool isScreenOn); 99 bool IsScreenOn(bool needPrintLog = true); 100 bool IsFoldScreenOn(); 101 bool IsCollaborationScreenOn(); 102 void Reset(); 103 int64_t GetSleepTime(); 104 #ifdef MSDP_MOVEMENT_ENABLE 105 bool IsMovementStateOn(); 106 #endif 107 GetState()108 PowerState GetState() 109 { 110 return currentState_; 111 }; GetStateAction()112 const std::shared_ptr<IDeviceStateAction>& GetStateAction() 113 { 114 return stateAction_; 115 }; 116 bool ForceSuspendDeviceInner(pid_t pid, int64_t callTimeMs); 117 #ifdef POWER_MANAGER_POWER_ENABLE_S4 118 bool HibernateInner(bool clearMemory); 119 #endif 120 void RegisterPowerStateCallback(const sptr<IPowerStateCallback>& callback, bool isSync = true); 121 void UnRegisterPowerStateCallback(const sptr<IPowerStateCallback>& callback); 122 void SetDelayTimer(int64_t delayTime, int32_t event); 123 void CancelDelayTimer(int32_t event); 124 void ResetInactiveTimer(bool needPrintLog = true); 125 void ResetSleepTimer(); 126 void SetAutoSuspend(SuspendDeviceType type, uint32_t delay); 127 bool SetState(PowerState state, StateChangeReason reason, bool force = false); 128 bool TryToCancelScreenOff(); 129 void BeginPowerkeyScreenOff(); 130 void EndPowerkeyScreenOff(); 131 void SetDisplaySuspend(bool enable); 132 void WriteHiSysEvent(TransitResult ret, StateChangeReason reason, int32_t beginTimeMs, PowerState state); 133 bool IsTransitFailed(TransitResult ret); 134 StateChangeReason GetReasonByUserActivity(UserActivityType type); 135 StateChangeReason GetReasonByWakeType(WakeupDeviceType type); 136 StateChangeReason GetReasionBySuspendType(SuspendDeviceType type); 137 WakeupDeviceType ParseWakeupDeviceType(const std::string& details); 138 static void DisplayOffTimeUpdateFunc(); 139 140 // only use for test GetLastSuspendDeviceTime()141 int64_t GetLastSuspendDeviceTime() const 142 { 143 return mDeviceState_.lastSuspendDeviceTime; 144 } GetLastWakeupDeviceTime()145 int64_t GetLastWakeupDeviceTime() const 146 { 147 return mDeviceState_.lastWakeupDeviceTime; 148 } GetLastRefreshActivityTime()149 int64_t GetLastRefreshActivityTime() const 150 { 151 return mDeviceState_.lastRefreshActivityTime; 152 } GetLastWakeupEventTime()153 int64_t GetLastWakeupEventTime() const 154 { 155 return mDeviceState_.lastWakeupEventTime; 156 } SetSwitchState(bool switchOpen)157 void SetSwitchState(bool switchOpen) 158 { 159 switchOpen_ = switchOpen; 160 } IsSwitchOpen()161 bool IsSwitchOpen() const 162 { 163 return switchOpen_; 164 } 165 #ifdef POWER_MANAGER_POWER_ENABLE_S4 IsHibernating()166 bool IsHibernating() const 167 { 168 return hibernating_; 169 } 170 #endif GetLastOnTime()171 int64_t GetLastOnTime() const 172 { 173 return mDeviceState_.screenState.lastOnTime; 174 } 175 class PowerStateCallbackDeathRecipient : public IRemoteObject::DeathRecipient { 176 public: 177 PowerStateCallbackDeathRecipient() = default; 178 virtual void OnRemoteDied(const wptr<IRemoteObject>& remote); 179 virtual ~PowerStateCallbackDeathRecipient() = default; 180 }; 181 void DumpInfo(std::string& result); 182 void EnableMock(IDeviceStateAction* mockAction); 183 int64_t GetDisplayOffTime(); 184 int64_t GetDimTime(int64_t displayOffTime); 185 static constexpr int64_t OFF_TIMEOUT_FACTOR = 5; 186 static constexpr int64_t MAX_DIM_TIME_MS = 7500; 187 static constexpr int64_t COORDINATED_STATE_SCREEN_OFF_TIME_MS = 10000; 188 static constexpr uint32_t SCREEN_CHANGE_TIMEOUT_MS = 10000; 189 static constexpr uint32_t SCREEN_CHANGE_REPORT_INTERVAL_MS = 600000; 190 void SetDisplayOffTime(int64_t time, bool needUpdateSetting = true); 191 static void RegisterDisplayOffTimeObserver(); 192 static void UnregisterDisplayOffTimeObserver(); 193 void SetSleepTime(int64_t time); 194 bool IsRunningLockEnabled(RunningLockType type); 195 void SetForceTimingOut(bool enabled); 196 void LockScreenAfterTimingOut(bool enabled, bool checkScreenOnLock, bool sendScreenOffEvent); 197 bool IsSettingState(PowerState state); 198 199 private: 200 enum PreBrightState : uint32_t { 201 PRE_BRIGHT_UNSTART = 0, 202 PRE_BRIGHT_STARTED, 203 PRE_BRIGHT_FINISHED, 204 }; 205 206 class SettingStateFlag { 207 public: SettingStateFlag(PowerState state,std::shared_ptr<PowerStateMachine> owner,StateChangeReason reason)208 SettingStateFlag(PowerState state, std::shared_ptr<PowerStateMachine> owner, StateChangeReason reason) 209 : owner_(owner) 210 { 211 std::shared_ptr<PowerStateMachine> stateMachine = owner_.lock(); 212 int64_t flag; 213 if (state == PowerState::DIM && reason == StateChangeReason::STATE_CHANGE_REASON_COORDINATION) { 214 flag = static_cast<int64_t>(StateFlag::FORCE_SETTING_DIM); 215 } else { 216 flag = static_cast<int64_t>(state); 217 } 218 stateMachine->settingStateFlag_ = flag; 219 } 220 SettingStateFlag(const SettingStateFlag&) = delete; 221 SettingStateFlag& operator=(const SettingStateFlag&) = delete; 222 SettingStateFlag(SettingStateFlag&&) = delete; 223 SettingStateFlag& operator=(SettingStateFlag&&) = delete; ~SettingStateFlag()224 ~SettingStateFlag() 225 { 226 std::shared_ptr<PowerStateMachine> stateMachine = owner_.lock(); 227 stateMachine->settingStateFlag_ = static_cast<int64_t>(StateFlag::NONE); 228 } 229 enum class StateFlag : int64_t { 230 FORCE_SETTING_DIM = -3, 231 SETTING_DIM_INTERRUPTED = -2, 232 NONE = -1 233 }; 234 protected: 235 std::weak_ptr<PowerStateMachine> owner_; 236 }; 237 class StateController { 238 public: StateController(PowerState state,std::shared_ptr<PowerStateMachine> owner,std::function<TransitResult (StateChangeReason)> action)239 StateController(PowerState state, std::shared_ptr<PowerStateMachine> owner, 240 std::function<TransitResult(StateChangeReason)> action) 241 : state_(state), 242 owner_(owner), action_(action) 243 { 244 } 245 ~StateController() = default; GetState()246 PowerState GetState() 247 { 248 return state_; 249 } 250 TransitResult TransitTo(StateChangeReason reason, bool ignoreLock = false); 251 void RecordFailure(PowerState from, StateChangeReason trigger, TransitResult failReason); 252 static bool IsReallyFailed(StateChangeReason reason); 253 StateChangeReason lastReason_; 254 int64_t lastTime_ {0}; 255 PowerState failFrom_; 256 StateChangeReason failTrigger_; 257 std::string failReason_; 258 int64_t failTime_ {0}; 259 260 protected: 261 bool CheckState(); 262 bool NeedNotify(PowerState currentState); 263 void MatchState(PowerState& currentState, DisplayState state); 264 void CorrectState(PowerState& currentState, PowerState correctState, DisplayState state); 265 PowerState state_; 266 std::weak_ptr<PowerStateMachine> owner_; 267 std::function<TransitResult(StateChangeReason)> action_; 268 }; 269 270 struct classcomp { operatorclasscomp271 bool operator()(const sptr<IPowerStateCallback>& l, const sptr<IPowerStateCallback>& r) const 272 { 273 return l->AsObject() < r->AsObject(); 274 } 275 }; 276 277 class ScreenChangeCheck { 278 public: 279 ScreenChangeCheck(std::shared_ptr<FFRTTimer> ffrtTimer, PowerState state, StateChangeReason reason); 280 ~ScreenChangeCheck() noexcept; 281 void SetReportTimerStartFlag(bool flag) const; 282 void ReportSysEvent(const std::string& msg) const; 283 284 private: 285 pid_t pid_ {-1}; 286 pid_t uid_ {-1}; 287 mutable bool isReportTimerStarted_ {false}; 288 std::shared_ptr<FFRTTimer> ffrtTimer_ {nullptr}; 289 PowerState state_; 290 StateChangeReason reason_; 291 }; 292 293 static std::string GetTransitResultString(TransitResult result); 294 void UpdateSettingStateFlag(PowerState state, StateChangeReason reason); 295 void RestoreSettingStateFlag(); 296 void InitStateMap(); 297 void EmplaceAwake(); 298 void EmplaceFreeze(); 299 void EmplaceInactive(); 300 void EmplaceStandBy(); 301 void EmplaceDoze(); 302 void EmplaceSleep(); 303 void EmplaceHibernate(); 304 void EmplaceShutdown(); 305 void EmplaceDim(); 306 void InitTransitMap(); 307 bool CanTransitTo(PowerState from, PowerState to, StateChangeReason reason); 308 void NotifyPowerStateChanged(PowerState state, 309 StateChangeReason reason = StateChangeReason::STATE_CHANGE_REASON_APPLICATION); 310 void SendEventToPowerMgrNotify(PowerState state, int64_t callTime); 311 bool CheckRunningLock(PowerState state); 312 void HandleActivityTimeout(); 313 void HandleActivitySleepTimeout(); 314 void HandleSystemWakeup(); 315 void AppendDumpInfo(std::string& result, std::string& reason, std::string& time); 316 std::shared_ptr<StateController> GetStateController(PowerState state); 317 void ResetScreenOffPreTimeForSwing(int64_t displayOffTime); 318 void ShowCurrentScreenLocks(); 319 void HandleProximityScreenOffTimer(PowerState state, StateChangeReason reason); 320 bool HandlePreBrightState(StateChangeReason reason); 321 bool IsPreBrightAuthReason(StateChangeReason reason); 322 bool IsPreBrightWakeUp(WakeupDeviceType type); 323 bool NeedShowScreenLocks(PowerState state); 324 #ifdef POWER_MANAGER_POWER_ENABLE_S4 325 bool PrepareHibernate(bool clearMemory); 326 void RestoreHibernate(bool clearMemory, HibernateStatus status, 327 std::shared_ptr<HibernateController>& hibernateController, std::shared_ptr<PowerMgrNotify>& notify); 328 FFRTTask CreateHibernateFfrtTask(bool clearMemory, sptr<PowerMgrService>& pms, 329 std::shared_ptr<HibernateController>& hibernateController, std::shared_ptr<PowerMgrNotify>& notify); 330 #endif 331 #ifdef HAS_SENSORS_SENSOR_PART 332 bool IsProximityClose(); 333 #endif 334 void StartSleepTimer(PowerState from); 335 336 std::shared_ptr<FFRTTimer> ffrtTimer_ {nullptr}; 337 const wptr<PowerMgrService> pms_; 338 PowerState currentState_; 339 std::map<PowerState, std::shared_ptr<std::vector<RunningLockType>>> lockMap_; 340 std::map<PowerState, std::shared_ptr<StateController>> controllerMap_; 341 std::mutex mutex_; 342 // all change to currentState_ should be inside stateMutex_ 343 std::mutex stateMutex_; 344 DevicePowerState mDeviceState_; 345 sptr<IRemoteObject::DeathRecipient> powerStateCBDeathRecipient_; 346 std::set<const sptr<IPowerStateCallback>, classcomp> syncPowerStateListeners_; 347 std::set<const sptr<IPowerStateCallback>, classcomp> asyncPowerStateListeners_; 348 std::shared_ptr<IDeviceStateAction> stateAction_; 349 350 std::atomic<int64_t> displayOffTime_ {DEFAULT_DISPLAY_OFF_TIME}; 351 int64_t sleepTime_ {DEFAULT_SLEEP_TIME}; 352 bool enableDisplaySuspend_ {false}; 353 bool isScreenOffTimeOverride_ {false}; 354 std::unordered_map<PowerState, std::set<PowerState>> forbidMap_; 355 std::atomic<bool> switchOpen_ {true}; 356 #ifdef POWER_MANAGER_POWER_ENABLE_S4 357 std::atomic<bool> hibernating_ {false}; 358 #endif 359 std::unordered_map<StateChangeReason, std::unordered_map<PowerState, std::set<PowerState>>> allowMapByReason_; 360 std::atomic<bool> forceTimingOut_ {false}; 361 std::atomic<bool> enabledTimingOutLockScreen_ {true}; 362 std::atomic<bool> enabledTimingOutLockScreenCheckLock_ {false}; 363 std::atomic<bool> enabledScreenOffEvent_{true}; 364 std::atomic<int64_t> settingStateFlag_ {-1}; 365 std::atomic<bool> settingOnStateFlag_ {false}; 366 std::atomic<bool> settingOffStateFlag_ {false}; 367 std::atomic<bool> isAwakeNotified_ {false}; 368 std::atomic<PreBrightState> preBrightState_ {PRE_BRIGHT_UNSTART}; 369 std::atomic<bool> proximityScreenOffTimerStarted_ {false}; 370 }; 371 } // namespace PowerMgr 372 } // namespace OHOS 373 #endif // POWERMGR_POWER_STATE_MACHINE_H 374