Page 246 - Hacking Roomba
P. 246
Chapter 11 — Connecting Roomba to the Internet 227
You should note two key differences in RoombaCommTCPClient. First, notice that the String
argument to connect() goes from being a serial port name to being a host:port combination.
The host is the IP address of the Ethernet-to-serial device and the port is either port 23 (for
SitePlayer) or port 10001 (for XPort).
The second thing to note is that Java uses the exact same objects (InputStream and
OutputStream) to represent reading and writing data over a network as it does for communi-
cating over a serial line.This means that most of the code like send() can be almost exactly the
same. For network devices, the Socket object provides InputStreams and OutputStreams;
for serial ports, the SerialPort object does.
The updateSensors() and associated code to read data back from Roomba aren’t shown, but
they are largely the same. Unlike SerialPort, which runs a separate thread and provides an
EventListener interface, Java’s Socket doesn’t. So a standard EventListener-like thread is
created to periodically look for input. When information arrives, the EventListener buffers it
and calls an internal event method to deal with the data, just like RoombaCommSerial
.serialEvent().
All of the example programs in this book thus far have explicitly created RoombaCommSerial
objects. This was done to make things more obvious, but all of the example programs can be
quickly changed to use another subclass of RoombaComm. Listing 11-2 shows a version of the
familiar SimpleTest example program, very slightly modified to use RoombaCommTCPClient.
In fact, the only modification necessary is changing what type of RoombaComm object is
instantiated and to remove the serial-specific parameter setting.
Similarly, all of the Processing sketches can quickly be modified to use
RoombaCommTCPClient instead.
Listing 11-2: SimpleTest, for Networked Roombas
package roombacomm.net;
import roombacomm.*;
public class SimpleTest {
static boolean debug = false;
public static void main(String[] args) {
String portnamem = args[0];
if( !roombacomm.connect(portname) ) {
System.out.println(“Couldn’t connect to
“+portname);
System.exit(1);
}
System.out.println(“Roomba startup on port “+portname);
roombacomm.startup();
roombacomm.control();
roombacomm.pause(50);
Continued