Java 类gnu.io.PortInUseException 实例源码

项目: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();
    }
}
项目:scorekeeperfrontend    文件:SerialDataInterface.java   
public void open() throws PortInUseException, UnsupportedCommOperationException, TooManyListenersException, IOException
{
    if (open)
    {
        log.info(commId.getName() + " already open, skipping");
        return;
    }

    log.info("Opening port " + commId.getName());
    buffer = new ByteBuffer();

    port = (SerialPort)commId.open("TimerInterface-"+commId.getName(), 30000);
    port.setSerialPortParams(9600, SerialPort.DATABITS_8, SerialPort.STOPBITS_1, SerialPort.PARITY_NONE);
    port.setFlowControlMode(SerialPort.FLOWCONTROL_NONE);

    port.addEventListener(this);
    port.notifyOnDataAvailable(true);
    port.enableReceiveTimeout(30);

    os = port.getOutputStream();
    is = port.getInputStream();
    open = true;
   }
项目: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();
        }
    };
}
项目:GPSSimulator    文件:TwoWaySerialComm.java   
private void connect(String portName) throws Exception {
    CommPortIdentifier portIdentifier = CommPortIdentifier.getPortIdentifier(portName);
    if (portIdentifier.isCurrentlyOwned())
        throw new PortInUseException();

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

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

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

        new Thread(new SerialReader(in)).start();
        new Thread(new SerialWriter(out)).start();

    } else {
        throw new PortUnreachableException("ERROR - Only serial ports are handled by this class");
    }

}
项目: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;
    }
}
项目:jmoduleconnect    文件:CommHandlerImpl.java   
/**
 * Creates an instance of this class.
 * @param commPortIdentifier Must point to an serial port
 * @param baudrate The baudrate of the communication. The baudrate must be 
 *        setted with <code>AT+IPR=*baudrate*</code>. The default baudrate
 *        of an device is <code>115200</code>
 * @param flowControlMode The flow control mode of the serial port
 * @return An instance of <code>CommHandlerImpl</code>
 * @throws PortInUseException The selected port is used by another application
 * @throws IOException The communication to the device failed
 * @throws IllegalArgumentException If parameter commPortIdentifier is 
 *         <code>null</code> or the result of {@link CommPortIdentifier#open(java.lang.String, int) } 
 *         is not an instance of {@link SerialPort}.
 * @since 1.5
 */
public static final CommHandler createCommHandler(final CommPortIdentifier commPortIdentifier
        , final int baudrate, final EnumSet<FlowControlMode> flowControlMode) 
        throws PortInUseException, IOException
{
    final CommHandlerImpl commHandler = new CommHandlerImpl();

    try
    {
        commHandler.init(commPortIdentifier, baudrate, flowControlMode);
        return commHandler;
    }
    catch (final PortInUseException | IOException ex)
    {
        commHandler.close();
        throw ex;
    }
}
项目:arduino-remote-uploader    文件:SerialSketchUploader.java   
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);
}
项目:EasyVote    文件:VCDSerialPort.java   
/**
 * Versucht den seriellen Port zu �ffnen. Klappt nur, wenn er noch nicht von einer anderen Anwendung benutzt wird. Der jeweilige
 * Port wird mit �bergeben. UNter Windows ist die Schreibweise "COM8" zum Beispeil unter Linux "dev/tts0"
 * @param portName
 * @return
 * @throws PortInUseException
 * @throws IOException
 * @throws UnsupportedCommOperationException
 */
public boolean oeffneSerialPort(String portName) throws PortInUseException, IOException, UnsupportedCommOperationException
{
    Boolean foundPort = false;
    if (serialPortGeoeffnet != false) {
        System.out.println("Serialport bereits ge�ffnet");
        schliesseSerialPort();
        return false;
    }
    System.out.println("�ffne Serialport");
    enumComm = CommPortIdentifier.getPortIdentifiers();
    while(enumComm.hasMoreElements()) {
        serialPortId = (CommPortIdentifier) enumComm.nextElement();
        System.out.println("SerialportIDs:" + serialPortId.getName());
        if (portName.contentEquals(serialPortId.getName())) {
            foundPort = true;
            break;
        }
    }
    if (foundPort != true) {
        System.out.println("Serialport nicht gefunden: " + portName);
        return false;
    }
        serialPort = (SerialPort) serialPortId.open("�ffnen und Senden", 500);
        outputStream = serialPort.getOutputStream();
        inputStream = serialPort.getInputStream();

    serialPort.notifyOnDataAvailable(true);
        serialPort.setSerialPortParams(baudrate, dataBits, stopBits, parity);


    serialPortGeoeffnet = true;
    return true;
}
项目:Animator    文件:FlashExporter.java   
/**
 * Write contents of stream inputStream to serial port
 * 
 * @param stream
 * @throws IOException
 * @throws UnsupportedCommOperationException
 * @throws PortInUseException
 */
public void write(InputStream inputStream) throws IOException,
        UnsupportedCommOperationException, PortInUseException {
    SerialPort serialPort = initSerialPort(getPortIdentifier(deviceName));
    OutputStream serialOut = serialPort.getOutputStream();
    writeTo(inputStream, serialOut);
    serialOut.close();
    serialPort.close();
}
项目:Animator    文件:FlashExporter.java   
public void write(String rawString)
        throws UnsupportedCommOperationException, PortInUseException,
        IOException {
    SerialPort serialPort = initSerialPort(getPortIdentifier(deviceName));
    OutputStream serialOut = serialPort.getOutputStream();
    writeTo(rawString, serialOut);
    serialOut.close();
    serialPort.close();
}
项目:jpowermeter    文件:SimulatedEhzSmlReader.java   
@Override
public SmartMeterReading read(String device) throws PortInUseException, IOException, UnsupportedCommOperationException {

    BigDecimal READING_POWER = new BigDecimal(new Random().nextInt(5000));
    READING_TOTAL = READING_TOTAL.add(READING_POWER.divide(new BigDecimal(WATT_TO_WATTHOURS), 2, BigDecimal.ROUND_DOWN));
    READING_ONE = READING_TOTAL;

    SmartMeterReading smartMeterReading = new SmartMeterReading();
    smartMeterReading.meterTotal = new Meter(READING_TOTAL, "WH");
    smartMeterReading.meterOne = new Meter(READING_ONE, "WH");
    smartMeterReading.meterTwo = new Meter(READING_TWO, "WH");
    smartMeterReading.power = new Meter(READING_POWER, "W");
    smartMeterReading.complete = true;
    log.debug(smartMeterReading.toString());

    return smartMeterReading;
}
项目:Animator    文件:FlashExporter.java   
/**
 * Write contents of stream inputStream to serial port
 * 
 * @param stream
 * @throws IOException
 * @throws UnsupportedCommOperationException
 * @throws PortInUseException
 */
public void write(InputStream inputStream) throws IOException,
        UnsupportedCommOperationException, PortInUseException {
    SerialPort serialPort = initSerialPort(getPortIdentifier(deviceName));
    OutputStream serialOut = serialPort.getOutputStream();
    writeTo(inputStream, serialOut);
    serialOut.close();
    serialPort.close();
}
项目:Animator    文件:FlashExporter.java   
public void write(String rawString)
        throws UnsupportedCommOperationException, PortInUseException,
        IOException {
    SerialPort serialPort = initSerialPort(getPortIdentifier(deviceName));
    OutputStream serialOut = serialPort.getOutputStream();
    writeTo(rawString, serialOut);
    serialOut.close();
    serialPort.close();
}
项目: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);
    }
项目: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);
}
项目:ArduinoLight    文件:SerialConnection.java   
/**
 * Tries to establish a serial connection with the given portId and baudRate and set the _serialOutputStream.
 * If the connection could be established, _open is set to true.
 * @param portId a CommPortIdentifier-object, used for identifying and connecting to a port.
 * @param baudRate This has to match the settings in the arduino-code. Recommended value: 256000.
 * @throws PortInUseException, IllegalArgumentException
 * @throws IllegalStateException if there is already a connection active
 */
public synchronized void open(CommPortIdentifier portId, int baudRate) throws PortInUseException
{
    if (_open)
        throw new IllegalStateException("This SerialConnection is already opened.");

    try
    {
        _serialPort = (SerialPort) portId.open(_APPNAME, _TIME_OUT); //throws PortInUse
        _serialPort.setSerialPortParams(baudRate,
                SerialPort.DATABITS_8,
                SerialPort.STOPBITS_1,
                SerialPort.PARITY_NONE);
        _serialOutputStream = new BufferedOutputStream(_serialPort.getOutputStream());
        _open = true;
        ShutdownHandler.getInstance().addShutdownListener(this);
        DebugConsole.print("SerialConnection", "open", "Connecting successful!");
    }
    catch (UnsupportedCommOperationException | IOException ex)
    {
        DebugConsole.print("SerialConnection", "open", ex.toString());
        throw new IllegalArgumentException(ex);
    }

}
项目: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();
    }
}
项目: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");

}
项目:pancakes    文件:JoystickDriver.java   
public JoystickDriver(Backend backend) {

        String osName = System.getProperty("os.name");
        Kernel.getInstance().getSyslog().debug("OS: " + osName);

        try {

                String portName = "";
                if(osName.contains("Mac")){
                    portName = "/dev/tty.usbserial-09KP8154";
                }
                else{
                    portName = "/dev/ttyUSB0";
                }
                this.connect(portName);

        } catch (Exception e) {
            if(e instanceof PortInUseException){
                PortInUseException piu = (PortInUseException) e;
                Kernel.getInstance().getSyslog().error("Port in use - owner: " + piu.currentOwner); 
            }
            else{
                e.printStackTrace();
            }
            Kernel.getInstance().getSyslog().error("Unable to connect to serial joystick.");
        }
    }
项目:xbee-api    文件:SerialPortConnection.java   
@SuppressWarnings("unchecked")
public void openSerialPort(String port, String appName, int timeout, int baudRate, int dataBits, int stopBits, int parity, int flowControl) throws PortInUseException, UnsupportedCommOperationException, TooManyListenersException, IOException, XBeeException {
    // Apparently you can't query for a specific port, but instead must iterate
    Enumeration<CommPortIdentifier> portList = CommPortIdentifier.getPortIdentifiers();

    CommPortIdentifier portId = null;

    boolean found = false;

    while (portList.hasMoreElements()) {

        portId = portList.nextElement();

        if (portId.getPortType() == CommPortIdentifier.PORT_SERIAL) {

            //log.debug("Found port: " + portId.getName());

            if (portId.getName().equals(port)) {
                //log.debug("Using Port: " + portId.getName());
                found = true;
                break;
            }
        }
    }

    if (!found) {
        throw new XBeeException("Could not find port: " + port);
    }

    serialPort = (SerialPort) portId.open(appName, timeout);

    serialPort.setSerialPortParams(baudRate, SerialPort.DATABITS_8, SerialPort.STOPBITS_1, SerialPort.PARITY_NONE);
    serialPort.setFlowControlMode(SerialPort.FLOWCONTROL_NONE);

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

    // activate the OUTPUT_BUFFER_EMPTY notifier
    //serialPort.notifyOnOutputEmpty(true);

    serialPort.addEventListener(this);

    inputStream = serialPort.getInputStream();
    outputStream = new BufferedOutputStream(serialPort.getOutputStream());
}
项目: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);
        }
    }
项目: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);
}
项目:arduino-remote-uploader    文件:NordicSketchUploader.java   
public void flash(String file, String device, int speed, boolean verbose, int ackTimeout, int arduinoTimeout, int retriesPerPacket, int delayBetweenRetriesMillis) throws IOException, PortInUseException, UnsupportedCommOperationException, TooManyListenersException, StartOverException {
    Map<String,Object> context = Maps.newHashMap();
    context.put("device", device);
    context.put("speed", speed);

    // determine max data we can send with each programming packet
    int pageSize = NORDIC_PACKET_SIZE - getProgramPageHeader(0, 0).length;
    super.process(file, pageSize, ackTimeout, arduinoTimeout, retriesPerPacket, delayBetweenRetriesMillis, verbose, context);
}
项目:arduino-remote-uploader    文件:NordicSketchUploader.java   
private void runFromCmdLine(String[] args) throws org.apache.commons.cli.ParseException, IOException, PortInUseException, UnsupportedCommOperationException, TooManyListenersException, StartOverException {
    CliOptions cliOptions = getCliOptions();

    cliOptions.addOption(
            OptionBuilder
            .withLongOpt(serialPort)
            .hasArg()
            .isRequired(true)
            .withDescription("Serial port of of Arduino running NordicSPI2Serial sketch (e.g. /dev/tty.usbserial-A6005uRz). Required")
            .create("p"));

    cliOptions.addOption(
            OptionBuilder
            .withLongOpt(baudRate)
            .hasArg()
            .isRequired(true)
            .withType(Number.class)
            .withDescription("Baud rate of Arduino. Required")
            .create("b"));

    cliOptions.build();

    CommandLine commandLine = cliOptions.parse(args);

    if (commandLine != null) {
        new NordicSketchUploader().flash(
                commandLine.getOptionValue(CliOptions.sketch), 
                commandLine.getOptionValue(serialPort), 
                cliOptions.getIntegerOption(baudRate), 
                commandLine.hasOption(CliOptions.verboseArg),
                cliOptions.getIntegerOption(CliOptions.ackTimeoutMillisArg),
                cliOptions.getIntegerOption(CliOptions.arduinoTimeoutArg),
                cliOptions.getIntegerOption(CliOptions.retriesPerPacketArg),
                cliOptions.getIntegerOption(CliOptions.delayBetweenRetriesMillisArg));
    }
}
项目: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);
    }
}
项目: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();
       }
}
项目:kkMulticopterFlashTool    文件:TestControllPanel.java   
@Override
public void actionPerformed(ActionEvent event) {
    if (event.getSource().equals(startButton)) {
        try {
            startAction();
        } catch (PortInUseException e) {
            JOptionPane.showMessageDialog(this, _("serialPort.portInUseException"));
            logger.log(Level.WARNING, e.getMessage());
        }
    } else if (event.getSource().equals(stopButton)) {
        stopAction();
    }
}
项目:kkMulticopterFlashTool    文件:TestControllPanel.java   
private void startAction() throws PortInUseException {
    logger.info("start serialReader");
    stopButton.setEnabled(true);
    startButton.setEnabled(false);

    serialReader = new SerialReader(baud, (String)portComboBox.getSelectedItem(), parent.getEvaluationPanel());
    serialReader.start();

}
项目:xbee-api-jssc    文件:RxTxSerialComm.java   
@SuppressWarnings("unchecked")
public void openSerialPort(String port, String appName, int timeout, int baudRate, int dataBits, int stopBits, int parity, int flowControl) throws PortInUseException, UnsupportedCommOperationException, TooManyListenersException, IOException, XBeeException {
    // Apparently you can't query for a specific port, but instead must iterate
    Enumeration<CommPortIdentifier> portList = CommPortIdentifier.getPortIdentifiers();

    CommPortIdentifier portId = null;

    boolean found = false;

    while (portList.hasMoreElements()) {

        portId = portList.nextElement();

        if (portId.getPortType() == CommPortIdentifier.PORT_SERIAL) {

            //log.debug("Found port: " + portId.getName());

            if (portId.getName().equals(port)) {
                //log.debug("Using Port: " + portId.getName());
                found = true;
                break;
            }
        }
    }

    if (!found) {
        throw new XBeeException("Could not find port: " + port);
    }

    serialPort = (SerialPort) portId.open(appName, timeout);

    serialPort.setSerialPortParams(baudRate, SerialPort.DATABITS_8, SerialPort.STOPBITS_1, SerialPort.PARITY_NONE);
    serialPort.setFlowControlMode(SerialPort.FLOWCONTROL_NONE);

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

    // activate the OUTPUT_BUFFER_EMPTY notifier
    //serialPort.notifyOnOutputEmpty(true);

    serialPort.addEventListener(this);

    inputStream = serialPort.getInputStream();
    outputStream = new BufferedOutputStream(serialPort.getOutputStream());
}
项目:jpowermeter    文件:DeviceEhzSmlReader.java   
public SmartMeterReading read(String device) throws PortInUseException, IOException, UnsupportedCommOperationException {
    log.debug("Reading from "+device);
    SML_SerialReceiver receiver = new SML_SerialReceiver();
    receiver.setupComPort(device);
    log.debug("Reading from device : {}", device);
    SmartMeterReading smartMeterReading = new SmartMeterReading();

    try {
        for (int j = 0; j < TRIES_TO_GET_THE_START_SEQUENCE_IN_DATA_FROM_DEVICE; j++) {
            List<SML_Message> smlMessages = getMessages(receiver);
            log.debug("Got {} SML messages.", smlMessages.size());
            for (SML_Message sml_message : smlMessages) {
                log.debug("Message : {} ", sml_message.toString());
                if (isListResponse(sml_message)) {
                    SML_ListEntry[] list = getEntries(sml_message);
                    int listEntryPosition = 0;
                    for (SML_ListEntry entry : list) {
                        listEntryPosition++;
                        int unit = entry.getUnit().getVal();
                        Integer8 scaler = entry.getScaler();
                        if (unit == SML_Unit.WATT_HOUR || unit == SML_Unit.WATT) {
                            smartMeterReading.date = new Date();
                            Meter meter = extractMeter(entry, unit, scaler);
                            assignConsumptionToMatchingPowerMeterField(smartMeterReading, listEntryPosition, meter);
                        }
                    }
                }
            }
            log.debug("Set complete status to true.");
            smartMeterReading.complete = true;
            log.info(smartMeterReading.toString());
        }
    } catch (Exception e) {
        log.error("Exception {}", e, e.getMessage());
        smartMeterReading.complete = false;
    } finally {
        receiver.close();
    }
    return smartMeterReading;
}
项目:jpowermeter    文件:Application.java   
@Scheduled(fixedRate = 1000, initialDelay = 5000)
public void readPowerMeter() throws PortInUseException, IOException, UnsupportedCommOperationException {

    log.debug("Trying to read from device: " + device);
    if (ehzSmlReader == null) {
        ehzSmlReader = getReader(device);
    }

    SmartMeterReading reading = ehzSmlReader.read(device);
    if (reading.complete) {
        readingBuffer.setSmartMeterReading(reading);
    }
}
项目: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);
    }
}