📄 basecommunicator.java
字号:
/* * BaseCommunicator.java * * Created on June 12, 2003, 3:33 PM */package gov.nist.examples.bps.reader.baselistener;import javax.comm.*;import java.io.*;import java.util.*;/** * @author Deruelle Olivier*/public class BaseCommunicator { private CommPortIdentifier portId; private Enumeration portList; private SerialPort serialPort; private CommandManager commandManager; private OutputStream os; private InputStream is; public static final String COM1="COM1"; public static final String COM2="COM2"; private String serialPortIdentifier; private int localPort; /** */ public BaseCommunicator(String serialPortIdentifier,int localPort){ this.serialPortIdentifier=serialPortIdentifier; this.localPort=localPort; } /** */ public void connect() { portList = CommPortIdentifier.getPortIdentifiers(); if (portList==null) { SerialDebug.println("BaseCommunicator, no serial ports found."); return; } while (portList.hasMoreElements()) { portId = (CommPortIdentifier) portList.nextElement(); SerialDebug.println("port found: - type: "+portId.getPortType()); SerialDebug.println(" - name: "+portId.getName()); if (portId.getPortType() == CommPortIdentifier.PORT_SERIAL) { if (portId.getName().equals(serialPortIdentifier)) { SerialDebug.println("Found the serial port: "+serialPortIdentifier); break; } } } try { serialPort = (SerialPort) portId.open("BaseCommunicator",localPort); SerialDebug.println("The serial port: "+serialPort+" is opened."); serialPort.setSerialPortParams(9600, SerialPort.DATABITS_8,SerialPort.STOPBITS_1,SerialPort.PARITY_NONE); } catch (PortInUseException e) { e.printStackTrace(); } catch (UnsupportedCommOperationException e) { e.printStackTrace(); } try { os = serialPort.getOutputStream(); is = serialPort.getInputStream(); } catch (IOException e) { serialPort.close(); e.printStackTrace(); } commandManager=new CommandManager(os,is,this); } public void reconnect() { try { disconnect(); serialPort = (SerialPort) portId.open("BaseCommunicator",localPort); SerialDebug.println("Reconnecting to the serial port..."); serialPort.setSerialPortParams(9600, SerialPort.DATABITS_8,SerialPort.STOPBITS_1,SerialPort.PARITY_NONE); os = serialPort.getOutputStream(); is = serialPort.getInputStream(); commandManager.is=is; commandManager.os=os; SerialDebug.println("Reconnected"); } catch (Exception e) { e.printStackTrace(); } } /** * Close the port and clean up associated elements. */ public void disconnect() { // Check to make sure sPort has reference to avoid a NPE. if (serialPort != null) { try { // close the i/o streams. os.close(); is.close(); } catch (Exception e) { e.printStackTrace(); } // Close the port. serialPort.close(); } } public CommandManager getCommandManager() { return commandManager; } public static void main(String[] args) { new BaseCommunicator("COM2",2000); } }
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -