コード例 #1
0
  @Override
  public void connect(String portName) {
    CommPortIdentifier portIdentifier;
    try {
      portIdentifier = CommPortIdentifier.getPortIdentifier(portName);
      CommPort commPort = portIdentifier.open("TigerControlPanel", 2000);

      SerialPort serialPort = (SerialPort) commPort;
      serialPort.setSerialPortParams(
          2400, SerialPort.DATABITS_8, SerialPort.STOPBITS_1, SerialPort.PARITY_NONE);

      _sReader = new SerialReader(serialPort.getInputStream());
      serialPort.addEventListener(_sReader);
      serialPort.notifyOnDataAvailable(true);
      _sWriter = new SerialWriter(serialPort.getOutputStream());

    } catch (NoSuchPortException e) {
      DialogManager.showDialog(
          "Error de conexión", "No existe el puerto seleccionado", null, DialogType.ERROR);
    } catch (PortInUseException e) {
      DialogManager.showDialog(
          "Error de conexión",
          "El puerto seleccionado se encuentra en uso",
          null,
          DialogType.ERROR);
    } catch (Exception e) {
      DialogManager.showDialog(
          "Error de conexión", "Se ha producido un error de conexión", null, DialogType.ERROR);
    }
  }
コード例 #2
0
  public void initialize() {
    CommPortIdentifier portId = null;
    Enumeration portEnum = CommPortIdentifier.getPortIdentifiers();

    // First, Find an instance of serial port as set in PORT_NAMES.
    while (portEnum.hasMoreElements()) {
      CommPortIdentifier currPortId = (CommPortIdentifier) portEnum.nextElement();
      for (String portName : PORT_NAMES) {
        if (currPortId.getName().equals(portName)) {
          portId = currPortId;
          break;
        }
      }
    }
    if (portId == null) {
      System.out.println("Could not find COM port.");
      return;
    }

    try {
      serialPort = (SerialPort) portId.open(this.getClass().getName(), TIME_OUT);
      serialPort.setSerialPortParams(
          DATA_RATE, SerialPort.DATABITS_8, SerialPort.STOPBITS_1, SerialPort.PARITY_NONE);

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

      serialPort.addEventListener(this);
      serialPort.notifyOnDataAvailable(true);
    } catch (Exception e) {
      System.err.println(e.toString());
    }
  }
コード例 #3
0
ファイル: ComManager.java プロジェクト: hZix/callbyj
  /**
   * Start modem command manager.
   *
   * @throws Exception the exception
   */
  public void startModemCommandManager() throws Exception {
    CommPortIdentifier portIdentifier = CommPortIdentifier.getPortIdentifier(this.commandPortName);
    if (portIdentifier.isCurrentlyOwned()) {
      logger.error("Serial port " + this.commandPortName + " is currently in use");
    }
    CommPort commPort = portIdentifier.open(this.getClass().getName(), 2000);
    if (commPort instanceof SerialPort) {
      modemComPort = (SerialPort) commPort;
      modemComPort.setSerialPortParams(
          9600, SerialPort.DATABITS_8, SerialPort.STOPBITS_1, SerialPort.PARITY_NONE);

      modemComPort.notifyOnDataAvailable(true);

      commandInputStream = new DataInputStream(modemComPort.getInputStream());
      serialCommandReader = new SerialCommandReader(commandInputStream, this);
      modemComPort.addEventListener(serialCommandReader);

      commandOutputStream = new DataOutputStream(modemComPort.getOutputStream());

      this.sendCommandToModem(ATCommands.DISABLE_ECHO);
      this.sendCommandToModem(ATCommands.DISABLE_DIAGNOSTIC);
      this.sendCommandToModem(ATCommands.END_CALL);
      this.sendCommandToModem(ATCommands.CHECK_PIN);
    }
  }
コード例 #4
0
ファイル: GateServer.java プロジェクト: islanderz/uasmqtt
 private void initSerial()
     throws NoSuchPortException, PortInUseException, UnsupportedCommOperationException,
         IOException, TooManyListenersException {
   serialPort = connectSerial(serialDeviceName);
   serialPort.addEventListener(mavlinkServer);
   serialPort.notifyOnDataAvailable(true);
 }
コード例 #5
0
  /** Opens the Serial port with the baud and port_name given */
  public boolean OpenSerial(int baud, String port) {
    CommPortIdentifier portId = null;
    Enumeration portEnum = CommPortIdentifier.getPortIdentifiers();

    while (portEnum.hasMoreElements()) {
      CommPortIdentifier currPortId = (CommPortIdentifier) portEnum.nextElement();
      if (currPortId.getName().equals(port)) {
        portId = currPortId;
        break;
      }
    }

    if (portId == null) {
      System.err.println("Can not open serial port");
      return false;
    }

    try {
      serialPort = (SerialPort) portId.open(this.getClass().getName(), 2000);

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

      input = serialPort.getInputStream();
      output = serialPort.getOutputStream();

      serialPort.addEventListener(this);
      serialPort.notifyOnDataAvailable(true);
      Thread.sleep(1500);
    } catch (Exception e) {
      return false;
    }

    return true;
  }
コード例 #6
0
  private void write(byte[] data) {
    try {
      if (m_out == null) {
        m_PortIdPrinter =
            CommPortIdentifier.getPortIdentifier(
                m_sPortScale); // Tomamos el puerto
        m_CommPortPrinter =
            (SerialPort) m_PortIdPrinter.open("PORTID", 2000); // Abrimos el puerto

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

        m_CommPortPrinter.addEventListener(this);
        m_CommPortPrinter.notifyOnDataAvailable(true);

        m_CommPortPrinter.setSerialPortParams(
            4800,
            SerialPort.DATABITS_8,
            SerialPort.STOPBITS_1,
            SerialPort.PARITY_ODD); // Configuramos el puerto
      }
      m_out.write(data);
    } catch (NoSuchPortException e) {
      e.printStackTrace();
    } catch (PortInUseException e) {
      e.printStackTrace();
    } catch (UnsupportedCommOperationException e) {
      e.printStackTrace();
    } catch (TooManyListenersException e) {
      e.printStackTrace();
    } catch (IOException e) {
      e.printStackTrace();
    }
  }
コード例 #7
0
  @Override
  public void connect(final String commPort, final String commSpeed) {
    try {
      synchronized (_mutex) {
        _comPortId = CommPortIdentifier.getPortIdentifier(commPort);
        _serialPort = (SerialPort) _comPortId.open("ComPort", 2000);
        _inputStream = _serialPort.getInputStream();
        _outputStream = _serialPort.getOutputStream();
        _serialPort.addEventListener(new MySerialCommPortEventListener());
        _serialPort.notifyOnDataAvailable(true);
        final int speed = Integer.parseInt(commSpeed);
        _serialPort.setSerialPortParams(
            speed, SerialPort.DATABITS_8, SerialPort.STOPBITS_1, SerialPort.PARITY_NONE);
        _connected = true;
        Thread.sleep(3000);
        notifyConnectionStatus(true);

        _connectionThread.start();
      }
    } catch (Exception e) {
      e
          .printStackTrace(); // To change body of catch statement use File | Settings | File
                              // Templates.
    }
  }
コード例 #8
0
ファイル: ArduinoLED.java プロジェクト: odinzwei/wsArduino
 private void initialize() throws Exception {
   serialPort = (SerialPort) Util.getCOMMPort().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(this);
   serialPort.notifyOnDataAvailable(true);
 }
コード例 #9
0
ファイル: Communicator.java プロジェクト: kihyunHwang/MUX
 // starts the event listener that knows whenever data is available to be read
 // pre: an open serial port
 // post: an event listener for the serial port that knows when data is recieved
 public void initListener() {
   try {
     serialPort.addEventListener(this);
     serialPort.notifyOnDataAvailable(true);
   } catch (TooManyListenersException e) {
     logText = "Too many listeners. (" + e.toString() + ")";
     System.out.println(logText + "\n");
   }
 }
コード例 #10
0
  private void initEventListenersAndIO() {
    try {
      input = serialPort.getInputStream();
      output = serialPort.getOutputStream();
      serialPort.addEventListener(new SerialRxEvent(input, deviceRx));
      serialPort.notifyOnDataAvailable(true);

    } catch (TooManyListenersException e) {
      e.printStackTrace();
    } catch (IOException e) {
      e.printStackTrace();
    }
  }
コード例 #11
0
 public SerialPortToRobot(String fileName, SerialPortInfo portInfo)
     throws PortInUseException, UnsupportedCommOperationException, TooManyListenersException,
         IOException {
   serialPortFileName = fileName;
   identifier = SerialPorts.getPortIdentifier(serialPortFileName);
   if (identifier == null)
     throw new RuntimeException("Port identifier " + serialPortFileName + " not found");
   serialPort = (SerialPort) identifier.open("RLPark", 2000);
   serialPort.addEventListener(this);
   serialPort.setFlowControlMode(portInfo.flowControl);
   serialPort.setSerialPortParams(
       portInfo.rate, portInfo.databits, portInfo.stopbits, portInfo.parity);
   serialStreams = new SerialStreams(serialPort);
   setNotifiers();
 }
コード例 #12
0
  public void connect(String port) throws Exception {
    initialiseRobot();

    CommPortIdentifier cpi = (CommPortIdentifier) portMap.get(port);
    CommPort cp = cpi.open(this.getClass().getName(), 2000);
    serialPort = (SerialPort) cp;
    // init is and os
    is = serialPort.getInputStream();
    os = serialPort.getOutputStream();

    // add listeners

    serialPort.addEventListener(this);
    serialPort.notifyOnDataAvailable(true);
  }
コード例 #13
0
  public SerialManager(SerialPortEventListener listener) {
    // the next line is for Raspberry Pi and
    // gets us into the while loop and was suggested here was suggested
    // http://www.raspberrypi.org/phpBB3/viewtopic.php?f=81&t=32186
    // System.setProperty("gnu.io.rxtx.SerialPorts", "/dev/ttyACM0");

    System.setProperty("gnu.io.rxtx.SerialPorts", "/dev/ttyACM0");

    CommPortIdentifier portId = null;
    Enumeration portEnum = CommPortIdentifier.getPortIdentifiers();

    // First, Find an instance of serial port as set in PORT_NAMES.
    while (portEnum.hasMoreElements()) {
      CommPortIdentifier currPortId = (CommPortIdentifier) portEnum.nextElement();
      System.out.println(currPortId.getName());
      for (String portName : PORT_NAMES) {
        if (currPortId.getName().equals(portName)) {
          portId = currPortId;
          break;
        }
      }
    }
    if (portId == null) {
      System.out.println("Could not find COM port.");
      return;
    }

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

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

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

      // add event listeners
      serialPort.addEventListener(listener);
      serialPort.notifyOnDataAvailable(true);
    } catch (Exception e) {
      System.err.println(e.toString());
    }
  }
コード例 #14
0
ファイル: IntRSModule.java プロジェクト: RWESmart/openhab
  @Override
  protected CommunicationChannel connect() {
    logger.info("Connecting to INT-RS module at {}", this.port);

    try {
      CommPortIdentifier portIdentifier = CommPortIdentifier.getPortIdentifier(this.port);
      SerialPort serialPort = portIdentifier.open("org.openhab.binding.satel", 2000);
      serialPort.setSerialPortParams(
          19200, SerialPort.DATABITS_8, SerialPort.STOPBITS_1, SerialPort.PARITY_NONE);
      serialPort.enableReceiveTimeout(this.getTimeout());
      // RXTX serial port library causes high CPU load
      // Start event listener, which will just sleep and slow down event
      // loop
      serialPort.addEventListener(
          new SerialPortEventListener() {
            @Override
            public void serialEvent(SerialPortEvent ev) {
              try {
                logger.trace("RXTX library CPU load workaround, sleep forever");
                Thread.sleep(Long.MAX_VALUE);
              } catch (InterruptedException e) {
              }
            }
          });
      serialPort.notifyOnDataAvailable(true);

      logger.info("INT-RS module connected successfuly");
      return new SerialCommunicationChannel(serialPort);

    } catch (NoSuchPortException e) {
      logger.error("Port {} does not exist", this.port);
    } catch (PortInUseException e) {
      logger.error("Port {} in use.", this.port);
    } catch (UnsupportedCommOperationException e) {
      logger.error("Unsupported comm operation on port {}.", this.port);
    } catch (TooManyListenersException e) {
      logger.error("Too many listeners on port {}.", this.port);
    }

    return null;
  }
コード例 #15
0
  public void initialize() {
    CommPortIdentifier portId = null;
    Enumeration portEnum = CommPortIdentifier.getPortIdentifiers();

    // Encontra uma instância da porta serial definida em PORT_NAMES
    while (portEnum.hasMoreElements()) {
      CommPortIdentifier currentPortId = (CommPortIdentifier) portEnum.nextElement();
      for (String portName : PORT_NAMES) {
        if (currentPortId.getName().equals(portName)) {
          portId = currentPortId;
          break;
        }
      }
    }
    if (portId == null) {
      System.out.println("Não foi possível encontrar uma porta COM");
      return;
    }

    try {
      // abre a porta serial e usa o nome da classe appName
      serialPort = (SerialPort) portId.open(this.getClass().getName(), TIME_OUT);

      // define os parâmetros da porta
      serialPort.setSerialPortParams(
          DATA_RATE, SerialPort.DATABITS_8, SerialPort.STOPBITS_1, SerialPort.PARITY_NONE);

      // abre a transferência
      input = new BufferedReader(new InputStreamReader(serialPort.getInputStream()));
      output = serialPort.getOutputStream();
      char ch = 1;
      output.write(ch);

      // adiciona ouvintes
      serialPort.addEventListener(this);
      serialPort.notifyOnDataAvailable(true);
    } catch (Exception ex) {
      System.err.println(ex.toString());
    }
  }
コード例 #16
0
  public void initialize() {
    CommPortIdentifier portId = null;
    Enumeration portEnum = CommPortIdentifier.getPortIdentifiers();

    // iterate through, looking for the port
    while (portEnum.hasMoreElements()) {
      CommPortIdentifier currPortId = (CommPortIdentifier) portEnum.nextElement();
      for (String portName : PORT_NAMES) {
        if (currPortId.getName().equals(portName)) {
          portId = currPortId;
          break;
        }
      }
    }

    if (portId == null) {
      System.out.println("Could not find COM port.");
      return;
    }

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

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

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

      // add event listeners
      serialPort.addEventListener(this);
      serialPort.notifyOnDataAvailable(true);
    } catch (Exception e) {
      System.err.println(e.toString());
    }
  }
コード例 #17
0
  @Override
  public void startPolling() {
    if (!_usable || !_isQuestionSupported) {
      return;
    }

    _votingStartTime = Calendar.getInstance().getTimeInMillis();
    try {
      _comPort = _comPortIdent.open(this.getClass().getName(), 2000);

      if (_comPort instanceof SerialPort) {
        _serialPort = (SerialPort) _comPort;
        _serialPort.setSerialPortParams(
            _baudrate, SerialPort.DATABITS_8, SerialPort.STOPBITS_1, SerialPort.PARITY_NONE);

        InputStream in = _serialPort.getInputStream();

        _serialReader = new SerialReader(in, _injectable, _votingStartTime);

        _serialPort.addEventListener(_serialReader);
        _serialPort.notifyOnDataAvailable(true);
      }
    } catch (PortInUseException e) {
      reportToDelegate(e);
      PLog.error("Port is alreay in use by " + e.currentOwner, e);
    } catch (UnsupportedCommOperationException e) {
      reportToDelegate(e);
      PLog.error("Error on setting SerialPort params", e);
    } catch (IOException e) {
      reportToDelegate(e);
      PLog.error("Error while getting Inputstream", e);
    } catch (TooManyListenersException e) {
      reportToDelegate(e);
      PLog.error("Error trying to add new EventListener", e);
    }
  }
コード例 #18
0
ファイル: SerialConnection.java プロジェクト: sdhibit/openhab
  /**
   * Opens the communication port.
   *
   * @throws Exception if an error occurs.
   */
  public void open() throws Exception {

    // If this is Linux then first of all we need to check that
    // device file exists. Otherwise call to m_PortIdentifyer.open()
    // method will crash JVM.
    // It is ugly patch but it is too late...
    if (SystemUtils.IS_OS_LINUX) {
      File portDevFile = new File(m_Parameters.getPortName());

      if (!portDevFile.exists()) {
        throw new Exception(
            "Modbus serial device " + m_Parameters.getPortName() + " doesn't exist!");
      }
    }

    // 1. obtain a CommPortIdentifier instance
    try {
      m_PortIdentifyer = CommPortIdentifier.getPortIdentifier(m_Parameters.getPortName());
    } catch (NoSuchPortException e) {
      final String errMsg =
          "Could not get port identifier, maybe insufficient permissions. " + e.getMessage();
      logger.debug(errMsg);
      throw new Exception(errMsg);
    }
    logger.trace("Got Port Identifier");

    // 2. open the port, wait for given timeout
    try {
      m_SerialPort = (SerialPort) m_PortIdentifyer.open("Modbus Serial Master", 30000);
    } catch (PortInUseException e) {
      logger.debug("open port failed: " + e.getMessage());

      throw new Exception(e.getMessage());
    }
    logger.trace("Got Serial Port");

    // 3. set the parameters
    try {
      setConnectionParameters();
    } catch (Exception e) {
      // ensure it is closed
      m_SerialPort.close();
      logger.debug("parameter setup failed: " + e.getMessage());
      throw e;
    }

    if (Modbus.SERIAL_ENCODING_ASCII.equals(m_Parameters.getEncoding())) {
      m_Transport = new ModbusASCIITransport();
    } else if (Modbus.SERIAL_ENCODING_RTU.equals(m_Parameters.getEncoding())) {
      m_Transport = new ModbusRTUTransport();
      setReceiveTimeout(m_Parameters.getReceiveTimeout()); // just here for the moment.
    } else if (Modbus.SERIAL_ENCODING_BIN.equals(m_Parameters.getEncoding())) {
      m_Transport = new ModbusBINTransport();
    }
    m_Transport.setEcho(m_Parameters.isEcho());

    // Open the input and output streams for the connection. If they won't
    // open, close the port before throwing an exception.
    try {
      m_SerialIn = m_SerialPort.getInputStream();
      m_Transport.setCommPort(m_SerialPort);
      //       m_Transport.prepareStreams(m_SerialIn,
      //                                  m_SerialPort.getOutputStream());
    } catch (IOException e) {
      m_SerialPort.close();
      logger.debug(e.getMessage());

      throw new Exception("Error opening i/o streams");
    }
    logger.trace("i/o Streams prepared");

    // Add this object as an event listener for the serial port.
    try {
      m_SerialPort.addEventListener(this);
    } catch (TooManyListenersException e) {
      m_SerialPort.close();
      final String errMsg = "too many listeners added";
      logger.debug("{}: {}", errMsg, e.getMessage());
      throw new Exception(errMsg);
    }

    // Set notifyOnBreakInterrup to allow event driven break handling.
    m_SerialPort.notifyOnBreakInterrupt(true);

    m_Open = true;
  } // open
コード例 #19
0
ファイル: UrtsiDevice.java プロジェクト: RWESmart/openhab
  /**
   * Sends a string to the serial port of this device. The writing of the msg is executed
   * synchronized, so it's guaranteed that the device doesn't get multiple messages concurrently.
   *
   * @param msg the string to send
   * @return true, if the message has been transmitted successfully, otherwise false.
   */
  synchronized boolean writeString(final String msg) {
    logger.debug("Writing '{}' to serial port {}", msg, port);

    final long earliestNextExecution = lastCommandTime + interval;
    while (earliestNextExecution > System.currentTimeMillis()) {
      try {
        Thread.sleep(100);
      } catch (InterruptedException ex) {
        return false;
      }
    }
    try {
      final List<Boolean> listenerResult = new ArrayList<Boolean>();
      serialPort.addEventListener(
          new SerialPortEventListener() {
            @Override
            public void serialEvent(SerialPortEvent event) {
              if (event.getEventType() == SerialPortEvent.DATA_AVAILABLE) {
                // we get here if data has been received
                final StringBuilder sb = new StringBuilder();
                final byte[] readBuffer = new byte[20];
                try {
                  do {
                    // read data from serial device
                    while (inputStream.available() > 0) {
                      final int bytes = inputStream.read(readBuffer);
                      sb.append(new String(readBuffer, 0, bytes));
                    }
                    try {
                      // add wait states around reading the stream, so that interrupted
                      // transmissions are
                      // merged
                      Thread.sleep(100);
                    } catch (InterruptedException e) {
                      // ignore interruption
                    }
                  } while (inputStream.available() > 0);
                  final String result = sb.toString();
                  if (result.equals(msg)) {
                    listenerResult.add(true);
                  }
                } catch (IOException e) {
                  logger.debug("Error receiving data on serial port {}: {}", port, e.getMessage());
                }
              }
            }
          });
      serialPort.notifyOnDataAvailable(true);
      outputStream.write(msg.getBytes());
      outputStream.flush();
      lastCommandTime = System.currentTimeMillis();
      final long timeout = lastCommandTime + 1000;
      while (listenerResult.isEmpty() && System.currentTimeMillis() < timeout) {
        // Waiting for response
        Thread.sleep(100);
      }
      return !listenerResult.isEmpty();
    } catch (Exception e) {
      logger.error("Error writing '{}' to serial port {}: {}", msg, port, e.getMessage());
    } finally {
      serialPort.removeEventListener();
    }
    return false;
  }
コード例 #20
0
  public Serial(String iname, int irate,
                 char iparity, int idatabits, float istopbits)
  throws SerialException {
    //if (port != null) port.close();
    //this.parent = parent;
    //parent.attach(this);

    this.rate = irate;
    
    parity = SerialPort.PARITY_NONE;
    if (iparity == 'E') parity = SerialPort.PARITY_EVEN;
    if (iparity == 'O') parity = SerialPort.PARITY_ODD;

    this.databits = idatabits;

    stopbits = SerialPort.STOPBITS_1;
    if (istopbits == 1.5f) stopbits = SerialPort.STOPBITS_1_5;
    if (istopbits == 2) stopbits = SerialPort.STOPBITS_2;

    try {
      port = null;
      Enumeration portList = CommPortIdentifier.getPortIdentifiers();
      while (portList.hasMoreElements()) {
        CommPortIdentifier portId =
          (CommPortIdentifier) portList.nextElement();

        if (portId.getPortType() == CommPortIdentifier.PORT_SERIAL) {
          //System.out.println("found " + portId.getName());
          if (portId.getName().equals(iname)) {
            //System.out.println("looking for "+iname);
            port = (SerialPort)portId.open("serial madness", 2000);
           
            input = port.getInputStream();
            output = port.getOutputStream();
            port.setSerialPortParams(rate, databits, stopbits, parity);
            port.addEventListener(this);
            port.notifyOnDataAvailable(true);
            //port.setFlowControlMode(SerialPort.FLOWCONTROL_XONXOFF_IN | SerialPort.FLOWCONTROL_XONXOFF_OUT);
            //port.setFlowControlMode(SerialPort.FLOWCONTROL_RTSCTS_IN | SerialPort.FLOWCONTROL_RTSCTS_OUT);
            port.setFlowControlMode(SerialPort.FLOWCONTROL_NONE);
            
           // System.out.println("[Serial]opening, ready to roll");
          }
        }
      }
    } catch (PortInUseException e) {
      throw new SerialException(
        I18n.format(
          _("Serial port ''{0}'' already in use. Try quiting any programs that may be using it."),
          iname
        )
      );
    } catch (Exception e) {
      throw new SerialException(
        I18n.format(
          _("Error opening serial port ''{0}''."),
          iname
        ),
        e
      );
//      //errorMessage("<init>", e);
//      //exception = e;
//      //e.printStackTrace();
    }
    
    if (port == null) {
    	System.out.println("Port is missing");
    }
  }
コード例 #21
0
 public void addSerialPortEventListener(SerialPortEventListener serialPortEventListener)
     throws TooManyListenersException {
   mSerialPort.addEventListener(serialPortEventListener);
 }
コード例 #22
0
ファイル: SerialDevice.java プロジェクト: RWESmart/openhab
  /**
   * Initialize this device and open the serial port
   *
   * @throws InitializationException if port can not be opened
   */
  @SuppressWarnings("rawtypes")
  public void initialize() throws InitializationException {
    // parse ports and if the default port is found, initialized the reader
    Enumeration portList = CommPortIdentifier.getPortIdentifiers();
    while (portList.hasMoreElements()) {
      CommPortIdentifier id = (CommPortIdentifier) portList.nextElement();
      if (id.getPortType() == CommPortIdentifier.PORT_SERIAL) {
        if (id.getName().equals(port)) {
          logger.debug("Serial port '{}' has been found.", port);
          portId = id;
        }
      }
    }
    if (portId != null) {
      // initialize serial port
      try {
        serialPort = portId.open("openHAB", 2000);
      } catch (PortInUseException e) {
        throw new InitializationException(e);
      }

      try {
        inputStream = serialPort.getInputStream();
      } catch (IOException e) {
        throw new InitializationException(e);
      }

      try {
        serialPort.addEventListener(this);
      } catch (TooManyListenersException e) {
        throw new InitializationException(e);
      }

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

      try {
        // set port parameters
        serialPort.setSerialPortParams(
            baud, SerialPort.DATABITS_8, SerialPort.STOPBITS_1, SerialPort.PARITY_NONE);
      } catch (UnsupportedCommOperationException e) {
        throw new InitializationException(e);
      }

      try {
        // get the output stream
        outputStream = serialPort.getOutputStream();
      } catch (IOException e) {
        throw new InitializationException(e);
      }
    } else {
      StringBuilder sb = new StringBuilder();
      portList = CommPortIdentifier.getPortIdentifiers();
      while (portList.hasMoreElements()) {
        CommPortIdentifier id = (CommPortIdentifier) portList.nextElement();
        if (id.getPortType() == CommPortIdentifier.PORT_SERIAL) {
          sb.append(id.getName() + "\n");
        }
      }
      throw new InitializationException(
          "Serial port '" + port + "' could not be found. Available ports are:\n" + sb.toString());
    }
  }
コード例 #23
0
ファイル: DrawbotGUI.java プロジェクト: bertbalcaen/DrawBot
  // open a serial connection to a device.  We won't know it's the robot until
  public int OpenPort(String portName) {
    if (portOpened && portName.equals(recentPort)) return 0;

    ClosePort();

    Log("<font color='green'>Connecting to " + portName + "...</font>\n");

    // find the port
    try {
      portIdentifier = CommPortIdentifier.getPortIdentifier(portName);
    } catch (Exception e) {
      Log("<span style='color:red'>Ports could not be identified:" + e.getMessage() + "</span>\n");
      e.printStackTrace();
      return 1;
    }

    if (portIdentifier.isCurrentlyOwned()) {
      Log(
          "<span style='color:red'>Error: Another program is currently using this port."
              + "</span>\n");
      return 2;
    }

    // open the port
    try {
      commPort = portIdentifier.open("DrawbotGUI", 2000);
    } catch (Exception e) {
      Log("Port could not be opened:" + e.getMessage() + NL);
      e.printStackTrace();
      return 3;
    }

    if ((commPort instanceof SerialPort) == false) {
      Log("<span style='color:red'>Only serial ports are handled by this example." + "</span>\n");
      return 4;
    }

    // set the port parameters (like baud rate)
    serialPort = (SerialPort) commPort;
    try {
      serialPort.setSerialPortParams(
          BAUD_RATE, SerialPort.DATABITS_8, SerialPort.STOPBITS_1, SerialPort.PARITY_NONE);
    } catch (Exception e) {
      Log("<span style='color:red'>Port could not be configured:" + e.getMessage() + "</span>\n");
      return 5;
    }

    try {
      in = serialPort.getInputStream();
      out = serialPort.getOutputStream();
    } catch (Exception e) {
      Log("<span style='color:red'>Streams could not be opened:" + e.getMessage() + "</span>\n");
      return 6;
    }

    try {
      serialPort.addEventListener(this);
      serialPort.notifyOnDataAvailable(true);
    } catch (TooManyListenersException e) {
      Log("<span style='color:red'>Streams could not be opened:" + e.getMessage() + "</span>\n");
      return 7;
    }

    Log("<span style='green'>Opened.</span>\n");
    SetRecentPort(portName);
    portOpened = true;
    UpdateMenuBar();

    return 0;
  }