|
| 1 | +#ifndef TICKER_H |
| 2 | +#define TICKER_H |
| 3 | + |
| 4 | +#include <stdint.h> |
| 5 | +#include <stddef.h> |
| 6 | + |
| 7 | +extern "C" { |
| 8 | + typedef struct _ETSTIMER_ ETSTimer; |
| 9 | +} |
| 10 | + |
| 11 | +class Ticker |
| 12 | +{ |
| 13 | +public: |
| 14 | + Ticker(); |
| 15 | + ~Ticker(); |
| 16 | + typedef void (*callback_t)(void); |
| 17 | + typedef void (*callback_with_arg_t)(void*); |
| 18 | + |
| 19 | + void attach(callback_t callback, float seconds) |
| 20 | + { |
| 21 | + _attach_ms(reinterpret_cast<callback_with_arg_t>(callback), seconds * 1000, 0); |
| 22 | + } |
| 23 | + |
| 24 | + void attach_ms(callback_t callback, uint32_t milliseconds) |
| 25 | + { |
| 26 | + _attach_ms(reinterpret_cast<callback_with_arg_t>(callback), milliseconds, 0); |
| 27 | + } |
| 28 | + |
| 29 | + template<typename TArg> |
| 30 | + void attach(void (*callback)(TArg), float seconds, TArg arg) |
| 31 | + { |
| 32 | + static_assert(sizeof(TArg) <= sizeof(uint32_t), "attach() callback argument size must be <= 4 bytes"); |
| 33 | + uint32_t arg32 = static_cast<uint32_t>(arg); |
| 34 | + _attach_ms(reinterpret_cast<callback_with_arg_t>(callback), seconds * 1000, reinterpret_cast<void*>(arg32)); |
| 35 | + } |
| 36 | + |
| 37 | + template<typename TArg> |
| 38 | + void attach_ms(void (*callback)(TArg), uint32_t milliseconds, TArg arg) |
| 39 | + { |
| 40 | + static_assert(sizeof(TArg) <= sizeof(uint32_t), "attach_ms() callback argument size must be <= 4 bytes"); |
| 41 | + uint32_t arg32 = static_cast<uint32_t>(arg); |
| 42 | + _attach_ms(reinterpret_cast<callback_with_arg_t>(callback), milliseconds, reinterpret_cast<void*>(arg32)); |
| 43 | + } |
| 44 | + |
| 45 | + void detach(); |
| 46 | + |
| 47 | +protected: |
| 48 | + void _attach_ms(callback_with_arg_t callback, uint32_t milliseconds, void* arg); |
| 49 | + |
| 50 | + |
| 51 | +protected: |
| 52 | + ETSTimer* _timer; |
| 53 | +}; |
| 54 | + |
| 55 | + |
| 56 | +#endif//TICKER_H |
0 commit comments