Debian Codegraph @

src/xrt/drivers/opengloves/communication/bluetooth/opengloves_prober_bt.c

raw
1 // Copyright 2019-2022, Collabora, Ltd.
2 // SPDX-License-Identifier: BSL-1.0
3 /*!
4 * @file
5 * @brief OpenGloves bluetooth prober implementation.
6 * @author Daniel Willmott <[email protected]>
7 * @ingroup drv_opengloves
8 */
9
10 #include <stdlib.h>
11
12 #include <bluetooth/bluetooth.h>
13 #include <bluetooth/hci.h>
14 #include <bluetooth/hci_lib.h>
15 #include <unistd.h>
16
17 #include "util/u_debug.h"
18 #include "xrt/xrt_defines.h"
19
20 #include "opengloves_bt_serial.h"
21 #include "opengloves_prober_bt.h"
22 #include "util/u_misc.h"
23
24 #define OPENGLOVES_PROBER_LOG_LEVEL U_LOGGING_TRACE
25
26 #define OPENGLOVES_ERROR(...) U_LOG_IFL_E(OPENGLOVES_PROBER_LOG_LEVEL, __VA_ARGS__)
27 #define OPENGLOVES_WARN(...) U_LOG_IFL_W(OPENGLOVES_PROBER_LOG_LEVEL, __VA_ARGS__)
28 #define OPENGLOVES_INFO(...) U_LOG_IFL_I(OPENGLOVES_PROBER_LOG_LEVEL, __VA_ARGS__)
29
30 #define OPENGLOVES_BT_MAX_ADDRESS_LEN 19
31 #define OPENGLOVES_BT_MAX_NAME_LEN 248
32 #define OPENGLOVES_BT_MAX_DEVICES 255
33
34 int
35 opengloves_get_bt_devices(const char *bt_name, struct opengloves_communication_device **out_ocd)
36 {
37 char addr[OPENGLOVES_BT_MAX_ADDRESS_LEN] = {0};
38 char name[OPENGLOVES_BT_MAX_NAME_LEN] = {0};
39
40 int dev_id = hci_get_route(NULL);
41 int sock = hci_open_dev(dev_id);
42
43 if (dev_id < 0 || sock < 0) {
44 OPENGLOVES_ERROR("Failed to open socket!");
45
46 return -1;
47 }
48
49 int max_rsp = OPENGLOVES_BT_MAX_DEVICES; // maximum devices to find
50 inquiry_info *ii = U_TYPED_ARRAY_CALLOC(inquiry_info, max_rsp);
51
52 int num_rsp = hci_inquiry(dev_id, 1, max_rsp, NULL, &ii, IREQ_CACHE_FLUSH);
53
54 if (num_rsp < 0) {
55 OPENGLOVES_ERROR("device inquiry failed!");
56
57 free(ii);
58 close(sock);
59
60 return -1;
61 }
62
63 for (int i = 0; i < num_rsp; i++) {
64 ba2str(&(ii + i)->bdaddr, addr);
65 memset(name, 0, sizeof(name));
66
67 hci_read_remote_name(sock, &(ii + i)->bdaddr, sizeof(name), name, 0);
68
69 if (!strcmp(name, bt_name) && *out_ocd == NULL) {
70 OPENGLOVES_INFO("Found bt device! %s", name);
71
72 opengloves_bt_open(addr, out_ocd);
73
74 break;
75 }
76 }
77
78 free(ii);
79 close(sock);
80 return 0;
81 }