2017-02-20 238 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);