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