ESPHome 2025.6.1
Loading...
Searching...
No Matches
ble_event_pool.h
Go to the documentation of this file.
1#pragma once
2
3#ifdef USE_ESP32
4
5#include <atomic>
6#include <cstddef>
7#include "ble_event.h"
8#include "queue.h"
10
11namespace esphome {
12namespace esp32_ble {
13
14// BLE Event Pool - On-demand pool of BLEEvent objects to avoid heap fragmentation
15// Events are allocated on first use and reused thereafter, growing to peak usage
16template<uint8_t SIZE> class BLEEventPool {
17 public:
18 BLEEventPool() : total_created_(0) {}
19
21 // Clean up any remaining events in the free list
22 BLEEvent *event;
23 while ((event = this->free_list_.pop()) != nullptr) {
24 delete event;
25 }
26 }
27
28 // Allocate an event from the pool
29 // Returns nullptr if pool is full
31 // Try to get from free list first
32 BLEEvent *event = this->free_list_.pop();
33 if (event != nullptr)
34 return event;
35
36 // Need to create a new event
37 if (this->total_created_ >= SIZE) {
38 // Pool is at capacity
39 return nullptr;
40 }
41
42 // Use internal RAM for better performance
44 event = allocator.allocate(1);
45
46 if (event == nullptr) {
47 // Memory allocation failed
48 return nullptr;
49 }
50
51 // Placement new to construct the object
52 new (event) BLEEvent();
53 this->total_created_++;
54 return event;
55 }
56
57 // Return an event to the pool for reuse
58 void release(BLEEvent *event) {
59 if (event != nullptr) {
60 this->free_list_.push(event);
61 }
62 }
63
64 private:
65 LockFreeQueue<BLEEvent, SIZE> free_list_; // Free events ready for reuse
66 uint8_t total_created_; // Total events created (high water mark)
67};
68
69} // namespace esp32_ble
70} // namespace esphome
71
72#endif
An STL allocator that uses SPI or internal RAM.
Definition helpers.h:684
T * allocate(size_t n)
Definition helpers.h:704
void release(BLEEvent *event)
Providing packet encoding functions for exchanging data with a remote host.
Definition a01nyub.cpp:7