注:目前的发展只涉及 modbus master即 client不涉及终端开发 slave开发终端服务器,slave在服务器设计中,嵌入式设备一般用作数据收集器,市场上有现成的设计slave使用数据采集器。
python封装的modbus库有:
modbus_tk :完整modbus协议栈的实现,支持modbus tcp/RTU{1.提供slave模拟器,即模拟modbus server:502), web-based hmi master支持}
pymodbus:使用twisted实现的modbus完整协议(支持异步通信)
MinimalModbus :只支持modbus rtu
使用modbus tcp推荐模式通信modbus_tk库
==============================================================================
modbus master 为client,连接远程的slave请求收集到的数据。
modbus slave 为 server ,监控502端口,一般slave为plc,plc从嵌入式设备modbus数据上收集数据。master发送modbus协议数据请求salve获取数据。
1.连接到远程slave(即modbus server502端口服务器)
master = modbus_tcp.TcpMaster("192.168.2.20",502)
master.set_timeout(5.0)
2.进行调用modbus_tk库的接口,方向slave要求收集的数据
类TcpMaster接口如下:
set_timeout(秒)
_send(modbus请求) modbus请求,即需要自己包装modbus协议头和请求命令
_recv() 返回modbus协议数据
open()
close()
execute(slave,功能代码,开始地址,quantity_of_x=0,output_value=0,data_format="",指定长度=-1)//execute线程安全函数
使用例子:
import modbus_tk.defines as de
master.execute(slave_id=1,de.READ_HOLDING_REGISTERS,100,3)
slave_id:1
slave_id : identifier of the slave. from 1 to 247. 0为广播所有slave
功能代码:de.READ_HOLDING_REGISTE 定义见:defines.py
开始地址如下 100
quantity_of_x = 3 (寄存器或线圈的数量)
output_value: (一个整数或可迭代值) 如:
output_value = 1或 54 或 output_value=[1,1,0,1,0,1,0,1 或者 output_value = xrange(12)
返回元祖类型的数据取决于查询的功能码,参考详细信息modbus构造协议说明书data_format
modbus 功能代码: defines.py
#modbus 异常代码
ILLEGAL_FUNCTION = 1 功能代码非法
ILLEGAL_DATA_ADDRESS = 2 非法数据地址
ILLEGAL_DATA_VALUE = 3 数据值不合法
SLAVE_DEVICE_FAILURE = 4 slave设备失败
COMMAND_ACKNOWLEDGE = 5 命令已收到
SLAVE_DEVICE_BUSY = 6 slave设备忙
MEMORY_PARITY_ERROR = 8 内存奇偶误差
#supported modbus 功能代码
READ_COILS = 1 读线圈
READ_DISCRETE_INPUTS = 2 读离散输入
READ_HOLDING_REGISTERS = 3 读乘法寄存器
READ_INPUT_REGISTERS = 4 读取输入寄存器
WRITE_SINGLE_COIL = 5 写单一线圈
WRITE_SINGLE_REGISTER = 6 写单个寄存器
WRITE_MULTIPLE_COILS = 15 写多个线圈 【强制多点线圈】
WRITE_MULTIPLE_REGISTERS = 16 写多寄存器 【写乘法寄存器】
#supported block types 支持块类型
COILS = 1 线圈
DISCRETE_INPUTS = 2 离散输入(数字输入)
HOLDING_REGISTERS = 3 乘法寄存器
ANALOG_INPUTS = 4 模拟量输入
以下段落来自网络
The master uses function codes 5, 6, 15 & 16 to send data to the slave.Function code 5 allows the master to write a single coil (address 00001->) to the slave device
Function code 15 allows the master to write multiple coils (address 00001->) to the slave device
Function code 6 allows the master to write a single holding register (address 40001->) to the slave device
Function code 16 allows the master to write multiple holding registers (address 40001->) to the slave device
3.下一步是做modbus协议的封装 和 对接受的modbus数据解析