Search in sources :

Example 41 with CommPortIdentifier

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

the class UsbDriverAdapter method openPort.

@Override
public String openPort(String portName, String appName) {
    // open the port, 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 communication via SerialDriver
        try {
            // find the baud rate value, configure comm options
            // default, but also defaulted in the initial value of selectedSpeed
            int baud = validSpeedValues[0];
            for (int i = 0; i < validSpeeds.length; i++) {
                if (validSpeeds[i].equals(mBaudRate)) {
                    baud = validSpeedValues[i];
                }
            }
            activeSerialPort.setSerialPortParams(baud, SerialPort.DATABITS_8, SerialPort.STOPBITS_1, SerialPort.PARITY_NONE);
        } 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 RTS high, DTR high
        // not connected in some serial ports and adapters
        activeSerialPort.setRTS(true);
        // pin 1 in DIN8; on main connector, this is DTR
        activeSerialPort.setDTR(true);
        // disable flow control; hardware lines used for signaling, XON/XOFF might appear in data
        activeSerialPort.setFlowControlMode(0);
        // 50 mSec timeout before sending chars
        activeSerialPort.enableReceiveTimeout(50);
        // set timeout
        // activeSerialPort.enableReceiveTimeout(1000);
        log.debug("Serial timeout was observed as: " + activeSerialPort.getReceiveTimeout() + " " + activeSerialPort.isReceiveTimeoutEnabled());
        // get and save stream
        serialStream = activeSerialPort.getInputStream();
        // purge contents, if any
        purgeStream(serialStream);
        // report status
        if (log.isInfoEnabled()) {
            log.info("NCE USB " + portName + " port opened at " + activeSerialPort.getBaudRate() + " baud");
        }
        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;
    }
    // indicates OK return
    return null;
}
Also used : PortInUseException(gnu.io.PortInUseException) CommPortIdentifier(gnu.io.CommPortIdentifier) PortInUseException(gnu.io.PortInUseException)

Example 42 with CommPortIdentifier

use of gnu.io.CommPortIdentifier 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)

Example 43 with CommPortIdentifier

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

the class Stick method initialize.

/**
     * Initialize this device and open the serial port
     *
     * @throws PlugwiseInitializationException if port can not be opened
     */
@SuppressWarnings("rawtypes")
private void initialize() throws PlugwiseInitializationException {
    // Flush the deviceCache
    plugwiseDeviceCache.clear();
    // 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 PlugwiseInitializationException(e);
        }
        try {
            serialPort.addEventListener(this);
        } catch (TooManyListenersException e) {
            throw new PlugwiseInitializationException(e);
        }
        // activate the DATA_AVAILABLE notifier
        serialPort.notifyOnDataAvailable(true);
        try {
            // set port parameters
            serialPort.setSerialPortParams(115200, SerialPort.DATABITS_8, SerialPort.STOPBITS_1, SerialPort.PARITY_NONE);
        } catch (UnsupportedCommOperationException e) {
            throw new PlugwiseInitializationException(e);
        }
        try {
            // get the output stream
            outputChannel = Channels.newChannel(serialPort.getOutputStream());
        } catch (IOException e) {
            throw new PlugwiseInitializationException(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 PlugwiseInitializationException("Serial port '" + port + "' could not be found. Available ports are:\n" + sb);
    }
    initialised = true;
    // initialise the Stick
    sendMessage(new InitialiseRequestMessage());
}
Also used : TooManyListenersException(java.util.TooManyListenersException) UnsupportedCommOperationException(gnu.io.UnsupportedCommOperationException) Enumeration(java.util.Enumeration) PortInUseException(gnu.io.PortInUseException) CommPortIdentifier(gnu.io.CommPortIdentifier) InitialiseRequestMessage(org.openhab.binding.plugwise.protocol.InitialiseRequestMessage) IOException(java.io.IOException)

Example 44 with CommPortIdentifier

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

the class PowerMaxSerialConnector method open.

/**
     * {@inheritDoc}
     **/
@Override
public void open() {
    logger.debug("open(): Opening Serial Connection");
    try {
        CommPortIdentifier portIdentifier = CommPortIdentifier.getPortIdentifier(serialPortName);
        CommPort commPort = portIdentifier.open(this.getClass().getName(), 2000);
        serialPort = (SerialPort) commPort;
        serialPort.setSerialPortParams(baudRate, SerialPort.DATABITS_8, SerialPort.STOPBITS_1, SerialPort.PARITY_NONE);
        serialPort.enableReceiveThreshold(1);
        serialPort.disableReceiveTimeout();
        setInput(serialPort.getInputStream());
        setOutput(serialPort.getOutputStream());
        getOutput().flush();
        if (getInput().markSupported()) {
            getInput().reset();
        }
        setReaderThread(new SerialReaderThread(getInput(), this));
        getReaderThread().start();
        setConnected(true);
    } catch (NoSuchPortException noSuchPortException) {
        logger.debug("open(): No Such Port Exception: {}", noSuchPortException.getMessage());
        setConnected(false);
    } catch (PortInUseException portInUseException) {
        logger.debug("open(): Port in Use Exception: {}", portInUseException.getMessage());
        setConnected(false);
    } catch (UnsupportedCommOperationException unsupportedCommOperationException) {
        logger.debug("open(): Unsupported Comm Operation Exception: {}", unsupportedCommOperationException.getMessage());
        setConnected(false);
    } catch (UnsupportedEncodingException unsupportedEncodingException) {
        logger.debug("open(): Unsupported Encoding Exception: {}", unsupportedEncodingException.getMessage());
        setConnected(false);
    } catch (IOException ioException) {
        logger.debug("open(): IO Exception: ", ioException.getMessage());
        setConnected(false);
    }
}
Also used : UnsupportedCommOperationException(gnu.io.UnsupportedCommOperationException) NoSuchPortException(gnu.io.NoSuchPortException) PortInUseException(gnu.io.PortInUseException) CommPortIdentifier(gnu.io.CommPortIdentifier) CommPort(gnu.io.CommPort) UnsupportedEncodingException(java.io.UnsupportedEncodingException) IOException(java.io.IOException)

Example 45 with CommPortIdentifier

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

the class SwegonVentilationSerialConnector method connect.

@Override
public void connect() throws SwegonVentilationException {
    try {
        CommPortIdentifier portIdentifier = CommPortIdentifier.getPortIdentifier(portName);
        CommPort commPort = portIdentifier.open(this.getClass().getName(), 2000);
        serialPort = (SerialPort) commPort;
        serialPort.setSerialPortParams(BAUDRATE, SerialPort.DATABITS_8, SerialPort.STOPBITS_1, SerialPort.PARITY_NONE);
        in = serialPort.getInputStream();
        logger.debug("Swegon ventilation Serial Port message listener started");
    } catch (Exception e) {
        throw new SwegonVentilationException(e);
    }
}
Also used : SwegonVentilationException(org.openhab.binding.swegonventilation.internal.SwegonVentilationException) CommPortIdentifier(gnu.io.CommPortIdentifier) CommPort(gnu.io.CommPort) SwegonVentilationException(org.openhab.binding.swegonventilation.internal.SwegonVentilationException) 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