Search in sources :

Example 11 with CommPortIdentifier

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

the class ComfoAirConnector method open.

/**
     * Open and initialize a serial port.
     *
     * @param portName
     *            e.g. /dev/ttyS0
     * @param listener
     *            the listener which is informed after a successful response
     *            read
     * @throws InitializationException
     */
public void open(String portName) throws InitializationException {
    logger.debug("Open ComfoAir connection");
    port = portName;
    CommPortIdentifier portIdentifier;
    try {
        portIdentifier = CommPortIdentifier.getPortIdentifier(port);
        try {
            serialPort = portIdentifier.open("openhab", 3000);
            serialPort.setSerialPortParams(9600, SerialPort.DATABITS_8, SerialPort.STOPBITS_1, SerialPort.PARITY_NONE);
            serialPort.enableReceiveThreshold(1);
            serialPort.enableReceiveTimeout(1000);
            // RXTX serial port library causes high CPU load
            // Start event listener, which will just sleep and slow down event loop
            serialPort.addEventListener(new CPUWorkaroundThread());
            serialPort.notifyOnDataAvailable(true);
            inputStream = new DataInputStream(new BufferedInputStream(serialPort.getInputStream()));
            outputStream = serialPort.getOutputStream();
            ComfoAirCommand command = ComfoAirCommandType.getChangeCommand(ComfoAirCommandType.ACTIVATE.key, new DecimalType(1));
            sendCommand(command);
        } catch (PortInUseException e) {
            throw new InitializationException(e);
        } catch (UnsupportedCommOperationException e) {
            throw new InitializationException(e);
        } catch (IOException e) {
            throw new InitializationException(e);
        } catch (TooManyListenersException e) {
            throw new InitializationException(e);
        }
    } catch (NoSuchPortException e) {
        StringBuilder sb = new StringBuilder();
        @SuppressWarnings("rawtypes") Enumeration portList = CommPortIdentifier.getPortIdentifiers();
        while (portList.hasMoreElements()) {
            CommPortIdentifier id = (CommPortIdentifier) portList.nextElement();
            if (id.getPortType() == CommPortIdentifier.PORT_SERIAL) {
                sb.append(id.getName() + "\n");
            }
        }
        throw new InitializationException("Serial port '" + port + "' could not be found. Available ports are:\n" + sb.toString());
    }
}
Also used : UnsupportedCommOperationException(gnu.io.UnsupportedCommOperationException) Enumeration(java.util.Enumeration) CommPortIdentifier(gnu.io.CommPortIdentifier) IOException(java.io.IOException) DataInputStream(java.io.DataInputStream) InitializationException(org.openhab.binding.comfoair.internal.InitializationException) TooManyListenersException(java.util.TooManyListenersException) PortInUseException(gnu.io.PortInUseException) NoSuchPortException(gnu.io.NoSuchPortException) BufferedInputStream(java.io.BufferedInputStream) DecimalType(org.openhab.core.library.types.DecimalType)

Example 12 with CommPortIdentifier

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

the class AlarmDecoderBinding method connect.

private synchronized void connect() {
    try {
        // make sure we have disconnected
        disconnect();
        markAllItemsUnupdated();
        if (m_tcpHostName != null && m_tcpPort > 0) {
            m_socket = new Socket(m_tcpHostName, m_tcpPort);
            m_reader = new BufferedReader(new InputStreamReader(m_socket.getInputStream()));
            m_writer = new BufferedWriter(new OutputStreamWriter(m_socket.getOutputStream()));
            logger.info("connected to {}:{}", m_tcpHostName, m_tcpPort);
            startMsgReader();
        } else if (this.m_serialDeviceName != null) {
            /*
                 * by default, RXTX searches only devices /dev/ttyS* and
                 * /dev/ttyUSB*, and will so not find symlinks. The
                 * setProperty() call below helps
                 */
            updateSerialProperties(m_serialDeviceName);
            CommPortIdentifier ci = CommPortIdentifier.getPortIdentifier(m_serialDeviceName);
            CommPort cp = ci.open("openhabalarmdecoder", 10000);
            if (cp == null) {
                throw new IllegalStateException("cannot open serial port!");
            }
            if (cp instanceof SerialPort) {
                m_port = (SerialPort) cp;
            } else {
                throw new IllegalStateException("unknown port type");
            }
            m_port.setSerialPortParams(m_portSpeed, SerialPort.DATABITS_8, SerialPort.STOPBITS_1, SerialPort.PARITY_NONE);
            m_port.setFlowControlMode(SerialPort.FLOWCONTROL_RTSCTS_IN | SerialPort.FLOWCONTROL_RTSCTS_OUT);
            m_port.disableReceiveFraming();
            m_port.disableReceiveThreshold();
            m_reader = new BufferedReader(new InputStreamReader(m_port.getInputStream()));
            m_writer = new BufferedWriter(new OutputStreamWriter(m_port.getOutputStream()));
            logger.info("connected to serial port: {}", m_serialDeviceName);
            startMsgReader();
        } else {
            logger.warn("alarmdecoder hostname or port not configured!");
        }
    } catch (PortInUseException e) {
        logger.error("cannot open serial port: {}, it is in use!", m_serialDeviceName);
    } catch (UnsupportedCommOperationException e) {
        logger.error("got unsupported operation {} on port {}", e.getMessage(), m_serialDeviceName);
    } catch (NoSuchPortException e) {
        logger.error("got no such port for {}", m_serialDeviceName);
    } catch (IllegalStateException e) {
        logger.error("got unknown port type for {}", m_serialDeviceName);
    } catch (UnknownHostException e) {
        logger.error("unknown host name :{}: ", m_tcpHostName, e);
    } catch (IOException e) {
        logger.error("cannot open connection to {}", m_connectString);
    }
}
Also used : UnsupportedCommOperationException(gnu.io.UnsupportedCommOperationException) InputStreamReader(java.io.InputStreamReader) UnknownHostException(java.net.UnknownHostException) CommPortIdentifier(gnu.io.CommPortIdentifier) CommPort(gnu.io.CommPort) IOException(java.io.IOException) BufferedWriter(java.io.BufferedWriter) PortInUseException(gnu.io.PortInUseException) NoSuchPortException(gnu.io.NoSuchPortException) SerialPort(gnu.io.SerialPort) BufferedReader(java.io.BufferedReader) OutputStreamWriter(java.io.OutputStreamWriter) Socket(java.net.Socket)

Example 13 with CommPortIdentifier

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

the class AlarmDecoderBinding method updateSerialProperties.

private void updateSerialProperties(String devName) {
    /*
         * By default, RXTX searches only devices /dev/ttyS* and
         * /dev/ttyUSB*, and will therefore not find devices that
         * have been symlinked. Adding them however is tricky, see below.
         */
    // first go through the port identifiers to find any that are not in
    // "gnu.io.rxtx.SerialPorts"
    ArrayList<String> allPorts = new ArrayList<String>();
    @SuppressWarnings("rawtypes") Enumeration portList = CommPortIdentifier.getPortIdentifiers();
    while (portList.hasMoreElements()) {
        CommPortIdentifier id = (CommPortIdentifier) portList.nextElement();
        if (id.getPortType() == CommPortIdentifier.PORT_SERIAL) {
            allPorts.add(id.getName());
        }
    }
    logger.trace("ports found from identifiers: {}", StringUtils.join(allPorts, ":"));
    // now add our port so it's in the list
    if (!allPorts.contains(devName)) {
        allPorts.add(devName);
    }
    // add any that are already in "gnu.io.rxtx.SerialPorts"
    // so we don't accidentally overwrite some of those ports
    String ports = System.getProperty("gnu.io.rxtx.SerialPorts");
    if (ports != null) {
        ArrayList<String> propPorts = new ArrayList<String>(Arrays.asList(ports.split(":")));
        for (String p : propPorts) {
            if (!allPorts.contains(p)) {
                allPorts.add(p);
            }
        }
    }
    String finalPorts = StringUtils.join(allPorts, ":");
    logger.trace("final port list: {}", finalPorts);
    // Finally overwrite the "gnu.io.rxtx.SerialPorts" System property.
    // Note: calling setProperty() is not threadsafe. All bindings run in
    // the same address space, System.setProperty() is globally visible
    // to all bindings.
    // This means if multiple bindings use the serial port there is a
    // race condition where two bindings could be changing the properties
    // at the same time.
    System.setProperty("gnu.io.rxtx.SerialPorts", finalPorts);
}
Also used : Enumeration(java.util.Enumeration) CommPortIdentifier(gnu.io.CommPortIdentifier) ArrayList(java.util.ArrayList)

Example 14 with CommPortIdentifier

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

the class NikobusInterface method openCommPort.

/**
     * Locate serial port and open connection.
     * 
     * @param portName
     * @throws Exception
     */
@SuppressWarnings("rawtypes")
private void openCommPort(String portName) throws Exception {
    if (log.isDebugEnabled()) {
        Enumeration portIdentifiers = CommPortIdentifier.getPortIdentifiers();
        while (portIdentifiers.hasMoreElements()) {
            CommPortIdentifier id = (CommPortIdentifier) portIdentifiers.nextElement();
            log.debug("Found port: {} x {}", id.getName(), id.getCurrentOwner());
        }
    }
    CommPortIdentifier portIdentifier = null;
    try {
        portIdentifier = CommPortIdentifier.getPortIdentifier(portName);
    } catch (NoSuchPortException e) {
        log.debug("Port not found during first attempt : {}", e.getMessage());
    }
    if (portIdentifier == null) {
        try {
            System.setProperty(SERIAL_PORT_PROPERTY_NAME, portName);
            portIdentifier = CommPortIdentifier.getPortIdentifier(portName);
        } catch (Exception e) {
            log.debug("Port not found during second attempt : {}", e.getMessage());
            System.clearProperty(SERIAL_PORT_PROPERTY_NAME);
        }
    }
    if (portIdentifier == null) {
        throw new Exception("Serial port '" + portName + "' not found.");
    }
    if (portIdentifier.isCurrentlyOwned()) {
        throw new Exception("Serial port '" + portName + "' is in use.");
    }
    // open port
    port = portIdentifier.open(this.getClass().getSimpleName(), CONNECT_TIMEOUT);
    log.info("Connected to serial port '{}'", portIdentifier.getName());
    // configure
    port.setSerialPortParams(9600, SerialPort.DATABITS_8, SerialPort.STOPBITS_1, SerialPort.PARITY_NONE);
    port.notifyOnDataAvailable(true);
    port.addEventListener(this);
}
Also used : Enumeration(java.util.Enumeration) NoSuchPortException(gnu.io.NoSuchPortException) CommPortIdentifier(gnu.io.CommPortIdentifier) NoSuchPortException(gnu.io.NoSuchPortException) IOException(java.io.IOException)

Example 15 with CommPortIdentifier

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

the class SerialDevice method initialize.

/**
     * Initialize this device and open the serial port
     * 
     * @throws InitializationException if port can not be opened
     */
@SuppressWarnings("rawtypes")
public void initialize() throws InitializationException {
    // parse ports and if the default port is found, initialized the reader
    Enumeration portList = CommPortIdentifier.getPortIdentifiers();
    while (portList.hasMoreElements()) {
        CommPortIdentifier id = (CommPortIdentifier) portList.nextElement();
        if (id.getPortType() == CommPortIdentifier.PORT_SERIAL) {
            if (id.getName().equals(port)) {
                logger.debug("Serial port '{}' has been found.", port);
                portId = id;
            }
        }
    }
    if (portId != null) {
        // initialize serial port
        try {
            serialPort = portId.open("openHAB", 2000);
        } catch (PortInUseException e) {
            throw new InitializationException(e);
        }
        try {
            inputStream = serialPort.getInputStream();
        } catch (IOException e) {
            throw new InitializationException(e);
        }
        try {
            serialPort.addEventListener(this);
        } catch (TooManyListenersException e) {
            throw new InitializationException(e);
        }
        // activate the DATA_AVAILABLE notifier
        serialPort.notifyOnDataAvailable(true);
        try {
            // set port parameters
            serialPort.setSerialPortParams(baud, SerialPort.DATABITS_8, SerialPort.STOPBITS_1, SerialPort.PARITY_NONE);
        } catch (UnsupportedCommOperationException e) {
            throw new InitializationException(e);
        }
        try {
            // get the output stream
            outputStream = serialPort.getOutputStream();
        } catch (IOException e) {
            throw new InitializationException(e);
        }
    } else {
        StringBuilder sb = new StringBuilder();
        portList = CommPortIdentifier.getPortIdentifiers();
        while (portList.hasMoreElements()) {
            CommPortIdentifier id = (CommPortIdentifier) portList.nextElement();
            if (id.getPortType() == CommPortIdentifier.PORT_SERIAL) {
                sb.append(id.getName() + "\n");
            }
        }
        throw new InitializationException("Serial port '" + port + "' could not be found. Available ports are:\n" + sb.toString());
    }
}
Also used : TooManyListenersException(java.util.TooManyListenersException) UnsupportedCommOperationException(gnu.io.UnsupportedCommOperationException) Enumeration(java.util.Enumeration) PortInUseException(gnu.io.PortInUseException) CommPortIdentifier(gnu.io.CommPortIdentifier) IOException(java.io.IOException)

Aggregations

CommPortIdentifier (gnu.io.CommPortIdentifier)84 PortInUseException (gnu.io.PortInUseException)62 IOException (java.io.IOException)34 SerialPortEvent (gnu.io.SerialPortEvent)25 SerialPortEventListener (gnu.io.SerialPortEventListener)23 UnsupportedCommOperationException (gnu.io.UnsupportedCommOperationException)20 CommPort (gnu.io.CommPort)15 NoSuchPortException (gnu.io.NoSuchPortException)15 TooManyListenersException (java.util.TooManyListenersException)14 Enumeration (java.util.Enumeration)10 DataInputStream (java.io.DataInputStream)9 SerialPort (gnu.io.SerialPort)8 BufferedReader (java.io.BufferedReader)5 InputStreamReader (java.io.InputStreamReader)5 OutputStreamWriter (java.io.OutputStreamWriter)4 BufferedInputStream (java.io.BufferedInputStream)3 BufferedWriter (java.io.BufferedWriter)3 DataOutputStream (java.io.DataOutputStream)3 ArrayList (java.util.ArrayList)3 InputStream (java.io.InputStream)2