SoFunction
Updated on 2025-03-08

Java docking Modbus protocol code example

1. The meaning of Modbus

Modbus is a single master/slave communication mode that defines a communication specification for enabling data exchange between devices in industrial automation systems. There can only be one master station on the Modbus network. The master station has no address on the Modbus network, and the address range of the slave station is 0-247, where 0 is the broadcast address and the actual address range of the slave station is 1-247.

The Modbus communication protocol can be propagated through a variety of transmission methods, such as RS232C, RS485, optical fiber and radio. It has two serial transmission modes, namely ASCII and RTU, which define how data is packaged and decoded. Generally speaking, devices that support the Modbus protocol will support the RTU format, and both parties to the communication must support one of these two modes at the same time.

In summary, Modbus is a communication protocol for industrial automation systems. It defines communication formats and specifications, and can exchange data through different transmission methods.

2. How to connect to Modbus in Java

1. Read data

public class Modbus4jUtils {
	/**
	  * factory.
	  */
	static ModbusFactory modbusFactory;
	static {
		if (modbusFactory == null) {
			modbusFactory = new ModbusFactory();
		}
	}

	/**
	  * Get the master
	  *
	  * @return
	  * @throws ModbusInitException
	  */
	public static ModbusMaster getMaster() throws ModbusInitException {
		IpParameters params = new IpParameters();
		("Your hardware ip");
		("Port Number");
		//
		// (wapper); //RTU protocol		// (params);//UDP protocol		// (wrapper);//ASCII protocol		ModbusMaster master = (params, false);// TCP protocol		();

		return master;
	}

	/**
	  * Read [01 Coil Status 0x] type switch data
	  *
	  * @param slaveId
	  * slaveId
	  * @param offset
	  *            Location
	  * @return Read value
	  * @throws ModbusTransportException
	  * Exception
	  * @throws ErrorResponseException
	  * Exception
	  * @throws ModbusInitException
	  * Exception
	  */
	public static Boolean readCoilStatus(int slaveId, int offset)
			throws ModbusTransportException, ErrorResponseException, ModbusInitException {
		// 01 Coil Status
		BaseLocator<Boolean> loc = (slaveId, offset);
		Boolean value = getMaster().getValue(loc);
		return value;
	}

	/**
	  * Read [02 Input Status 1x] type switch data
	  *
	  * @param slaveId
	  * @param offset
	  * @return
	  * @throws ModbusTransportException
	  * @throws ErrorResponseException
	  * @throws ModbusInitException
	  */
	public static Boolean readInputStatus(int slaveId, int offset)
			throws ModbusTransportException, ErrorResponseException, ModbusInitException {
		// 02 Input Status
		BaseLocator<Boolean> loc = (slaveId, offset);
		Boolean value = getMaster().getValue(loc);
		return value;
	}

	/**
	  * Read [03 Holding Register type 2x] simulated data
	  *
	  * @param slaveId
	  * slave Id
	  * @param offset
	  *            Location
	  * @param dataType
	  * Data type, from.
	  * @return
	  * @throws ModbusTransportException
	  * Exception
	  * @throws ErrorResponseException
	  * Exception
	  * @throws ModbusInitException
	  * Exception
	  */
	public static Number readHoldingRegister(int slaveId, int offset, int dataType)
			throws ModbusTransportException, ErrorResponseException, ModbusInitException {
		// 03 Holding Register type data reading		BaseLocator<Number> loc = (slaveId, offset, dataType);
		Number value = getMaster().getValue(loc);
		return value;
	}

	/**
	  * Read [04 Input Registers 3x] type simulated data
	  *
	  * @param slaveId
	  * slaveId
	  * @param offset
	  *            Location
	  * @param dataType
	  * Data type, from.
	  * @return Return result
	  * @throws ModbusTransportException
	  * Exception
	  * @throws ErrorResponseException
	  * Exception
	  * @throws ModbusInitException
	  * Exception
	  */
	public static Number readInputRegisters(int slaveId, int offset, int dataType)
			throws ModbusTransportException, ErrorResponseException, ModbusInitException {
		// 04 Input Registers type data reading		BaseLocator<Number> loc = (slaveId, offset, dataType);
		Number value = getMaster().getValue(loc);
		return value;
	}
}

2. Write data

public class Modbus4jWriteUtils {
	static Log log = ();
	/**
	  * factory.
	  */
	static ModbusFactory modbusFactory;
	static {
		if (modbusFactory == null) {
			modbusFactory = new ModbusFactory();
		}
	}

	/**
	  * Get tcpMaster
	  *
	  * @return
	  * @throws ModbusInitException
	  */
	public static ModbusMaster getMaster() throws ModbusInitException {
		IpParameters params = new IpParameters();
		("Your hardware address");
		("Port Number");

		ModbusMaster tcpMaster = (params, false);
		();

		return tcpMaster;
	}

	/**
	  * Write [01 Coil Status(0x)] Write a function ID = 5
	  *
	  * @param slaveId
	  * slave's ID
	  * @param writeOffset
	  *            Location
	  * @param writeValue
	  * Value
	  * @return Whether the write is successful
	  * @throws ModbusTransportException
	  * @throws ModbusInitException
	  */
	public static boolean writeCoil(int slaveId, int writeOffset, boolean writeValue)
			throws ModbusTransportException, ModbusInitException {
		// Get the master		ModbusMaster tcpMaster = getMaster();
		// Create a request		WriteCoilRequest request = new WriteCoilRequest(slaveId, writeOffset, writeValue);
		// Send a request and get the response object		WriteCoilResponse response = (WriteCoilResponse) (request);
		if (()) {
			return false;
		} else {
			return true;
		}
	}

	/**
	  * Write [01 Coil Status(0x)] Write multiple function IDs = 15
	  *
	  * @param slaveId
	  * slaveId
	  * @param startOffset
	  * Start location
	  * @param bdata
	  * Write data
	  * @return Whether the write is successful
	  * @throws ModbusTransportException
	  * @throws ModbusInitException
	  */
	public static boolean writeCoils(int slaveId, int startOffset, boolean[] bdata)
			throws ModbusTransportException, ModbusInitException {
		// Get the master		ModbusMaster tcpMaster = getMaster();
		// Create a request		WriteCoilsRequest request = new WriteCoilsRequest(slaveId, startOffset, bdata);
		// Send a request and get the response object		WriteCoilsResponse response = (WriteCoilsResponse) (request);
		if (()) {
			return false;
		} else {
			return true;
		}

	}

	/***
	  * Write [03 Holding Register(4x)] Write a function ID = 6
	  *
	  * @param slaveId
	  * @param writeOffset
	  * @param writeValue
	  * @return
	  * @throws ModbusTransportException
	  * @throws ModbusInitException
	  */
	public static boolean writeRegister(int slaveId, int writeOffset, short writeValue)
			throws ModbusTransportException, ModbusInitException {
		// Get the master		ModbusMaster tcpMaster = getMaster();
		// Create a request object		WriteRegisterRequest request = new WriteRegisterRequest(slaveId, writeOffset, writeValue);
		WriteRegisterResponse response = (WriteRegisterResponse) (request);
		if (()) {
			(());
			return false;
		} else {
			return true;
		}

	}

	/**
	  *
	  * Write to [03 Holding Register(4x)] and write multiple function IDs=16
	  *
	  * @param slaveId
	  * modbus' slaveID
	  * @param startOffset
	  * Start position offset value
	  * @param sdata
	  * Write data
	  * @return Return whether the write is successful
	  * @throws ModbusTransportException
	  * @throws ModbusInitException
	  */
	public static boolean writeRegisters(int slaveId, int startOffset, short[] sdata)
			throws ModbusTransportException, ModbusInitException {
		// Get the master		ModbusMaster tcpMaster = getMaster();
		// Create a request object		WriteRegistersRequest request = new WriteRegistersRequest(slaveId, startOffset, sdata);
		// Send a request and get the response object		ModbusResponse response = (request);
		if (()) {
			(());
			return false;
		} else {
			return true;
		}
	}

	/**
	  * Write analog quantities to the number type (such as: write analog quantities to the Float type, double type analog quantities, integer types Short, Integer, Long)
	  *
	  * @param slaveId
	  * @param offset
	  * @param value
	  * Write value, number subclass, such as write Float floating point type, Double double precision type, and integer short, int, long
	  * @param registerCount
	  * ,.
	  * @throws ModbusTransportException
	  * @throws ErrorResponseException
	  * @throws ModbusInitException
	  */
	public static void writeHoldingRegister(int slaveId, int offset, Number value, int dataType)
			throws ModbusTransportException, ErrorResponseException, ModbusInitException {
		// Get the master		ModbusMaster tcpMaster = getMaster();
		// type		BaseLocator<Number> locator = (slaveId, offset, dataType);
		(locator, value);
	}
 
}

Summarize

This is all about this article about java docking Modbus protocol. For more related java docking Modbus content, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!