import java.io.*; import java.util.*; import javax.comm.*; class WTCommunication implements SerialPortEventListener { //##### DECLARATIONS ##### //variables private byte[] readBuffer = new byte[3]; //in our application we needed 3 bytes per send/receive private WTConnection conn; //constructor WTCommunication(WTConnection conn) { this.conn = conn; //enable listening on port so we get noticed when there's data coming in try { conn.serialPort.addEventListener(this); } catch (TooManyListenersException e) {} conn.serialPort.notifyOnDataAvailable(true); } //##### METHOD SEND: sends a packet to the port ##### public void Send(byte[] pkg) { try { conn.outputStream.write(pkg); } catch (IOException e) { System.err.println(e); } } public void Send(int pkg) { System.out.println((byte) pkg + " sent to port"); try { conn.outputStream.write((byte) (pkg)); conn.outputStream.write((byte) (pkg)); conn.outputStream.write((byte) (pkg )); conn.outputStream.write((byte) (pkg)); conn.outputStream.write((byte) (pkg)); } catch (IOException e) { System.err.println(e); } } //##### METHOD RECEIVE: receives a packet from the serial port ##### public byte[] Receive(byte[] pkg) { Send(pkg); //send an empty packet first to trigger a response, this is application specific. try { //wait a while to allow a response - application specific Thread.sleep(100); } catch(InterruptedException e) { System.err.println(e); } return readBuffer; } //##### METHOD SERIALEVENT: this is an inherited method that is called automatically when there is data coming in ##### public void serialEvent(SerialPortEvent event) { switch(event.getEventType()) { case SerialPortEvent.DATA_AVAILABLE: try { while (conn.inputStream.available() > 0) { int numBytes = conn.inputStream.read(readBuffer); } } catch (IOException e) { System.err.println(e); } } } }