Java串口助手(程序源码) 分类: Java 2015-07-30 10:13 16人阅读 评论(0) 收藏


 

/**
* Java串口助手 
* 本程序主要是模拟delphi/vc#/vb.net的窗体构架来简化Java的SWT应用
*/
package comm;


 

import java.io.*;
import java.util.*;
import java.util.Timer;
//import java.text.SimpleDateFormat;
//import java.util.Date;
 

import javax.comm.*;
 

//import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.swt.*;
import org.eclipse.swt.browser.Browser;
//import org.eclipse.swt.browser.CloseWindowListener;
//import org.eclipse.swt.browser.WindowEvent;
import org.eclipse.swt.events.*;
import org.eclipse.swt.layout.*;
import org.eclipse.swt.widgets.*;
 

//import org.eclipse.swt.graphics.Color;
 

public class CommReadWrite {//CommReadWrite只是摆设
public static void main(String[] args) {//main()只是摆设
new Form();//建立新窗体直接并运行
}
 

public static class Form implements SerialPortEventListener {
private Display display;
 

private Shell shell;
 

private Browser browser;
 

private Label status;
 

private Label datetime;
 

private Label labelPortName;
 

private Combo comboPortName;
 

private Label labelBaudrate;

private Combo comboBaudrate;
 

private Label labelByteSize;
 

private Combo comboByteSize;
 

private Label labelParity;
private Combo comboParity;
 

private Label labelStopBits;
 

private Combo comboStopBits;
 

private Button buttonOpen;
 

private Button buttonClose;
 

private Button buttonSend;
 

private Button buttonExit;
 

private Label labelWrite;
 

private Text textWrite;

private Label labelRead;
 

private Text textRead;
 

private String messageString = "菜农Java习作\n";
 

private Enumeration portList;
 

private CommPortIdentifier portId;
 

private OutputStream outputStream;
 

private InputStream inputStream;
 

private SerialPort serialPort;
 

private Timer TimerDisplay;
 

private byte[] readRxBuffer = new byte[2048];
 

private int readRxCount = 0;
 


public Form() {
Initialize();//窗体组件初始化
Load();// 窗体装载初始化
Event();// 监听事件处理
Run();//运行窗体程序
}


 

// public void finalize() {
// System.out.println("程序结束!!!");
// }
 

public void Initialize() {//窗体控件构建及初始化过程处理
display = new Display();// 创建一个Display对象
// shell = new Shell(display, SWT.CLOSE | SWT.SYSTEM_MODAL);//
// 创建一个Shell对象(程序的窗口)
shell = new Shell(display);// 创建一个Shell对象(程序的窗口)
shell.setText(" Java串口助手");// 窗口标题
 

shell.setLayout(new FormLayout());
 

Composite controls = new Composite(shell, SWT.NONE);
FormData data = new FormData();
data.top = new FormAttachment(0, 0);
data.left = new FormAttachment(0, 0);
data.right = new FormAttachment(100, 0);
controls.setLayoutData(data);
 

status = new Label(shell, SWT.NONE);
data = new FormData();
data.left = new FormAttachment(0, 0);
data.right = new FormAttachment(100, 0);
data.bottom = new FormAttachment(100, 0);
status.setLayoutData(data);
 

browser = new Browser(shell, SWT.BORDER);
data = new FormData();
data.top = new FormAttachment(controls);
data.bottom = new FormAttachment(status);
data.left = new FormAttachment(0, 0);
data.right = new FormAttachment(100, 0);
browser.setLayoutData(data);
 

browser.setText("Java 串口助手");
 

controls.setLayout(new GridLayout(11, false));
 

labelPortName = new Label(controls, SWT.BORDER);
comboPortName = new Combo(controls, SWT.DROP_DOWN | SWT.BORDER);
labelBaudrate = new Label(controls, SWT.BORDER);
comboBaudrate = new Combo(controls, SWT.DROP_DOWN | SWT.BORDER);
labelByteSize = new Label(controls, SWT.BORDER);
comboByteSize = new Combo(controls, SWT.DROP_DOWN | SWT.BORDER);
labelParity = new Label(controls, SWT.BORDER);
comboParity = new Combo(controls, SWT.DROP_DOWN | SWT.BORDER);
labelStopBits = new Label(controls, SWT.BORDER);
comboStopBits = new Combo(controls, SWT.DROP_DOWN | SWT.BORDER);
 

buttonOpen = new Button(controls, SWT.PUSH);
buttonClose = new Button(controls, SWT.PUSH);
 

labelRead = new Label(controls, SWT.BORDER);
textRead = new Text(controls, SWT.BORDER | SWT.MULTI);// 多行文本框
labelWrite = new Label(controls, SWT.BORDER);
textWrite = new Text(controls, SWT.BORDER | SWT.MULTI);// 多行文本框
 

buttonSend = new Button(controls, SWT.PUSH);
buttonExit = new Button(controls, SWT.PUSH);
 

datetime = new Label(controls, SWT.NONE);
datetime.setText("2008-11-18 11:11:11");
controls.setLayout(new GridLayout(10, false));
 

labelPortName.setText("串口号");
 

labelBaudrate.setText("波特率");
comboBaudrate.add("110");
comboBaudrate.add("300");
comboBaudrate.add("600");
comboBaudrate.add("1200");
comboBaudrate.add("2400");
comboBaudrate.add("4800");
comboBaudrate.add("9600");
comboBaudrate.add("14400");
comboBaudrate.add("15200");
comboBaudrate.add("28800");
comboBaudrate.add("38400");
comboBaudrate.add("56000");
comboBaudrate.add("57600");
comboBaudrate.add("115200");
comboBaudrate.add("128000");
comboBaudrate.add("256000");
comboBaudrate.add("512000");
comboBaudrate.add("921600");
comboBaudrate.select(6);// 9600


 

labelByteSize.setText("数据位");
comboByteSize.add("5");
comboByteSize.add("6");
comboByteSize.add("7");
comboByteSize.add("8");
comboByteSize.select(3);// 8


 

labelParity.setText("校验位");
comboParity.add("无");
comboParity.add("奇校验");
comboParity.add("偶校验");
comboParity.select(0);// 无


 

labelStopBits.setText("停止位");
comboStopBits.add("1");
comboStopBits.add("2");
comboStopBits.select(0);// 1


 

buttonOpen.setText("打开串口");// 按钮标题
buttonClose.setText("关闭串口");// 按钮标题
buttonSend.setText("发送数据");// 按钮标题
buttonExit.setText("退出系统");// 按钮标题
labelWrite.setText("发送数据区");
textWrite.setText(messageString);
labelRead.setText("接收数据区");


 

status.setText("系统提示:");


 

comboPortName.setToolTipText("选择合法串口");
comboBaudrate.setToolTipText("选择合法波特率");
comboByteSize.setToolTipText("选择合法数据位");
comboParity.setToolTipText("选择合法校验位");
comboStopBits.setToolTipText("选择合法停止位");


 

buttonOpen.setToolTipText("打开所选串口");
buttonClose.setToolTipText("关闭当前串口");
buttonSend.setToolTipText("发送所选串口数据");
buttonExit.setToolTipText("关闭当前窗口,并退出系统");
buttonSend.setToolTipText("发送所选串口数据");


 

textWrite.setToolTipText("双击发送文本框数据");
textRead.setToolTipText("双击清空文本框数据");


 

comboPortName.setEnabled(true);
comboBaudrate.setEnabled(true);
comboByteSize.setEnabled(true);
comboParity.setEnabled(true);
comboStopBits.setEnabled(true);
buttonOpen.setEnabled(true);
buttonClose.setEnabled(false);
buttonSend.setEnabled(false);
textWrite.setEnabled(false);
 

TimerDisplay = new Timer();
}
 

public void Load() {//装载及用户初始化处理过程
CommPortInit();// Comm控件初始化
comboPortName.setText(comboPortName.getItem(0));
}
 

public void Run() {//运行主窗体
shell.open();// 显示窗体
while (!shell.isDisposed())// 测试关闭窗口事件
{
if (!display.readAndDispatch())
display.sleep();// 休眠
}
this.Close();// 关闭窗体及资源
}
public void Close() {//关闭及卸载事件处理过程
if (serialPort != null)
serialPort.close();// 关闭串口
TimerDisplay.cancel();
this.display.dispose();// 显式地调用dispose() 方法来释放程序运行中所获得的资源
}
public void Event() {//添加所有事件(监听)处理过程
 

TimerDisplay.schedule(new TimerTask() {
public void run() {
Display.getDefault().asyncExec(new Runnable() {
// @Override
public void run() {
// Calendar Now = Calendar.getInstance();
// SimpleDateFormat fmt = new
// SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
// datetime.setText(fmt.format(Now.getTime()));
if (!shell.isDisposed()) {// 避免异常并显示本地日期和时间
// 不要理会系统的建议!!!toLocaleString方法很好(2008-11-18
// 11:11:11)
datetime.setText(Calendar.getInstance()
.getTime().toLocaleString());
}
}
});
}
}, 1000, 1);
 

textWrite.addMouseListener(new MouseAdapter() {
 

public void mouseDoubleClick(MouseEvent e) {// 鼠标双击事件处理
if (serialPort != null) {
try {
if (((Text) e.widget).getText().length() > 0) {
outputStream.write(((Text) e.widget).getText()
.getBytes());
status.setText("系统提示: " + "串口"
+ serialPort.getName() + "发送成功!!!");
} else
status.setText("系统提示: " + "串口"
+ serialPort.getName() + "空串发送失败!!!");
} catch (IOException ex) {
status.setText("系统提示: " + "串口"
+ serialPort.getName() + "发送失败!!!");
}
}
}
});
textRead.addMouseListener(new MouseAdapter() {
 

public void mouseDoubleClick(MouseEvent e) {// 鼠标双击事件处理
((Text) e.widget).setText("");
}
 

public void mouseDown(MouseEvent e) {// 鼠标单击事件处理
// MessageDialog.openInformation (null,"","Hello World");
// ((Text)e.widget).setText("1223");   }
 

public void mouseUp(MouseEvent e) {// 鼠标单击释放事件处理
// ((Text)e.widget).setText("");
}
});
 

buttonOpen.addSelectionListener(new SelectionAdapter() {// 加入按钮事件监听
public void widgetSelected(SelectionEvent e) {
portList = CommPortIdentifier.getPortIdentifiers();// 枚举端口
while (portList.hasMoreElements()) {// 枚举端口(串口)
portId = (CommPortIdentifier) portList
.nextElement();
if (portId.getPortType() == CommPortIdentifier.PORT_SERIAL) {// 只取串口设备
if (portId.getName().equals(
comboPortName.getText())) {
CommPortOpen();
}
}
}
}
});
 

buttonClose.addSelectionListener(new SelectionAdapter() {// 加入按钮事件监听
public void widgetSelected(SelectionEvent e) {
if (serialPort != null) {
status.setText("系统提示: " + "串口"
+ serialPort.getName() + "被关闭!!!");
serialPort.close();// 关闭串口
comboPortName.setEnabled(true);
comboBaudrate.setEnabled(true);
comboByteSize.setEnabled(true);
comboParity.setEnabled(true);
comboStopBits.setEnabled(true);
buttonOpen.setEnabled(true);
buttonClose.setEnabled(false);
buttonSend.setEnabled(false);
}
}
});
 

buttonSend.addSelectionListener(new SelectionAdapter() {// 加入按钮事件监听
public void widgetSelected(SelectionEvent e) {
if (serialPort != null) {
try {
if (textWrite.getText().length() > 0) {
outputStream.write(textWrite.getText()
.getBytes());
status.setText("系统提示: " + "串口"
+ serialPort.getName()
+ "发送成功!!!");
} else
status.setText("系统提示: " + "串口"
+ serialPort.getName()
+ "空串发送失败!!!");
} catch (IOException ex) {
status.setText("系统提示: " + "串口"
+ serialPort.getName() + "发送失败!!!");
}
}
}
});
 

buttonExit.addSelectionListener(new SelectionAdapter() {// 加入按钮事件监听
public void widgetSelected(SelectionEvent e) {
Close();
}
});
}
 

public void CommPortOpen() {
try {
if (serialPort != null)
serialPort.close();// 保证只打开一个串口
serialPort = (SerialPort) portId.open("CommReadWriteApp", 2000);
try {
outputStream = serialPort.getOutputStream();
try {
inputStream = serialPort.getInputStream();
try {
serialPort.addEventListener(this);
try {
serialPort.setSerialPortParams(Integer
.parseInt(comboBaudrate.getText()),
Integer.parseInt(comboByteSize
.getText()),// SerialPort.DATABITS_8,
Integer.parseInt(comboStopBits
.getText()),// SerialPort.STOPBITS_1,
comboParity.getSelectionIndex());// SerialPort.PARITY_NONE);
serialPort.notifyOnDataAvailable(true);// 打开监听
status
.setText("系统提示: " + "串口"
+ serialPort.getName()
+ "正常打开,监听开始!!!");
comboPortName.setEnabled(false);
comboBaudrate.setEnabled(false);
comboByteSize.setEnabled(false);
comboParity.setEnabled(false);
comboStopBits.setEnabled(false);
buttonOpen.setEnabled(false);
buttonClose.setEnabled(true);
buttonSend.setEnabled(true);
textWrite.setEnabled(true);
 

} catch (UnsupportedCommOperationException e) {
status.setText("系统提示: " + "串口"
+ serialPort.getName() + "设置异常!!!");
}
} catch (TooManyListenersException e) {
status.setText("系统提示: " + "串口"
+ serialPort.getName() + "监听事件异常!!!");
}
} catch (IOException e) {
status.setText("系统提示: " + "串口" + serialPort.getName()
+ "输入流输出异常!!!");
}
} catch (IOException e) {
status.setText("系统提示: " + "串口" + serialPort.getName()
+ "输出流输出异常!!!");
}
} catch (PortInUseException ex) {
status.setText("系统提示: " + "串口" + serialPort.getName()
+ "打开异常!!!");
}
}
public void CommPortInit() {
portList = CommPortIdentifier.getPortIdentifiers();// 枚举端口
while (portList.hasMoreElements()) {// 枚举端口(串口)
portId = (CommPortIdentifier) portList.nextElement();
if (portId.getPortType() == CommPortIdentifier.PORT_SERIAL) {// 只取串口设备
comboPortName.add(portId.getName());
}
}
}  
  public void serialEvent(SerialPortEvent event) {
switch (event.getEventType()) {
case SerialPortEvent.BI:
case SerialPortEvent.OE:
case SerialPortEvent.FE:
case SerialPortEvent.PE:
case SerialPortEvent.CD:
case SerialPortEvent.CTS:
case SerialPortEvent.DSR:
case SerialPortEvent.RI:
case SerialPortEvent.OUTPUT_BUFFER_EMPTY:
break;
case SerialPortEvent.DATA_AVAILABLE:
byte[] readBuffer = new byte[256];
try {
int numBytes = 0;
while (inputStream.available() > 0) {
numBytes = inputStream.read(readBuffer);
}
if (numBytes > 0) {
for (int i = 0; i < numBytes; i++) {
readRxBuffer[i + readRxCount] = readBuffer[i];
}
readRxCount += numBytes;
if (readBuffer[numBytes - 1] == '\n') {
readRxBuffer[readRxCount] = '\0';
Display.getDefault().asyncExec(new Runnable() {
// @Override
public void run() {
textRead.append(new String(readRxBuffer));
browser.setText(textRead.getText());
status.setText("系统提示: " + "串口"
+ serialPort.getName() + "输入成功!!!");
}
});
readRxCount = 0;
}
}
} catch (IOException e) {
Display.getDefault().asyncExec(new Runnable() {
// @Override
public void run() {
status.setText("系统提示: " + "串口"
+ serialPort.getName() + "输入失败!!!");
}
});
}
break;
}
}
}
}

posted @ 2015-07-30 10:13  xiexie2015  阅读(305)  评论(0编辑  收藏  举报