import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Enumeration;
import java.util.StringTokenizer;
import java.util.TooManyListenersException;
import javax.comm.CommPortIdentifier;
import javax.comm.PortInUseException;
import javax.comm.SerialPort;
import javax.comm.SerialPortEvent;
import javax.comm.SerialPortEventListener;
import javax.comm.UnsupportedCommOperationException;
/*
* Created on 2005-4-18 10:36:39
*
*/
/**
* @author zxub
*
*/
public class CommConnection implements SerialPortEventListener {
private Enumeration portList;
private String portName;
private CommPortIdentifier portId;//串口管理器,负责打开,调用,和初始化串口等管理工作
private SerialPort serialPort=null;
private int getReplyInterval;
private int commandDelay;
private String replyString;
private InputStream inputStream=null;
private OutputStream outputStream=null;
private int Baudrate;
private String sendMode;
private String message;
private int msgCount = 0;
public boolean errFlag = false;
public CommConnection() {
getSysConfig();
}
public void getSysConfig()
{
OperaXML ox = new OperaXML();
ox.read("config.xml");
this.portName = ox.getNodeValue("Config1/PortName");
this.Baudrate = Integer.parseInt(ox.getNodeValue("Config1/BAUDRATE"));
this.sendMode = ox.getNodeValue("Config1/SendMode");
this.getReplyInterval = Integer.parseInt(ox
.getNodeValue("Config1/GetReplyInterval"));
this.commandDelay = Integer.parseInt(ox
.getNodeValue("Config1/CommandDelay"));
ox.close();
}
//********************************************************************
//列出所有串口
public void listSerialPort() {
// CommPortIdentifier类的getPortIdentifiers方法可以找到系统所有的串口,
//每个串口对应一个CommPortIdentifier类的实例。
portList=null;
portId=null;
portList = CommPortIdentifier.getPortIdentifiers();
returnStateInfo("串口列表:");
while (portList.hasMoreElements()) {
portId = (CommPortIdentifier) portList.nextElement();
/* 如果端口类型是串口,则打印出其端口信息 */
if (portId.getPortType() == CommPortIdentifier.PORT_SERIAL) {
returnStateInfo(portId.getName());
}
}
returnStateInfo("串口列表显示结束!");
}
//********************************************************************
//********************************************************************
public void getSerialPort() {
if (this.errFlag == true)
return;
returnStateInfo("检查连接情况...");
if (this.portName == "") {
returnStateInfo("串口号为空,请检查配置文件!");
this.errFlag = true;
return;
//System.out.println("Portname is null, get err, the program now
// exit!");
//System.exit(0);
}
portList = CommPortIdentifier.getPortIdentifiers();
while (portList.hasMoreElements()) {
portId = (CommPortIdentifier) portList.nextElement();
if ((portId.getPortType() == CommPortIdentifier.PORT_SERIAL)
&& portId.getName().equalsIgnoreCase(this.portName)) {
try {
this.serialPort = (SerialPort) portId.open("SendSms", 2000);
} catch (PortInUseException e) {
returnStateInfo("获取" + this.portName + "时出错!原因:"
+ e.getMessage());
this.errFlag = true;
return;
}
}
}
}
public void listenSerialPort() {
if (this.errFlag == true)
return;
if (this.serialPort == null) {
returnStateInfo("不存在" + this.portName + ",请检查相关配置!");
this.errFlag = true;
return;
}
//设置输入输出流
try {
outputStream = (OutputStream) this.serialPort.getOutputStream();
inputStream = (InputStream) this.serialPort.getInputStream();
} catch (IOException e) {
returnStateInfo(e.getMessage());
}
try {
//监听端口
this.serialPort.notifyOnDataAvailable(true);
this.serialPort.notifyOnBreakInterrupt(true);
this.serialPort.addEventListener(this);
} catch (TooManyListenersException e) {
this.serialPort.close();
returnStateInfo(e.getMessage());
}
try {
this.serialPort.enableReceiveTimeout(20);
} catch (UnsupportedCommOperationException e) {
}
//设置端口的基本参数
try {
this.serialPort.setSerialPortParams(this.Baudrate,
SerialPort.DATABITS_8, SerialPort.STOPBITS_1,
SerialPort.PARITY_NONE);
} catch (UnsupportedCommOperationException e) {
}
} //********************************************************************
//********************************************************************
//对串口的读写操作
public void writeToSerialPort(String msgString) {
try {
this.outputStream.write(msgString.getBytes());
//CTRL+Z=(char)26
} catch (IOException e) {
System.out.println(e.getMessage());
}
}
private void waitForRead(int waitTime) {
try {
Thread.sleep(waitTime);
} catch (Exception e) {
System.out.println(e.getMessage());
}
}
public String readFromSerialPort(String messageString) {
int strLength;
String messageStr;
String returnString;
strLength = messageString.length();
messageStr = messageString.substring(strLength - 4, strLength - 2);
if (messageStr.equals("OK")) {
returnString = messageStr;
} else {
returnString = messageString;
}
messageStr = messageString.substring(strLength - 7, strLength - 2);
if (messageStr.equals("ERROR")) {
returnString = messageStr;
}
return returnString;
}
//********************************************************************
//********************************************************************
//操作结束,关闭所用资源
public void closeSerialPort() {
if (this.serialPort != null) {
try {
this.serialPort.close();
} catch (RuntimeException e) {
System.out.println(e.getMessage());
}
}
returnStateInfo("已断开连接!");
}
public void closeIOStream() {
if (this.inputStream!=null)
{
try {
this.inputStream.close();
} catch (IOException e) {
System.out.println(e.getMessage());
}
}
if (this.outputStream!=null)
{
try {
this.outputStream.close();
} catch (IOException e1) {
System.out.println(e1.getMessage());
}
}
//returnStateInfo("已关闭I/O流!");
}
//********************************************************************
public void setToNull()
{
if (this.serialPort!=null) this.serialPort.close();
this.serialPort = null;
this.inputStream=null;
this.outputStream=null;
}
//********************************************************************
//监听事件
public void serialEvent(SerialPortEvent e) {
StringBuffer inputBuffer = new StringBuffer();
int newData = 0;
switch (e.getEventType()) {
case SerialPortEvent.DATA_AVAILABLE ://DATA_AVAILABLE - 有数据到达
while (newData != -1) {
try {
newData = this.inputStream.read();
if (newData == -1) {
break;
}
if ('\r' == (char) newData) {
inputBuffer.append('\n');
} else {
inputBuffer.append((char) newData);
}
} catch (IOException ex) {
System.err.println(ex);
return;
}
}
this.message = this.message + new String(inputBuffer);
break;
case SerialPortEvent.BI ://BI - 通讯中断.
System.out.println("\n--- BREAK RECEIVED ---\n");
}
}
//*****************************************************************
//*****************************************************************
//信息发送
public void sendmsg(String messageString, String phoneNumber) {
boolean sendSucc = false;
getSerialPort();
listenSerialPort();
checkConn();
if (this.errFlag == true)
return;
int msglength;
String sendmessage, tempSendString;
returnStateInfo("开始发送...");
switch (Integer.parseInt(this.sendMode)) {
case 0 ://按PDU方式发送
{
this.message = "";
writeToSerialPort("AT+CMGF=0\r");