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 TIMER_MGR_H 16 #define TIMER_MGR_H 17 18 #include <memory> 19 #include <list> 20 #include <mutex> 21 #include <thread> 22 #include <condition_variable> 23 #include "id_allocator.h" 24 #include "thread_wrapper.h" 25 26 namespace OHOS { 27 namespace IntellVoiceUtils { 28 constexpr int32_t US_PER_MS = 1000; 29 // struct for set timer 30 struct TimerCfg { 31 explicit TimerCfg(int type = 0, int64_t delayUs = 0, int cookie = 0) 32 : type(type), delayUs(delayUs), cookie(cookie) 33 { 34 }; 35 36 int type; 37 int64_t delayUs; 38 int cookie; 39 }; 40 41 // struct for callback 42 struct TimerEvent { 43 explicit TimerEvent(int type = 0, int timeId = 0, int cookie = 0) : type(type), timeId(timeId), cookie(cookie) {}; 44 45 int type; 46 int timeId; 47 int cookie; 48 }; 49 50 51 struct ITimerObserver { ~ITimerObserverITimerObserver52 virtual ~ITimerObserver() {}; 53 virtual void OnTimerEvent(TimerEvent &info) = 0; 54 }; 55 56 enum class TimerStatus { 57 TIMER_STATUS_INIT, 58 TIMER_STATUS_STARTED, 59 TIMER_STATUS_TO_QUIT 60 }; 61 62 struct TimerItem { 63 explicit TimerItem(int id = 0, int type = 0, int cookie = 0, 64 int64_t delayUs = static_cast<long long>(0), ITimerObserver *observer = nullptr); 65 bool operator==(const TimerItem& right) const 66 { 67 return tgtUs == right.tgtUs; 68 }; 69 bool operator<(const TimerItem& right) const 70 { 71 return tgtUs < right.tgtUs; 72 }; 73 74 int timerId; 75 int type; 76 int cookie; 77 int64_t tgtUs; 78 ITimerObserver *observer; 79 }; 80 81 class TimerMgr : public ThreadWrapper, private IdAllocator { 82 public: 83 explicit TimerMgr(int maxTimerNum = 10); 84 ~TimerMgr() override; 85 86 void Start(const std::string &threadName, ITimerObserver *observer = nullptr); 87 void Stop(); 88 int SetTimer(int type, int64_t delayUs, int cookie = 0, ITimerObserver *currObserver = nullptr); 89 int ResetTimer(int timerId, int type, int64_t delayUs, int cookie, ITimerObserver *currObserver); 90 void KillTimer(int &timerId); 91 92 protected: 93 void Run() override; 94 95 private: 96 void Clear(); 97 98 private: 99 TimerStatus status_; 100 ITimerObserver *timerObserver_; 101 std::list<std::shared_ptr<TimerItem>> itemQueue_; 102 103 ffrt::mutex timeMutex_; 104 ffrt::condition_variable cv_; 105 }; 106 } 107 } 108 #endif 109