-
Notifications
You must be signed in to change notification settings - Fork 0
/
Main.cpp
108 lines (86 loc) · 2.39 KB
/
Main.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
#include <vector>
#include <errno.h>
#include <cstdint>
#include <cstring>
#include <fcntl.h>
#include <stdio.h>
#include <iostream>
#include <string.h>
#include <unistd.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <bluetooth/bluetooth.h>
#include <bluetooth/l2cap.h>
#include <bluetooth/hci.h>
#include <bluetooth/hci_lib.h>
int initConnection(std::string address);
void log(std::string msg);
std::string getNextBluetoothMessage();
// bluetooth communication
int socketConnection = 0;
char buffer[1024] = { 0 };
// inter-proccess communication
int num = -1, fifo = -1;
int main(int argc, char **argv) {
// init bluetooth connection
if (initConnection(argv[1])) return -1;
// open the pipe
int fifo;
if ((fifo = open("/tmp/fifoBlueJava", O_WRONLY)) < 0) {
printf("%s\n", strerror(errno));
return -1;
}
while (true) {
std::string msg = getNextBluetoothMessage();
if ((num = write(fifo, msg.c_str(), msg.length())) < 0) {
printf("ERROR: %s\n", strerror(errno));
}
}
close(fifo);
return system("rm /tmp/fifoBlueJava");
}
std::string getNextBluetoothMessage() {
// empty buffer
std::memset(buffer, 0, sizeof(buffer));
// read data from the client
int bytes_read = read(socketConnection, buffer, sizeof(buffer));
// if there was anything, write to message queue
if (bytes_read > 0) {
return std::string(buffer) + "\n";
}
return "";
}
int initConnection(std::string address) {
// power the local bluetooth device on
log("Turn bluetooth device on");
system("echo \"power on\" | bluetoothctl");
log("");
log("Trying to connect to " + address);
struct sockaddr_l2 addr = { 0 };
int status = -1;
// allocate a socket
socketConnection = socket(AF_BLUETOOTH, SOCK_SEQPACKET, BTPROTO_L2CAP);
// set the connection parameters (who to connect to)
addr.l2_family = AF_BLUETOOTH;
addr.l2_psm = htobs(0x1001);
str2ba(address.c_str(), &addr.l2_bdaddr);
// attempt connection
status = connect(socketConnection, (struct sockaddr *)&addr, sizeof(addr));
// if connection is successful, this is our address
if (status == 0) {
log("Connected to " + address);
return 0;
}
else {
log("Error connecting: " + std::string(std::strerror(errno)));
}
// power the local bluetooth device off
log("Turn bluetooth device off");
system("echo \"power off\" | bluetoothctl");
log("");
return -1;
}
void log(std::string msg) {
std::cout << msg << std::endl;
}