pymodbus - pymodbus 自定义请求中的单元参数
问题描述
这是我在这里的第一篇文章。我潜伏了一段时间。
所以,我在 pymodbus ModbusTcpClient 中遇到了关于自定义消息的问题
我正在使用一种具有自定义寄存器和命令的旧 Modbus 设备。我能够读/写线圈、寄存器等。问题是这个设备需要特殊的命令来进行某种复位。
我做了一些wireshark 嗅探,并制作了自定义消息,但我一直在定义单位参数。
这是代码片段:
class CustomModbusRequest(ModbusRequest):
function_code = 8
def __init__(self, address):
ModbusRequest.__init__(self)
self.address = address
self.count = 1
def encode(self):
return struct.pack('>HH', self.address, self.count)
def decode(self, data):
self.address, self.count = struct.unpack('>HH', data)
def execute(self, context):
if not (1 <= self.count <= 0x7d0):
return self.doException(ModbusExceptions.IllegalValue)
if not context.validate(self.function_code, self.address, self.count):
return self.doException(ModbusExceptions.IllegalAddress)
values = context.getValues(self.function_code, self.address,
self.count)
return CustomModbusResponse(values)
def custom_8():
client = ModbusTcpClient('192.168.0.222')
connection = client.connect()
request = CustomModbusRequest(170)
result = client.execute(request)
print(result)
time.sleep(1)
在读取寄存器的正常请求中,有指定的单元参数,如下所示:
request = client.read_input_registers(513,4, unit=0x4)
在自定义请求中,我不知道如何指定。在wireshark中我可以看到在自定义消息中,我正在向地址0发送请求,我需要使用地址4。
请帮忙。
解决方案
您将不得不传递unit
自定义消息,这应该可以解决问题。
request = CustomModbusRequest(170, unit=<unit_id>)
. 您还必须更新__init__
ofCustomModbusRequest
以将额外的 kwargs 传递给parent
.
class CustomModbusRequest(ModbusRequest):
function_code = 8
def __init__(self, address, **kwargs):
ModbusRequest.__init__(self, **kwargs)
self.address = address
self.count = 1
...
...
request = CustomModbusRequest(170, unit=<unit_id>)
result = client.execute(request)
推荐阅读
- jquery - RShiny:为 tabsetPanel 中具有随机生成的 ID 的 UI 项检索 jsQuery 选择器
- android - 如何在 pexels API 中的 Flutter 图像中设置壁纸
- java - 为什么我使用 setLayoutParams 时 FrameLayout 不显示?
- kotlin - 替换非空断言运算符“!!” 执行数学表达式
- java - 在按钮单击中显示加载 GIF,并在执行操作后再次隐藏它
- java - Javadoc 不会在 IntelliJ IDEA 中自动生成
- c# - 为什么 adapter.Fill 突然停止在 C# 中填充我的数据表?
- ubuntu - Lubuntu 18.04 中的自动启动应用程序
- visual-studio - Visual Studio 2019“禁用项目代码”不再可见
- python - TypeError:参数必须是矩形样式对象