ESPHome  2024.11.0
queue.h
Go to the documentation of this file.
1 #pragma once
2 
3 #ifdef USE_ESP32
4 
5 #include <mutex>
6 #include <queue>
7 
8 #include <freertos/FreeRTOS.h>
9 #include <freertos/semphr.h>
10 
11 /*
12  * BLE events come in from a separate Task (thread) in the ESP32 stack. Rather
13  * than trying to deal with various locking strategies, all incoming GAP and GATT
14  * events will simply be placed on a semaphore guarded queue. The next time the
15  * component runs loop(), these events are popped off the queue and handed at
16  * this safer time.
17  */
18 
19 namespace esphome {
20 namespace esp32_ble {
21 
22 template<class T> class Queue {
23  public:
24  Queue() { m_ = xSemaphoreCreateMutex(); }
25 
26  void push(T *element) {
27  if (element == nullptr)
28  return;
29  if (xSemaphoreTake(m_, 5L / portTICK_PERIOD_MS)) {
30  q_.push(element);
31  xSemaphoreGive(m_);
32  }
33  }
34 
35  T *pop() {
36  T *element = nullptr;
37 
38  if (xSemaphoreTake(m_, 5L / portTICK_PERIOD_MS)) {
39  if (!q_.empty()) {
40  element = q_.front();
41  q_.pop();
42  }
43  xSemaphoreGive(m_);
44  }
45  return element;
46  }
47 
48  protected:
49  std::queue<T *> q_;
50  SemaphoreHandle_t m_;
51 };
52 
53 } // namespace esp32_ble
54 } // namespace esphome
55 
56 #endif
std::queue< T * > q_
Definition: queue.h:49
void push(T *element)
Definition: queue.h:26
Implementation of SPI Controller mode.
Definition: a01nyub.cpp:7
SemaphoreHandle_t m_
Definition: queue.h:50