Debian Codegraph @

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

raw
1 // Copyright 2022, Collabora, Ltd.
2 // SPDX-License-Identifier: BSL-1.0
3 /*!
4 * @file
5 * @brief OpenGloves bluetooth serial implementation
6 * @author Daniel Willmott <[email protected]>
7 * @ingroup drv_opengloves
8 */
9
10 #include <unistd.h>
11 #include <errno.h>
12 #include <bluetooth/bluetooth.h>
13 #include <bluetooth/rfcomm.h>
14
15 #include "util/u_misc.h"
16 #include "util/u_debug.h"
17
18 #include "opengloves_bt_serial.h"
19
20 #define OPENGLOVES_PROBER_LOG_LEVEL U_LOGGING_TRACE
21
22 #define OPENGLOVES_ERROR(...) U_LOG_IFL_E(OPENGLOVES_PROBER_LOG_LEVEL, __VA_ARGS__)
23 #define OPENGLOVES_WARN(...) U_LOG_IFL_W(OPENGLOVES_PROBER_LOG_LEVEL, __VA_ARGS__)
24 #define OPENGLOVES_INFO(...) U_LOG_IFL_I(OPENGLOVES_PROBER_LOG_LEVEL, __VA_ARGS__)
25
26 static void
27 opengloves_bt_close(struct opengloves_bt_device *btdev)
28 {
29 if (btdev->sock != 0) {
30 close(btdev->sock);
31 btdev->sock = 0;
32 }
33 }
34
35 static int
36 opengloves_bt_read(struct opengloves_communication_device *ocdev, char *data, size_t length)
37 {
38 struct opengloves_bt_device *obdev = (struct opengloves_bt_device *)ocdev;
39
40 return read(obdev->sock, data, length);
41 }
42
43 static int
44 opengloves_bt_write(struct opengloves_communication_device *ocdev, const char *data, size_t length)
45 {
46 struct opengloves_bt_device *obdev = (struct opengloves_bt_device *)ocdev;
47
48 return write(obdev->sock, data, length);
49 }
50
51 static void
52 opengloves_bt_destroy(struct opengloves_communication_device *ocdev)
53 {
54 struct opengloves_bt_device *obdev = (struct opengloves_bt_device *)ocdev;
55
56 opengloves_bt_close(obdev);
57 free(obdev);
58 }
59
60 int
61 opengloves_bt_open(const char *btaddr, struct opengloves_communication_device **out_comm_dev)
62 {
63 struct opengloves_bt_device *obdev = U_TYPED_CALLOC(struct opengloves_bt_device);
64
65 obdev->base.read = opengloves_bt_read;
66 obdev->base.write = opengloves_bt_write;
67 obdev->base.destroy = opengloves_bt_destroy;
68
69 // allocate a socket
70 obdev->sock = socket(AF_BLUETOOTH, SOCK_STREAM, BTPROTO_RFCOMM);
71
72 // set the connection parameters (who to connect to)
73 struct sockaddr_rc addr = {0};
74 addr.rc_family = AF_BLUETOOTH;
75 addr.rc_channel = (uint8_t)1;
76 str2ba(btaddr, &addr.rc_bdaddr);
77
78 // connect to server
79 int ret = connect(obdev->sock, (struct sockaddr *)&addr, sizeof(addr));
80
81 if (ret < 0) {
82 OPENGLOVES_ERROR("Failed to connect to device! %s", strerror(errno));
83 return ret;
84 }
85
86 *out_comm_dev = &obdev->base;
87
88 return 0;
89 }