Java 类gnu.io.NoSuchPortException 实例源码

项目:spring-serial-port-connector    文件:AbstractSpringSerialPortConnector.java   
@PostConstruct
public void connect() throws TooManyListenersException, NoSuchPortException {
    log.info("Connection PostConstruct callback: connecting ...");

    serial = new NRSerialPort(serialPortProperties.getPortName(), serialPortProperties.getBaudRate());
    serial.connect();

    if (serial.isConnected()) {
        log.info("Connection opened!");
    } else {
        throw new RuntimeException("Is not possible to open connection in " + serialPortProperties.getPortName() + " port");
    }
    serial.addEventListener(this);
    serial.notifyOnDataAvailable(true);
    input = new BufferedReader(new InputStreamReader(serial.getInputStream()));
}
项目:FlashLib    文件:RXTXCommInterface.java   
@Override
public void open() {
    try{
        CommPortIdentifier portIdentifier = CommPortIdentifier.getPortIdentifier(portName);
        if (portIdentifier.isCurrentlyOwned())
            System.out.println("Error: Port is currently in use");
        else {
            CommPort port = portIdentifier.open(this.getClass().getName(), getTimeout());//for now class name

            if (port instanceof SerialPort){
                serial = (SerialPort) port;
                serial.setSerialPortParams(baudrate, SerialPort.DATABITS_8 
                        , SerialPort.STOPBITS_1, SerialPort.PARITY_NONE);

                serial.enableReceiveTimeout(timeout);

                this.in = serial.getInputStream();
                this.out = serial.getOutputStream();
                isOpened = true;
            }
            else
                System.out.println("Error: Only serial ports are handled");
        }   
    }
    catch (PortInUseException | UnsupportedCommOperationException | NoSuchPortException | IOException e) {
        if(serial != null)
            serial.close();
        serial = null;
        e.printStackTrace();
    }
}
项目:4mila-1.0    文件:RXTXUtility.java   
public static FMilaSerialPort getPort(int speed, String port) throws IOException {
  SerialPort serialPort;

  try {

    CommPortIdentifier comm = CommPortIdentifier.getPortIdentifier(port);
    if (comm.isCurrentlyOwned()) {
      throw new IOException("StationInUseError");
    }
    serialPort = comm.open("4mila", 2000);

    serialPort.setSerialPortParams(speed, SerialPort.DATABITS_8, SerialPort.STOPBITS_1, SerialPort.PARITY_NONE);
    serialPort.setFlowControlMode(SerialPort.FLOWCONTROL_NONE);
    serialPort.disableReceiveTimeout();
    serialPort.disableReceiveFraming();
    serialPort.disableReceiveThreshold();
    serialPort.notifyOnDataAvailable(true);
    serialPort.notifyOnOutputEmpty(true);
  }
  catch (PortInUseException | UnsupportedCommOperationException | NoSuchPortException e) {
    throw new IOException(e.getMessage(), e);
  }

  return new RXTXSerialPort(serialPort);
}
项目:Ardulink-2    文件:SerialLinkFactory.java   
@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());
    @SuppressWarnings("resource")
    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();
        }
    };
}
项目:modbus-mini    文件:RtuTransportRxtx.java   
@Override
synchronized protected void openPort() throws NoSuchPortException, PortInUseException, UnsupportedCommOperationException {
    if (port != null)
        return;
    log.info("Opening port: " + portName);
    CommPortIdentifier ident = CommPortIdentifier.getPortIdentifier(portName);
    port = ident.open("ModbusRtuClient on " + portName, 2000);
    port.setOutputBufferSize(buffer.length);
    port.setInputBufferSize(buffer.length);
    try {
        port.setSerialPortParams(baudRate, dataBits, stopBits, parity);             
        port.enableReceiveTimeout(timeout);
        port.setFlowControlMode(SerialPort.FLOWCONTROL_NONE);
    } catch (UnsupportedCommOperationException e) {
        close();
        throw e;
    }
    log.info("Port opened: " + port.getName());
}
项目:openhab-hdl    文件:RFXComSerialConnector.java   
@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();
}
项目:openhab-hdl    文件:SerialConnector.java   
/**
 * {@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;
    }
}
项目:contexttoolkit    文件:SerialConnection.java   
private CommPortIdentifier getSerialPort() {

    if (port != null) {
        try {
            return CommPortIdentifier.getPortIdentifier(port);
        } catch (NoSuchPortException e) {
            e.printStackTrace();
        }
        return null;
    }

    Enumeration<?> portEnum = CommPortIdentifier.getPortIdentifiers();
    while (portEnum.hasMoreElements()) {
        CommPortIdentifier currPortId = (CommPortIdentifier) portEnum.nextElement();
        for (String portName : PORT_NAMES) {
            if (currPortId.getName().equals(portName)) {
                return currPortId;
            }
        }
    }
    return null;
}
项目:openhab1-addons    文件:RFXComSerialConnector.java   
@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();
}
项目:openhab1-addons    文件:SerialConnector.java   
/**
 * {@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;
    }
}
项目:meshnet    文件:SerialRXTXComm.java   
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);
    }
项目:Dirigino    文件:SerialInterface.java   
public void connect(String portName) throws NoSuchPortException {
    CommPortIdentifier portId = CommPortIdentifier.getPortIdentifier(portName);

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

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

        // open the streams
        input = new BufferedReader(new InputStreamReader(serialPort.getInputStream()));
        output = serialPort.getOutputStream();

        // add event listeners
        serialPort.addEventListener(this);
        serialPort.notifyOnDataAvailable(true);
    } catch (Exception e) {
        System.err.println(e.toString());
    }
}
项目:jzwave    文件:SerialTransport.java   
public SerialTransport(String serialPortName) throws NoSuchPortException, PortInUseException, UnsupportedCommOperationException
{
    CommPortIdentifier usablePort = CommPortIdentifier.getPortIdentifier(serialPortName);
    commPort = (SerialPort)usablePort.open("SerialTransport", 0);
    commPort.setSerialPortParams(115200, SerialPort.DATABITS_8, SerialPort.STOPBITS_1, SerialPort.PARITY_NONE);
    commPort.setFlowControlMode(SerialPort.FLOWCONTROL_NONE);
    commPort.setDTR(true);
    commPort.setRTS(true);
    commPort.setEndOfInputChar((byte)0x0D);
}
项目:SerialPortDemo    文件:SerialPortManager.java   
/**
 * 打开串口
 * 
 * @param portName
 *            端口名称
 * @param baudrate
 *            波特率
 * @return 串口对象
 * @throws SerialPortParameterFailure
 *             设置串口参数失败
 * @throws NotASerialPort
 *             端口指向设备不是串口类型
 * @throws NoSuchPort
 *             没有该端口对应的串口设备
 * @throws PortInUse
 *             端口已被占用
 */
public static final SerialPort openPort(String portName, int baudrate)
        throws SerialPortParameterFailure, NotASerialPort, NoSuchPort,
        PortInUse {
    try {
        // 通过端口名识别端口
        CommPortIdentifier portIdentifier = CommPortIdentifier
                .getPortIdentifier(portName);
        // 打开端口,并给端口名字和一个timeout(打开操作的超时时间)
        CommPort commPort = portIdentifier.open(portName, 2000);
        // 判断是不是串口
        if (commPort instanceof SerialPort) {
            SerialPort serialPort = (SerialPort) commPort;
            try {
                // 设置一下串口的波特率等参数
                serialPort.setSerialPortParams(baudrate,
                        SerialPort.DATABITS_8, SerialPort.STOPBITS_1,
                        SerialPort.PARITY_NONE);
            } catch (UnsupportedCommOperationException e) {
                throw new SerialPortParameterFailure();
            }
            return serialPort;
        } else {
            // 不是串口
            throw new NotASerialPort();
        }
    } catch (NoSuchPortException e1) {
        throw new NoSuchPort();
    } catch (PortInUseException e2) {
        throw new PortInUse();
    }
}
项目:blackbird    文件:RXTXSerialPort.java   
public void connect(String port, int baudRate, int timeout) throws IOException {
    scan();
    try {
        connect(CommPortIdentifier.getPortIdentifier(port), baudRate, timeout);
    } catch (NoSuchPortException e) {
        throw new IOException("No such port", e);
    }
}
项目:ihmc-ethercat-master    文件:SerialPortRTSPulseGenerator.java   
public SerialPortRTSPulseGenerator(String port)
{
   if ((System.getProperty("os.name").toLowerCase().indexOf("linux") != -1))
   {
      System.setProperty("gnu.io.rxtx.SerialPorts", port);
   }
   try
   {
      this.identifier = CommPortIdentifier.getPortIdentifier(port);
      CommPort commPort = identifier.open(getClass().getSimpleName(), OPEN_TIMEOUT); 
      if(commPort instanceof SerialPort)
      {
         serial = (SerialPort) commPort;
         serial.setFlowControlMode(SerialPort.FLOWCONTROL_NONE);
      }
      else
      {
         throw new IOException("Port is not a serial port");
      }
   }
   catch (NoSuchPortException | PortInUseException | IOException | UnsupportedCommOperationException e)
   {
      throw new RuntimeException(e);
   }
}
项目:EmbeddedMonitor    文件:WirelessLCDSystem.java   
private void startRS232Com() throws NoSuchPortException,
        PortInUseException,
        UnsupportedCommOperationException,
        IOException,
        TooManyListenersException {
    // get the port identifer
    String portName = comListStr[comList.getSelectedIndex()];
    portIdentifier = CommPortIdentifier.getPortIdentifier(portName);
    if (portIdentifier.isCurrentlyOwned()) {
        System.out.println("Error: Port is currently in use");
    } else {
        // Wait for 2ms when the COM is Busy
        String baudrate = baudrateListStr[baudrateList.getSelectedIndex()];
        CommPort comPort = portIdentifier.open(this.getClass().getName(), 2000);

        if (comPort instanceof SerialPort) {
            serialPort = (SerialPort) comPort;
            // set the notify on data available

            // serialPort.addEventListener(this);

            // use state machine here
            // so do not use the interrupt now
            // first time must open this notify

            //serialPort.notifyOnDataAvailable(true); 

            // set params
            serialPort.setSerialPortParams(
                    Integer.parseInt(baudrate),
                    SerialPort.DATABITS_8,
                    SerialPort.STOPBITS_1,
                    SerialPort.PARITY_NONE);
            // Do not use flow control
            serialPort.setFlowControlMode(SerialPort.FLOWCONTROL_NONE);

            // set the out/in stream
            serialIn = serialPort.getInputStream();
            serialOut = serialPort.getOutputStream();

            // initialize the read thread here
            // do not need initialize the thread here
            // first time do not initialize this thread
            if(null == serialReadThread){
                serialReadThread = new Thread(new SerialReader(serialIn));
                // start the thread
                serialReadThread.start();
            }

        } else {
            System.out.println(
                    "Error: Only serial ports are handled by this example.");
        }
    }
}
项目:Gomoku    文件:Com.java   
public Com(String str, App a) throws NoSuchPortException, PortInUseException, UnsupportedCommOperationException, TooManyListenersException{
        this.app=a;
        this.name=str;
        CommPortIdentifier id=CommPortIdentifier.getPortIdentifier(str);

        this.port = (SerialPort) id.open("Gomoku", timeout);    
//      this.port.setSerialPortParams(baudrate, SerialPort.DATABITS_8, SerialPort.STOPBITS_1, SerialPort.PARITY_NONE);
        this.port.setFlowControlMode(SerialPort.FLOWCONTROL_NONE);

        this.listen();
    }
项目:Gomoku    文件:App.java   
private void preparePort() throws NoSuchPortException, PortInUseException, UnsupportedCommOperationException, TooManyListenersException{
    this.comPort=new Com(selectedCom, this);
    this.status=AppStatus.READY;

    this.menu.setVisible(false);
    this.startGame.setVisible(true);
    this.displayMessage("Procure um jogo clicando no botao abaixo ou aguarde um convite");

}
项目:openhab-hdl    文件:EnoceanBinding.java   
@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;
        }
    }
}
项目:openhab-hdl    文件:RFXComConnection.java   
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);

        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);
        }
    }
项目:openhab-hdl    文件:PrimareSerialConnector.java   
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;
        }
    }
项目:harctoolboxbundle    文件:SendingGenericSerialPort.java   
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);
}
项目:openhab2-addons    文件:IT100BridgeHandler.java   
@Override
public void openConnection() {

    try {
        logger.debug("openConnection(): Connecting to IT-100 ");

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

        setConnected(true);

    } catch (NoSuchPortException noSuchPortException) {
        logger.error("openConnection(): No Such Port Exception: {}", noSuchPortException.getMessage());
        setConnected(false);
    } catch (PortInUseException portInUseException) {
        logger.error("openConnection(): Port in Use Exception: {}", portInUseException.getMessage());
        setConnected(false);
    } catch (UnsupportedCommOperationException unsupportedCommOperationException) {
        logger.error("openConnection(): Unsupported Comm Operation Exception: {}",
                unsupportedCommOperationException.getMessage());
        setConnected(false);
    } catch (UnsupportedEncodingException unsupportedEncodingException) {
        logger.error("openConnection(): Unsupported Encoding Exception: {}",
                unsupportedEncodingException.getMessage());
        setConnected(false);
    } catch (IOException ioException) {
        logger.error("openConnection(): IO Exception: {}", ioException.getMessage());
        setConnected(false);
    }
}
项目:openhab2-addons    文件:Cm11aBridgeHandler.java   
@Override
public void initialize() {
    // Get serial port number from config
    cm11aConfig = getThing().getConfiguration().as(Cm11aConfig.class);
    logger.trace("********* cm11a initialize started *********");

    // Verify the configuration is valid
    if (!validateConfig(this.cm11aConfig)) {
        return;
    }

    // Initialize the X10 interface
    try {
        x10Interface = new X10Interface(cm11aConfig.serialPort, this);
        x10Interface.setDaemon(true);
        x10Interface.start();
        x10Interface.addReceivedDataListener(this);
        logger.info("Initialized CM11A X10 interface on: {}", cm11aConfig.serialPort);
    } catch (NoSuchPortException e) {
        x10Interface = null;
        logger.error("No such port exists on this machine: {}", cm11aConfig.serialPort);
        updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR,
                "No such port exists on this machine: " + cm11aConfig.serialPort);
        return;
    }

    updateStatus(ThingStatus.ONLINE);
}
项目:openhab2-addons    文件:X10Interface.java   
/**
 *
 * @param serialPort serial port device. e.g. /dev/ttyS0
 * @throws NoSuchPortException
 *
 */
public X10Interface(String serialPort, Cm11aBridgeHandler bridgeHandler) throws NoSuchPortException {
    super();
    logger.trace("**** Constructing X10Interface for serial port: {} *******", serialPort);
    portId = CommPortIdentifier.getPortIdentifier(serialPort);
    this.bridgeHandler = bridgeHandler;
}
项目:kkMulticopterFlashTool    文件:SerialWriter.java   
private void openPort() throws IOException, NoSuchPortException, PortInUseException, UnsupportedCommOperationException{
    CommPortIdentifier portIdentifier = CommPortIdentifier.getPortIdentifier(port);
    CommPort commPort = portIdentifier.open("LightController",2000);

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

           this.out = serialPort.getOutputStream();
       }
}
项目:openhab1-addons    文件:EnoceanBinding.java   
@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;
        }
    }
}
项目:openhab1-addons    文件:RFXComConnection.java   
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);
    }
}
项目:openhab1-addons    文件:PrimareSerialConnector.java   
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;
        }
    }
项目:elexis-3-base    文件:CobasMiraConnection.java   
void connect(String portName) throws NoSuchPortException, PortInUseException,
    UnsupportedCommOperationException, IOException{
    CommPortIdentifier portIdentifier = CommPortIdentifier.getPortIdentifier(portName);
    if (portIdentifier.isCurrentlyOwned()) {
        logger.warn("Error: Port is currently in use");
    } else {
        CommPort commPort = portIdentifier.open(this.getClass().getName(), 2000);
        if (commPort instanceof SerialPort) {
            SerialPort serialPort = (SerialPort) commPort;
            serialPort.setSerialPortParams(1200, SerialPort.DATABITS_7, SerialPort.STOPBITS_2,
                SerialPort.PARITY_EVEN);
            serialPort.setFlowControlMode(SerialPort.FLOWCONTROL_RTSCTS_IN
                | SerialPort.FLOWCONTROL_RTSCTS_OUT);
            serialPort.setDTR(true);

            logger.debug("Opening connection to " + portName);
            logger.debug("BaudRate: " + serialPort.getBaudRate());
            logger.debug("STPB/DTB/PAR: " + serialPort.getStopBits() + " "
                + serialPort.getDataBits() + " " + serialPort.getParity());
            logger.debug("FCM: " + serialPort.getFlowControlMode() + " should be: "
                + (SerialPort.FLOWCONTROL_RTSCTS_IN | SerialPort.FLOWCONTROL_RTSCTS_OUT));
            logger.debug("CTS/CD/DTR/DSR/RTS: " + serialPort.isCTS() + " " + serialPort.isCD()
                + " " + serialPort.isDTR() + " " + serialPort.isDSR() + " "
                + serialPort.isRTS());

            InputStream in = serialPort.getInputStream();
            //OutputStream out = serialPort.getOutputStream();

            reader = new CobasMiraSerialReader(in, serialPort);
            cobasMiraReader = new Thread(reader);
            cobasMiraReader.start();
            logger.debug("Reader Thread ID: " + cobasMiraReader.getId() + " Priority: "
                + cobasMiraReader.getPriority() + " Name: " + cobasMiraReader.getName());

            //serialPort.setDTR(true);
            //(new Thread(new SerialWriter(out))).start();
        } else {
            logger.warn("Error: Only serial ports are handled by this example.");
        }
    }
}
项目:robotoy    文件:ArduinoController.java   
public void setControllerPort(String portName) throws NoSuchPortException {
    this.controllerPort = CommPortIdentifier.getPortIdentifier(portName);
}
项目:project-bianca    文件:PortRXTX.java   
public PortRXTX(String portName, int rate, int databits, int stopbits, int parity) throws IOException, PortInUseException, UnsupportedCommOperationException, NoSuchPortException {
    super(portName, rate, databits, stopbits, parity);
    commPortId = CommPortIdentifier.getPortIdentifier(portName);
}
项目:fax4j    文件:RXTXCommPortConnectionFactoryTest.java   
/**
 * Sets up the test objects.
 * 
 * @throws  Exception
 *          Any exception
 */
@Before
public void setUp() throws Exception
{
    this.connectionFactory=new RXTXCommPortConnectionFactory()
    {
        /**
         * This function returns the COMM port identifier object.
         * 
         * @param   portName
         *          The port name
         * @return  The port identifier object
         * @throws  NoSuchPortException
         *          In case no such port exists
         */
        @Override
        protected CommPortIdentifier getPortIdentifier(String portName) throws NoSuchPortException
        {
            CommPortIdentifier commPortIdentifier=Mockito.mock(CommPortIdentifier.class);
            try
            {
                CommPort commPort=Mockito.mock(CommPort.class);
                Mockito.when(commPort.getInputStream()).thenReturn(new ByteArrayInputStream(new byte[0]));
                Mockito.when(commPort.getOutputStream()).thenReturn(new ByteArrayOutputStream());
                Mockito.when(commPortIdentifier.open("fax4j",123)).thenReturn(commPort);
            }
            catch(Exception exception)
            {
                throw new RuntimeException(exception);
            }
            return commPortIdentifier;
        }
    };

    Properties configuration=new Properties();
    configuration.setProperty("org.fax4j.spi.comm.port.name","abc");
    configuration.setProperty("org.fax4j.spi.comm.connection.factory.class.name",RXTXCommPortConnectionFactory.class.getName());
    configuration.setProperty("org.fax4j.spi.comm.fax.modem.class.name",TestFaxModemAdapter.class.getName());   
    configuration.setProperty("org.fax4j.spi.comm.connection.timeout","123");
    CommFaxClientSpi faxClientSpi=(CommFaxClientSpi)TestUtil.createFaxClientSpi(CommFaxClientSpi.class.getName(),configuration);
    this.connectionFactory.initialize(faxClientSpi);
}
项目:JGirs    文件:SerialGirsClient.java   
public SerialGirsClient(String portName, int baudRate) throws HarcHardwareException, IOException, NoSuchPortException, PortInUseException, UnsupportedCommOperationException {
        this(new LocalSerialPortBuffered(portName, baudRate));
}
项目:JGirs    文件:SerialGirsClient.java   
public SerialGirsClient(String portName) throws HarcHardwareException, IOException, NoSuchPortException, PortInUseException, UnsupportedCommOperationException {
        this(new LocalSerialPortBuffered(portName));
}
项目:JGirs    文件:TcpGirsClient.java   
public TcpGirsClient(String ipName, int portNumber) throws HarcHardwareException, IOException, NoSuchPortException, PortInUseException, UnsupportedCommOperationException {
        this(new TcpSocketPort(ipName, portNumber));//, defaultSerialTimeout, verbose, TcpSocketPort.ConnectionMode.keepAlive));
}
项目:myrobotlab    文件:PortRXTX.java   
public PortRXTX(String portName, int rate, int databits, int stopbits, int parity)
    throws IOException, PortInUseException, UnsupportedCommOperationException, NoSuchPortException {
  super(portName, rate, databits, stopbits, parity);
  commPortId = CommPortIdentifier.getPortIdentifier(portName);
}
项目:Sentry-Gun-Computer-Vision    文件:ArduinoInteraction.java   
public static void main(String[] args) throws UnsupportedCommOperationException, PortInUseException, NoSuchPortException, InterruptedException, IOException {
    ArduinoInteraction a=new ArduinoInteraction(args);
    a.arduinoScreenPositiontoAngle(new int[]{50,50}, 100,100);
    a.flush();
    a.close();
}
项目:openhab1-addons    文件:PowerMaxSerialConnector.java   
/**
 * {@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);
    }
}