Search in sources :

Example 1 with SerialPortEventListener

use of gnu.io.SerialPortEventListener in project openhab1-addons by openhab.

the class IntRSModule method connect.

@Override
protected CommunicationChannel connect() {
    logger.info("Connecting to INT-RS module at {}", this.port);
    try {
        CommPortIdentifier portIdentifier = CommPortIdentifier.getPortIdentifier(this.port);
        SerialPort serialPort = portIdentifier.open("org.openhab.binding.satel", 2000);
        serialPort.setSerialPortParams(19200, SerialPort.DATABITS_8, SerialPort.STOPBITS_1, SerialPort.PARITY_NONE);
        serialPort.enableReceiveTimeout(this.getTimeout());
        // RXTX serial port library causes high CPU load
        // Start event listener, which will just sleep and slow down event
        // loop
        serialPort.addEventListener(new SerialPortEventListener() {

            @Override
            public void serialEvent(SerialPortEvent ev) {
                try {
                    logger.trace("RXTX library CPU load workaround, sleep forever");
                    Thread.sleep(Long.MAX_VALUE);
                } catch (InterruptedException e) {
                }
            }
        });
        serialPort.notifyOnDataAvailable(true);
        logger.info("INT-RS module connected successfuly");
        return new SerialCommunicationChannel(serialPort);
    } catch (NoSuchPortException e) {
        logger.error("Port {} does not exist", this.port);
    } catch (PortInUseException e) {
        logger.error("Port {} in use.", this.port);
    } catch (UnsupportedCommOperationException e) {
        logger.error("Unsupported comm operation on port {}.", this.port);
    } catch (TooManyListenersException e) {
        logger.error("Too many listeners on port {}.", this.port);
    }
    return null;
}
Also used : UnsupportedCommOperationException(gnu.io.UnsupportedCommOperationException) TooManyListenersException(java.util.TooManyListenersException) NoSuchPortException(gnu.io.NoSuchPortException) PortInUseException(gnu.io.PortInUseException) SerialPort(gnu.io.SerialPort) CommPortIdentifier(gnu.io.CommPortIdentifier) SerialPortEventListener(gnu.io.SerialPortEventListener) SerialPortEvent(gnu.io.SerialPortEvent)

Example 2 with SerialPortEventListener

use of gnu.io.SerialPortEventListener in project openhab1-addons by openhab.

the class UrtsiDevice method writeString.

/**
     * Sends a string to the serial port of this device.
     * The writing of the msg is executed synchronized, so it's guaranteed that the device doesn't get
     * multiple messages concurrently.
     *
     * @param msg
     *            the string to send
     * @return true, if the message has been transmitted successfully, otherwise false.
     */
synchronized boolean writeString(final String msg) {
    logger.debug("Writing '{}' to serial port {}", msg, port);
    final long earliestNextExecution = lastCommandTime + interval;
    while (earliestNextExecution > System.currentTimeMillis()) {
        try {
            Thread.sleep(100);
        } catch (InterruptedException ex) {
            return false;
        }
    }
    try {
        final List<Boolean> listenerResult = new ArrayList<Boolean>();
        serialPort.addEventListener(new SerialPortEventListener() {

            @Override
            public void serialEvent(SerialPortEvent event) {
                if (event.getEventType() == SerialPortEvent.DATA_AVAILABLE) {
                    // we get here if data has been received
                    final StringBuilder sb = new StringBuilder();
                    final byte[] readBuffer = new byte[20];
                    try {
                        do {
                            // read data from serial device
                            while (inputStream.available() > 0) {
                                final int bytes = inputStream.read(readBuffer);
                                sb.append(new String(readBuffer, 0, bytes));
                            }
                            try {
                                // add wait states around reading the stream, so that interrupted transmissions are
                                // merged
                                Thread.sleep(100);
                            } catch (InterruptedException e) {
                            // ignore interruption
                            }
                        } while (inputStream.available() > 0);
                        final String result = sb.toString();
                        if (result.equals(msg)) {
                            listenerResult.add(true);
                        }
                    } catch (IOException e) {
                        logger.debug("Error receiving data on serial port {}: {}", port, e.getMessage());
                    }
                }
            }
        });
        serialPort.notifyOnDataAvailable(true);
        outputStream.write(msg.getBytes());
        outputStream.flush();
        lastCommandTime = System.currentTimeMillis();
        final long timeout = lastCommandTime + 1000;
        while (listenerResult.isEmpty() && System.currentTimeMillis() < timeout) {
            // Waiting for response
            Thread.sleep(100);
        }
        return !listenerResult.isEmpty();
    } catch (Exception e) {
        logger.error("Error writing '{}' to serial port {}: {}", msg, port, e.getMessage());
    } finally {
        serialPort.removeEventListener();
    }
    return false;
}
Also used : SerialPortEventListener(gnu.io.SerialPortEventListener) ArrayList(java.util.ArrayList) SerialPortEvent(gnu.io.SerialPortEvent) IOException(java.io.IOException) PortInUseException(gnu.io.PortInUseException) UnsupportedCommOperationException(gnu.io.UnsupportedCommOperationException) IOException(java.io.IOException) NoSuchPortException(gnu.io.NoSuchPortException)

Example 3 with SerialPortEventListener

use of gnu.io.SerialPortEventListener in project JMRI by JMRI.

the class SerialDriverAdapter method openPort.

@Override
public String openPort(String portName, String appName) {
    try {
        // get and open the primary port
        CommPortIdentifier portID = CommPortIdentifier.getPortIdentifier(portName);
        try {
            // name of program, msec to wait
            activeSerialPort = (SerialPort) portID.open(appName, 2000);
        } catch (PortInUseException p) {
            return handlePortBusy(p, portName, log);
        }
        // try to set it for CMRI serial
        try {
            setSerialPort();
        } catch (gnu.io.UnsupportedCommOperationException e) {
            log.error("Cannot set serial parameters on port " + portName + ": " + e.getMessage());
            return "Cannot set serial parameters on port " + portName + ": " + e.getMessage();
        }
        // set framing (end) character
        try {
            activeSerialPort.enableReceiveFraming(0x03);
            log.debug("Serial framing was observed as: " + activeSerialPort.isReceiveFramingEnabled() + " " + activeSerialPort.getReceiveFramingByte());
        } catch (Exception ef) {
            log.debug("failed to set serial framing: " + ef);
        }
        // set timeout; framing should work before this anyway
        try {
            activeSerialPort.enableReceiveTimeout(10);
            log.debug("Serial timeout was observed as: " + activeSerialPort.getReceiveTimeout() + " " + activeSerialPort.isReceiveTimeoutEnabled());
        } catch (Exception et) {
            log.info("failed to set serial timeout: " + et);
        }
        // get and save stream
        serialStream = activeSerialPort.getInputStream();
        // purge contents, if any
        purgeStream(serialStream);
        // report status?
        if (log.isInfoEnabled()) {
            // report now
            log.info(portName + " port opened at " + activeSerialPort.getBaudRate() + " baud with" + " DTR: " + activeSerialPort.isDTR() + " RTS: " + activeSerialPort.isRTS() + " DSR: " + activeSerialPort.isDSR() + " CTS: " + activeSerialPort.isCTS() + "  CD: " + activeSerialPort.isCD());
        }
        if (log.isDebugEnabled()) {
            // report additional status
            log.debug(" port flow control shows " + (activeSerialPort.getFlowControlMode() == SerialPort.FLOWCONTROL_RTSCTS_OUT ? "hardware flow control" : "no flow control"));
        }
        if (log.isDebugEnabled()) {
            // arrange to notify later
            activeSerialPort.addEventListener(new SerialPortEventListener() {

                @Override
                public void serialEvent(SerialPortEvent e) {
                    int type = e.getEventType();
                    switch(type) {
                        case SerialPortEvent.DATA_AVAILABLE:
                            log.info("SerialEvent: DATA_AVAILABLE is " + e.getNewValue());
                            return;
                        case SerialPortEvent.OUTPUT_BUFFER_EMPTY:
                            log.info("SerialEvent: OUTPUT_BUFFER_EMPTY is " + e.getNewValue());
                            return;
                        case SerialPortEvent.CTS:
                            log.info("SerialEvent: CTS is " + e.getNewValue());
                            return;
                        case SerialPortEvent.DSR:
                            log.info("SerialEvent: DSR is " + e.getNewValue());
                            return;
                        case SerialPortEvent.RI:
                            log.info("SerialEvent: RI is " + e.getNewValue());
                            return;
                        case SerialPortEvent.CD:
                            log.info("SerialEvent: CD is " + e.getNewValue());
                            return;
                        case SerialPortEvent.OE:
                            log.info("SerialEvent: OE (overrun error) is " + e.getNewValue());
                            return;
                        case SerialPortEvent.PE:
                            log.info("SerialEvent: PE (parity error) is " + e.getNewValue());
                            return;
                        case SerialPortEvent.FE:
                            log.info("SerialEvent: FE (framing error) is " + e.getNewValue());
                            return;
                        case SerialPortEvent.BI:
                            log.info("SerialEvent: BI (break interrupt) is " + e.getNewValue());
                            return;
                        default:
                            log.info("SerialEvent of unknown type: " + type + " value: " + e.getNewValue());
                            return;
                    }
                }
            });
            try {
                activeSerialPort.notifyOnFramingError(true);
            } catch (Exception e) {
                log.debug("Could not notifyOnFramingError: " + e);
            }
            try {
                activeSerialPort.notifyOnBreakInterrupt(true);
            } catch (Exception e) {
                log.debug("Could not notifyOnBreakInterrupt: " + e);
            }
            try {
                activeSerialPort.notifyOnParityError(true);
            } catch (Exception e) {
                log.debug("Could not notifyOnParityError: " + e);
            }
            try {
                activeSerialPort.notifyOnOverrunError(true);
            } catch (Exception e) {
                log.debug("Could not notifyOnOverrunError: " + e);
            }
        }
        opened = true;
    } catch (gnu.io.NoSuchPortException p) {
        return handlePortNotFound(p, portName, log);
    } catch (Exception ex) {
        log.error("Unexpected exception while opening port " + portName + " trace follows: " + ex);
        ex.printStackTrace();
        return "Unexpected error while opening port " + portName + ": " + ex;
    }
    // normal operation
    return null;
}
Also used : PortInUseException(gnu.io.PortInUseException) CommPortIdentifier(gnu.io.CommPortIdentifier) SerialPortEventListener(gnu.io.SerialPortEventListener) SerialPortEvent(gnu.io.SerialPortEvent) PortInUseException(gnu.io.PortInUseException)

Example 4 with SerialPortEventListener

use of gnu.io.SerialPortEventListener in project JMRI by JMRI.

the class LocoBufferAdapter method openPort.

@Override
public String openPort(String portName, String appName) {
    // open the primary and secondary ports in LocoNet mode, check ability to set moderators
    try {
        // get and open the primary port
        CommPortIdentifier portID = CommPortIdentifier.getPortIdentifier(portName);
        try {
            // name of program, msec to wait
            activeSerialPort = (SerialPort) portID.open(appName, 2000);
        } catch (PortInUseException p) {
            return handlePortBusy(p, portName, log);
        }
        // try to set it for LocoNet via LocoBuffer
        try {
            setSerialPort(activeSerialPort);
        } catch (gnu.io.UnsupportedCommOperationException e) {
            log.error(// NOI18N
            "Cannot set serial parameters on port " + portName + ": " + e.getMessage());
            return // NOI18N
            "Cannot set serial parameters on port " + portName + ": " + e.getMessage();
        }
        // set timeout
        try {
            activeSerialPort.enableReceiveTimeout(10);
            log.debug(// NOI18N
            "Serial timeout was observed as: " + activeSerialPort.getReceiveTimeout() + " " + activeSerialPort.isReceiveTimeoutEnabled());
        } catch (Exception et) {
            // NOI18N
            log.info("failed to set serial timeout: " + et);
        }
        // get and save stream
        serialStream = activeSerialPort.getInputStream();
        // purge contents, if any
        purgeStream(serialStream);
        // report status?
        if (log.isInfoEnabled()) {
            // report now
            log.info(// NOI18N
            portName + " port opened at " + activeSerialPort.getBaudRate() + // NOI18N
            " baud with" + " DTR: " + // NOI18N
            activeSerialPort.isDTR() + " RTS: " + // NOI18N
            activeSerialPort.isRTS() + " DSR: " + // NOI18N
            activeSerialPort.isDSR() + " CTS: " + // NOI18N
            activeSerialPort.isCTS() + "  CD: " + // NOI18N
            activeSerialPort.isCD());
        }
        if (log.isDebugEnabled()) {
            // report additional status
            log.debug(// NOI18N
            " port flow control shows " + // NOI18N
            (activeSerialPort.getFlowControlMode() == SerialPort.FLOWCONTROL_RTSCTS_OUT ? "hardware flow control" : "no flow control"));
        }
        if (log.isDebugEnabled()) {
            // arrange to notify later
            activeSerialPort.addEventListener(new SerialPortEventListener() {

                @Override
                public void serialEvent(SerialPortEvent e) {
                    int type = e.getEventType();
                    switch(type) {
                        case SerialPortEvent.DATA_AVAILABLE:
                            // NOI18N
                            log.info("SerialEvent: DATA_AVAILABLE is " + e.getNewValue());
                            return;
                        case SerialPortEvent.OUTPUT_BUFFER_EMPTY:
                            // NOI18N
                            log.info("SerialEvent: OUTPUT_BUFFER_EMPTY is " + e.getNewValue());
                            return;
                        case SerialPortEvent.CTS:
                            // NOI18N
                            log.info("SerialEvent: CTS is " + e.getNewValue());
                            return;
                        case SerialPortEvent.DSR:
                            // NOI18N
                            log.info("SerialEvent: DSR is " + e.getNewValue());
                            return;
                        case SerialPortEvent.RI:
                            // NOI18N
                            log.info("SerialEvent: RI is " + e.getNewValue());
                            return;
                        case SerialPortEvent.CD:
                            // NOI18N
                            log.info("SerialEvent: CD is " + e.getNewValue());
                            return;
                        case SerialPortEvent.OE:
                            // NOI18N
                            log.info("SerialEvent: OE (overrun error) is " + e.getNewValue());
                            return;
                        case SerialPortEvent.PE:
                            // NOI18N
                            log.info("SerialEvent: PE (parity error) is " + e.getNewValue());
                            return;
                        case SerialPortEvent.FE:
                            // NOI18N
                            log.info("SerialEvent: FE (framing error) is " + e.getNewValue());
                            return;
                        case SerialPortEvent.BI:
                            // NOI18N
                            log.info("SerialEvent: BI (break interrupt) is " + e.getNewValue());
                            return;
                        default:
                            // NOI18N
                            log.info("SerialEvent of unknown type: " + type + " value: " + e.getNewValue());
                            return;
                    }
                }
            });
            try {
                activeSerialPort.notifyOnFramingError(true);
            } catch (Exception e) {
                // NOI18N
                log.debug("Could not notifyOnFramingError: " + e);
            }
            try {
                activeSerialPort.notifyOnBreakInterrupt(true);
            } catch (Exception e) {
                // NOI18N
                log.debug("Could not notifyOnBreakInterrupt: " + e);
            }
            try {
                activeSerialPort.notifyOnParityError(true);
            } catch (Exception e) {
                // NOI18N
                log.debug("Could not notifyOnParityError: " + e);
            }
            try {
                activeSerialPort.notifyOnOverrunError(true);
            } catch (Exception e) {
                // NOI18N
                log.debug("Could not notifyOnOverrunError: " + e);
            }
        }
        opened = true;
    } catch (gnu.io.NoSuchPortException p) {
        return handlePortNotFound(p, portName, log);
    } catch (Exception ex) {
        // NOI18N
        log.error("Unexpected exception while opening port {} trace follows:", portName, ex);
        return "Unexpected error while opening port " + portName + ": " + ex;
    }
    // normal operation
    return null;
}
Also used : PortInUseException(gnu.io.PortInUseException) CommPortIdentifier(gnu.io.CommPortIdentifier) SerialPortEventListener(gnu.io.SerialPortEventListener) SerialPortEvent(gnu.io.SerialPortEvent) PortInUseException(gnu.io.PortInUseException)

Example 5 with SerialPortEventListener

use of gnu.io.SerialPortEventListener in project JMRI by JMRI.

the class SerialDriverAdapter method openPort.

@Override
public String openPort(String portName, String appName) {
    try {
        // get and open the primary port
        CommPortIdentifier portID = CommPortIdentifier.getPortIdentifier(portName);
        try {
            // name of program, msec to wait
            activeSerialPort = (SerialPort) portID.open(appName, 2000);
        } catch (PortInUseException p) {
            return handlePortBusy(p, portName, log);
        }
        // try to set it for serial
        try {
            setSerialPort();
        } catch (gnu.io.UnsupportedCommOperationException e) {
            log.error("Cannot set serial parameters on port " + portName + ": " + e.getMessage());
            return "Cannot set serial parameters on port " + portName + ": " + e.getMessage();
        }
        // set framing (end) character
        try {
            activeSerialPort.enableReceiveFraming(0x03);
            log.debug("Serial framing was observed as: " + activeSerialPort.isReceiveFramingEnabled() + " " + activeSerialPort.getReceiveFramingByte());
        } catch (Exception ef) {
            log.debug("failed to set serial framing: " + ef);
        }
        // set timeout; framing should work before this anyway
        try {
            activeSerialPort.enableReceiveTimeout(10);
            log.debug("Serial timeout was observed as: " + activeSerialPort.getReceiveTimeout() + " " + activeSerialPort.isReceiveTimeoutEnabled());
        } catch (Exception et) {
            log.info("failed to set serial timeout: " + et);
        }
        // get and save stream
        serialStream = activeSerialPort.getInputStream();
        // purge contents, if any
        purgeStream(serialStream);
        // report status?
        if (log.isInfoEnabled()) {
            // report now
            log.info(portName + " port opened at " + activeSerialPort.getBaudRate() + " baud with" + " DTR: " + activeSerialPort.isDTR() + " RTS: " + activeSerialPort.isRTS() + " DSR: " + activeSerialPort.isDSR() + " CTS: " + activeSerialPort.isCTS() + "  CD: " + activeSerialPort.isCD());
        }
        if (log.isDebugEnabled()) {
            // report additional status
            log.debug(" port flow control shows " + (activeSerialPort.getFlowControlMode() == SerialPort.FLOWCONTROL_RTSCTS_OUT ? "hardware flow control" : "no flow control"));
        }
        if (log.isDebugEnabled()) {
            // arrange to notify later
            activeSerialPort.addEventListener(new SerialPortEventListener() {

                @Override
                public void serialEvent(SerialPortEvent e) {
                    int type = e.getEventType();
                    switch(type) {
                        case SerialPortEvent.DATA_AVAILABLE:
                            log.info("SerialEvent: DATA_AVAILABLE is " + e.getNewValue());
                            return;
                        case SerialPortEvent.OUTPUT_BUFFER_EMPTY:
                            log.info("SerialEvent: OUTPUT_BUFFER_EMPTY is " + e.getNewValue());
                            return;
                        case SerialPortEvent.CTS:
                            log.info("SerialEvent: CTS is " + e.getNewValue());
                            return;
                        case SerialPortEvent.DSR:
                            log.info("SerialEvent: DSR is " + e.getNewValue());
                            return;
                        case SerialPortEvent.RI:
                            log.info("SerialEvent: RI is " + e.getNewValue());
                            return;
                        case SerialPortEvent.CD:
                            log.info("SerialEvent: CD is " + e.getNewValue());
                            return;
                        case SerialPortEvent.OE:
                            log.info("SerialEvent: OE (overrun error) is " + e.getNewValue());
                            return;
                        case SerialPortEvent.PE:
                            log.info("SerialEvent: PE (parity error) is " + e.getNewValue());
                            return;
                        case SerialPortEvent.FE:
                            log.info("SerialEvent: FE (framing error) is " + e.getNewValue());
                            return;
                        case SerialPortEvent.BI:
                            log.info("SerialEvent: BI (break interrupt) is " + e.getNewValue());
                            return;
                        default:
                            log.info("SerialEvent of unknown type: " + type + " value: " + e.getNewValue());
                            return;
                    }
                }
            });
            try {
                activeSerialPort.notifyOnFramingError(true);
            } catch (Exception e) {
                log.debug("Could not notifyOnFramingError: " + e);
            }
            try {
                activeSerialPort.notifyOnBreakInterrupt(true);
            } catch (Exception e) {
                log.debug("Could not notifyOnBreakInterrupt: " + e);
            }
            try {
                activeSerialPort.notifyOnParityError(true);
            } catch (Exception e) {
                log.debug("Could not notifyOnParityError: " + e);
            }
            try {
                activeSerialPort.notifyOnOverrunError(true);
            } catch (Exception e) {
                log.debug("Could not notifyOnOverrunError: " + e);
            }
        }
        opened = true;
    } catch (gnu.io.NoSuchPortException p) {
        return handlePortNotFound(p, portName, log);
    } catch (Exception ex) {
        log.error("Unexpected exception while opening port " + portName + " trace follows: " + ex);
        ex.printStackTrace();
        return "Unexpected error while opening port " + portName + ": " + ex;
    }
    // normal operation
    return null;
}
Also used : PortInUseException(gnu.io.PortInUseException) CommPortIdentifier(gnu.io.CommPortIdentifier) SerialPortEventListener(gnu.io.SerialPortEventListener) SerialPortEvent(gnu.io.SerialPortEvent) PortInUseException(gnu.io.PortInUseException)

Aggregations

PortInUseException (gnu.io.PortInUseException)24 SerialPortEvent (gnu.io.SerialPortEvent)24 SerialPortEventListener (gnu.io.SerialPortEventListener)24 CommPortIdentifier (gnu.io.CommPortIdentifier)23 IOException (java.io.IOException)10 UnsupportedCommOperationException (gnu.io.UnsupportedCommOperationException)3 NoSuchPortException (gnu.io.NoSuchPortException)2 TooManyListenersException (java.util.TooManyListenersException)2 SerialPort (gnu.io.SerialPort)1 ArrayList (java.util.ArrayList)1