jssc getInputStream() getOutputstream()

耗尽温柔 提交于 2019-12-12 01:44:46

问题


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:


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);


来源:https://stackoverflow.com/questions/42341530/jssc-getinputstream-getoutputstream

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!