1 /* 2 * Copyright (c) 2021 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_SUSPEND_CONTROLLER_H 17 #define POWERMGR_SUSPEND_CONTROLLER_H 18 19 #include <chrono> 20 #include <condition_variable> 21 #include <functional> 22 #include <mutex> 23 #include <thread> 24 25 #include "suspend/isuspend_controller.h" 26 27 #include "unique_fd.h" 28 29 namespace OHOS { 30 namespace PowerMgr { 31 namespace Suspend { 32 using namespace std::chrono_literals; 33 34 class SuspendController : public ISuspendController { 35 public: 36 SuspendController(); ~SuspendController()37 ~SuspendController() override {}; 38 39 void Suspend(SuspendCallback onSuspend, SuspendCallback onWakeup, bool force) override; 40 void Wakeup() override; 41 void IncSuspendBlockCounter() override; 42 void DecSuspendBlockCounter() override; 43 44 private: 45 using WaitingSuspendConditionFunc = std::function<void()>; 46 class AutoSuspend { 47 public: AutoSuspend(const WaitingSuspendConditionFunc & waitingFunc)48 explicit AutoSuspend(const WaitingSuspendConditionFunc& waitingFunc) : waitingFunc_(waitingFunc) {} 49 ~AutoSuspend() = default; 50 51 void AutoSuspendLoop(); 52 void Start(SuspendCallback onSuspend, SuspendCallback onWakeup); 53 void Stop(); 54 bool SuspendEnter(); 55 56 private: 57 static bool started_; 58 std::string WaitWakeupCount(); 59 bool WriteWakeupCount(std::string wakeupCount); 60 61 static constexpr const char * const SUSPEND_STATE = "mem"; 62 static constexpr const char * const SUSPEND_STATE_PATH = "/sys/power/state"; 63 static constexpr const char * const WAKEUP_COUNT_PATH = "/sys/power/wakeup_count"; 64 UniqueFd wakeupCountFd {-1}; 65 66 std::chrono::milliseconds waitTime_ {100ms}; 67 std::unique_ptr<std::thread> daemon_; 68 WaitingSuspendConditionFunc waitingFunc_; 69 SuspendCallback onSuspend_; 70 SuspendCallback onWakeup_; 71 }; 72 73 bool SuspendConditionSatisfied(); 74 void WaitingSuspendCondition(); 75 76 uint32_t suspendBlockCounter_ {0}; 77 std::condition_variable suspendCv_; 78 std::unique_ptr<AutoSuspend> suspend_; 79 std::mutex suspendMutex_; 80 }; 81 } // namespace Suspend 82 } // namespace PowerMgr 83 } // namespace OHOS 84 #endif // POWERMGR_SUSPEND_CONTROLLER_H 85