一種可能性是提供延伸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);