python - 在 python 中使用 pymodbus 读取离散输入
问题描述
我正在使用 python 通过 modbus 从控制器收集数据。我阅读了很多文档,这些文档解释了如何显示从线圈、输入寄存器和保持寄存器收集的数据,但对于离散寄存器,我什么也没看到。
我正在使用的代码是:
def connect_apm(self):
try:
# RTU
self.client = ModbusClient(method='rtu', port='/dev/ttyUSB0',
timeout=1, stopbits=1, bytesize=8, parity='N', baudrate=9600)
# IP
# self.client = ModbusClient('ip', port=)
self.connection = self.client.connect()
print('Conexión:', self.connection)
except Exception as e:
print('Error al conectar: ', e)
def registers(self):
memo_binaries = {'Emergency stop': 0x0060}
return {'self.memo_Binaries': memo_binaries}
def data_fails(self):
try:
if self.connection:
for key, value in self.registers()['self.memo_Binaries'].items():
rr = self.client.read_discrete_inputs(value, 2, unit=1) # address, count, slave address
if not rr.isError():
val = rr.registers[0]
print('{}: {}'.format(key,val))
else:
print('{}: error'.format(key))
time.sleep(0.3)
except Exception as e:
print('Error: ',e)
原始代码分为两部分,一部分包含 apm 连接和寄存器,另一部分搜索输入。
本案例的输出:
Error: 'ReadDiscreteInputsResponse' object has no attribute 'registers'
解决方案
如错误消息所示,线圈读取操作的响应是一个ReadDiscreteInputsResponse
对象,它没有名为 的成员registers
。这是有道理的,因为离散输入(或线圈)是位大小的变量(或常数)。
您需要rr.bits[0]
才能访问它们。还有与该类相关的其他功能。请参阅下面的 GitHub 链接。
资源:
https://pymodbus.readthedocs.io/en/latest/source/example/synchronous_client.html
推荐阅读
- c++ - 检查编号顺序
- python - 从 xlwings 更改单元格的宽度和高度
- deep-learning - batch_sampler 与 pytorch 数据加载器模块中的采样器有何不同
- python - 在if语句python中检查多个条件的更简单方法
- c# - 同时更新数据库中计数器值的正确方法?
- python - Scrape web pages using python
- python - 如何在 aws lambda 中添加 mecab 库
- node.js - Tsc 与 aws 崩溃
- visual-studio-code - ESLint 不建议在 VS 代码编辑器中进行任何修复
- api - 向 coinGecko API 发出请求时访问被拒绝错误 809