1 /* main.c - Application main entry point */
2
3 /*
4 * Copyright (c) 2023 Nordic Semiconductor ASA
5 *
6 * SPDX-License-Identifier: Apache-2.0
7 */
8
9 #include <zephyr/kernel.h>
10 #include <zephyr/device.h>
11
12 #include <zephyr/drivers/gpio.h>
13
14 #include <zephyr/sys/util.h>
15 #include <zephyr/sys/printk.h>
16
17 #include <zephyr/bluetooth/conn.h>
18
19 #include <zephyr/logging/log.h>
20
21 #include "common.h"
22
23 LOG_MODULE_DECLARE(ead_peripheral_sample, CONFIG_BT_EAD_LOG_LEVEL);
24
25 /*
26 * Get button configuration from the devicetree sw0 alias. This is mandatory.
27 */
28 #define SW0_NODE DT_ALIAS(sw0)
29 #if !DT_NODE_HAS_STATUS(SW0_NODE, okay)
30 #error "Unsupported board: sw0 devicetree alias is not defined"
31 #endif
32 static const struct gpio_dt_spec button = GPIO_DT_SPEC_GET_OR(SW0_NODE, gpios, {0});
33 static struct gpio_callback button_cb_data;
34
35 extern int run_peripheral_sample(int get_passkey_confirmation(struct bt_conn *conn));
36
37 static struct k_poll_signal button_pressed_signal;
38
button_pressed(const struct device * dev,struct gpio_callback * cb,uint32_t pins)39 static void button_pressed(const struct device *dev, struct gpio_callback *cb, uint32_t pins)
40 {
41 LOG_DBG("Button pressed...");
42
43 k_poll_signal_raise(&button_pressed_signal, 0);
44 k_sleep(K_SECONDS(1));
45 k_poll_signal_reset(&button_pressed_signal);
46 }
47
get_passkey_confirmation(struct bt_conn * conn)48 static int get_passkey_confirmation(struct bt_conn *conn)
49 {
50 int err;
51
52 printk("Confirm passkey by pressing button at %s pin %d...\n", button.port->name,
53 button.pin);
54
55 await_signal(&button_pressed_signal);
56
57 err = bt_conn_auth_passkey_confirm(conn);
58 if (err) {
59 LOG_DBG("Failed to confirm passkey.");
60 return -1;
61 }
62
63 printk("Passkey confirmed.\n");
64
65 return 0;
66 }
67
setup_btn(void)68 static int setup_btn(void)
69 {
70 int ret;
71
72 k_poll_signal_init(&button_pressed_signal);
73
74 if (!gpio_is_ready_dt(&button)) {
75 LOG_ERR("Error: button device %s is not ready", button.port->name);
76 return -1;
77 }
78
79 ret = gpio_pin_configure_dt(&button, GPIO_INPUT);
80 if (ret != 0) {
81 LOG_ERR("Error %d: failed to configure %s pin %d", ret, button.port->name,
82 button.pin);
83 return -1;
84 }
85
86 ret = gpio_pin_interrupt_configure_dt(&button, GPIO_INT_EDGE_TO_ACTIVE);
87 if (ret != 0) {
88 LOG_ERR("Error %d: failed to configure interrupt on %s pin %d", ret,
89 button.port->name, button.pin);
90 return -1;
91 }
92
93 gpio_init_callback(&button_cb_data, button_pressed, BIT(button.pin));
94 gpio_add_callback(button.port, &button_cb_data);
95 LOG_DBG("Set up button at %s pin %d", button.port->name, button.pin);
96
97 return 0;
98 }
99
main(void)100 int main(void)
101 {
102 int err;
103
104 err = setup_btn();
105 if (err) {
106 return 0;
107 }
108
109 LOG_DBG("Starting peripheral sample...");
110
111 (void)run_peripheral_sample(get_passkey_confirmation);
112 return 0;
113 }
114