Page 42 - The Definitive Guide to Building Java Robots
P. 42
Preston_5564C02.fm Page 23 Wednesday, September 14, 2005 5:42 AM
CHAPTER 2 ■ SERIAL COMMUNICATION 23
Example 2-4. StandardSerialPort.Java
package com.scottpreston.javarobot.chapter2;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Enumeration;
import javax.comm.CommPortIdentifier;
import javax.comm.SerialPort;
import javax.comm.SerialPortEvent;
import javax.comm.SerialPortEventListener;
public class StandardSerialPort implements SerialPortEventListener,
JSerialPort {
private Enumeration portList;
private CommPortIdentifier portId;
private SerialPort serialPort;
private OutputStream outputStream;
private InputStream inputStream;
private byte[] readBuffer;
private boolean dataIn = false;
private byte[] currentWrite;
private int i = 0;
public StandardSerialPort(int id) throws Exception {
init(id, 9600);
}
public StandardSerialPort(int id, int baud) throws Exception {
init(id, baud);
}
private void init(int comID, int baud) {
String comIdAsString = new Integer(comID).toString();
try {
portList = CommPortIdentifier.getPortIdentifiers();
while (portList.hasMoreElements()) {
portId = (CommPortIdentifier) portList.nextElement();
if (portId.getPortType() == CommPortIdentifier.PORT_SERIAL) {
if (portId.getName().endsWith(comIdAsString)) {
// create serial port
serialPort = (SerialPort) portId.open(
"StandardSerialPort", 3000);