ESPHome 2026.8.0-dev
Loading...
Searching...
No Matches
ble_scanner.h
Go to the documentation of this file.
1#pragma once
2
3#include <cinttypes>
4#include <cstdio>
5#include <ctime>
6
10
11#ifdef USE_ESP32
12
13namespace esphome::ble_scanner {
14
17 public Component {
18 public:
19 bool parse_device(const esp32_ble_tracker::ESPBTDevice &device) override {
20 char addr_buf[MAC_ADDRESS_PRETTY_BUFFER_SIZE];
21 // Escape special characters in the device name for valid JSON
22 const char *name = device.get_name().c_str();
23 char escaped_name[128];
24 size_t pos = 0;
25 for (; *name != '\0' && pos < sizeof(escaped_name) - 7; name++) {
26 uint8_t c = static_cast<uint8_t>(*name);
27 if (c == '"' || c == '\\') {
28 escaped_name[pos++] = '\\';
29 escaped_name[pos++] = c;
30 } else if (c < 0x20) {
31 pos += snprintf(escaped_name + pos, sizeof(escaped_name) - pos, "\\u%04x", c);
32 } else {
33 escaped_name[pos++] = c;
34 }
35 }
36 escaped_name[pos] = '\0';
37
38 char buf[256];
39 snprintf(buf, sizeof(buf), "{\"timestamp\":%" PRId64 ",\"address\":\"%s\",\"rssi\":%d,\"name\":\"%s\"}",
40 static_cast<int64_t>(::time(nullptr)), device.address_str_to(addr_buf), device.get_rssi(), escaped_name);
41 this->publish_state(buf);
42 return true;
43 }
44 void dump_config() override;
45};
46
47} // namespace esphome::ble_scanner
48
49#endif
const char * address_str_to(char *buf) const
Buffer overload: writes "XX:XX:XX:XX:XX:XX\0" into buf (>= 18 bytes), returns buf.
const std::string & get_name() const
Definition ble_device.h:186
bool parse_device(const esp32_ble_tracker::ESPBTDevice &device) override
Definition ble_scanner.h:19
void publish_state(const std::string &state)
size_t size_t pos
Definition helpers.h:1052