| 6 |
| * Copyright Nikolai Kudashov, 2015-2018. |
| 7 | */ |
| 8 |
| 9 | #include "Timer.h" |
| 10 | #include "FileLog.h" |
| 11 | #include "EventObject.h" |
| 12 | #include "ConnectionsManager.h" |
| 13 |
| 14 | Timer::Timer(int32_t instance, std::function<void()> function) { |
| 15 | eventObject = new EventObject(this, EventObjectTypeTimer); |
| 16 | instanceNum = instance; |
| 17 | callback = function; |
| 18 | } |
| 19 |
| 20 | Timer::~Timer() { |
| 21 | stop(); |
| 22 | if (eventObject != nullptr) { |
| 23 | delete eventObject; |
| 24 | eventObject = nullptr; |
| 25 | } |
| 26 | } |
| 27 |
| 28 | void Timer::start() { |
| 29 | if (started || timeout == 0) { |
| 30 | return; |
| 31 | } |
| 32 | started = true; |
| 33 | ConnectionsManager::getInstance(instanceNum).scheduleEvent(eventObject, timeout); |
| 34 | } |
| 35 |
| 36 | void Timer::stop() { |
| 37 | if (!started) { |
| 38 | return; |
| 39 | } |
| 40 | started = false; |
| 41 | ConnectionsManager::getInstance(instanceNum).removeEvent(eventObject); |
| 42 | } |
| 43 |
| 44 | void Timer::setTimeout(uint32_t ms, bool repeat) { |
| 45 | if (ms == timeout) { |
| 46 | return; |
| 47 | } |
| 48 | repeatable = repeat; |
| 49 | timeout = ms; |
| 50 | if (started) { |
| 51 | ConnectionsManager::getInstance(instanceNum).removeEvent(eventObject); |
| 52 | ConnectionsManager::getInstance(instanceNum).scheduleEvent(eventObject, timeout); |
| 53 | } |
| 54 | } |
| 55 |
| 56 | void Timer::onEvent() { |
| 57 | callback(); |
| 58 | if (LOGS_ENABLED) DEBUG_D("timer(%p) call", this); |
| 59 | if (started && repeatable && timeout != 0) { |
| 60 | ConnectionsManager::getInstance(instanceNum).scheduleEvent(eventObject, timeout); |
| 61 | } |
| 62 | } |
| 63 |