1 /*
2  * Copyright (c) 2012-2014 Wind River Systems, Inc.
3  * Copyright (c) 2020 Prevas A/S
4  *
5  * SPDX-License-Identifier: Apache-2.0
6  */
7 
8 #include <zephyr/bluetooth/bluetooth.h>
9 #include <zephyr/bluetooth/conn.h>
10 #include <zephyr/bluetooth/gatt.h>
11 #include <zephyr/bluetooth/hci.h>
12 #include <zephyr/mgmt/mcumgr/transport/smp_bt.h>
13 
14 #define LOG_LEVEL LOG_LEVEL_DBG
15 #include <zephyr/logging/log.h>
16 LOG_MODULE_REGISTER(smp_bt_sample);
17 
18 static struct k_work advertise_work;
19 
20 static const struct bt_data ad[] = {
21 	BT_DATA_BYTES(BT_DATA_FLAGS, (BT_LE_AD_GENERAL | BT_LE_AD_NO_BREDR)),
22 	BT_DATA_BYTES(BT_DATA_UUID128_ALL, SMP_BT_SVC_UUID_VAL),
23 };
24 
25 static const struct bt_data sd[] = {
26 	BT_DATA(BT_DATA_NAME_COMPLETE, CONFIG_BT_DEVICE_NAME, sizeof(CONFIG_BT_DEVICE_NAME) - 1),
27 };
28 
advertise(struct k_work * work)29 static void advertise(struct k_work *work)
30 {
31 	int rc;
32 
33 	rc = bt_le_adv_start(BT_LE_ADV_CONN_FAST_1, ad, ARRAY_SIZE(ad), sd, ARRAY_SIZE(sd));
34 	if (rc) {
35 		LOG_ERR("Advertising failed to start (rc %d)", rc);
36 		return;
37 	}
38 
39 	LOG_INF("Advertising successfully started");
40 }
41 
connected(struct bt_conn * conn,uint8_t err)42 static void connected(struct bt_conn *conn, uint8_t err)
43 {
44 	if (err) {
45 		LOG_ERR("Connection failed, err 0x%02x %s", err, bt_hci_err_to_str(err));
46 		k_work_submit(&advertise_work);
47 	} else {
48 		LOG_INF("Connected");
49 	}
50 }
51 
disconnected(struct bt_conn * conn,uint8_t reason)52 static void disconnected(struct bt_conn *conn, uint8_t reason)
53 {
54 	LOG_INF("Disconnected, reason 0x%02x %s", reason, bt_hci_err_to_str(reason));
55 }
56 
on_conn_recycled(void)57 static void on_conn_recycled(void)
58 {
59 	k_work_submit(&advertise_work);
60 }
61 
62 BT_CONN_CB_DEFINE(conn_callbacks) = {
63 	.connected = connected,
64 	.disconnected = disconnected,
65 	.recycled = on_conn_recycled,
66 };
67 
bt_ready(int err)68 static void bt_ready(int err)
69 {
70 	if (err != 0) {
71 		LOG_ERR("Bluetooth failed to initialise: %d", err);
72 	} else {
73 		k_work_submit(&advertise_work);
74 	}
75 }
76 
start_smp_bluetooth_adverts(void)77 void start_smp_bluetooth_adverts(void)
78 {
79 	int rc;
80 
81 	k_work_init(&advertise_work, advertise);
82 	rc = bt_enable(bt_ready);
83 
84 	if (rc != 0) {
85 		LOG_ERR("Bluetooth enable failed: %d", rc);
86 	}
87 }
88