Java 类gnu.io.CommPort 实例源码

项目:jaer    文件:PanTiltControlDynamixel.java   
void connect(String destination) throws Exception {
    CommPortIdentifier portIdentifier = CommPortIdentifier.getPortIdentifier(destination);
    if (portIdentifier.isCurrentlyOwned()) {
        log.warning("Error: Port for Dynamixel-Communication is currently in use");
    } else {
        CommPort commPort = portIdentifier.open(this.getClass().getName(), 2000);
        if (commPort instanceof SerialPort) {
            SerialPort serialPort = (SerialPort) commPort;
            serialPort.setSerialPortParams(57600, SerialPort.DATABITS_8, SerialPort.STOPBITS_1, SerialPort.PARITY_NONE);
            in = serialPort.getInputStream();
            out = serialPort.getOutputStream();
            serialReader = new SerialReader(in);
            serialPort.addEventListener(serialReader);
            serialPort.notifyOnDataAvailable(true);
            connected = true;
            log.info("Connected to Dynamixel!");
        } else {
            log.warning("Error: Cannot connect to Dynamixel!");
        }

    }
}
项目:jaer    文件:PanTiltControlPTU.java   
void connect(String destination) throws Exception {
    CommPortIdentifier portIdentifier = CommPortIdentifier.getPortIdentifier(destination);
    if (portIdentifier.isCurrentlyOwned()) {
        log.warning("Error: Port for Pan-Tilt-Communication is currently in use");
    } else {
        CommPort commPort = portIdentifier.open(this.getClass().getName(), 2000);
        if (commPort instanceof SerialPort) {
            SerialPort serialPort = (SerialPort) commPort;
            serialPort.setSerialPortParams(9600, SerialPort.DATABITS_8, SerialPort.STOPBITS_1, SerialPort.PARITY_NONE);
            in = serialPort.getInputStream();
            out = serialPort.getOutputStream();
            serialPort.addEventListener(new SerialReader(in));
            serialPort.notifyOnDataAvailable(true);
            connected = true;
            log.info("Connected to Pan-Tilt-Unit!");
        } else {
            log.warning("Error: Cannot connect to Pan-Tilt-Unit!");
        }
    }
}
项目:jaer    文件:DynamixelControl.java   
void connect(String destination) throws Exception {
    CommPortIdentifier portIdentifier = CommPortIdentifier.getPortIdentifier(destination);
    if (portIdentifier.isCurrentlyOwned()) {
        log.warning("Error: Port for Dynamixel-Communication is currently in use");
    } else {
        CommPort commPort = portIdentifier.open(this.getClass().getName(), 2000);
        if (commPort instanceof SerialPort) {
            SerialPort serialPort = (SerialPort) commPort;
            serialPort.setSerialPortParams(57142, SerialPort.DATABITS_8, SerialPort.STOPBITS_1, SerialPort.PARITY_NONE);
            in = serialPort.getInputStream();
            out = serialPort.getOutputStream();
            serialPort.addEventListener(new SerialReader(in));
            serialPort.notifyOnDataAvailable(true);
            log.info("Connected to Dynamixel!");
        } else {
            log.warning("Error: Cannot connect to Dynamixel!");
        }
    }
}
项目:POPBL_V    文件:SerialManagement.java   
/** Method to connect to an available port */
@SuppressWarnings("static-access")
private void connect(String portName) throws Exception {
    CommPortIdentifier commPortIdentifier = CommPortIdentifier.getPortIdentifier(portName);

    if (commPortIdentifier.isCurrentlyOwned()) {
        System.out.println("Error: Port is currently in use");
    } else {
        CommPort commPort = commPortIdentifier.open(this.getClass().getName(), 2000);

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

            this.inputStream = serialPort.getInputStream();
            this.outputStream = serialPort.getOutputStream();

            References.SERIAL_READER = new SerialReader(this.inputStream);
            readThread = new Thread(References.SERIAL_READER);
            readThread.start();
        } else {
            System.out.println("Error: Only serial ports allowed");
        }
    }
}
项目: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();
    }
}
项目:RPLidar4J    文件:RpLidarLowLevelDriver.java   
/**
 * Initializes serial connection
 *
 * @param portName Path to serial port
 * @param listener Listener for in comming packets
 * @throws Exception
 */
public RpLidarLowLevelDriver(final String portName, final RpLidarListener listener) throws Exception {

    log.info("Opening port " + portName);

    this.listener = listener;

    //Configuration for Serial port operations
    final CommPortIdentifier portIdentifier = CommPortIdentifier.getPortIdentifier(portName);
    final CommPort commPort = portIdentifier.open("FOO", 2000);
    serialPort = (SerialPort) commPort;
    serialPort.setSerialPortParams(115200, SerialPort.DATABITS_8, SerialPort.STOPBITS_1, SerialPort.PARITY_NONE);
    serialPort.setFlowControlMode(SerialPort.FLOWCONTROL_NONE);
    serialPort.setDTR(false); // lovely undocumented feature where if true the motor stops spinning

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

    readThread = new ReadSerialThread();
    new Thread(readThread).start();
}
项目:JLamp    文件:Serial.java   
public void connect(String portName) throws Exception {
    CommPortIdentifier portIdentifier = CommPortIdentifier.getPortIdentifier(portName);
    LOG.info("Found the " + portName + " port.");
    if (portIdentifier.isCurrentlyOwned()) {
        LOG.error("Port is currently in use");
    } else {
        CommPort commPort = portIdentifier.open(this.getClass().getName(), 2000);
        LOG.info("Opened port " + portName);

        if (commPort instanceof SerialPort) {
            SerialPort serialPort = (SerialPort) commPort;
            serialPort.setSerialPortParams(115200, SerialPort.DATABITS_8, SerialPort.PARITY_EVEN, SerialPort.FLOWCONTROL_NONE);

            printWriter = new PrintWriter(serialPort.getOutputStream());
            bufferedReader = new BufferedReader(new InputStreamReader(serialPort.getInputStream()));

               // For skipping AnA string
               skipInput();

        } else {
            LOG.error("Only serial ports are handled by this example.");
        }
    }
}
项目: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");
    }

}
项目:Serial    文件:SerialEvent.java   
public void handleEvent() {
    try {
        CommPortIdentifier portId = CommPortIdentifier.getPortIdentifier(SerialConf.WINDOWS_PORT);

        if (portId.isCurrentlyOwned()) {
            System.out.println("Port busy!");
        } else {
            CommPort commPort = portId.open("whatever it's name", SerialConf.TIME_OUT);
            if (commPort instanceof SerialPort) {
                serialPort = (SerialPort) commPort;
                serialPort.setSerialPortParams(SerialConf.BAUD, 
                                                SerialPort.DATABITS_8, 
                                                SerialPort.STOPBITS_1, 
                                                SerialPort.PARITY_EVEN);
                in = serialPort.getInputStream();
                serialPort.notifyOnDataAvailable(true);
                serialPort.addEventListener(this);
            } else {
                commPort.close();
                System.out.println("the port is not serial!");
            }
        }
    } catch (Exception e) {
        serialPort.close();
        System.out.println("Error: SerialOpen!!!");
        e.printStackTrace();
    }
}
项目:wot_gateways    文件:SerialComm.java   
/**
 * Constructor
 * 
 * @param portName
 *            The name of the serial port
 * @param listeners
 *            The listeners for incoming telegrams
 * @throws Exception
 */
public SerialComm(String portName, ArrayList<EnoceanListener> listeners)
        throws Exception {
    this.listeners = listeners;
    CommPortIdentifier portIdentifier = CommPortIdentifier
            .getPortIdentifier(portName);
    if (portIdentifier.isCurrentlyOwned()) {
        throw new Exception("Port is currently in use");
    }

    CommPort commPort = portIdentifier
            .open(this.getClass().getName(), 2000); // timeout 2 s.
    if (!(commPort instanceof SerialPort)) {
        throw new Exception("Only serial port is supported");
    }
    port = commPort;

    SerialPort serialPort = (SerialPort) commPort;

    // 57600 bit/s, 8 bits, stop bit length 1, no parity bit
    serialPort.setSerialPortParams(57600, SerialPort.DATABITS_8,
            SerialPort.STOPBITS_1, SerialPort.PARITY_NONE);
    input = serialPort.getInputStream();
    output = serialPort.getOutputStream();
}
项目:openhab-hdl    文件:SwegonVentilationSerialConnector.java   
@Override
public void connect() throws SwegonVentilationException {

    try {
        CommPortIdentifier portIdentifier = CommPortIdentifier
                .getPortIdentifier(portName);
        CommPort commPort = portIdentifier.open(this.getClass().getName(),
                2000);
        serialPort = (SerialPort) commPort;
        serialPort.setSerialPortParams(BAUDRATE, SerialPort.DATABITS_8,
                SerialPort.STOPBITS_1, SerialPort.PARITY_NONE);

        in = serialPort.getInputStream();

        logger.debug("Swegon ventilation Serial Port message listener started");

    } catch (Exception e) {
        throw new SwegonVentilationException(e);
    }
}
项目:openhab-hdl    文件:OpenEnergyMonitorSerialConnector.java   
@Override
public void connect() throws OpenEnergyMonitorException {

    try {
        CommPortIdentifier portIdentifier = CommPortIdentifier
                .getPortIdentifier(portName);
        CommPort commPort = portIdentifier.open(this.getClass().getName(),
                2000);
        serialPort = (SerialPort) commPort;
        serialPort.setSerialPortParams(BAUDRATE, SerialPort.DATABITS_8,
                SerialPort.STOPBITS_1, SerialPort.PARITY_NONE);

        in = serialPort.getInputStream();
        logger.debug("Open Energy Monitor Serial Port message listener started");

    } catch (Exception e) {
        throw new OpenEnergyMonitorException(e);
    }
}
项目: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    文件:EpsonProjectorSerialConnector.java   
/**
 * {@inheritDoc}
 */
public void connect() throws EpsonProjectorException {

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

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

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

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

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

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

}
项目: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;
    }
}
项目:kkMulticopterFlashTool    文件:SerialReader.java   
private void openPort() throws Exception{
    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);

           in = serialPort.getInputStream();

           isr = new InputStreamReader(in);
           br = new BufferedReader(isr);
       }
}
项目:phil-cereals    文件:SerialInterface.java   
private void openPort(String id) {
    System.out.printf("opening port %s @ %d bauds\n", id, this.baudRate);
    try {
        CommPortIdentifier portId = CommPortIdentifier.getPortIdentifier(id);
        if (portId.isCurrentlyOwned()) {
            System.err.printf("error: %s port currently in use\n", id);
            return;
        }
        CommPort commPort = portId.open(this.getClass().getName(), 5000);
        if (commPort instanceof SerialPort) {
            this.port = (SerialPort) commPort;
            this.port.setSerialPortParams(this.baudRate, SerialPort.DATABITS_8, SerialPort.STOPBITS_1, SerialPort.PARITY_NONE);
            this.portOut = this.port.getOutputStream();
        } else {
            System.err.printf("error: port %s is not serial\n", id);
            return;
        }
    } catch (Exception e) {
        System.err.printf("error: cannot find/open port %s\n", id);
        System.err.printf("%s\n", e.getMessage());
    }
}
项目:tc65sh    文件:Device.java   
public void connect(String portname, int baudrate, char flowControl) throws Exception {
    Log.debug(this.getClass(), "connecting device "+portname+", "+baudrate+" baud");
       boolean isCommonPortname = portname.contains("ttyS") || portname.contains("COM");
    if ( ! isCommonPortname ) {
           System.setProperty("gnu.io.rxtx.SerialPorts", portname);
       }
    System.setProperty("gnu.io.rxtx.NoVersionOutput", "true");
    CommPortIdentifier commPortIdentifier = CommPortIdentifier.getPortIdentifier(portname);
    CommPort commPort = commPortIdentifier.open("tc65sh", 2000);
    serialPort = (SerialPort) commPort;
    serialPort.setSerialPortParams(baudrate, SerialPort.DATABITS_8, SerialPort.STOPBITS_1, SerialPort.PARITY_NONE);
    serialPort.enableReceiveTimeout(2000);
    if ( flowControl == FLOWCONTROL_NONE ) {
        serialPort.setFlowControlMode(SerialPort.FLOWCONTROL_NONE);
    } else if ( flowControl == FLOWCONTROL_RTSCTS) {
        serialPort.setFlowControlMode(SerialPort.FLOWCONTROL_RTSCTS_OUT | SerialPort.FLOWCONTROL_RTSCTS_IN);
    } else if ( flowControl == FLOWCONTROL_XONXOFF) {
        serialPort.setFlowControlMode(SerialPort.FLOWCONTROL_XONXOFF_OUT | SerialPort.FLOWCONTROL_XONXOFF_IN);
    } else {
        throw new RuntimeException("invalid flowControl "+flowControl);
    }
    serialIn = serialPort.getInputStream();
    serialOut = serialPort.getOutputStream();
}
项目:openhab1-addons    文件:SwegonVentilationSerialConnector.java   
@Override
public void connect() throws SwegonVentilationException {

    try {
        CommPortIdentifier portIdentifier = CommPortIdentifier.getPortIdentifier(portName);
        CommPort commPort = portIdentifier.open(this.getClass().getName(), 2000);
        serialPort = (SerialPort) commPort;
        serialPort.setSerialPortParams(BAUDRATE, SerialPort.DATABITS_8, SerialPort.STOPBITS_1,
                SerialPort.PARITY_NONE);

        in = serialPort.getInputStream();

        logger.debug("Swegon ventilation Serial Port message listener started");

    } catch (Exception e) {
        throw new SwegonVentilationException(e);
    }
}
项目:openhab1-addons    文件:SerialPortConnector.java   
@Override
protected void connectPort() throws Exception {
    CommPortIdentifier portIdentifier = CommPortIdentifier.getPortIdentifier(device);

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

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

    in = serialPort.getInputStream();
    out = new DataOutputStream(serialPort.getOutputStream());
}
项目: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    文件:EpsonProjectorSerialConnector.java   
/**
 * {@inheritDoc}
 */
@Override
public void connect() throws EpsonProjectorException {

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

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

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

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

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

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

}
项目: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;
    }
}
项目:openhab1-addons    文件:EiscpSerial.java   
/**
 * {@inheritDoc}
 */
public boolean connect(String serialPortName) {

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

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

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

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

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

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

}
项目: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);
    }
项目:MEEPROMMER    文件:MySerial.java   
void connect(String portName, int speed) throws Exception {
    CommPortIdentifier portIdentifier = CommPortIdentifier.getPortIdentifier(portName);
    if (portIdentifier.isCurrentlyOwned()) {
        throw (new Exception("Error: Port is currently in use"));
    } else {
        CommPort commPort = portIdentifier.open("MEEPROMMER", 2000);
        if (commPort instanceof SerialPort) {
            serialPort = (SerialPort) commPort;
            serialPort.setSerialPortParams(speed, SerialPort.DATABITS_8,
                    SerialPort.STOPBITS_1, SerialPort.PARITY_NONE);
            in = serialPort.getInputStream();
            out = serialPort.getOutputStream();

        } else {
            throw (new Exception("Error: Only serial ports are handled by this example."));
        }
    }
}
项目: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.");
        }
    }
}
项目:netty4.0.27Learn    文件:RxtxChannel.java   
@Override
protected void doConnect(SocketAddress remoteAddress, SocketAddress localAddress) throws Exception {
    RxtxDeviceAddress remote = (RxtxDeviceAddress) remoteAddress;
    final CommPortIdentifier cpi = CommPortIdentifier.getPortIdentifier(remote.value());
    final CommPort commPort = cpi.open(getClass().getName(), 1000);
    commPort.enableReceiveTimeout(config().getOption(READ_TIMEOUT));
    deviceAddress = remote;

    serialPort = (SerialPort) commPort;
}
项目: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;
        }
    }
项目:fax4j    文件:RXTXCommPortConnectionFactory.java   
/**
 * Creates and returns the resource.
 *  
 * @return  The resource
 */
@Override
protected CommPortAdapter createResourceImpl()
{
    //get COMM port name
    String portName=this.getPortName();

    //get timeout
    int timeout=this.getTimeOut();

    CommPort commPort=null;
    try
    {
        //get COMM port identifier
        CommPortIdentifier commPortIdentifier=this.getPortIdentifier(portName);

        //open connection
        commPort=commPortIdentifier.open("fax4j",timeout);
    }
    catch(Exception exception)
    {
        throw new FaxException("Unable to connect to COMM port: "+portName,exception);
    }

    //create adapter wrapper
    CommPortAdapter adapter=new RXTXCommPortAdapter(commPort);

    return adapter;
}
项目:fax4j    文件:RXTXCommPortAdapter.java   
/**
 * This is the class constructor.
 * 
 * @param   commPort
 *          The COMM port
 */
public RXTXCommPortAdapter(CommPort commPort)
{
    super();

    //validate COMM port object provided
    if(commPort==null)
    {
        throw new FaxException("COMM port object not provided.");
    }

    this.commPort=commPort;
}
项目:fax4j    文件:RXTXCommPortAdapter.java   
/**
 * Closes the connection.
 */
@Override
protected void closeImpl()
{
    //remove reference
    CommPort port=this.commPort;
    this.commPort=null;

    //close connection
    port.close();
}
项目: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);
    }
}
项目:netty4study    文件:RxtxChannel.java   
@Override
protected void doConnect(SocketAddress remoteAddress, SocketAddress localAddress) throws Exception {
    RxtxDeviceAddress remote = (RxtxDeviceAddress) remoteAddress;
    final CommPortIdentifier cpi = CommPortIdentifier.getPortIdentifier(remote.value());
    final CommPort commPort = cpi.open(getClass().getName(), 1000);

    deviceAddress = remote;

    serialPort = (SerialPort) commPort;
}
项目: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();
       }
}
项目:uia.comm4j    文件:RS232.java   
/**
 * Connect.
 * @param portName RS232 port name.
 * @param baudrate Baud rate.
 * @param dataBits Data bits.
 * @param stopBits Stop bits.
 * @param parity Parity.
 * @return Success or not.
 * @throws Exception
 */
public boolean connect(String portName, int baudrate, int dataBits, int stopBits, int parity) throws Exception {
    this.monitor = this.protocol.createMonitor(this.aliasName);
    this.monitor.setController(this);

    if (this.started) {
        return true;
    }

    CommPortIdentifier portIdentifier = CommPortIdentifier.getPortIdentifier(portName);
    if (portIdentifier.isCurrentlyOwned()) {
        return false;
    }

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

    this.serialPort = (SerialPort) commPort;
    this.serialPort.setSerialPortParams(baudrate, dataBits, stopBits, parity);

    this.in = this.serialPort.getInputStream();
    this.out = this.serialPort.getOutputStream();
    this.serialPort.addEventListener(new SerialPortEventListener() {

        @Override
        public void serialEvent(SerialPortEvent evt) {
            messageReceived();
        }
    });
    this.serialPort.notifyOnDataAvailable(true);

    this.started = true;

    return true;
}
项目:fpga-shovel-and-pickaxe    文件:FpgaSerial.java   
private void connect (String portName, int threshold) throws Exception
{
    CommPortIdentifier portIdentifier = CommPortIdentifier.getPortIdentifier(portName);
    if ( portIdentifier.isCurrentlyOwned() )
    {
        appender.append("Error: Port is currently in use");
    }
    else
    {
        //from RXTX examples
        CommPort commPort = portIdentifier.open(this.getClass().getName(),2000);

        if (commPort instanceof SerialPort)
        {
            //set up serial port
            serialPort = (SerialPort) commPort;
            serialPort.enableReceiveTimeout(threshold);
            serialPort.setSerialPortParams(115200,SerialPort.DATABITS_8,SerialPort.STOPBITS_2,SerialPort.PARITY_NONE);

            //start async reader
            sr = new SerialReader(serialPort, server);
            serailThread = new Thread(sr);
            serailThread.start();
        }
        else
        {
            appender.append("Error: Only serial ports are handled by this example.");
        }
    }     
}
项目:fpga-shovel-and-pickaxe    文件:Serial.java   
public void connect ( String portName, int threshold, int newLineAfter) throws Exception
{
    CommPortIdentifier portIdentifier = CommPortIdentifier.getPortIdentifier(portName);
    if ( portIdentifier.isCurrentlyOwned() )
    {
        System.out.println("Error: Port is currently in use");
    }
    else
    {
        CommPort commPort = portIdentifier.open(this.getClass().getName(),2000);

        if ( commPort instanceof SerialPort )
        {
            serialPort = (SerialPort) commPort;
            serialPort.enableReceiveTimeout(threshold);
            serialPort.setSerialPortParams(115200,SerialPort.DATABITS_8,SerialPort.STOPBITS_2,SerialPort.PARITY_NONE);

            sr = new SerialReader(serialPort, newLineAfter, System.currentTimeMillis());
            serialThread = new Thread(sr);
            serialThread.start();

        }
        else
        {
//                    arrayco
            System.out.println("Error: Only serial ports are handled by this example.");
        }
    }
}