arduino-audio-tools
QueueRTOS.h
1 #pragma once
2 #include "AudioBasic/Collections/Allocator.h"
3 #include "AudioConfig.h"
4 
5 #if defined(USE_CONCURRENCY)
6 #ifdef ESP32
7 # include <freertos/queue.h>
8 # include "freertos/FreeRTOS.h"
9 #else
10 # include "FreeRTOS.h"
11 # include "queue.h"
12 #endif
13 
14 namespace audio_tools {
15 
25 template <class T>
26 class QueueRTOS {
27  public:
28  QueueRTOS(int size, TickType_t writeMaxWait = portMAX_DELAY,
29  TickType_t readMaxWait = portMAX_DELAY,
30  Allocator& allocator = DefaultAllocator) {
31  TRACED();
32  p_allocator = &allocator;
33  read_max_wait = readMaxWait;
34  write_max_wait = writeMaxWait;
35  queue_size = size;
36  setup();
37  };
38 
39  ~QueueRTOS() {
40  TRACED();
41  end();
42  }
43 
44  void setReadMaxWait(TickType_t ticks) { read_max_wait = ticks; }
45 
46  void setWriteMaxWait(TickType_t ticks) { write_max_wait = ticks; }
47 
49  bool resize(int size) {
50  bool result = true;
51  TRACED();
52  if (size != queue_size) {
53  end();
54  queue_size = size;
55  result = setup();
56  }
57  return result;
58  }
59 
60  bool enqueue(T& data) {
61  TRACED();
62  if (xQueue==nullptr) return false;
63  return xQueueSend(xQueue, (void*)&data, (TickType_t)write_max_wait);
64  }
65 
66  bool peek(T& data) {
67  TRACED();
68  if (xQueue==nullptr) return false;
69  return xQueuePeek(xQueue, &data, (TickType_t)read_max_wait);
70  }
71 
72  bool dequeue(T& data) {
73  TRACED();
74  if (xQueue==nullptr) return false;
75  return xQueueReceive(xQueue, &data, (TickType_t)read_max_wait);
76  }
77 
78  size_t size() { return queue_size; }
79 
80  bool clear() {
81  TRACED();
82  if (xQueue==nullptr) return false;
83  xQueueReset(xQueue);
84  return true;
85  }
86 
87  bool empty() { return size() == 0; }
88 
89  protected:
90  QueueHandle_t xQueue = nullptr;
91  TickType_t write_max_wait = portMAX_DELAY;
92  TickType_t read_max_wait = portMAX_DELAY;
93  Allocator* p_allocator = nullptr;
94  int queue_size;
95  uint8_t* p_data = nullptr;
96  StaticQueue_t queue_buffer;
97 
98  bool setup() {
99  if (queue_size > 0) {
100  p_data = (uint8_t*)p_allocator->allocate((queue_size + 1) * sizeof(T));
101  if (p_data == nullptr) return false;
102  xQueue = xQueueCreateStatic(queue_size, sizeof(T), p_data, &queue_buffer);
103  if (xQueue == nullptr) return false;
104  }
105  return true;
106  }
107 
108  void end() {
109  if (xQueue != nullptr) vQueueDelete(xQueue);
110  if (p_data != nullptr) p_allocator->free(p_data);
111  }
112 };
113 
114 } // namespace audio_tools
115 
116 #endif
Memory allocateator which uses malloc.
Definition: Allocator.h:22
FIFO Queue whch is based on the FreeRTOS queue API. The default allocator will allocate the memory fr...
Definition: QueueRTOS.h:26
bool resize(int size)
(Re-)defines the size
Definition: QueueRTOS.h:49
Generic Implementation of sound input and output for desktop environments using portaudio.
Definition: AnalogAudio.h:10