1 /*
2  * Copyright (c) 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 #ifndef HGM_ONE_SHOT_TIME_H
16 #define HGM_ONE_SHOT_TIME_H
17 #include <semaphore.h>
18 #include <chrono>
19 #include <condition_variable>
20 #include <thread>
21 
22 #include "event_handler.h"
23 
24 namespace OHOS::Rosen {
25 class ChronoSteadyClock {
26 public:
27     ChronoSteadyClock() = default;
28     ~ChronoSteadyClock() = default;
29 
Now()30     static std::chrono::steady_clock::time_point Now()
31     {
32         return std::chrono::steady_clock::now();
33     }
34 };
35 
36 class HgmOneShotTimer {
37 public:
38     using Interval = std::chrono::milliseconds;
39     using ResetCallback = std::function<void()>;
40     using ExpiredCallback = std::function<void()>;
41 
42     HgmOneShotTimer(std::string name, const Interval& interval, const ResetCallback& resetCallback,
43         const ExpiredCallback& expiredCallback,
44         std::unique_ptr<ChronoSteadyClock> clock = std::make_unique<ChronoSteadyClock>());
45     ~HgmOneShotTimer();
46 
47     // Initializes and turns on the idle timer.
48     void Start();
49     // Stops the idle timer and any held resources.
50     void Stop();
51     // Resets the wakeup time and fires the reset callback.
52     void Reset();
53 
54     std::string Dump() const;
55 
56 private:
57     enum class HgmTimerState {
58         STOP = 0,
59         RESET = 1,
60         WAITING = 2,
61         IDLE = 3
62     };
63 
64     void Loop();
65     HgmTimerState CheckForResetAndStop(HgmTimerState state);
66     bool CheckTimerExpired(std::chrono::steady_clock::time_point expireTime) const;
67 
68     std::unique_ptr<ChronoSteadyClock> clock_;
69 
70     std::shared_ptr<AppExecFwk::EventRunner> runner_ = nullptr;
71     std::shared_ptr<AppExecFwk::EventHandler> handler_ = nullptr;
72     std::mutex startMutex_;
73 
74     sem_t semaphone_;
75     std::string name_;
76 
77     const Interval interval_;
78     const ResetCallback resetCallback_;
79     const ExpiredCallback expiredCallback_;
80 
81     std::atomic<bool> resetFlag_ = false;
82     std::atomic<bool> stopFlag_ = false;
83 };
84 } // namespace OHOS::Rosen
85 
86 #endif // HGM_ONE_SHOT_TIME_H