Files
MuditaOS/module-sys/Service/Timer.hpp
Adam f5f27d642f EGD-2955 EGD-3588 Timers fully refactored & updated (#721)
* Timers now are Application thread safe
* Timers now have consistent API independend of Application (no more c style timers)
* Timers can have either: callback or override onTimer() method - this
  way we can create more complicated timers or just use existing ones
* gui::Timer added via adapter class GuiTimer to decouple sys::Timer
  with gui::Timer
* Fixed race in wrapper
* Updated docs
* fixed using std and cpp_freertos and DataReceivedHandler hidden in Application.hpp
2020-10-02 14:04:57 +02:00

83 lines
2.4 KiB
C++

#pragma once
#include "FreeRTOS.h"
#include "portmacro.h" // for TickType_t
#include "timer.hpp" // for Timer
#include <functional> // for function
#include <string> // for string
namespace sys
{
class Service;
} // namespace sys
namespace sys
{
using ms = unsigned int;
/// Base timer for all coarse timers in system
class Timer : public cpp_freertos::Timer
{
public:
static const ms timeout_infinite;
enum class Type
{
Periodic,
SingleShot
};
/// Create named timer and register it in parent
/// @param name this will be name of timer + postfix
/// @param parent service on which behalf timer events will be sent and received
/// @param interval time for next timer event in
Timer(const std::string &name, Service *parent, ms interval, Type type = Type::Periodic);
/// Create timer with default name `_<id_number>` and register it in parent
/// @param parent service on which behalf timer events will be sent and received
/// @param interval time for next timer event in
Timer(Service *parent, ms interval, Type type = Type::Periodic);
Timer() = delete;
Timer(const Timer &) = delete;
Timer operator=(const Timer &) = delete;
/// just to stop timer
~Timer() override;
/// This is final by design - to avoid missuse we send Timer notification to Service
/// and then handle it like any other event. Not by callback as this could cause unrestricted access (no mutex)
void Run() final;
/// executed when we receive timeout notification (from overriden Run()) on bus
void onTimeout();
/// @defgroup API
/// {
void start();
void reload(ms from_time = 0);
void stop();
void setInterval(ms new_interval);
/// }
protected:
Service *parent = nullptr;
private:
Type type;
ms interval;
std::function<void(Timer &)> callback = nullptr;
const std::string name;
public:
void connect(std::function<void(Timer &)> new_callback)
{
callback = new_callback;
}
[[nodiscard]] constexpr auto getName() const -> const std::string &
{
return name;
}
};
}; // namespace sys