diff options
Diffstat (limited to 'examples/opcua/opcuaviewer/mainwindow.cpp')
-rw-r--r-- | examples/opcua/opcuaviewer/mainwindow.cpp | 228 |
1 files changed, 96 insertions, 132 deletions
diff --git a/examples/opcua/opcuaviewer/mainwindow.cpp b/examples/opcua/opcuaviewer/mainwindow.cpp index 589cd6d..810577d 100644 --- a/examples/opcua/opcuaviewer/mainwindow.cpp +++ b/examples/opcua/opcuaviewer/mainwindow.cpp @@ -51,21 +51,13 @@ #include "mainwindow.h" #include "opcuamodel.h" #include "certificatedialog.h" +#include "ui_mainwindow.h" -#include <QCoreApplication> +#include <QApplication> #include <QDir> -#include <QLineEdit> -#include <QComboBox> #include <QMessageBox> -#include <QHBoxLayout> -#include <QVBoxLayout> -#include <QPushButton> -#include <QLabel> #include <QTextCharFormat> -#include <QPlainTextEdit> #include <QTextBlock> -#include <QTreeView> -#include <QHeaderView> #include <QOpcUaProvider> #include <QOpcUaAuthenticationInformation> #include <QOpcUaErrorState> @@ -80,29 +72,34 @@ static void messageHandler(QtMsgType type, const QMessageLogContext &context, co if (!mainWindowGlobal) return; - QString message = "%1: %2"; - QString contextStr = " (%1:%2, %3)"; - QString typeString; - - if (type == QtDebugMsg) - typeString = QObject::tr("Debug"); - else if (type == QtInfoMsg) - typeString = QObject::tr("Info"); - else if (type == QtWarningMsg) - typeString = QObject::tr("Warning"); - else if (type == QtCriticalMsg) - typeString = QObject::tr("Critical"); - else if (type == QtFatalMsg) - typeString = QObject::tr("Fatal"); - - message = message.arg(typeString).arg(msg); - contextStr = contextStr.arg(context.file).arg(context.line).arg(context.function); - + QString message; QColor color = Qt::black; - if (type == QtFatalMsg || type == QtCriticalMsg) - color = Qt::darkRed; - else if (type == QtWarningMsg) + + switch (type) { + case QtWarningMsg: + message = QObject::tr("Warning"); color = Qt::darkYellow; + break; + case QtCriticalMsg: + message = QObject::tr("Critical"); + color = Qt::darkRed; + break; + case QtFatalMsg: + message = QObject::tr("Fatal"); + color = Qt::darkRed; + break; + case QtInfoMsg: + message = QObject::tr("Info"); + break; + case QtDebugMsg: + message = QObject::tr("Debug"); + break; + } + message += QLatin1String(": "); + message += msg; + + const QString contextStr = + QStringLiteral(" (%1:%2, %3)").arg(context.file).arg(context.line).arg(context.function); // Logging messages from backends are sent from different threads and need to be // synchronized with the GUI thread. @@ -116,70 +113,36 @@ static void messageHandler(QtMsgType type, const QMessageLogContext &context, co } MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent) - , mOpcUaPlugin(new QComboBox(this)) - , mHost(new QLineEdit(this)) - , mServers(new QComboBox(this)) - , mEndpoints(new QComboBox(this)) - , mFindServersButton(new QPushButton(tr("Find Servers"), this)) - , mGetEndpointsButton(new QPushButton(tr("Get Endpoints"), this)) - , mConnectButton(new QPushButton(tr("Connect"), this)) - , mLog(new QPlainTextEdit(this)) - , mTreeView(new QTreeView(this)) + , ui(new Ui::MainWindow) , mOpcUaModel(new OpcUaModel(this)) , mOpcUaProvider(new QOpcUaProvider(this)) - , mOpcUaClient(nullptr) - , mClientConnected(false) { - int row = 0; + ui->setupUi(this); mainWindowGlobal = this; - auto grid = new QGridLayout; - grid->addWidget(new QLabel(tr("Select OPC UA Backend:")), row, 0); - grid->addWidget(mOpcUaPlugin, row, 1); - grid->addWidget(new QLabel(tr("Select host to discover:")), ++row, 0); - grid->addWidget(mHost, row, 1); - grid->addWidget(mFindServersButton, row, 2); - grid->addWidget(new QLabel(tr("Select OPC UA Server:")), ++row, 0); - grid->addWidget(mServers, row, 1); - grid->addWidget(mGetEndpointsButton, row, 2); - grid->addWidget(new QLabel(tr("Select OPC UA Endpoint:")), ++row, 0); - grid->addWidget(mEndpoints, row, 1); - grid->addWidget(mConnectButton, row, 2); - - auto vbox = new QVBoxLayout; - vbox->addLayout(grid); - vbox->addWidget(mTreeView); - vbox->addWidget(new QLabel(tr("Log:"))); - vbox->addWidget(mLog); - - auto widget = new QWidget; - widget->setLayout(vbox); - setCentralWidget(widget); - - mHost->setText("opc.tcp://localhost:48010"); - mEndpoints->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Preferred); + connect(ui->quitAction, &QAction::triggered, this, &QWidget::close); + ui->quitAction->setShortcut(QKeySequence(Qt::CTRL + Qt::Key_Q)); + + connect(ui->aboutAction, &QAction::triggered, this, &QApplication::aboutQt); + ui->aboutAction->setShortcut(QKeySequence(QKeySequence::HelpContents)); updateUiState(); - mOpcUaPlugin->addItems(mOpcUaProvider->availableBackends()); - mLog->setReadOnly(true); - mLog->setLineWrapMode(QPlainTextEdit::NoWrap); - setMinimumWidth(800); - mTreeView->setModel(mOpcUaModel); - mTreeView->header()->setSectionResizeMode(QHeaderView::ResizeToContents); - mTreeView->setTextElideMode(Qt::ElideRight); - mTreeView->setAlternatingRowColors(true); - mTreeView->setSelectionBehavior(QAbstractItemView::SelectItems); - - if (mOpcUaPlugin->count() == 0) { - mOpcUaPlugin->setDisabled(true); - mConnectButton->setDisabled(true); + ui->opcUaPlugin->addItems(mOpcUaProvider->availableBackends()); + ui->treeView->setModel(mOpcUaModel); + ui->treeView->header()->setSectionResizeMode(QHeaderView::ResizeToContents); + + if (ui->opcUaPlugin->count() == 0) { + ui->opcUaPlugin->setDisabled(true); + ui->connectButton->setDisabled(true); QMessageBox::critical(this, tr("No OPCUA plugins available"), tr("The list of available OPCUA plugins is empty. No connection possible.")); } - connect(mFindServersButton, &QPushButton::clicked, this, &MainWindow::findServers); - connect(mGetEndpointsButton, &QPushButton::clicked, this, &MainWindow::getEndpoints); - connect(mConnectButton, &QPushButton::clicked, this, &MainWindow::connectToServer); + connect(ui->findServersButton, &QPushButton::clicked, this, &MainWindow::findServers); + connect(ui->host, &QLineEdit::returnPressed, this->ui->findServersButton, + [this]() { this->ui->findServersButton->animateClick(); }); + connect(ui->getEndpointsButton, &QPushButton::clicked, this, &MainWindow::getEndpoints); + connect(ui->connectButton, &QPushButton::clicked, this, &MainWindow::connectToServer); oldMessageHandler = qInstallMessageHandler(&messageHandler); setupPkiConfiguration(); @@ -189,6 +152,11 @@ MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent) //! [Application Identity] } +MainWindow::~MainWindow() +{ + delete ui; +} + //! [PKI Configuration] void MainWindow::setupPkiConfiguration() { @@ -212,7 +180,7 @@ void MainWindow::setupPkiConfiguration() void MainWindow::createClient() { if (mOpcUaClient == nullptr) { - mOpcUaClient = mOpcUaProvider->createClient(mOpcUaPlugin->currentText()); + mOpcUaClient = mOpcUaProvider->createClient(ui->opcUaPlugin->currentText()); if (!mOpcUaClient) { const QString message(tr("Connecting to the given sever failed. See the log for details.")); log(message, QString(), Qt::red); @@ -243,7 +211,7 @@ void MainWindow::findServers() { QStringList localeIds; QStringList serverUris; - QUrl url(mHost->text()); + QUrl url(ui->host->text()); updateUiState(); @@ -262,11 +230,11 @@ void MainWindow::findServersComplete(const QVector<QOpcUaApplicationDescription> QOpcUaApplicationDescription server; if (isSuccessStatus(statusCode)) { - mServers->clear(); + ui->servers->clear(); for (const auto &server : servers) { QVector<QString> urls = server.discoveryUrls(); for (const auto &url : qAsConst(urls)) - mServers->addItem(url); + ui->servers->addItem(url); } } @@ -275,11 +243,11 @@ void MainWindow::findServersComplete(const QVector<QOpcUaApplicationDescription> void MainWindow::getEndpoints() { - mEndpoints->clear(); + ui->endpoints->clear(); updateUiState(); - if (mServers->currentIndex() >= 0) { - const QString serverUrl = mServers->currentText(); + if (ui->servers->currentIndex() >= 0) { + const QString serverUrl = ui->servers->currentText(); createClient(); mOpcUaClient->requestEndpoints(serverUrl); } @@ -306,7 +274,7 @@ void MainWindow::getEndpointsComplete(const QVector<QOpcUaEndpointDescription> & const QString EndpointName = QString("%1 (%2)") .arg(endpoint.securityPolicy()) .arg(modes[endpoint.securityMode()]); - mEndpoints->addItem(EndpointName, index++); + ui->endpoints->addItem(EndpointName, index++); } } @@ -320,8 +288,8 @@ void MainWindow::connectToServer() return; } - if (mEndpoints->currentIndex() >= 0) { - m_endpoint = mEndpointList[mEndpoints->currentIndex()]; + if (ui->endpoints->currentIndex() >= 0) { + m_endpoint = mEndpointList[ui->endpoints->currentIndex()]; createClient(); mOpcUaClient->connectToEndpoint(m_endpoint); } @@ -354,7 +322,7 @@ void MainWindow::namespacesArrayUpdated(const QStringList &namespaceArray) disconnect(mOpcUaClient, &QOpcUaClient::namespaceArrayUpdated, this, &MainWindow::namespacesArrayUpdated); mOpcUaModel->setOpcUaClient(mOpcUaClient); - mTreeView->header()->setSectionResizeMode(1 /* Value column*/, QHeaderView::Interactive); + ui->treeView->header()->setSectionResizeMode(1 /* Value column*/, QHeaderView::Interactive); } void MainWindow::clientError(QOpcUaClient::ClientError error) @@ -370,46 +338,44 @@ void MainWindow::clientState(QOpcUaClient::ClientState state) void MainWindow::updateUiState() { // allow changing the backend only if it was not already created - mOpcUaPlugin->setEnabled(mOpcUaClient == nullptr); - mConnectButton->setText(mClientConnected?tr("Disconnect"):tr("Connect")); + ui->opcUaPlugin->setEnabled(mOpcUaClient == nullptr); + ui->connectButton->setText(mClientConnected ? tr("Disconnect") : tr("Connect")); if (mClientConnected) { - mHost->setEnabled(false); - mServers->setEnabled(false); - mEndpoints->setEnabled(false); - mFindServersButton->setEnabled(false); - mGetEndpointsButton->setEnabled(false); - mConnectButton->setEnabled(true); - mConnectButton->setText(tr("Disconnect")); + ui->host->setEnabled(false); + ui->servers->setEnabled(false); + ui->endpoints->setEnabled(false); + ui->findServersButton->setEnabled(false); + ui->getEndpointsButton->setEnabled(false); + ui->connectButton->setEnabled(true); } else { - mHost->setEnabled(true); - mServers->setEnabled(mServers->count() > 0); - mEndpoints->setEnabled(mEndpoints->count() > 0); - - mFindServersButton->setDisabled(mHost->text().isEmpty()); - mGetEndpointsButton->setEnabled(mServers->currentIndex() != -1); - mConnectButton->setEnabled(mEndpoints->currentIndex() != -1); - mConnectButton->setText(tr("Connect")); + ui->host->setEnabled(true); + ui->servers->setEnabled(ui->servers->count() > 0); + ui->endpoints->setEnabled(ui->endpoints->count() > 0); + + ui->findServersButton->setDisabled(ui->host->text().isEmpty()); + ui->getEndpointsButton->setEnabled(ui->servers->currentIndex() != -1); + ui->connectButton->setEnabled(ui->endpoints->currentIndex() != -1); } if (!mOpcUaClient) { - mServers->setEnabled(false); - mEndpoints->setEnabled(false); - mGetEndpointsButton->setEnabled(false); - mConnectButton->setEnabled(false); + ui->servers->setEnabled(false); + ui->endpoints->setEnabled(false); + ui->getEndpointsButton->setEnabled(false); + ui->connectButton->setEnabled(false); } } void MainWindow::log(const QString &text, const QString &context, QColor color) { - auto cf = mLog->currentCharFormat(); + auto cf = ui->log->currentCharFormat(); cf.setForeground(color); - mLog->setCurrentCharFormat(cf); - mLog->appendPlainText(text); + ui->log->setCurrentCharFormat(cf); + ui->log->appendPlainText(text); if (!context.isEmpty()) { cf.setForeground(Qt::gray); - mLog->setCurrentCharFormat(cf); - mLog->insertPlainText(context); + ui->log->setCurrentCharFormat(cf); + ui->log->insertPlainText(context); } } @@ -424,11 +390,10 @@ bool MainWindow::createPkiPath(const QString &path) QDir dir; const bool ret = dir.mkpath(path); - if (ret) { + if (ret) qDebug() << msg.arg(path).arg("SUCCESS."); - } else { - qCritical(msg.arg(path).arg("FAILED.").toLocal8Bit()); - } + else + qCritical("%s", qPrintable(msg.arg(path).arg("FAILED."))); return ret; } @@ -456,23 +421,22 @@ bool MainWindow::createPkiFolders() void MainWindow::showErrorDialog(QOpcUaErrorState *errorState) { - QString msg; - CertificateDialog dlg; int result = 0; const QString statuscode = QOpcUa::statusToString(errorState->errorCode()); - if (errorState->isClientSideError()) - msg = tr("The client reported: "); - else - msg = tr("The server reported: "); + QString msg = errorState->isClientSideError() ? tr("The client reported: ") : tr("The server reported: "); switch (errorState->connectionStep()) { - case QOpcUaErrorState::ConnectionStep::CertificateValidation: + case QOpcUaErrorState::ConnectionStep::Unknown: + break; + case QOpcUaErrorState::ConnectionStep::CertificateValidation: { + CertificateDialog dlg(this); msg += tr("Server certificate validation failed with error 0x%1 (%2).\nClick 'Abort' to abort the connect, or 'Ignore' to continue connecting.") .arg(static_cast<ulong>(errorState->errorCode()), 8, 16, QLatin1Char('0')).arg(statuscode); result = dlg.showCertificate(msg, m_endpoint.serverCertificate(), m_pkiConfig.trustListDirectory()); errorState->setIgnoreError(result == 1); + } break; case QOpcUaErrorState::ConnectionStep::OpenSecureChannel: msg += tr("OpenSecureChannel failed with error 0x%1 (%2).").arg(errorState->errorCode(), 8, 16, QLatin1Char('0')).arg(statuscode); |