jssc getInputStream() getOutputstream()

1.8k views Asked by At

I'm using jssc library for communicating with device over serial port. In standard java SerialComm library there are two methods getInputStream() and getOutputStream().

Why I need this? I want to implement Xmodem according to this example and xmodem constructor requires two params:

public Xmodem(InputStream inputStream, OutputStream outputStream) 
{
     this.inputStream = inputStream;
     this.outputStream = outputStream;
}


Xmodem xmodem = new Xmodem(serialPort.getInputStream(),serialPort.getOutputStream());

In jssc there are are no such methods but I'm wondering is there some alternative way?

1

There are 1 answers

0
crnv On

One possibility is to provide a custom PortInputStream class that extends InputStream and implements JSSCs SerialPortEventListener interface. This class receives data from the serial port and stores it in a buffer. It also provides a read() method to get the data from the buffer.

private class PortInputStream extends InputStream implements SerialPortEventListener {
  CircularBuffer buffer = new CircularBuffer(); //backed by a byte[]

  @Override
  public void serialEvent(SerialPortEvent event) {
    if (event.isRXCHAR() && event.getEventValue() > 0) {
     // exception handling omitted
     buffer.write(serialPort.readBytes(event.getEventValue()));
    }
  }

 @Override
 public int read() throws IOException {
  int data = -1;
  try {
    data = buffer.read();
  } catch (InterruptedException e) {
    // exception handling
  } 

  return data;
}

@Override
public int available() throws IOException {
  return buffer.getLength();
}

Similarly, you can provide a custom PortOutputStream class which extends OutputStream and writes to the serial interface:

private class PortOutputStream extends OutputStream {

  SerialPort serialPort = null;

  public PortOutputStream(SerialPort port) {
    serialPort = port;
  }

  @Override
  public void write(int data) throws IOException,SerialPortException {
    if (serialPort != null && serialPort.isOpened()) {
      serialPort.writeByte((byte)(data & 0xFF));
    } else {
      // exception handling
  }
  // you may also override write(byte[], int, int)
}

Before you instantiate your Xmodem object, you have to create both streams:

// omitted serialPort initialization
InputStream pin = new PortInputStream();
serialPort.addEventListener(pin, SerialPort.MASK_RXCHAR);
OutPutStream pon = new PortOutputStream(serialPort);

Xmodem xmodem = new Xmodem(pin,pon);