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 char message[CONFIG_BT_L2CAP_TX_MTU + 1] = "";
33
34 ARG_UNUSED(conn);
35 ARG_UNUSED(ctx);
36
37 memcpy(message, data, MIN(sizeof(message) - 1, len));
38 printk("%s() - Len: %d, Message: %s\n", __func__, len, message);
39 }
40
41 struct bt_nus_cb nus_listener = {
42 .notif_enabled = notif_enabled,
43 .received = received,
44 };
45
main(void)46 int main(void)
47 {
48 int err;
49
50 printk("Sample - Bluetooth Peripheral NUS\n");
51
52 err = bt_nus_cb_register(&nus_listener, NULL);
53 if (err) {
54 printk("Failed to register NUS callback: %d\n", err);
55 return err;
56 }
57
58 err = bt_enable(NULL);
59 if (err) {
60 printk("Failed to enable bluetooth: %d\n", err);
61 return err;
62 }
63
64 err = bt_le_adv_start(BT_LE_ADV_CONN_FAST_1, ad, ARRAY_SIZE(ad), sd, ARRAY_SIZE(sd));
65 if (err) {
66 printk("Failed to start advertising: %d\n", err);
67 return err;
68 }
69
70 printk("Initialization complete\n");
71
72 while (true) {
73 const char *hello_world = "Hello World!\n";
74
75 k_sleep(K_SECONDS(3));
76
77 err = bt_nus_send(NULL, hello_world, strlen(hello_world));
78 printk("Data send - Result: %d\n", err);
79
80 if (err < 0 && (err != -EAGAIN) && (err != -ENOTCONN)) {
81 return err;
82 }
83 }
84
85 return 0;
86 }
87