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 StateChangeReason GetReasonByUserActivity(UserActivityType type); 133 StateChangeReason GetReasonByWakeType(WakeupDeviceType type); 134 StateChangeReason GetReasionBySuspendType(SuspendDeviceType type); 135 WakeupDeviceType ParseWakeupDeviceType(const std::string& details); 136 static void DisplayOffTimeUpdateFunc(); 137 138 // only use for test GetLastSuspendDeviceTime()139 int64_t GetLastSuspendDeviceTime() const 140 { 141 return mDeviceState_.lastSuspendDeviceTime; 142 } GetLastWakeupDeviceTime()143 int64_t GetLastWakeupDeviceTime() const 144 { 145 return mDeviceState_.lastWakeupDeviceTime; 146 } GetLastRefreshActivityTime()147 int64_t GetLastRefreshActivityTime() const 148 { 149 return mDeviceState_.lastRefreshActivityTime; 150 } GetLastWakeupEventTime()151 int64_t GetLastWakeupEventTime() const 152 { 153 return mDeviceState_.lastWakeupEventTime; 154 } SetSwitchState(bool switchOpen)155 void SetSwitchState(bool switchOpen) 156 { 157 switchOpen_ = switchOpen; 158 } IsSwitchOpen()159 bool IsSwitchOpen() const 160 { 161 return switchOpen_; 162 } 163 #ifdef POWER_MANAGER_POWER_ENABLE_S4 IsHibernating()164 bool IsHibernating() const 165 { 166 return hibernating_; 167 } 168 #endif GetLastOnTime()169 int64_t GetLastOnTime() const 170 { 171 return mDeviceState_.screenState.lastOnTime; 172 } 173 class PowerStateCallbackDeathRecipient : public IRemoteObject::DeathRecipient { 174 public: 175 PowerStateCallbackDeathRecipient() = default; 176 virtual void OnRemoteDied(const wptr<IRemoteObject>& remote); 177 virtual ~PowerStateCallbackDeathRecipient() = default; 178 }; 179 void DumpInfo(std::string& result); 180 void EnableMock(IDeviceStateAction* mockAction); 181 int64_t GetDisplayOffTime(); 182 int64_t GetDimTime(int64_t displayOffTime); 183 static constexpr int64_t OFF_TIMEOUT_FACTOR = 5; 184 static constexpr int64_t MAX_DIM_TIME_MS = 7500; 185 static constexpr int64_t COORDINATED_STATE_SCREEN_OFF_TIME_MS = 10000; 186 static constexpr uint32_t SCREEN_CHANGE_TIMEOUT_MS = 10000; 187 static constexpr uint32_t SCREEN_CHANGE_REPORT_INTERVAL_MS = 600000; 188 void SetDisplayOffTime(int64_t time, bool needUpdateSetting = true); 189 static void RegisterDisplayOffTimeObserver(); 190 static void UnregisterDisplayOffTimeObserver(); 191 void SetSleepTime(int64_t time); 192 bool IsRunningLockEnabled(RunningLockType type); 193 void SetForceTimingOut(bool enabled); 194 void LockScreenAfterTimingOut(bool enabled, bool checkScreenOnLock, bool sendScreenOffEvent); 195 bool IsSettingState(PowerState state); 196 197 private: 198 enum PreBrightState : uint32_t { 199 PRE_BRIGHT_UNSTART = 0, 200 PRE_BRIGHT_STARTED, 201 PRE_BRIGHT_FINISHED, 202 }; 203 204 class SettingStateFlag { 205 public: SettingStateFlag(PowerState state,std::shared_ptr<PowerStateMachine> owner,StateChangeReason reason)206 SettingStateFlag(PowerState state, std::shared_ptr<PowerStateMachine> owner, StateChangeReason reason) 207 : owner_(owner) 208 { 209 std::shared_ptr<PowerStateMachine> stateMachine = owner_.lock(); 210 int64_t flag; 211 if (state == PowerState::DIM && reason == StateChangeReason::STATE_CHANGE_REASON_COORDINATION) { 212 flag = static_cast<int64_t>(StateFlag::FORCE_SETTING_DIM); 213 } else { 214 flag = static_cast<int64_t>(state); 215 } 216 stateMachine->settingStateFlag_ = flag; 217 } 218 SettingStateFlag(const SettingStateFlag&) = delete; 219 SettingStateFlag& operator=(const SettingStateFlag&) = delete; 220 SettingStateFlag(SettingStateFlag&&) = delete; 221 SettingStateFlag& operator=(SettingStateFlag&&) = delete; ~SettingStateFlag()222 ~SettingStateFlag() 223 { 224 std::shared_ptr<PowerStateMachine> stateMachine = owner_.lock(); 225 stateMachine->settingStateFlag_ = static_cast<int64_t>(StateFlag::NONE); 226 } 227 enum class StateFlag : int64_t { 228 FORCE_SETTING_DIM = -3, 229 SETTING_DIM_INTERRUPTED = -2, 230 NONE = -1 231 }; 232 protected: 233 std::weak_ptr<PowerStateMachine> owner_; 234 }; 235 class StateController { 236 public: StateController(PowerState state,std::shared_ptr<PowerStateMachine> owner,std::function<TransitResult (StateChangeReason)> action)237 StateController(PowerState state, std::shared_ptr<PowerStateMachine> owner, 238 std::function<TransitResult(StateChangeReason)> action) 239 : state_(state), 240 owner_(owner), action_(action) 241 { 242 } 243 ~StateController() = default; GetState()244 PowerState GetState() 245 { 246 return state_; 247 } 248 TransitResult TransitTo(StateChangeReason reason, bool ignoreLock = false); 249 void RecordFailure(PowerState from, StateChangeReason trigger, TransitResult failReason); 250 static bool IsReallyFailed(StateChangeReason reason); 251 StateChangeReason lastReason_; 252 int64_t lastTime_ {0}; 253 PowerState failFrom_; 254 StateChangeReason failTrigger_; 255 std::string failReason_; 256 int64_t failTime_ {0}; 257 258 protected: 259 bool CheckState(); 260 bool NeedNotify(PowerState currentState); 261 void MatchState(PowerState& currentState, DisplayState state); 262 void CorrectState(PowerState& currentState, PowerState correctState, DisplayState state); 263 PowerState state_; 264 std::weak_ptr<PowerStateMachine> owner_; 265 std::function<TransitResult(StateChangeReason)> action_; 266 }; 267 268 struct classcomp { operatorclasscomp269 bool operator()(const sptr<IPowerStateCallback>& l, const sptr<IPowerStateCallback>& r) const 270 { 271 return l->AsObject() < r->AsObject(); 272 } 273 }; 274 275 class ScreenChangeCheck { 276 public: 277 ScreenChangeCheck(std::shared_ptr<FFRTTimer> ffrtTimer, PowerState state, StateChangeReason reason); 278 ~ScreenChangeCheck() noexcept; 279 void SetReportTimerStartFlag(bool flag) const; 280 void ReportSysEvent(const std::string& msg) const; 281 282 private: 283 pid_t pid_ {-1}; 284 pid_t uid_ {-1}; 285 mutable bool isReportTimerStarted_ {false}; 286 std::shared_ptr<FFRTTimer> ffrtTimer_ {nullptr}; 287 PowerState state_; 288 StateChangeReason reason_; 289 }; 290 291 static std::string GetTransitResultString(TransitResult result); 292 void UpdateSettingStateFlag(PowerState state, StateChangeReason reason); 293 void RestoreSettingStateFlag(); 294 void InitStateMap(); 295 void EmplaceAwake(); 296 void EmplaceFreeze(); 297 void EmplaceInactive(); 298 void EmplaceStandBy(); 299 void EmplaceDoze(); 300 void EmplaceSleep(); 301 void EmplaceHibernate(); 302 void EmplaceShutdown(); 303 void EmplaceDim(); 304 void InitTransitMap(); 305 bool CanTransitTo(PowerState to, StateChangeReason reason); 306 void NotifyPowerStateChanged(PowerState state, 307 StateChangeReason reason = StateChangeReason::STATE_CHANGE_REASON_APPLICATION); 308 void SendEventToPowerMgrNotify(PowerState state, int64_t callTime); 309 bool CheckRunningLock(PowerState state); 310 void HandleActivityTimeout(); 311 void HandleActivitySleepTimeout(); 312 void HandleSystemWakeup(); 313 void AppendDumpInfo(std::string& result, std::string& reason, std::string& time); 314 std::shared_ptr<StateController> GetStateController(PowerState state); 315 void ResetScreenOffPreTimeForSwing(int64_t displayOffTime); 316 void ShowCurrentScreenLocks(); 317 void HandleProximityScreenOffTimer(PowerState state, StateChangeReason reason); 318 bool HandlePreBrightState(StateChangeReason reason); 319 bool IsPreBrightAuthReason(StateChangeReason reason); 320 bool IsPreBrightWakeUp(WakeupDeviceType type); 321 bool NeedShowScreenLocks(PowerState state); 322 #ifdef POWER_MANAGER_POWER_ENABLE_S4 323 bool PrepareHibernate(bool clearMemory); 324 #endif 325 #ifdef HAS_SENSORS_SENSOR_PART 326 bool IsProximityClose(); 327 #endif 328 329 std::shared_ptr<FFRTTimer> ffrtTimer_ {nullptr}; 330 const wptr<PowerMgrService> pms_; 331 PowerState currentState_; 332 std::map<PowerState, std::shared_ptr<std::vector<RunningLockType>>> lockMap_; 333 std::map<PowerState, std::shared_ptr<StateController>> controllerMap_; 334 std::mutex mutex_; 335 // all change to currentState_ should be inside stateMutex_ 336 std::mutex stateMutex_; 337 DevicePowerState mDeviceState_; 338 sptr<IRemoteObject::DeathRecipient> powerStateCBDeathRecipient_; 339 std::set<const sptr<IPowerStateCallback>, classcomp> syncPowerStateListeners_; 340 std::set<const sptr<IPowerStateCallback>, classcomp> asyncPowerStateListeners_; 341 std::shared_ptr<IDeviceStateAction> stateAction_; 342 343 std::atomic<int64_t> displayOffTime_ {DEFAULT_DISPLAY_OFF_TIME}; 344 int64_t sleepTime_ {DEFAULT_SLEEP_TIME}; 345 bool enableDisplaySuspend_ {false}; 346 bool isScreenOffTimeOverride_ {false}; 347 std::unordered_map<PowerState, std::set<PowerState>> forbidMap_; 348 std::atomic<bool> switchOpen_ {true}; 349 #ifdef POWER_MANAGER_POWER_ENABLE_S4 350 std::atomic<bool> hibernating_ {false}; 351 #endif 352 std::unordered_map<StateChangeReason, std::unordered_map<PowerState, std::set<PowerState>>> allowMapByReason_; 353 std::atomic<bool> forceTimingOut_ {false}; 354 std::atomic<bool> enabledTimingOutLockScreen_ {true}; 355 std::atomic<bool> enabledTimingOutLockScreenCheckLock_ {false}; 356 std::atomic<bool> enabledScreenOffEvent_{true}; 357 std::atomic<int64_t> settingStateFlag_ {-1}; 358 std::atomic<bool> settingOnStateFlag_ {false}; 359 std::atomic<bool> settingOffStateFlag_ {false}; 360 std::atomic<bool> isAwakeNotified_ {false}; 361 std::atomic<PreBrightState> preBrightState_ {PRE_BRIGHT_UNSTART}; 362 std::atomic<bool> proximityScreenOffTimerStarted_ {false}; 363 }; 364 } // namespace PowerMgr 365 } // namespace OHOS 366 #endif // POWERMGR_POWER_STATE_MACHINE_H 367