import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import javax.comm.CommPortIdentifier; import javax.comm.SerialPort; public class CricketComm { private static final boolean DEBUG = false; private static final String hex(int x) { return "0x"+Integer.toHexString(x); } private SerialPort fPort; private InputStream fIn; private OutputStream fOut; CricketComm(String port) { try { CommPortIdentifier id = CommPortIdentifier.getPortIdentifier(port); fPort = (SerialPort) id.open("Passing", /*timeout=*/ 0); fPort.setSerialPortParams(/*baudrate=*/ 9600, SerialPort.DATABITS_8, SerialPort.STOPBITS_1, SerialPort.PARITY_NONE); fIn = fPort.getInputStream(); fOut = fPort.getOutputStream(); } catch (Exception e) { throw new Problem(e, "Cannot start CricketComm"); } } void send(int value) { try { if (DEBUG) System.out.println("Send "+hex(value)); fOut.write(value); if (DEBUG) System.out.println("Waiting for echo"); int echo = fIn.read(); if (echo != value) throw new Problem("Send "+hex(value)+", echo "+hex(echo)); if (DEBUG) System.out.println("Received echo"); } catch (IOException e) { throw new Problem(e, "Cannot send to Cricket"); } } int receive() { try { if (DEBUG) System.out.println("Waiting for receive"); int value = fIn.read(); if (DEBUG) System.out.println("Received "+hex(value)); return value; } catch (IOException e) { throw new Problem(e, "Cannot receive from Cricket"); } } void close() { fPort.close(); } }