In this blog, I would like to provide a small Qt Quick application (qml) as an example of a Modbus connection over TCP/IP.
In the Qt examples, I have only found QWidget examples for Modbus connections, and after recently creating a Qt Quick application for this, I would like to provide a slimmed-down version of it as an example.
Lab
In order to be able to test the application, you need a Modbus server or a program that "simulates" such a server. I used the "Modbus Server Pro" from http://www.apphugs.com/modbus-server.html for this. This allows you to run through all the scenarios you need.
Qt application
First of all: Since it would go too far to post all the code here, I will provide the entire code as a ZIP file (see below).
Settings
First, I created a simple SettingsDialog class that contains the connection options. In the simplified example, this is just the "modbusServerUrl", the "responseTime" and the "numberOfRetries".
struct Settings {
QString modbusServerUrl = "192.168.2.86:1502";
int responseTime = 1000;
int numberOfRetries = 3;
};
The designations are - I think - self-explanatory.
- modbusServerUrl = the TCP/IP number plus Modbus server port, e.g. 192.168.2.86:502
- responseTime = the maximum time in ms in which a response from the server is waited for
- numberOfRetries = the number of failed attempts that will be accepted.
Application
onConnectButtonClicked()
The onConnectButtonClicked() function reads the connection data from the settings file and establishes the connection to the Modbus server.
onReadButtonClicked()
With onReadButtonClicked() various readRequests are then initiated and the corresponding registers are read from the Modbus server. The returned values are passed on to qml as Q_PROPERTY via emit signals and updated in the user interface.
Write function
The function onWriteButtonClicked(int writeregister) is used to write to the Modbus server registers. Here it is envisaged that different registers can be written on the Modbus server via the variable "writeregister".
You can download the application here ix-modbus-tcp-example.zip.