/** To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.*/
packagetina;importjava.io.IOException;importjava.io.InputStream;importjava.io.OutputStream;importjava.io.PrintWriter;importjava.util.TooManyListenersException;importjava.util.logging.Level;importjava.util.logging.Logger;importjavax.comm.CommPortIdentifier;importjavax.comm.NoSuchPortException;importjavax.comm.PortInUseException;importjavax.comm.SerialPort;importjavax.comm.SerialPortEvent;importjavax.comm.SerialPortEventListener;importjavax.comm.UnsupportedCommOperationException;importjavax.swing.JOptionPane;/***
*@authorTina*/
public class DemoCom implementsSerialPortEventListener {private static final String PORT_NAME = "COM4"; //串口号
private static final int PORT_BAUDRATE = 115200; //波特率
private staticDemoCom instance;private finalSerialPort mSerialPort;private finalPrintWriter mWriter;private finalInputStream mInputStream;privateOnMsgArrivedListener mListener;private final StringBuffer buffer = newStringBuffer();public interfaceOnMsgArrivedListener {//收到字符
void OnMsgArrived(charc);
}private DemoCom(CommPortIdentifier portId, int baudrate) throwsPortInUseException, UnsupportedCommOperationException, IOException {
mSerialPort= (SerialPort) portId.open("DemoCom", baudrate);
mSerialPort.setSerialPortParams(baudrate,
SerialPort.DATABITS_8,//Data Bits
SerialPort.STOPBITS_1, //Stop Bits
SerialPort.PARITY_NONE); //无校验
mSerialPort.notifyOnDataAvailable(true);
OutputStream mOutputStream=mSerialPort.getOutputStream();
mInputStream=mSerialPort.getInputStream();
mWriter= newPrintWriter(mOutputStream);
}public staticDemoCom getInstance() {if (instance == null) {
CommPortIdentifier portId;try{
portId=(CommPortIdentifier) CommPortIdentifier.getPortIdentifier(PORT_NAME);
instance= newDemoCom(portId, PORT_BAUDRATE);
}catch(NoSuchPortException ex) {
JOptionPane.showMessageDialog(null, "没有找到串口" + PORT_NAME + ",请确认USB线是否连接好!");
System.exit(0);
}catch(PortInUseException ex) {
JOptionPane.showMessageDialog(null, "串口" + PORT_NAME + "被占用,请关闭其他可能占用的应用软件!");
System.exit(0);
}catch(UnsupportedCommOperationException ex) {
JOptionPane.showMessageDialog(null, "串口" + PORT_NAME + "打开失败:" +ex.getMessage());
System.exit(0);
}catch(IOException ex) {
JOptionPane.showMessageDialog(null, "串口" + PORT_NAME + "打开失败:" +ex.getMessage());
System.exit(0);
}
}returninstance;
}
@Overridepublic voidserialEvent(SerialPortEvent spe) {if (spe.getEventType() ==SerialPortEvent.DATA_AVAILABLE) {try{while (mInputStream.available() > 0) {//处理数据
int c =mInputStream.read();
buffer.append((char) c);//这里只是将数据传到其他需要监听串口数据的地方
if (mListener != null) {
mListener.OnMsgArrived((char) c);
}
}
}catch(IOException ex) {
Logger.getLogger(PortFixture.class.getName()).log(Level.SEVERE, null, ex);
}
}
}public String sendAndGet(String command, intdelayMs) {//发送命令
if (mWriter != null) {
mWriter.println(command);
mWriter.flush();
}//延时
try{
Thread.sleep(delayMs);
}catch(InterruptedException ex) {
Logger.getLogger(PortFixture.class.getName()).log(Level.SEVERE,null, ex);
}//查看回复的数据
if (!buffer.toString().isEmpty()) { //如果buffer非空
String str =buffer.toString();
System.out.println(buffer.toString());
buffer.delete(0, buffer.length());//读完之后清空
returnstr;
}else{return "";
}
}public voidsend(String command) {
buffer.delete(0, buffer.length());//发送之前清空
try{
Thread.sleep(10);
}catch(InterruptedException ex) {
Logger.getLogger(PortFixture.class.getName()).log(Level.SEVERE, null, ex);
}//发送命令
if (mWriter != null) {
mWriter.println(command);
mWriter.flush();
}
}public voidopen() {try{
mSerialPort.addEventListener(this);
}catch(TooManyListenersException ex) {
Logger.getLogger(PortFixture.class.getName()).log(Level.SEVERE,null, ex);
}//打开串口后,做一些处理
if (!sendAndGet("reset", 1000).toLowerCase().contains("ok")) {
JOptionPane.showMessageDialog(null, "无法复位!");
System.exit(0);
}
}public voidclose() {if (mWriter != null) {
mWriter.close();
}if (mInputStream != null) {try{
mInputStream.close();
}catch(IOException ex) {
Logger.getLogger(PortFixture.class.getName()).log(Level.SEVERE, null, ex);
}
}if (mSerialPort != null) {
mSerialPort.close();
}
}public voidsetOnMsgArrivedListener(OnMsgArrivedListener listener) {
mListener=listener;
}
}