1/****************************************************************************
2**
3** Copyright (C) 2017 The Qt Company Ltd.
4** Contact: https://www.qt.io/licensing/
5**
6** This file is part of the examples of the QtSerialBus module.
7**
8** $QT_BEGIN_LICENSE:BSD$
9** Commercial License Usage
10** Licensees holding valid commercial Qt licenses may use this file in
11** accordance with the commercial license agreement provided with the
12** Software or, alternatively, in accordance with the terms contained in
13** a written agreement between you and The Qt Company. For licensing terms
14** and conditions see https://www.qt.io/terms-conditions. For further
15** information use the contact form at https://www.qt.io/contact-us.
16**
17** BSD License Usage
18** Alternatively, you may use this file under the terms of the BSD license
19** as follows:
20**
21** "Redistribution and use in source and binary forms, with or without
22** modification, are permitted provided that the following conditions are
23** met:
24** * Redistributions of source code must retain the above copyright
25** notice, this list of conditions and the following disclaimer.
26** * Redistributions in binary form must reproduce the above copyright
27** notice, this list of conditions and the following disclaimer in
28** the documentation and/or other materials provided with the
29** distribution.
30** * Neither the name of The Qt Company Ltd nor the names of its
31** contributors may be used to endorse or promote products derived
32** from this software without specific prior written permission.
33**
34**
35** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
36** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
37** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
38** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
39** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
40** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
41** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
42** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
43** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
44** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
45** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE."
46**
47** $QT_END_LICENSE$
48**
49****************************************************************************/
50
51#include "mainwindow.h"
52#include "modbustcpclient.h"
53
54#include <QLoggingCategory>
55#include <QModbusPdu>
56#include <QModbusRtuSerialMaster>
57#include <QSerialPortInfo>
58
59#ifndef QT_STATIC
60 QT_BEGIN_NAMESPACE
61 Q_LOGGING_CATEGORY(QT_MODBUS, "qt.modbus")
62 Q_LOGGING_CATEGORY(QT_MODBUS_LOW, "qt.modbus.lowlevel")
63 QT_END_NAMESPACE
64#endif
65
66QT_USE_NAMESPACE
67
68MainWindow *s_instance = nullptr;
69
70static void HandlerFunction(QtMsgType, const QMessageLogContext &, const QString &msg)
71{
72 if (auto instance = MainWindow::instance())
73 instance->appendToLog(msg);
74}
75
76MainWindow::MainWindow(QWidget *parent)
77 : QMainWindow(parent)
78 , m_debugHandler(HandlerFunction)
79{
80 setupUi(this);
81 s_instance = this;
82
83 const auto ports = QSerialPortInfo::availablePorts();
84 for (const QSerialPortInfo &info : ports)
85 serialPortCombo->addItem(atext: info.portName(), auserData: false);
86 serialPortCombo->insertSeparator(index: serialPortCombo->count());
87 serialPortCombo->addItem(atext: tr(s: "Add port..."), auserData: true);
88 serialPortCombo->setInsertPolicy(QComboBox::InsertAtTop);
89
90 connect(sender: tcpRadio, signal: &QRadioButton::toggled, context: this, slot: [this](bool toggled) {
91 stackedWidget->setCurrentIndex(toggled);
92 });
93 connect(sender: actionExit, signal: &QAction::triggered, receiver: this, slot: &QMainWindow::close);
94
95 QLoggingCategory::setFilterRules(QStringLiteral("qt.modbus* = true"));
96}
97
98MainWindow::~MainWindow()
99{
100 disconnectAndDelete();
101 s_instance = nullptr;
102}
103
104MainWindow *MainWindow::instance()
105{
106 return s_instance;
107}
108
109void MainWindow::on_sendButton_clicked()
110{
111 const bool isSerial = serialRadio->isChecked();
112 const bool isCustom = (isSerial ? fcSerialDrop : fcTcpDrop)->currentIndex() == 0;
113 const QByteArray pduData = QByteArray::fromHex(hexEncoded: (isSerial ? pduSerialLine : pduTcpLine)->text()
114 .toLatin1());
115
116 QModbusReply *reply = nullptr;
117 if (isCustom && pduData.isEmpty()) {
118 qDebug() << "Error: Cannot send custom PDU without any data.";
119 return;
120 }
121
122 const quint8 address = quint8((isSerial ? addressSpin : ui1Spin)->value());
123 if (isCustom) {
124 qDebug() << "Send: Sending custom PDU.";
125 reply = m_device->sendRawRequest(request: QModbusRequest(QModbusRequest::FunctionCode(
126 pduData[0]), pduData.mid(index: 1)), serverAddress: address);
127 } else {
128 qDebug() << "Send: Sending PDU with predefined function code.";
129 quint16 fc = (isSerial ? fcSerialDrop : fcTcpDrop)->currentText().left(n: 4).toUShort(ok: 0, base: 16);
130 reply = m_device->sendRawRequest(request: QModbusRequest(QModbusRequest::FunctionCode(fc), pduData),
131 serverAddress: address);
132 }
133
134 if (reply) {
135 sendButton->setDisabled(true);
136 if (!reply->isFinished()) {
137 connect(sender: reply, signal: &QModbusReply::finished, slot: [reply, this]() {
138 sendButton->setEnabled(true);
139 qDebug() << "Receive: Asynchronous response PDU: " << reply->rawResult() << Qt::endl;
140 });
141 } else {
142 sendButton->setEnabled(true);
143 qDebug() << "Receive: Synchronous response pdu: " << reply->rawResult() << Qt::endl;
144 }
145 }
146}
147
148void MainWindow::on_connectButton_clicked()
149{
150 if (tcpRadio->isChecked()) {
151 auto device = new ModbusTcpClient;
152 connect(sender: ti1Spin, signal: QOverload<int>::of(ptr: &QSpinBox::valueChanged),
153 receiver: device, slot: &ModbusTcpClient::valueChanged);
154 connect(sender: ti2Spin, signal: QOverload<int>::of(ptr: &QSpinBox::valueChanged),
155 receiver: device, slot: &ModbusTcpClient::valueChanged);
156
157 connect(sender: pi1Spin, signal: QOverload<int>::of(ptr: &QSpinBox::valueChanged),
158 receiver: device, slot: &ModbusTcpClient::valueChanged);
159 connect(sender: pi2Spin, signal: QOverload<int>::of(ptr: &QSpinBox::valueChanged),
160 receiver: device, slot: &ModbusTcpClient::valueChanged);
161
162 connect(sender: l1Spin, signal: QOverload<int>::of(ptr: &QSpinBox::valueChanged),
163 receiver: device, slot: &ModbusTcpClient::valueChanged);
164 connect(sender: l2Spin, signal: QOverload<int>::of(ptr: &QSpinBox::valueChanged),
165 receiver: device, slot: &ModbusTcpClient::valueChanged);
166
167 connect(sender: ui1Spin, signal: QOverload<int>::of(ptr: &QSpinBox::valueChanged),
168 receiver: device, slot: &ModbusTcpClient::valueChanged);
169
170 m_device = device;
171 device->valueChanged(value: 0); // trigger update
172 m_device->setConnectionParameter(parameter: QModbusDevice::NetworkAddressParameter,
173 value: tcpAddressEdit->text());
174 m_device->setConnectionParameter(parameter: QModbusDevice::NetworkPortParameter,
175 value: tcpPortEdit->text());
176 } else {
177 m_device = new QModbusRtuSerialMaster;
178 m_device->setConnectionParameter(parameter: QModbusDevice::SerialPortNameParameter,
179 value: serialPortCombo->currentText());
180
181 int parity = parityCombo->currentIndex();
182 if (parity > 0)
183 parity++;
184 m_device->setConnectionParameter(parameter: QModbusDevice::SerialParityParameter, value: parity);
185 m_device->setConnectionParameter(parameter: QModbusDevice::SerialDataBitsParameter,
186 value: dataBitsCombo->currentText().toInt());
187 m_device->setConnectionParameter(parameter: QModbusDevice::SerialStopBitsParameter,
188 value: stopBitsCombo->currentText().toInt());
189 m_device->setConnectionParameter(parameter: QModbusDevice::SerialBaudRateParameter,
190 value: baudRateCombo->currentText().toInt());
191 }
192 m_device->setTimeout(timeoutSpin->value());
193 m_device->setNumberOfRetries(retriesSpin->value());
194
195 connect(sender: m_device, signal: &QModbusDevice::errorOccurred, context: this, slot: [this](QModbusDevice::Error) {
196 qDebug().noquote() << QStringLiteral("Error: %1").arg(a: m_device->errorString());
197 emit disconnectButton->clicked();
198 }, type: Qt::QueuedConnection);
199
200 connect(sender: m_device, signal: &QModbusDevice::stateChanged, slot: [](QModbusDevice::State state) {
201 switch (state) {
202 case QModbusDevice::UnconnectedState:
203 qDebug().noquote() << QStringLiteral("State: Entered unconnected state.");
204 break;
205 case QModbusDevice::ConnectingState:
206 qDebug().noquote() << QStringLiteral("State: Entered connecting state.");
207 break;
208 case QModbusDevice::ConnectedState:
209 qDebug().noquote() << QStringLiteral("State: Entered connected state.");
210 break;
211 case QModbusDevice::ClosingState:
212 qDebug().noquote() << QStringLiteral("State: Entered closing state.");
213 break;
214 }
215 });
216 m_device->connectDevice();
217}
218
219void MainWindow::on_disconnectButton_clicked()
220{
221 disconnectAndDelete();
222}
223
224void MainWindow::on_serialPortCombo_currentIndexChanged(int index)
225{
226 const bool custom = serialPortCombo->itemData(index, role: Qt::UserRole).toBool();
227 serialPortCombo->setEditable(custom);
228 if (custom) {
229 serialPortCombo->clearEditText();
230 serialPortCombo->lineEdit()->setPlaceholderText(QStringLiteral("Type here..."));
231 }
232}
233
234void MainWindow::disconnectAndDelete()
235{
236 if (!m_device)
237 return;
238 m_device->disconnectDevice();
239 m_device->disconnect();
240 delete m_device;
241 m_device = nullptr;
242}
243

source code of qtserialbus/examples/serialbus/modbus/adueditor/mainwindow.cpp