如何读取从modbus持有寄存器pymodbus?



我正试图用python读取Modbus RTU上的持有寄存器。我可以使它与minimalmodbus库一起工作,但不能与pymodbus库一起工作。

目前为止工作的是minimalmodbus库:

`import minimalmodbus
PORT='com5'
A_REGISTER = 40320
B_REGISTER  = 40321
OFFSET = 38001
A_REGISTER =A_REGISTER - OFFSET
B_REGISTER =B_REGISTER - OFFSET
#Set up instrument
instrument = minimalmodbus.Instrument(PORT,1,mode=minimalmodbus.MODE_RTU)
#Make the settings explicit
instrument.serial.baudrate = 19200        # Baud
instrument.serial.bytesize = 8
instrument.serial.parity   = minimalmodbus.serial.PARITY_EVEN
instrument.serial.stopbits = 1
instrument.serial.timeout  = 1          # seconds
#Good practice
instrument.close_port_after_each_call = True
instrument.clear_buffers_before_each_transaction = True
#Read temperatureas a float
#if you need to read a 16 bit register use instrument.read_register()
A_reg = instrument.read_float(A_REGISTER)
#Read the humidity
B_reg = instrument.read_float(B_REGISTER)
#Pront the values
print('The A register value is : %.1f deg Cr' % A_reg)
print('The B rgister value is: %.1f percentr' % B_reg)
`

这个效果很好。

然而,当我尝试连接到完全相同的modbus slave时,使用完全相同的物理设置,读取相同的寄存器,但使用pymodbus库,使用以下代码,它不起作用:

`from pymodbus.client import ModbusSerialClient
from pymodbus.transaction import ModbusRtuFramer as ModbusFramer
client = ModbusSerialClient(
framer=ModbusFramer,
method='rtu',
port='COM5',
baudrate=19200,
bytesize=8,
parity="E",
stopbits=1,
retries = 5,
timeout=1 
)
client.strict = False
client.connect()
res = client.read_holding_registers(address=B_REGISTER, count=1, unit=1)
res.registers`

大多数时候我得到以下错误:ConnectionException: Modbus Error: [Connection] Failed to connect[ModbusSerialClient(<pymodbus.framer.rtu_framer.ModbusRtuFramer object at 0x0000021CE12F2EE0> baud[19200])]

但有几次我得到[0]

有什么好主意吗?我一直在阅读相当多的Stackoverflow和其他来源,但我不知道我做错了什么。

感谢您的快速回复。不幸的是,我不确定我知道如何确切地遵循你的建议,但这里,请原谅我。

当我运行以下代码

import asyncio
import logging
import os
# --------------------------------------------------------------------------- #
# import the various client implementations
# --------------------------------------------------------------------------- #
from examples.helper import get_commandline
from pymodbus.client import (
AsyncModbusSerialClient,
AsyncModbusTcpClient,
AsyncModbusTlsClient,
AsyncModbusUdpClient,
)

_logger = logging.getLogger()

def setup_async_client(args):
if args.comm == "serial":
client = AsyncModbusSerialClient(
args.port,
# Common optional paramers:
#    framer=ModbusRtuFramer,
#    timeout=10,
#    retries=3,
#    retry_on_empty=False,
#    close_comm_on_error=False,
#    strict=True,
# Serial setup parameters
#    baudrate=9600,
#    bytesize=8,
#    parity="N",
#    stopbits=1,
#    handle_local_echo=False,
)
return client

async def run_async_client(client, modbus_calls=None):
"""Run sync client."""
_logger.info("### Client starting")
await client.connect()
assert client.protocol
if modbus_calls:
await modbus_calls(client)
await client.close()
_logger.info("### End of Program")

if __name__ == "__main__":
cmd_args = get_commandline(
server=False,
description="Run asynchronous client.",
)
testclient = setup_async_client(cmd_args)
asyncio.run(run_async_client(testclient), debug=True)

我得到以下错误

ModuleNotFoundError: No module named 'examples'

如果我尝试设置异步modbus串行客户端

from pymodbus.client import AsyncModbusSerialClient
from pymodbus.transaction import ModbusRtuFramer as ModbusFramer
client = AsyncModbusSerialClient(
framer=ModbusFramer,
method='rtu',
port='COM5',
baudrate=19200,
bytesize=8,
parity="E",
stopbits=1,
retries = 5,
timeout=1,
debug = True
)
client.strict = False
client.connect()
res = client.read_holding_registers(address=B_REGISTER, count=1, unit=1)
res.registers

我得到以下错误

C:Usersgen0238AppDataLocalTempipykernel_137001340640402.py:18: RuntimeWarning: coroutine 'AsyncModbusSerialClient.connect' was never awaited
client.connect()
RuntimeWarning: Enable tracemalloc to get the object allocation traceback
---------------------------------------------------------------------------
ConnectionException                       Traceback (most recent call last)
~AppDataLocalTempipykernel_137001340640402.py in <module>
18 client.connect()
19 
---> 20 res = client.read_holding_registers(address=B_REGISTER, count=1, unit=1)
21 res.registers
~AppDataRoamingPythonPython39site-packagespymodbusclientmixin.py in read_holding_registers(self, address, count, slave, **kwargs)
116             address, count, slave, **kwargs
117         )
--> 118         return self.execute(request)
119 
120     def read_input_registers(
~AppDataRoamingPythonPython39site-packagespymodbusclientbase.py in execute(self, request)
181         if self.use_protocol:
182             if not self.protocol:
--> 183                 raise ConnectionException(f"Not connected[{str(self)}]")
184             return self.protocol.execute(request)
185         if not self.connect():
ConnectionException: Modbus Error: [Connection] Not connected[AsyncModbusSerialClient None:COM5]

关于偏移量;我正试图通过串行端口连接质谱仪。问题是,如果我设置一个测量值存储在modbus持有寄存器40105的设备上,我需要从地址2104的modbus主机访问该值,但是有一些modbus寄存器/地址我不完全理解。

相关内容

  • 没有找到相关文章

最新更新