ESPHome 2026.11.0b6
Loading...
Searching...
No Matches
ble_server.cpp
Go to the documentation of this file.
1#ifdef USE_ZEPHYR
2#include "ble_server.h"
6#include "esphome/core/log.h"
7#include <zephyr/bluetooth/bluetooth.h>
8#include <zephyr/settings/settings.h>
9
11
12ESPHOME_LOG_TAG(TAG, "zephyr_ble_server");
13
14static k_work advertise_work; // NOLINT(cppcoreguidelines-avoid-non-const-global-variables)
15
16BLEServer *global_ble_server; // NOLINT(cppcoreguidelines-avoid-non-const-global-variables)
17
18// What the advertisement has left for the name: the flags take 3 bytes and the name header 2
19static constexpr size_t MAX_ADV_NAME_LEN = BT_GAP_ADV_MAX_ADV_DATA_LEN - 3 - 2;
20
21static const bt_data SD[] = {
22#ifdef USE_OTA
23 BT_DATA_BYTES(BT_DATA_UUID128_ALL, 0x84, 0xaa, 0x60, 0x74, 0x52, 0x8a, 0x8b, 0x86, 0xd3, 0x4c, 0xb7, 0x1d, 0x1d,
24 0xdc, 0x53, 0x8d),
25#endif
26};
27
28const bt_le_adv_param *const ADV_PARAM = BT_LE_ADV_CONN;
29
30static void advertise(k_work *work) {
31 int rc = bt_le_adv_stop();
32 if (rc) {
33 ESP_LOGE(TAG, "Advertising failed to stop (rc %d)", rc);
34 }
35
36 // Zephyr would cut the end of a long name, which is where the MAC suffix is
37 char name[MAX_ADV_NAME_LEN + 1];
38 const auto &app_name = App.get_name();
39 const size_t name_len =
40 truncate_name_to(name, sizeof(name), app_name.c_str(), app_name.length(),
41 App.is_name_add_mac_suffix_enabled() ? MAC_ADDRESS_SUFFIX_WITH_SEPARATOR_LEN : 0);
42 const uint8_t name_type = name_len < app_name.length() ? BT_DATA_NAME_SHORTENED : BT_DATA_NAME_COMPLETE;
43 static constexpr uint8_t FLAGS[] = {BT_LE_AD_GENERAL | BT_LE_AD_NO_BREDR};
44 const bt_data ad[] = {
45 BT_DATA(BT_DATA_FLAGS, FLAGS, sizeof(FLAGS)),
46 BT_DATA(name_type, name, static_cast<uint8_t>(name_len)),
47 };
48
49 rc = bt_le_adv_start(ADV_PARAM, ad, ARRAY_SIZE(ad), SD, ARRAY_SIZE(SD));
50 if (rc) {
51 ESP_LOGE(TAG, "Advertising failed to start (rc %d)", rc);
52 return;
53 }
54 ESP_LOGI(TAG, "Advertising successfully started");
55}
56
57void BLEServer::connected(bt_conn *conn, uint8_t err) {
58 char addr[BT_ADDR_LE_STR_LEN];
59 bt_addr_le_to_str(bt_conn_get_dst(conn), addr, sizeof(addr));
60 if (err) {
61 ESP_LOGE(TAG, "Failed to connect to %s (%u)", addr, err);
62 return;
63 }
64 ESP_LOGI(TAG, "Connected %s", addr);
65#ifdef CONFIG_BT_SMP
66 if (bt_conn_set_security(conn, BT_SECURITY_L4)) {
67 ESP_LOGE(TAG, "Failed to set security");
68 }
69#endif
70 conn = bt_conn_ref(conn);
72}
73
74void BLEServer::disconnected(bt_conn *conn, uint8_t reason) {
75 char addr[BT_ADDR_LE_STR_LEN];
76
77 bt_addr_le_to_str(bt_conn_get_dst(conn), addr, sizeof(addr));
78
79 ESP_LOGI(TAG, "Disconnected from %s (reason 0x%02x)", addr, reason);
80 conn = bt_conn_ref(conn);
81 global_ble_server->defer([conn]() {
82 if (global_ble_server->conn_ == conn) {
83 bt_conn_unref(conn);
84 global_ble_server->conn_ = nullptr;
85 }
86 bt_conn_unref(conn);
87 });
88 k_work_submit(&advertise_work);
89}
90
91void BLEServer::set_conn_(bt_conn *conn) {
92 // The disconnect may have run first; deferred callbacks are not ordered on this platform.
93 bt_conn_info info;
94 if (bt_conn_get_info(conn, &info) != 0 || info.state != BT_CONN_STATE_CONNECTED) {
95 bt_conn_unref(conn);
96 return;
97 }
98 if (this->conn_ != nullptr) {
99 bt_conn_unref(this->conn_);
100 }
101 this->conn_ = conn;
102}
103
104#ifdef CONFIG_BT_SMP
105static void identity_resolved(bt_conn *conn, const bt_addr_le_t *rpa, const bt_addr_le_t *identity) {
106 char addr_identity[BT_ADDR_LE_STR_LEN];
107 char addr_rpa[BT_ADDR_LE_STR_LEN];
108
109 bt_addr_le_to_str(identity, addr_identity, sizeof(addr_identity));
110 bt_addr_le_to_str(rpa, addr_rpa, sizeof(addr_rpa));
111
112 ESP_LOGD(TAG, "Identity resolved %s -> %s", addr_rpa, addr_identity);
113}
114
115static void security_changed(bt_conn *conn, bt_security_t level, bt_security_err err) {
116 char addr[BT_ADDR_LE_STR_LEN];
117
118 bt_addr_le_to_str(bt_conn_get_dst(conn), addr, sizeof(addr));
119
120 if (!err) {
121 ESP_LOGD(TAG, "Security changed: %s level %u", addr, level);
122 } else {
123 ESP_LOGE(TAG, "Security failed: %s level %u err %d", addr, level, err);
124 }
125}
126
127static void pairing_complete(bt_conn *conn, bool bonded) {
128 char addr[BT_ADDR_LE_STR_LEN];
129
130 bt_addr_le_to_str(bt_conn_get_dst(conn), addr, sizeof(addr));
131
132 ESP_LOGD(TAG, "Pairing completed: %s, bonded: %d", addr, bonded);
133}
134
135static void pairing_failed(bt_conn *conn, bt_security_err reason) {
136 char addr[BT_ADDR_LE_STR_LEN];
137
138 bt_addr_le_to_str(bt_conn_get_dst(conn), addr, sizeof(addr));
139
140 ESP_LOGE(TAG, "Pairing failed conn: %s, reason %d", addr, reason);
141
142 bt_conn_disconnect(conn, BT_HCI_ERR_REMOTE_USER_TERM_CONN);
143}
144
145static void bond_deleted(uint8_t id, const bt_addr_le_t *peer) {
146 char addr[BT_ADDR_LE_STR_LEN];
147
148 bt_addr_le_to_str(peer, addr, sizeof(addr));
149 ESP_LOGD(TAG, "Bond deleted for %s, id %u", addr, id);
150}
151
152static void auth_passkey_display(bt_conn *conn, unsigned int passkey) {
153 char addr[BT_ADDR_LE_STR_LEN];
154 char passkey_str[7];
155
156 bt_addr_le_to_str(bt_conn_get_dst(conn), addr, sizeof(addr));
157
158 snprintk(passkey_str, 7, "%06u", passkey);
159
160 ESP_LOGI(TAG, "Passkey for %s: %s", addr, passkey_str);
161}
162
163static void conn_addr_str(bt_conn *conn, char *addr, size_t len) {
164 struct bt_conn_info info;
165
166 if (bt_conn_get_info(conn, &info) < 0) {
167 addr[0] = '\0';
168 return;
169 }
170
171 switch (info.type) {
172 case BT_CONN_TYPE_LE:
173 bt_addr_le_to_str(info.le.dst, addr, len);
174 break;
175 default:
176 ESP_LOGE(TAG, "Not implemented");
177 addr[0] = '\0';
178 break;
179 }
180}
181
182static void auth_cancel(bt_conn *conn) {
183 char addr[BT_ADDR_LE_STR_LEN];
184
185 conn_addr_str(conn, addr, sizeof(addr));
186
187 ESP_LOGI(TAG, "Pairing cancelled: %s", addr);
188}
189
190void BLEServer::auth_passkey_confirm(bt_conn *conn, unsigned int passkey) {
191 char addr[BT_ADDR_LE_STR_LEN];
192 char passkey_str[7];
193
194 bt_addr_le_to_str(bt_conn_get_dst(conn), addr, sizeof(addr));
195
196 snprintk(passkey_str, 7, "%06u", passkey);
197
198 ESP_LOGI(TAG, "Confirm passkey for %s: %s", addr, passkey_str);
199 global_ble_server->defer([passkey]() {
200 if (global_ble_server->passkey_cb_.size() == 0) {
201 ESP_LOGW(TAG, "Nothing answers numeric comparison (safe mode skips the automation), rejecting pairing");
203 return;
204 }
206 });
207}
208
209static void auth_pairing_confirm(bt_conn *conn) {
210 /* Automatically confirm pairing request from the device side. */
211 auto err = bt_conn_auth_pairing_confirm(conn);
212 if (err) {
213 ESP_LOGE(TAG, "Can't confirm pairing (err: %d)", err);
214 return;
215 }
216
217 char addr[BT_ADDR_LE_STR_LEN];
218
219 bt_addr_le_to_str(bt_conn_get_dst(conn), addr, sizeof(addr));
220
221 ESP_LOGI(TAG, "Pairing confirmed: %s", addr);
222}
223
224#endif
225
227 global_ble_server = this;
228 int err = 0;
229 k_work_init(&advertise_work, advertise);
230
231 static bt_conn_cb conn_callbacks = {
232 .connected = connected,
233 .disconnected = disconnected,
234#ifdef CONFIG_BT_SMP
235 .identity_resolved = identity_resolved,
236 .security_changed = security_changed,
237#endif
238 };
239
240 bt_conn_cb_register(&conn_callbacks);
241#ifdef CONFIG_BT_SMP
242 static struct bt_conn_auth_info_cb conn_auth_info_callbacks = {
243 .pairing_complete = pairing_complete, .pairing_failed = pairing_failed, .bond_deleted = bond_deleted};
244 err = bt_conn_auth_info_cb_register(&conn_auth_info_callbacks);
245 if (err) {
246 ESP_LOGE(TAG, "Failed to register authorization info callbacks.");
247 }
248 static struct bt_conn_auth_cb auth_cb = {
249 .passkey_display = auth_passkey_display,
250 .passkey_confirm = auth_passkey_confirm,
251 .cancel = auth_cancel,
252 .pairing_confirm = auth_pairing_confirm,
253 };
254 err = bt_conn_auth_cb_register(&auth_cb);
255 if (err) {
256 ESP_LOGE(TAG, "Failed to set auth handlers (%d)", err);
257 }
258#endif
259 // callback cannot be used to start scanning due to race conditions with BT_SETTINGS
260 err = bt_enable(nullptr);
261 if (err) {
262 ESP_LOGE(TAG, "Bluetooth enable failed: %d", err);
263 return;
264 }
265#ifdef CONFIG_BT_SETTINGS
266 err = settings_load();
267 if (err) {
268 ESP_LOGE(TAG, "Cannot load settings, err: %d", err);
269 }
270#endif
271 k_work_submit(&advertise_work);
272}
273
274#ifdef ESPHOME_LOG_HAS_DEBUG
275static const char *role_str(uint8_t role) {
276 switch (role) {
277 case BT_CONN_ROLE_CENTRAL:
278 return "Central";
279 case BT_CONN_ROLE_PERIPHERAL:
280 return "Peripheral";
281 default:
282 break;
283 }
284
285 return "Unknown";
286}
287
288static void connection_info(bt_conn *conn, void *user_data) {
289 char addr[BT_ADDR_LE_STR_LEN];
290 struct bt_conn_info info;
291
292 if (bt_conn_get_info(conn, &info) < 0) {
293 ESP_LOGE(TAG, "Unable to get info: conn %p", conn);
294 return;
295 }
296
297 switch (info.type) {
298 case BT_CONN_TYPE_LE:
299 bt_addr_le_to_str(info.le.dst, addr, sizeof(addr));
300 ESP_LOGD(TAG, " %u [LE][%s] %s: Interval %u latency %u timeout %u security L%u", info.id, role_str(info.role),
301 addr, info.le.interval, info.le.latency, info.le.timeout, info.security.level);
302 break;
303 default:
304 ESP_LOGE(TAG, "Not implemented");
305 break;
306 }
307}
308#ifdef CONFIG_BT_BONDABLE
309static void bond_info(const struct bt_bond_info *info, void *user_data) {
310 char addr[BT_ADDR_LE_STR_LEN];
311
312 bt_addr_le_to_str(&info->addr, addr, sizeof(addr));
313 ESP_LOGD(TAG, " Bond remote identity: %s", addr);
314}
315#endif
316#endif
317
319 ESP_LOGCONFIG(TAG,
320 "ble server:\n"
321 " connected: %s\n"
322 " name: %s\n"
323 " appearance: %u\n"
324 " ready: %s\n"
325#ifdef CONFIG_BT_SMP
326 " security manager: YES",
327#else
328 " security manager: NO",
329#endif
330 YESNO(this->conn_), bt_get_name(), bt_get_appearance(), YESNO(bt_is_ready()));
331
332#ifdef ESPHOME_LOG_HAS_DEBUG
333 bt_conn_foreach(BT_CONN_TYPE_ALL, connection_info, nullptr);
334#ifdef CONFIG_BT_BONDABLE
335 bt_foreach_bond(BT_ID_DEFAULT, bond_info, nullptr);
336#endif
337#endif
338}
339
341 if (this->conn_ == nullptr) {
342 ESP_LOGE(TAG, "Not connected");
343 return;
344 }
345 ESP_LOGD(TAG, "Numeric comparison %s", accept ? "accepted" : "rejected");
346 if (accept) {
347 bt_conn_auth_passkey_confirm(this->conn_);
348 } else {
349 bt_conn_auth_cancel(this->conn_);
350 }
351}
352
353} // namespace esphome::zephyr_ble_server
354
355#endif
const StringRef & get_name() const
Get the name of this Application set by pre_setup().
bool is_name_add_mac_suffix_enabled() const
void defer(const char *name, std::function< void()> &&f)
Defer a callback to the next loop() call with a const char* name.
static void disconnected(bt_conn *conn, uint8_t reason)
CallbackManager< void(uint32_t)> passkey_cb_
Definition ble_server.h:22
static void auth_passkey_confirm(bt_conn *conn, unsigned int passkey)
static void connected(bt_conn *conn, uint8_t err)
ESPHOME_LOG_TAG(TAG, "zephyr_ble_server")
const bt_le_adv_param *const ADV_PARAM
size_t truncate_name_to(char *buffer, size_t buffer_size, const char *name, size_t name_len, size_t keep_suffix_len)
Copy a name into a buffer, cutting it when it does not fit.
Definition helpers.cpp:297
const void size_t len
Definition hal.h:68
Application App
Global storage of Application pointer - only one Application can exist.