如何解决 Pylibmodbus 中的这个 TypeError 异常?

How to solve this TypeError Exception in Pylibmodbus?

我正在尝试创建此 ModbusRtu 对象,但是当我尝试插入一些参数时,它似乎引发了错误。即使我只是尝试 运行 它按照作者的指示使用其原始参数,也会出现相同的错误。我目前已经安装了所有必需的软件包。

libffi-dev - 3.2.1-4 libmodbus-3.1.4-2 libmodbus-dev-3.1.4-2 python-dev - 2.7.15~rc1-1 cffi - 2.19

我真的很困惑为什么它不起作用,因为即使是作者定义的参数似乎也会产生同样的错误。

我已经尝试通过将参数转换为字节、列表或元组来遵循它的消息,但它只会引发另一个异常

``` Python Code 1 (before my solution)
self.master = ModbusRtu(device='/dev/ttyACM0', 
                        baud=9600, data_bit=8, 
                        parity='N', stop_bit=1)

``` Python Code 2 (after my solution)
self.master = ModbusRtu(device=bytes('/dev/ttyACM0', 'ascii), 
                        baud=9600, data_bit=8, 
                        parity=bytes('N', 'ascii), stop_bit=1)


``` Simpler Python Code 1
from pylibmodbus import ModbusRtu

def main():
    client = ModbusRtu()
    # i can't instantiate the ModbusRtu class
    print(client)
    # i should have at least the id of the instantiated class
if __name__ == '__main__':
    main()

应该是在创建对象,但是我只收到这条消息:

文件“/usr/local/lib/python3.6/dist-packages/pylibmodbus/modbus_rtu.py”,第 11 行,在 init 中 self.ctx = C.modbus_new_rtu(设备,波特率,奇偶校验,data_bit, stop_bit) 类型错误:ctype 'char *' 的初始值设定项必须是字节或列表或元组,而不是 str

当我尝试将字符串参数转换为字节时,我收到了这条消息:

文件“/usr/local/lib/python3.6/dist-packages/pylibmodbus/modbus_core.py”,第 60 行,在 _运行 引发异常(ffi.string(C.modbus_strerror(ffi.errno))) 异常:b'没有那个文件或目录'

这对我有用 Python 2.x:

from pylibmodbus import ModbusRtu

client=ModbusRtu(device="/dev/ttyACM0", baud=19200, parity="N", data_bit=8, stop_bit=1)

client.connect()
SERVER_ID=0

client.set_slave(SERVER_ID)

client.write_registers(0, [0]*10)

result=(client.read_registers(0, 10))
print result

client.close()

对于 Python 3.x,您必须 对文本进行编码 ,我认为这是您的问题:

从 pylibmodbus 导入 ModbusRtu

client=ModbusRtu(device="/dev/ttyACM0".encode("ascii"), baud=19200, parity="N".encode("ascii"), data_bit=8, stop_bit=1)

client.connect()
SERVER_ID=0

client.set_slave(SERVER_ID)

client.write_registers(0, [0]*10)

result=(client.read_registers(0, 10))
print(result)

client.close()