Python3 读取Modbus数据 含浮点数处理
1、引入依赖库
#!/usr/bin/python3
import modbus_tk.modbus_tcp as mt
import modbus_tk.defines as md
import time
import datetime
import struct
2、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 写多寄存器 【写乘法寄存器】
# logger.info(master.execute(1, cst.READ_COILS, 0, 10))
# logger.info(master.execute(1, cst.READ_DISCRETE_INPUTS, 0, 8))
# logger.info(master.execute(1, cst.READ_INPUT_REGISTERS, 100, 3))
# logger.info(master.execute(1, cst.READ_HOLDING_REGISTERS, 100, 12))
# logger.info(master.execute(1, cst.WRITE_SINGLE_COIL, 7, output_value=1))
# logger.info(master.execute(1, cst.WRITE_SINGLE_REGISTER, 100, output_value=54))
# logger.info(master.execute(1, cst.WRITE_MULTIPLE_COILS, 0, output_value=[1, 1, 0, 1, 1, 0, 1, 1]))
# logger.info(master.execute(1, cst.WRITE_MULTIPLE_REGISTERS, 100, output_value=xrange(12)))
3、读取保持寄存器
# 读保持寄存器
def read_AI():
AI = {}
master_0 = mt.TcpMaster(
"192.168.1.111",
502
)
master_0.set_timeout(5.0)
try:
a_0 = master_0.execute(1, md.READ_HOLDING_REGISTERS, 512, 3)
#AI[0] = a_0[0]
#AI[1] = a_0[1]
#AI[2] = a_0[2]
AI[0] =float('%.2f' % int2float(a_0[0], a_0[1]))# 锅炉蒸发量
AI[1] =float(a_0[2]/100.0)# 转速
except BaseException as e:
print(e)
return (AI)
4、读到的数据转换为浮点型
# 浮点数转换
def int2float(a,b):
f=0
try:
z0=hex(a)[2:].zfill(4) #取0x后边的部分 右对齐 左补零
z1=hex(b)[2:].zfill(4) #取0x后边的部分 右对齐 左补零
z=z1+z0 #高字节在前 低字节在后
#z=z0+z1 #低字节在前 高字节在后
#print (z)
f=struct.unpack('!f', bytes.fromhex(z))[0] #返回浮点数
except BaseException as e:
print(e)
return f
5、上完整代码
#!/usr/bin/python3
import modbus_tk.modbus_tcp as mt
import modbus_tk.defines as md
import time
import datetime
import struct
# 读模拟量
def read_AI():
AI = {}
master_0 = mt.TcpMaster(
"192.168.1.111",
502
)
master_0.set_timeout(5.0)
try:
a_0 = master_0.execute(1, md.READ_HOLDING_REGISTERS, 512, 3)
AI[0] =float('%.2f' % int2float(a_0[0], a_0[1]))# 锅炉蒸发量
AI[1] =float(a_0[2]/100.0)# 转速
except BaseException as e:
print(e)
return (AI)
# 读开关量
def read_DI():
DI = {}
master_0 = mt.TcpMaster(
"192.168.1.111",
502
)
master_0.set_timeout(5.0)
try:
d_0 = master_0.execute(1, md.READ_DISCRETE_INPUTS, 3072, 4)
DI[0] = d_0[0]# 运行
DI[1] = d_0[1]# 停运
DI[2] = d_0[2]# 阀门开
DI[3] = d_0[3]# 阀门关
except BaseException as e:
print(e)
return (DI)
# 浮点数转换
def int2float(a,b):
f=0
try:
z0=hex(a)[2:].zfill(4) #取0x后边的部分
z1=hex(b)[2:].zfill(4) #取0x后边的部分
z=z1+z0 #高字节在前 低字节在后
f=struct.unpack('!f', bytes.fromhex(z))[0] #返回浮点数
#z=z0+z1 #低字节在前 高字节在后
#print (z)
except BaseException as e:
print(e)
return f
# 自我测试
if __name__ == "__main__":
print(read_AI())
print(read_DI())