Page 48 - The Definitive Guide to Building Java Robots
P. 48
Preston_5564C02.fm Page 29 Wednesday, September 14, 2005 5:42 AM
CHAPTER 2 ■ SERIAL COMMUNICATION 29
// return a port in use if it exist.
for (int i=0; i< portsInUse.size(); i++) {
StandardSerialPort aPort = (StandardSerialPort)portsInUse.get(i);
if (aPort.getName().endsWith(tmpComID)) {
aPort.close();
portsInUse.remove(i);
}
}
}
public static void closeAll() {
// cycle through all and close
for (int i=0; i< portsInUse.size(); i++) {
StandardSerialPort aPort = (StandardSerialPort)portsInUse.get(i);
aPort.close();
portsInUse.remove(i);
}
}
}
Section Summary
In this section, I discussed and compared five different ways to handle serial port concurrency.
By placing a serial port in a resource pool that is thread-safe, I ensure that the serial port will be
accessed in a synchronized fashion and I will never get a PortInUseException when accessing
the serial port while programming my robot.
The class I created in this section was
• SingleSerialPort.java: This class showed how to create a resource pool of serial ports that
provide concurrent access for multiple threads.
You may not have a need for this functionality if you are always working from your PC with
a single program accessing the serial port; however, as you will see in the next section, we can
have multiple threads accessing the same serial port. In such cases, strings or images serial port
comes in very handy.
2.3 Creating a Web Serial Port
I’ve found that working on a serial port at my desk using my PC is fine, but as soon as I start
debugging the code with my robot, I find that working on a remote machine via terminal
services is much slower. So, I need another option. I want to work from the Eclipse IDE at my
desk, but I also want to do serial communication with a microcontroller connected to my
robot’s serial port. I also want an easy way to test this remotely and do not want to write soft-
ware for handling multiple connections or managing data packets of strings or images that
might be going back and forth between my desktop and the robot.
To remedy these problems, I’ll create a web serial port. This is a serial port I can access
over the Internet, send commands to, get data from, and then employ web clients to do remote
control for diagnostics and so on.