| 1 | // Copyright (C) 2017 The Qt Company Ltd. |
|---|---|
| 2 | // SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only |
| 3 | |
| 4 | #include "qmodbustcpclient.h" |
| 5 | #include "qmodbustcpclient_p.h" |
| 6 | |
| 7 | #include <QtCore/qurl.h> |
| 8 | |
| 9 | QT_BEGIN_NAMESPACE |
| 10 | |
| 11 | /*! |
| 12 | \class QModbusTcpClient |
| 13 | \inmodule QtSerialBus |
| 14 | \since 5.8 |
| 15 | |
| 16 | \brief The QModbusTcpClient class is the interface class for Modbus TCP client device. |
| 17 | |
| 18 | QModbusTcpClient communicates with the Modbus backend providing users with a convenient API. |
| 19 | */ |
| 20 | |
| 21 | /*! |
| 22 | Constructs a QModbusTcpClient with the specified \a parent. |
| 23 | */ |
| 24 | QModbusTcpClient::QModbusTcpClient(QObject *parent) |
| 25 | : QModbusClient(*new QModbusTcpClientPrivate, parent) |
| 26 | { |
| 27 | Q_D(QModbusTcpClient); |
| 28 | d->setupTcpSocket(); |
| 29 | } |
| 30 | |
| 31 | /*! |
| 32 | Destroys the QModbusTcpClient instance. |
| 33 | */ |
| 34 | QModbusTcpClient::~QModbusTcpClient() |
| 35 | { |
| 36 | close(); |
| 37 | } |
| 38 | |
| 39 | /*! |
| 40 | \internal |
| 41 | */ |
| 42 | QModbusTcpClient::QModbusTcpClient(QModbusTcpClientPrivate &dd, QObject *parent) |
| 43 | : QModbusClient(dd, parent) |
| 44 | { |
| 45 | Q_D(QModbusTcpClient); |
| 46 | d->setupTcpSocket(); |
| 47 | } |
| 48 | |
| 49 | /*! |
| 50 | \reimp |
| 51 | */ |
| 52 | bool QModbusTcpClient::open() |
| 53 | { |
| 54 | if (state() == QModbusDevice::ConnectedState) |
| 55 | return true; |
| 56 | |
| 57 | Q_D(QModbusTcpClient); |
| 58 | if (d->m_socket->state() != QAbstractSocket::UnconnectedState) |
| 59 | return false; |
| 60 | |
| 61 | const QUrl url = QUrl::fromUserInput(userInput: d->m_networkAddress + QStringLiteral(":") |
| 62 | + QString::number(d->m_networkPort)); |
| 63 | |
| 64 | if (!url.isValid()) { |
| 65 | setError(errorText: tr(s: "Invalid connection settings for TCP communication specified."), |
| 66 | error: QModbusDevice::ConnectionError); |
| 67 | qCWarning(QT_MODBUS) << "(TCP client) Invalid host:"<< url.host() << "or port:" |
| 68 | << url.port(); |
| 69 | return false; |
| 70 | } |
| 71 | |
| 72 | d->m_socket->connectToHost(hostName: url.host(), port: url.port()); |
| 73 | |
| 74 | return true; |
| 75 | } |
| 76 | |
| 77 | /*! |
| 78 | \reimp |
| 79 | */ |
| 80 | void QModbusTcpClient::close() |
| 81 | { |
| 82 | if (state() == QModbusDevice::UnconnectedState) |
| 83 | return; |
| 84 | |
| 85 | Q_D(QModbusTcpClient); |
| 86 | d->m_socket->disconnectFromHost(); |
| 87 | } |
| 88 | |
| 89 | QT_END_NAMESPACE |
| 90 |
