arduino-audio-tools
Loading...
Searching...
No Matches
Task.h
1#pragma once
2
3#ifdef ESP32
4#include "freertos/FreeRTOS.h"
5#include "freertos/task.h"
6#elif defined(__linux__)
7#else
8#include "FreeRTOS.h"
9#include "task.h"
10#endif
11#include <functional>
12
13namespace audio_tools {
14
21class Task {
22 public:
24 Task(const char* name, int stackSize, int priority = 1, int core = -1) {
25 create(name, stackSize, priority, core);
26 }
27
28 Task() = default;
29 ~Task() { remove(); }
30
32 bool create(const char* name, int stackSize, int priority = 1,
33 int core = -1) {
34 if (xHandle != 0) return false;
35#ifdef ESP32
36 if (core >= 0)
37 xTaskCreatePinnedToCore(task_loop, name, stackSize, this, priority,
38 &xHandle, core);
39 else
40 xTaskCreate(task_loop, name, stackSize, this, priority, &xHandle);
41#else
42 xTaskCreate(task_loop, name, stackSize, this, priority, &xHandle);
43#endif
44 suspend();
45 return true;
46 }
47
49 void remove() {
50 if (xHandle != nullptr) {
51 suspend();
52 vTaskDelete(xHandle);
53 xHandle = nullptr;
54 }
55 }
56
57 bool begin(std::function<void()> process) {
58 LOGI("staring task");
59 loop_code = process;
60 resume();
61 return true;
62 }
63
65 void end() { suspend(); }
66
67 void suspend() { vTaskSuspend(xHandle); }
68
69 void resume() { vTaskResume(xHandle); }
70
71 TaskHandle_t &getTaskHandle() {
72 return xHandle;
73 }
74
75 void setReference(void *r){
76 ref = r;
77 }
78
79 void *getReference(){
80 return ref;
81 }
82
83#ifdef ESP32
84 int getCoreID() {
85 return xPortGetCoreID();
86 }
87#endif
88
89 protected:
90 TaskHandle_t xHandle = nullptr;
91 std::function<void()> loop_code = nop;
92 void *ref;
93
94 static void nop() { delay(100); }
95
96 static void task_loop(void* arg) {
97 Task* self = (Task*)arg;
98 while (true) {
99 self->loop_code();
100 }
101 }
102};
103
104} // namespace audio_tools
105
FreeRTOS task.
Definition Task.h:21
bool create(const char *name, int stackSize, int priority=1, int core=-1)
If you used the empty constructor, you need to call create!
Definition Task.h:32
void remove()
deletes the FreeRTOS task
Definition Task.h:49
Task(const char *name, int stackSize, int priority=1, int core=-1)
Defines and creates a FreeRTOS task.
Definition Task.h:24
void end()
suspends the task
Definition Task.h:65
Generic Implementation of sound input and output for desktop environments using portaudio.
Definition AudioCodecsBase.h:10