fg71
Lets build a modern interface using 2 buttons to set the state of Modbus TCP Server (Address = 0, State = True or False)
We will use Qt and Python as front and backend.
 
To run this example you need to have pymodbus and PySide6 module installed in your Python environment.
The server use IP 127.0.0.1 so your python code and modbus tcp server could be running on the same computer.
 
[203128%2F9355371%2Fmceclip0]
 
Create a folder with 2 files ( main.py and modbus_buttons.qml)
 
In the file modbus_buttons.qml
import QtQuick 2.15
import QtQuick.Controls 2.15

ApplicationWindow {
    visible: true
    width: 400
    height: 250
    title: "Modbus ON/OFF UI"

    Rectangle {
        width: parent.width
        height: parent.height
        color: "#2E3440" // Dark background

        Column {
            anchors.centerIn: parent
            spacing: 20

            Label {
                id: statusLabel
                text: "2 buttons"
                font.pixelSize: 24
                color: "#D8DEE9" // Light text
                horizontalAlignment: Text.AlignHCenter
                anchors.horizontalCenter: parent
            }

            Row {
                spacing: 10
                anchors.horizontalCenter: parent

                Button {
                    text: "ON"
                    width: 120
                    height: 50
                    background: Rectangle {
                        radius: 10
                        color: "#A3BE8C" // Green button
                    }
                    onClicked: modbusClient.writeState(0, true)
                }

                Button {
                    text: "OFF"
                    width: 120
                    height: 50
                    background: Rectangle {
                        radius: 10
                        color: "#BF616A" // Red button
                    }
                    onClicked: modbusClient.writeState(0, false)
                }
            }
        }
    }
}
 
 
In the file main.py
import sys
from PySide6.QtGui import QGuiApplication
from PySide6.QtQml import QQmlApplicationEngine
from PySide6.QtCore import QObject, Slot
from pymodbus.client import ModbusTcpClient

# Modbus Client Class
class ModbusHandler(QObject):
    def __init__(self, ip="127.0.0.1", port=502):
        super().__init__()
        self.client = ModbusTcpClient(host=ip, port=port)
        self.client.connect()

    @Slot(int, bool)
    def writeState(self, address, state):
        print(f"Writing to Modbus: Address {address}, State {state}")
        self.client.write_coil(address, state)

# Main Application
app = QGuiApplication(sys.argv)
engine = QQmlApplicationEngine()

modbus_client = ModbusHandler()
engine.rootContext().setContextProperty("modbusClient", modbus_client)

engine.load("modbus_buttons.qml")

if not engine.rootObjects():
    sys.exit(-1)

sys.exit(app.exec())
 
Reply 0 0
Reply