[ble_scanner] Use stack-based string formatting to reduce heap allocations (#13013)

This commit is contained in:
J. Nick Koston
2026-01-06 07:34:38 -10:00
committed by GitHub
parent e0981323bd
commit 11aed601b8
+9 -12
View File
@@ -1,7 +1,8 @@
#pragma once #pragma once
#include <cinttypes>
#include <cstdio>
#include <ctime> #include <ctime>
#include <string>
#include "esphome/core/component.h" #include "esphome/core/component.h"
#include "esphome/components/esp32_ble_tracker/esp32_ble_tracker.h" #include "esphome/components/esp32_ble_tracker/esp32_ble_tracker.h"
@@ -15,17 +16,13 @@ namespace ble_scanner {
class BLEScanner : public text_sensor::TextSensor, public esp32_ble_tracker::ESPBTDeviceListener, public Component { class BLEScanner : public text_sensor::TextSensor, public esp32_ble_tracker::ESPBTDeviceListener, public Component {
public: public:
bool parse_device(const esp32_ble_tracker::ESPBTDevice &device) override { bool parse_device(const esp32_ble_tracker::ESPBTDevice &device) override {
this->publish_state("{\"timestamp\":" + to_string(::time(nullptr)) + // Format JSON using stack buffer to avoid heap allocations from string concatenation
"," char buf[128];
"\"address\":\"" + char addr_buf[MAC_ADDRESS_PRETTY_BUFFER_SIZE];
device.address_str() + snprintf(buf, sizeof(buf), "{\"timestamp\":%" PRId64 ",\"address\":\"%s\",\"rssi\":%d,\"name\":\"%s\"}",
"\"," static_cast<int64_t>(::time(nullptr)), device.address_str_to(addr_buf), device.get_rssi(),
"\"rssi\":" + device.get_name().c_str());
to_string(device.get_rssi()) + this->publish_state(buf);
","
"\"name\":\"" +
device.get_name() + "\"}");
return true; return true;
} }
void dump_config() override; void dump_config() override;