blob: c9bad04993770033f3e37afb5681190e29ac607a (
plain)
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
|
package com.hackingroomba.roombacomm;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Enumeration;
import gnu.io.CommPortIdentifier;
import gnu.io.SerialPort;
import gnu.io.SerialPortEvent;
import gnu.io.SerialPortEventListener;
public class BetterRoomba implements SerialPortEventListener {
private static final String PORT = "/dev/ttyUSB0";
private static final int TIMEOUT = 2000;
private static final int RATE = 115200;
private static final int DATABITS = 8;
private static final int PARITY = SerialPort.PARITY_NONE;
private static final int STOPBITS = SerialPort.STOPBITS_1;
private SerialPort serialPort;
private InputStream input;
private OutputStream output;
public static void main(String[] args) throws Exception {
System.out.println("Starting...");
BetterRoomba br = new BetterRoomba();
br.startup();
br.send(new byte[] {(byte) 136, (byte) 8});
Thread.sleep(5000);
br.send(new byte[] {(byte) 136, (byte) 255});
br.shutdown();
System.out.println("-END-");
}
@Override
public void serialEvent(SerialPortEvent e) {
// do smthng with e
}
public void startup() throws Exception {
serialConnect();
}
public void shutdown() throws Exception {
try {
if (input != null)
input.close();
if (output != null)
output.close();
} catch (Exception e) {
e.printStackTrace();
}
try {
if (serialPort != null)
serialPort.close();
} catch (Exception e) {
e.printStackTrace();
}
}
private void send(byte[] arr) throws Exception {
output.write(arr);
}
private void serialConnect() throws Exception {
try {
Enumeration portList = CommPortIdentifier.getPortIdentifiers();
while (portList.hasMoreElements()) {
CommPortIdentifier portId = (CommPortIdentifier) portList.nextElement();
if (portId.getPortType() == CommPortIdentifier.PORT_SERIAL) {
System.out.println("Found " + portId.getName());
if (portId.getName().equals(PORT)) {
System.out.println("Opening port: "+ portId.getName());
serialPort = (SerialPort) portId.open("roomba serial", TIMEOUT);
input = serialPort.getInputStream();
output = serialPort.getOutputStream();
serialPort.setSerialPortParams(RATE, DATABITS, STOPBITS, PARITY);
serialPort.addEventListener(this);
serialPort.notifyOnDataAvailable(true);
System.out.println("Port opened successfully");
}
}
}
} catch (Exception e) {
System.out.println(e.getMessage());
throw e;
}
}
}
|