/* * Author: David Loudon (Converted from Sun microsystems JavaTanks Demonstration) * Description: Handles low level sending and receiving of messages via the infrared tower. * Makes use of the Java communications API to control the serial port. */ import java.io.*; import java.util.*; import javax.comm.*; public class IRProtocol implements SerialPortEventListener { private SerialPort port; private OutputStream out; private InputStream in; private MessageBuffer mbuf; public IRProtocol() { //initialises serial port with correct parameters for communication with RCX CommPortIdentifier portID= null; try { portID= CommPortIdentifier.getPortIdentifier("COM1"); System.out.println("COM ID: "+ portID); port= (SerialPort) portID.open("IRProtocol", 1000); out= port.getOutputStream(); in= port.getInputStream(); port.setSerialPortParams( 2400, SerialPort.DATABITS_8, SerialPort.STOPBITS_1, SerialPort.PARITY_ODD ); port.addEventListener(this); port.notifyOnDataAvailable(true); } catch (Exception e) { e.printStackTrace(); } mbuf= new MessageBuffer(); System.out.println("\nUsing port: " + portID.getName()); System.out.println("Parity is set to: " + (port.getParity() == SerialPort.PARITY_ODD ? "ODD" : "NONE")); System.out.println("Receive buffer size is: " + port.getInputBufferSize()); }//IRProtocol constructor private String toHex(byte x) { return ((x & 0xff) < 16 ? "0" : "") + Integer.toHexString(x & 0xff).toUpperCase(); }//toHex /* * SerialPortEventListener method. Only responds to data being * available on the input buffer. */ public void serialEvent(SerialPortEvent e) { int type= e.getEventType(); if(type == SerialPortEvent.DATA_AVAILABLE){ int available= 0; try{ //Read in all data on the input buffer available= in.available(); byte[] chunk= new byte[available]; in.read(chunk); //Send data to the message buffer mbuf.append(chunk); /* for(int i=0;i