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