forked from blevinstein/cs3240
-
Notifications
You must be signed in to change notification settings - Fork 0
/
BluetoothConnection.java
101 lines (82 loc) · 1.94 KB
/
BluetoothConnection.java
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
import java.io.*;
import lejos.nxt.comm.*;
public class BluetoothConnection {
//the bluetooth connection
private NXTConnection connection;
//the data input stream
private DataInputStream input;
//the data output stream
private DataOutputStream output;
//constructor that starts a bluetooth connection with robot
public BluetoothConnection(){
connect();
}
//getters for the class
public NXTConnection getConnection(){
return connection;
}
public DataInputStream getInput(){
return input;
}
public DataOutputStream getOutput(){
return output;
}
//returns true if BT connection exists
public boolean connected(){
return connection != null;
}
//establishes a bluetooth connection with robot
public boolean connect(){
connection = Bluetooth.waitForConnection();
if(!connected()){
return false;
}
else{
input = connection.openDataInputStream();
output = connection.openDataOutputStream();
return true;
}
}
public boolean disconnect(){
//try to close the input and output data streams
//return false if an IOException occurs
//return true if streams close and connection closes
try{
input.close();
}
catch(IOException e){
return false;
}
try{
output.close();
}
catch(IOException e){
return false;
}
connection.close();
return true;
}
public synchronized void send(String s) throws IOException{
for (int i = 0; i < s.length(); ++i){
byte byteToSend = (byte) s.charAt(i);
output.write(byteToSend);
}
}
public byte[] read(){
try{
byte[] msg = new byte[256];
int size = input.read(msg);
//if the size is greater than zero then we have a message
if(size > 0){
return msg;
}
}
catch(Exception e){
//if we lose a connection, reconnect
if(disconnect() == true){
this.connect();
}
}
return null;
}
}