java调用串口详解
1,下载调用串口工具包
根据对应平台下载对应工具包
http://fizzed.com/oss/rxtx-for-java
2,拷贝对应文件到jdk指定目录下
RXTXcomm.jar ---> <JAVA_HOME>\jre\lib\ext
rxtxSerial.dll ---> <JAVA_HOME>\jre\bin
rxtxParallel.dll ---> <JAVA_HOME>\jre\bin
3,将工程导入jar
将RXTXcomm.jar安装到java工程中
4,串口操作工具示例代码
工具类
package com.bami.common.serial_com;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;
import java.util.TooManyListenersException;
import gnu.io.CommPort;
import gnu.io.CommPortIdentifier;
import gnu.io.NoSuchPortException;
import gnu.io.PortInUseException;
import gnu.io.SerialPort;
import gnu.io.SerialPortEventListener;
import gnu.io.UnsupportedCommOperationException;
public class SerialComKit {
public static List<String> findPort() {
@SuppressWarnings("unchecked")
Enumeration<CommPortIdentifier> portList =
CommPortIdentifier.getPortIdentifiers();
List<String> portNameList = new ArrayList<>(9);
while (portList.hasMoreElements()) {
String portName = portList.nextElement().getName();
portNameList.add(portName);
}
return portNameList;
}
public static SerialPort openPort(
String portName,
int baudrate) throws NoSuchPortException, PortInUseException, UnsupportedCommOperationException{
CommPortIdentifier portIdentifier =
CommPortIdentifier.getPortIdentifier(portName);
CommPort commPort = portIdentifier.open(portName, 3000);
if (commPort instanceof SerialPort) {
SerialPort serialPort = (SerialPort) commPort;
serialPort.setSerialPortParams(
baudrate, SerialPort.DATABITS_8,
SerialPort.STOPBITS_1,
SerialPort.PARITY_NONE);
return serialPort;
}else {
return null;
}
}
public static void closePort(
SerialPort serialPort) {
if (serialPort != null) {
try {
serialPort.removeEventListener();
serialPort.close();
serialPort = null;
} catch (Exception e) {
}
}
}
public static boolean sendToPort(
SerialPort serialPort,
byte[] data) throws Exception{
OutputStream out = null;
try {
out = serialPort.getOutputStream();
out.write(data);
out.flush();
return true;
} catch (IOException e) {
return false;
} finally {
try {
if (out != null) {
out.close();
out = null;
}
} catch (IOException e) {
}
}
}
public static byte[] readFromPort(
SerialPort serialPort) {
InputStream in = null;
byte[] bytes = null;
try {
in = serialPort.getInputStream();
int bufflenth = in.available();
while (bufflenth != 0) {
bytes = new byte[bufflenth];
in.read(bytes);
bufflenth = in.available();
}
} catch (IOException e) {
return null;
} finally {
try {
if (in != null) {
in.close();
in = null;
}
} catch(IOException e) {
}
}
return bytes;
}
public static void addListener(
SerialPort port,
SerialPortEventListener listener) throws TooManyListenersException{
port.addEventListener(listener);
port.notifyOnDataAvailable(true);
port.notifyOnBreakInterrupt(true);
}
public static void main(String[] args) {
List<String> findPort = SerialComKit.findPort();
System.out.println(findPort);
}
}
自定义监听类
package com.bami.service.v1.instruc;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
import org.apache.commons.lang3.StringUtils;
import com.bami.common.serial_com.SerialComKit;
import com.bami.common.spring.SpringUtils;
import com.bami.pojo.client.B9JiYunClient;
import gnu.io.SerialPort;
import gnu.io.SerialPortEvent;
import gnu.io.SerialPortEventListener;
public class SerialPortListener implements SerialPortEventListener{
private String dataFlag;
private SerialPort serialPort;
public SerialPortListener(SerialPort serialPort) {
this.serialPort = serialPort;
}
@Override
public void serialEvent(SerialPortEvent event) {
B9JiYunClient b9JiYunClient =
SpringUtils.getBean(B9JiYunClient.class);
if(event.getEventType() != SerialPortEvent.DATA_AVAILABLE)
return;
if(serialPort == null)
return;
byte[] dataByte = SerialComKit.readFromPort(serialPort);
String data = new String(dataByte);
String[] split = data.split("[^\\d^\\.]+");
List<String> list = Arrays.asList(split);
list = list.stream().distinct().filter(p ->p!=null && p.length() != 0).collect(Collectors.toList());
if(list == null || list.isEmpty())
return;
data = list.get(0);
if(StringUtils.isEmpty(this.dataFlag) ||
!this.dataFlag.equals(data)) {
this.dataFlag = data;
b9JiYunClient.pushWeight(data);
}
}
}
自定义监听业务
package com.bami.service.v1.instruc;
import java.util.TooManyListenersException;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import com.bami.common.serial_com.SerialComKit;
import com.bami.pojo.annotation.ExecInstruc;
import com.bami.pojo.dict.Config;
import com.bami.pojo.dict.DeviceNews;
import com.bami.pojo.dict.InstrucChannel;
import com.bami.pojo.dict.InstrucInfo;
import gnu.io.NoSuchPortException;
import gnu.io.PortInUseException;
import gnu.io.SerialPort;
import gnu.io.UnsupportedCommOperationException;
@ExecInstruc(instruc = InstrucInfo.OpenComListen)
public class OpenComListenInstrucService implements InstrucChannel {
@Autowired
private Config config;
@Override
public String exceInstruc(String instruc) {
String portName = config.getPortName();
Integer baudrate = config.getBaudrate();
SerialPort serialPort = config.getSerialPort();
if(StringUtils.isEmpty(portName))
return DeviceNews.instance()
.error()
.result("无法开启串口监听,串口名称未设置.")
.toString();
if(baudrate == null)
return DeviceNews.instance()
.error()
.result("无法开启串口监听,串口波特率未设置.")
.toString();
try {
SerialComKit.closePort(serialPort);
SerialPort openPort =
SerialComKit.openPort(portName,baudrate);
serialPort = openPort;
config.setSerialPort(openPort);
SerialComKit.addListener(
openPort,
new SerialPortListener(openPort));
} catch (NoSuchPortException e) {
return DeviceNews.instance()
.error()
.result("开启串口监听失败,没有找到与该端口名匹配的串口设备")
.toString();
} catch (PortInUseException e) {
return DeviceNews.instance()
.error()
.result("开启串口监听失败,端口已被占用")
.toString();
} catch (UnsupportedCommOperationException e) {
return DeviceNews.instance()
.error()
.result("开启串口监听失败,请检查串口参数是否正确")
.toString();
} catch (TooManyListenersException e) {
return DeviceNews.instance()
.error()
.result("串口监听数量过多,开启串口监听失败")
.toString();
}
return DeviceNews.instance()
.success()
.result("开启串口监听成功")
.toString();
}
}