ESPHome
2026.8.0-dev
Loading...
Searching...
No Matches
esphome
components
ble_scanner
ble_scanner.h
Go to the documentation of this file.
1
#pragma once
2
3
#include <cinttypes>
4
#include <cstdio>
5
#include <ctime>
6
7
#include "
esphome/core/component.h
"
8
#include "
esphome/components/esp32_ble_tracker/esp32_ble_tracker.h
"
9
#include "
esphome/components/text_sensor/text_sensor.h
"
10
11
#ifdef USE_ESP32
12
13
namespace
esphome::ble_scanner
{
14
15
class
BLEScanner
final :
public
text_sensor::TextSensor
,
16
public
esp32_ble_tracker::ESPBTDeviceListener
,
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
esphome::Component
Definition
component.h:145
esphome::ble_device_base::ESPBTDevice
Definition
ble_device.h:151
esphome::ble_device_base::ESPBTDevice::address_str_to
const char * address_str_to(char *buf) const
Buffer overload: writes "XX:XX:XX:XX:XX:XX\0" into buf (>= 18 bytes), returns buf.
Definition
ble_device.cpp:349
esphome::ble_device_base::ESPBTDevice::get_rssi
int get_rssi() const
Definition
ble_device.h:185
esphome::ble_device_base::ESPBTDevice::get_name
const std::string & get_name() const
Definition
ble_device.h:186
esphome::ble_scanner::BLEScanner
Definition
ble_scanner.h:17
esphome::ble_scanner::BLEScanner::dump_config
void dump_config() override
Definition
ble_scanner.cpp:10
esphome::ble_scanner::BLEScanner::parse_device
bool parse_device(const esp32_ble_tracker::ESPBTDevice &device) override
Definition
ble_scanner.h:19
esphome::esp32_ble_tracker::ESPBTDeviceListener
Definition
esp32_ble_tracker.h:60
esphome::text_sensor::TextSensor
Definition
text_sensor.h:28
esphome::text_sensor::TextSensor::publish_state
void publish_state(const std::string &state)
Definition
text_sensor.cpp:21
component.h
esp32_ble_tracker.h
esphome::ble_scanner
Definition
ble_scanner.cpp:6
esphome::pos
size_t size_t pos
Definition
helpers.h:1052
text_sensor.h
Generated by
1.12.0