Home >Backend Development >PHP Tutorial >PHP and Modbus TCP: Best Practices for Building Real-Time Alerting Systems
PHP and Modbus TCP: Best Practices for Building Real-Time Alarm Systems
Abstract:
This article will introduce how to use PHP and Modbus TCP protocols to build a real-time alarm system. By using PHP's network programming capabilities and Modbus TCP protocol, we can easily obtain data from remote devices and detect abnormal status in real time. At the same time, we will also provide code examples so that readers can better understand and apply these technologies.
<?php $device_ip = '192.168.1.100'; $device_port = 502; // 创建一个TCP socket $socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP); if ($socket === false) { echo "socket_create() failed: " . socket_strerror(socket_last_error()) . "<br>"; exit; } // 连接远程设备 $result = socket_connect($socket, $device_ip, $device_port); if ($result === false) { echo "socket_connect() failed: " . socket_strerror(socket_last_error()) . "<br>"; exit; } // 发送读取设备数据的请求 $request = ""; socket_write($socket, $request, strlen($request)); // 读取设备返回的数据 $response = socket_read($socket, 1024); echo "设备返回的数据:" . bin2hex($response) . "<br>"; // 关闭TCP连接 socket_close($socket); ?>
<?php function readModbusRegister($socket, $address, $quantity) { $request = "" . pack('n*', $address) . pack('n*', $quantity); socket_write($socket, $request, strlen($request)); $response = socket_read($socket, 1024); // 解析设备返回的数据 $data = substr($response, 9); $values = unpack('n*', $data); return $values; } ?>
The following is a sample code for a real-time alarm system:
<?php $device_ip = '192.168.1.100'; $device_port = 502; $socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP); socket_connect($socket, $device_ip, $device_port); while (true) { // 读取设备数据 $values = readModbusRegister($socket, $address, $quantity); // 判断是否触发报警 if ($values[1] > $threshold) { // 发送报警信息 sendAlert('设备故障!当前值:' . $values[1]); } // 延迟一段时间 sleep(10); } socket_close($socket); function readModbusRegister($socket, $address, $quantity) { // ... } function sendAlert($message) { // ... } ?>
The above is the detailed content of PHP and Modbus TCP: Best Practices for Building Real-Time Alerting Systems. For more information, please follow other related articles on the PHP Chinese website!