gnu.io.CommPortIdentifier Java Examples

The following examples show how to use gnu.io.CommPortIdentifier. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: SerialSketchUploader.java    From arduino-remote-uploader with GNU General Public License v2.0 8 votes vote down vote up
public void openSerial(String serialPortName, int speed) throws PortInUseException, IOException, UnsupportedCommOperationException, TooManyListenersException {
	
	CommPortIdentifier commPortIdentifier = findPort(serialPortName);
	
	// initalize serial port
	serialPort = (SerialPort) commPortIdentifier.open("Arduino", 2000);
	inputStream = serialPort.getInputStream();
	serialPort.addEventListener(this);

	// activate the DATA_AVAILABLE notifier
	serialPort.notifyOnDataAvailable(true);

	serialPort.setSerialPortParams(speed, SerialPort.DATABITS_8, 
			SerialPort.STOPBITS_1, SerialPort.PARITY_NONE);
	serialPort.setFlowControlMode(SerialPort.FLOWCONTROL_NONE);
}
 
Example #2
Source File: RFXComSerialConnector.java    From openhab1-addons with Eclipse Public License 2.0 6 votes vote down vote up
@Override
public void connect(String device)
        throws NoSuchPortException, PortInUseException, UnsupportedCommOperationException, IOException {
    CommPortIdentifier portIdentifier = CommPortIdentifier.getPortIdentifier(device);

    CommPort commPort = portIdentifier.open(this.getClass().getName(), 2000);

    serialPort = (SerialPort) commPort;
    serialPort.setSerialPortParams(38400, SerialPort.DATABITS_8, SerialPort.STOPBITS_1, SerialPort.PARITY_NONE);
    serialPort.enableReceiveThreshold(1);
    serialPort.disableReceiveTimeout();

    in = serialPort.getInputStream();
    out = serialPort.getOutputStream();

    out.flush();
    if (in.markSupported()) {
        in.reset();
    }

    readerThread = new SerialReader(in);
    readerThread.start();
}
 
Example #3
Source File: SerialPortRxTx.java    From xbee-java with Mozilla Public License 2.0 6 votes vote down vote up
/**
 * Retrieves the list of available serial ports in the system.
 * 
 * @return List of available serial ports.
 * 
 * @see #listSerialPortsInfo()
 */
public static String[] listSerialPorts() {
	ArrayList<String> serialPorts = new ArrayList<String>();
	
	@SuppressWarnings("unchecked")
	Enumeration<CommPortIdentifier> comPorts = CommPortIdentifier.getPortIdentifiers();
	if (comPorts == null)
		return serialPorts.toArray(new String[serialPorts.size()]);
	
	while (comPorts.hasMoreElements()) {
		CommPortIdentifier identifier = (CommPortIdentifier)comPorts.nextElement();
		if (identifier == null)
			continue;
		String strName = identifier.getName();
		serialPorts.add(strName);
	}
	return serialPorts.toArray(new String[serialPorts.size()]);
}
 
Example #4
Source File: SerialSketchUploader.java    From arduino-remote-uploader with GNU General Public License v2.0 6 votes vote down vote up
public CommPortIdentifier findPort(String port) {
    // parse ports and if the default port is found, initialized the reader
    Enumeration portList = CommPortIdentifier.getPortIdentifiers();
    
    while (portList.hasMoreElements()) {
        
        CommPortIdentifier portId = (CommPortIdentifier) portList.nextElement();
        
        if (portId.getPortType() == CommPortIdentifier.PORT_SERIAL) {

            //System.out.println("Found port: " + portId.getName());
            
            if (portId.getName().equals(port)) {
                //System.out.println("Using Port: " + portId.getName());
                return portId;
            }
        }
    }
    
    throw new RuntimeException("Port not found " + port);
}
 
Example #5
Source File: TwoWaySerialComm2.java    From ATCommandTester with GNU General Public License v2.0 6 votes vote down vote up
public String listPorts() {
	List<String> port_name = new ArrayList<String>();
	String tmp = "";

	// int i = 0;
	@SuppressWarnings("unchecked")
	Enumeration<CommPortIdentifier> portEnum = CommPortIdentifier
			.getPortIdentifiers();

	// Enumeration portList = CommPortIdentifier.getPortIdentifiers();
	while (portEnum.hasMoreElements()) {
		CommPortIdentifier portIdentifier = (CommPortIdentifier) portEnum
				.nextElement();
		if (getPortTypeName(portIdentifier.getPortType()) == "Serial") {
			port_name.add(portIdentifier.getName());
			String tmp2 = portIdentifier.getName() + "#";

			tmp = tmp + tmp2;
		}
		System.out.println(portIdentifier.getName() + " - "
				+ getPortTypeName(portIdentifier.getPortType()));
	}
	// i = port_name.size();

	return tmp;
}
 
Example #6
Source File: SerialPortRxTx.java    From xbee-java with Mozilla Public License 2.0 6 votes vote down vote up
/**
 * Retrieves the list of available serial ports with their information.
 * 
 * @return List of available serial ports with their information.
 * 
 * @see #listSerialPorts()
 * @see SerialPortInfo
 */
public static ArrayList<SerialPortInfo> listSerialPortsInfo() {
	ArrayList<SerialPortInfo> ports = new ArrayList<SerialPortInfo>();
	
	@SuppressWarnings("unchecked")
	Enumeration<CommPortIdentifier> comPorts = CommPortIdentifier.getPortIdentifiers();
	if (comPorts == null)
		return ports;
	
	while (comPorts.hasMoreElements()) {
		CommPortIdentifier identifier = (CommPortIdentifier)comPorts.nextElement();
		if (identifier == null)
			continue;
		ports.add(new SerialPortInfo(identifier.getName()));
	}
	return ports;
}
 
Example #7
Source File: SerialConnection.java    From Ardulink-1 with Apache License 2.0 6 votes vote down vote up
/**
 * This method is used to get a list of all the available Serial ports
 * (note: only Serial ports are considered). Any one of the elements
 * contained in the returned {@link List} can be used as a parameter in
 * {@link #connect(String)} or {@link #connect(String, int)} to open a
 * Serial connection.
 * 
 * @return A {@link List} containing {@link String}s showing all available
 *         Serial ports.
 */
public List<String> getPortList() {
	List<String> ports = new ArrayList<String>();
	Enumeration<?> portList = CommPortIdentifier.getPortIdentifiers();
	while (portList.hasMoreElements()) {
		CommPortIdentifier portId = (CommPortIdentifier) portList.nextElement();
		if (portId.getPortType() == CommPortIdentifier.PORT_SERIAL) {
			ports.add(portId.getName());
		}
	}
	writeLog("found the following ports:");
	for (String port : ports) {
		writeLog("   " + port);
	}

	return ports;
}
 
Example #8
Source File: SwegonVentilationSerialConnector.java    From openhab1-addons with Eclipse Public License 2.0 6 votes vote down vote up
@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);
    }
}
 
Example #9
Source File: SerialPortUtil.java    From openhab-core with Eclipse Public License 2.0 6 votes vote down vote up
/**
 * Scans for available port identifiers by calling RXTX without using the ({@value #GNU_IO_RXTX_SERIAL_PORTS}
 * property. Finds port identifiers based on operating system and distribution.
 *
 * @return the scanned port identifiers
 */
@SuppressWarnings("unchecked")
public static synchronized Stream<CommPortIdentifier> getPortIdentifiersUsingScan() {
    Enumeration<CommPortIdentifier> identifiers;
    if (isSerialPortsKeySet()) {
        // Save the existing serial ports property
        String value = System.getProperty(GNU_IO_RXTX_SERIAL_PORTS);
        // Clear the property so library scans the ports
        System.clearProperty(GNU_IO_RXTX_SERIAL_PORTS);
        identifiers = CommPortIdentifier.getPortIdentifiers();
        // Restore the existing serial ports property
        System.setProperty(GNU_IO_RXTX_SERIAL_PORTS, value);
    } else {
        identifiers = CommPortIdentifier.getPortIdentifiers();
    }

    // Save the Enumeration to a new list so the result is thread safe
    return Collections.list(identifiers).stream();
}
 
Example #10
Source File: SerialFatekConnectionFactory.java    From openhab1-addons with Eclipse Public License 2.0 6 votes vote down vote up
private CommPortIdentifier findComPort() throws IOException {

            // list all available serial ports
            final List<String> availableNames = new ArrayList<>();
            final Enumeration portIdentifiers = CommPortIdentifier.getPortIdentifiers();
            while (portIdentifiers.hasMoreElements()) {
                final CommPortIdentifier id = (CommPortIdentifier) portIdentifiers.nextElement();
                if (id.getPortType() == CommPortIdentifier.PORT_SERIAL) {
                    availableNames.add(id.getName());
                }
            }

            final String portNameCandidate = getFullName();
            // find first matching port name, on some system usb serial port can have suffix depends on which usb port we use
            final Optional<String> portName = availableNames.stream().filter(name -> name.startsWith(portNameCandidate)).findFirst();

            try {
                return CommPortIdentifier.getPortIdentifier(portName.orElseThrow(NoSuchPortException::new));
            } catch (NoSuchPortException e) {
                throw new IOException("Serial port '" + portNameCandidate + "' could not be found. Available ports are:\n" + availableNames);
            }
        }
 
Example #11
Source File: KNXConnection.java    From openhab1-addons with Eclipse Public License 2.0 6 votes vote down vote up
private static KNXNetworkLink connectBySerial(String serialPort) throws KNXException {

        try {
            RXTXVersion.getVersion();
            return new KNXNetworkLinkFT12(serialPort, new TPSettings(true));
        } catch (NoClassDefFoundError e) {
            throw new KNXException(
                    "The serial FT1.2 KNX connection requires the RXTX libraries to be available, but they could not be found!");
        } catch (KNXException knxe) {
            if (knxe.getMessage().startsWith("can not open serial port")) {
                StringBuilder sb = new StringBuilder("Available ports are:\n");
                Enumeration<?> portList = CommPortIdentifier.getPortIdentifiers();
                while (portList.hasMoreElements()) {
                    CommPortIdentifier id = (CommPortIdentifier) portList.nextElement();
                    if (id.getPortType() == CommPortIdentifier.PORT_SERIAL) {
                        sb.append(id.getName() + "\n");
                    }
                }
                sb.deleteCharAt(sb.length() - 1);
                knxe = new KNXException("Serial port '" + serialPort + "' could not be opened. " + sb.toString());
            }
            throw knxe;
        }
    }
 
Example #12
Source File: Connection.java    From elexis-3-core with Eclipse Public License 1.0 6 votes vote down vote up
@SuppressWarnings("unchecked")
public static String[] getComPorts(){
	ArrayList<String> p = new ArrayList<String>();
	try {
		Enumeration<CommPortIdentifier> ports = CommPortIdentifier.getPortIdentifiers();
		
		while (ports.hasMoreElements()) {
			CommPortIdentifier port = ports.nextElement();
			p.add(port.getName());
		}
	} catch (LinkageError error) {
		SWTHelper.showError("COM Port Initialization Error", error.getMessage()+"\nPlease see log file and/or https://wiki.elexis.info/SerialConfiguration.");
		log.error("COM Port Initialization", error);
	}
	return p.toArray(new String[0]);
}
 
Example #13
Source File: SerialFatekConnectionFactory.java    From openhab1-addons with Eclipse Public License 2.0 5 votes vote down vote up
Connection(FatekConfig fatekConfig) throws IOException, PortInUseException, UnsupportedCommOperationException {
    super(fatekConfig);

    final CommPortIdentifier commPortIdentifier = findComPort();

    serialPort = commPortIdentifier.open("openHAB-FatekPLC", 2000);
    serialPort.setSerialPortParams(getBaud(), getDataBits(), getStopBits(), getParity());
    serialPort.enableReceiveTimeout(getTimeout());

    logger.info("New connection to: {} opened", serialPort.getName());
}
 
Example #14
Source File: AbstractConnection.java    From elexis-3-core with Eclipse Public License 1.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
public static String[] getComPorts(){
	Enumeration<CommPortIdentifier> ports = CommPortIdentifier.getPortIdentifiers();
	ArrayList<String> p = new ArrayList<String>();
	while (ports.hasMoreElements()) {
		CommPortIdentifier port = ports.nextElement();
		p.add(port.getName());
	}
	return p.toArray(new String[0]);
}
 
Example #15
Source File: SerialPortConnector.java    From openhab1-addons with Eclipse Public License 2.0 5 votes vote down vote up
@Override
protected void connectPort() throws Exception {
    CommPortIdentifier portIdentifier = CommPortIdentifier.getPortIdentifier(device);

    CommPort commPort = portIdentifier.open(this.getClass().getName(), 2000);

    serialPort = (SerialPort) commPort;
    setSerialPortParameters(baudrate);

    in = serialPort.getInputStream();
    out = new DataOutputStream(serialPort.getOutputStream());
}
 
Example #16
Source File: EpsonProjectorSerialConnector.java    From openhab1-addons with Eclipse Public License 2.0 5 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
public void connect() throws EpsonProjectorException {

    try {
        logger.debug("Open connection to serial port '{}'", serialPortName);
        CommPortIdentifier portIdentifier = CommPortIdentifier.getPortIdentifier(serialPortName);

        CommPort commPort = portIdentifier.open(this.getClass().getName(), 2000);

        serialPort = (SerialPort) commPort;
        serialPort.setSerialPortParams(9600, SerialPort.DATABITS_8, SerialPort.STOPBITS_1, SerialPort.PARITY_NONE);
        serialPort.enableReceiveThreshold(1);
        serialPort.disableReceiveTimeout();

        in = serialPort.getInputStream();
        out = serialPort.getOutputStream();

        out.flush();
        if (in.markSupported()) {
            in.reset();
        }

        // RXTX serial port library causes high CPU load
        // Start event listener, which will just sleep and slow down event loop
        serialPort.addEventListener(this);
        serialPort.notifyOnDataAvailable(true);
    } catch (Exception e) {
        throw new EpsonProjectorException(e);
    }

}
 
Example #17
Source File: EnoceanBinding.java    From openhab1-addons with Eclipse Public License 2.0 5 votes vote down vote up
@Override
public void updated(Dictionary<String, ?> config) throws ConfigurationException {
    if (config == null) {
        return;
    }
    serialPort = (String) config.get(CONFIG_KEY_SERIAL_PORT);

    if (connector != null) {
        connector.disconnect();
    }
    try {
        connect();
    } catch (RuntimeException e) {
        if (e.getCause() instanceof NoSuchPortException) {
            StringBuilder sb = new StringBuilder("Available ports are:\n");
            Enumeration<?> portList = CommPortIdentifier.getPortIdentifiers();
            while (portList.hasMoreElements()) {
                CommPortIdentifier id = (CommPortIdentifier) portList.nextElement();
                if (id.getPortType() == CommPortIdentifier.PORT_SERIAL) {
                    sb.append(id.getName() + "\n");
                }
            }
            sb.deleteCharAt(sb.length() - 1);
            throw new ConfigurationException(CONFIG_KEY_SERIAL_PORT,
                    "Serial port '" + serialPort + "' could not be opened. " + sb.toString());
        } else {
            throw e;
        }
    }
}
 
Example #18
Source File: RxTxPortProvider.java    From smarthome with Eclipse Public License 2.0 5 votes vote down vote up
@Override
public Stream<SerialPortIdentifier> getSerialPortIdentifiers() {
    @SuppressWarnings("unchecked")
    final Enumeration<CommPortIdentifier> ids = CommPortIdentifier.getPortIdentifiers();
    return StreamSupport.stream(new SplitIteratorForEnumeration<>(ids), false)
            .filter(id -> id.getPortType() == CommPortIdentifier.PORT_SERIAL)
            .map(sid -> new SerialPortIdentifierImpl(sid));
}
 
Example #19
Source File: RxTxPortProvider.java    From smarthome with Eclipse Public License 2.0 5 votes vote down vote up
@Override
public @Nullable SerialPortIdentifier getPortIdentifier(URI port) {
    CommPortIdentifier ident = null;
    if ((System.getProperty("os.name").toLowerCase().indexOf("linux") != -1)) {
        SerialPortUtil.appendSerialPortProperty(port.getPath());
    }
    try {
        ident = CommPortIdentifier.getPortIdentifier(port.getPath());
    } catch (gnu.io.NoSuchPortException e) {
        logger.debug("No SerialPortIdentifier found for: {}", port.getPath());
        return null;
    }
    return new SerialPortIdentifierImpl(ident);

}
 
Example #20
Source File: SerialConnector.java    From openhab1-addons with Eclipse Public License 2.0 5 votes vote down vote up
/**
 * {@inheritDoc}
 **/
public void open() {

    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();

        serialOutput = new OutputStreamWriter(serialPort.getOutputStream(), "US-ASCII");
        serialInput = new BufferedReader(new InputStreamReader(serialPort.getInputStream()));

        setSerialEventHandler(this);

        connected = true;

    } catch (NoSuchPortException noSuchPortException) {
        logger.error("open(): No Such Port Exception: ", noSuchPortException);
        connected = false;
    } catch (PortInUseException portInUseException) {
        logger.error("open(): Port in Use Exception: ", portInUseException);
        connected = false;
    } catch (UnsupportedCommOperationException unsupportedCommOperationException) {
        logger.error("open(): Unsupported Comm Operation Exception: ", unsupportedCommOperationException);
        connected = false;
    } catch (UnsupportedEncodingException unsupportedEncodingException) {
        logger.error("open(): Unsupported Encoding Exception: ", unsupportedEncodingException);
        connected = false;
    } catch (IOException ioException) {
        logger.error("open(): IO Exception: ", ioException);
        connected = false;
    }
}
 
Example #21
Source File: EiscpSerial.java    From openhab1-addons with Eclipse Public License 2.0 5 votes vote down vote up
/**
 * {@inheritDoc}
 */
public boolean connect(String serialPortName) {

    try {
        logger.debug("Open connection to serial port '{}'", serialPortName);
        CommPortIdentifier portIdentifier = CommPortIdentifier.getPortIdentifier(serialPortName);

        CommPort commPort = portIdentifier.open(this.getClass().getName(), 2000);

        serialPort = (SerialPort) commPort;
        serialPort.setSerialPortParams(9600, SerialPort.DATABITS_8, SerialPort.STOPBITS_1, SerialPort.PARITY_NONE);
        serialPort.enableReceiveThreshold(1);
        serialPort.disableReceiveTimeout();

        in = serialPort.getInputStream();
        out = serialPort.getOutputStream();

        out.flush();
        if (in.markSupported()) {
            in.reset();
        }

        // RXTX serial port library causes high CPU load
        // Start event listener, which will just sleep and slow down event
        // loop
        serialPort.addEventListener(this);
        serialPort.notifyOnDataAvailable(true);
        return true;
    } catch (Exception e) {
        logger.error("serial port connect error", e);
        e.printStackTrace();
        return false;
    }

}
 
Example #22
Source File: SerialRXTXComm.java    From meshnet with GNU General Public License v3.0 5 votes vote down vote up
public SerialRXTXComm(CommPortIdentifier portIdentifier, Layer3Base layer3) throws NoSuchPortException, PortInUseException, UnsupportedCommOperationException, IOException, TooManyListenersException{

		if (portIdentifier.isCurrentlyOwned()) {
			throw new IOException("Port is currently in use");
		} else {
			CommPort commPort = portIdentifier.open(this.getClass().getName(),
					TIME_OUT);

			if (commPort instanceof SerialPort) {
				SerialPort serialPort = (SerialPort) commPort;
				serialPort.setSerialPortParams(9600, SerialPort.DATABITS_8,
						SerialPort.STOPBITS_1, SerialPort.PARITY_NONE);

				inStream = serialPort.getInputStream();
				outStream = serialPort.getOutputStream();

				new SerialReceiver().start();

				/*serialPort.addEventListener(this);
				serialPort.notifyOnDataAvailable(true);*/

			} else {
				throw new IOException("This is not a serial port!.");
			}
		}
		
		this.layer2 = new Layer2Serial(this, layer3);
	}
 
Example #23
Source File: RxtxChannel.java    From netty-4.1.22 with Apache License 2.0 5 votes vote down vote up
@Override
protected void doConnect(SocketAddress remoteAddress, SocketAddress localAddress) throws Exception {
    RxtxDeviceAddress remote = (RxtxDeviceAddress) remoteAddress;
    final CommPortIdentifier cpi = CommPortIdentifier.getPortIdentifier(remote.value());
    final CommPort commPort = cpi.open(getClass().getName(), 1000);
    commPort.enableReceiveTimeout(config().getOption(READ_TIMEOUT));
    deviceAddress = remote;

    serialPort = (SerialPort) commPort;
}
 
Example #24
Source File: SerialPortManager.java    From SerialPortDemo with Apache License 2.0 5 votes vote down vote up
/**
 * 查找所有可用端口
 * 
 * @return 可用端口名称列表
 */
public static final ArrayList<String> findPorts() {
	// 获得当前所有可用串口
	Enumeration<CommPortIdentifier> portList = CommPortIdentifier.getPortIdentifiers();
	ArrayList<String> portNameList = new ArrayList<String>();
	// 将可用串口名添加到List并返回该List
	while (portList.hasMoreElements()) {
		String portName = portList.nextElement().getName();
		portNameList.add(portName);
	}
	return portNameList;
}
 
Example #25
Source File: SerialPortManager.java    From SerialPortDemo with Apache License 2.0 5 votes vote down vote up
/**
 * 打开串口
 * 
 * @param portName
 *            端口名称
 * @param baudrate
 *            波特率
 * @return 串口对象
 * @throws PortInUseException
 *             串口已被占用
 */
public static final SerialPort openPort(String portName, int baudrate) throws PortInUseException {
	try {
		// 通过端口名识别端口
		CommPortIdentifier portIdentifier = CommPortIdentifier.getPortIdentifier(portName);
		// 打开端口,并给端口名字和一个timeout(打开操作的超时时间)
		CommPort commPort = portIdentifier.open(portName, 2000);
		// 判断是不是串口
		if (commPort instanceof SerialPort) {
			SerialPort serialPort = (SerialPort) commPort;
			try {
				// 设置一下串口的波特率等参数
				// 数据位:8
				// 停止位:1
				// 校验位:None
				serialPort.setSerialPortParams(baudrate, SerialPort.DATABITS_8, SerialPort.STOPBITS_1,
						SerialPort.PARITY_NONE);
			} catch (UnsupportedCommOperationException e) {
				e.printStackTrace();
			}
			return serialPort;
		}
	} catch (NoSuchPortException e1) {
		e1.printStackTrace();
	}
	return null;
}
 
Example #26
Source File: ObdAdapterClient.java    From java-obd-adapter with Apache License 2.0 5 votes vote down vote up
private void prepareSerialPort() {
//		String wantedPortName = "/dev/pts/34";
		String wantedPortName = "/dev/ttyUSB0";
		System.setProperty("gnu.io.rxtx.SerialPorts", wantedPortName);
		Enumeration portIdentifiers = CommPortIdentifier.getPortIdentifiers();

		CommPortIdentifier portId = null;

		while (portIdentifiers.hasMoreElements()) {
			CommPortIdentifier pid = (CommPortIdentifier) portIdentifiers.nextElement();
			if (pid.getPortType() == CommPortIdentifier.PORT_SERIAL &&
					pid.getName().equals(wantedPortName)) {
				portId = pid;
				break;
			}
		}

		try {
			// open serial port, and use class name for the appName.
			SerialPort serialPort = (SerialPort) portId.open(ObdAdapterClient.class.getName(), TIME_OUT);

			// set port parameters
			serialPort.setSerialPortParams(DATA_RATE,
					SerialPort.DATABITS_8,
					SerialPort.STOPBITS_1,
					SerialPort.PARITY_NONE);

			// open the streams
			is = serialPort.getInputStream();
			os = serialPort.getOutputStream();

			// add event listeners
			serialPort.addEventListener(this);
			serialPort.notifyOnDataAvailable(false);
		} catch (Exception e) {
			log.error("cannot connect to serial port", e);
		}
	}
 
Example #27
Source File: RxtxChannel.java    From netty4.0.27Learn with Apache License 2.0 5 votes vote down vote up
@Override
protected void doConnect(SocketAddress remoteAddress, SocketAddress localAddress) throws Exception {
    RxtxDeviceAddress remote = (RxtxDeviceAddress) remoteAddress;
    final CommPortIdentifier cpi = CommPortIdentifier.getPortIdentifier(remote.value());
    final CommPort commPort = cpi.open(getClass().getName(), 1000);
    commPort.enableReceiveTimeout(config().getOption(READ_TIMEOUT));
    deviceAddress = remote;

    serialPort = (SerialPort) commPort;
}
 
Example #28
Source File: RxTxPortProvider.java    From openhab-core with Eclipse Public License 2.0 5 votes vote down vote up
@Override
public Stream<SerialPortIdentifier> getSerialPortIdentifiers() {
    Stream<CommPortIdentifier> scanIds = SerialPortUtil.getPortIdentifiersUsingScan();
    Stream<CommPortIdentifier> propIds = SerialPortUtil.getPortIdentifiersUsingProperty();

    return Stream.concat(scanIds, propIds).filter(distinctByKey(CommPortIdentifier::getName))
            .filter(id -> id.getPortType() == CommPortIdentifier.PORT_SERIAL)
            .map(sid -> new SerialPortIdentifierImpl(sid));
}
 
Example #29
Source File: SerialPortFactoryRXTX.java    From jlibmodbus with Apache License 2.0 5 votes vote down vote up
@Override
public List<String> getPortIdentifiersImpl() {
    Enumeration ports = gnu.io.CommPortIdentifier.getPortIdentifiers();
    List<String> list = new ArrayList<String>();
    while (ports.hasMoreElements()) {
        CommPortIdentifier id = (CommPortIdentifier) ports.nextElement();
        if (id.getPortType() == CommPortIdentifier.PORT_RS485 ||
                id.getPortType() == CommPortIdentifier.PORT_SERIAL) {
            list.add(id.getName());
        }
    }
    return list;
}
 
Example #30
Source File: RxTxPortProvider.java    From openhab-core with Eclipse Public License 2.0 5 votes vote down vote up
@Override
public @Nullable SerialPortIdentifier getPortIdentifier(URI port) {
    try {
        CommPortIdentifier ident = SerialPortUtil.getPortIdentifier(port.getPath());
        return new SerialPortIdentifierImpl(ident);
    } catch (NoSuchPortException e) {
        logger.debug("No SerialPortIdentifier found for: {}", port.getPath());
        return null;
    }
}