ESPHome 2026.6.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
16 public:
17 bool parse_device(const esp32_ble_tracker::ESPBTDevice &device) override {
18 char addr_buf[MAC_ADDRESS_PRETTY_BUFFER_SIZE];
19 // Escape special characters in the device name for valid JSON
20 const char *name = device.get_name().c_str();
21 char escaped_name[128];
22 size_t pos = 0;
23 for (; *name != '\0' && pos < sizeof(escaped_name) - 7; name++) {
24 uint8_t c = static_cast<uint8_t>(*name);
25 if (c == '"' || c == '\\') {
26 escaped_name[pos++] = '\\';
27 escaped_name[pos++] = c;
28 } else if (c < 0x20) {
29 pos += snprintf(escaped_name + pos, sizeof(escaped_name) - pos, "\\u%04x", c);
30 } else {
31 escaped_name[pos++] = c;
32 }
33 }
34 escaped_name[pos] = '\0';
35
36 char buf[256];
37 snprintf(buf, sizeof(buf), "{\"timestamp\":%" PRId64 ",\"address\":\"%s\",\"rssi\":%d,\"name\":\"%s\"}",
38 static_cast<int64_t>(::time(nullptr)), device.address_str_to(addr_buf), device.get_rssi(), escaped_name);
39 this->publish_state(buf);
40 return true;
41 }
42 void dump_config() override;
43};
44
45} // namespace esphome::ble_scanner
46
47#endif
bool parse_device(const esp32_ble_tracker::ESPBTDevice &device) override
Definition ble_scanner.h:17
const char * address_str_to(std::span< char, MAC_ADDRESS_PRETTY_BUFFER_SIZE > buf) const
Format MAC address into provided buffer, returns pointer to buffer for convenience.
void publish_state(const std::string &state)
size_t size_t pos
Definition helpers.h:1038