java与modbusRtu(COM口)通讯

2024-09-04 06:18
文章标签 java com 通讯 modbusrtu

本文主要是介绍java与modbusRtu(COM口)通讯,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

  • modbous协议通讯byte数据解析含义
  1. 依赖的modbus包请看java与modbusTcp通讯
  2. JDK中配置串口通讯能力 提取码:hmfn
  3. 串口模拟工具 提取码: npqx
  4. 依赖串口协议包:
<dependency><groupId>org.rxtx</groupId><artifactId>rxtx</artifactId><version>2.1.7</version>
</dependency>
  • 实现代码 1 抽象类
import com.serotonin.modbus4j.serial.SerialPortWrapper;
import gnu.io.SerialPort;import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;public abstract class AbstractSerialPortWrapper implements SerialPortWrapper {private SerialPort serialPort = null;private Integer baudRate;private String port;protected AbstractSerialPortWrapper(String port,Integer baudRate){this.port = port;this.baudRate = baudRate;}@Overridepublic void close() throws Exception {if(serialPort != null){serialPort.close();}}@Overridepublic void open() throws Exception {serialPort = serialPort(port);}@Overridepublic InputStream getInputStream() {try {if(serialPort != null){return serialPort.getInputStream();}} catch (IOException e) {throw new RuntimeException("对象空指针异常");}throw new RuntimeException("对象空指针异常");}@Overridepublic OutputStream getOutputStream() {try {if(serialPort != null){return serialPort.getOutputStream();}} catch (IOException e) {throw new RuntimeException("对象空指针异常");}throw new RuntimeException("对象空指针异常");}@Overridepublic int getBaudRate() {return baudRate;}@Overridepublic int getFlowControlIn() {return SerialPort.FLOWCONTROL_NONE;}@Overridepublic int getFlowControlOut() {return SerialPort.FLOWCONTROL_NONE;}@Overridepublic int getDataBits() {return SerialPort.DATABITS_8;}@Overridepublic int getStopBits() {return SerialPort.STOPBITS_1;}@Overridepublic int getParity() {return SerialPort.PARITY_EVEN;}public abstract SerialPort serialPort(String portName);
}
  • 实现代码 2 支持类
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;public class SerialPortSupport extends AbstractSerialPortWrapper {public SerialPortSupport(String port,Integer baudRate){super(port,baudRate);}/*** 查找所有可用端口** @return 可用端口名称列表*/@SuppressWarnings("all")public static List<String> findPorts() {// 获得当前所有可用串口Enumeration<CommPortIdentifier> portList = CommPortIdentifier.getPortIdentifiers();List<String> portNameList = new ArrayList<String>();// 将可用串口名添加到List并返回该Listwhile (portList.hasMoreElements()) {String portName = portList.nextElement().getName();portNameList.add(portName);}return portNameList;}@Overridepublic SerialPort serialPort(String portName) {try {// 通过端口名识别端口CommPortIdentifier portIdentifier = CommPortIdentifier.getPortIdentifier(portName);// 打开端口,并给端口名字和一个timeout(打开操作的超时时间)CommPort commPort = portIdentifier.open(portName, 2000);// 判断是不是串口if (commPort instanceof SerialPort) {SerialPort serialPort = (SerialPort) commPort;try {// 设置一下串口的波特率等参数 // 数据位:8 // 停止位:1 // 校验位:NoneserialPort.setSerialPortParams(getBaudRate(), getDataBits(), getStopBits(), getParity());} catch (UnsupportedCommOperationException e) {throw new RuntimeException("打开串口异常");}return serialPort;}} catch (Exception e1) {throw new RuntimeException("打开串口异常");}return null;}
}
  • 实现代码 3 通讯类
import com.serotonin.modbus4j.ModbusFactory;
import com.serotonin.modbus4j.ModbusMaster;
import com.serotonin.modbus4j.exception.ModbusInitException;
import com.serotonin.modbus4j.exception.ModbusTransportException;
import com.serotonin.modbus4j.msg.*;
import com.serotonin.modbus4j.serial.SerialPortWrapper;
import com.sotring.asd.modbus.suport.SerialPortSupport;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;import java.util.Arrays;public class RtuMasterWrapper {private static final Logger log = LoggerFactory.getLogger(RtuMasterWrapper.class);private int slaveId;private ModbusMaster rutMaster;private boolean connected;public RtuMasterWrapper(int slaveId) {this.slaveId = slaveId;log.info("slaveId: {}",  slaveId);}public boolean connect() {disconnect();try {SerialPortWrapper port = new SerialPortSupport("COM1",9600);rutMaster = new ModbusFactory().createRtuMaster(port);rutMaster.setTimeout(3000);rutMaster.init();connected = true;} catch (ModbusInitException ex) {log.error("connect error, try to disconnect...", ex);disconnect();}return isConnected();}private void disconnect() {if (rutMaster != null) {rutMaster.destroy();}connected = false;log.info("disconnect");}private boolean isConnected() {return connected;}/*** 读取单个线圈(01功能码)* @param startOffset 读取地址*/public Boolean readCoils(int startOffset) throws ModbusTransportException {ReadCoilsRequest request = new ReadCoilsRequest(slaveId,startOffset,1);ReadCoilsResponse response = (ReadCoilsResponse) rutMaster.send(request);if (response!= null && response.isException()) {throw new ModbusTransportException(response.getExceptionMessage());} else if(response!= null){return response.getBooleanData()[0];}connected = false;return null;}/*** 写入单个地址* @param startOffset 写入地址* @param value 写入值*/public void writeCoils(int startOffset,boolean value) throws ModbusTransportException {WriteCoilRequest request = new WriteCoilRequest(slaveId,startOffset,value);WriteCoilResponse response = (WriteCoilResponse) rutMaster.send(request);if (response!= null && response.isException()) {throw new ModbusTransportException(response.getExceptionMessage());}}/*** 写多个线圈(01功能码)* @param startOffset 写入开始地址* @param value 写入值集合* @throws ModbusTransportException*/public void writeCoilsMultiple(int startOffset,boolean[] value) throws ModbusTransportException {WriteCoilsRequest request = new WriteCoilsRequest(slaveId,startOffset,value);WriteCoilsResponse response = (WriteCoilsResponse) rutMaster.send(request);if (response!= null && response.isException()) {throw new ModbusTransportException(response.getExceptionMessage());}}/*** 读取单个离散线圈(02功能码)* @param startOffset 读取地址*/public Boolean readDiscrete(int startOffset) throws ModbusTransportException {ReadDiscreteInputsRequest request = new ReadDiscreteInputsRequest(slaveId,startOffset,1);ReadDiscreteInputsResponse response = (ReadDiscreteInputsResponse) rutMaster.send(request);if (response!= null && response.isException()) {throw new ModbusTransportException(response.getExceptionMessage());} else if(response!= null){return response.getBooleanData()[0];}connected = false;return null;}/*** 读取单个保持寄存器(03功能码)* @param startOffset 读取地址*/public Short readHoldingRegisterValue(int startOffset) throws ModbusTransportException {ReadHoldingRegistersRequest request = new ReadHoldingRegistersRequest(slaveId, startOffset, 1);log.info("Reading Holding Register, startAddress: {}", startOffset);ReadHoldingRegistersResponse response = (ReadHoldingRegistersResponse)rutMaster.send(request);if (response != null && response.isException()) {log.error("Modbus execution failed: \nslaveId: {}, startAddress: {}", slaveId, startOffset);return null;} else if (response != null && response.getShortData().length > 0) {return response.getShortData()[0];}connected = false;return null;}/*** 读取多个保持寄存器(03功能码)* @param startOffset 开始读取位置* @param numberOfRegisters 读取个数*/public short[] readHoldingRegisterValues(int startOffset, int numberOfRegisters) throws ModbusTransportException {ReadHoldingRegistersRequest request = new ReadHoldingRegistersRequest(slaveId, startOffset, numberOfRegisters);log.info("Reading Holding Registers, startAddress: {}, len: {}", startOffset, numberOfRegisters);ReadHoldingRegistersResponse response = (ReadHoldingRegistersResponse)rutMaster.send(request);if (response != null && response.isException()) {log.error("Modbus execution failed: \nslaveId: {}, startAddress: {}, len: {}", slaveId, startOffset, numberOfRegisters);return null;} else if (response != null) {return response.getShortData();}connected = false;return null;}/*** 写入保持寄存器多个值(03功能码)* @param startOffset 写入开始地址* @param values 写入多个数据集合*/public void writeRegisterValues(int startOffset, short[] values) throws ModbusTransportException {WriteRegistersRequest request = new WriteRegistersRequest(slaveId, startOffset, values);log.info(String.format("WRITE Holding Register, startOffset: %d, values: %s",startOffset, Arrays.toString(values)));WriteRegistersResponse response = (WriteRegistersResponse) rutMaster.send(request);if (response!= null && response.isException()) {throw new ModbusTransportException(response.getExceptionMessage());}}/*** 写入保持寄存器(03功能码)* @param startOffset 写入地址* @param value 写入值*/public void writeRegisterValue(int startOffset, short value) throws ModbusTransportException {WriteRegistersRequest request = new WriteRegistersRequest(slaveId, startOffset, new short[]{value});log.info(String.format("Writing Holding Register, startAddress: %d, value: %d", startOffset, value));WriteRegistersResponse response = (WriteRegistersResponse) rutMaster.send(request);if (response!= null && response.isException()) {throw new ModbusTransportException(response.getExceptionMessage());}}/*** 读取输入寄存器(04功能码)* @param startOffset 读取地址*/public Short readInput(int startOffset) throws ModbusTransportException {ReadInputRegistersRequest request = new ReadInputRegistersRequest(slaveId,startOffset,1);ReadInputRegistersResponse response = (ReadInputRegistersResponse) rutMaster.send(request);if (response!= null && response.isException()) {throw new ModbusTransportException(response.getExceptionMessage());} else if(response!= null){return response.getShortData()[0];}connected = false;return null;}
}

这篇关于java与modbusRtu(COM口)通讯的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/1135226

相关文章

java脚本使用不同版本jdk的说明介绍

《java脚本使用不同版本jdk的说明介绍》本文介绍了在Java中执行JavaScript脚本的几种方式,包括使用ScriptEngine、Nashorn和GraalVM,ScriptEngine适用... 目录Java脚本使用不同版本jdk的说明1.使用ScriptEngine执行javascript2.

Spring MVC如何设置响应

《SpringMVC如何设置响应》本文介绍了如何在Spring框架中设置响应,并通过不同的注解返回静态页面、HTML片段和JSON数据,此外,还讲解了如何设置响应的状态码和Header... 目录1. 返回静态页面1.1 Spring 默认扫描路径1.2 @RestController2. 返回 html2

Spring常见错误之Web嵌套对象校验失效解决办法

《Spring常见错误之Web嵌套对象校验失效解决办法》:本文主要介绍Spring常见错误之Web嵌套对象校验失效解决的相关资料,通过在Phone对象上添加@Valid注解,问题得以解决,需要的朋... 目录问题复现案例解析问题修正总结  问题复现当开发一个学籍管理系统时,我们会提供了一个 API 接口去

Java操作ElasticSearch的实例详解

《Java操作ElasticSearch的实例详解》Elasticsearch是一个分布式的搜索和分析引擎,广泛用于全文搜索、日志分析等场景,本文将介绍如何在Java应用中使用Elastics... 目录简介环境准备1. 安装 Elasticsearch2. 添加依赖连接 Elasticsearch1. 创

Spring核心思想之浅谈IoC容器与依赖倒置(DI)

《Spring核心思想之浅谈IoC容器与依赖倒置(DI)》文章介绍了Spring的IoC和DI机制,以及MyBatis的动态代理,通过注解和反射,Spring能够自动管理对象的创建和依赖注入,而MyB... 目录一、控制反转 IoC二、依赖倒置 DI1. 详细概念2. Spring 中 DI 的实现原理三、

SpringBoot 整合 Grizzly的过程

《SpringBoot整合Grizzly的过程》Grizzly是一个高性能的、异步的、非阻塞的HTTP服务器框架,它可以与SpringBoot一起提供比传统的Tomcat或Jet... 目录为什么选择 Grizzly?Spring Boot + Grizzly 整合的优势添加依赖自定义 Grizzly 作为

Java后端接口中提取请求头中的Cookie和Token的方法

《Java后端接口中提取请求头中的Cookie和Token的方法》在现代Web开发中,HTTP请求头(Header)是客户端与服务器之间传递信息的重要方式之一,本文将详细介绍如何在Java后端(以Sp... 目录引言1. 背景1.1 什么是 HTTP 请求头?1.2 为什么需要提取请求头?2. 使用 Spr

Java如何通过反射机制获取数据类对象的属性及方法

《Java如何通过反射机制获取数据类对象的属性及方法》文章介绍了如何使用Java反射机制获取类对象的所有属性及其对应的get、set方法,以及如何通过反射机制实现类对象的实例化,感兴趣的朋友跟随小编一... 目录一、通过反射机制获取类对象的所有属性以及相应的get、set方法1.遍历类对象的所有属性2.获取

Java中的Opencv简介与开发环境部署方法

《Java中的Opencv简介与开发环境部署方法》OpenCV是一个开源的计算机视觉和图像处理库,提供了丰富的图像处理算法和工具,它支持多种图像处理和计算机视觉算法,可以用于物体识别与跟踪、图像分割与... 目录1.Opencv简介Opencv的应用2.Java使用OpenCV进行图像操作opencv安装j

java Stream操作转换方法

《javaStream操作转换方法》文章总结了Java8中流(Stream)API的多种常用方法,包括创建流、过滤、遍历、分组、排序、去重、查找、匹配、转换、归约、打印日志、最大最小值、统计、连接、... 目录流创建1、list 转 map2、filter()过滤3、foreach遍历4、groupingB