Java 类gnu.io.SerialPort 实例源码

项目:uyariSistemi    文件:UI_uyari.java   
public void initialize() {
        System.setProperty("gnu.io.rxtx.SerialPorts", getComPortName());        
        CommPortIdentifier portId = null;        
        Enumeration portEnum = CommPortIdentifier.getPortIdentifiers();

        while (portEnum.hasMoreElements()) {
            CommPortIdentifier currPortId = (CommPortIdentifier) portEnum.nextElement();
            if(currPortId.getPortType() == CommPortIdentifier.PORT_SERIAL) {
                if (currPortId.getName().equals(txtComPortName.getText())) {
                    System.out.println(txtComPortName.getText());
                    portId = currPortId;
                    break;
                }
            }
        }
        if (portId == null) {

            JOptionPane.showMessageDialog(null," Portuna bağlı cihaz yok!","Hata",JOptionPane.ERROR_MESSAGE);
            System.out.println("Porta bağlı cihaz yok!");
            return;
        }
System.out.println(portId);
        try {
            serialPort = (SerialPort) portId.open(this.getClass().getName(), TIME_OUT);

            serialPort.setSerialPortParams(DATA_RATE, SerialPort.DATABITS_8, SerialPort.STOPBITS_1,
                    SerialPort.PARITY_NONE);

            input = new BufferedReader(new InputStreamReader(serialPort.getInputStream()));
            output = serialPort.getOutputStream();

            serialPort.addEventListener((SerialPortEventListener) this);
           serialPort.notifyOnDataAvailable(true);
        } catch (Exception e) {
            System.err.println(e.toString());
        }
    }
项目:openhab-hdl    文件:SerialParameters.java   
/**
 * Sets the number of data bits.
 *
 * @param databits the new number of data bits.
 */
public void setDatabits(int databits) throws IllegalArgumentException {
  if (!SerialParameterValidator.isDataBitsValid(databits)) {
    throw new IllegalArgumentException("Databit '" + databits + "' invalid");
  }

  switch (databits) {
  case 5:
    m_Databits = SerialPort.DATABITS_5;
    break;
  case 6:
    m_Databits = SerialPort.DATABITS_6;
    break;
  case 7:
    m_Databits = SerialPort.DATABITS_7;
    break;
  case 8:
    m_Databits = SerialPort.DATABITS_8;
    break;
  default:
    m_Databits = SerialPort.DATABITS_8;
    break;
  }
}
项目:openhab-hdl    文件:SerialParameters.java   
/**
 * Sets the number of stop bits.
 *
 * @param stopbits the new number of stop bits setting.
 */
public void setStopbits(double stopbits) throws IllegalArgumentException {
  if (!SerialParameterValidator.isStopbitsValid(stopbits)) {
    throw new IllegalArgumentException("stopbit value '" +
        stopbits + "' not valid");
  }

  if (stopbits == 1) {
    m_Stopbits = SerialPort.STOPBITS_1;
  } else if (stopbits == 1.5) {
    m_Stopbits = SerialPort.STOPBITS_1_5;
  } else if (stopbits == 2) {
    m_Stopbits = SerialPort.STOPBITS_2;
  } else {
    m_Stopbits = SerialPort.STOPBITS_1;
  }
}
项目:openhab-hdl    文件:SerialParameters.java   
/**
 * Sets the parity schema from the given
 * <tt>String</tt>.
 *
 * @param parity the new parity schema as <tt>String</tt>.
 */
public void setParity(String parity) throws IllegalArgumentException {
  parity = parity.toLowerCase();
  int intParity = SerialPort.PARITY_NONE;

  if (parity.equals("none") || parity.equals("n")) {
    intParity = SerialPort.PARITY_NONE;
  } else if (parity.equals("even") || parity.equals("e")) {
    intParity = SerialPort.PARITY_EVEN;
  } else if (parity.equals("odd") || parity.equals("o")) {
    intParity = SerialPort.PARITY_ODD;
  } else {
    throw new IllegalArgumentException(
        "unknown parity string '" + parity + "'");
  }

  setParity(intParity);
}
项目:opennmszh    文件:RxtxCommands.java   
private void removeListener(SerialPort port) {

    port.notifyOnRingIndicator( false );
    port.notifyOnParityError( false );
    port.notifyOnOverrunError( false );
    port.notifyOnOutputEmpty( false );
    port.notifyOnFramingError( false );
    port.notifyOnDSR( false );
    port.notifyOnDataAvailable( false );
    port.notifyOnCTS( false );
    port.notifyOnCarrierDetect( false );
    port.notifyOnBreakInterrupt( false );

    port.removeEventListener();

}
项目:opennmszh    文件:RxtxCommands.java   
/**
 * <p>stop</p>
 */
public void stop() {

    for( Pipe pipe : m_loggingPorts.values() )
    {
        pipe.stop();
    }

    m_loggingPorts.clear();

    System.out.print( "Closing " + m_openPorts.size() + " open comm ports... ");

    for( SerialPort port : m_openPorts.values() )
    {
        removeListener( port );
        port.close();
    }

    m_openPorts.clear();

    System.out.println("done.");

}
项目:openhab1-addons    文件:SerialParameters.java   
/**
 * Sets the number of data bits.
 *
 * @param databits the new number of data bits.
 */
public void setDatabits(int databits) throws IllegalArgumentException {
    if (!SerialParameterValidator.isDataBitsValid(databits)) {
        throw new IllegalArgumentException("Databit '" + databits + "' invalid");
    }

    switch (databits) {
        case 5:
            m_Databits = SerialPort.DATABITS_5;
            break;
        case 6:
            m_Databits = SerialPort.DATABITS_6;
            break;
        case 7:
            m_Databits = SerialPort.DATABITS_7;
            break;
        case 8:
            m_Databits = SerialPort.DATABITS_8;
            break;
        default:
            m_Databits = SerialPort.DATABITS_8;
            break;
    }
}
项目:openhab1-addons    文件:SerialParameters.java   
/**
 * Sets the number of stop bits.
 *
 * @param stopbits the new number of stop bits setting.
 */
public void setStopbits(double stopbits) throws IllegalArgumentException {
    if (!SerialParameterValidator.isStopbitsValid(stopbits)) {
        throw new IllegalArgumentException("stopbit value '" + stopbits + "' not valid");
    }

    if (stopbits == 1) {
        m_Stopbits = SerialPort.STOPBITS_1;
    } else if (stopbits == 1.5) {
        m_Stopbits = SerialPort.STOPBITS_1_5;
    } else if (stopbits == 2) {
        m_Stopbits = SerialPort.STOPBITS_2;
    } else {
        m_Stopbits = SerialPort.STOPBITS_1;
    }
}
项目:openhab1-addons    文件:SerialParameters.java   
/**
 * Sets the parity schema from the given
 * <tt>String</tt>.
 *
 * @param parity the new parity schema as <tt>String</tt>.
 */
public void setParity(String parity) throws IllegalArgumentException {
    parity = parity.toLowerCase();
    int intParity = SerialPort.PARITY_NONE;

    if (parity.equals("none") || parity.equals("n")) {
        intParity = SerialPort.PARITY_NONE;
    } else if (parity.equals("even") || parity.equals("e")) {
        intParity = SerialPort.PARITY_EVEN;
    } else if (parity.equals("odd") || parity.equals("o")) {
        intParity = SerialPort.PARITY_ODD;
    } else {
        throw new IllegalArgumentException("unknown parity string '" + parity + "'");
    }

    setParity(intParity);
}
项目:openhab1-addons    文件:CULSerialConfigFactory.java   
@Override
public CULConfig create(String deviceType, String deviceAddress, CULMode mode, Dictionary<String, ?> config)
        throws ConfigurationException {
    int baudRate = 9600;
    final String configuredBaudRate = (String) config.get(KEY_BAUDRATE);
    Integer tmpBaudRate = baudrateFromConfig(configuredBaudRate);
    if (tmpBaudRate != null) {
        baudRate = tmpBaudRate;
        logger.info("Update config, {} = {}", KEY_BAUDRATE, baudRate);
    }

    int parityMode = SerialPort.PARITY_EVEN;
    final String configuredParity = (String) config.get(KEY_PARITY);
    Integer parsedParityNumber = parityFromConfig(configuredParity);
    if (parsedParityNumber != null) {
        parityMode = parsedParityNumber;
        logger.info("Update config, {} = {} ({})", KEY_PARITY, convertParityModeToString(parityMode), parityMode);
    }

    return new CULSerialConfig(deviceType, deviceAddress, mode, baudRate, parityMode);
}
项目:OpenNMS    文件:RxtxCommands.java   
private void removeListener(SerialPort port) {

    port.notifyOnRingIndicator( false );
    port.notifyOnParityError( false );
    port.notifyOnOverrunError( false );
    port.notifyOnOutputEmpty( false );
    port.notifyOnFramingError( false );
    port.notifyOnDSR( false );
    port.notifyOnDataAvailable( false );
    port.notifyOnCTS( false );
    port.notifyOnCarrierDetect( false );
    port.notifyOnBreakInterrupt( false );

    port.removeEventListener();

}
项目:OpenNMS    文件:RxtxCommands.java   
/**
 * <p>stop</p>
 */
public void stop() {

    for( Pipe pipe : m_loggingPorts.values() )
    {
        pipe.stop();
    }

    m_loggingPorts.clear();

    System.out.print( "Closing " + m_openPorts.size() + " open comm ports... ");

    for( SerialPort port : m_openPorts.values() )
    {
        removeListener( port );
        port.close();
    }

    m_openPorts.clear();

    System.out.println("done.");

}
项目:SerialPortDemo    文件:SerialPortManager.java   
/**
 * 关闭串口
 * 
 * @param serialport
 *            待关闭的串口对象
 */
public static void closePort(SerialPort serialPort) {
    if (serialPort != null) {
        serialPort.close();
        serialPort = null;
    }
}
项目: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!");
        }
    }
}
项目:jaer    文件:StreamCommand.java   
/**
 * Creates a new instance for serial communication.
 *
 * @param listener receiving all messages/answers/errors asynchronously;
 *      there can only be one registered listener
 * @param baudRate for the serial line
 *
 * @see #setBaudRate
 */
public StreamCommand(StreamCommandListener listener,int baudRate)
{
    this.listener= listener;

    this.baudRate= baudRate;
    log.info("serial communication settings : "
            +baudRate+" baud, 8 data- 1 stop-bit, no flow control");
    dataBits= SerialPort.DATABITS_8;
    stopBits= SerialPort.STOPBITS_1;
    paritiyFlags= SerialPort.PARITY_NONE;

    port= null;
    is= null;
    os= null;

    synced= true;
    currentCommand= null;
    cmdPipe= new ArrayList<String>();
    cmdWatchdog= null;
    rtsWatchdog= null;
    message= new StreamCommandMessage();

    messageTimes= new ArrayList<Long>();
    cmdsSent= 0;
    cmdsTimeouts= 0;
}
项目:jaer    文件:HyperTerminal.java   
private void openPort() {
        appendString("opening " + portName + "...");
        try {

            CommPortIdentifier cpi = CommPortIdentifier.getPortIdentifier(portName);
            port = (SerialPort) cpi.open(portName, 1000);

            port.setSerialPortParams(
                    Integer.parseInt(baudText.getText()),
                    SerialPort.DATABITS_8,
                    SerialPort.STOPBITS_1,
                    SerialPort.PARITY_NONE);
//            port.setFlowControlMode(SerialPort.FLOWCONTROL_NONE);
            port.setFlowControlMode(SerialPort.FLOWCONTROL_RTSCTS_IN
                    | SerialPort.FLOWCONTROL_RTSCTS_OUT);
            port.setFlowControlMode(SerialPort.FLOWCONTROL_NONE);
            port.addEventListener(this);
            port.notifyOnDataAvailable(true);
            port.notifyOnCTS(true);

            isr = new InputStreamReader(port.getInputStream());
            os = port.getOutputStream();

        } catch (Exception e) {
            log.warning(e.toString());
            appendString(e.toString());
        } finally {

            updateFlags();
            appendString("done.\n");
        }
    }
项目:jaer    文件:HWP_RS232.java   
public synchronized int setBaudRate(int baudRate) {
    if (isOpen()) {

        setSingleCharFlushTransfer(false);
        if (baudRate == 3000000) {
            setSingleCharFlushTransfer(true);
        }
        try {       // set serial port parameters
            serialPort.setSerialPortParams(baudRate,
                    SerialPort.DATABITS_8,
                    SerialPort.STOPBITS_1,
                    SerialPort.PARITY_NONE);
        } catch (Exception e) {return(-2); }
        return(0);
    }
    return(-1);
}
项目: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();
}
项目: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);
}
项目: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.");
        }
    }
}
项目: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");
    }

}
项目: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();
    }
}
项目:micro-Blagajna    文件:CommStream.java   
private void init() {

        try {  
            if (m_out == null) {
                m_PortIdPrinter = CommPortIdentifier.getPortIdentifier(m_sPort); // Tomamos el puerto                   
                m_CommPortPrinter = m_PortIdPrinter.open("PORTID", 2000); // Abrimos el puerto       

                m_out = m_CommPortPrinter.getOutputStream(); // Tomamos el chorro de escritura   

                if (m_PortIdPrinter.getPortType() == CommPortIdentifier.PORT_SERIAL) {
                    ((SerialPort)m_CommPortPrinter).setSerialPortParams(9600, SerialPort.DATABITS_8, SerialPort.STOPBITS_1, SerialPort.PARITY_NONE); // Configuramos el puerto
                } else if (m_PortIdPrinter.getPortType() == CommPortIdentifier.PORT_PARALLEL) {
                    ((ParallelPort)m_CommPortPrinter).setMode(1);
                }
            }
        } catch (Exception e) {
            m_PortIdPrinter = null;
            m_CommPortPrinter = null;  
            m_out = null;
            m_in = null;
//        } catch (NoSuchPortException e) {
//        } catch (PortInUseException e) {
//        } catch (UnsupportedCommOperationException e) {
//        } catch (IOException e) {
        } 
    }
项目: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());
}
项目:modbus-mini    文件:SerialClientRxtx.java   
public static void main(String[] args) {

    ModbusClient mc = new ModbusClient();
    mc.setTransport(new RtuTransportRxtx("COM3", 9600, 8, SerialPort.PARITY_NONE, SerialPort.STOPBITS_1, 1000, 5));

    mc.InitReadHoldingsRequest(1, 0, 10);

    try {
        mc.execRequest();
        if (mc.getResult() == ModbusClient.RESULT_OK)
            for (int i = 0; i < mc.getResponseCount(); i++)
                System.out.println("HR" + i + "=" + mc.getResponseRegister(mc.getResponseAddress() + i, false));
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        mc.close();
    }

}
项目: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();
}
项目:optolink    文件:OptolinkInterface.java   
OptolinkInterface(String device, int timeout) throws Exception {

        // constructor with implicit open

        this.device = device;

        log.debug("Open TTY {} ...", this.device);
        portIdentifier = CommPortIdentifier.getPortIdentifier(this.device);

        if (portIdentifier.isCurrentlyOwned()) {
            log.error("TTY {} in use.", this.device);
            throw new IOException();
        }
        commPort = portIdentifier.open(this.getClass().getName(), timeout);
        if (commPort instanceof SerialPort) {
            SerialPort serialPort = (SerialPort) commPort;
            serialPort.setSerialPortParams(4800, SerialPort.DATABITS_8,
                    SerialPort.STOPBITS_2, SerialPort.PARITY_EVEN);

            input = serialPort.getInputStream();
            output = serialPort.getOutputStream();
            commPort.enableReceiveTimeout(timeout); // Reading Time-Out
        }
        log.debug("TTY {} opened", this.device);
    }
项目: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    文件:SerialParameters.java   
/**
 * Constructs a new <tt>SerialParameters</tt> instance with
 * default values: 9600 boud - 8N1 - ASCII.
 */
public SerialParameters() {
  m_PortName = "";
  m_BaudRate = 9600;
  m_FlowControlIn = SerialPort.FLOWCONTROL_NONE;
  m_FlowControlOut = SerialPort.FLOWCONTROL_NONE;
  m_Databits = SerialPort.DATABITS_8;
  m_Stopbits = SerialPort.STOPBITS_1;
  m_Parity = SerialPort.PARITY_NONE;
  m_Encoding = Modbus.DEFAULT_SERIAL_ENCODING;
  m_ReceiveTimeout = 500; //5 secs
  m_Echo = false;
}
项目:openhab-hdl    文件:SerialParameters.java   
/**
 * Constructs a new <tt>SerialParameters</tt> instance with
 * parameters obtained from a <tt>Properties</tt> instance.
 *
 * @param props  a <tt>Properties</tt> instance.
 * @param prefix a prefix for the properties keys if embedded into
 *               other properties.
 */
public SerialParameters(Properties props, String prefix) {
  if (prefix == null) {
    prefix = "";
  }
  setPortName(props.getProperty(prefix + "portName", ""));
  setBaudRate(props.getProperty(prefix + "baudRate", "" + 9600));
  setFlowControlIn(props.getProperty(prefix + "flowControlIn", "" + SerialPort.FLOWCONTROL_NONE));
  setFlowControlOut(props.getProperty(prefix + "flowControlOut", "" + SerialPort.FLOWCONTROL_NONE));
  setParity(props.getProperty(prefix + "parity", "" + SerialPort.PARITY_NONE));
  setDatabits(props.getProperty(prefix + "databits", "" + SerialPort.DATABITS_8));
  setStopbits(props.getProperty(prefix + "stopbits", "" + SerialPort.STOPBITS_1));
  setEncoding(props.getProperty(prefix + "encoding", Modbus.DEFAULT_SERIAL_ENCODING));
  setEcho("true".equals(props.getProperty(prefix + "echo")));
  setReceiveTimeout(props.getProperty(prefix + "timeout", "" + 500));
}
项目:openhab-hdl    文件:SerialParameters.java   
/**
 * Returns the number of data bits as <tt>String</tt>.
 *
 * @return the number of data bits as <tt>String</tt>.
 */
public String getDatabitsString() {
  switch (m_Databits) {
    case SerialPort.DATABITS_5:
      return "5";
    case SerialPort.DATABITS_6:
      return "6";
    case SerialPort.DATABITS_7:
      return "7";
    case SerialPort.DATABITS_8:
      return "8";
    default:
      return "8";
  }
}
项目:openhab-hdl    文件:SerialParameters.java   
/**
 * Returns the number of stop bits as <tt>String</tt>.
 *
 * @return the number of stop bits as <tt>String</tt>.
 */
public String getStopbitsString() {
  switch (m_Stopbits) {
    case SerialPort.STOPBITS_1:
      return "1";
    case SerialPort.STOPBITS_1_5:
      return "1.5";
    case SerialPort.STOPBITS_2:
      return "2";
    default:
      return "1";
  }
}