maven依赖:
<dependency> <groupId>io.github.java-native</groupId> <artifactId>jssc</artifactId> <version>2.9.4</version> </dependency>
代码示例:
package com.hs.modbusstu.utils;
import jssc.SerialPort;
import jssc.SerialPortException;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
/**
* jssc工具类
*/
public class JsscUtilSingleton {
public static final String HEX_PLACE_HOLDER = "0";
/**
* 十六进制进位阈值
*/
public static final int HEX_CARRY_THRESHOLD = 15;
private static class JsscUtil {
public static final JsscUtilSingleton JSSC_UTIL_SINGLETON = new JsscUtilSingleton();
}
public static JsscUtilSingleton getInstance() {
return JsscUtil.JSSC_UTIL_SINGLETON;
}
/**
* 发送数据
* 统一发送指令的方法
*
* @param serialPort
* @param bytes 命令字节数组
*/
public static List<String> sendData(SerialPort serialPort, byte[] bytes) {
if (serialPort != null && serialPort.isOpened()) {
try {
serialPort.writeBytes(bytes);
// 延时时间,50ms多次测试最稳当
Thread.sleep(50);
// 读取命令返回数据
String[] resCode = serialPort.readHexStringArray();
if (resCode == null || resCode.length == 0) {
return Collections.emptyList();
} else {
System.out.println("命令发送后的返回值: " + Arrays.toString(resCode));
return Arrays.asList(resCode);
}
} catch (SerialPortEx