Java源码示例:gnu.io.NoSuchPortException

示例1
@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();
}
 
示例2
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);
            }
        }
 
示例3
/**
 * 打开串口
 * 
 * @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;
}
 
示例4
@Override
public LinkDelegate newLink(SerialLinkConfig config)
		throws NoSuchPortException, PortInUseException,
		UnsupportedCommOperationException, IOException {
	CommPortIdentifier portIdentifier = CommPortIdentifier
			.getPortIdentifier(config.getPort());
	checkState(!portIdentifier.isCurrentlyOwned(),
			"Port %s is currently in use", config.getPort());
	final SerialPort serialPort = serialPort(config, portIdentifier);

	StreamConnection connection = new StreamConnection(
			serialPort.getInputStream(), serialPort.getOutputStream(),
			config.getProto());

	ConnectionBasedLink connectionBasedLink = new ConnectionBasedLink(
			connection, config.getProto());
	Link link = config.isQos() ? new QosLink(connectionBasedLink)
			: connectionBasedLink;

	waitForArdulink(config, connectionBasedLink);
	return new LinkDelegate(link) {
		@Override
		public void close() throws IOException {
			super.close();
			serialPort.close();
		}
	};
}
 
示例5
public static synchronized CommPortIdentifier getPortIdentifier(String port) throws NoSuchPortException {
    if ((System.getProperty("os.name").toLowerCase().indexOf("linux") != -1)) {
        appendSerialPortProperty(port);
    }

    return CommPortIdentifier.getPortIdentifier(port);
}
 
示例6
@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;
    }
}
 
示例7
private void setupGenericSerialPort() throws IOException {
    String newPort = this.genericSerialSenderBean.getPortName();
    if (rawIrSender != null && (newPort == null || newPort.equals(portName)))
        return;

    if (rawIrSender != null)
        rawIrSender.close();
    rawIrSender = null;

    //genericSerialSenderBean.setVerbose(properties.getVerbose());
    close();

    try {
        rawIrSender = new IrGenericSerial(genericSerialSenderBean.getPortName(), genericSerialSenderBean.getBaud(),
                genericSerialSenderBean.getDataSize(), genericSerialSenderBean.getStopBits(), genericSerialSenderBean.getParity(),
                genericSerialSenderBean.getFlowControl(), properties.getSendingTimeout(), properties.getVerbose());
        rawIrSender.setCommand(genericSerialSenderBean.getCommand());
        rawIrSender.setRaw(genericSerialSenderBean.getRaw());
        rawIrSender.setSeparator(genericSerialSenderBean.getSeparator());
        rawIrSender.setUseSigns(genericSerialSenderBean.getUseSigns());
        rawIrSender.setLineEnding(genericSerialSenderBean.getLineEnding());
    } catch (NoSuchPortException | PortInUseException | UnsupportedCommOperationException | IOException ex) {
        // Should not happen
        guiUtils.error(ex);
    }
    portName = genericSerialSenderBean.getPortName();
    genericSerialSenderBean.setHardware(rawIrSender);
}
 
示例8
@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;
        }
    }
}
 
示例9
private void connect() throws NoSuchPortException, PortInUseException, UnsupportedCommOperationException,
        IOException, InterruptedException, ConfigurationException {

    logger.info("Connecting to RFXCOM [serialPort='{}' ].", new Object[] { serialPort });

    connector.addEventListener(eventLister);
    connector.connect(serialPort);

    logger.debug("Reset controller");
    connector.sendMessage(RFXComMessageFactory.CMD_RESET);

    // controller does not response immediately after reset,
    // so wait a while
    Thread.sleep(1000);
    // Clear received buffers
    connector.clearReceiveBuffer();

    if (setMode != null) {
        try {
            logger.debug("Set mode: {}", DatatypeConverter.printHexBinary(setMode));
        } catch (IllegalArgumentException e) {
            throw new ConfigurationException("setMode", e.getMessage());
        }

        connector.sendMessage(setMode);
    } else {
        connector.sendMessage(RFXComMessageFactory.CMD_STATUS);
    }
}
 
示例10
/**
 * {@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;
    }
}
 
示例11
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);
	}
 
示例12
/**
 * Opens the Operation System Serial Port
 * <p>
 * This method opens the port and set Serial Port parameters according to
 * the DSMR specification. Since the specification is clear about these
 * parameters there are not configurable.
 * <p>
 * If there are problem while opening the port, it is the responsibility of
 * the calling method to handle this situation (and for example close the
 * port again).
 * <p>
 * Opening an already open port is harmless. The method will return
 * immediately
 *
 * @return true if opening was successful (or port was already open), false
 *         otherwise
 */
private boolean open() {
    synchronized (portLock) {
        // Sanity check
        if (portState != PortState.CLOSED) {
            return true;
        }

        try {
            // GNU.io autodetects standard serial port names
            // Add non standard port names if not exists (fixes part of #4175)
            if (!portExists(portName)) {
                logger.warn("Port {} does not exists according to the system, we will still try to open it",
                        portName);
            }
            // Opening Operating System Serial Port
            logger.debug("Creating CommPortIdentifier");
            CommPortIdentifier portIdentifier = CommPortIdentifier.getPortIdentifier(portName);
            logger.debug("Opening CommPortIdentifier");
            CommPort commPort = portIdentifier.open("org.openhab.binding.dsmr", readTimeoutMSec);
            logger.debug("Configure serial port");
            serialPort = (SerialPort) commPort;
            serialPort.enableReceiveThreshold(1);
            serialPort.enableReceiveTimeout(readTimeoutMSec);

            // Configure Serial Port based on specified port speed
            logger.debug("Configure serial port parameters: {}", portSettings);

            if (portSettings != null) {
                serialPort.setSerialPortParams(portSettings.getBaudrate(), portSettings.getDataBits(),
                        portSettings.getStopbits(), portSettings.getParity());

                /* special settings for low speed port (checking reference here) */
                if (portSettings == DSMRPortSettings.LOW_SPEED_SETTINGS) {
                    serialPort.setDTR(false);
                    serialPort.setRTS(true);
                }
            } else {
                logger.error("Invalid port parameters, closing port:{}", portSettings);

                return false;
            }
        } catch (NoSuchPortException nspe) {
            logger.error("Could not open port: {}", portName, nspe);

            return false;
        } catch (PortInUseException piue) {
            logger.error("Port already in use: {}", portName, piue);

            return false;
        } catch (UnsupportedCommOperationException ucoe) {
            logger.error(
                    "Port does not support requested port settings " + "(invalid dsmr:portsettings parameter?): {}",
                    portName, ucoe);

            return false;
        }

        // SerialPort is ready, open the reader
        logger.info("SerialPort opened successful");
        try {
            bis = new BufferedInputStream(serialPort.getInputStream());
        } catch (IOException ioe) {
            logger.error("Failed to get inputstream for serialPort. Closing port", ioe);

            return false;
        }
        logger.info("DSMR Port opened successful");

        return true;
    }
}
 
示例13
private void connectSerial() throws Exception {

        logger.debug("Initializing serial port {}", serialPortName);

        try {

            CommPortIdentifier portIdentifier = CommPortIdentifier.getPortIdentifier(serialPortName);

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

            serialPort = (SerialPort) commPort;

            try {
                serialPort.setSerialPortParams(4800, SerialPort.DATABITS_8, SerialPort.STOPBITS_1,
                        SerialPort.PARITY_NONE);

                serialPort.enableReceiveThreshold(1);
                serialPort.disableReceiveTimeout();
            } catch (UnsupportedCommOperationException unimportant) {
                // We might have a perfectly usable PTY even if above operations are unsupported
            }
            ;

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

            outStream.flush();
            if (inStream.markSupported()) {
                inStream.reset();
            }

            logger.debug("Starting DataListener for {}", PrimareSerialConnector.this.toString());
            dataListener = new DataListener();
            dataListener.start();
            logger.debug("Starting DataListener for {}", PrimareSerialConnector.this.toString());

            sendInitMessages();

        } catch (NoSuchPortException e) {
            logger.error("No such port: {}", serialPortName);

            Enumeration portList = CommPortIdentifier.getPortIdentifiers();
            if (portList.hasMoreElements()) {
                StringBuilder sb = new StringBuilder();
                while (portList.hasMoreElements()) {
                    CommPortIdentifier portId = (CommPortIdentifier) portList.nextElement();
                    sb.append(String.format("%s ", portId.getName()));
                }
                logger.error("The following communications ports are available: {}", sb.toString().trim());
            } else {
                logger.error("There are no communications ports available");
            }
            logger.error("You may consider OpenHAB startup parameter [ -Dgnu.io.rxtx.SerialPorts={} ]", serialPortName);
            throw e;
        }
    }
 
示例14
/**
 * {@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);
    }
}