У меня нет под рукой самого API, но по идее это должно выглядеть так:
Код | import java.io.*; import java.util.*; import javax.comm.*;
public class Read implements Runnable, SerialPortEventListener { private InputStream inputStream; private SerialPort serialPort; private Thread readThread; private boolean running; private Object LOCK = new Object();
public SimpleRead(CommPortIdentifier portId) { try { serialPort = (SerialPort) portId.open("SimpleReadApp", 2000); inputStream = serialPort.getInputStream(); } catch(Exception e) {}
serialPort.notifyOnDataAvailable(true);
try { serialPort.setSerialPortParams(9600, SerialPort.DATABITS_8, SerialPort.STOPBITS_1, SerialPort.PARITY_NONE); } catch(UnsupportedCommOperationException e) {}
readThread = new Thread(this); running = true; readThread.start(); }
public void run() { try { serialPort.addEventListener(this); } catch(TooManyListenersException e) {} while(running) { synchronized(LOCK) { try { LOCK.wait(); } catch(InterruptedException e) {} } } try { serialPort.removeEventListener(this); } catch(TooManyListenersException e) {} }
public void stop() { synchronized(LOCK) { this.running = false; LOCK.notifyAll(); } }
public void serialEvent(SerialPortEvent event) { //process event } } |
|