PHP Modbus Library
PHPMODBUS is a Modbus UDP/TCP communication library implemented in PHP, hosted on Google Code Archivecode.google.com/p/phpmodbus(Archived). It implements the basic functions of the Modbus UDP protocol, supporting FC03 (read and hold registers), FC16 (write multiple registers), and FC23 (read/write multiple registers).
Although Modbus UDP is far less common than Modbus TCP in industrial settings, PHPMODBUS has unique value in certain special web application scenarios - such as directly reading data from Modbus UDP devices in SCADA kanban websites written in PHP, or remotely controlling Modbus devices through a browser interface.
Installation and Basic Use
<?php
// 引入 phpmodbus 库
require_once 'PhpModBus.php';
// 创建 Modbus UDP 主站实例
$modbus = new ModbusUdpMaster('192.168.1.100', 502);
try {
// FC03: 读取从站 1,起始地址 0,10 个保持寄存器
$data = $modbus->readMultipleRegisters(1, 0, 10);
// 输出结果
echo "读取到的寄存器数据:n";
for ($i = 0; $i < count($data); $i++) {
echo sprintf(" 地址 %d: %d (0x%04X)n", $i, $data[$i], $data[$i]);
}
} catch (Exception $e) {
echo "Modbus 通信错误: " . $e->getMessage();
}
?>FC16 Writing Multiple Keep registers
<?php
$modbus = new ModbusUdpMaster('192.168.1.100', 502);
// 要写入的数据
$values = [100, 200, 300, 400];
// FC16: 从站 1,起始地址 10,写入 4 个寄存器
$modbus->writeMultipleRegister(1, 10, $values);
echo "写入成功n";
?>FC23 Combining Read and Write
<?php
$modbus = new ModbusUdpMaster('192.168.1.100', 502);
// FC23: 读地址 0-9,同时写地址 10-13
$valuesToWrite = [99, 88, 77, 66];
$readData = $modbus->readWriteRegisters(1, 0, 10, 10, $valuesToWrite);
echo "读取数据: ";
print_r($readData);
echo "写入数据: ";
print_r($valuesToWrite);
?>Go Modbus Library (gobrow/modbus)
go modbus (full namegithub.com/goburrow/modbus) is a Modbus protocol client library written in Go language, GitHub address:github.com/goburrow/modbus. It is described as an implementation of 'fault fault, fail fast' - with a focus on error handling and fast failure in design, suitable for use in industrial edge gateway scenarios with high reliability and stability requirements.
⚠️Note: According to the latest description from modbus.org in 2024, the library is still in the "incubating" stage, "do not use in production yet (more testing needed)". Although the API design is excellent, it needs to be thoroughly tested before use in production environments.
Installation
go get github.com/goburrow/modbusModbus TCP Client Example
package main
import (
"fmt"
"time"
"github.com/goburrow/modbus"
)
func main() {
// 创建 TCP 客户端
handler := modbus.NewTCPClientHandler("192.168.1.100:502")
handler.Timeout = 5 * time.Second
handler.SlaveId = 1
// 建立连接
err := handler.Connect()
if err != nil {
fmt.Printf("连接失败: %vn", err)
return
}
defer handler.Close()
client := modbus.NewClient(handler)
// 读取 10 个保持寄存器(地址 0-9)
results, err := client.ReadHoldingRegisters(0, 10)
if err != nil {
fmt.Printf("读取失败: %vn", err)
return
}
fmt.Println("寄存器数据:")
for i := 0; i < len(results)-1; i += 2 {
value := uint16(results[i])<<8 | uint16(results[i+1])
fmt.Printf(" 地址 %d: %d (0x%04X)n", i/2, value, value)
}
// 写入单个寄存器
err = client.WriteSingleRegister(0, 1234)
if err != nil {
fmt.Printf("写入失败: %vn", err)
} else {
fmt.Println("写入成功")
}
}Modbus RTU Serial Client
package main
import (
"fmt"
"github.com/goburrow/modbus"
)
func main() {
// 创建 RTU 客户端(RS-485)
handler := modbus.NewRTUClientHandler("/dev/ttyUSB0")
handler.BaudRate = 9600
handler.DataBits = 8
handler.Parity = "N" // 无校验
handler.StopBits = 1
handler.SlaveId = 1
handler.Timeout = 3 * time.Second
err := handler.Connect()
if err != nil {
panic(err)
}
defer handler.Close()
client := modbus.NewClient(handler)
results, _ := client.ReadHoldingRegisters(0, 5)
fmt.Printf("RTU 读取结果: % Xn", results)
}Advantages of Go Language in Industrial IoT
Go Language has become increasingly popular in the field of industrial IoT edge gateways in recent years for several reasons:
- Native concurrency: goroutine makes connecting hundreds of Modbus slaves at the same time simple and efficient
- Single binary deployment: compiled as an independent executable file without runtime dependencies (such as JVM, Python interpreter), deployment is extremely simple
- Cross platform compilation:
GOOS=linux GOARCH=arm64 go buildCross compile to ARM Linux (Raspberry Pi, industrial computer) - Memory SecurityCompared to C language, Go's automatic garbage collection and memory security checks are more suitable for writing stable long-running services
Python Modbus Test Kit (modbus-tk)
Modbus Test Kit (modbus tk) is a Python implemented Modbus protocol library, project in Google Code Archive. It supports Modbus RTU and Modbus TCP, and can write both client and server simultaneously. For Python users, another more modern option ispymodbusThe two have different API styles but similar functional coverage.
#!/usr/bin/env python3
# modbus-tk 基本使用示例
import modbus_tk
import modbus_tk.defines as cst
from modbus_tk import modbus_tcp
# 创建 TCP 主站
master = modbus_tcp.TcpMaster(host="192.168.1.100", port=502)
master.set_timeout(5.0)
# 读取从站 1 的保持寄存器 0-9
try:
values = master.execute(1, cst.READ_HOLDING_REGISTERS, 0, 10)
print(f"读取结果: {values}")
except modbus_tk.modbus.ModbusError as exc:
print(f"Modbus 错误: {exc}")Suggestions for selecting Modbus libraries for various languages
| Usage Scenarios | Recommended Library | Language | Status |
|---|---|---|---|
| Web application integration | phpmodbus | PHP | Stop updating (UDP only) |
| Edge Gateway Service | goburrow/modbus | Go | Incubating |
| Automated testing script | modbus-tk / pymodbus | Python | active |
| Embedded Linux | libmodbus | C | stable |
Summary
Although Modbus is an old protocol that has been around for over 40 years, it has corresponding implementations in various modern programming languages. PHP's phpmodbus is suitable for Web integration scenarios (although only UDP is supported). Go's gobrrow/modbus shows the potential of Go language in edge computing of the industrial Internet of Things. Python's pymodbus and modbus tk are the best choices for writing automated test scripts and researching prototypes. Choose the appropriate library based on your project's language stack and stability requirements.
Leave a Reply