Thread and Timer converted to class (#81)

This commit is contained in:
Ken Van Hoeylandt
2024-11-22 23:08:18 +01:00
committed by GitHub
parent 85e26636a3
commit 854fefa1a1
20 changed files with 550 additions and 679 deletions
+125 -208
View File
@@ -1,20 +1,11 @@
#include "Thread.h"
#include <cstdlib>
#include <cstring>
#include <string>
#include "Check.h"
#include "CoreDefines.h"
#include "Kernel.h"
#include "Log.h"
#ifdef ESP_PLATFORM
#include "freertos/FreeRTOS.h"
#include "freertos/task.h"
#else
#include "FreeRTOS.h"
#include "task.h"
#endif
namespace tt {
#define TAG "Thread"
@@ -28,32 +19,15 @@ namespace tt {
#define THREAD_FLAGS_INVALID_BITS (~((1UL << MAX_BITS_TASK_NOTIFY) - 1U))
#define EVENT_FLAGS_INVALID_BITS (~((1UL << MAX_BITS_EVENT_GROUPS) - 1U))
static_assert(ThreadPriorityHighest <= TT_CONFIG_THREAD_MAX_PRIORITIES, "highest thread priority is higher than max priority");
static_assert(Thread::PriorityHighest <= TT_CONFIG_THREAD_MAX_PRIORITIES, "highest thread priority is higher than max priority");
static_assert(TT_CONFIG_THREAD_MAX_PRIORITIES <= configMAX_PRIORITIES, "highest tactility priority is higher than max FreeRTOS priority");
struct Thread {
ThreadState state;
int32_t ret;
ThreadCallback callback;
void* context;
ThreadStateCallback state_callback;
void* state_context;
char* name;
char* appid;
ThreadPriority priority;
TaskHandle_t task_handle;
// Keep all non-alignable byte types in one place,
// this ensures that the size of this structure is minimal
bool is_static;
configSTACK_DEPTH_TYPE stack_size;
};
void setState(Thread::Data* data, Thread::State state) {
data->state = state;
if (data->stateCallback) {
data->stateCallback(state, data->stateCallbackContext);
}
}
/** Catch threads that are trying to exit wrong way */
__attribute__((__noreturn__)) void thread_catch() { //-V1082
@@ -64,238 +38,178 @@ __attribute__((__noreturn__)) void thread_catch() { //-V1082
__builtin_unreachable();
}
static void thread_set_state(Thread* thread, ThreadState state) {
tt_assert(thread);
thread->state = state;
if (thread->state_callback) {
thread->state_callback(state, thread->state_context);
}
}
static void thread_body(void* context) {
tt_assert(context);
auto* thread = static_cast<Thread*>(context);
auto* data = static_cast<Thread::Data*>(context);
// Store thread instance to thread local storage
// Store thread data instance to thread local storage
tt_assert(pvTaskGetThreadLocalStoragePointer(nullptr, 0) == nullptr);
vTaskSetThreadLocalStoragePointer(nullptr, 0, thread);
vTaskSetThreadLocalStoragePointer(nullptr, 0, data->thread);
tt_assert(thread->state == ThreadStateStarting);
thread_set_state(thread, ThreadStateRunning);
tt_assert(data->state == Thread::StateStarting);
setState(data, Thread::StateRunning);
data->callbackResult = data->callback(data->callbackContext);
tt_assert(data->state == Thread::StateRunning);
thread->ret = thread->callback(thread->context);
tt_assert(thread->state == ThreadStateRunning);
if (thread->is_static) {
if (data->isStatic) {
TT_LOG_I(
TAG,
"%s static task memory will not be reclaimed",
thread->name ? thread->name : "<unnamed service>"
data->name.empty() ? "<unnamed service>" : data->name.c_str()
);
}
thread_set_state(thread, ThreadStateStopped);
setState(data, Thread::StateStopped);
vTaskSetThreadLocalStoragePointer(nullptr, 0, nullptr);
thread->task_handle = nullptr;
data->taskHandle = nullptr;
vTaskDelete(nullptr);
thread_catch();
}
Thread* thread_alloc() {
auto* thread = static_cast<Thread*>(malloc(sizeof(Thread)));
// TODO: create default struct instead of using memset()
memset(thread, 0, sizeof(Thread));
thread->is_static = false;
Thread::Thread() :
data({
.taskHandle = nullptr,
.state = StateStopped,
.callback = nullptr,
.callbackContext = nullptr,
.callbackResult = 0,
.stateCallback = nullptr,
.stateCallbackContext = nullptr,
.name = std::string(),
.priority = PriorityNormal,
.isStatic = false,
.stackSize = 0,
}) { }
Thread* parent = nullptr;
if (xTaskGetSchedulerState() != taskSCHEDULER_NOT_STARTED) {
// TLS is not available, if we called not from thread context
parent = (Thread*)pvTaskGetThreadLocalStoragePointer(nullptr, 0);
if (parent && parent->appid) {
thread_set_appid(thread, parent->appid);
} else {
thread_set_appid(thread, "unknown");
}
} else {
// If scheduler is not started, we are starting driver thread
thread_set_appid(thread, "driver");
}
return thread;
}
Thread* thread_alloc_ex(
const char* name,
uint32_t stack_size,
ThreadCallback callback,
void* context
) {
Thread* thread = thread_alloc();
thread_set_name(thread, name);
thread_set_stack_size(thread, stack_size);
thread_set_callback(thread, callback);
thread_set_context(thread, context);
return thread;
}
void thread_free(Thread* thread) {
tt_assert(thread);
Thread::Thread(
const std::string& name,
configSTACK_DEPTH_TYPE stackSize,
Callback callback,
_Nullable void* callbackContext) :
data({
.taskHandle = nullptr,
.state = StateStopped,
.callback = callback,
.callbackContext = callbackContext,
.callbackResult = 0,
.stateCallback = nullptr,
.stateCallbackContext = nullptr,
.name = name,
.priority = PriorityNormal,
.isStatic = false,
.stackSize = stackSize,
}) { }
Thread::~Thread() {
// Ensure that use join before free
tt_assert(thread->state == ThreadStateStopped);
tt_assert(thread->task_handle == nullptr);
if (thread->name) free(thread->name);
if (thread->appid) free(thread->appid);
free(thread);
tt_assert(data.state == StateStopped);
tt_assert(data.taskHandle == nullptr);
}
void thread_set_name(Thread* thread, const char* name) {
tt_assert(thread);
tt_assert(thread->state == ThreadStateStopped);
if (thread->name) free(thread->name);
thread->name = name ? strdup(name) : nullptr;
void Thread::setName(const std::string& newName) {
tt_assert(data.state == StateStopped);
data.name = newName;
}
void thread_set_appid(Thread* thread, const char* appid) {
tt_assert(thread);
tt_assert(thread->state == ThreadStateStopped);
if (thread->appid) free(thread->appid);
thread->appid = appid ? strdup(appid) : nullptr;
void Thread::markAsStatic() {
data.isStatic = true;
}
void thread_mark_as_static(Thread* thread) {
thread->is_static = true;
bool Thread::isMarkedAsStatic() const {
return data.isStatic;
}
bool thread_mark_is_static(ThreadId thread_id) {
auto hTask = (TaskHandle_t)thread_id;
assert(!TT_IS_IRQ_MODE() && (hTask != nullptr));
auto* thread = (Thread*)pvTaskGetThreadLocalStoragePointer(hTask, 0);
assert(thread != nullptr);
return thread->is_static;
void Thread::setStackSize(size_t stackSize) {
tt_assert(data.state == StateStopped);
tt_assert(stackSize % 4 == 0);
data.stackSize = stackSize;
}
void thread_set_stack_size(Thread* thread, size_t stack_size) {
tt_assert(thread);
tt_assert(thread->state == ThreadStateStopped);
tt_assert(stack_size % 4 == 0);
thread->stack_size = stack_size;
void Thread::setCallback(Callback callback, _Nullable void* callbackContext) {
tt_assert(data.state == StateStopped);
data.callback = callback;
data.callbackContext = callbackContext;
}
void thread_set_callback(Thread* thread, ThreadCallback callback) {
tt_assert(thread);
tt_assert(thread->state == ThreadStateStopped);
thread->callback = callback;
}
void thread_set_context(Thread* thread, void* context) {
tt_assert(thread);
tt_assert(thread->state == ThreadStateStopped);
thread->context = context;
}
void thread_set_priority(Thread* thread, ThreadPriority priority) {
tt_assert(thread);
tt_assert(thread->state == ThreadStateStopped);
void Thread::setPriority(Priority priority) {
tt_assert(data.state == StateStopped);
tt_assert(priority >= 0 && priority <= TT_CONFIG_THREAD_MAX_PRIORITIES);
thread->priority = priority;
data.priority = priority;
}
void thread_set_current_priority(ThreadPriority priority) {
UBaseType_t new_priority = priority ? priority : ThreadPriorityNormal;
vTaskPrioritySet(nullptr, new_priority);
void Thread::setStateCallback(StateCallback callback, _Nullable void* callbackContext) {
tt_assert(data.state == StateStopped);
data.stateCallback = callback;
data.stateCallbackContext = callbackContext;
}
ThreadPriority thread_get_current_priority() {
return (ThreadPriority)uxTaskPriorityGet(nullptr);
Thread::State Thread::getState() const {
return data.state;
}
void thread_set_state_callback(Thread* thread, ThreadStateCallback callback) {
tt_assert(thread);
tt_assert(thread->state == ThreadStateStopped);
thread->state_callback = callback;
}
void Thread::start() {
tt_assert(data.callback);
tt_assert(data.state == StateStopped);
tt_assert(data.stackSize > 0 && data.stackSize < (UINT16_MAX * sizeof(StackType_t)));
void thread_set_state_context(Thread* thread, void* context) {
tt_assert(thread);
tt_assert(thread->state == ThreadStateStopped);
thread->state_context = context;
}
setState(&data, StateStarting);
ThreadState thread_get_state(Thread* thread) {
tt_assert(thread);
return thread->state;
}
void thread_start(Thread* thread) {
tt_assert(thread);
tt_assert(thread->callback);
tt_assert(thread->state == ThreadStateStopped);
tt_assert(thread->stack_size > 0 && thread->stack_size < (UINT16_MAX * sizeof(StackType_t)));
thread_set_state(thread, ThreadStateStarting);
uint32_t stack = thread->stack_size / sizeof(StackType_t);
UBaseType_t priority = thread->priority ? thread->priority : ThreadPriorityNormal;
if (thread->is_static) {
uint32_t stack_depth = data.stackSize / sizeof(StackType_t);
if (data.isStatic) {
#if configSUPPORT_STATIC_ALLOCATION == 1
thread->task_handle = xTaskCreateStatic(
data.taskHandle = xTaskCreateStatic(
thread_body,
thread->name,
stack,
thread,
priority,
static_cast<StackType_t*>(malloc(sizeof(StackType_t) * stack)),
data.name.c_str(),
stack_depth,
&data,
data.priority,
static_cast<StackType_t*>(malloc(sizeof(StackType_t) * stack_depth)),
static_cast<StaticTask_t*>(malloc(sizeof(StaticTask_t)))
);
#else
TT_LOG_E(TAG, "static tasks are not supported by current FreeRTOS config/platform - creating regular one");
BaseType_t ret = xTaskCreate(
thread_body, thread->name, stack, thread, priority, &(thread->task_handle)
BaseType_t result = xTaskCreate(
thread_body, data.name.c_str(), stack_depth, this, data.priority, &(data.taskHandle)
);
tt_check(ret == pdPASS);
tt_check(result == pdPASS);
#endif
} else {
BaseType_t ret = xTaskCreate(
thread_body, thread->name, stack, thread, priority, &(thread->task_handle)
BaseType_t result = xTaskCreate(
thread_body, data.name.c_str(), stack_depth, this, data.priority, &(data.taskHandle)
);
tt_check(ret == pdPASS);
tt_check(result == pdPASS);
}
tt_check(thread->state == ThreadStateStopped || thread->task_handle);
tt_check(data.state == StateStopped || data.taskHandle);
}
bool thread_join(Thread* thread) {
tt_assert(thread);
tt_check(thread_get_current() != thread);
bool Thread::join() {
tt_check(thread_get_current() != this);
// !!! IMPORTANT NOTICE !!!
//
// If your thread exited, but your app stuck here: some other thread uses
// all cpu time, which delays kernel from releasing task handle
while (thread->task_handle) {
while (data.taskHandle) {
delay_ms(10);
}
return true;
}
ThreadId thread_get_id(Thread* thread) {
tt_assert(thread);
return thread->task_handle;
ThreadId Thread::getId() {
return data.taskHandle;
}
int32_t thread_get_return_code(Thread* thread) {
tt_assert(thread);
tt_assert(thread->state == ThreadStateStopped);
return thread->ret;
int32_t Thread::getReturnCode() {
tt_assert(data.state == StateStopped);
return data.callbackResult;
}
ThreadId thread_get_current_id() {
@@ -307,11 +221,28 @@ Thread* thread_get_current() {
return thread;
}
void thread_set_current_priority(Thread::Priority priority) {
UBaseType_t new_priority = priority ? priority : Thread::PriorityNormal;
vTaskPrioritySet(nullptr, new_priority);
}
Thread::Priority thread_get_current_priority() {
return (Thread::Priority)uxTaskPriorityGet(nullptr);
}
void thread_yield() {
tt_assert(!TT_IS_IRQ_MODE());
taskYIELD();
}
bool thread_mark_is_static(ThreadId thread_id) {
auto hTask = (TaskHandle_t)thread_id;
assert(!TT_IS_IRQ_MODE() && (hTask != nullptr));
auto* thread = (Thread*)pvTaskGetThreadLocalStoragePointer(hTask, 0);
assert(thread != nullptr);
return thread->isMarkedAsStatic();
}
uint32_t thread_flags_set(ThreadId thread_id, uint32_t flags) {
auto hTask = (TaskHandle_t)thread_id;
uint32_t rflags;
@@ -470,20 +401,6 @@ const char* thread_get_name(ThreadId thread_id) {
return (name);
}
const char* thread_get_appid(ThreadId thread_id) {
auto hTask = (TaskHandle_t)thread_id;
const char* appid = "system";
if (!TT_IS_IRQ_MODE() && (hTask != nullptr)) {
auto* thread = (Thread*)pvTaskGetThreadLocalStoragePointer(hTask, 0);
if (thread) {
appid = thread->appid;
}
}
return (appid);
}
uint32_t thread_get_stack_space(ThreadId thread_id) {
auto hTask = (TaskHandle_t)thread_id;
uint32_t sz;
+189 -189
View File
@@ -5,203 +5,211 @@
#include <cstddef>
#include <cstdint>
#include <string>
#ifdef ESP_PLATFORM
#include "freertos/FreeRTOS.h"
#include "freertos/task.h"
#else
#include "FreeRTOS.h"
#include "task.h"
#endif
namespace tt {
/** ThreadState */
typedef enum {
ThreadStateStopped,
ThreadStateStarting,
ThreadStateRunning,
} ThreadState;
typedef TaskHandle_t ThreadId;
/** ThreadPriority */
typedef enum {
ThreadPriorityNone = 0, /**< Uninitialized, choose system default */
ThreadPriorityIdle = 1,
ThreadPriorityLowest = 2,
ThreadPriorityLow = 3,
ThreadPriorityNormal = 4,
ThreadPriorityHigh = 5,
ThreadPriorityHigher = 6,
ThreadPriorityHighest = 7
} ThreadPriority;
class Thread {
public:
#define THREAD_PRIORITY_APP ThreadPriorityNormal
#define THREAD_PRIORITY_SERVICE ThreadPriorityHigh
#define THREAD_PRIORITY_RENDER ThreadPriorityHigher
typedef enum {
StateStopped,
StateStarting,
StateRunning,
} State;
/** ThreadPriority */
typedef enum {
PriorityNone = 0, /**< Uninitialized, choose system default */
PriorityIdle = 1,
PriorityLowest = 2,
PriorityLow = 3,
PriorityNormal = 4,
PriorityHigh = 5,
PriorityHigher = 6,
PriorityHighest = 7
} Priority;
/** ThreadCallback Your callback to run in new thread
* @warning never use osThreadExit in Thread
*/
typedef int32_t (*Callback)(void* context);
/** Write to stdout callback
* @param data pointer to data
* @param size data size @warning your handler must consume everything
*/
typedef void (*StdoutWriteCallback)(const char* data, size_t size);
/** Thread state change callback called upon thread state change
* @param state new thread state
* @param context callback context
*/
typedef void (*StateCallback)(State state, void* context);
typedef struct {
Thread* thread;
TaskHandle_t taskHandle;
State state;
Callback callback;
void* callbackContext;
int32_t callbackResult;
StateCallback stateCallback;
void* stateCallbackContext;
std::string name;
Priority priority;
// Keep all non-alignable byte types in one place,
// this ensures that the size of this structure is minimal
bool isStatic;
configSTACK_DEPTH_TYPE stackSize;
} Data;
Thread();
/** Allocate Thread, shortcut version
* @param name
* @param stack_size
* @param callback
* @param context
* @return Thread*
*/
Thread(
const std::string& name,
configSTACK_DEPTH_TYPE stackSize,
Callback callback,
_Nullable void* callbackContext
);
~Thread();
/** Set Thread name
*
* @param name string
*/
void setName(const std::string& name);
/** Mark thread as service
* The service cannot be stopped or removed, and cannot exit from the thread body
*/
void markAsStatic();
/** Check if thread is as service
* If true, the service cannot be stopped or removed, and cannot exit from the thread body
*/
bool isMarkedAsStatic() const;
/** Set Thread stack size
*
* @param thread Thread instance
* @param stackSize stack size in bytes
*/
void setStackSize(size_t stackSize);
/** Set Thread callback
*
* @param thread Thread instance
* @param callback ThreadCallback, called upon thread run
* @param callbackContext what to pass to the callback
*/
void setCallback(Callback callback, _Nullable void* callbackContext = nullptr);
/** Set Thread priority
*
* @param thread Thread instance
* @param priority ThreadPriority value
*/
void setPriority(Priority priority);
/** Set Thread state change callback
*
* @param thread Thread instance
* @param callback state change callback
* @param context pointer to context
*/
void setStateCallback(StateCallback callback, _Nullable void* callbackContext = nullptr);
/** Get Thread state
*
* @param thread Thread instance
*
* @return thread state from ThreadState
*/
[[nodiscard]] State getState() const;
/** Start Thread
*
* @param thread Thread instance
*/
void start();
/** Join Thread
*
* @warning Use this method only when CPU is not busy(Idle task receives
* control), otherwise it will wait forever.
*
* @param thread Thread instance
*
* @return success result
*/
bool join();
/** Get FreeRTOS ThreadId for Thread instance
*
* @param thread Thread instance
*
* @return ThreadId or nullptr
*/
ThreadId getId();
/** Get thread return code
*
* @param thread Thread instance
*
* @return return code
*/
int32_t getReturnCode();
private:
Data data;
};
#define THREAD_PRIORITY_APP Thread::PriorityNormal
#define THREAD_PRIORITY_SERVICE Thread::PriorityHigh
#define THREAD_PRIORITY_RENDER Thread::PriorityHigher
#define THREAD_PRIORITY_ISR (TT_CONFIG_THREAD_MAX_PRIORITIES - 1)
/** Thread anonymous structure */
typedef struct Thread Thread;
/** ThreadId proxy type to OS low level functions */
typedef void* ThreadId;
/** ThreadCallback Your callback to run in new thread
* @warning never use osThreadExit in Thread
*/
typedef int32_t (*ThreadCallback)(void* context);
/** Write to stdout callback
* @param data pointer to data
* @param size data size @warning your handler must consume everything
*/
typedef void (*ThreadStdoutWriteCallback)(const char* data, size_t size);
/** Thread state change callback called upon thread state change
* @param state new thread state
* @param context callback context
*/
typedef void (*ThreadStateCallback)(ThreadState state, void* context);
/** Allocate Thread
*
* @return Thread instance
*/
Thread* thread_alloc();
/** Allocate Thread, shortcut version
*
* @param name
* @param stack_size
* @param callback
* @param context
* @return Thread*
*/
Thread* thread_alloc_ex(
const char* name,
uint32_t stack_size,
ThreadCallback callback,
void* context
);
/** Release Thread
*
* @warning see tt_thread_join
*
* @param thread Thread instance
*/
void thread_free(Thread* thread);
/** Set Thread name
*
* @param thread Thread instance
* @param name string
*/
void thread_set_name(Thread* thread, const char* name);
/**
* @brief Set Thread appid
* Technically, it is like a "process id", but it is not a system-wide unique identifier.
* All threads spawned by the same app will have the same appid.
*
* @param thread
* @param appid
*/
void thread_set_appid(Thread* thread, const char* appid);
/** Mark thread as service
* The service cannot be stopped or removed, and cannot exit from the thread body
*
* @param thread
*/
void thread_mark_as_static(Thread* thread);
/** Set Thread stack size
*
* @param thread Thread instance
* @param stack_size stack size in bytes
*/
void thread_set_stack_size(Thread* thread, size_t stack_size);
/** Set Thread callback
*
* @param thread Thread instance
* @param callback ThreadCallback, called upon thread run
*/
void thread_set_callback(Thread* thread, ThreadCallback callback);
/** Set Thread context
*
* @param thread Thread instance
* @param context pointer to context for thread callback
*/
void thread_set_context(Thread* thread, void* context);
/** Set Thread priority
*
* @param thread Thread instance
* @param priority ThreadPriority value
*/
void thread_set_priority(Thread* thread, ThreadPriority priority);
/** Set current thread priority
*
* @param priority ThreadPriority value
*/
void thread_set_current_priority(ThreadPriority priority);
void thread_set_current_priority(Thread::Priority priority);
/** Get current thread priority
*
* @return ThreadPriority value
*/
ThreadPriority thread_get_current_priority();
/** Set Thread state change callback
*
* @param thread Thread instance
* @param callback state change callback
*/
void thread_set_state_callback(Thread* thread, ThreadStateCallback callback);
/** Set Thread state change context
*
* @param thread Thread instance
* @param context pointer to context
*/
void thread_set_state_context(Thread* thread, void* context);
/** Get Thread state
*
* @param thread Thread instance
*
* @return thread state from ThreadState
*/
ThreadState thread_get_state(Thread* thread);
/** Start Thread
*
* @param thread Thread instance
*/
void thread_start(Thread* thread);
/** Join Thread
*
* @warning Use this method only when CPU is not busy(Idle task receives
* control), otherwise it will wait forever.
*
* @param thread Thread instance
*
* @return bool
*/
bool thread_join(Thread* thread);
/** Get FreeRTOS ThreadId for Thread instance
*
* @param thread Thread instance
*
* @return ThreadId or NULL
*/
ThreadId thread_get_id(Thread* thread);
/** Get thread return code
*
* @param thread Thread instance
*
* @return return code
*/
int32_t thread_get_return_code(Thread* thread);
Thread::Priority thread_get_current_priority();
/** Thread related methods that doesn't involve Thread directly */
@@ -238,14 +246,6 @@ uint32_t thread_flags_wait(uint32_t flags, uint32_t options, uint32_t timeout);
*/
const char* thread_get_name(ThreadId thread_id);
/**
* @brief Get thread appid
*
* @param thread_id
* @return const char* appid
*/
const char* thread_get_appid(ThreadId thread_id);
/**
* @brief Get thread stack watermark
*
+31 -90
View File
@@ -1,148 +1,89 @@
#include "Timer.h"
#include "Check.h"
#include "Kernel.h"
#include <cstdlib>
#ifdef ESP_PLATFORM
#include "freertos/FreeRTOS.h"
#include "freertos/timers.h"
#else
#include "FreeRTOS.h"
#include "timers.h"
#endif
namespace tt {
typedef struct {
TimerCallback func;
void* context;
} TimerCallback_t;
static void timer_callback(TimerHandle_t hTimer) {
auto* callback = static_cast<TimerCallback_t*>(pvTimerGetTimerID(hTimer));
auto* timer = static_cast<Timer*>(pvTimerGetTimerID(hTimer));
if (callback != nullptr) {
callback->func(callback->context);
if (timer != nullptr) {
timer->callback(timer->callbackContext);
}
}
Timer* timer_alloc(TimerCallback func, TimerType type, void* context) {
tt_assert((kernel_is_irq() == 0U) && (func != nullptr));
auto* callback = static_cast<TimerCallback_t*>(malloc(sizeof(TimerCallback_t)));
Timer::Timer(Type type, Callback callback, void* callbackContext) {
tt_assert((kernel_is_irq() == 0U) && (callback != nullptr));
callback->func = func;
callback->context = context;
this->callback = callback;
this->callbackContext = callbackContext;
UBaseType_t reload;
if (type == TimerTypeOnce) {
if (type == TypeOnce) {
reload = pdFALSE;
} else {
reload = pdTRUE;
}
// TimerCallback function is always provided as a callback and is used to call application
// specified function with its context both stored in structure callb.
// TODO: should we use pointer to function or function directly as-is?
TimerHandle_t hTimer = xTimerCreate(nullptr, portMAX_DELAY, (BaseType_t)reload, callback, timer_callback);
tt_assert(hTimer);
/* Return timer ID */
return (Timer*)hTimer;
this->timerHandle = xTimerCreate(nullptr, portMAX_DELAY, (BaseType_t)reload, this, timer_callback);
tt_assert(this->timerHandle);
}
void timer_free(Timer* instance) {
Timer::~Timer() {
tt_assert(!kernel_is_irq());
tt_assert(instance);
auto hTimer = static_cast<TimerHandle_t>(instance);
auto* callback = static_cast<TimerCallback_t*>(pvTimerGetTimerID(hTimer));
tt_check(xTimerDelete(hTimer, portMAX_DELAY) == pdPASS);
while (timer_is_running(instance)) delay_tick(2);
/* Return allocated memory to dynamic pool */
free(callback);
tt_check(xTimerDelete(timerHandle, portMAX_DELAY) == pdPASS);
}
TtStatus timer_start(Timer* instance, uint32_t ticks) {
TtStatus Timer::start(uint32_t ticks) {
tt_assert(!kernel_is_irq());
tt_assert(instance);
tt_assert(ticks < portMAX_DELAY);
auto hTimer = static_cast<TimerHandle_t>(instance);
TtStatus stat;
if (xTimerChangePeriod(hTimer, ticks, portMAX_DELAY) == pdPASS) {
stat = TtStatusOk;
if (xTimerChangePeriod(timerHandle, ticks, portMAX_DELAY) == pdPASS) {
return TtStatusOk;
} else {
stat = TtStatusErrorResource;
return TtStatusErrorResource;
}
/* Return execution status */
return (stat);
}
TtStatus timer_restart(Timer* instance, uint32_t ticks) {
TtStatus Timer::restart(uint32_t ticks) {
tt_assert(!kernel_is_irq());
tt_assert(instance);
tt_assert(ticks < portMAX_DELAY);
auto hTimer = static_cast<TimerHandle_t>(instance);
TtStatus stat;
if (xTimerChangePeriod(hTimer, ticks, portMAX_DELAY) == pdPASS &&
xTimerReset(hTimer, portMAX_DELAY) == pdPASS) {
stat = TtStatusOk;
if (xTimerChangePeriod(timerHandle, ticks, portMAX_DELAY) == pdPASS &&
xTimerReset(timerHandle, portMAX_DELAY) == pdPASS) {
return TtStatusOk;
} else {
stat = TtStatusErrorResource;
return TtStatusErrorResource;
}
/* Return execution status */
return (stat);
}
TtStatus timer_stop(Timer* instance) {
TtStatus Timer::stop() {
tt_assert(!kernel_is_irq());
tt_assert(instance);
auto hTimer = static_cast<TimerHandle_t>(instance);
tt_check(xTimerStop(hTimer, portMAX_DELAY) == pdPASS);
tt_check(xTimerStop(timerHandle, portMAX_DELAY) == pdPASS);
return TtStatusOk;
}
uint32_t timer_is_running(Timer* instance) {
bool Timer::isRunning() {
tt_assert(!kernel_is_irq());
tt_assert(instance);
auto hTimer = static_cast<TimerHandle_t>(instance);
/* Return 0: not running, 1: running */
return (uint32_t)xTimerIsTimerActive(hTimer);
return xTimerIsTimerActive(timerHandle) == pdTRUE;
}
uint32_t timer_get_expire_time(Timer* instance) {
uint32_t Timer::getExpireTime() {
tt_assert(!kernel_is_irq());
tt_assert(instance);
auto hTimer = static_cast<TimerHandle_t>(instance);
return (uint32_t)xTimerGetExpiryTime(hTimer);
return (uint32_t)xTimerGetExpiryTime(timerHandle);
}
void timer_pending_callback(TimerPendigCallback callback, void* context, uint32_t arg) {
void Timer::pendingCallback(PendigCallback callback, void* callbackContext, uint32_t arg) {
BaseType_t ret = pdFAIL;
if (kernel_is_irq()) {
ret = xTimerPendFunctionCallFromISR(callback, context, arg, nullptr);
ret = xTimerPendFunctionCallFromISR(callback, callbackContext, arg, nullptr);
} else {
ret = xTimerPendFunctionCall(callback, context, arg, TtWaitForever);
ret = xTimerPendFunctionCall(callback, callbackContext, arg, TtWaitForever);
}
tt_assert(ret == pdPASS);
}
void timer_set_thread_priority(TimerThreadPriority priority) {
void Timer::setThreadPriority(TimerThreadPriority priority) {
tt_assert(!kernel_is_irq());
TaskHandle_t task_handle = xTimerGetTimerDaemonTaskHandle();
+89 -81
View File
@@ -2,101 +2,109 @@
#include "CoreTypes.h"
#ifdef ESP_PLATFORM
#include "freertos/FreeRTOS.h"
#include "freertos/timers.h"
#else
#include "FreeRTOS.h"
#include "timers.h"
#endif
namespace tt {
typedef void (*TimerCallback)(void* context);
typedef enum {
TimerTypeOnce = 0, ///< One-shot timer.
TimerTypePeriodic = 1 ///< Repeating timer.
} TimerType;
class Timer {
private:
TimerHandle_t timerHandle;
public:
typedef void Timer;
typedef void (*Callback)(void* context);
typedef void (*PendigCallback)(void* context, uint32_t arg);
/** Allocate timer
*
* @param[in] func The callback function
* @param[in] type The timer type
* @param context The callback context
*
* @return The pointer to Timer instance
*/
Timer* timer_alloc(TimerCallback func, TimerType type, void* context);
/** Free timer
*
* @param instance The pointer to Timer instance
*/
void timer_free(Timer* instance);
Callback callback;
void* callbackContext;
/** Start timer
*
* @warning This is asynchronous call, real operation will happen as soon as
* timer service process this request.
*
* @param instance The pointer to Timer instance
* @param[in] ticks The interval in ticks
*
* @return The status.
*/
TtStatus timer_start(Timer* instance, uint32_t ticks);
typedef enum {
TypeOnce = 0, ///< One-shot timer.
TypePeriodic = 1 ///< Repeating timer.
} Type;
/** Restart timer with previous timeout value
*
* @warning This is asynchronous call, real operation will happen as soon as
* timer service process this request.
*
* @param instance The pointer to Timer instance
* @param[in] ticks The interval in ticks
*
* @return The status.
*/
TtStatus timer_restart(Timer* instance, uint32_t ticks);
/**
* @param[in] type The timer type
* @param[in] callback The callback function
* @param callbackContext The callback context
*/
Timer(Type type, Callback callback, void* callbackContext);
/** Stop timer
*
* @warning This is asynchronous call, real operation will happen as soon as
* timer service process this request.
*
* @param instance The pointer to Timer instance
*
* @return The status.
*/
TtStatus timer_stop(Timer* instance);
~Timer();
/** Is timer running
*
* @warning This cal may and will return obsolete timer state if timer
* commands are still in the queue. Please read FreeRTOS timer
* documentation first.
*
* @param instance The pointer to Timer instance
*
* @return 0: not running, 1: running
*/
uint32_t timer_is_running(Timer* instance);
/** Start timer
*
* @warning This is asynchronous call, real operation will happen as soon as
* timer service process this request.
*
* @param[in] ticks The interval in ticks
* @return The status.
*/
TtStatus start(uint32_t ticks);
/** Restart timer with previous timeout value
*
* @warning This is asynchronous call, real operation will happen as soon as
* timer service process this request.
*
* @param[in] ticks The interval in ticks
*
* @return The status.
*/
TtStatus restart(uint32_t ticks);
/** Stop timer
*
* @warning This is asynchronous call, real operation will happen as soon as
* timer service process this request.
*
* @return The status.
*/
TtStatus stop();
/** Is timer running
*
* @warning This cal may and will return obsolete timer state if timer
* commands are still in the queue. Please read FreeRTOS timer
* documentation first.
*
* @return true when running
*/
bool isRunning();
/** Get timer expire time
*
* @param instance The Timer instance
*
* @return expire tick
*/
uint32_t getExpireTime();
void pendingCallback(PendigCallback callback, void* callbackContext, uint32_t arg);
typedef enum {
TimerThreadPriorityNormal, /**< Lower then other threads */
TimerThreadPriorityElevated, /**< Same as other threads */
} TimerThreadPriority;
/** Set Timer thread priority
*
* @param[in] priority The priority
*/
void setThreadPriority(TimerThreadPriority priority);
};
/** Get timer expire time
*
* @param instance The Timer instance
*
* @return expire tick
*/
uint32_t timer_get_expire_time(Timer* instance);
typedef void (*TimerPendigCallback)(void* context, uint32_t arg);
void timer_pending_callback(TimerPendigCallback callback, void* context, uint32_t arg);
typedef enum {
TimerThreadPriorityNormal, /**< Lower then other threads */
TimerThreadPriorityElevated, /**< Same as other threads */
} TimerThreadPriority;
/** Set Timer thread priority
*
* @param[in] priority The priority
*/
void timer_set_thread_priority(TimerThreadPriority priority);
} // namespace