Example #1
0
  public static boolean touchPort(String iname, int irate) throws SerialException {
    SerialPort port;
    boolean result = false;
    try {
      Enumeration portList = CommPortIdentifier.getPortIdentifiers();
      while (portList.hasMoreElements()) {
        CommPortIdentifier portId = (CommPortIdentifier) portList.nextElement();
        if ((CommPortIdentifier.PORT_SERIAL == portId.getPortType()) && (portId.getName().equals(iname))) {
          port = (SerialPort) portId.open("tap", 2000);
          port.setSerialPortParams(irate, 8, SerialPort.STOPBITS_1, SerialPort.PARITY_NONE);
          port.close();				
          result = true;
        }
      }
    } catch (PortInUseException e) {
      throw new SerialException(
        I18n.format(_("Serial port ''{0}'' already in use. Try quitting any programs that may be using it."), iname)
      );
    } catch (Exception e) {
      throw new SerialException(
        I18n.format(_("Error touching serial port ''{0}''."), iname), e
      );
    }
	return result;
  }
  @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.
    }
  }
  /**
   * Gets the serial port on the given port name. Throws an {@link IOException} if it does not
   * succeed in doing so.
   *
   * @param portName The port name.
   * @return The port.
   * @throws IOException If the port could not be opened.
   */
  private final SerialPort getSerialPort(final String portName) throws IOException {
    try {
      final CommPortIdentifier identifier = CommPortIdentifier.getPortIdentifier(portName);

      if (identifier.isCurrentlyOwned()) {
        throw new IOException(
            "The port specified ["
                + portName
                + "] is already in use by ["
                + identifier.getCurrentOwner()
                + "] !");
      }

      final CommPort rawPort = identifier.open("DOM_SER_DRV", 2000);

      if (rawPort instanceof SerialPort) {
        final SerialPort port = (SerialPort) rawPort;
        port.setSerialPortParams(
            BAUDRATE, SerialPort.DATABITS_8, SerialPort.STOPBITS_1, SerialPort.PARITY_NONE);

        return port;
      } else {
        throw new IOException("Port [" + portName + "] is not a serial port !");
      }
    } catch (NoSuchPortException e) {
      throw new IOException("The port specified [" + portName + "] does not exist !", e);
    } catch (PortInUseException e) {
      throw new IOException("The port specified [" + portName + "] is already in use !");
    } catch (UnsupportedCommOperationException e) {
      throw new IOException("Unsupported comm operation when setting the serial parameters !", e);
    }
  }
Example #4
0
  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) {
    }
  }
Example #5
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);
    }
  }
  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());
    }
  }
Example #7
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) {
          }
        }
      }
    }
  }
Example #8
0
  /**
   * If this just hangs and never completes on Windows, 
   * it may be because the DLL doesn't have its exec bit set.
   * Why the hell that'd be the case, who knows.
   */
  static public List<String> list() {
    List<String> list = new ArrayList<String>();
    try {
      //System.err.println("trying");
      @SuppressWarnings("unchecked")
      Enumeration portList = CommPortIdentifier.getPortIdentifiers();
      //System.err.println("got port list");
      while (portList.hasMoreElements()) {
        CommPortIdentifier portId = 
          (CommPortIdentifier) portList.nextElement();
        //System.out.println(portId);

        if (portId.getPortType() == CommPortIdentifier.PORT_SERIAL) {
          String name = portId.getName();
          list.add(name);
        }
      }

    } catch (UnsatisfiedLinkError e) {
      //System.err.println("1");
      errorMessage("ports", e);

    } catch (Exception e) {
      //System.err.println("2");
      errorMessage("ports", e);
    }
    //System.err.println("move out");
    return list;
  }
Example #9
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();
    }
  }
Example #10
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();
    }
  }
Example #11
0
  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();
    }
  }
Example #12
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();
   }
 }
  public static void main(String[] args)
      throws NoSuchPortException, PortInUseException, UnsupportedCommOperationException,
          IOException, ParseException {
    if (args.length != 2) {
      System.err.println("Usage: <prog> portDevice hexfile.hex");
      System.exit(1);
    }

    STM32BootLoader me = new STM32BootLoader();

    CommPortIdentifier comident = CommPortIdentifier.getPortIdentifier(args[0]);

    SerialPort sp = (SerialPort) comident.open("STM32BootLoader", 200);

    sp.setSerialPortParams(
        57600, SerialPort.DATABITS_8, SerialPort.STOPBITS_1, SerialPort.PARITY_EVEN);

    sp.setFlowControlMode(SerialPort.FLOWCONTROL_NONE);

    // Setup serial port and reply timeout. Found that such a long timeout
    // IS necessary.
    me.setSerialPort(sp, 5000);

    try {
      File f = new File(args[1]);

      byte[] image = HexFileParser.parseFile(f);

      me.program(image, false, 0);
    } finally {
      me.close();
    }
  }
Example #14
0
  /** 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.");
    }
  }
Example #15
0
  public static boolean checkPort(){
	  SerialPort testPort = null;
	  String iname = Preferences.get("serial.port");
	  if(iname == null)
		  return false;
	  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)) {
        	  try {
				 testPort = (SerialPort)portId.open("serial madness", 2000);
			} catch (PortInUseException e) {
				// TODO Auto-generated catch block
				//e.printStackTrace();
				System.out.println("[Serial]Port is already in use, press reset button!");
				//testPort.close();
				return false;
				
			}
        	 // System.out.println("[SERIAL]port is ok!");
        	  testPort.close();
        	  return true;
          }
        }
      }
      //System.out.println("[SERIAL]port is not ok!");
    //testPort.close();
	return false;
	  
  }
Example #16
0
  /**
   * 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);
    }
  }
  /** 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;
  }
  @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);
    }
  }
Example #19
0
  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
  }
Example #20
0
 public static void listPorts() {
   Enumeration<CommPortIdentifier> portEnum = CommPortIdentifier.getPortIdentifiers();
   while (portEnum.hasMoreElements()) {
     CommPortIdentifier portIdentifier = portEnum.nextElement();
     System.out.println(
         portIdentifier.getName() + " - " + getPortTypeName(portIdentifier.getPortType()));
   }
 }
  private void getAllPorts() {
    Enumeration portsEnum = CommPortIdentifier.getPortIdentifiers();

    while (portsEnum.hasMoreElements()) {
      CommPortIdentifier port = (CommPortIdentifier) portsEnum.nextElement();
      this.ports.put(port.getName(), port);
    }
  }
Example #22
0
 static void listPorts() {
   Enumeration portEnums = CommPortIdentifier.getPortIdentifiers();
   while (portEnums.hasMoreElements()) {
     CommPortIdentifier portId = (CommPortIdentifier) portEnums.nextElement();
     System.out.println(portId.getName() + " - " + getPortTypeName(portId.getPortType()));
     // System.out.println(portId.getName());
   }
 }
Example #23
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;
  }
 @SuppressWarnings("unchecked")
 public static void enumerate() {
   Enumeration<CommPortIdentifier> ports = CommPortIdentifier.getPortIdentifiers();
   System.out.println("Serial ports:");
   while (ports.hasMoreElements()) {
     CommPortIdentifier portIdentifier = ports.nextElement();
     System.out.println("  " + portIdentifier.getName());
   }
 }
 public static List<String> getAvailablePorts() {
   List<String> portNames = new ArrayList<>();
   Enumeration identifiers = CommPortIdentifier.getPortIdentifiers();
   while (identifiers.hasMoreElements()) {
     CommPortIdentifier identifier = (CommPortIdentifier) identifiers.nextElement();
     if (identifier.getPortType() == CommPortIdentifier.PORT_SERIAL) {
       portNames.add(identifier.getName());
     }
   }
   return portNames;
 }
    private void updateComList() {
      // CommPortIdentifier portId = null;
      Enumeration<?> portEnum;
      portEnum = CommPortIdentifier.getPortIdentifiers();
      // ComBox.addItem("COM1");

      while (portEnum.hasMoreElements()) {
        CommPortIdentifier currentPortIdentifier = (CommPortIdentifier) portEnum.nextElement();
        comPortList.addItem(currentPortIdentifier.getName());
      }
    }
Example #27
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);
  }
Example #28
0
  // search for all the serial ports
  // pre: none
  // post: adds all the found ports to a combo box on the GUI
  public void searchForPorts() {
    ports = CommPortIdentifier.getPortIdentifiers();

    while (ports.hasMoreElements()) {
      CommPortIdentifier curPort = (CommPortIdentifier) ports.nextElement();

      // get only serial ports
      if (curPort.getPortType() == CommPortIdentifier.PORT_SERIAL) {
        portMap.put(curPort.getName(), curPort);
      }
    }
  }
 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;
 }
  @Override
  public HashMap<String, CommPortIdentifier> getAvailablePorts() {
    HashMap<String, CommPortIdentifier> portMap = new HashMap<>();
    Enumeration<?> ports = CommPortIdentifier.getPortIdentifiers();

    while (ports.hasMoreElements()) {
      CommPortIdentifier curPort = (CommPortIdentifier) ports.nextElement();

      if (curPort.getPortType() == CommPortIdentifier.PORT_SERIAL) {
        portMap.put(curPort.getName(), curPort);
      }
    }
    return portMap;
  }