stm32f1xx_HBL/srv/task.c
2024-07-06 22:43:50 +02:00

91 lines
1.9 KiB
C

/** @file task.c
* Module handling the task creation and management
*
* The module provides an API to create, run and manage lightweight, stack-less
* threads (tasks). This system is based on protothreads,
* see https://dunkels.com/adam/pt/index.html
*/
//--includes--------------------------------------------------------------------
#include "task.h"
#include "error.h"
//--local definitions-----------------------------------------------------------
#define MAX_TASK_NB 10
//--local variables-------------------------------------------------------------
static struct Task task_list[MAX_TASK_NB];
static uint8_t task_nb;
//--public functions------------------------------------------------------------
void task_schedule(uint32_t elapsed_ms)
{
for (uint8_t i = 0; i < task_nb; ++i) {
if (task_list[i].function != nullptr) {
if (task_list[i].state.is_active
|| task_list[i].state.delay <= 0) {
task_list[i].function(&task_list[i].state);
if (task_list[i].state.count == _TASK_COUNT_EXIT) {
task_list[i].function = nullptr;
}
} else {
task_list[i].state.delay -= elapsed_ms;
}
}
}
}
void task_start(TaskFunction function)
{
for (uint8_t i = 0; i < MAX_TASK_NB; ++i) {
if (task_list[i].function == nullptr) {
task_list[i].function = function;
task_list[i].state.delay = 0;
task_list[i].state.count = 0;
task_list[i].state.is_active = false;
++task_nb;
return;
}
}
error_trigger("task list is full");
}
void task_stop(TaskFunction function)
{
for (uint8_t i = 0; i < task_nb; ++i) {
if (task_list[i].function == function) {
task_list[i].state.count = _TASK_COUNT_CLEANUP & 0x7F;
task_list[i].function(&task_list[i].state);
task_list[i].function = nullptr;
return;
}
}
error_trigger("task does not exist");
}
bool task_is_running(TaskFunction function)
{
for (uint8_t i = 0; i < task_nb; ++i) {
if (task_list[i].function == function) {
return true;
}
}
return false;
}