赞
踩
在我最近的项目中,我需要与PLC(可编程逻辑控制器)进行交互,使用的是Modbus TCP协议。这种协议广泛用于工业自动化领域,因为它的结构简单且稳定。在开发过程中,我之前用过的是一个静态工具类来处理与PLC的通信。然而,我发现这种静态工具类在使用过程中不够灵活,尤其是在处理需要长时间维持的TCP连接时。
为了改善这个问题,我决定将工具类重新封装成一个Spring Bean。这样做的好处是可以更好地集成到我的Spring应用中,利用Spring的生命周期管理和依赖注入等特性来增强模块的管理和可维护性。
在TCP通信中,粘包和拆包是常见的问题,这可能会导致数据传输中的错误解析。幸运的是,Modbus TCP协议的报文结构帮助我较容易地解决了这些问题。每个Modbus报文都有一个固定长度的头部,包含了重要的控制信息,如事务标识符、协议标识符和长度字段,这些都是处理粘包和拆包问题时的关键。
总的来说,通过将通信工具类封装为Spring Bean,并解决了TCP通信中的粘包和拆包问题,能够更高效地实现与PLC的稳定通信。
Modbus4J的jar包阿里云镜像仓库中没有我们采用最原生的导包方式:
pom.xml 文件
- <?xml version="1.0" encoding="UTF-8"?>
- <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
- xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
- <modelVersion>4.0.0</modelVersion>
- <groupId>com.ljh</groupId>
- <artifactId>modbus</artifactId>
- <version>0.0.1-SNAPSHOT</version>
- <name>modbus</name>
- <description>modbus</description>
- <properties>
- <java.version>1.8</java.version>
- <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
- <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
- <spring-boot.version>2.3.12.RELEASE</spring-boot.version>
- </properties>
-
- <parent>
- <groupId>org.springframework.boot</groupId>
- <artifactId>spring-boot-starter-parent</artifactId>
- <version>2.3.12.RELEASE</version>
- <relativePath/>
- </parent>
-
- <dependencies>
-
- <dependency>
- <groupId>org.springframework.boot</groupId>
- <artifactId>spring-boot-starter-web</artifactId>
- </dependency>
- <dependency>
- <groupId>org.projectlombok</groupId>
- <artifactId>lombok</artifactId>
- </dependency>
- <dependency>
- <groupId>com.infiniteautomation</groupId>
- <artifactId>modbus4j</artifactId>
- <version>3.0.3</version>
- <scope>system</scope>
- <systemPath>${project.basedir}/lib/modbus4j-3.0.3.jar</systemPath>
- </dependency>
-
- <dependency>
- <groupId>org.apache.commons</groupId>
- <artifactId>commons-lang3</artifactId>
- <version>3.12.0</version>
- </dependency>
-
- </dependencies>
-
-
- <build>
- <finalName>${project.artifactId}</finalName>
- <plugins>
- <plugin>
- <groupId>org.springframework.boot</groupId>
- <artifactId>spring-boot-maven-plugin</artifactId>
- <configuration>
- <excludes>
- <exclude>
- <groupId>org.project lombok</groupId>
- <artifactId>lombok</artifactId>
- </exclude>
- </excludes>
- </configuration>
- </plugin>
- </plugins>
- </build>
-
- </project>
ModbusService
- package com.ljh.modbus.service;
-
-
- import com.serotonin.modbus4j.BatchRead;
- import com.serotonin.modbus4j.BatchResults;
- import com.serotonin.modbus4j.ModbusFactory;
- import com.serotonin.modbus4j.ModbusMaster;
- import com.serotonin.modbus4j.code.DataType;
- import com.serotonin.modbus4j.exception.ErrorResponseException;
- import com.serotonin.modbus4j.exception.ModbusInitException;
- import com.serotonin.modbus4j.exception.ModbusTransportException;
- import com.serotonin.modbus4j.ip.IpParameters;
- import com.serotonin.modbus4j.locator.BaseLocator;
- import lombok.extern.slf4j.Slf4j;
- import org.springframework.beans.factory.annotation.Value;
- import org.springframework.stereotype.Service;
-
- import javax.annotation.PostConstruct;
- import javax.annotation.PreDestroy;
- import java.util.ArrayList;
- import java.util.concurrent.Executors;
- import java.util.concurrent.ScheduledExecutorService;
- import java.util.concurrent.TimeUnit;
-
- /**
- * @Author: ljh
- * @Date: 2024/04/12 11:04:00
- * @Description: Modbus客户端
- **/
- @Service
- @Slf4j
- public class ModbusService {
-
- private ModbusMaster master;
- private ScheduledExecutorService scheduledExecutorService = Executors.newSingleThreadScheduledExecutor();
- private Integer count = 0;
- private Integer time = 10;
-
- /**
- * Modbus服务器地址
- */
- @Value("${modbus.host}")
- private String host;
-
- /**
- * Modbus服务器端口号
- */
- @Value("${modbus.port}")
- private int port;
-
- /**
- * 初始化连接
- */
- @PostConstruct
- public void init() {
- setupMaster();
- scheduleConnectionCheck();
- }
-
- /**
- * 获得执行的ModbusMaster对象并赋值给成员变量master
- */
- private void setupMaster() {
- ModbusFactory factory = new ModbusFactory();
- IpParameters parameters = new IpParameters();
- parameters.setHost(host);
- parameters.setPort(port);
- master = factory.createTcpMaster(parameters, true);
- master.setTimeout(5000);
- master.setRetries(0);
- try {
- master.init();
- time = 10;
- count = 0;
- log.info("与Modbus服务器的连接初始化成功");
- } catch (ModbusInitException e) {
- log.error("初始化连接失败", e.getMessage());
- }
- }
-
- /**
- * 心跳包
- */
- private void scheduleConnectionCheck() {
- // 这里使用了一个定时任务来每分钟检查一次Modbus连接是否正常,如果出现异常则尝试重新初始化连接
- scheduledExecutorService.scheduleWithFixedDelay(() -> {
- try {
- // 这里使用了一个假定的从站ID为1,寄存器地址为0的读取操作作为连接检查
- master.getValue(BaseLocator.holdingRegister(1, 0, DataType.TWO_BYTE_INT_UNSIGNED));
- } catch (Exception e) {
- if (count >= 20) {
- log.error("超过连接次数,退出");
- return;
- }
- count++;
- time = time + 20;
- log.error("连接检查失败,尝试重新连接");
- setupMaster();
- }
- }, 0, time, TimeUnit.SECONDS);
- }
-
- /**
- * 程序关闭关闭连接
- */
- @PreDestroy
- public void close() {
- if (master != null) {
- master.destroy();
- }
- scheduledExecutorService.shutdown();
- log.info("Modbus 连接关闭");
- }
-
- /**
- * 单个寄存器读取
- *
- * @param slaveId 站点
- * @param offset 位置
- * @param dataType 数据类型
- * @return
- */
- public Number readSingleRegister(int slaveId, int offset, int dataType) {
- BaseLocator<Number> locator = BaseLocator.holdingRegister(slaveId, offset, dataType);
- try {
- return master.getValue(locator);
- } catch (ModbusTransportException | ErrorResponseException e) {
- e.printStackTrace();
- return null;
- }
- }
-
- /**
- * 单个寄存器写入
- *
- * @param slaveId 站点
- * @param offset 位置
- * @param value 值
- */
- public boolean writeSingleRegister(int slaveId, int offset, int value, int dataType) {
- try {
- master.setValue(BaseLocator.holdingRegister(slaveId, offset, dataType), value);
- return true;
- } catch (ModbusTransportException | ErrorResponseException e) {
- e.printStackTrace();
- return false;
- }
- }
-
- /**
- * 批量读取多个寄存器
- *
- * @param slaveId 站点
- * @param startOffset 开始位置
- * @param count 读取数量
- * @return
- */
- public ArrayList<Integer> readMultipleRegisters(int slaveId, int startOffset, int count, int dataType) {
- BatchRead<Integer> batch = new BatchRead<>();
- if (dataType == DataType.TWO_BYTE_INT_UNSIGNED) {
- // 如果数据类型是2字节的,每个整数占用一个寄存器
- for (int i = 0; i < count; i++) {
- batch.addLocator(i, BaseLocator.holdingRegister(slaveId, startOffset + i, dataType));
- }
- } else if (dataType == DataType.FOUR_BYTE_INT_UNSIGNED) {
- // 如果数据类型是4字节的,每个整数占用两个寄存器
- for (int i = 0; i < count; i++) {
- batch.addLocator(2 * i, BaseLocator.holdingRegister(slaveId, startOffset + 2 * i, DataType.TWO_BYTE_INT_UNSIGNED));
- batch.addLocator(2 * i + 1, BaseLocator.holdingRegister(slaveId, startOffset + 2 * i + 1, DataType.TWO_BYTE_INT_UNSIGNED));
- }
- }
- try {
- BatchResults<Integer> results = master.send(batch);
- ArrayList<Integer> integers = new ArrayList<>();
- if (dataType == DataType.TWO_BYTE_INT_UNSIGNED) {
- for (int i = 0; i < count; i++) {
- int value = (int) results.getValue(i);
- integers.add(value);
- }
- } else if (dataType == DataType.FOUR_BYTE_INT_UNSIGNED) {
- for (int i = 0; i < count; i++) {
- int high = (int) results.getValue(2 * i + 1);
- int low = (int) results.getValue(2 * i);
- integers.add((high << 16) | (low & 0xFFFF));
- }
- }
- return integers;
- } catch (ModbusTransportException | ErrorResponseException e) {
- e.printStackTrace();
- return null;
- }
- }
-
- }
Controller 层
- package com.ljh.modbus.controller;
-
- import com.ljh.modbus.service.ModbusService;
- import com.serotonin.modbus4j.code.DataType;
- import org.springframework.beans.factory.annotation.Autowired;
- import org.springframework.web.bind.annotation.PostMapping;
- import org.springframework.web.bind.annotation.RequestMapping;
- import org.springframework.web.bind.annotation.RestController;
-
- import java.util.List;
-
- /**
- * @Author: ljh
- * @Date: 2024/4/12 12:11
- * @Description:
- **/
- @RestController
- @RequestMapping("/modbus")
- public class ModbusTest {
-
- private final ModbusService modbusService;
-
- public ModbusTest(ModbusService modbusService) {
- this.modbusService = modbusService;
- }
-
- @PostMapping("/single-read")
- public Integer singleRead() {
- Number number = modbusService.readSingleRegister(1, 0, DataType.TWO_BYTE_INT_UNSIGNED);
- System.out.println(number);
- return number.intValue();
- }
-
- @PostMapping("/single-write")
- public boolean singleWrite() {
- return modbusService.writeSingleRegister(1, 0, 100, DataType.TWO_BYTE_INT_UNSIGNED);
- }
-
-
- @PostMapping("/multiple-read")
- public List<Integer> multipleRead() {
- return modbusService.readMultipleRegisters(1, 0, 3, DataType.TWO_BYTE_INT_UNSIGNED);
- }
- }
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。