public static void main(String[] args) { /* * 不带参数的getPortIdentifiers方法获得一个枚举对象 * , * 该对象又包含了系统中管理每个端口的CommPortIdentifier对象 * 。 * 注意这里的端口不仅仅是指串口,也包括并口 * 。这个方法还可以带参数。 * getPortIdentifiers * (CommPort) * 获得与已经被应用程序打开的端口相对应的CommPortIdentifier对象 * 。 * getPortIdentifier * (String * portName)获取指定端口名 * (比如“COM1”) * 的CommPortIdentifier对象 * 。 */ portList = CommPortIdentifier.getPortIdentifiers(); while (portList.hasMoreElements()) { portId = (CommPortIdentifier) portList.nextElement(); if (portId.getPortType() == CommPortIdentifier.PORT_SERIAL) /* getPortType方法返回端口类型 */ { if (portId.getName().equals(CommPortUtil.getCommPortName())) /* 找Windows下的第一个串口*/ { // if (portId.getName().equals("/dev/term/a"))/* // * 找Unix-like系统下的第一个串口 // */{ @SuppressWarnings("unused") SimpleRead reader = new SimpleRead(); } } } }
/** * 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"); } }
public static void main(String[] args) { portList = CommPortIdentifier.getPortIdentifiers(); // hasMoreElements()指的是,是否還有其它物件內容 while (portList.hasMoreElements()) { portId = (CommPortIdentifier) portList.nextElement(); System.out.println(" " + portId.getName()); // 取得通訊埠的名稱,例如:COM1、COM2 } }
/*! 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)); }
/** * Check that the port specified is in fact available; * * @return true or false */ public static boolean isPortAvailable(String portName) { Enumeration enumr = CommPortIdentifier.getPortIdentifiers(); while (enumr.hasMoreElements()) { CommPortIdentifier comId = (CommPortIdentifier) enumr.nextElement(); if (comId.getPortType() == CommPortIdentifier.PORT_SERIAL) { if (portName.equalsIgnoreCase(comId.getName())) { return true; } } } return false; }
public Connection(String device, Dumper dumper) throws NoSuchPortException, PortInUseException, UnsupportedCommOperationException, IOException { this.device = device; this.dumper = dumper; this.portIdentifier = CommPortIdentifier.getPortIdentifier(this.device); this.serialPort = (SerialPort) portIdentifier.open(this.getClass().getName(), 2000); this.serialPort.setSerialPortParams( 57600, SerialPort.DATABITS_8, SerialPort.STOPBITS_1, SerialPort.PARITY_NONE); this.inputStream = this.serialPort.getInputStream(); this.outputStream = this.serialPort.getOutputStream(); }
public SimpleRead() { try { /* * open方法打开通讯端口 * , * 获得一个CommPort对象 * 。 * 它使程序独占端口 * 。 * 如果端口正被其他应用程序占用 * ,将使用 * CommPortOwnershipListener事件机制 * , * 传递一个PORT_OWNERSHIP_REQUESTED事件 * 。 * 每个端口都关联一个 * InputStream * 何一个OutputStream * 。 * 如果端口是用open方法打开的 * , * 那么任何的getInputStream都将返回相同的数据流对象 * , * 除非有close * 被调用 * 。有两个参数 * , * 第一个为应用程序名 * ; * 第二个参数是在端口打开时阻塞等待的毫秒数 * 。 */ serialPort = (SerialPort) portId.open("packinglinesmanage", 2000); } catch (PortInUseException e) { } try { inputStream = serialPort.getInputStream(); /* 获取端口的输入流对象 */ } catch (IOException e) { } try { serialPort.addEventListener(this); /* 注册一个SerialPortEventListener事件来监听串口事件 */ } catch (TooManyListenersException e) { } serialPort.notifyOnDataAvailable(true); /* 数据可用 */ try { serialPort.setSerialPortParams( 9600, SerialPort.DATABITS_8, SerialPort.STOPBITS_1, SerialPort.PARITY_NONE); /* * 设置串口初始化参数, * 依次是波特率 * ,数据位 * ,停止位和校验 */ } catch (UnsupportedCommOperationException e) { } readThread = new Thread(this); readThread.start(); }
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(); }
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; }
/** * Check that the port specified is in fact available; * * @return The portName specified, or, if not available, return first port found (to use as * default) */ public static String checkPortAvailable(String portName) { String firstPort = null; Enumeration enumr = CommPortIdentifier.getPortIdentifiers(); int i = 1; while (enumr.hasMoreElements()) { CommPortIdentifier comId = (CommPortIdentifier) enumr.nextElement(); if (comId.getPortType() == CommPortIdentifier.PORT_SERIAL) { if (i == 1) { firstPort = comId.getName(); } i++; if (portName.equalsIgnoreCase(comId.getName())) { return portName; } } } return firstPort; }
/** * -------------------------------------------------------------------------- Get serial ports * * @return String array of ports on workstation (may return null) */ public static String[] getAvailablePorts() { Enumeration enumr = CommPortIdentifier.getPortIdentifiers(); String[] retStr = null; ArrayList list = new ArrayList(); while (enumr.hasMoreElements()) { CommPortIdentifier comId = (CommPortIdentifier) enumr.nextElement(); if (comId.getPortType() == CommPortIdentifier.PORT_SERIAL) { list.add(comId.getName()); // System.out.println(comId.getName()); } } Object[] ports = list.toArray(); if (ports != null) { retStr = new String[ports.length]; for (int i = 0; i < ports.length; i++) { retStr[i] = (String) ports[i]; } } return retStr; }
public void connection() { try { portId = CommPortIdentifier.getPortIdentifier("COM10"); sPort = (SerialPort) portId.open("COM10", 1000); sPort.setSerialPortParams(9600, 8, 1, sPort.PARITY_NONE); is = sPort.getInputStream(); os = sPort.getOutputStream(); dis = new DataInputStream(is); dos = new DataOutputStream(os); } catch (NoSuchPortException e) { System.out.println("No Port\n" + e); } catch (PortInUseException e) { System.out.println("Port\n" + e); } catch (UnsupportedCommOperationException e) { System.out.println("Unsupported Problem\n" + e); } catch (IOException e) { System.out.println("IO Problem" + e); } catch (Exception e) { System.out.println("Unknown Problem" + e); } }
public void printAllPorts() { Enumeration ports = CommPortIdentifier.getPortIdentifiers(); if (ports == null) { System.out.println("No comm ports found!"); return; } // print out all ports System.out.println("printing all ports..."); while (ports.hasMoreElements()) { System.out.println(" " + ((CommPortIdentifier) ports.nextElement()).getName()); } System.out.println("done."); }
public static String getStatusOfPorts() { Enumeration enumr = CommPortIdentifier.getPortIdentifiers(); StringBuffer s = new StringBuffer(); while (enumr.hasMoreElements()) { CommPortIdentifier comId = (CommPortIdentifier) enumr.nextElement(); if (comId.getPortType() == CommPortIdentifier.PORT_SERIAL) { s.append(comId.getName() + ": "); if (comId.isCurrentlyOwned()) { s.append("owner: " + comId.getCurrentOwner() + " "); } else { s.append("no owner."); } s.append("\n"); } } return s.toString(); }
/** * Opens a device for subsequent I/O. * * @param logicalDeviceName Parameter specifies the device name to open * @param ec Callback event handler * @throws JposException */ public void open(String logicalDeviceName, EventCallbacks ec) throws JposException { // Check port opened if ((state != JposConst.JPOS_S_CLOSED) && (port != null)) throw new JposException( JposConst.JPOS_E_ILLEGAL, getErrorDescription(JposConst.JPOS_E_ILLEGAL)); powerNotify = JposConst.JPOS_PN_DISABLED; powerState = JposConst.JPOS_PS_UNKNOWN; // Read and check parameters // if (!jposEntry.getProp("deviceBus").getValueAsString().equalsIgnoreCase("RS232")) // throw new JposException(JposConst.JPOS_E_NOSERVICE, // getErrorDescription(JposConst.JPOS_E_NOSERVICE)); portName = jposEntry.getProp("portName").getValueAsString(); int baudRate = Integer.valueOf(jposEntry.getProp("baudRate").getValueAsString()); // if (!(jposEntry.getProp("dataBits").getValueAsString().equalsIgnoreCase("8") && // jposEntry.getProp("stopBits").getValueAsString().equalsIgnoreCase("1") && // jposEntry.getProp("parity").getValueAsString().equalsIgnoreCase("None"))) // throw new JposException(JposConst.JPOS_E_NOSERVICE, // getErrorDescription(JposConst.JPOS_E_NOSERVICE)); // Try find existen serial port for (DeviceService value : deviceServices.keySet()) { if (value.getPortName().equalsIgnoreCase(portName)) { port = deviceServices.get(value); break; } } // Open port if (port == null) { try { CommPortIdentifier portIdentifier = CommPortIdentifier.getPortIdentifier(portName); CommPort commPort = portIdentifier.open("CASHCODE", DeviceTiming.NON_RESPONSE); if (commPort instanceof SerialPort) { port = ((SerialPort) commPort); port.setSerialPortParams( baudRate, SerialPort.DATABITS_8, SerialPort.STOPBITS_1, SerialPort.PARITY_NONE); // Init timing responseTime = System.currentTimeMillis(); executeTime = responseTime + DeviceTiming.BUS_RESET; port.setFlowControlMode(SerialPort.FLOWCONTROL_NONE); port.setDTR(true); port.setRTS(true); port.setInputBufferSize(SIZE_BUFFER); port.setOutputBufferSize(SIZE_BUFFER); port.enableReceiveTimeout(DeviceTiming.INTER_BYTE); } else throw new JposException( JposConst.JPOS_E_NOSERVICE, getErrorDescription(JposConst.JPOS_E_NOSERVICE)); } catch (Exception e) { throw new JposException( JposConst.JPOS_E_NOSERVICE, getErrorDescription(JposConst.JPOS_E_NOSERVICE), e); } } // Streams try { is = port.getInputStream(); os = port.getOutputStream(); } catch (IOException e) { throw new JposException( JposConst.JPOS_E_FAILURE, getErrorDescription(JposConst.JPOS_E_FAILURE), e); } // Add reference to port deviceServices.put(this, port); // Set events callback handler eventCallbacks = ec; // Initialize device try { initialize(); state = JposConst.JPOS_S_IDLE; } catch (JposException e) { state = JposConst.JPOS_S_ERROR; startInit(DeviceTiming.RESET_NON_RESPONSE); } }
@Override public void open() { // r�cup�ration de l'identifiant du port try { logger.info("Liste des ports : " + CommPortIdentifier.getPortIdentifiers()); final Enumeration identifiers = CommPortIdentifier.getPortIdentifiers(); while (identifiers.hasMoreElements()) { logger.info(((CommPortIdentifier) identifiers.nextElement()).getName()); } portId = CommPortIdentifier.getPortIdentifier(connectionDescriptor.getPortName()); } catch (final NoSuchPortException e) { throw new RuntimeException( "Rs232Connector (" + connectionDescriptor.getPortName() + ") : " + e.toString()); } // ouverture du port try { serialPort = (SerialPort) portId.open("driver", 2000); } catch (final PortInUseException e) { throw new RuntimeException( "Rs232Connector (" + connectionDescriptor.getPortName() + ") : " + e.toString()); } // param�trage du port // hmmmmmmmmmmmm cf : // http://forum.java.sun.com/thread.jspa?threadID=673793&start=15&tstart=0 boolean result = false; while (!result) { try { serialPort.setSerialPortParams( connectionDescriptor.getBaudRate(), connectionDescriptor.getDataBits(), connectionDescriptor.getStopBits(), connectionDescriptor.getParity()); result = true; } catch (final Exception ex) { logger.error("Unable to set serial ports parameters", ex); result = false; try { Thread.sleep(200); } catch (final InterruptedException exc) { logger.error("Error while sleeping", exc); } } } /** @todo : test */ // Suppression try { serialPort.enableReceiveTimeout(5000); // timeout de 1 ms } catch (final UnsupportedCommOperationException ex) { logger.warn( "Warning : impossible to set timeout for port " + connectionDescriptor.getPortName(), ex); } try { // inputStream = new BufferedReader(new // InputStreamReader(serialPort.getInputStream())); inputStream = serialPort.getInputStream(); } catch (final IOException e) { serialPort.close(); throw new RuntimeException( "Rs232Connector (" + connectionDescriptor.getPortName() + ") : " + e.toString()); } try { serialPort.addEventListener( new SerialPortEventListener() { @Override public void serialEvent(final SerialPortEvent evt) { if (evt.getEventType() == SerialPortEvent.DATA_AVAILABLE) { synchronized (bufferMonitor) { if (writeIndex >= BUFFER_LENGTH - 1) { flushBuffer(); } try { byte newData = 0; while (newData != -1) { newData = (byte) inputStream.read(); if (newData == -1) { break; } if (writeIndex >= BUFFER_LENGTH - 1) { flushBuffer(); } buffer[writeIndex++] = newData; } } catch (final Exception exc) { logger.error("Error reading input stream from serial port", exc); } bufferMonitor.notify(); } } } }); serialPort.notifyOnDataAvailable(true); serialPort.enableReceiveTimeout(20); } catch (final TooManyListenersException exc) { logger.error("", exc); } catch (final UnsupportedCommOperationException exc) { logger.error("", exc); } final Thread threadParse = new Thread("Rs232Connector_" + connectionDescriptor.getPortName() + "_dispatch_thread") { @Override public void run() { try { parseThread(); } catch (final Exception e) { logger.error("Error while parsing thread", e); } } }; threadParse.start(); }
public Enumeration getAvalablePorts() { return CommPortIdentifier.getPortIdentifiers(); }
public static void main(String args[]) { // Command to turn of GPS int[] turn_off = new int[8]; turn_off[0] = DLE; turn_off[1] = Pid_Command_Packet; turn_off[2] = 2; // Length of data turn_off[3] = Cmnd_Turn_Off_Pwr; turn_off[4] = 0; turn_off[6] = DLE; turn_off[7] = ETX; calcChecksum(turn_off); System.out.println("Turn off checksum: " + turn_off[5]); // Command to ask GPS for time data. int[] transfer_time = new int[8]; transfer_time[0] = DLE; transfer_time[1] = Pid_Command_Packet; transfer_time[2] = 2; transfer_time[3] = Cmnd_Transfer_Time; transfer_time[4] = 0; transfer_time[6] = DLE; transfer_time[7] = ETX; calcChecksum(transfer_time); System.out.println("Transfer time" + transfer_time[5]); // Command to make a product request to the GPS. int[] product_request = new int[6]; product_request[0] = DLE; product_request[1] = Pid_Product_Rqst; product_request[2] = 0; product_request[4] = DLE; product_request[5] = ETX; calcChecksum(product_request); System.out.println("Product request:" + product_request[5]); // Command to ask GPS for position data int[] transfer_position = new int[8]; transfer_position[0] = DLE; transfer_position[1] = Pid_Command_Packet; transfer_position[2] = 2; transfer_position[3] = Cmnd_Transfer_Posn; transfer_position[4] = 0; transfer_position[6] = DLE; transfer_position[7] = ETX; calcChecksum(transfer_position); // Command to ask the GPS to start transmitting PVT data int[] start_PVT = new int[8]; start_PVT[0] = DLE; start_PVT[1] = Pid_Command_Packet; start_PVT[2] = 2; start_PVT[3] = Cmnd_Start_Pvt_Data; start_PVT[4] = 0; start_PVT[6] = DLE; start_PVT[7] = ETX; calcChecksum(start_PVT); // Acknowledge-packet. int[] ack = new int[8]; ack[0] = DLE; ack[1] = Pid_Ack_Byte; ack[2] = 2; ack[4] = 0; ack[6] = DLE; ack[7] = ETX; SerialPort port; BufferedInputStream input; BufferedOutputStream output; System.out.println("Using COM1."); // Open port. try { port = (SerialPort) CommPortIdentifier.getPortIdentifier("COM1").open("dk.itu.haas.GPS", 3000); } catch (NoSuchPortException e) { System.out.println("No such port!\n" + e.getMessage()); return; } catch (PortInUseException e) { System.out.println("Port already in use! (??!)\n" + e.getMessage()); return; } try { input = new BufferedInputStream(port.getInputStream()); output = new BufferedOutputStream(port.getOutputStream()); } catch (IOException e) { System.out.println("IOException... "); return; } System.out.println("Sending:"); printPacket(turn_off); sendPacket(output, turn_off); /* printPacket(transfer_position); sendPacket(output, transfer_position); */ /* printPacket(start_PVT); sendPacket(output, start_PVT); */ /* printPacket(product_request); sendPacket(output, product_request); */ System.out.println("--"); int[] packet; try { Thread.sleep(500); } catch (InterruptedException e) { } try { while (input.available() > 0) { packet = readPacket(input); if (packet != null) { System.out.println("Received:"); printPacket(packet); // Send acknowledge. ack[3] = packet[1]; calcChecksum(ack); sendPacket(output, ack); System.out.println("--"); } else { System.out.println("No packet received."); } try { Thread.sleep(5000); } catch (InterruptedException e) { } } } catch (IOException e) { System.out.println("IOError!"); return; } }
private void initialize() { // ========================================== /* * get System porperties: */ String operatingSystem = null; Properties p = System.getProperties(); Enumeration e = p.elements(); while (e.hasMoreElements()) { operatingSystem = e.nextElement().toString(); // System.out.println(operatingSystem); if (operatingSystem.equals("Linux")) { logger.debug("found " + operatingSystem + " Operating System"); comPort = "/dev/ttyS0"; break; } if (operatingSystem.equals("Windows XP")) { logger.debug("found " + operatingSystem + " Operating System"); comPort = "COM1"; break; } // if(operatingSystem.equals("Linux") || operatingSystem.equals("Windows")) { // logger.debug("found "+operatingSystem+" Operating System"); // break; // } } // ===============end=========================== Enumeration pList = CommPortIdentifier.getPortIdentifiers(); // logger.debug("(Khepera) initializeeeee()..."); while (pList.hasMoreElements()) { CommPortIdentifier cpi = (CommPortIdentifier) pList.nextElement(); if (cpi.getName().equals(comPort)) { try { com = null; com = (SerialPort) cpi.open("KHEPERA_" + comPort, 1000); try { // ======================================== /* under Linux this block is crucial to setSerialPortParams() * - i have no idea why... */ String s = "default settings: " + com.getBaudRate() + " " + com.getDataBits() + " " + com.getParity() + " " + com.getStopBits(); System.out.println(s); // ===============end========================= com.setSerialPortParams( 57600, SerialPort.DATABITS_8, SerialPort.STOPBITS_2, SerialPort.PARITY_NONE); System.out.println( "Current settings: " + com.getBaudRate() + " " + com.getDataBits() + " " + com.getParity() + " " + com.getStopBits()); } catch (UnsupportedCommOperationException e1) { logger.debug("(Khepera) UnsupportedCommOperation: " + e1); e1.printStackTrace(); } // try { // com.setSerialPortParams(BAUDRATE, // com.DATABITS_8, // com.STOPBITS_2, // com.PARITY_NONE); // com.setFlowControlMode(com.FLOWCONTROL_NONE); // } catch (UnsupportedCommOperationException e1) { // logger.debug("(Khepera) UnsupportedCommOperation: "+e1); // e1.printStackTrace(); // } logger.debug("[Khepera.initialize()] established " + comPort); out = null; out = com.getOutputStream(); inStream = null; inStream = com.getInputStream(); byte[] readBuffer2 = new byte[1000]; if (inStream.available() > 0) { int numBytes2 = inStream.read(readBuffer2); String result2 = new String(readBuffer2, 0, numBytes2); logger.debug("result2: " + result2); } // in = null; in = new BufferedReader(new InputStreamReader(inStream)); bufferedKheperaAnswer = new BufferedKheperaAnswer(logger, inStream, this, writelock, debug, operatingSystem); try { com.addEventListener(bufferedKheperaAnswer); com.notifyOnOutputEmpty(true); com.notifyOnDataAvailable(true); com.notifyOnOverrunError(true); com.notifyOnBreakInterrupt(true); com.notifyOnCarrierDetect(true); com.notifyOnCTS(true); com.notifyOnDSR(true); com.notifyOnFramingError(true); com.notifyOnParityError(true); com.notifyOnRingIndicator(false); } catch (TooManyListenersException e1) { logger.debug( "[Khepera.initialize()] can not add further eventListeners to serialPort object" + e); e1.printStackTrace(); } } catch (PortInUseException e2) { logger.debug("[Khepera.initialize()] Port in use: " + e2); e2.printStackTrace(); } catch (IOException e3) { logger.debug( "[Khepera.initialize()] IOException while initialising COMport: <" + comPort + ">" + e); e3.printStackTrace(); } break; } } if (com == null) logger.error( "[Khepera.initialize()] unable to find specified COMport " + comPort + ". giving up! (the robot is not connected yet.)"); else { logger.debug("[Khepera.initialize()] starting bufferedKheperaAnswer.start()"); bufferedKheperaAnswer.start(); if (debug) logger.debug("[Khepera.initialize()] initialize() finished"); update = new KheperaUpdateManager(this, logger, debug); logger.debug("[Khepera.initialize()] starting KheperaUpdateManager update.start()"); update.start(); } }