diff --git a/include/sta/rtos/timer.hpp b/include/sta/rtos/timer.hpp index 2d0cf3d..7507c3a 100644 --- a/include/sta/rtos/timer.hpp +++ b/include/sta/rtos/timer.hpp @@ -57,12 +57,13 @@ namespace sta */ void stop() override; + /** + * @returns True of the timmer is currently running. + */ + bool isRunning(); + private: - static void timeoutHandler(void* arg) - { - RtosTimer* timer = static_cast(arg); - timer->callback_(timer->callbackArg_); - } + static void timeoutHandler(void* arg); private: osTimerId_t timer_id_; /**< CMSIS RTOS2 Timer */ @@ -70,6 +71,7 @@ namespace sta std::function callback_; /**< The callback to call on timeout. */ void* callbackArg_; /**< The argument to pass to the callback. */ + bool running_; /**< The current state of the timer. Running or not? */ }; } // namespace sta diff --git a/src/timer.cpp b/src/timer.cpp index dbaab72..967396d 100644 --- a/src/timer.cpp +++ b/src/timer.cpp @@ -5,7 +5,11 @@ namespace sta { RtosTimer::RtosTimer(void (*callback)(void *arg), void *arg) - : timer_id_{NULL}, timer_attr_{.name="Timer", .attr_bits=osTimerOnce, .cb_size=sizeof(osTimerAttr_t)}, callback_{callback}, callbackArg_{arg} + : timer_id_{NULL}, + timer_attr_{.name="Timer", .attr_bits=osTimerOnce, /*.cb_size=sizeof(osTimerAttr_t)*/}, + callback_{callback}, + callbackArg_{arg}, + running_{false} { // Pass an anonymous function as the callback which will invoke the currently registered callback. timer_id_ = osTimerNew(timeoutHandler, osTimerOnce, arg, &timer_attr_); @@ -19,6 +23,8 @@ namespace sta { RtosTimer::~RtosTimer() { + if (isRunning()) stop(); + osTimerDelete(timer_id_); } @@ -32,13 +38,38 @@ namespace sta { { osStatus_t status = osTimerStart(timer_id_, millis); - if (status != osOK) STA_DEBUG_PRINTLN("Timer start failed"); + if (status != osOK) + { + STA_DEBUG_PRINTLN("Timer start failed"); + return; + } + + running_ = true; } void RtosTimer::stop() { osStatus_t status = osTimerStop(timer_id_); - if (status != osOK) STA_DEBUG_PRINTLN("Timer stop failed"); + if (status != osOK) + { + STA_DEBUG_PRINTLN("Timer stop failed"); + return; + } + + running_ = false; } + + bool RtosTimer::isRunning() + { + return running_; + } + + void RtosTimer::timeoutHandler(void* arg) + { + RtosTimer* timer = static_cast(arg); + timer->running_ = false; + timer->callback_(timer->callbackArg_); + } + } // namespace sta