Beispiel #1
0
  public static void main(String[] args) {
    portList = CommPortIdentifier.getPortIdentifiers();

    while (portList.hasMoreElements()) {
      portId = (CommPortIdentifier) portList.nextElement();
      if (portId.getPortType() == CommPortIdentifier.PORT_SERIAL) {
        if (portId.getName().equals("COM17")) {
          // if (portId.getName().equals("/dev/term/a")) {
          try {
            serialPort = (SerialPort) portId.open("SimpleWriteApp", 2000);
          } catch (PortInUseException e) {
          }

          try {
            outputStream = serialPort.getOutputStream();
          } catch (IOException e) {
          }
          try {
            serialPort.setSerialPortParams(
                9600, SerialPort.DATABITS_8, SerialPort.STOPBITS_1, SerialPort.PARITY_NONE);
          } catch (UnsupportedCommOperationException e) {
          }

          try {
            outputStream.write(messageString.getBytes());
          } catch (IOException e) {
          }
        }
      }
    }
  }
Beispiel #2
0
 private static String _guessWindowsPortName(ArrayList<String> portNames) {
   /*
   // if the for loop below this comment block does not work right,
   // try using the code in this comment block instead
   String portName = null;
   for(int n=1; n<10; n++)
   {
     portName = "COM" + n;
     SerialPort port = new SerialPort(portName);
     try
     {
       port.open();
       port.close();
       break;
     }
     catch(Exception exn)
     {}
   }
   return portName;*/
   for (String portName : portNames) {
     SerialPort port = new SerialPort(portName);
     try {
       port.open();
       port.close();
       return portName;
     } catch (Exception exn) {
     }
   }
   return null;
 }
Beispiel #3
0
 public boolean digitalRead(int pinNumber) {
   String s = "dr" + pinNumber;
   _serialPort.writeLn(s);
   String result = _serialPort.readLine();
   char cRes = result.charAt(0);
   return cRes == '0' ? false : true;
 }
Beispiel #4
0
 public static void initSerial() {
   Enumeration portList = CommPortIdentifier.getPortIdentifiers();
   CommPortIdentifier portId = null;
   boolean portFound = false;
   while (portList.hasMoreElements()) {
     portId = (CommPortIdentifier) portList.nextElement();
     if (portId.getPortType() == CommPortIdentifier.PORT_SERIAL) {
       if (portId.getName().equals("COM3")) {
         portFound = true;
       }
     }
   }
   if (!portFound) {
     System.out.println("port COM3 not found.");
     return;
   }
   SerialPort port;
   try {
     port = (SerialPort) portId.open("COM3", 2000);
     port.setSerialPortParams(
         115200, SerialPort.DATABITS_8, SerialPort.STOPBITS_1, SerialPort.PARITY_NONE);
     comOS = new DataOutputStream(port.getOutputStream());
   } catch (PortInUseException e) {
     e.printStackTrace();
   } catch (IOException e) {
     e.printStackTrace();
   } catch (UnsupportedCommOperationException e) {
     // TODO Auto-generated catch block
     e.printStackTrace();
   }
 }
  /** 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;
  }
  /**
   * This creates an mbed object for an mbed connected over Serial. <br>
   * Using this class requires the Sun Communications API to be installed
   *
   * @param PortName The Serial Port mbed is connected to eg "COM5" on Windows.
   * @param Baud The baud rate
   */
  public SerialRPC(String PortName, int Baud) {
    // open serial port
    try {
      mbedPortID = CommPortIdentifier.getPortIdentifier(PortName);

      mbedPort = mbedPortID.open("mbed", 100000);
      mbedSerialPort = (SerialPort) mbedPort;
      mbedSerialPort.setSerialPortParams(
          Baud, SerialPort.DATABITS_8, SerialPort.STOPBITS_1, SerialPort.PARITY_NONE);

      inputStream = new DataInputStream(mbedPort.getInputStream());
      outputStream = new PrintStream(mbedPort.getOutputStream(), true);

      reader = new BufferedReader(new InputStreamReader(inputStream));
      to_mbed = new PrintWriter(outputStream, true);

      mbedSerialPort.addEventListener(this);
      // Important to set this regardless of whether interrupts are in use to keep the buffer clear
      mbedSerialPort.notifyOnDataAvailable(true);

    } catch (TooManyListenersException e) {
      // Error adding event listener
      System.out.println("Too many Event Listeners");
    } catch (NoSuchPortException e) {
      System.out.println("No Such Port");
    } catch (PortInUseException e) {
      System.out.println("Port Already In Use");
    } catch (UnsupportedCommOperationException e) {
      System.out.println("Unsupported Comm Operation");
    } catch (IOException e) {
      System.out.println("Serial Port IOException");
    }
  }
  /** {@inheritDoc} */
  public String RPC(String Name, String Method, String[] Args) {
    // write to serial port and receive result
    String Response;
    String Arguments = "";
    if (Args != null) {
      int s = Args.length;
      for (int i = 0; i < s; i++) {
        Arguments = Arguments + " " + Args[i];
      }
    }
    try {
      to_mbed.println("/" + Name + "/" + Method + Arguments);
      mbedSerialPort.notifyOnDataAvailable(false);
    } catch (NullPointerException e) {

    }
    boolean valid = true;
    try {
      while (reader.ready() == false) {}
      ;
      do {
        Response = reader.readLine();

        if (Response.length() >= 1) {
          valid = Response.charAt(0) != '!';
        }
      } while (valid == false);
    } catch (IOException e) {
      System.err.println("IOException, error reading from port");
      Response = "error";
    }

    mbedSerialPort.notifyOnDataAvailable(true);
    return (Response);
  }
  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();
    }
  }
Beispiel #9
0
  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);
    }
  }
Beispiel #10
0
 // 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");
   }
 }
Beispiel #11
0
  public static Serial open(String defaultPort) {
    boolean portFound = false;
    final int mComPortIdentifier = CommPortIdentifier.PORT_SERIAL;
    final Enumeration portList = CommPortIdentifier.getPortIdentifiers();
    final int BAUD = 115200;

    while (portList.hasMoreElements()) {
      final CommPortIdentifier portId = (CommPortIdentifier) portList.nextElement();
      System.out.println("Found port id: " + portId);

      if (portId.getPortType() == mComPortIdentifier) {
        System.out.println("Found CommPortIdentifier.");

        if (portId.getName().equals(defaultPort)) {
          System.out.println("Found port " + defaultPort);

          SerialPort serialPort;
          OutputStream outputStream = null;

          try {
            serialPort = (SerialPort) portId.open("SimpleWrite", 2000);
          } catch (PortInUseException e) {
            System.out.println("Port in use.");
            continue;
          }

          try {
            outputStream = serialPort.getOutputStream();
          } catch (IOException e) {
            e.printStackTrace();
          }

          try {
            serialPort.setSerialPortParams(
                BAUD, SerialPort.DATABITS_8, SerialPort.STOPBITS_1, SerialPort.PARITY_NONE);
          } catch (UnsupportedCommOperationException e) {
            e.printStackTrace();
          }

          try {
            serialPort.notifyOnOutputEmpty(true);
          } catch (Exception e) {
            System.out.println("Error setting event notification");
            System.out.println(e.toString());
            System.exit(-1);
          }

          return new Serial(serialPort, outputStream);
        }
      }
    }

    if (!portFound) {
      System.out.println("port " + defaultPort + " not found.");
    }
    return null;
  }
 public synchronized void sendEvent(RobotEvent ev) {
   try {
     output.write(ev.toStringSend().getBytes()); // write needs a byte array instead of a string
     long milli = (long) (1.0 / ((float) serialPort.getBaudRate() / (8.0 * 16.0)) * 1000.0);
     long nano =
         (long) (1.0 / ((float) serialPort.getBaudRate() / (8.0 * 16.0)) * 1000000000.0)
             - milli * 1000000;
     Thread.sleep((int) milli, (int) nano);
   } catch (Exception e) {
   }
 }
Beispiel #13
0
 /*! This method initializes the input and output stream member
 	variables. It throws an exception if the COM port identifier
 	is not found.
 */
 private void initSerial() throws Exception {
   CommPortIdentifier portId =
       CommPortIdentifier.getPortIdentifier(
           comPort); // get the port ID for the port name received through command line
   if (portId == null) {
     throw new NullPointerException("no com port identifier");
   }
   serPort = (SerialPort) portId.open("Shake", 5000); // open the serial Port
   outStream = serPort.getOutputStream(); // get output stream to the serial port
   inStream = serPort.getInputStream(); // get input stram to the serial port
   inBufReader = new BufferedReader(new InputStreamReader(inStream));
 }
  /** Close the serial port. */
  public void delete() {
    // Close the serial port
    try {
      if (inputStream != null) inputStream.close();
      outputStream.close();
    } catch (IOException e) {

    }
    mbedSerialPort.removeEventListener();
    mbedSerialPort.close();
    mbedPort.close();
  }
Beispiel #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);
  }
 public static SerialPort openPortByName(String name, int baudRate) {
   SerialPort port = null;
   try {
     CommPortIdentifier identifier = CommPortIdentifier.getPortIdentifier(name);
     port = (SerialPort) identifier.open("SerialPort", 2000);
     port.setSerialPortParams(
         baudRate, SerialPort.DATABITS_8, SerialPort.STOPBITS_1, SerialPort.PARITY_NONE);
   } catch (PortInUseException | NoSuchPortException | UnsupportedCommOperationException ex) {
     ErrorDialog dialog = new ErrorDialog(null, true, ex.getMessage());
     ComponentPosition.centerFrame(dialog);
     dialog.setVisible(true);
   }
   return port;
 }
  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;
  }
Beispiel #18
0
  public int setUpBam() {
    Enumeration<?> portIdentifiers = CommPortIdentifier.getPortIdentifiers();
    CommPortIdentifier portId = null;

    while (portIdentifiers.hasMoreElements()) {
      CommPortIdentifier pid = (CommPortIdentifier) portIdentifiers.nextElement();

      if (pid.getPortType() == CommPortIdentifier.PORT_SERIAL
          && pid.getName().equals(wantedPortName)) {
        portId = pid;
        System.out.println("Found port: " + pid.getName());
        break;
      }
    }

    try {
      port = (SerialPort) portId.open("Driver", 10000);
    } catch (PortInUseException e) {
      System.err.println("Port already in use: " + e);
      System.exit(1);
    }

    try {
      port.setSerialPortParams(
          57600, SerialPort.DATABITS_8, SerialPort.STOPBITS_1, SerialPort.PARITY_NONE);
    } catch (UnsupportedCommOperationException e) {
      System.err.println("Failed to set up port: " + e);
    }
    System.out.println("Port should be open now");
    return 0;
  }
 private void init(
     SerialPort serialPort, SerialParameters serialParams, SerialTestResultsDisplay results)
     throws SerialConnectionException {
   _parameters = serialParams;
   _sPort = serialPort;
   _results = results;
   _sendThread = new Thread(this);
   _chunkSize = 4096;
   _savedStream = new ByteArrayOutputStream();
   try {
     _os = _sPort.getOutputStream();
   } catch (IOException e) {
     _sPort.close();
     throw new SerialConnectionException("Error opening i/o streams");
   }
 }
Beispiel #20
0
 // disconnect the serial port
 // pre: an open serial port
 // post: clsoed serial port
 public void disconnect() {
   // close the serial port
   try {
     //            writeData(0, 0);
     serialPort.removeEventListener();
     serialPort.close();
     input.close();
     output.close();
     setConnected(false);
     logText = "Disconnected.";
     System.out.println(logText + "\n");
   } catch (Exception e) {
     logText = "Failed to close " + serialPort.getName() + "(" + e.toString() + ")";
     System.out.println(logText + "\n");
   }
 }
  public void open()
      throws NoSuchPortException, PortInUseException, IOException,
          UnsupportedCommOperationException {
    portId = CommPortIdentifier.getPortIdentifier(portName);
    port = (SerialPort) portId.open(CLASS_NAME, 0);
    in = port.getInputStream();
    out = port.getOutputStream();

    port.setFlowControlMode(SerialPort.FLOWCONTROL_RTSCTS_IN);
    port.setFlowControlMode(SerialPort.FLOWCONTROL_RTSCTS_OUT);

    printPortStatus();
    port.setSerialPortParams(
        19200, SerialPort.DATABITS_8, SerialPort.STOPBITS_1, SerialPort.PARITY_NONE);
    printPortStatus();
  }
Beispiel #22
0
  // 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;
    }
  }
Beispiel #23
0
  public void write(final String pMessageString) {
    System.out.println("\n>>> \"" + pMessageString + "\" to " + serialPort.getName());

    try {
      out.write(pMessageString.getBytes());
    } catch (IOException e) {
      e.printStackTrace();
    }
  }
 public void schliesseSerialPort() {
   if (serialPortGeoeffnet == true) {
     System.out.println("Schließe Serialport");
     serialPort.close();
     serialPortGeoeffnet = false;
   } else {
     System.out.println("Serialport bereits geschlossen");
   }
 }
Beispiel #25
0
 public void setReceiveTimeout(int ms) {
   // Set receive timeout to allow breaking out of polling loop during
   // input handling.
   try {
     m_SerialPort.enableReceiveTimeout(ms);
   } catch (UnsupportedCommOperationException e) {
     logger.error("Failed to set receive timeout: {}", e.getMessage());
   }
 } // setReceiveTimeout
  /** @param data */
  @Override
  protected void internalWrite(byte[] data) {
    try {
      if (m_out == null) {
        m_PortIdPrinter =
            CommPortIdentifier.getPortIdentifier(
                m_sPortPrinter); // 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
          ((SerialPort) m_CommPortPrinter)
              .setFlowControlMode(
                  SerialPort
                      .FLOWCONTROL_RTSCTS_IN); // this line prevents the printer tmu220 to stop
                                               // printing after +-18 lines printed
          // this line prevents the printer tmu220 to stop printing after +-18 lines printed. Bug
          // 8324
          // But if added a regression error appears. Bug 9417, Better to keep it commented.
          // ((SerialPort)m_CommPortPrinter).setFlowControlMode(SerialPort.FLOWCONTROL_RTSCTS_IN);
          // Not needed to set parallel properties
          //                } else if (m_PortIdPrinter.getPortType() ==
          // CommPortIdentifier.PORT_PARALLEL) {
          //                    ((ParallelPort)m_CommPortPrinter).setMode(1);

        }
      }
      m_out.write(data);
      // JG 16 May 12 use multicatch
    } catch (NoSuchPortException
        | PortInUseException
        | UnsupportedCommOperationException
        | IOException e) {
      System.err.println(e);
    }
  }
 public void connectionclose() {
   try {
     is.close();
     os.close();
     dis.close();
     dos.close();
     sPort.close();
   } catch (Exception e) {
     System.out.println("close" + e);
   }
 }
Beispiel #28
0
  public void read(byte[] data) {
    try {
      is = port.getInputStream();
    } catch (IOException e) {
      System.err.println("IOException: " + e);
    }

    try {
      is.read(data);
    } catch (IOException e) {
      System.err.println("IOException: " + e);
    }
  }
Beispiel #29
0
 /*
  * Code cribbed from RXTX example
  */
 public static void closePort(SerialPort serialPort) {
   if (serialPort != null) {
     serialPort.notifyOnDataAvailable(false);
     serialPort.removeEventListener();
     if (inputStream != null) {
       try {
         inputStream.close();
         inputStream = null;
       } catch (IOException e) {
       }
     }
     if (outputStream != null) {
       try {
         outputStream.close();
         outputStream = null;
       } catch (IOException e) {
       }
     }
     serialPort.close();
     serialPort = null;
   }
 }
Beispiel #30
0
 public static String guessPortName() {
   String osName = System.getProperty("os.name").toLowerCase();
   // System.out.println("OS name = \"" + osName + "\"");
   ArrayList<String> portNames = SerialPort.listPortNames();
   String portName = null;
   if (osName.indexOf("mac") >= 0) portName = _guessMacPortName(portNames);
   else if (osName.indexOf("win") >= 0) portName = _guessWindowsPortName(portNames);
   else if (osName.indexOf("linux") >= 0) portName = _guessLinuxPortName(portNames);
   else
     throw new RuntimeException(
         "GuessPortName.guess: operating system " + osName + " not supported");
   return portName;
 }