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