2017-02-20 51 views
0

我使用jssc库通过串口与设备进行通信。 在标准的Java SerialComm库中有两个方法getInputStream()和getOutputStream()。jssc getInputStream()getOutputstream()

为什么我需要这个?我想实现Xmodem协议根据this例子,XMODEM构造函数需要两个参数:

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


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

在JSSC有没有这样的方法,但我不知道是否有一些替代办法?

回答

0

一种可能性是提供延伸InputStream并实现JSSC SerialPortEventListener接口的定制PortInputStream类。该类从串口接收数据并将其存储在缓冲区中。它还提供了一个read()方法来从缓冲区获取数据。

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) { 
    Log.e(TAG, "interrupted while waiting for serial data."); 
    } 

    return data; 
} 

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

同样,你可以提供一个自定义PortOutputStream类延伸OutputStream和写入到串行接口:

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 { 
     Log.e(TAG, "cannot write to serial port."); 
     throw new IOException("serial port is closed."); 
    } 
    // you may also override write(byte[], int, int) 
} 

之前您实例化你的Xmodem对象,你必须创建两个流:

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

Xmodem xmodem = new Xmodem(pin,pon);