1 /*
2  * Copyright (c) 2023 Victor Chavez
3  *
4  * SPDX-License-Identifier: Apache-2.0
5  */
6 
7 #include <zephyr/kernel.h>
8 #include <zephyr/bluetooth/gatt.h>
9 #include <zephyr/bluetooth/hci.h>
10 #include <zephyr/logging/log.h>
11 #include <zephyr/logging/log_backend_ble.h>
12 
13 LOG_MODULE_REGISTER(ble_backend);
14 
15 
16 static const struct bt_data ad[] = {
17 	BT_DATA_BYTES(BT_DATA_FLAGS, (BT_LE_AD_GENERAL | BT_LE_AD_NO_BREDR)),
18 	BT_DATA_BYTES(BT_DATA_UUID128_ALL, LOGGER_BACKEND_BLE_ADV_UUID_DATA)
19 };
20 
21 static const struct bt_data sd[] = {
22 	BT_DATA(BT_DATA_NAME_COMPLETE, CONFIG_BT_DEVICE_NAME, sizeof(CONFIG_BT_DEVICE_NAME) - 1),
23 };
24 
start_adv(void)25 static void start_adv(void)
26 {
27 	int err;
28 
29 	err = bt_le_adv_start(BT_LE_ADV_CONN_ONE_TIME, ad, ARRAY_SIZE(ad), sd, ARRAY_SIZE(sd));
30 	if (err) {
31 		LOG_ERR("Advertising failed to start (err %d)", err);
32 		return;
33 	}
34 
35 	LOG_INF("Advertising successfully started");
36 }
37 
connected(struct bt_conn * conn,uint8_t err)38 static void connected(struct bt_conn *conn, uint8_t err)
39 {
40 	if (err) {
41 		LOG_ERR("Connection failed, err 0x%02x %s", err, bt_hci_err_to_str(err));
42 	} else {
43 		LOG_INF("Connected");
44 	}
45 }
46 
disconnected(struct bt_conn * conn,uint8_t reason)47 static void disconnected(struct bt_conn *conn, uint8_t reason)
48 {
49 	LOG_INF("Disconnected, reason 0x%02x %s", reason, bt_hci_err_to_str(reason));
50 	start_adv();
51 }
52 
53 BT_CONN_CB_DEFINE(conn_callbacks) = {
54 	.connected = connected,
55 	.disconnected = disconnected,
56 };
57 
auth_cancel(struct bt_conn * conn)58 static void auth_cancel(struct bt_conn *conn)
59 {
60 	char addr[BT_ADDR_LE_STR_LEN];
61 
62 	bt_addr_le_to_str(bt_conn_get_dst(conn), addr, sizeof(addr));
63 
64 	LOG_INF("Pairing cancelled: %s", addr);
65 }
66 
67 static struct bt_conn_auth_cb auth_cb_display = {
68 	.cancel = auth_cancel,
69 };
70 
backend_ble_hook(bool status,void * ctx)71 void backend_ble_hook(bool status, void *ctx)
72 {
73 	ARG_UNUSED(ctx);
74 
75 	if (status) {
76 		LOG_INF("BLE Logger Backend enabled.");
77 	} else {
78 		LOG_INF("BLE Logger Backend disabled.");
79 	}
80 }
81 
82 
main(void)83 int main(void)
84 {
85 	int err;
86 
87 	LOG_INF("BLE LOG Demo");
88 	logger_backend_ble_set_hook(backend_ble_hook, NULL);
89 	err = bt_enable(NULL);
90 	if (err) {
91 		LOG_ERR("Bluetooth init failed (err %d)", err);
92 		return 0;
93 	}
94 
95 	bt_conn_auth_cb_register(&auth_cb_display);
96 
97 	start_adv();
98 
99 	while (1) {
100 		uint32_t uptime_secs = k_uptime_get_32()/1000U;
101 
102 		LOG_INF("Uptime %d secs", uptime_secs);
103 		k_sleep(K_MSEC(1000));
104 	}
105 	return 0;
106 }
107