2017-02-20 7 views
0

シリアルポート経由でデバイスと通信するためにjsscライブラリを使用しています。 標準のjava SerialCommライブラリには、getInputStream()とgetOutputStream()の2つのメソッドがあります。jssc getInputStream()getOutputstream()

なぜこれが必要ですか?私はthis例に係るXmodemの実装したいとXMODEMコンストラクタは2のparamsを必要とします。JSSCで

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


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

いくつかの代替方法があるが、そのような方法はありませんですが、私は思ったんだけど?

答えて

0

可能性の1つは、InputStreamを拡張し、JSSC SerialPortEventListenerインターフェイスを実装するカスタムクラスを提供することです。このクラスは、シリアルポートからデータを受け取り、バッファに格納します。また、バッファからデータを取得する方法はread()です。

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オブジェクトをインスタンス化する前に、あなたは両方のストリームを作成する必要があります。

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

同様に、あなたはOutputStreamを拡張し、シリアルインタフェースへの書き込みカスタムPortOutputStreamクラスを提供することができます

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

Xmodem xmodem = new Xmodem(pin,pon); 
関連する問題