1 /*
2  * Copyright (c) 2024 Croxel, Inc.
3  *
4  * SPDX-License-Identifier: Apache-2.0
5  */
6 
7 #include <zephyr/kernel.h>
8 #include <zephyr/bluetooth/bluetooth.h>
9 #include <zephyr/bluetooth/services/nus.h>
10 
11 #define DEVICE_NAME		CONFIG_BT_DEVICE_NAME
12 #define DEVICE_NAME_LEN		(sizeof(DEVICE_NAME) - 1)
13 
14 static const struct bt_data ad[] = {
15 	BT_DATA_BYTES(BT_DATA_FLAGS, (BT_LE_AD_GENERAL | BT_LE_AD_NO_BREDR)),
16 	BT_DATA(BT_DATA_NAME_COMPLETE, DEVICE_NAME, DEVICE_NAME_LEN),
17 };
18 
19 static const struct bt_data sd[] = {
20 	BT_DATA_BYTES(BT_DATA_UUID128_ALL, BT_UUID_NUS_SRV_VAL),
21 };
22 
notif_enabled(bool enabled,void * ctx)23 static void notif_enabled(bool enabled, void *ctx)
24 {
25 	ARG_UNUSED(ctx);
26 
27 	printk("%s() - %s\n", __func__, (enabled ? "Enabled" : "Disabled"));
28 }
29 
received(struct bt_conn * conn,const void * data,uint16_t len,void * ctx)30 static void received(struct bt_conn *conn, const void *data, uint16_t len, void *ctx)
31 {
32 	ARG_UNUSED(conn);
33 	ARG_UNUSED(ctx);
34 
35 	printk("%s() - Len: %d, Message: %.*s\n", __func__, len, len, (char *)data);
36 }
37 
38 struct bt_nus_cb nus_listener = {
39 	.notif_enabled = notif_enabled,
40 	.received = received,
41 };
42 
main(void)43 int main(void)
44 {
45 	int err;
46 
47 	printk("Sample - Bluetooth Peripheral NUS\n");
48 
49 	err = bt_nus_cb_register(&nus_listener, NULL);
50 	if (err) {
51 		printk("Failed to register NUS callback: %d\n", err);
52 		return err;
53 	}
54 
55 	err = bt_enable(NULL);
56 	if (err) {
57 		printk("Failed to enable bluetooth: %d\n", err);
58 		return err;
59 	}
60 
61 	err = bt_le_adv_start(BT_LE_ADV_CONN_FAST_1, ad, ARRAY_SIZE(ad), sd, ARRAY_SIZE(sd));
62 	if (err) {
63 		printk("Failed to start advertising: %d\n", err);
64 		return err;
65 	}
66 
67 	printk("Initialization complete\n");
68 
69 	while (true) {
70 		const char *hello_world = "Hello World!\n";
71 
72 		k_sleep(K_SECONDS(3));
73 
74 		err = bt_nus_send(NULL, hello_world, strlen(hello_world));
75 		printk("Data send - Result: %d\n", err);
76 
77 		if (err < 0 && (err != -EAGAIN) && (err != -ENOTCONN)) {
78 			return err;
79 		}
80 	}
81 
82 	return 0;
83 }
84