Java串列埠助手(程式原始碼)
/**
* 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;
}
}
}
}
相關推薦
Java串列埠助手(程式原始碼)
/** * Java串列埠助手 * 本程式主要是模擬delphi/vc#/vb.net的窗體構架來簡化Java的SWT應用 */ package comm; import java.io.*; import java.util.*; import java.u
簡單的串列埠助手程式開發
1.簡介 之前在烽火集團實習的時候,開發串列埠通訊程式用的都是純C++。感覺串列埠程式開發很考驗人的邏輯思考能力。不過,現在好了,科研工作中,一切已存在的“利器”都可以用來為自己的“idea”服務。
java掉plc串列埠通訊helloworld原始碼
import spr.uhf.*; import spr.uhf.server.Collector; import spr.uhf.server.SocketListener; public class TestClass implements TagEvent,Ru
PC通過串列埠助手如何給單片機發送小數,微控制器接收後如何處理?
兩種思路,供參考。1. 原始位元組按原始位元組資料傳送,這也是我個人比較傾向的方式。首先,位、位元組和位元組流本身沒有任何意義,如果按約定的方式去解析,才能有具體的含義。用什麼約定方式呢?使用符合IEEE 754的浮點數標準,每個浮點數為4個位元組,按標準解析就可以了。其實這個標準,包括STM32在
轉 [經驗] STM32 USB虛擬串列埠(有原始碼)
原文出處:http://bbs.elecfans.com/jishu_467116_1_1.html 串列埠除錯在專案中被使用越來越多,串列埠資源的緊缺也變的尤為突出。很多本本人群,更是深有體會,不準備一個USB轉串列埠工具就沒辦法進行開發。本章節來簡單概述STM32低端晶片上
windows下C語言版串列埠接收程式(基於VS2017)
#include "pch.h" #define _CRT_SECURE_NO_WARNINGS #include <iostream> #include <stdio.h> #include <windows.h> #include <s
windows下C語言版串列埠傳送程式(基於VS2017)
#include "pch.h" #define _CRT_SECURE_NO_WARNINGS #include <stdio.h> #include <windows.h> #include <string.h> #include <conio.h&
C語言RL78 serial bootloader和C#語言bootloader PC端串列埠通訊程式
瞭解更多關於bootloader 的C語言實現,請加我QQ: 1273623966 (驗證資訊請填 bootloader),歡迎諮詢或定製bootloader(線上升級程式)。 前段時間完成的hyperboot_rl78, 是專門為Renesas 16-bit微控制器RL78 通
STM32 UART串列埠驅動程式
文章原始地址: http://feotech.com/?p=56 示例1.通過UART1進行資料傳送 UART 1 的初始化 /** * @brief UART1 Initialise. * @param None. * @retval None. */ void UART
QT下的串列埠通訊例項(原始碼可下載QT5下測試通過)
在不瞭解QT下的串列埠如何呼叫的時候,我們可以首先到QT的官網上尋找答案,首先,我們可以訪問:以下網址,搜尋serial port qt,可以得到很多相關的線索 http://doc.qt.io/ 這個QSerialport類十分豐富,比VC中的使用起來更方便,如下網址,我們可以檢視它的所
S3C2440裸機程式【2】串列埠uart程式
學習ARM7晶片stm32時,裸機程式開發可以很方便的根據庫函式在工程模板上進行開發,而ARM9主要是移植Linux開發,很少有裸機程式開發,因此在玩S3C2440希望最終形成一個keil環境下的模板。用的淘寶上的JZ2440v
你聽說過嗎:使用網頁技術開發桌面串列埠助手工具
串列埠助手是嵌入式開發中常用到的一個桌面工具,用於串列埠除錯,而Angular 是一個Web應用框架。桌面端原生功能和硬體操作似乎永遠都不會和Web發生直接關係。然而,隨著JavaScript技術的進步和變革,一切都成為可能。Electron 是一個使用 JavaScript, HTML 和 CSS 等 We
java 串列埠除錯 感測器指令傳送與資料接收
本文主要講述串列埠除錯的Java工具類,並實現迴圈傳送指令,接收資料!! 本文主要實現的功能是呼叫工具類中開啟串列埠方法,連線感測器所在串列埠,向串列埠(感測器)傳送指令,並接收串列埠(感測器)資料。 主函式-----main(): public sta
NanoPC-T3 plus 串列埠通訊程式程式碼
我是用的是NanoPC-T3plus 串列埠UART0(除錯串列埠接收的資料不全,不知道什麼原因),將程式碼改成程式中的const char *DeviceName = "/dev/ttyS0"的ttyS0改成ttySAC0即可使用; 本程式摘自友善之臂最新Linux示例(光碟
pc 串列埠控制檯程式
//#include "stdafx.h" #include <stdio.h> #include <stdlib.h> #include <windows.h> #include <Strsafe.h> #include<iostream>
Java串列埠接收資料顯示到label上
最近有個小任務,就是把下位機發送過來的資料實時顯示到label上,一直沒有頭緒, 後來看到了這篇博文,連結: 不如也開個執行緒,實時的取資料; 下面的是通過com口接收資料的程式碼,因為沒有用到傳送的部分,所以註釋掉了; com3,波特率9600 import
C# 串列埠助手小應用
C# 串列埠助手小應用 一、簡述 記--使用C#+VS2010編寫簡單的串列埠助手小應用。(測試版本) 工程打包:連結: https://pan.baidu.com/
(轉)VC串列埠小程式(用SerialPort類)
××××××××××××××××××××××××××××××××××××××××××××××××××××× 在MFC裡面實現串列埠通訊有很多方式: 方案一:使用微軟公司提供的 串列埠類,SerialPort。這是官方的東西 有最大的靈活性和可靠性。 我的主攻選擇為這
STC15F2K60S2/STC15系列讀取MPU6050陀螺儀角度加速度串列埠顯示程式程式碼
STC15F2K60S2/STC15系列讀取MPU6050陀螺儀角度加速度串列埠顯示程式程式碼 除錯通過,複製貼上即編譯可使用,無需除錯,晶振:24M,串列埠輸出,波特率:115200 為方便大家除錯,特附該程式的專案檔案,下載開啟即可除錯,下載地址:http://download.cs