The protocol typically follows a master-slave architecture, where the master initiates communication and the slave responds to requests. This structure allows centralized control of multiple devices, enabling efficient data acquisition and remote monitoring in industrial environments.
<?php class ModbusTCP { private $socket; public function __construct($ip, $port) { $this->socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP); socket_connect($this->socket, $ip, $port); } public function readRegisters($slaveId, $registerAddress, $registerCount) { $buffer = pack("nnnn", $slaveId, 0x03, $registerAddress, $registerCount); socket_send($this->socket, $buffer, strlen($buffer), 0); $response = ''; $bytes = socket_recv($this->socket, $response, 2048, MSG_WAITALL); $registers = unpack("n*", substr($response, 9)); return $registers; } public function writeRegister($slaveId, $registerAddress, $registerValue) { $buffer = pack("nnn", $slaveId, 0x06, $registerAddress, $registerValue); socket_send($this->socket, $buffer, strlen($buffer), 0); } public function __destruct() { socket_close($this->socket); } } // Usage example $modbus = new ModbusTCP('192.168.0.1', 502); $registers = $modbus->readRegisters(1, 0, 10); foreach ($registers as $address => $value) { echo "Register $address: $value\n"; } $modbus->writeRegister(1, 0, 100);
This code defines a ModbusTCP class in PHP that encapsulates the key functionalities of MODBUS TCP communication. It includes methods to create and close socket connections, read registers, and write values to them. Developers can use this class to connect to a MODBUS device over a specified IP and port, perform register operations, and process the response.
Reference:
[1] MODBUS Application Protocol Specification v1.1b3 — https://modbus.org/docs/Modbus_Application_Protocol_V1_1b3.pdf