Introduction: Generally speaking, there are many common iot communication protocols, such as Bluetooth, Zigbee, WiFi, ModBus, PROFINET, EtherCAT, cellular, etc. Among many communication protocols of the Internet of Things, Modbus is a very popular one. It is a serial communication protocol, Modicon company in 1979 for the use of programmable logic controller (PLC) communication and developed, it can be said that it has become the industry standard of communication protocol in the industrial field.

1 overview

With the rapid development of IT technology, IT has entered the era of intelligence, among which the Internet of Things technology will occupy an increasingly important position in the future. According to the definition of Baidu Baike, Internet of Things (IOT for short) refers to the “Internet connected to all things”, which is the extension and expansion of the Network based on the Internet. The Internet of Things organically combines all kinds of information to realize the interconnection of people, machines and things at any time and any place. Technically, the core of the Internet of Things is communication protocol, that is, how to connect computers, things and people with the Internet according to the agreed communication protocol to carry out information communication, so as to realize intelligent identification, positioning, tracking, monitoring and management of people, machines and things.

Generally speaking, there are many common iot communication protocols, such as Bluetooth, Zigbee, WiFi, ModBus, PROFINET, EtherCAT, cellular, etc. Among many communication protocols of the Internet of Things, Modbus is a very popular one. It is a serial communication protocol, Modicon company in 1979 for the use of programmable logic controller (PLC) communication and developed, it can be said that it has become the industry standard of communication protocol in the industrial field. Its advantages are as follows:

  • Free of royalty
  • Easy to deploy
  • Flexible and less restrictive

2ModBus Protocol Overview

The Modbus protocol uses the request-reply mechanism to exchange information between the Master (Client) and Slave (Server). The client-server principle is a communication protocol model in which a master device controls multiple slave devices. Note that the Master corresponds to the Client, while the Slave corresponds to the Server. The official website of Modbus is www.modbus.org. Currently, the official website recommends replacing the master-slave with the client-server. Protocol types include MODbus-RTU (ASCII), Modbus-TCP, and Modbus-plus. This paper mainly introduces the Modbus-RTU (ASCII) communication protocol principle. Standard Physical layer interfaces of Modbus protocol include RS232, RS422, RS485 and Ethernet interfaces.

The communication diagram is as follows:

Generally speaking, Modbus communication protocol has the following characteristics:

  • Only one host (Master) is connected to the network at a time
  • Only the Master device can initiate communication and send requests to the Slave device
  • The Master device can address each Slave individually using its specific address, or address all Slave devices simultaneously using address 0(broadcast)
  • The Slave device can only send replies to the Master device
  • The Slave device cannot start communication with the Master device or other Slave devices

Modbus protocol can exchange information using two communication modes:

  • Unicast mode
  • Broadcasting mode

Whether it is a request packet or a reply packet, the data structure is as follows:

That is, a packet (frame Data) consists of four parts: address (Slave Number)+ Function Codes (Data)+ Check. The address represents the ID address of the slave device as addressing information. The function code indicates what the current request does, such as read or write. Data represents the service data that needs to be communicated and can be determined based on the actual situation. The final check is to see if the data is incorrect. The function codes are described as follows:

For example, 03 means reading one or more binary values from the current register, while 06 means writing binary values to a single register. In order to simulate the Modbus communication protocol process, simulation software can be used here:

  • Modbus Poll (Master)
  • Modbus Slave

The specific installation process is not described here. Firstly, an Iot sensor device needs to be simulated, which is defined by Modbus Slave. Firstly, open this software and define a device with ID 1:

The function code is 03. In addition, to set connection parameters, an example interface is as follows:

Next, Modbus Poll software is used to simulate the host to obtain data from the device. First define a read/write message.

Then define a connection message:

Note: Use different names for the two COM ports.

After the communication is successfully established, the packet format is as follows:

Tx represents a request message and Rx represents a reply message.

3 the modbus Java implementation

Here is how to implement a Modbus TCP communication in Java. In this case, the Java framework uses Spring Boot and first needs to introduce Modbus4j library. Maven dependency library pom.xml is defined as follows:

< the dependency > < groupId > com. Infiniteautomation < / groupId > < artifactId > modbus4j < / artifactId > < version > 3.0.3 < / version > </dependency> <dependency> <groupId>org. RXTX </groupId> <artifactId> <version>2.1.7</version> </dependency>Copy the code

The modbus4J library may not be available for download in Maven. You can manually download it, place it in your project, and add it to the project library. As shown below:

Note: No rxtxSerial in java.library.path error will be reported when the serial port is used for the first time.

Visit fizzed.com/oss/rxtx-fo… Download the operating system library file, decompress it, and install it.

For a JDK installation:
Copy RXTXcomm.jar ---> <JAVA_HOME>\jre\lib\ext
Copy rxtxSerial.dll ---> <JAVA_HOME>\jre\bin
Copy rxtxParallel.dll ---> <JAVA_HOME>\jre\bin
Copy the code

In addition, it needs to be noted that there is also a need for serial port support, which can be solved with virtual serial software.

The Java core code snippet is shown below.

public static SerialPort open(String portName, Integer baudRate, Integer dataBits, Integer stopBits, Integer parity) { SerialPort result = null; try { CommPortIdentifier identifier = CommPortIdentifier.getPortIdentifier(portName); CommPort CommPort = identifier. Open (portName, 2000); If (commPort instanceof SerialPort) {result = (SerialPort) commPort; / / set the parameters of the serial port result. SetSerialPortParams (baudRate, dataBits, stopBits, parity); Log.info (" open serial port {} succeeded ", portName); }else{log.info("{} is not a serial port ", portName); }} catch (Exception e) {log.error(" open serial port {} error ", portName, e); } return result; }Copy the code

First, you need to start the Modbus RTU Slave program. The core code snippet is as follows:

Public static void createRtuSlave(){// The serial port is COM3, SerialPortWrapperImpl wrapper = new SerialPortWrapperImpl("COM3", 9600, serialport.databits_8, SerialPort.STOPBITS_1, SerialPort.PARITY_NONE, 0, 0); ModbusFactory modbusFactory = new ModbusFactory(); Create the RTU Slave final ModbusSlaveSet Slave = modbusFactory. CreateRtuSlave (wrapper); BasicProcessImage = new BasicProcessImage(1); BasicProcessImage = new BasicProcessImage(1); processImage.setInvalidAddressValue(Short.MIN_VALUE); slave.addProcessImage(processImage); Processimage.addlistener (new MyProcessImageListener()); // Set data setCoil(processImage); setInput(processImage); setHoldingRegister(processImage); setInputRegister(processImage); New Thread(() -> {try {slave.start(); } catch (ModbusInitException e) { e.printStackTrace(); } }).start(); }Copy the code

Modbus RTU Master program, the core code snippet is as follows:

Private static void createRtuMaster() throws Exception{// The serial port is COM4, SerialPortWrapperImpl wrapper = new SerialPortWrapperImpl("COM4", 9600, serialport.databits_8, SerialPort.STOPBITS_1, SerialPort.PARITY_NONE, 0, 0); ModbusFactory modbusFactory = new ModbusFactory(); //RTU Master ModbusMaster master = modbusFactory.createRtuMaster(wrapper); master.init(); // slave device ID is 1 int slaveId = 1; Registers(master, slaveId, 0, 3); WriteRegister (master, slaveId, 0, 0); Registers(master, slaveId, 0, 3); }Copy the code

After startup, the output is as follows:

/ / Slave INFO cn [Thread - 1]. Wu. Demo. Modbus4j. Util. SerialPortUtils - open the serial port COM3 success keep register address = 0, the old value = 8, The new value = 0 / / Master / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / the main INFO Cn. Wu. Demo. Modbus4j. Util. SerialPortUtils - open the serial port COM4 read keep register success = [8, 56, 0] keep register successful in writing Read keep register = [0, 56, 0]Copy the code

Refer to the open source project: github.com/wu-boy/modb…

The original link

This article is the original content of Aliyun and shall not be reproduced without permission.