Page 40 - The Definitive Guide to Building Java Robots
P. 40
Preston_5564C02.fm Page 21 Wednesday, September 14, 2005 5:42 AM
CHAPTER 2 ■ SERIAL COMMUNICATION 21
Figure 2-3. The class diagram for JSerialPort and StandardSerialPort
To begin let’s look at the class-level variables. The Enumeration portList is a returned list
of ports by the Driver. The ComPortIdentifier, portId, is the actual port we’re interested in
working with, while SerialPort is the actual java.comm.SerialPort we’ll be use to read and write
data packets with our microcontroller. InputStream and OutputStream, with variable names of
the same name, are the returned streams from our working SerialPort.
The byte[] readBuffer will be a temporary buffer used while reading our serial port’s input
stream. The Boolean, dataIn, is an indicator flag that lets the class know how long to read the
input stream into the readBuffer. Finally, the last two variables currentWrite and i are used in
conjunction with read-write behavior implemented in the WebSerialClient.
Moving to the class constructors, I created two constructors for this class simplifying the
input parameter creation to just baud and id. Because I’m just checking to see if the port ends
with a specific number (for instance, 1,2,3,…,n), this class will work with either Windows- or
UNIX-based serial ports. In the case where the baud is not set, I decided on a default baud rate
of 9600. Each constructor also calls a common init method. Inside this method you’ll find the
same logic used in Example 2-1, ListOpenPorts. Once an enumeration is created, I iterate
through this enumeration until I find the serial ports (specifically the one that ends with the int
passed in as an input parameter). I then open a named instance of this port and set the default
parameters to be eight data bits, one stop bit, no parity, and no flow control. Next, I set the
input stream and output stream of the port to be equal to two class variables of the same name,
followed by adding the event listener and notifyOnDataAvailable flag.