1
0
mirror of https://github.com/esphome/esphome.git synced 2026-02-08 08:41:59 +00:00

avoid heap wifi scans

This commit is contained in:
J. Nick Koston
2026-01-20 12:56:53 -10:00
parent 6edecd3d45
commit b1304f64cb
2 changed files with 10 additions and 7 deletions

View File

@@ -827,7 +827,8 @@ void WiFiComponent::wifi_process_event_(IDFWiFiEvent *data) {
}
uint16_t number = it.number;
auto records = std::make_unique<wifi_ap_record_t[]>(number);
// Stack buffer for up to 38 APs (~3.5KB), heap fallback for dense environments
SmallBufferWithHeapFallback<38, wifi_ap_record_t> records(number);
err = esp_wifi_scan_get_ap_records(&number, records.get());
if (err != ESP_OK) {
ESP_LOGW(TAG, "esp_wifi_scan_get_ap_records failed: %s", esp_err_to_name(err));

View File

@@ -371,13 +371,15 @@ template<typename T> class FixedVector {
/// @brief Helper class for efficient buffer allocation - uses stack for small sizes, heap for large
/// This is useful when most operations need a small buffer but occasionally need larger ones.
/// The stack buffer avoids heap allocation in the common case, while heap fallback handles edge cases.
template<size_t STACK_SIZE> class SmallBufferWithHeapFallback {
/// @tparam STACK_SIZE Number of elements in the stack buffer
/// @tparam T Element type (default: uint8_t)
template<size_t STACK_SIZE, typename T = uint8_t> class SmallBufferWithHeapFallback {
public:
explicit SmallBufferWithHeapFallback(size_t size) {
if (size <= STACK_SIZE) {
this->buffer_ = this->stack_buffer_;
} else {
this->heap_buffer_ = new uint8_t[size];
this->heap_buffer_ = new T[size];
this->buffer_ = this->heap_buffer_;
}
}
@@ -389,12 +391,12 @@ template<size_t STACK_SIZE> class SmallBufferWithHeapFallback {
SmallBufferWithHeapFallback(SmallBufferWithHeapFallback &&) = delete;
SmallBufferWithHeapFallback &operator=(SmallBufferWithHeapFallback &&) = delete;
uint8_t *get() { return this->buffer_; }
T *get() { return this->buffer_; }
private:
uint8_t stack_buffer_[STACK_SIZE];
uint8_t *heap_buffer_{nullptr};
uint8_t *buffer_;
T stack_buffer_[STACK_SIZE];
T *heap_buffer_{nullptr};
T *buffer_;
};
///@}