Page 36 - The Definitive Guide to Building Java Robots
P. 36
Preston_5564C02.fm Page 17 Wednesday, September 14, 2005 5:42 AM
CHAPTER 2 ■ SERIAL COMMUNICATION 17
The Java Communications API
I will use the following classes from the Java Communications API for port access. Table 2-1
summarizes the class names and class descriptions.
Table 2-1. Important Classes in Java Communications API
Java Class Description
javax.comm.CommPortIdentifer This is the main class for controlling access to communi-
cations ports. It provides a list of communications ports
made available by the driver, assists with the opening of
communications ports, and assists with port ownership.
javax.comm.SerialPort This is the standard RS-232 communications port
provided by the comm.jar. Per the Java documentation,
this class defines the minimum required functionality for
serial communications ports.
Code Objectives
The objective for this example is to list all available communications ports.
■Tip Make this the first program you run since it will test the installation of the Java communications API.
Code Discussion
The fields in this class are ComPortIdentifer, portId, and an enumeration of all ports called
portsList. Next, I’ll create an empty constructor where I initialize the enumeration of the ports.
This will be the list of all ports identified by the driver.
The second method in the class is the list() method. The first line in the method is a while
loop that iterates through the enumeration of ports. Upon getting the next element from the
enumeration, it receives the portType (serial or parallel), and then prints the name of the port.
Upon outputting the name to the console, I’ll make an attempt to open the port, pause 250
milliseconds, and then close the port. This will be repeated until the enumeration has no more
elements.
This class throws two exception types. The first, InterruptedException, is thrown by the
static Thread.sleep() method, while the PortInUseException is thrown by the portId.open()
method. (See Example 2-1.)
97022d2480fe4a63cfdfa123a6e70098