ESPHome 2026.3.0
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 {
14namespace ble_scanner {
15
17 public:
18 bool parse_device(const esp32_ble_tracker::ESPBTDevice &device) override {
19 char addr_buf[MAC_ADDRESS_PRETTY_BUFFER_SIZE];
20 // Escape special characters in the device name for valid JSON
21 const char *name = device.get_name().c_str();
22 char escaped_name[128];
23 size_t pos = 0;
24 for (; *name != '\0' && pos < sizeof(escaped_name) - 7; name++) {
25 uint8_t c = static_cast<uint8_t>(*name);
26 if (c == '"' || c == '\\') {
27 escaped_name[pos++] = '\\';
28 escaped_name[pos++] = c;
29 } else if (c < 0x20) {
30 pos += snprintf(escaped_name + pos, sizeof(escaped_name) - pos, "\\u%04x", c);
31 } else {
32 escaped_name[pos++] = c;
33 }
34 }
35 escaped_name[pos] = '\0';
36
37 char buf[256];
38 snprintf(buf, sizeof(buf), "{\"timestamp\":%" PRId64 ",\"address\":\"%s\",\"rssi\":%d,\"name\":\"%s\"}",
39 static_cast<int64_t>(::time(nullptr)), device.address_str_to(addr_buf), device.get_rssi(), escaped_name);
40 this->publish_state(buf);
41 return true;
42 }
43 void dump_config() override;
44};
45
46} // namespace ble_scanner
47} // namespace esphome
48
49#endif
bool parse_device(const esp32_ble_tracker::ESPBTDevice &device) override
Definition ble_scanner.h:18
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)
Providing packet encoding functions for exchanging data with a remote host.
Definition a01nyub.cpp:7
size_t size_t pos
Definition helpers.h:929