ESPHome 2025.12.0-dev
Loading...
Searching...
No Matches
ble_server.cpp
Go to the documentation of this file.
1#ifdef USE_ZEPHYR
2#include "ble_server.h"
4#include "esphome/core/log.h"
5#include <zephyr/bluetooth/bluetooth.h>
6#include <zephyr/bluetooth/conn.h>
7
9
10static const char *const TAG = "zephyr_ble_server";
11
12static struct k_work advertise_work; // NOLINT(cppcoreguidelines-avoid-non-const-global-variables)
13
14#define DEVICE_NAME CONFIG_BT_DEVICE_NAME
15#define DEVICE_NAME_LEN (sizeof(DEVICE_NAME) - 1)
16
17static const struct bt_data AD[] = {
18 BT_DATA_BYTES(BT_DATA_FLAGS, (BT_LE_AD_GENERAL | BT_LE_AD_NO_BREDR)),
19 BT_DATA(BT_DATA_NAME_COMPLETE, DEVICE_NAME, DEVICE_NAME_LEN),
20};
21
22static const struct bt_data SD[] = {
23#ifdef USE_OTA
24 BT_DATA_BYTES(BT_DATA_UUID128_ALL, 0x84, 0xaa, 0x60, 0x74, 0x52, 0x8a, 0x8b, 0x86, 0xd3, 0x4c, 0xb7, 0x1d, 0x1d,
25 0xdc, 0x53, 0x8d),
26#endif
27};
28
29const struct bt_le_adv_param *const ADV_PARAM = BT_LE_ADV_CONN;
30
31static void advertise(struct k_work *work) {
32 int rc = bt_le_adv_stop();
33 if (rc) {
34 ESP_LOGE(TAG, "Advertising failed to stop (rc %d)", rc);
35 }
36
37 rc = bt_le_adv_start(ADV_PARAM, AD, ARRAY_SIZE(AD), SD, ARRAY_SIZE(SD));
38 if (rc) {
39 ESP_LOGE(TAG, "Advertising failed to start (rc %d)", rc);
40 return;
41 }
42 ESP_LOGI(TAG, "Advertising successfully started");
43}
44
45static void connected(struct bt_conn *conn, uint8_t err) {
46 if (err) {
47 ESP_LOGE(TAG, "Connection failed (err 0x%02x)", err);
48 } else {
49 ESP_LOGI(TAG, "Connected");
50 }
51}
52
53static void disconnected(struct bt_conn *conn, uint8_t reason) {
54 ESP_LOGI(TAG, "Disconnected (reason 0x%02x)", reason);
55 k_work_submit(&advertise_work);
56}
57
58static void bt_ready(int err) {
59 if (err != 0) {
60 ESP_LOGE(TAG, "Bluetooth failed to initialise: %d", err);
61 } else {
62 k_work_submit(&advertise_work);
63 }
64}
65
66BT_CONN_CB_DEFINE(conn_callbacks) = {
67 .connected = connected,
68 .disconnected = disconnected,
69};
70
72 k_work_init(&advertise_work, advertise);
73 resume_();
74}
75
77 if (this->suspended_) {
78 resume_();
79 this->suspended_ = false;
80 }
81}
82
84 int rc = bt_enable(bt_ready);
85 if (rc != 0) {
86 ESP_LOGE(TAG, "Bluetooth enable failed: %d", rc);
87 return;
88 }
89}
90
92 struct k_work_sync sync;
93 k_work_cancel_sync(&advertise_work, &sync);
94 bt_disable();
95 this->suspended_ = true;
96}
97
98} // namespace esphome::zephyr_ble_server
99
100#endif
BT_CONN_CB_DEFINE(conn_callbacks)
const struct bt_le_adv_param *const ADV_PARAM
uint16_t sync
Definition sun_gtil2.cpp:0