Install pyModbusTCP python library for Modbus TCP
pi@raspberrypi:~/BMS $ sudo pip3 install pyModbusTCP
Output
Looking in indexes: https://pypi.org/simple, https://www.piwheels.org/simple
Collecting pyModbusTCP
Downloading https://www.piwheels.org/simple/pymodbustcp/pyModbusTCP-0.1.10-py3-none-any.whl (17 kB)
Installing collected packages: pyModbusTCP
Successfully installed pyModbusTCP-0.1.10
Using the Library
Import the Modbus Client object from the library
from pyModbusTCP.client import ModbusClient # Modbus TCP Client
Open TCP and keep it open
# TCP auto connect on modbus request, keep it open
ModbusBMS = ModbusClient(host="10.1.3.8", port=2000, unit_id=1, auto_open=True)
open/close TCP socket before/after read or write
# TCP auto connect on modbus request, close after it
ModbusBMS = ModbusClient(host="10.1.3.8", port=2000, unit_id=1, auto_open=True, auto_close=True)
Read Registers
Read two 16-bit Holding registers from Register 0
Reg= ModbusBMS.read_holding_registers(0, 2)
if Reg:
print(Reg[0])
else:
print("read error")
Complete Code
from pyModbusTCP.client import ModbusClient # Modbus TCP Client
import os, time
# TCP auto connect on modbus request, close after it
ModbusBMS = ModbusClient(host="10.1.3.8", port=2000, unit_id=1, auto_open=True, auto_close=True)
time.sleep(5)
def ModbusTCP():
global AlarmStatus
Alarm = ModbusBMS.read_holding_registers(0, 2)
time.sleep(2)
if Alarm:
print(Alarm[0])
else:
print("read error")
if __name__ == '__main__':
ModbusTCP()
time.sleep(5) #delay 5 sec
DEMO – Read Data From Slave