Page 50 - The Definitive Guide to Building Java Robots
P. 50
Preston_5564C02.fm Page 31 Wednesday, September 14, 2005 5:42 AM
CHAPTER 2 ■ SERIAL COMMUNICATION 31
Because Tomcat is a multithreaded web server, any two calls from a web browser
or web client could happen on different threads. This is not a desired effect, so to avoid the
PortInUseException I will use the SingleSerialPort.getIntance() method in the constructor of
the WebSerialPort.
The only other public method in this class is execute(), which takes the parameters and
actions corresponding to read, write, or write-read. The string, cmds, will be a comma-delimited
string of bytes, while the string, timeout, will tell the class to wait around for the result. In this
method, I will also throw exceptions if any of the constructor elements are null.
The other methods that get called depend upon the action. The private read() method
returns the com.readString() value. This will be a tilde-delimited list of numbers. The write()
method will convert the comma-delimited string to a byte[] and send that to the serial port’s
output stream. Finally, the read() method with input parameters will call the write() method,
wait until the timeout, and then call the read() method. (See Example 2-6.)
Example 2-6. WebSerialPort.java
package com.scottpreston.javarobot.chapter2;
public class WebSerialPort{
JSerialPort com;
public static final String CMD_ACK = "ok";
public static final String COMM_JSP = "webcom.jsp";
public static final byte[] READ_ONLY = new byte[] { (byte) 0 };
public static final int DEFAULT_TIMEOUT = 0;
private int timeout;
public WebSerialPort(String comId) throws Exception {
int pId = new Integer(comId).intValue();
com = SingleSerialPort.getInstance(pId);
}
public String execute(String action, String cmds, String timeout,String dtr) ➥
throws Exception{
if (action == null) {
throw new Exception("Action is null");
}
if (cmds == null) {
throw new Exception("Commands are null");
}
if (timeout == null) {
throw new Exception("Timeout is null");
}
if (dtr == null) {
throw new Exception("DTR is null");
}
97022d2480fe4a63cfdfa123a6e70098