Modbus is a widely used communication protocol in industrial automation. Modbus TCP is its implementation over TCP/IP networks. Using PHP to work with Modbus TCP allows interaction with devices, enabling reading and writing registers. This article explains the process of parsing Modbus TCP commands and responses with PHP and provides practical code examples.
The basic process of communicating with Modbus TCP in PHP includes:
<?php // Modbus device information $host = '192.168.1.1'; // IP address of the Modbus device $port = 502; // Port of the Modbus device // Modbus commands $readCommand = pack('nnnn', 0x0001, 0x0004, 0x0000, 0x0008); // Read registers 0x0000~0x0008 $writeCommand = pack('nnnC*', 0x0001, 0x0006, 0x0000, 0x01, 0x00, 0x0A); // Write value 0x0A to register 0x0000 // Establish TCP connection $socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP); $result = socket_connect($socket, $host, $port); if (!$result) { die("Failed to connect to the Modbus device!"); } // Send read command socket_write($socket, $readCommand, strlen($readCommand)); // Receive response data $response = socket_read($socket, 1024); $registers = unpack('n*', substr($response, 9)); // Parse register data // Print the read register values echo "Register values read: "; foreach ($registers as $register) { echo $register . " "; } // Send write command socket_write($socket, $writeCommand, strlen($writeCommand)); // Receive response data $response = socket_read($socket, 1024); // Parse response data // TODO: Parse response data according to the Modbus protocol // Close TCP connection socket_close($socket); ?>
The example code first establishes a TCP connection using the Modbus device's IP and port. It uses pack() to convert read/write register commands into binary data and sends them over TCP. After receiving device responses, unpack() is used to parse register values. The read values can be further processed as needed, and write operations require parsing according to the Modbus protocol.
Parsing Modbus TCP commands and responses with PHP enables data interaction with Modbus devices. This article provides the basic communication process and example code. Developers can build on this foundation to implement more advanced functionality and enhance data handling in industrial automation systems.