Java串口通信 RXTX 解决过程
背景介绍:
由于第一次用Java与硬件通信,网上查了许多资料,在这进行整理,便于以后学习。本人串口测试是USB串口设备连接电脑,在设备管理器中找到端口名称(也可以通过一些虚拟串口工具模拟)。
下面主要简述获取串口消息返回值的一些问题,在最下面将会附上完整代码。
准备工作:
RXTX包:mfz-rxtx-2.2-20081207-win-x64.zip,解压,RXTXcomm.jar加入项目依赖库里,rxtxParallel.dll和rxtxSerial.dll放入jdk的bin目录下(我使用的jdk1.8)
RXTX工具类编写:
编写基础方法:获取可用端口名,开启端口,发送命令,接受命令,关闭端口
import gnu.io.*;
import javax.sound.midi.SoundbankResource;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;
import java.util.TooManyListenersException;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;
import java.util.TooManyListenersException;
import static com.why.rxtx.utill.HexadecimalUtil.get16NumAdd0;
import static com.why.rxtx.utill.HexadecimalUtil.hexStringToByteArray;
import static com.why.rxtx.utill.OrderUtil.retuenLogOrder;
import static com.why.rxtx.utill.OrderUtil.send;
import static com.why.rxtx.utill.HexadecimalUtil.hexStringToByteArray;
import static com.why.rxtx.utill.OrderUtil.retuenLogOrder;
import static com.why.rxtx.utill.OrderUtil.send;
/**
* 使用rxtx连接串口工具类
*/
public class RXTXUtil {
* 使用rxtx连接串口工具类
*/
public class RXTXUtil {
private static final String DEMONAME = "串口测试";
/**
* 检测系统中可用的端口
*/
private CommPortIdentifier portId;
/**
* 获得系统可用的端口名称列表
*/
private static Enumeration<CommPortIdentifier> portList;
/**
* 输入流
*/
private static InputStream inputStream;
/**
* RS-232的串行口
*/
private static SerialPort serialPort;
/**
* 返回结果
*/
private static String res=null;
* 检测系统中可用的端口
*/
private CommPortIdentifier portId;
/**
* 获得系统可用的端口名称列表
*/
private static Enumeration<CommPortIdentifier> portList;
/**
* 输入流
*/
private static InputStream inputStream;
/**
* RS-232的串行口
*/
private static SerialPort serialPort;
/**
* 返回结果
*/
private static String res=null;
/**
* 获得系统可用的端口名称列表
* @return 可用端口名称列表
*/
@SuppressWarnings("unchecked")
public static void getSystemPort(){
List<String> systemPorts = new ArrayList<>();
//获得系统可用的端口
portList = CommPortIdentifier.getPortIdentifiers();
while(portList.hasMoreElements()) {
String portName = portList.nextElement().getName();//获得端口的名字
systemPorts.add(portName);
}
* 获得系统可用的端口名称列表
* @return 可用端口名称列表
*/
@SuppressWarnings("unchecked")
public static void getSystemPort(){
List<String> systemPorts = new ArrayList<>();
//获得系统可用的端口
portList = CommPortIdentifier.getPortIdentifiers();
while(portList.hasMoreElements()) {
String portName = portList.nextElement().getName();//获得端口的名字
systemPorts.add(portName);
}
}
/**
* 开启串口
* @param serialPortName 串口名称
* @param baudRate 波特率
* @return 串口对象
*/
public static void openSerialPort(String serialPortName,int baudRate) {
try {
//通过端口名称得到端口
CommPortIdentifier portIdentifier = CommPortIdentifier.getPortIdentifier(serialPortName);
//打开端口,(自定义名字,打开超时时间)
CommPort commPort = portIdentifier.open(serialPortName, 5000);
//判断是不是串口
if (commPort instanceof SerialPort) {
serialPort = (SerialPort) commPort;
//设置串口参数(波特率,数据位8,停止位1,校验位无)
serialPort.setSerialPortParams(baudRate, SerialPort.DATABITS_8, SerialPort.STOPBITS_1, SerialPort.PARITY_NONE);
// System.out.println("开启串口成功,串口名称:"+serialPortName);
}else {
//是其他类型的端口
throw new NoSuchPortException();
}
} catch (NoSuchPortException e) {
e.printStackTrace();
} catch (PortInUseException e) {
e.printStackTrace();
} catch (UnsupportedCommOperationException e) {
e.printStackTrace();
}
* 开启串口
* @param serialPortName 串口名称
* @param baudRate 波特率
* @return 串口对象
*/
public static void openSerialPort(String serialPortName,int baudRate) {
try {
//通过端口名称得到端口
CommPortIdentifier portIdentifier = CommPortIdentifier.getPortIdentifier(serialPortName);
//打开端口,(自定义名字,打开超时时间)
CommPort commPort = portIdentifier.open(serialPortName, 5000);
//判断是不是串口
if (commPort instanceof SerialPort) {
serialPort = (SerialPort) commPort;
//设置串口参数(波特率,数据位8,停止位1,校验位无)
serialPort.setSerialPortParams(baudRate, SerialPort.DATABITS_8, SerialPort.STOPBITS_1, SerialPort.PARITY_NONE);
// System.out.println("开启串口成功,串口名称:"+serialPortName);
}else {
//是其他类型的端口
throw new NoSuchPortException();
}
} catch (NoSuchPortException e) {
e.printStackTrace();
} catch (PortInUseException e) {
e.printStackTrace();
} catch (UnsupportedCommOperationException e) {
e.printStackTrace();
}
}
/**
* 向串口发送数据
* @param order 发送的命令
*/
public static void sendData( String order) {
//16进制表示的字符串转换为字节数组
byte[] data =hexStringToByteArray(order);
OutputStream os = null;
try {
os = serialPort.getOutputStream();//获得串口的输出流
os.write(data);
os.flush();
} catch (IOException e) {
e.printStackTrace();
} finally {
//关闭流操作
try {
if (os != null) {
os.close();
os = null;
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
* 向串口发送数据
* @param order 发送的命令
*/
public static void sendData( String order) {
//16进制表示的字符串转换为字节数组
byte[] data =hexStringToByteArray(order);
OutputStream os = null;
try {
os = serialPort.getOutputStream();//获得串口的输出流
os.write(data);
os.flush();
} catch (IOException e) {
e.printStackTrace();
} finally {
//关闭流操作
try {
if (os != null) {
os.close();
os = null;
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
/**
* 从串口读取数据
* @return 读取的数据
*/
public static String readData() {
//保存串口返回信息
StringBuffer res=new StringBuffer(40);
InputStream is = null;
byte[] bytes = null;
try {
is = serialPort.getInputStream();//获得串口的输入流
int bufflenth = is.available();//获得数据长度
while (bufflenth != 0) {
bytes = new byte[bufflenth];//初始化byte数组
is.read(bytes);
bufflenth = is.available();
}
if(bytes!=null) {
for (int i = 0; i < bytes.length; i++) {
//转换成16进制数(FF)
res.append(get16NumAdd0((bytes[i]&0xff)+"",2));
}
}
System.out.println("res: "+res.toString());
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (is != null) {
is.close();
is = null;
}
} catch(IOException e) {
e.printStackTrace();
}
}
* 从串口读取数据
* @return 读取的数据
*/
public static String readData() {
//保存串口返回信息
StringBuffer res=new StringBuffer(40);
InputStream is = null;
byte[] bytes = null;
try {
is = serialPort.getInputStream();//获得串口的输入流
int bufflenth = is.available();//获得数据长度
while (bufflenth != 0) {
bytes = new byte[bufflenth];//初始化byte数组
is.read(bytes);
bufflenth = is.available();
}
if(bytes!=null) {
for (int i = 0; i < bytes.length; i++) {
//转换成16进制数(FF)
res.append(get16NumAdd0((bytes[i]&0xff)+"",2));
}
}
System.out.println("res: "+res.toString());
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (is != null) {
is.close();
is = null;
}
} catch(IOException e) {
e.printStackTrace();
}
}
return res.toString();
}
}
/**
* 关闭串口
*
*/
public static void closeSerialPort() {
if(serialPort != null) {
serialPort.close();
//System.out.println("关闭了串口:"+serialPort.getName());
serialPort = null;
}
}
* 关闭串口
*
*/
public static void closeSerialPort() {
if(serialPort != null) {
serialPort.close();
//System.out.println("关闭了串口:"+serialPort.getName());
serialPort = null;
}
}
}