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