文章參考 飛機票
下載Rxtx.jar
下載地址位 http://files.cnblogs.com/files/Dreamer-1/mfz-rxtx-2.2-20081207-win-x64.zip (64位)
eclipse裏面導入RXTXcomm.jar
<dependency>
<groupId>com.ruoyi</groupId>
<artifactId>RXTXcomm</artifactId>
<version>0.0.1-SNAPSHOT</version>
</dependency>
然後右鍵項目-->import
爲防止運行過程中拋出 java.lang.UnsatisfiedLinkError 錯誤或 gnu.io 下的類找不到,請將rxtx解壓包中的 rxtxParallel.dll,rxtxSerial.dll 這兩個文件複製到 C:\Windows\System32 目錄下即可解決該錯誤
新增一個項目啓動是一起啓動的方法
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import com.ruoyi.web.core.config.ParamConfig;
import com.ruoyi.web.core.config.SerialPortUtils;
/**
* 繼承Application接口後項目啓動時會按照執行順序執行run方法
* 通過設置Order的value來指定執行的順序
*/
@Component
@Order(value = 10)
public class StartService implements ApplicationRunner {
@Override
public void run(ApplicationArguments args) throws Exception {
SerialPortUtils spu = new SerialPortUtils();
ParamConfig paramConfig = new ParamConfig("COM1", 9600, 0, 8, 1);
//初始化串口
spu.init(paramConfig);
}
}
SerialPortUtils裏面實現對串口的操作,裏面有一些自定義異常
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Enumeration;
import java.util.TooManyListenersException;
import org.springframework.stereotype.Component;
import com.ruoyi.common.exception.serialport.CustomException;
import com.ruoyi.common.exception.serialport.NoSuchPort;
import com.ruoyi.common.exception.serialport.NotASerialPort;
import com.ruoyi.common.exception.serialport.PortInUse;
import com.ruoyi.common.exception.serialport.ReadDataFromSerialPortFailure;
import com.ruoyi.common.exception.serialport.SendDataToSerialPortFailure;
import com.ruoyi.common.exception.serialport.SerialPortInputStreamCloseFailure;
import com.ruoyi.common.exception.serialport.SerialPortOutputStreamCloseFailure;
import com.ruoyi.common.exception.serialport.TooManyListeners;
import gnu.io.CommPortIdentifier;
import gnu.io.PortInUseException;
import gnu.io.SerialPort;
import gnu.io.SerialPortEvent;
import gnu.io.SerialPortEventListener;
import gnu.io.UnsupportedCommOperationException;
/**
* 串口參數的配置 串口一般有如下參數可以在該串口打開以前進行配置: 包括串口號,波特率,輸入/輸出流控制,數據位數,停止位和奇偶校驗。
*/
// 注:串口操作類一定要繼承SerialPortEventListener
@Component
public class SerialPortUtils implements SerialPortEventListener {
// 檢測系統中可用的通訊端口類
private CommPortIdentifier commPortId;
// 枚舉類型
private Enumeration<CommPortIdentifier> portList;
// RS232串口
private SerialPort serialPort;
// 輸入流
private InputStream inputStream;
// 輸出流
private OutputStream outputStream;
// 保存串口返回信息
private String data;
// 保存串口返回信息十六進制
private String dataHex;
/**
* 初始化串口
* @author LinWenLi
* @date 2018年7月21日下午3:44:16
* @Description: TODO
* @param: paramConfig 存放串口連接必要參數的對象(會在下方給出類代碼)
* @return: void
* @throws
*/
@SuppressWarnings("unchecked")
public void init(ParamConfig paramConfig) {
// 獲取系統中所有的通訊端口
portList = CommPortIdentifier.getPortIdentifiers();
// 記錄是否含有指定串口
boolean isExsist = false;
// 循環通訊端口
while (portList.hasMoreElements()) {
commPortId = portList.nextElement();
// 判斷是否是串口
if (commPortId.getPortType() == CommPortIdentifier.PORT_SERIAL) {
// 比較串口名稱是否是指定串口
if (paramConfig.getSerialNumber().equals(commPortId.getName())) {
// 串口存在
isExsist = true;
// 打開串口
try {
// open:(應用程序名【隨意命名】,阻塞時等待的毫秒數)
serialPort = (SerialPort) commPortId.open(Object.class.getSimpleName(), 2000);
// 設置串口監聽
serialPort.addEventListener(this);
// 設置串口數據時間有效(可監聽)
serialPort.notifyOnDataAvailable(true);
// 設置串口通訊參數:波特率,數據位,停止位,校驗方式
serialPort.setSerialPortParams(paramConfig.getBaudRate(), paramConfig.getDataBit(),
paramConfig.getStopBit(), paramConfig.getCheckoutBit());
} catch (PortInUseException e) {
new PortInUse().printStackTrace();;
} catch (TooManyListenersException e) {
new TooManyListeners().printStackTrace();;
} catch (UnsupportedCommOperationException e) {
new NotASerialPort().printStackTrace();;
}
// 結束循環
break;
}
}
}
// 若不存在該串口則拋出異常
if (!isExsist) {
new NoSuchPort().printStackTrace();;
}
}
/**
* 實現接口SerialPortEventListener中的方法 讀取從串口中接收的數據
*/
@Override
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: // 有數據到達
// 調用讀取數據的方法
readComm();
break;
default:
break;
}
}
/**
* 讀取串口返回信息
* @author LinWenLi
* @date 2018年7月21日下午3:43:04
* @return: void
*/
public void readComm() {
try {
inputStream = serialPort.getInputStream();
// 通過輸入流對象的available方法獲取數組字節長度
byte[] readBuffer = new byte[inputStream.available()];
// 從線路上讀取數據流
int len = 0;
while ((len = inputStream.read(readBuffer)) != -1) {
//獲取串口返回數據
data = new String(readBuffer, 0, len).trim();
//轉爲十六進制數據
dataHex = bytesToHexString(readBuffer);
System.out.println("data:" + data);
System.out.println("dataHex:" + dataHex);// 讀取後置空流對象
inputStream.close();
inputStream = null;
break;
}
} catch (IOException e) {
new ReadDataFromSerialPortFailure().printStackTrace();
}
}
/**
* 發送信息到串口
* @author LinWenLi
* @date 2018年7月21日下午3:45:22
* @param: data
* @return: void
* @throws
*/
public void sendComm(String data) {
byte[] writerBuffer = null;
try {
writerBuffer = hexToByteArray(data);
} catch (NumberFormatException e) {
new CustomException().printStackTrace();
}
try {
outputStream = serialPort.getOutputStream();
outputStream.write(writerBuffer);
outputStream.flush();
} catch (NullPointerException e) {
new NoSuchPort().printStackTrace();;
} catch (IOException e) {
new SendDataToSerialPortFailure().printStackTrace();;
}
}
/**
* 關閉串口
* @author LinWenLi
* @date 2018年7月21日下午3:45:43
* @Description: 關閉串口
* @param:
* @return: void
* @throws
*/
public void closeSerialPort() {
if (serialPort != null) {
serialPort.notifyOnDataAvailable(false);
serialPort.removeEventListener();
if (inputStream != null) {
try {
inputStream.close();
inputStream = null;
} catch (IOException e) {
new SerialPortInputStreamCloseFailure().printStackTrace();
}
}
if (outputStream != null) {
try {
outputStream.close();
outputStream = null;
} catch (IOException e) {
new SerialPortOutputStreamCloseFailure().printStackTrace();
}
}
serialPort.close();
serialPort = null;
}
}
/**
* 十六進制串口返回值獲取
*/
public String getDataHex() {
String result = dataHex;
// 置空執行結果
dataHex = null;
// 返回執行結果
return result;
}
/**
* 串口返回值獲取
*/
public String getData() {
String result = data;
// 置空執行結果
data = null;
// 返回執行結果
return result;
}
/**
* Hex字符串轉byte
* @param inHex 待轉換的Hex字符串
* @return 轉換後的byte
*/
public static byte hexToByte(String inHex) {
return (byte) Integer.parseInt(inHex, 16);
}
/**
* hex字符串轉byte數組
* @param inHex 待轉換的Hex字符串
* @return 轉換後的byte數組結果
*/
public static byte[] hexToByteArray(String inHex) {
int hexlen = inHex.length();
byte[] result;
if (hexlen % 2 == 1) {
// 奇數
hexlen++;
result = new byte[(hexlen / 2)];
inHex = "0" + inHex;
} else {
// 偶數
result = new byte[(hexlen / 2)];
}
int j = 0;
for (int i = 0; i < hexlen; i += 2) {
result[j] = hexToByte(inHex.substring(i, i + 2));
j++;
}
return result;
}
/**
* 數組轉換成十六進制字符串
* @param byte[]
* @return HexString
*/
public static final String bytesToHexString(byte[] bArray) {
StringBuffer sb = new StringBuffer(bArray.length);
String sTemp;
for (int i = 0; i < bArray.length; i++) {
sTemp = Integer.toHexString(0xFF & bArray[i]);
if (sTemp.length() < 2)
sb.append(0);
sb.append(sTemp.toUpperCase());
}
return sb.toString();
}
}
ParamConfig是串口連接的實體類
public class ParamConfig {
private String serialNumber;// 串口號
private int baudRate; // 波特率
private int checkoutBit; // 校驗位
private int dataBit; // 數據位
private int stopBit; // 停止位
public ParamConfig() {}
/**
* 構造方法
* @param serialNumber 串口號
* @param baudRate 波特率
* @param checkoutBit 校驗位
* @param dataBit 數據位
* @param stopBit 停止位
*/
public ParamConfig(String serialNumber, int baudRate, int checkoutBit, int dataBit, int stopBit) {
this.serialNumber = serialNumber;
this.baudRate = baudRate;
this.checkoutBit = checkoutBit;
this.dataBit = dataBit;
this.stopBit = stopBit;
}
public String getSerialNumber() {
return serialNumber;
}
public void setSerialNumber(String serialNumber) {
this.serialNumber = serialNumber;
}
public int getBaudRate() {
return baudRate;
}
public void setBaudRate(int baudRate) {
this.baudRate = baudRate;
}
public int getCheckoutBit() {
return checkoutBit;
}
public void setCheckoutBit(int checkoutBit) {
this.checkoutBit = checkoutBit;
}
public int getDataBit() {
return dataBit;
}
public void setDataBit(int dataBit) {
this.dataBit = dataBit;
}
public int getStopBit() {
return stopBit;
}
public void setStopBit(int stopBit) {
this.stopBit = stopBit;
}
}