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