本文中启动的串口为:COM5,以自己电脑开启的串口为准,改后即用
1.添加RXTXcomm.jar,放在项目的lib 目录下及 jre->lib->ext 即可
2.在jre -> bin目录下 添加如下文件
3.在jre ->lib 目录下添加如下文件
纯干货,CV即用 上菜
串口参数配置实体类
package com.mobilesms.serialport.config;
import gnu.io.SerialPort;
import lombok.Data;
/**
* 串口参数配置实体类
*/
@Data
public final class SerialPortParameter {
/**
* 串口名称,以COM开头(COM0、COM1、COM2等等)
*/
private String serialPortName;
/**
* 波特率, 默认:115200
*/
private int baudRate = 115200;
/**
* 数据位 默认8位
* 可以设置的值:SerialPort.DATABITS_5、SerialPort.DATABITS_6、SerialPort.DATABITS_7、SerialPort.DATABITS_8
*/
private int dataBits = SerialPort.DATABITS_8;
/**
* 停止位
* 可以设置的值:SerialPort.STOPBITS_1、SerialPort.STOPBITS_2、SerialPort.STOPBITS_1_5
*/
private int stopBits = SerialPort.STOPBITS_1;
/**
* 校验位
* 可以设置的值:SerialPort.PARITY_NONE、SerialPort.PARITY_ODD、SerialPort.PARITY_EVEN、SerialPort.PARITY_MARK、SerialPort.PARITY_SPACE
*/
private int parity = SerialPort.PARITY_NONE;
}
串口工具类
package com.mobilesms.serialport.utils;
import com.uav.common.exception.base.BaseException;
import com.uav.mobilesms.serialport.config.SerialPortParameter;
import gnu.io.*;
import lombok.extern.slf4j.Slf4j;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStreamWriter;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;
import java.util.TooManyListenersException;
/**
* 串口工具类
*/
@Slf4j
public class SerialPortUtil {
/**
* 获得系统可用的端口名称列表(COM0、COM1、COM2等等)
*
* @return List<String>可用端口名称列表
*/
@SuppressWarnings("unchecked")
public static List<String> getSerialPortList() {
List<String> systemPorts = new ArrayList<>();
// 获得本系统可用的端口
Enumeration<CommPortIdentifier> portList = CommPortIdentifier.getPortIdentifiers();
while (portList.hasMoreElements()) {
systemPorts.add(portList.nextElement().getName());
}
return systemPorts;
}
/**
* 打开串口
*
* @param serialPortName 串口名称
* @return SerialPort 串口对象
* @throws NoSuchPortException 对应串口不存在
* @throws PortInUseException 串口在使用中
* @throws UnsupportedCommOperationException 不支持操作操作
*/
public static SerialPort openSerialPort(String serialPortName)
throws NoSuchPortException, PortInUseException, UnsupportedCommOperationException {
SerialPortParameter parameter = new SerialPortParameter();
parameter.setSerialPortName(serialPortName);
return openSerialPort(parameter);
}
/**
* 打开串口
*
* @param parameter 串口参数
* @return SerialPort 串口对象
* @throws NoSuchPortException 对应串口不存在
* @throws PortInUseException 串口在使用中
* @throws UnsupportedCommOperationException 不支持操作操作
*/
public static SerialPort openSerialPort(SerialPortParameter parameter)
throws NoSuchPortException, PortInUseException, UnsupportedCommOperationException {
return openSerialPort(parameter, 2000);
}
/**
* 打开串口
*
* @param parameter 串口参数
* @param timeout 串口打开超时时间
* @return SerialPort串口对象
* @throws NoSuchPortException 对应串口不存在
* @throws PortInUseException 串口在使用中
* @throws UnsupportedCommOperationException 不支持操作操作
*/
public static SerialPort openSerialPort(SerialPortParameter parameter, int timeout)
throws NoSuchPortException, PortInUseException, UnsupportedCommOperationException {
// 通过端口名称得到端口
CommPortIdentifier portIdentifier = CommPortIdentifier.getPortIdentifier(parameter.getSerialPortName());
// 打开端口,(自定义名字,打开超时时间)
CommPort commPort = portIdentifier.open(parameter.getSerialPortName(), timeout);
// 判断是不是串口
if (commPort instanceof SerialPort) {
SerialPort serialPort = (SerialPort) commPort;
// 设置串口参数(波特率,数据位8,停止位1,校验位无)
serialPort.setSerialPortParams(parameter.getBaudRate(), parameter.getDataBits(), parameter.getStopBits(),
parameter.getParity());
log.info("开启串口成功,串口名称:{}", parameter.getSerialPortName());
return serialPort;
} else {
// 是其他类型的端口
throw new NoSuchPortException();
}
}
/**
* 关闭串口
*
* @param serialPort 要关闭的串口对象
*/
public static void closeSerialPort(SerialPort serialPort) {
if (serialPort != null) {
serialPort.close();
log.info("关闭了串口:{}", serialPort.getName());
}
}
/**
* 向串口发送数据
*
* @param serialPort 串口对象
* @param data 发送的数据
*/
public static void sendData(SerialPort serialPort, String data) {
OutputStreamWriter os = null;
try {
// 获得串口的输出流
os = new OutputStreamWriter(serialPort.getOutputStream());
os.write(data);
os.write('\r');
os.flush();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (os != null) {
os.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
/**
* 从串口读取数据
*
* @param serialPort 要读取的串口
* @return 读取的数据
*/
public static byte[] readData(SerialPort serialPort) {
InputStream is = null;
byte[] bytes = null;
try {
// 获得串口的输入流
is = serialPort.getInputStream();
// 获得数据长度
int bufflenth = is.available();
while (bufflenth != 0) {
// 初始化byte数组
bytes = new byte[bufflenth];
is.read(bytes);
bufflenth = is.available();
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (is != null) {
is.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return bytes;
}
/**
* 给串口设置监听
*
* @param serialPort serialPort 要读取的串口
* @param listener SerialPortEventListener监听对象
* @throws TooManyListenersException 监听对象异常
*/
public static void setListenerToSerialPort(SerialPort serialPort, SerialPortEventListener listener) throws TooManyListenersException {
// 给串口添加事件监听
serialPort.addEventListener(listener);
// 串口有数据监听
serialPort.notifyOnDataAvailable(true);
// 中断事件监听
serialPort.notifyOnBreakInterrupt(true);
}
public static void main(String[] args) {
String message = sendMessage("AT+DSTNUM=18234943228");
log.info(message);
}
public static String sendMessage(String msg) {
try {
final SerialPort serialPort = SerialPortUtil.openSerialPort("COM5");
new Thread(() -> {
SerialPortUtil.sendData(serialPort, msg);//发送数据
log.info("发送数据为:{}",msg);
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
log.error("睡眠失效", e);
Thread.currentThread().interrupt();
}
}).start();
//设置串口的listener
SerialPortUtil.setListenerToSerialPort(serialPort, event -> {
//数据通知
byte[] bytess = new byte[1024];
if (event.getEventType() == SerialPortEvent.DATA_AVAILABLE) {
bytess = SerialPortUtil.readData(serialPort);
log.info("收到的数据长度:{}", bytess.length);
log.info("收到的数据:{}" ,new String(bytess));
}
if(!new String(bytess).contains("OK")){
log.info("收到的数据:{}" ,new String(bytess));
throw new BaseException("配置失败,请检查后重新配置");
}
});
try {
//sleep 一段时间保证线程可以执行完
Thread.sleep(3000);
} catch (InterruptedException e) {
log.error("睡眠失效", e);
Thread.currentThread().interrupt();
return "ERROR";
}
} catch (Exception e) {
log.error("串口消息发送失败", e);
return "ERROR";
}
return "OK";
}
/**
* byte[]转16进制Str
*/
public static String byteArrayToHexStr(byte[] byteArray) {
if (byteArray == null) {
return null;
}
char[] hexArray = "0123456789ABCDEF".toCharArray();
char[] hexChars = new char[byteArray.length * 2];
for (int i = 0; i < byteArray.length; i++) {
int temp = byteArray[i] & 0xFF;
hexChars[i * 2] = hexArray[temp >>> 4];
hexChars[i * 2 + 1] = hexArray[temp & 0x0F];
}
return new String(hexChars);
}
}
pom配置
<dependency>
<groupId>gnu.io</groupId>
<artifactId>RXTXcomm</artifactId>
<version>2.2</version>
<scope>system</scope>
<systemPath>${project.basedir}/lib/RXTXcomm.jar</systemPath>
</dependency>
若启动报错,参加如下修改
1.找不到jar包
在C:\Windows\System32 下放入jar包
2.jdk报错
试着降低jdk版本尝试