Integrating Modbus with Spring Boot for device communication

freeFree Technical Resource

This content is free to read, suitable for basic learning and search traffic.

Integrating Modbus with Spring Boot for device communication缩略图

Abstract:
Efficient communication between devices is a fundamental and critical element in automation and industrial control systems. This article aims to introduce how to integrate Modbus through Spring Boot and achieve efficient device communication. Modbus is a serial communication protocol widely used in the field of industrial automation, particularly suitable for monitoring and control systems. We will explore the core concepts of Modbus, its implementation methods in Spring Boot, and how to integrate reading and writing device data through this.

Overview of Modbus Protocol:
Modbus is a communication protocol developed by Modicon company, mainly used for communication between programmable logic controllers (PLCs). It is known for its simplicity, real-time performance, and interoperability as an open standard. Modbus supports multiple forms, including Modbus RTU, Modbus ASCII, and Ethernet based Modbus TCP/IP, which can meet different communication needs.

Integrating Spring Boot and Modbus:
Integrating Modbus in Spring Boot applications mainly involves the following steps:

  1. Dependency configuration:Add dependencies for Java Modbus Library in the pom.xml file of the project to enable Modbus communication.
<dependency>
    <groupId>com.intelligt.modbus</groupId>
    <artifactId>modbus-core</artifactId>
    <version>1.2.0</version>
</dependency>
  1. Modbus Configuration:Create a configuration class to configure the connection information of the Modbus Master, such as serial port path, baud rate, etc.
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;

@Configuration
public class ModbusConfig {

    @Value("${modbus.serialPort}")
    private String serialPort;

    @Value("${modbus.baudRate}")
    private int baudRate;

    @Value("${modbus.dataBits}")
    private int dataBits;

    @Value("${modbus.stopBits}")
    private int stopBits;

    @Value("${modbus.parity}")
    private int parity;

    // ...其他配置参数

    @Bean
    public ModbusMaster modbusMaster() {
        ModbusFactory modbusFactory = new ModbusFactory();
        Transport transport = new SerialTransport(serialPort, baudRate, dataBits, stopBits, parity);
        ModbusMaster master = modbusFactory.createRtuMaster(transport);
        master.init();
        return master;
    }
}
  1. Data Reading and Writing:Implement the Service class to encapsulate methods for reading and writing Modbus device data. By calling these methods, it is possible to read and control Modbus slaves.
@Service
public class ModbusService {

    @Autowired
    private ModbusMaster modbusMaster;

    public int readHoldingRegister(int slaveId, int offset) {
        try {
            //创建一个保持寄存器的数据定位器(Locator)对象
            BaseLocator<Integer> locator = BaseLocator.holdingRegister(slaveId, offset, DataType.TWO_BYTE_INT_SIGNED);
            return modbusMaster.getValue(locator);
        } catch (ModbusTransportException | ErrorResponseException e) {
            e.printStackTrace();
            return -1;
        }
    }
}

Example Application:
We will demonstrate a simple application example that shows how to read the hold register data of a Modbus device through Spring Boot. This involves creating a data locator and executing Modbus read commands.

Parameter Description:

  1. slaveId: This is the slave address in Modbus communication. Each Modbus slave device has a unique address, typically between 1 and 247. TheslaveIdparameter is used to specify the address of the target slave device to communicate with. Usually, a Modbus master sends requests to specific slave devices, and the slave devices determine whether they need to respond to the request based on their address. Therefore, theslaveIdparameter specifies the target of communication.
  2. offset: This parameter is used to specify the starting address of the hold register to be read. The register in Modbus protocol is usually a 16 bit data unit that can store integers, floating-point numbers, or other data types. TheoffsetThe parameter indicates which register to start reading data from. By specifyingoffsetYou can determine the location of the register to be read.

For example, if you callreadHoldingRegister(1, 100)This means to read the hold register of the device with a slave address of 1, starting from register address 100. These two parameters together determine the location of the register to be read and the target device. Usually, you will transmit different information based on specific slave device configurations and communication requirementsslaveIdAndoffsetValue, to achieve read operations on different devices and registers. These two parameters are key parameters in Modbus communication, used to specify the target of communication and the location of data.

Write Modbus data

If data needs to be written to Modbus devices, a method can be created to perform the write operation. Here is an example:

public void writeHoldingRegister(int slaveId, int offset, int value) {
    //slaveId:这是 Modbus 通信中的从站地址
    //offset:用于指定要写入的保持寄存器的起始地址
    //value:这是要写入到指定寄存器的数值
    try {
        BaseLocator<Integer> locator = BaseLocator.holdingRegister(slaveId, offset, DataType.TWO_BYTE_INT_SIGNED);
        modbusMaster.setValue(locator, value);
    } catch (ModbusTransportException | ErrorResponseException e) {
        e.printStackTrace();
    }
}

This method allows you to write the value of the Modbus hold register.

configuration file

According to project requirements, you canapplication.propertiesapplication.ymlConfigure Modbus connection information, such as serial device path, baud rate, etc. Here is an example YAML configuration:

modbus:
  #串口设备路径
  serialPort: /dev/ttyUSB0
  #波特率
  baudRate: 9600
  #数据位数
  dataBits: 8
  #停止位数
  stopBits: 1
  #校验位,例如0(0表示无校验,1表示奇校验,2表示偶校验)
  parity: 0

Conclusion:
Integrating Spring Boot with Modbus provides developers with a powerful and flexible platform for building and managing industrial communication systems. Through the methods and examples provided in this article, you can quickly start implementing Modbus based device communication.

Put this resource to use in a real project?

Go to the Tool Center for message parsing, CRC verification and device debugging, or submit your requirements for selection and integration advice.

Engineer Membership

Turn this article into actionable debugging resources

After activation, you can use advanced message parsing, resource pack downloads, code examples, engineering cases and priority technical support, suitable for real project delivery.

Unlimited Advanced Tools
Resource & Code Packs
Complete Engineering Case Library
Priority Technical Support

《 “Integrating Modbus with Spring Boot for device communication” 》 有 2 条Comments

Leave a Reply

Your email address will not be published. Required fields are marked *.