I am trying to develop a python gui application which communicates with a PLC using pymodbus. Using the documentation from the website & what I've found online, I can easily communicate & everything works perfectly. I am struggling with how to incorportate all this into a gui class with various methods. I am new to python & oo programing as my background is in mechanical engineering.
Please have a look at the code below. I want to connect to the device with method 'modbusConnect' when the user clicks & button. Therefore I've created the 'client' instance of ModbusTcpClient.
How can I then reference this instance in the 'dialValueChanged' method to read or write to a register. Please let me know if the structure of my code is incorrect & I should have various classes & etc.
Thank you in advance.
David
from pymodbus.client.sync import ModbusTcpClient
import struct
import sys
from PyQt4 import QtCore, QtGui, uic
form_class = uic.loadUiType("C:\Users\David\.PyCharm30\VC-22D Modbus TCP\UI Design\Modbus- MainScreen.ui")[0]
form_class2 = uic.loadUiType("C:\Users\David\.PyCharm30\VC-22D Modbus TCP\UI Design\Modbus- ConnectMenu.ui")[0]
class MyWindowClass(QtGui.QMainWindow, form_class):
def __init__(self, parent=None):
QtGui.QMainWindow.__init__(self, parent)
self.setupUi(self)
self.setFixedSize(1500,1200)
self.dial.valueChanged.connect(self.dialValueChanged)
self.pushButton_Connect.clicked.connect(self.modbusConnect)
self.label.setAlignment(QtCore.Qt.AlignCenter)
self.setWindowIcon(QtGui.QIcon("C:\Users\David\.PyCharm30\VC-22D Modbus TCP\UI Design\Cla-Val_30px.png"))
def modbusConnect(self):
#modbus connection
ipaddress = str(self.lineEdit_IP.text())
client = ModbusTcpClient(ipaddress)
testconnection = client.connect()
if testconnection == True:
print ("Connection Successful")
else:
print ("Connection Not Successful")
print (self.lineEdit_IP.text())
exit()
def dialValueChanged(self):
setvalue = float(self.label.text())
if setvalue == 0:
setvalueint = 0
else:
setvaluehex = str(hex(struct.unpack('<I', struct.pack('<f', setvalue))[0]))
setvaluehexstr = setvaluehex[:-4]
setvalueint = int(setvaluehexstr, 16)
app = QtGui.QApplication(sys.argv)
myWindow = MyWindowClass(None)
myWindow.show()
app.exec_()
Turn the client
into an instance attribute of this GUI:
def modbusConnect(self):
#modbus connection
ipaddress = str(self.lineEdit_IP.text())
self.client = ModbusTcpClient(ipaddress)
You can then refer to it from dialValueChanged
:
def dialValueChanged(self):
[... 7 lines omitted from output ...]
self.client.write_coil(some_register, setvalueint) #write_coil or write_register, depends on your communication
However, this means the GUI class is not fully instantiated when it is created. You should add some failsafes for when the pushButtonConnect
is clicked again as well.