我正在尝试使用pymodbus Callback Sever将RS252 Ascii字符串数据从传感器转换为Modbus TCP输入/保持寄存器,当请求客户端记录程序时服务器是主报告数据,我不知道我需要做什么才能使其正常工作。我目前能够读取数据并将其记录到一个csv文件中
#!/usr/bin/env python
# Log data from serial port
import argparse
import serial
import datetime
import time
import os
parser = argparse.ArgumentParser(formatter_class=argparse.ArgumentDefaultsHelpFormatter)
parser.add_argument("-d", "--device", help="device to read from", default="/dev/ttyUSB0")
parser.add_argument("-s", "--speed", help="speed in bps", default=9600, type=int)
args = parser.parse_args()
outputFilePath = os.path.join(os.path.dirname(__file__),
datetime.datetime.now().strftime("%Y-%m-%d") + ".csv")
with serial.Serial(args.device, args.speed) as ser, open(outputFilePath,'w') as outputFile:
print("Logging started. Ctrl-C to stop.")
try:
while True:
time.sleep(0.2)
x = (ser.read(ser.inWaiting()))
data = x.decode('UTF-8')
if data !="":
outputFile.write(time.strftime("%Y/%m/%d %H:%M ") + " " + data )
outputFile.flush()
except KeyboardInterrupt:
print("Logging stopped")
来自传感器的字符串以如下方式从设备中发出:
0.00 0.0 0.0 346.70 25.14
我需要将每个模块都作为自己的Modbus寄存器,并且我试图在Raspberry Pi Zero上使用pymodbus。传感器每秒更新4次,我能够将数据分解成几部分,但我还没有做到这一点,因为我不确定我需要在Callback脚本中做什么,我还不熟悉Python我是我还在学习。我确实了解Modbus TCP,并且以前在Arduino系统上使用过它。任何帮助将不胜感激。
答案 0 :(得分:2)
您需要的是updating server,可用于填充寄存器。您将必须专注于功能def updating_writer
并进行串行读取,处理它们并写入您选择的寄存器。这个例子一开始很难阅读和理解。我已修改example以满足您的需求。但是这里有一些关键概念,这些概念很容易理解代码。
还要注意,该示例使用基于twisted的异步服务器。如果您是twisted的新手,或者有一些不允许在目标上使用twisted的约束,则也可以使用简单线程来实现相同目的。设计大概是这样的。
# Complete gist here --> https://gist.github.com/dhoomakethu/540b15781c62de6d1f7c318c3fc8ae22
def updating_writer(context, device, baudrate):
""" A worker process that runs every so often and
updates live values of the context. It should be noted
that there is a race condition for the update.
:param arguments: The input arguments to the call
"""
log.debug("updating the context")
log.debug("device - {}, baudrate-{}".format(device, baudrate))
data = serial_reader(device, baudrate) # Implement your serial reads, return list of floats.
if data:
# We can not directly write float values to registers, Use BinaryPayloadBuilder to convert float to IEEE-754 hex integer
for d in data:
builder.add_32bit_float(d)
registers = builder.to_registers()
context = context
register = 3 # Modbus function code (3) read holding registers. Just to uniquely identify what we are reading from /writing in to.
slave_id = 0x01 # Device Unit address , refer ModbusSlaveContext below
address = 0x00 # starting offset of register to write (0 --> 40001)
log.debug("new values: " + str(registers))
context[slave_id].setValues(register, address, registers)
一旦服务器运行且值已更新,则可以使用客户端读取值并将其解析回浮点数。
from pymodbus.client.sync import ModbusTcpClient as Client
from pymodbus.payload import BinaryPayloadDecoder, Endian
client = Client(<IP-ADDRESS>, port=5020)
# Each 32 bit float is stored in 2 words, so we will read 10 registers
raw_values = client.read_holding_registers(0, 10, unit=1)
if not registers.isError():
registers = raw_values.registers
decoder = BinaryPayloadDecoder.fromRegisters(registers,
wordorder=Endian.Big, byteorder=Endian.Big)
for _ in range(5):
print(decoder.decode_32bit_float())