コード例 #1
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);
  }
コード例 #2
0
 private HashMap<String, CommPortIdentifier> getAvailablePorts() {
   HashMap<String, CommPortIdentifier> result = new HashMap<String, CommPortIdentifier>();
   Enumeration<CommPortIdentifier> ports = CommPortIdentifier.getPortIdentifiers();
   while (ports.hasMoreElements()) {
     CommPortIdentifier port = ports.nextElement();
     if (port.getPortType() == CommPortIdentifier.PORT_SERIAL) {
       result.put(port.getName(), port);
       logger.info(port.getName());
       logger.info(port.getCurrentOwner());
     }
   }
   return result;
 }
コード例 #3
0
  public ProgrammerDialog(ProjectDriver plp, java.awt.Frame parent, boolean modal) {
    super(parent, modal);
    initComponents();

    this.plp = plp;

    plptool.PLPToolbox.attachHideOnEscapeListener(this);

    cmbPort.removeAllItems();
    if (plp.isSerialSupported() && Config.prgAutoDetectPorts) {
      Enumeration portList = CommPortIdentifier.getPortIdentifiers();
      while (portList.hasMoreElements()) {
        CommPortIdentifier portId = (CommPortIdentifier) portList.nextElement();
        Msg.D("rxtx portId name: " + portId.getName() + " type: " + portId.getPortType(), 2, null);
        if (portId.getPortType() == CommPortIdentifier.PORT_SERIAL) {
          cmbPort.addItem(portId.getName());
        }
      }
    } else {
      if (PLPToolbox.getOS(false) == Constants.PLP_OS_LINUX_32
          || PLPToolbox.getOS(false) == Constants.PLP_OS_LINUX_64) {
        cmbPort.addItem("/dev/ttyUSB0");
        cmbPort.addItem("/dev/ttyUSB1");
        cmbPort.addItem("/dev/ttyS0");
        cmbPort.addItem("/dev/ttyS1");
      } else if (PLPToolbox.getOS(false) == Constants.PLP_OS_WIN_32
          || PLPToolbox.getOS(false) == Constants.PLP_OS_WIN_64) {
        cmbPort.addItem("COM1");
        cmbPort.addItem("COM2");
        cmbPort.addItem("COM3");
        cmbPort.addItem("COM4");
      } else cmbPort.addItem("Specify your serial port here.");
    }

    javax.swing.KeyStroke escapeKeyStroke =
        javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_ESCAPE, 0, false);
    javax.swing.Action escapeAction =
        new javax.swing.AbstractAction() {
          public void actionPerformed(java.awt.event.ActionEvent e) {
            setVisible(false);
            close();
          }
        };

    getRootPane()
        .getInputMap(javax.swing.JComponent.WHEN_IN_FOCUSED_WINDOW)
        .put(escapeKeyStroke, "ESCAPE");
    getRootPane().getActionMap().put("ESCAPE", escapeAction);

    this.setLocationRelativeTo(null);
  }
コード例 #4
0
ファイル: SimpleWrite (1).java プロジェクト: cocojk/major
  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) {
          }
        }
      }
    }
  }
コード例 #5
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;
	  
  }
コード例 #6
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());
   }
 }
コード例 #7
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();
    }
  }
コード例 #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;
  }
コード例 #9
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();
    }
  }
コード例 #10
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;
  }
コード例 #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
ファイル: Server.java プロジェクト: Kairus101/soccerRobots
 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();
   }
 }
コード例 #13
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;
  }
コード例 #14
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());
    }
  }
コード例 #15
0
ファイル: serialportlist.java プロジェクト: kc8hfi/arduino
 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());
   }
 }
コード例 #16
0
ファイル: Serial.java プロジェクト: HfK-Bremen/In-Between
 public static void listPorts() {
   Enumeration<CommPortIdentifier> portEnum = CommPortIdentifier.getPortIdentifiers();
   while (portEnum.hasMoreElements()) {
     CommPortIdentifier portIdentifier = portEnum.nextElement();
     System.out.println(
         portIdentifier.getName() + " - " + getPortTypeName(portIdentifier.getPortType()));
   }
 }
コード例 #17
0
ファイル: TanitaInstrument.java プロジェクト: emorency/onyx
  @SuppressWarnings("unchecked")
  protected void refreshSerialPortList() {

    log.info("Refreshing serial port list...");
    Enumeration<CommPortIdentifier> portEnum = CommPortIdentifier.getPortIdentifiers();
    availablePortNames = new ArrayList<String>();

    // Build a list of all serial ports found.
    while (portEnum != null && portEnum.hasMoreElements()) {

      CommPortIdentifier port = portEnum.nextElement();
      if (port.getPortType() == CommPortIdentifier.PORT_SERIAL) {
        log.info("Port name={}, Port type={}", port.getName(), port.getPortType());
        availablePortNames.add(port.getName());
      }
    }
  }
コード例 #18
0
  private void getAllPorts() {
    Enumeration portsEnum = CommPortIdentifier.getPortIdentifiers();

    while (portsEnum.hasMoreElements()) {
      CommPortIdentifier port = (CommPortIdentifier) portsEnum.nextElement();
      this.ports.put(port.getName(), port);
    }
  }
コード例 #19
0
ファイル: SerialDevice.java プロジェクト: EaseTech/things-api
  public Collection<Device> scanPorts() {

    Collection<Device> devicesFound = new ArrayList<Device>();

    Enumeration portList;
    CommPortIdentifier portId;

    portList = CommPortIdentifier.getPortIdentifiers();
    Logger.getLogger(Things.class.getName()).log(Level.INFO, "Starting jHome 1.0");
    SerialPort serialPort = null;
    while (portList.hasMoreElements()) {
      portId = (CommPortIdentifier) portList.nextElement();
      Logger.getLogger(Things.class.getName()).log(Level.INFO, "Scaning port: " + portId.getName());

      if (portId.getPortType() == CommPortIdentifier.PORT_SERIAL) {
        Logger.getLogger(Things.class.getName())
            .log(
                Level.INFO,
                "Serial Device Port found "
                    + portId.getName()
                    + ". Trying to discovery this device.");
        try {
          /*serialPort =
          (SerialPort) portId.open(portId.getName(), 115200);
          Device device = new SerialDevice(serialPort);*/
          Device device = new SerialDevice(portId, DEFAULT_BAUDRATE);
          device.open();
          device.discovery();
          if (device.connected()) {
            devicesFound.add(device);
          } else {
            Logger.getLogger(Things.class.getName())
                .log(Level.INFO, "Serial Device is not Things API Compatible" + portId.getName());
            device.close();
          }
          devicesFound.add(device);
        } catch (Exception e) {
          Logger.getLogger(Things.class.getName())
              .log(Level.SEVERE, "Couldn't connect to" + portId.getName());
          e.printStackTrace();
        }
      }
    }
    return devicesFound;
  }
コード例 #20
0
ファイル: Serial.java プロジェクト: HfK-Bremen/In-Between
  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;
  }
コード例 #21
0
 @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());
   }
 }
コード例 #22
0
 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;
 }
コード例 #23
0
    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());
      }
    }
コード例 #24
0
ファイル: Communicator.java プロジェクト: kihyunHwang/MUX
  // 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);
      }
    }
  }
コード例 #25
0
ファイル: COMPorts.java プロジェクト: ksorokosz/Generator
 /**
  * @return A HashSet containing the CommPortIdentifier for all serial ports that are not currently
  *     being used.
  */
 @SuppressWarnings({"rawtypes"})
 private static HashSet<CommPortIdentifier> getAvailableSerialPorts() {
   HashSet<CommPortIdentifier> h = new HashSet<CommPortIdentifier>();
   Enumeration thePorts = CommPortIdentifier.getPortIdentifiers();
   while (thePorts.hasMoreElements()) {
     CommPortIdentifier com = (CommPortIdentifier) thePorts.nextElement();
     switch (com.getPortType()) {
       case CommPortIdentifier.PORT_SERIAL:
         try {
           CommPort thePort = com.open("CommUtil", 50);
           thePort.close();
           h.add(com);
         } catch (PortInUseException e) {
           System.out.println("Port, " + com.getName() + ", is in use.");
         } catch (Exception e) {
           System.err.println("Failed to open port " + com.getName());
           e.printStackTrace();
         }
     }
   }
   return h;
 }
コード例 #26
0
ファイル: DrawbotGUI.java プロジェクト: bertbalcaen/DrawBot
 // find all available serial ports for the settings->ports menu.
 public String[] ListSerialPorts() {
   @SuppressWarnings("unchecked")
   Enumeration<CommPortIdentifier> ports =
       (Enumeration<CommPortIdentifier>) CommPortIdentifier.getPortIdentifiers();
   ArrayList<String> portList = new ArrayList<String>();
   while (ports.hasMoreElements()) {
     CommPortIdentifier port = (CommPortIdentifier) ports.nextElement();
     if (port.getPortType() == CommPortIdentifier.PORT_SERIAL) {
       portList.add(port.getName());
     }
   }
   portsDetected = (String[]) portList.toArray(new String[0]);
   return portsDetected;
 }
コード例 #27
0
  /** 获得所有可用串口 */
  public ArrayList<String> getAllports() {
    @SuppressWarnings("rawtypes")
    Enumeration portList = CommPortIdentifier.getPortIdentifiers();
    CommPortIdentifier portId;

    while (portList.hasMoreElements()) {
      portId = (CommPortIdentifier) portList.nextElement();
      if (portId.getPortType() == CommPortIdentifier.PORT_SERIAL) {
        this.sPorts.add(portId.getName());
      }
    }
    System.out.println(this.sPorts.toString());
    return sPorts;
  }
コード例 #28
0
  @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;
  }
コード例 #29
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;
  }
コード例 #30
0
  @SuppressWarnings("unchecked")
  public SerialTransmitController(String port, String rts_or_dtr) throws Exception {
    CommPortIdentifier pi = null;
    try {
      pi = CommPortIdentifier.getPortIdentifier(port);
    } catch (NoSuchPortException nspe) {
      String port_names = "";
      boolean comma = false;
      Enumeration<CommPortIdentifier> ports = CommPortIdentifier.getPortIdentifiers();
      while (ports.hasMoreElements()) {
        CommPortIdentifier portIdentifier = ports.nextElement();
        if (comma) port_names += ",";
        port_names += portIdentifier.getName();
        comma = true;
      }
      throw new IOException(
          String.format("Port %s is not valid (valid ports are %s)", port, port_names));
    }
    CommPort ptt_comm_port = null;
    try {
      ptt_comm_port = pi.open(this.getClass().getName(), 1000);
    } catch (PortInUseException piue) {
      throw new IOException(String.format("Port %s is in use", port));
    }
    if (ptt_comm_port instanceof SerialPort) {
      ptt_serial_port = (SerialPort) ptt_comm_port;
      // serialPort.setSerialPortParams(57600,SerialPort.DATABITS_8,
      //		                           SerialPort.STOPBITS_1,SerialPort.PARITY_NONE);
    } else {
      System.err.println("5");
      throw new IOException(String.format("Port %s is not a serial port", port));
    }

    ptt_serial_port.setRTS(false);
    ptt_serial_port.setDTR(false);

    System.err.println("Opened a PTT port: " + port);

    if (rts_or_dtr.equalsIgnoreCase("RTS")) {
      rts = true;
      return;
    }
    if (rts_or_dtr.equalsIgnoreCase("DTR")) {
      dtr = true;
      return;
    }

    throw new IOException(String.format("Signal %s is not valid (must be RTS or DTR)", rts_or_dtr));
  }