コード例 #1
0
ファイル: TestSer.java プロジェクト: sherckuith/jop
  public TestSer(String port) {

    try {
      portId = CommPortIdentifier.getPortIdentifier(port);
      serialPort = (SerialPort) portId.open("TestSer", 2000);
      is = serialPort.getInputStream();
      os = serialPort.getOutputStream();
      /*
      			serialPort.addEventListener(this);
      			serialPort.notifyOnDataAvailable(true);
      */

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

      serialPort.setFlowControlMode(
          SerialPort.FLOWCONTROL_RTSCTS_OUT | SerialPort.FLOWCONTROL_RTSCTS_IN);

      serialPort.enableReceiveTimeout(TIMEOUT);
      //			serialPort.enableReceiveThreshold(4);

    } catch (Exception e) {
      System.out.println(e.getMessage());
      System.exit(-1);
    }
  }
コード例 #2
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;
  }
コード例 #3
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);
    }
  }
コード例 #4
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);
    }
  }
コード例 #5
0
ファイル: UrtsiDevice.java プロジェクト: RWESmart/openhab
 /**
  * Initialize this device and open the serial port.
  *
  * @throws InitializationException if port can not be opened
  */
 void initialize() throws InitializationException {
   try {
     // parse ports and if the default port is found, initialized the reader
     portId = CommPortIdentifier.getPortIdentifier(port);
     // initialize serial port
     serialPort = portId.open("openHAB", 2000);
     // set port parameters
     serialPort.setSerialPortParams(baud, databits, stopbit, parity);
     inputStream = serialPort.getInputStream();
     outputStream = serialPort.getOutputStream();
   } catch (UnsupportedCommOperationException e) {
     throw new InitializationException(e);
   } catch (IOException e) {
     throw new InitializationException(e);
   } catch (PortInUseException e) {
     throw new InitializationException(e);
   } catch (NoSuchPortException e) {
     // enumerate the port identifiers in the exception to be helpful
     final StringBuilder sb = new StringBuilder();
     @SuppressWarnings("unchecked")
     Enumeration<CommPortIdentifier> portList = CommPortIdentifier.getPortIdentifiers();
     while (portList.hasMoreElements()) {
       final CommPortIdentifier id = 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());
   }
 }
コード例 #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
  public void initialize() {
    Enumeration portNum = CommPortIdentifier.getPortIdentifiers();

    while (portNum.hasMoreElements()) {
      CommPortIdentifier currId = (CommPortIdentifier) portNum.nextElement();
      for (String portNames : PORT_NAMES) {
        if (currId.getName().equals(portNames)) {
          portID = currId;
          break;
        }
      }
    }

    if (portID == null) {
      JOptionPane.showMessageDialog(
          null, "Connect Device!", "Please Connect Device!", JOptionPane.ERROR_MESSAGE);
      System.exit(0);
    }

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

      output = serialPort.getOutputStream();
      in = serialPort.getInputStream();
      printStream = new PrintStream(output);
      inputStream = new BufferedInputStream(in);

    } catch (Exception e) {
      e.getStackTrace();
    }
  }
コード例 #8
0
ファイル: SerialDevice.java プロジェクト: EaseTech/things-api
  public void open() throws IOException {
    try {
      if (portName != null) {
        portId = CommPortIdentifier.getPortIdentifier(portName);
      }
      if (portId == null) {
        throw new IOException("Invalid port " + portName);
      }
      serialPort = (SerialPort) portId.open(portId.getName(), baudRate);
      if (portId == null) {
        throw new IOException("Invalid port " + portName);
      }

      serialPort.setSerialPortParams(
          baudRate, SerialPort.DATABITS_8, SerialPort.STOPBITS_1, SerialPort.PARITY_NONE);
      serialPort.notifyOnOutputEmpty(true);
      outputStream = serialPort.getOutputStream();
      inputStream = serialPort.getInputStream();
      Logger.getLogger(SerialDevice.class.getName())
          .log(Level.INFO, "Connection Stabilished with {0}", serialPort.getName());
    } catch (Exception e) {
      e.printStackTrace();
      Logger.getLogger(SerialDevice.class.getName())
          .log(Level.SEVERE, "Could not init the device on " + serialPort.getName(), e);
      serialPort.close();
    }
  }
コード例 #9
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.
    }
  }
コード例 #10
0
ファイル: TanitaInstrument.java プロジェクト: emorency/onyx
  /** Establish the connection with the device connected to the serial port. */
  public void setupSerialPort() {

    try {

      // If port already open, close it.
      if (serialPort != null) {
        serialPort.close();
        serialPort = null;
      }

      // Initialize serial port attributes.
      log.info("Fetching communication port {}", getTanitaCommPort());
      CommPortIdentifier wPortId = CommPortIdentifier.getPortIdentifier(getTanitaCommPort());

      log.info("Opening communication port {}", getTanitaCommPort());
      serialPort = (SerialPort) wPortId.open(portOwnerName, 2000);

      // Make sure the port is "Clear To Send"
      serialPort.setSerialPortParams(baudeRate, dataLength, stopBit, parity);
      bufferedReader = new BufferedReader(new InputStreamReader(serialPort.getInputStream()));

      portIsAvailable = checkIfPortIsAvailable();

    } catch (Exception wCouldNotAccessSerialPort) {
      portIsAvailable = false;
      log.warn("Could not access the specified serial port.");
    }
  }
コード例 #11
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());
    }
  }
コード例 #12
0
ファイル: SerialDriverAdapter.java プロジェクト: KenC57/JMRI
  public String openPort(String portName, String appName) {
    // open the port, check ability to set moderators
    try {
      // get and open the primary port
      CommPortIdentifier portID = CommPortIdentifier.getPortIdentifier(portName);
      try {
        activeSerialPort = (SerialPort) portID.open(appName, 2000); // name of program, msec to wait
      } catch (PortInUseException p) {
        return handlePortBusy(p, portName, log);
      }

      // try to set it for communication via SerialDriver
      try {
        activeSerialPort.setSerialPortParams(
            9600, SerialPort.DATABITS_8, SerialPort.STOPBITS_1, SerialPort.PARITY_NONE);
      } catch (gnu.io.UnsupportedCommOperationException e) {
        log.error("Cannot set serial parameters on port " + portName + ": " + e.getMessage());
        return "Cannot set serial parameters on port " + portName + ": " + e.getMessage();
      }

      // set RTS high, DTR high
      activeSerialPort.setRTS(true); // not connected in some serial ports and adapters
      activeSerialPort.setDTR(true); // pin 1 in DIN8; on main connector, this is DTR

      // disable flow control; hardware lines used for signaling, XON/XOFF might appear in data
      activeSerialPort.setFlowControlMode(0);
      activeSerialPort.enableReceiveTimeout(50); // 50 mSec timeout before sending chars

      // set timeout
      // activeSerialPort.enableReceiveTimeout(1000);
      log.debug(
          "Serial timeout was observed as: "
              + activeSerialPort.getReceiveTimeout()
              + " "
              + activeSerialPort.isReceiveTimeoutEnabled());

      // get and save stream
      serialStream = activeSerialPort.getInputStream();

      // purge contents, if any
      purgeStream(serialStream);

      // report status
      if (log.isInfoEnabled()) {
        log.info(
            "Wangrow " + portName + " port opened at " + activeSerialPort.getBaudRate() + " baud");
      }
      opened = true;

    } catch (gnu.io.NoSuchPortException p) {
      return handlePortNotFound(p, portName, log);
    } catch (Exception ex) {
      log.error("Unexpected exception while opening port " + portName + " trace follows: " + ex);
      ex.printStackTrace();
      return "Unexpected error while opening port " + portName + ": " + ex;
    }

    return null; // indicates OK return
  }
コード例 #13
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);
 }
コード例 #14
0
  public synchronized void serialEvent(SerialPortEvent oEvent) {

    try {
      switch (oEvent.getEventType()) {
        case SerialPortEvent.DATA_AVAILABLE:
          if (input == null) {
            System.out.println("here11");
            input = new BufferedReader(new InputStreamReader(serialPort.getInputStream()));
          }
          String inputLine = input.readLine();
          // System.out.println(input.readLine().trim());
          if (inputLine.equals("")) {
          } else {
            String url = "jdbc:mysql://localhost/secureplanet";
            Properties prop = new Properties();
            prop.setProperty("user", "root");
            prop.setProperty("password", "toor");
            Driver d = new com.mysql.jdbc.Driver();
            Connection conn = d.connect(url, prop);
            if (conn == null) {
              System.out.println("connection failed");
              return;
            }
            DatabaseMetaData dm = conn.getMetaData();
            String dbversion = dm.getDatabaseProductVersion();
            String dbname = dm.getDatabaseProductName();
            System.out.println("name:" + dbname);
            System.out.println("version:" + dbversion);

            String rfidtoken = inputLine.trim();
            Statement stmt = conn.createStatement();

            Double lat = 17.4416;
            Double lng = 78.3826;

            String sql =
                "INSERT INTO smarttracking "
                    + "VALUES ('"
                    + rfidtoken
                    + "','"
                    + lat
                    + "','"
                    + lng
                    + "')";
            stmt.executeUpdate(sql);
          }
          break;

        default:
          break;
      }
    } catch (Exception e) {
      e.printStackTrace();
    }
  }
コード例 #15
0
  /*
   * Open the port, wait for chip init
   */
  public static int initialize(String portName) {
    System.out.println("Enumerating serial ports:");
    portList = CommPortIdentifier.getPortIdentifiers();
    while (portList.hasMoreElements()) {
      portId = (CommPortIdentifier) portList.nextElement();
      if (portId.getPortType() == CommPortIdentifier.PORT_SERIAL) {
        // DDT
        System.out.println(portId.getName());

        if (portId.getName().equals(portName)) {
          System.out.println("Name match on port " + portName);
          // Init the port, matches name we were given
          try {
            serialPort = (SerialPort) portId.open("tx-skeleton", 64);
          } catch (PortInUseException e) {
            e.printStackTrace();
            System.out.println("Port in use!");
            return (4);
          }
          try {
            inputStream = serialPort.getInputStream();
            outputStream = serialPort.getOutputStream();
          } catch (IOException e) {
            System.out.println("Unable to connect to I/O streams");
            return (3);
          }

          try {
            System.out.println("Initializing ADXL202 board...");
            // 38400N81
            serialPort.setSerialPortParams(
                38400, SerialPort.DATABITS_8, SerialPort.STOPBITS_1, SerialPort.PARITY_NONE);

            // ADXL202 is powered via DTR line, so set it on
            serialPort.setDTR(true);

            try {
              // Wait a couple of seconds for chip to initialize (blinking LED)
              Thread.sleep(2000);
            } catch (InterruptedException ie) {
            }

          } catch (UnsupportedCommOperationException e) {
            System.out.println("Unable to configure serial port!");
            return (1);
          }
          return (0);
        }
      }
    }

    return (1);
  }
コード例 #16
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();
    }
  }
コード例 #17
0
  public boolean oeffneSerialPort() {
    Boolean foundPort = false;
    if (serialPortGeoeffnet != false) {
      System.out.println("Serialport bereits geöffnet");
      return false;
    }
    System.out.println("Öffne Serialport");
    enumComm = CommPortIdentifier.getPortIdentifiers();
    while (enumComm.hasMoreElements()) {
      serialPortId = (CommPortIdentifier) enumComm.nextElement();
      if (portName.contentEquals(serialPortId.getName())) {
        foundPort = true;
        break;
      }
    }
    if (foundPort != true) {
      System.out.println("Serialport nicht gefunden: " + portName);
      return false;
    }
    try {
      serialPort = (SerialPort) serialPortId.open("Öffnen und Senden", 500);
    } catch (PortInUseException e) {
      System.out.println("Port belegt");
    }

    try {
      outputStream = serialPort.getOutputStream();
    } catch (IOException e) {
      System.out.println("Keinen Zugriff auf OutputStream");
    }

    try {
      inputStream = serialPort.getInputStream();
    } catch (IOException e) {
      System.out.println("Keinen Zugriff auf InputStream");
    }

    serialPort.notifyOnDataAvailable(true);
    try {
      serialPort.setSerialPortParams(baudrate, dataBits, stopBits, parity);
    } catch (UnsupportedCommOperationException e) {
      System.out.println("Konnte Schnittstellen-Paramter nicht setzen");
    }

    reader = new BufferedReader(new InputStreamReader(inputStream));
    writer = new BufferedWriter(new OutputStreamWriter(outputStream));
    serialPortGeoeffnet = true;
    return true;
  }
コード例 #18
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);
  }
コード例 #19
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());
    }
  }
コード例 #20
0
ファイル: Communicator.java プロジェクト: kihyunHwang/MUX
  // open the input and output streams
  // pre: an open port
  // post: initialized intput and output streams for use to communicate data
  public boolean initIOStream() {
    // return value for whather opening the streams is successful or not
    boolean successful = false;

    try {
      input = serialPort.getInputStream();
      output = serialPort.getOutputStream();
      //            writeData(0, 0);

      successful = true;
      return successful;
    } catch (IOException e) {
      logText = "I/O Streams failed to open. (" + e.toString() + ")";
      System.out.println(logText + "\n");
      return successful;
    }
  }
コード例 #21
0
ファイル: ComManager.java プロジェクト: hZix/callbyj
 /**
  * Start call.
  *
  * @throws Exception the exception
  */
 public void startCall() throws Exception {
   CommPortIdentifier portIdentifier = CommPortIdentifier.getPortIdentifier(this.streamPortName);
   if (portIdentifier.isCurrentlyOwned()) {
     logger.error("Serial port " + this.streamPortName + " is currently in use");
   }
   CommPort commPort = portIdentifier.open(this.getClass().getName(), 2000);
   if (commPort instanceof SerialPort) {
     voiceStreamCommPort = (SerialPort) commPort;
     voiceStreamCommPort.setSerialPortParams(
         230400, SerialPort.DATABITS_8, SerialPort.STOPBITS_1, SerialPort.PARITY_NONE);
     voiceInputStream = new DataInputStream(voiceStreamCommPort.getInputStream());
     voiceOutputStream = new DataOutputStream(voiceStreamCommPort.getOutputStream());
     serialVoiceReader = new SerialVoiceReader(voiceInputStream, af);
     serialVoiceWriter = new SerialVoiceWriter(voiceOutputStream, af, playMessage);
     (new Thread(serialVoiceReader, "VoiceReader")).start();
     (new Thread(serialVoiceWriter, "VoiceWriter")).start();
   }
 }
コード例 #22
0
  public static void readFromArduino() throws Exception {
    // for linux
    // CommPortIdentifier portId = CommPortIdentifier.getPortIdentifier("/dev/ttyACM3");

    // for windows
    CommPortIdentifier portId = CommPortIdentifier.getPortIdentifier("COM5");
    // CommPortIdentifier portId = CommPortIdentifier.getPortIdentifier("COM4");

    SerialPort port = (SerialPort) portId.open("serial talk", 4000);
    input = port.getInputStream();
    port.setSerialPortParams(
        9600, SerialPort.DATABITS_8, SerialPort.STOPBITS_1, SerialPort.PARITY_NONE);

    while (true) {
      if (input.available() > 0) {
        System.out.print((char) (input.read()));
      }
    }
  }
コード例 #23
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());
    }
  }
コード例 #24
0
ファイル: Serial.java プロジェクト: HfK-Bremen/In-Between
  public Serial(SerialPort pSerialPort, OutputStream pOutputStream) {
    serialPort = pSerialPort;
    out = pOutputStream;

    //
    // serialPort.setSerialPortParams(57600,SerialPort.DATABITS_8,SerialPort.STOPBITS_1,SerialPort.PARITY_NONE);

    in = null;
    try {
      in = serialPort.getInputStream();
    } catch (IOException ex) {
      ex.printStackTrace();
    }
    //        try {
    //            OutputStream out = serialPort.getOutputStream();
    //        } catch (IOException ex) {
    //            ex.printStackTrace();
    //        }

    (new Thread(new SerialReader(in))).start();
    //        (new Thread(new SerialWriter(out))).start();
  }
コード例 #25
0
ファイル: CardReader.java プロジェクト: prg-dtu/door-computer
  public CardReader(String portName)
      throws IOException, PortInUseException, UnsupportedCommOperationException,
          NoSuchPortException {
    CommPortIdentifier portIdentifier = CommPortIdentifier.getPortIdentifier(portName);
    if (portIdentifier.isCurrentlyOwned()) {
      System.out.println("Error: Port is currently in use");
    } else {
      int timeout = 2000;
      CommPort commPort = portIdentifier.open(this.getClass().getName(), timeout);

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

        in = serialPort.getInputStream();

      } else {
        System.out.println("Error: Only serial ports are handled by this example.");
      }
    }
  }
コード例 #26
0
  /** @see com.svhelloworld.knotlog.engine.sources.StreamedSource#open() */
  @Override
  public InputStream open() {
    try {
      // make sure the specified port is available
      CommPortIdentifier identifier = CommPortIdentifier.getPortIdentifier(config.getName());
      if (identifier.isCurrentlyOwned()) {
        throw new SerialPortOccupiedException(
            config.getName() + " port is currently opened by another application");
      }
      // open up the port
      CommPort port = identifier.open(getOwnerName(), PORT_TIMEOUT);
      if (port instanceof SerialPort) {

        // configure serial port
        serialPort = (SerialPort) port;
        serialPort.setSerialPortParams(
            config.getBaudRate(),
            config.getDataBits().getRXTXConstant(),
            config.getStopBit().getRXTXConstant(),
            config.getParity().getRXTXConstant());
        /*
         * the following 2 lines fix the exception:
         *       "IOException: Underlying input stream returned zero bytes"
         *       that is thrown when we read from the InputStream.
         */
        serialPort.enableReceiveTimeout(PORT_TIMEOUT);
        serialPort.enableReceiveThreshold(0);

        InputStream is = serialPort.getInputStream();
        return is;
      }
      // not a serial port
      throw new SerialPortException("must operate against a serial port");
    } catch (PortInUseException e) {
      throw new SerialPortOccupiedException(e.getMessage(), e);
    } catch (Exception e) {
      throw new SerialPortException(e.getMessage(), e);
    }
  }
コード例 #27
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());
    }
  }
コード例 #28
0
ファイル: Serial.java プロジェクト: HfK-Bremen/In-Between
  void connect(String portName) 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 mSerialPort = (SerialPort) commPort;
        mSerialPort.setSerialPortParams(
            57600, SerialPort.DATABITS_8, SerialPort.STOPBITS_1, SerialPort.PARITY_NONE);

        InputStream mIn = mSerialPort.getInputStream();
        OutputStream mOut = mSerialPort.getOutputStream();

        (new Thread(new SerialReader(mIn))).start();
        (new Thread(new SerialWriter(mOut))).start();

      } else {
        System.out.println("Error: Only serial ports are handled by this example.");
      }
    }
  }
コード例 #29
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);
    }
  }
コード例 #30
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");
    }
  }