diff --git a/src/org/hwo/servicelink/ServiceLink.java b/src/org/hwo/servicelink/ServiceLink.java index d0301a5..91a328c 100644 --- a/src/org/hwo/servicelink/ServiceLink.java +++ b/src/org/hwo/servicelink/ServiceLink.java @@ -64,6 +64,8 @@ public class ServiceLink implements NewSerialPortListener { RxWorker rxWorker; TxWorker txWorker; + boolean closing; + private List serviceLinkListeners; public ServiceLink(NewSerialPort serialPort) @@ -114,31 +116,35 @@ public class ServiceLink implements NewSerialPortListener { this.serialPort.close(); } - public synchronized void open() throws ServiceLinkException + public void open() throws ServiceLinkException { - close(); - - if (serialPort != null){ - _open(); - } else { - throwNotOpen(); + if (!closing){ + close(); + + if (serialPort != null){ + _open(); + } else { + throwNotOpen(); + } } } - public synchronized void close() + public void close() { - if (txWorker != null){ - _close(); - } + if (!closing){ + if (txWorker != null){ + _close(); + } + } } - private synchronized void throwNotOpen() throws ServiceLinkException + private void throwNotOpen() throws ServiceLinkException { if (!isOpen()) throw new ServiceLinkException("serial port not opened!"); } - public synchronized boolean isOpen() + public boolean isOpen() { return (this.serialPort != null) && (this.serialPort.isOpen()) && (this.txWorker != null); } @@ -344,11 +350,11 @@ public class ServiceLink implements NewSerialPortListener { queueRequest(request); } - public synchronized NewSerialPort getSerialPort() { + public NewSerialPort getSerialPort() { return serialPort; } - public synchronized void setSerialPort(NewSerialPort serialPort) { + public void setSerialPort(NewSerialPort serialPort) { if (isOpen()){ this.close(); this.serialPort.removeNewSerialPortListener(this); @@ -373,6 +379,9 @@ public class ServiceLink implements NewSerialPortListener { if (!isAlive()) return; + if (exit) + return; + exit = true; this.notifyAll(); try { @@ -413,6 +422,7 @@ public class ServiceLink implements NewSerialPortListener { } catch (Exception io){ log(io); + exit = true; ServiceLink.this.close(); }; } @@ -430,9 +440,17 @@ public class ServiceLink implements NewSerialPortListener { if (!isAlive()) return; + if (exit) + return; + exit = true; try { - this.wait(); + this.notifyAll(); + this.wait(250); + + if (this.isAlive()) + this.stop(); + } catch (InterruptedException e) { log(e); } @@ -464,13 +482,14 @@ public class ServiceLink implements NewSerialPortListener { tx = txQueue.pollFirst(); } - while (tx != null){ + while ((tx != null)&&(!exit)&&(ServiceLink.this.isOpen())){ byte[] txbytes = tx.toByteArray(); try { log(DEBUGDETAIL,"TX BYTES: %s",ByteArrayHexlifier.byteArrayToString(txbytes)); - serialPort.getOutputStream().write(txbytes); + serialPort.getOutputStream().write(txbytes); } catch (IOException io) { log(io); + exit = true; ServiceLink.this.close(); }