diff --git a/src/backend/datasources/MQTTClient.cpp b/src/backend/datasources/MQTTClient.cpp index f7610efb7..589e44073 100644 --- a/src/backend/datasources/MQTTClient.cpp +++ b/src/backend/datasources/MQTTClient.cpp @@ -1,1356 +1,1354 @@ /*************************************************************************** File : MQTTClient.cpp Project : LabPlot Description : Represents a MQTT Client -------------------------------------------------------------------- Copyright : (C) 2018 Kovacs Ferencz (kferike98@gmail.com) ***************************************************************************/ /*************************************************************************** * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) any later version. * * * * This program is distributed in the hope that it will be useful, * * but WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * * GNU General Public License for more details. * * * * You should have received a copy of the GNU General Public License * * along with this program; if not, write to the Free Software * * Foundation, Inc., 51 Franklin Street, Fifth Floor, * * Boston, MA 02110-1301 USA * * * ***************************************************************************/ #include "backend/datasources/MQTTClient.h" #include "backend/datasources/MQTTSubscription.h" #include "backend/datasources/MQTTTopic.h" #include "backend/datasources/filters/AsciiFilter.h" #include "backend/datasources/filters/FITSFilter.h" #include "backend/datasources/filters/BinaryFilter.h" #include "backend/core/Project.h" #include "kdefrontend/spreadsheet/PlotDataDialog.h" #include "commonfrontend/spreadsheet/SpreadsheetView.h" #include "kdefrontend/datasources/MQTTErrorWidget.h" #include #include #include #include #include #include #include #include #include #include -#include - /*! \class MQTTClient \brief The MQTT Client connects to the broker set in ImportFileWidget. It manages the MQTTSubscriptions, and the MQTTTopics. \ingroup datasources */ MQTTClient::MQTTClient(const QString& name) : Folder(name, AspectType::MQTTClient), m_updateTimer(new QTimer(this)), m_client(new QMqttClient(this)), m_willTimer(new QTimer(this)) { connect(m_updateTimer, &QTimer::timeout, this, &MQTTClient::read); connect(m_client, &QMqttClient::connected, this, &MQTTClient::onMQTTConnect); connect(m_willTimer, &QTimer::timeout, this, &MQTTClient::updateWillMessage); connect(m_client, &QMqttClient::errorChanged, this, &MQTTClient::MQTTErrorChanged); } MQTTClient::~MQTTClient() { emit clientAboutToBeDeleted(m_client->hostname(), m_client->port()); //stop reading before deleting the objects pauseReading(); qDebug() << "Delete MQTTClient: " << m_client->hostname() << m_client->port(); delete m_filter; delete m_updateTimer; delete m_willTimer; m_client->disconnectFromHost(); delete m_client; } /*! * depending on the update type, periodically or on data changes, starts the timer. */ void MQTTClient::ready() { if (m_updateType == TimeInterval) m_updateTimer->start(m_updateInterval); } /*! * \brief Updates the MQTTTopics of the client */ void MQTTClient::updateNow() { m_updateTimer->stop(); read(); if ((m_updateType == TimeInterval) && !m_paused) m_updateTimer->start(m_updateInterval); } /*! * \brief Continue reading from messages after it was paused. */ void MQTTClient::continueReading() { m_paused = false; if (m_updateType == TimeInterval) m_updateTimer->start(m_updateInterval); } /*! * \brief Pause the reading from messages. */ void MQTTClient::pauseReading() { m_paused = true; if (m_updateType == TimeInterval) m_updateTimer->stop(); } /*! * \brief Sets the filter of the MQTTClient. * The ownership of the filter is passed to MQTTClient. * * \param f a pointer to the new filter */ void MQTTClient::setFilter(AsciiFilter* f) { delete m_filter; m_filter = f; } /*! * \brief Returns the filter of the MQTTClient. */ AsciiFilter* MQTTClient::filter() const { return m_filter; } /*! * \brief Sets the MQTTclient's update interval to \c interval * \param interval */ void MQTTClient::setUpdateInterval(int interval) { m_updateInterval = interval; if (!m_paused) m_updateTimer->start(m_updateInterval); } /*! * \brief Returns the MQTTClient's update interval to \c interval * \param interval */ int MQTTClient::updateInterval() const { return m_updateInterval; } /*! * \brief Sets how many values we should store * \param keepNValues */ void MQTTClient::setKeepNValues(int keepNValues) { m_keepNValues = keepNValues; } /*! * \brief Returns how many values we should store */ int MQTTClient::keepNValues() const { return m_keepNValues; } /*! * \brief Provides information about whether the reading is paused or not * * \return true if the reading is paused * \return false otherwise */ bool MQTTClient::isPaused() const { return m_paused; } /*! * \brief Sets the size rate to sampleSize * \param sampleSize */ void MQTTClient::setSampleSize(int sampleSize) { m_sampleSize = sampleSize; } /*! * \brief Returns the size rate */ int MQTTClient::sampleSize() const { return m_sampleSize; } /*! * \brief Sets the MQTTClient's reading type to readingType * \param readingType */ void MQTTClient::setReadingType(ReadingType readingType) { m_readingType = readingType; } /*! * \brief Returns the MQTTClient's reading type */ MQTTClient::ReadingType MQTTClient::readingType() const { return m_readingType; } /*! * \brief Sets the MQTTClient's update type to updatetype and handles this change * \param updatetype */ void MQTTClient::setUpdateType(UpdateType updateType) { if (updateType == NewData) m_updateTimer->stop(); m_updateType = updateType; } /*! * \brief Returns the MQTTClient's update type */ MQTTClient::UpdateType MQTTClient::updateType() const { return m_updateType; } /*! * \brief Returns the MQTTClient's icon */ QIcon MQTTClient::icon() const { return QIcon::fromTheme("network-server-database"); } /*! * \brief Sets the host and port for the client. * * \param host the hostname of the broker we want to connect to * \param port the port used by the broker */ void MQTTClient::setMQTTClientHostPort(const QString& host, const quint16& port) { m_client->setHostname(host); m_client->setPort(port); } /*! * \brief Returns hostname of the broker the client is connected to. */ QString MQTTClient::clientHostName() const { return m_client->hostname(); } /*! * \brief Returns the port used by the broker. */ quint16 MQTTClient::clientPort() const { return m_client->port(); } /*! * \brief Sets the flag on the given value. * If set true it means that the broker requires authentication, otherwise it doesn't. * * \param use */ void MQTTClient::setMQTTUseAuthentication(bool use) { m_MQTTUseAuthentication = use; } /*! * \brief Returns whether the broker requires authentication or not. */ bool MQTTClient::MQTTUseAuthentication() const { return m_MQTTUseAuthentication; } /*! * \brief Sets the username and password for the client. * * \param username the username used for authentication * \param password the password used for authentication */ void MQTTClient::setMQTTClientAuthentication(const QString& username, const QString& password) { m_client->setUsername(username); m_client->setPassword(password); } /*! * \brief Returns the username used for authentication. */ QString MQTTClient::clientUserName() const { return m_client->username(); } /*! * \brief Returns the password used for authentication. */ QString MQTTClient::clientPassword() const { return m_client->password(); } /*! * \brief Sets the flag on the given value. * If set true it means that user wants to set the client ID, otherwise it's not the case. * * \param use */ void MQTTClient::setMQTTUseID(bool use) { m_MQTTUseID = use; } /*! * \brief Returns whether the user wants to set the client ID or not. */ bool MQTTClient::MQTTUseID() const { return m_MQTTUseID; } /*! * \brief Sets the ID of the client * * \param id */ void MQTTClient::setMQTTClientId(const QString& clientId) { m_client->setClientId(clientId); } /*! * \brief Returns the ID of the client */ QString MQTTClient::clientID () const { return m_client->clientId(); } /*! * \brief Sets the flag on the given value. * If retain is true we interpret retain messages, otherwise we do not * * \param retain */ void MQTTClient::setMQTTRetain(bool retain) { m_MQTTRetain = retain; } /*! * \brief Returns the flag, which set to true means that interpret retain messages, otherwise we do not */ bool MQTTClient::MQTTRetain() const { return m_MQTTRetain; } /*! * \brief Returns the name of every MQTTTopics which already received a message, and is child of the MQTTClient */ QVector MQTTClient::topicNames() const { return m_topicNames; } /*! * \brief Adds the initial subscriptions that were set in ImportFileWidget * * \param filter the name of the subscribed topic * \param qos the qos level of the subscription */ void MQTTClient::addInitialMQTTSubscriptions(const QMqttTopicFilter& filter, const quint8& qos) { m_subscribedTopicNameQoS[filter] = qos; } /*! * \brief Returns the name of every MQTTSubscription of the MQTTClient */ QVector MQTTClient::MQTTSubscriptions() const { return m_subscriptions; } /*! * \brief Adds a new MQTTSubscription to the MQTTClient * * \param topic, the name of the topic * \param QoS */ void MQTTClient::addMQTTSubscription(const QString& topicName, quint8 QoS) { //Check whether the subscription already exists, if it doesn't, we can add it if (!m_subscriptions.contains(topicName)) { const QMqttTopicFilter filter {topicName}; QMqttSubscription* temp = m_client->subscribe(filter, QoS); if (temp) { qDebug()<<"Subscribe to: "<< temp->topic() << " " << temp->qos(); m_subscriptions.push_back(temp->topic().filter()); m_subscribedTopicNameQoS[temp->topic().filter()] = temp->qos(); MQTTSubscription* newSubscription = new MQTTSubscription(temp->topic().filter()); newSubscription->setMQTTClient(this); addChildFast(newSubscription); m_MQTTSubscriptions.push_back(newSubscription); //Search for inferior subscriptions, that the new subscription contains bool found = false; QVector inferiorSubscriptions; for (auto* subscription : m_MQTTSubscriptions) { if (checkTopicContains(topicName, subscription->subscriptionName()) && topicName != subscription->subscriptionName()) { found = true; inferiorSubscriptions.push_back(subscription); } } //If there are some inferior subscriptions, we have to deal with them if (found) { for (auto* inferiorSubscription : inferiorSubscriptions) { qDebug()<<"Reparent topics of inferior subscription: "<< inferiorSubscription->subscriptionName(); //We have to reparent every topic of the inferior subscription, so no data is lost QVector topics = inferiorSubscription->topics(); for (auto* topic : topics) { topic->reparent(newSubscription); } //Then remove the subscription and every connected information QMqttTopicFilter unsubscribeFilter {inferiorSubscription->subscriptionName()}; m_client->unsubscribe(unsubscribeFilter); for (int j = 0; j < m_MQTTSubscriptions.size(); ++j) { if (m_MQTTSubscriptions[j]->subscriptionName() == inferiorSubscription->subscriptionName()) { m_MQTTSubscriptions.remove(j); } } m_subscriptions.removeAll(inferiorSubscription->subscriptionName()); m_subscribedTopicNameQoS.remove(inferiorSubscription->subscriptionName()); removeChild(inferiorSubscription); } } connect(temp, &QMqttSubscription::messageReceived, this, &MQTTClient::MQTTSubscriptionMessageReceived); emit MQTTTopicsChanged(); } } } /*! * \brief Removes a MQTTSubscription from the MQTTClient * * \param name, the name of the subscription to remove */ void MQTTClient::removeMQTTSubscription(const QString& subscriptionName) { //We can only remove the subscription if it exists if (m_subscriptions.contains(subscriptionName)) { //unsubscribe from the topic const QMqttTopicFilter filter{subscriptionName}; m_client->unsubscribe(filter); qDebug()<<"Unsubscribe from: " << subscriptionName; //Remove every connected information m_subscriptions.removeAll(subscriptionName); for (int i = 0; i < m_MQTTSubscriptions.size(); ++i) { if (m_MQTTSubscriptions[i]->subscriptionName() == subscriptionName) { MQTTSubscription* removeSubscription = m_MQTTSubscriptions[i]; m_MQTTSubscriptions.remove(i); //Remove every topic of the subscription as well QVector topics = removeSubscription->topics(); for (int j = 0; j < topics.size(); ++j) { m_topicNames.removeAll(topics[j]->topicName()); } //Remove the MQTTSubscription removeChild(removeSubscription); break; } } QMapIterator j(m_subscribedTopicNameQoS); while (j.hasNext()) { j.next(); if (j.key().filter() == subscriptionName) { m_subscribedTopicNameQoS.remove(j.key()); break; } } emit MQTTTopicsChanged(); } } /*! * \brief Adds a MQTTSubscription to the MQTTClient *Used when the user unsubscribes from a topic of a MQTTSubscription * * \param topic, the name of the topic * \param QoS */ void MQTTClient::addBeforeRemoveSubscription(const QString& topicName, quint8 QoS) { //We can't add the subscription if it already exists if (!m_subscriptions.contains(topicName)) { //Subscribe to the topic QMqttTopicFilter filter {topicName}; QMqttSubscription* temp = m_client->subscribe(filter, QoS); if (temp) { //Add the MQTTSubscription and other connected data qDebug()<<"Add subscription before remove: " << temp->topic() << " " << temp->qos(); m_subscriptions.push_back(temp->topic().filter()); m_subscribedTopicNameQoS[temp->topic().filter()] = temp->qos(); MQTTSubscription* newSubscription = new MQTTSubscription(temp->topic().filter()); newSubscription->setMQTTClient(this); addChildFast(newSubscription); m_MQTTSubscriptions.push_back(newSubscription); //Search for the subscription the topic belonged to bool found = false; MQTTSubscription* superiorSubscription = nullptr; for (auto* subscription : m_MQTTSubscriptions) { if (checkTopicContains(subscription->subscriptionName(), topicName) && topicName != subscription->subscriptionName()) { found = true; superiorSubscription = subscription; break; } } if (found) { //Search for topics belonging to the superior(old) subscription //which are also contained by the new subscription QVector topics = superiorSubscription->topics(); qDebug()<< topics.size(); QVector inferiorTopics; for (auto* topic : topics) { if (checkTopicContains(topicName, topic->topicName())) { inferiorTopics.push_back(topic); } } //Reparent these topics, in order to avoid data loss for (auto* inferiorTopic : inferiorTopics) { inferiorTopic->reparent(newSubscription); } } connect(temp, &QMqttSubscription::messageReceived, this, &MQTTClient::MQTTSubscriptionMessageReceived); } } } /*! * \brief Reparents the given MQTTTopic to the given MQTTSubscription * * \param topic, the name of the MQTTTopic * \param parent, the name of the MQTTSubscription */ void MQTTClient::reparentTopic(const QString& topicName, const QString& parentTopicName) { //We can only reparent if the parent containd the topic if (m_subscriptions.contains(parentTopicName) && m_topicNames.contains(topicName)) { qDebug() << "Reparent " << topicName << " to " << parentTopicName; //search for the parent MQTTSubscription bool found = false; MQTTSubscription* superiorSubscription = nullptr; for (auto* subscription : m_MQTTSubscriptions) { if (subscription->subscriptionName() == parentTopicName) { found = true; superiorSubscription = subscription; break; } } if (found) { //get every topic of the MQTTClient QVector topics = children(AbstractAspect::Recursive); //Search for the given topic among the MQTTTopics for (auto* topic : topics) { if (topicName == topic->topicName()) { //if found, it is reparented to the parent MQTTSubscription topic->reparent(superiorSubscription); break; } } } } } /*! *\brief Checks if a topic contains another one * * \param superior the name of a topic * \param inferior the name of a topic * \return true if superior is equal to or contains(if superior contains wildcards) inferior, * false otherwise */ bool MQTTClient::checkTopicContains(const QString& superior, const QString& inferior) { if (superior == inferior) return true; else { if (superior.contains(QLatin1String("/"))) { QStringList superiorList = superior.split('/', QString::SkipEmptyParts); QStringList inferiorList = inferior.split('/', QString::SkipEmptyParts); //a longer topic can't contain a shorter one if (superiorList.size() > inferiorList.size()) return false; bool ok = true; for (int i = 0; i < superiorList.size(); ++i) { if (superiorList.at(i) != inferiorList.at(i)) { if ((superiorList.at(i) != '+') && !(superiorList.at(i) == '#' && i == superiorList.size() - 1)) { //if the two topics differ, and the superior's current level isn't + or #(which can be only in the last position) //then superior can't contain inferior ok = false; break; } else if (i == superiorList.size() - 1 && (superiorList.at(i) == '+' && inferiorList.at(i) == '#') ) { //if the two topics differ at the last level //and the superior's current level is + while the inferior's is #(which can be only in the last position) //then superior can't contain inferior ok = false; break; } } } return ok; } return false; } } /*! *\brief Returns the '+' wildcard containing topic name, which includes the given topic names * * \param first the name of a topic * \param second the name of a topic * \return The name of the common topic, if it exists, otherwise an empty string */ QString MQTTClient::checkCommonLevel(const QString& first, const QString& second) { QStringList firstList = first.split('/', QString::SkipEmptyParts); QStringList secondtList = second.split('/', QString::SkipEmptyParts); QString commonTopic; if (!firstList.isEmpty()) { //the two topics have to be the same size and can't be identic if ((firstList.size() == secondtList.size()) && (first != second)) { //the index where they differ int differIndex = -1; for (int i = 0; i < firstList.size(); ++i) { if (firstList.at(i) != secondtList.at(i)) { differIndex = i; break; } } //they can differ at only one level and that can't be the first bool differ = false; if (differIndex > 0) { for (int j = differIndex +1; j < firstList.size(); ++j) { if (firstList.at(j) != secondtList.at(j)) { differ = true; break; } } } else differ = true; if (!differ) { for (int i = 0; i < firstList.size(); ++i) { if (i != differIndex) { commonTopic.append(firstList.at(i)); } else { //we put '+' wildcard at the level where they differ commonTopic.append('+'); } if (i != firstList.size() - 1) commonTopic.append("/"); } } } } qDebug() << first << " " << second << " common topic: "<stop(); } /*! * \brief Returns whether the user wants to use will message or not */ bool MQTTClient::MQTTWillUse() const { return m_MQTTWill.enabled; } /*! * \brief Sets the will topic of the client * * \param topic */ void MQTTClient::setWillTopic(const QString& topic) { qDebug() << "Set will topic:" << topic; m_MQTTWill.willTopic = topic; } /*! * \brief Returns the will topic of the client */ QString MQTTClient::willTopic() const { return m_MQTTWill.willTopic; } /*! * \brief Sets the retain flag of the client's will message * * \param retain */ void MQTTClient::setWillRetain(bool retain) { m_MQTTWill.willRetain = retain; } /*! * \brief Returns the retain flag of the client's will message */ bool MQTTClient::willRetain() const { return m_MQTTWill.willRetain; } /*! * \brief Sets the QoS level of the client's will message * * \param QoS */ void MQTTClient::setWillQoS(quint8 QoS) { m_MQTTWill.willQoS = QoS; } /*! * \brief Returns the QoS level of the client's will message */ quint8 MQTTClient::willQoS() const { return m_MQTTWill.willQoS; } /*! * \brief Sets the will message type of the client * * \param messageType */ void MQTTClient::setWillMessageType(WillMessageType messageType) { m_MQTTWill.willMessageType = messageType; } /*! * \brief Returns the will message type of the client */ MQTTClient::WillMessageType MQTTClient::willMessageType() const { return m_MQTTWill.willMessageType; } /*! * \brief Sets the own will message of the user * * \param ownMessage */ void MQTTClient::setWillOwnMessage(const QString& ownMessage) { m_MQTTWill.willOwnMessage = ownMessage; } /*! * \brief Returns the own will message of the user */ QString MQTTClient::willOwnMessage() const { return m_MQTTWill.willOwnMessage; } /*! * \brief Updates the will message of the client */ void MQTTClient::updateWillMessage() { QVector topics = children(AbstractAspect::Recursive); const MQTTTopic* willTopic = nullptr; //Search for the will topic for (const auto* topic : topics) { if (topic->topicName() == m_MQTTWill.willTopic) { willTopic = topic; break; } } //if the will topic is found we can update the will message if (willTopic != nullptr) { //To update the will message we have to disconnect first, then after setting everything connect again if (m_MQTTWill.enabled && (m_client->state() == QMqttClient::ClientState::Connected) ) { //Disconnect only once (disconnecting may take a while) if (!m_disconnectForWill) { qDebug() << "Disconnecting from host in order to update will message"; m_client->disconnectFromHost(); m_disconnectForWill = true; } //Try to update again updateWillMessage(); } //If client is disconnected we can update the settings else if (m_MQTTWill.enabled && (m_client->state() == QMqttClient::ClientState::Disconnected) && m_disconnectForWill) { m_client->setWillQoS(m_MQTTWill.willQoS); qDebug()<<"Will QoS" << m_MQTTWill.willQoS; m_client->setWillRetain(m_MQTTWill.willRetain); qDebug()<<"Will retain" << m_MQTTWill.willRetain; m_client->setWillTopic(m_MQTTWill.willTopic); qDebug()<<"Will Topic" << m_MQTTWill.willTopic; //Set the will message according to m_willMessageType switch (m_MQTTWill.willMessageType) { case WillMessageType::OwnMessage: m_client->setWillMessage(m_MQTTWill.willOwnMessage.toUtf8()); qDebug()<<"Will own message" << m_MQTTWill.willOwnMessage; break; case WillMessageType::Statistics: { const auto asciiFilter = willTopic->filter(); //If the topic's asciiFilter was found, get the needed statistics if (asciiFilter != nullptr) { //Statistics is only possible if the data stored in the MQTTTopic is of type integer or numeric if ((asciiFilter->MQTTColumnMode() == AbstractColumn::ColumnMode::Integer) || (asciiFilter->MQTTColumnMode() == AbstractColumn::ColumnMode::Numeric)) { m_client->setWillMessage(asciiFilter->MQTTColumnStatistics(willTopic).toUtf8()); } //Otherwise set empty message else { m_client->setWillMessage(QByteArray()); } qDebug() << "Will statistics message: "<< QString(m_client->willMessage()); } break; } case WillMessageType::LastMessage: m_client->setWillMessage(m_MQTTWill.willLastMessage.toUtf8()); qDebug()<<"Will last message:\n" << m_MQTTWill.willLastMessage; break; default: break; } m_disconnectForWill = false; //Reconnect with the updated message m_client->connectToHost(); qDebug()<< "Reconnect to host after updating will message"; } } } /*! * \brief Returns the MQTTClient's will update type */ MQTTClient::WillUpdateType MQTTClient::willUpdateType() const { return m_MQTTWill.willUpdateType; } /*! * \brief Sets the MQTTClient's will update type * * \param willUpdateType */ void MQTTClient::setWillUpdateType(WillUpdateType willUpdateType) { m_MQTTWill.willUpdateType = willUpdateType; } /*! * \brief Returns the time interval of updating the MQTTClient's will message */ int MQTTClient::willTimeInterval() const { return m_MQTTWill.willTimeInterval; } /*! * \brief Sets the time interval of updating the MQTTClient's will message, if update type is TimePeriod * * \param interval */ void MQTTClient::setWillTimeInterval(int interval) { m_MQTTWill.willTimeInterval = interval; } /*! * \brief Clear the lastly received message by the will topic * Called when the will topic is changed */ void MQTTClient::clearLastMessage() { m_MQTTWill.willLastMessage.clear(); } /*! * \brief Sets true the corresponding flag of the statistic type, * what means that the given statistic type will be added to the will message * * \param statistics */ void MQTTClient::addWillStatistics(WillStatisticsType statistic) { m_MQTTWill.willStatistics[static_cast(statistic)] = true; } /*! * \brief Sets false the corresponding flag of the statistic type, * what means that the given statistic will no longer be added to the will message * * \param statistics */ void MQTTClient::removeWillStatistics(WillStatisticsType statistic) { m_MQTTWill.willStatistics[static_cast(statistic)] = false; } /*! * \brief Returns a bool vector, meaning which statistic types are included in the will message * If the corresponding value is true, the statistic type is included, otherwise it isn't */ QVector MQTTClient::willStatistics() const { return m_MQTTWill.willStatistics; } /*! * \brief Starts the will timer, which will update the will message */ void MQTTClient::startWillTimer() const { if (m_MQTTWill.willUpdateType == WillUpdateType::TimePeriod) m_willTimer->start(m_MQTTWill.willTimeInterval); } /*! * \brief Stops the will timer */ void MQTTClient::stopWillTimer() const { m_willTimer->stop(); } //############################################################################## //################################# SLOTS #################################### //############################################################################## /*! *\brief called periodically when update type is TimeInterval */ void MQTTClient::read() { if (!m_filter) return; if (!m_prepared) { qDebug()<<"Connect"; //connect to the broker m_client->connectToHost(); m_prepared = true; } if ((m_client->state() == QMqttClient::ClientState::Connected) && m_MQTTFirstConnectEstablished) { // qDebug()<<"Read"; //Signal for every MQTTTopic that they can read emit readFromTopics(); } } /*! *\brief called when the client successfully connected to the broker */ void MQTTClient::onMQTTConnect() { if (m_client->error() == QMqttClient::NoError) { //if this is the first connection (after setting the options in ImportFileWidget or loading saved project) if (!m_MQTTFirstConnectEstablished) { qDebug()<<"connection made in MQTTClient"; //Subscribe to initial or loaded topics QMapIterator i(m_subscribedTopicNameQoS); while (i.hasNext()) { i.next(); qDebug()<subscribe(i.key(), i.value()); if (temp) { //If we didn't load the MQTTClient from xml we have to add the MQTTSubscriptions if (!m_loaded) { m_subscriptions.push_back(temp->topic().filter()); MQTTSubscription* newSubscription = new MQTTSubscription(temp->topic().filter()); newSubscription->setMQTTClient(this); addChildFast(newSubscription); m_MQTTSubscriptions.push_back(newSubscription); } connect(temp, &QMqttSubscription::messageReceived, this, &MQTTClient::MQTTSubscriptionMessageReceived); } } m_MQTTFirstConnectEstablished = true; //Signal that the initial subscriptions were made emit MQTTSubscribed(); } //if there was already a connection made(happens after updating will message) else { qDebug() << "Start resubscribing after will message update"; //Only the client has to make the subscriptions again, every other connected data is still available QMapIterator i(m_subscribedTopicNameQoS); while (i.hasNext()) { i.next(); QMqttSubscription* temp = m_client->subscribe(i.key(), i.value()); if (temp) { qDebug()<topic()<<" "<qos(); connect(temp, &QMqttSubscription::messageReceived, this, &MQTTClient::MQTTSubscriptionMessageReceived); } else qDebug()<<"Couldn't subscribe after will update"; } } } } /*! *\brief called when a message is received by a topic belonging to one of subscriptions of the client. * It passes the message to the appropriate MQTTSubscription which will pass it to the appropriate MQTTTopic */ void MQTTClient::MQTTSubscriptionMessageReceived(const QMqttMessage& msg) { //Decide to interpret retain message or not if (!msg.retain() || m_MQTTRetain) { //If this is the first message from the topic, save its name if (!m_topicNames.contains(msg.topic().name())) m_topicNames.push_back(msg.topic().name()); //Pass the message and the topic name to the MQTTSubscription which contains the topic for (auto* subscription : m_MQTTSubscriptions) { if (checkTopicContains(subscription->subscriptionName(), msg.topic().name())) { subscription->messageArrived(msg.payload(), msg.topic().name()); break; } } //if the message was received by the will topic, update the last message received by it if (msg.topic().name() == m_MQTTWill.willTopic) { m_MQTTWill.willLastMessage = QString(msg.payload()); emit MQTTTopicsChanged(); } } } /*! *\brief Handles some of the possible errors of the client, using MQTTErrorWidget */ void MQTTClient::MQTTErrorChanged(QMqttClient::ClientError clientError) { if (clientError != QMqttClient::ClientError::NoError) { MQTTErrorWidget* errorWidget = new MQTTErrorWidget(clientError, this); errorWidget->show(); } } /*! *\brief Called when a subscription is loaded. * Checks whether every saved subscription was loaded or not. * If everything is loaded, it makes the connection and starts the reading * * \param name, the name of the subscription */ void MQTTClient::subscriptionLoaded(const QString &name) { if (!name.isEmpty()) { qDebug() << "Finished loading: " << name; //Save information about the subscription m_subscriptionsLoaded++; m_subscriptions.push_back(name); QMqttTopicFilter filter {name}; m_subscribedTopicNameQoS[filter] = 0; //Save the topics belonging to the subscription for (const auto* subscription : m_MQTTSubscriptions) { if (subscription->subscriptionName() == name) { const auto& topics = subscription->topics(); for (auto* topic : topics) { m_topicNames.push_back(topic->topicName()); } break; } } //Check whether every subscription was loaded or not if (m_subscriptionsLoaded == m_subscriptionCountToLoad) { //if everything was loaded we can start reading m_loaded = true; read(); } } } //############################################################################## //################## Serialization/Deserialization ########################### //############################################################################## /*! Saves as XML. */ void MQTTClient::save(QXmlStreamWriter* writer) const { writer->writeStartElement("MQTTClient"); writeBasicAttributes(writer); writeCommentElement(writer); //general writer->writeStartElement("general"); writer->writeAttribute("subscriptionCount", QString::number(m_MQTTSubscriptions.size())); writer->writeAttribute("updateType", QString::number(m_updateType)); writer->writeAttribute("readingType", QString::number(m_readingType)); writer->writeAttribute("keepValues", QString::number(m_keepNValues)); if (m_updateType == TimeInterval) writer->writeAttribute("updateInterval", QString::number(m_updateInterval)); if (m_readingType != TillEnd) writer->writeAttribute("sampleSize", QString::number(m_sampleSize)); writer->writeAttribute("host", m_client->hostname()); writer->writeAttribute("port", QString::number(m_client->port())); writer->writeAttribute("username", m_client->username()); writer->writeAttribute("password", m_client->password()); writer->writeAttribute("clientId", m_client->clientId()); writer->writeAttribute("useRetain", QString::number(m_MQTTRetain)); writer->writeAttribute("useWill", QString::number(m_MQTTWill.enabled)); writer->writeAttribute("willTopic", m_MQTTWill.willTopic); writer->writeAttribute("willOwnMessage", m_MQTTWill.willOwnMessage); writer->writeAttribute("willQoS", QString::number(m_MQTTWill.willQoS)); writer->writeAttribute("willRetain", QString::number(m_MQTTWill.willRetain)); writer->writeAttribute("willMessageType", QString::number(static_cast(m_MQTTWill.willMessageType))); writer->writeAttribute("willUpdateType", QString::number(static_cast(m_MQTTWill.willUpdateType))); writer->writeAttribute("willTimeInterval", QString::number(m_MQTTWill.willTimeInterval)); for (int i = 0; i < m_MQTTWill.willStatistics.count(); ++i) writer->writeAttribute("willStatistics"+QString::number(i), QString::number(m_MQTTWill.willStatistics[i])); writer->writeAttribute("useID", QString::number(m_MQTTUseID)); writer->writeAttribute("useAuthentication", QString::number(m_MQTTUseAuthentication)); writer->writeEndElement(); //filter m_filter->save(writer); //MQTTSubscription for (auto* sub : children(IncludeHidden)) sub->save(writer); writer->writeEndElement(); // "MQTTClient" } /*! Loads from XML. */ bool MQTTClient::load(XmlStreamReader* reader, bool preview) { if (!readBasicAttributes(reader)) return false; QString attributeWarning = i18n("Attribute '%1' missing or empty, default value is used"); QXmlStreamAttributes attribs; QString str; while (!reader->atEnd()) { reader->readNext(); if (reader->isEndElement() && reader->name() == "MQTTClient") break; if (!reader->isStartElement()) continue; if (reader->name() == "comment") { if (!readCommentElement(reader)) return false; } else if (reader->name() == "general") { attribs = reader->attributes(); str = attribs.value("subscriptionCount").toString(); if (str.isEmpty()) reader->raiseWarning(attributeWarning.arg("'subscriptionCount'")); else m_subscriptionCountToLoad = str.toInt(); str = attribs.value("keepValues").toString(); if (str.isEmpty()) reader->raiseWarning(attributeWarning.arg("'keepValues'")); else m_keepNValues = str.toInt(); str = attribs.value("updateType").toString(); if (str.isEmpty()) reader->raiseWarning(attributeWarning.arg("'updateType'")); else m_updateType = static_cast(str.toInt()); str = attribs.value("readingType").toString(); if (str.isEmpty()) reader->raiseWarning(attributeWarning.arg("'readingType'")); else m_readingType = static_cast(str.toInt()); if (m_updateType == TimeInterval) { str = attribs.value("updateInterval").toString(); if (str.isEmpty()) reader->raiseWarning(attributeWarning.arg("'updateInterval'")); else m_updateInterval = str.toInt(); } if (m_readingType != TillEnd) { str = attribs.value("sampleSize").toString(); if (str.isEmpty()) reader->raiseWarning(attributeWarning.arg("'sampleSize'")); else m_sampleSize = str.toInt(); } str = attribs.value("host").toString(); if (str.isEmpty()) reader->raiseWarning(attributeWarning.arg("'host'")); else m_client->setHostname(str); str = attribs.value("port").toString(); if (str.isEmpty()) reader->raiseWarning(attributeWarning.arg("'port'")); else m_client->setPort(str.toUInt()); str = attribs.value("useAuthentication").toString(); if (str.isEmpty()) reader->raiseWarning(attributeWarning.arg("'useAuthentication'")); else m_MQTTUseAuthentication = str.toInt(); if (m_MQTTUseAuthentication) { str = attribs.value("username").toString(); if (!str.isEmpty()) m_client->setUsername(str); str = attribs.value("password").toString(); if (!str.isEmpty()) m_client->setPassword(str); } str = attribs.value("useID").toString(); if (str.isEmpty()) reader->raiseWarning(attributeWarning.arg("'useID'")); else m_MQTTUseID = str.toInt(); if (m_MQTTUseID) { str = attribs.value("clientId").toString(); if (!str.isEmpty()) m_client->setClientId(str); } str = attribs.value("useRetain").toString(); if (str.isEmpty()) reader->raiseWarning(attributeWarning.arg("'useRetain'")); else m_MQTTRetain = str.toInt(); str = attribs.value("useWill").toString(); if (str.isEmpty()) reader->raiseWarning(attributeWarning.arg("'useWill'")); else m_MQTTWill.enabled = str.toInt(); if (m_MQTTWill.enabled) { str = attribs.value("willTopic").toString(); if (str.isEmpty()) reader->raiseWarning(attributeWarning.arg("'willTopic'")); else m_MQTTWill.willTopic = str; str = attribs.value("willOwnMessage").toString(); if (str.isEmpty()) reader->raiseWarning(attributeWarning.arg("'willOwnMessage'")); else m_MQTTWill.willOwnMessage = str; str = attribs.value("willQoS").toString(); if (str.isEmpty()) reader->raiseWarning(attributeWarning.arg("'willQoS'")); else m_MQTTWill.willQoS = str.toUInt(); str = attribs.value("willRetain").toString(); if (str.isEmpty()) reader->raiseWarning(attributeWarning.arg("'willRetain'")); else m_MQTTWill.willRetain = str.toInt(); str = attribs.value("willMessageType").toString(); if (str.isEmpty()) reader->raiseWarning(attributeWarning.arg("'willMessageType'")); else m_MQTTWill.willMessageType = static_cast(str.toInt()); str = attribs.value("willUpdateType").toString(); if (str.isEmpty()) reader->raiseWarning(attributeWarning.arg("'willUpdateType'")); else m_MQTTWill.willUpdateType = static_cast(str.toInt()); str = attribs.value("willTimeInterval").toString(); if (str.isEmpty()) reader->raiseWarning(attributeWarning.arg("'willTimeInterval'")); else m_MQTTWill.willTimeInterval = str.toInt(); for (int i = 0; i < m_MQTTWill.willStatistics.count(); ++i) { str = attribs.value("willStatistics"+QString::number(i)).toString(); if (str.isEmpty()) reader->raiseWarning(attributeWarning.arg("'willTimeInterval'")); else m_MQTTWill.willStatistics[i] = str.toInt(); } } } else if (reader->name() == "asciiFilter") { setFilter(new AsciiFilter); if (!m_filter->load(reader)) return false; } else if (reader->name() == "MQTTSubscription") { MQTTSubscription* subscription = new MQTTSubscription(QString()); subscription->setMQTTClient(this); m_MQTTSubscriptions.push_back(subscription); connect(subscription, &MQTTSubscription::loaded, this, &MQTTClient::subscriptionLoaded); if (!subscription->load(reader, preview)) { delete subscription; return false; } addChildFast(subscription); } else {// unknown element reader->raiseWarning(i18n("unknown element '%1'", reader->name().toString())); if (!reader->skipToEndElement()) return false; } } return !reader->hasError(); } diff --git a/src/backend/datasources/MQTTClient.h b/src/backend/datasources/MQTTClient.h index 891d87d97..afb0ee8b2 100644 --- a/src/backend/datasources/MQTTClient.h +++ b/src/backend/datasources/MQTTClient.h @@ -1,257 +1,255 @@ /*************************************************************************** File : MQTTClient.h Project : LabPlot Description : Represents a MQTT Client -------------------------------------------------------------------- Copyright : (C) 2018 Kovacs Ferencz (kferike98@gmail.com) ***************************************************************************/ /*************************************************************************** * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) any later version. * * * * This program is distributed in the hope that it will be useful, * * but WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * * GNU General Public License for more details. * * * * You should have received a copy of the GNU General Public License * * along with this program; if not, write to the Free Software * * Foundation, Inc., 51 Franklin Street, Fifth Floor, * * Boston, MA 02110-1301 USA * * * ***************************************************************************/ #ifndef MQTTCLIENT_H #define MQTTCLIENT_H #include "backend/core/Folder.h" -#include #include #include #include #include #include #include #include -class QString; class AsciiFilter; class MQTTSubscription; class QAction; -#endif +class QTimer; +class QString; class MQTTClient : public Folder { -#ifdef HAVE_MQTT Q_OBJECT public: enum UpdateType { TimeInterval = 0, NewData }; enum ReadingType { ContinuousFixed = 0, FromEnd, TillEnd }; enum WillMessageType { OwnMessage = 0, Statistics, LastMessage }; enum WillUpdateType { TimePeriod = 0, OnClick }; enum WillStatisticsType { NoStatistics = -1, Minimum, Maximum, ArithmeticMean, GeometricMean, HarmonicMean, ContraharmonicMean, Median, Variance, StandardDeviation, MeanDeviation, MeanDeviationAroundMedian, MedianDeviation, Skewness, Kurtosis, Entropy }; struct MQTTWill { bool enabled{false}; QString willMessage; QString willTopic; bool willRetain{false}; quint8 willQoS{0}; WillMessageType willMessageType{MQTTClient::WillMessageType::OwnMessage}; QString willOwnMessage; QString willLastMessage; int willTimeInterval{1000}; WillUpdateType willUpdateType{MQTTClient::WillUpdateType::TimePeriod}; QVector willStatistics{0,0,0,0,0,0,0,0,0,0,0,0,0,0,0}; }; explicit MQTTClient(const QString& name); virtual ~MQTTClient() override; void ready(); UpdateType updateType() const; void setUpdateType(UpdateType); ReadingType readingType() const; void setReadingType(ReadingType); int sampleSize() const; void setSampleSize(int); bool isPaused() const; void setUpdateInterval(int); int updateInterval() const; void setKeepNValues(int); int keepNValues() const; void setKeepLastValues(bool); bool keepLastValues() const; void setMQTTClientHostPort(const QString&, const quint16&); void setMQTTClientAuthentication(const QString&, const QString&); void setMQTTClientId(const QString&); void addInitialMQTTSubscriptions(const QMqttTopicFilter&, const quint8&); QVector MQTTSubscriptions() const; bool checkTopicContains(const QString& superior, const QString& inferior); QString checkCommonLevel(const QString& first, const QString& second); QString clientHostName() const; quint16 clientPort() const; QString clientPassword() const; QString clientUserName() const; QString clientID () const; void updateNow(); void pauseReading(); void continueReading(); void setFilter(AsciiFilter*); AsciiFilter* filter() const; QIcon icon() const override; void save(QXmlStreamWriter*) const override; bool load(XmlStreamReader*, bool preview) override; QVector topicNames() const; bool checkAllArrived(); void setWillSettings(MQTTWill); MQTTWill willSettings() const; void setMQTTWillUse(bool); bool MQTTWillUse() const; void setWillTopic(const QString&); QString willTopic() const; void setWillRetain(bool); bool willRetain() const; void setWillQoS(quint8); quint8 willQoS() const; void setWillMessageType(WillMessageType); WillMessageType willMessageType() const; void setWillOwnMessage(const QString&); QString willOwnMessage() const; WillUpdateType willUpdateType() const; void setWillUpdateType(WillUpdateType); int willTimeInterval() const; void setWillTimeInterval(int); void startWillTimer() const; void stopWillTimer() const; void updateWillMessage() ; void setMQTTRetain(bool); bool MQTTRetain() const; void setMQTTUseID(bool); bool MQTTUseID() const; void setMQTTUseAuthentication(bool); bool MQTTUseAuthentication() const; void clearLastMessage(); void addWillStatistics(WillStatisticsType); void removeWillStatistics(WillStatisticsType); QVector willStatistics() const; void addMQTTSubscription(const QString&, quint8); void removeMQTTSubscription(const QString&); void addBeforeRemoveSubscription(const QString&, quint8); void reparentTopic(const QString& topic, const QString& parent); private: UpdateType m_updateType{TimeInterval}; ReadingType m_readingType{ContinuousFixed}; bool m_paused{false}; bool m_prepared{false}; int m_sampleSize{1}; int m_keepNValues{0}; int m_updateInterval{1000}; AsciiFilter* m_filter{nullptr}; QTimer* m_updateTimer; QMqttClient* m_client; QMap m_subscribedTopicNameQoS; QVector m_subscriptions; QVector m_topicNames; bool m_MQTTTest{false}; QTimer* m_willTimer; bool m_MQTTFirstConnectEstablished{false}; bool m_MQTTRetain{false}; bool m_MQTTUseID{false}; bool m_MQTTUseAuthentication{false}; QVector m_MQTTSubscriptions; bool m_disconnectForWill{false}; bool m_loaded{false}; int m_subscriptionsLoaded{0}; int m_subscriptionCountToLoad{0}; MQTTWill m_MQTTWill; public slots: void read(); private slots: void onMQTTConnect(); void MQTTSubscriptionMessageReceived(const QMqttMessage&); void MQTTErrorChanged(QMqttClient::ClientError); void subscriptionLoaded(const QString&); signals: void MQTTSubscribed(); void MQTTTopicsChanged(); void readFromTopics(); void clientAboutToBeDeleted(const QString&, quint16); }; #endif // MQTTCLIENT_H diff --git a/src/backend/datasources/MQTTSubscription.cpp b/src/backend/datasources/MQTTSubscription.cpp index 22eea4e8a..7dd229f2c 100644 --- a/src/backend/datasources/MQTTSubscription.cpp +++ b/src/backend/datasources/MQTTSubscription.cpp @@ -1,196 +1,195 @@ /*************************************************************************** File : MQTTSubscription.cpp Project : LabPlot Description : Represents a subscription made in MQTTClient -------------------------------------------------------------------- Copyright : (C) 2018 Kovacs Ferencz (kferike98@gmail.com) ***************************************************************************/ /*************************************************************************** * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) any later version. * * * * This program is distributed in the hope that it will be useful, * * but WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * * GNU General Public License for more details. * * * * You should have received a copy of the GNU General Public License * * along with this program; if not, write to the Free Software * * Foundation, Inc., 51 Franklin Street, Fifth Floor, * * Boston, MA 02110-1301 USA * * * ***************************************************************************/ #include "backend/datasources/MQTTSubscription.h" - #include "backend/datasources/MQTTTopic.h" #include "backend/datasources/MQTTClient.h" #include #include /*! \class MQTTSubscription \brief Represents a subscription made in a MQTTClient object. It plays a role in managing MQTTTopic objects and makes possible representing the subscriptions and topics in a tree like structure \ingroup datasources */ MQTTSubscription::MQTTSubscription(const QString& name) : Folder(name, AspectType::MQTTSubscription), m_subscriptionName(name) { qDebug() << "New MQTTSubscription: " << name; } MQTTSubscription::~MQTTSubscription() { qDebug() << "Delete MQTTSubscription: " << m_subscriptionName; } /*! *\brief Returns the object's MQTTTopic children * * \return a vector of pointers to the children of the MQTTSubscription */ const QVector MQTTSubscription::topics() const { return children(); } /*! *\brief Returns the object's parent * * \return a pointer to the parent MQTTTopic of the object */ MQTTClient* MQTTSubscription::mqttClient() const { return m_MQTTClient; } /*! *\brief Called when a message arrived to a topic contained by the MQTTSubscription * If the topic can't be found among the children, a new MQTTTopic is instantiated * Passes the messages to the appropriate MQTTTopic * * \param message the message to pass * \param topicName the name of the topic the message was sent to */ void MQTTSubscription::messageArrived(const QString& message, const QString& topicName) { bool found = false; QVector topics = children(); //search for the topic among the MQTTTopic children for (auto* topic: topics) { if (topicName == topic->topicName()) { //pass the message to the topic topic->newMessage(message); //read the message if needed if ((m_MQTTClient->updateType() == MQTTClient::UpdateType::NewData) && !m_MQTTClient->isPaused()) topic->read(); found = true; break; } } //if the topic can't be found, we add it as a new MQTTTopic, and read from it if needed if (!found) { MQTTTopic* newTopic = new MQTTTopic(topicName, this, false); addChildFast(newTopic); //no need for undo/redo here newTopic->newMessage(message); if ((m_MQTTClient->updateType() == MQTTClient::UpdateType::NewData) && !m_MQTTClient->isPaused()) newTopic->read(); } } /*! *\brief Returns the subscription's name * * \return m_subscriptionName */ QString MQTTSubscription::subscriptionName() const { return m_subscriptionName; } /*! *\brief Sets the MQTTClient the subscription belongs to * * \param client */ void MQTTSubscription::setMQTTClient(MQTTClient* client) { m_MQTTClient = client; } /*! *\brief Returns the icon of MQTTSubscription */ QIcon MQTTSubscription::icon() const { return QIcon::fromTheme("mail-signed-full"); } //############################################################################## //################## Serialization/Deserialization ########################### //############################################################################## /*! Saves as XML. */ void MQTTSubscription::save(QXmlStreamWriter* writer) const { writer->writeStartElement("MQTTSubscription"); writeBasicAttributes(writer); writeCommentElement(writer); //general writer->writeStartElement("general"); writer->writeAttribute("subscriptionName", m_subscriptionName); writer->writeEndElement(); //MQTTTopics for (auto* topic : children(IncludeHidden)) topic->save(writer); writer->writeEndElement(); // "MQTTSubscription" } /*! Loads from XML. */ bool MQTTSubscription::load(XmlStreamReader* reader, bool preview) { if (!readBasicAttributes(reader)) return false; QString attributeWarning = i18n("Attribute '%1' missing or empty, default value is used"); QXmlStreamAttributes attribs; QString str; while (!reader->atEnd()) { reader->readNext(); if (reader->isEndElement() && reader->name() == "MQTTSubscription") break; if (!reader->isStartElement()) continue; if (reader->name() == "comment") { if (!readCommentElement(reader)) return false; } else if (reader->name() == "general") { attribs = reader->attributes(); m_subscriptionName = attribs.value("subscriptionName").toString(); } else if(reader->name() == QLatin1String("MQTTTopic")) { MQTTTopic* topic = new MQTTTopic(QString(), this, false); if (!topic->load(reader, preview)) { delete topic; return false; } addChildFast(topic); } else {// unknown element reader->raiseWarning(i18n("unknown element '%1'", reader->name().toString())); if (!reader->skipToEndElement()) return false; } } emit loaded(this->subscriptionName()); return !reader->hasError(); } diff --git a/src/backend/datasources/MQTTSubscription.h b/src/backend/datasources/MQTTSubscription.h index 61f4d5bde..6870c8095 100644 --- a/src/backend/datasources/MQTTSubscription.h +++ b/src/backend/datasources/MQTTSubscription.h @@ -1,63 +1,63 @@ /*************************************************************************** File : MQTTSubscription.h Project : LabPlot Description : Represents a subscription made in MQTTClient -------------------------------------------------------------------- Copyright : (C) 2018 Kovacs Ferencz (kferike98@gmail.com) ***************************************************************************/ /*************************************************************************** * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) any later version. * * * * This program is distributed in the hope that it will be useful, * * but WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * * GNU General Public License for more details. * * * * You should have received a copy of the GNU General Public License * * along with this program; if not, write to the Free Software * * Foundation, Inc., 51 Franklin Street, Fifth Floor, * * Boston, MA 02110-1301 USA * * * ***************************************************************************/ #ifndef MQTTSUBSCRIPTION_H #define MQTTSUBSCRIPTION_H #include "backend/core/Folder.h" -#include "backend/datasources/MQTTTopic.h" +class MQTTClient; +class MQTTTopic; class QString; - class MQTTSubscription : public Folder { Q_OBJECT public: explicit MQTTSubscription(const QString& name); ~MQTTSubscription() override; - void setMQTTClient(MQTTClient *client); + void setMQTTClient(MQTTClient*); QString subscriptionName() const; const QVector topics() const; MQTTClient* mqttClient() const; void messageArrived(const QString&, const QString&); QIcon icon() const override; void save(QXmlStreamWriter*) const override; bool load(XmlStreamReader*, bool preview) override; private: QString m_subscriptionName; MQTTClient* m_MQTTClient{nullptr}; signals: void loaded(const QString &); }; #endif // MQTTSUBSCRIPTION_H diff --git a/src/backend/datasources/MQTTTopic.cpp b/src/backend/datasources/MQTTTopic.cpp index 5f1accd31..9a72a3ab9 100644 --- a/src/backend/datasources/MQTTTopic.cpp +++ b/src/backend/datasources/MQTTTopic.cpp @@ -1,312 +1,310 @@ /*************************************************************************** File : MQTTTopic.cpp Project : LabPlot Description : Represents a topic of a MQTTSubscription -------------------------------------------------------------------- Copyright : (C) 2018 Kovacs Ferencz (kferike98@gmail.com) ***************************************************************************/ /*************************************************************************** * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) any later version. * * * * This program is distributed in the hope that it will be useful, * * but WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * * GNU General Public License for more details. * * * * You should have received a copy of the GNU General Public License * * along with this program; if not, write to the Free Software * * Foundation, Inc., 51 Franklin Street, Fifth Floor, * * Boston, MA 02110-1301 USA * * * ***************************************************************************/ #include "backend/datasources/MQTTTopic.h" #include "backend/datasources/MQTTSubscription.h" #include "backend/datasources/MQTTClient.h" #include "kdefrontend/spreadsheet/PlotDataDialog.h" #include "commonfrontend/spreadsheet/SpreadsheetView.h" #include "backend/datasources/filters/AsciiFilter.h" #include -#include #include #include #include -#include /*! \class MQTTTopic \brief Represents a topic of a subscription made in MQTTClient. \ingroup datasources */ MQTTTopic::MQTTTopic(const QString& name, MQTTSubscription* subscription, bool loading) : Spreadsheet(name, loading, AspectType::MQTTTopic), m_topicName(name), m_MQTTClient(subscription->mqttClient()), m_filter(new AsciiFilter) { auto mainFilter = m_MQTTClient->filter(); m_filter->setAutoModeEnabled(mainFilter->isAutoModeEnabled()); if (!mainFilter->isAutoModeEnabled()) { m_filter->setCommentCharacter(mainFilter->commentCharacter()); m_filter->setSeparatingCharacter(mainFilter->separatingCharacter()); m_filter->setDateTimeFormat(mainFilter->dateTimeFormat()); m_filter->setCreateIndexEnabled(mainFilter->createIndexEnabled()); m_filter->setSimplifyWhitespacesEnabled(mainFilter->simplifyWhitespacesEnabled()); m_filter->setNaNValueToZero(mainFilter->NaNValueToZeroEnabled()); m_filter->setRemoveQuotesEnabled(mainFilter->removeQuotesEnabled()); m_filter->setSkipEmptyParts(mainFilter->skipEmptyParts()); m_filter->setHeaderEnabled(mainFilter->isHeaderEnabled()); QString vectorNames; const QStringList& filterVectorNames = mainFilter->vectorNames(); for (int i = 0; i < filterVectorNames.size(); ++i) { vectorNames.append(filterVectorNames.at(i)); if (i != vectorNames.size() - 1) vectorNames.append(QLatin1String(" ")); } m_filter->setVectorNames(vectorNames); m_filter->setStartRow(mainFilter->startRow()); m_filter->setEndRow(mainFilter->endRow()); m_filter->setStartColumn(mainFilter->startColumn()); m_filter->setEndColumn(mainFilter->endColumn()); } connect(m_MQTTClient, &MQTTClient::readFromTopics, this, &MQTTTopic::read); qDebug()<<"New MqttTopic: " << m_topicName; initActions(); } MQTTTopic::~MQTTTopic() { qDebug()<<"MqttTopic destructor:"<actions().size() > 1) firstAction = menu->actions().at(1); menu->insertAction(firstAction, m_plotDataAction); menu->insertSeparator(firstAction); return menu; } QWidget* MQTTTopic::view() const { if (!m_partView) m_partView = new SpreadsheetView(const_cast(this), true); return m_partView; } /*! *\brief Adds a message received by the topic to the message puffer */ void MQTTTopic::newMessage(const QString& message) { m_messagePuffer.push_back(message); } /*! *\brief Returns the name of the MQTTTopic */ QString MQTTTopic::topicName() const { return m_topicName; } /*! *\brief Initializes the actions of MQTTTopic */ void MQTTTopic::initActions() { m_plotDataAction = new QAction(QIcon::fromTheme("office-chart-line"), i18n("Plot data"), this); connect(m_plotDataAction, &QAction::triggered, this, &MQTTTopic::plotData); } /*! *\brief Returns the MQTTClient the topic belongs to */ MQTTClient *MQTTTopic::mqttClient() const { return m_MQTTClient; } //############################################################################## //################################# SLOTS #################################### //############################################################################## /*! *\brief Plots the data stored in MQTTTopic */ void MQTTTopic::plotData() { PlotDataDialog* dlg = new PlotDataDialog(this); dlg->exec(); } /*! *\brief Reads every message from the message puffer */ void MQTTTopic::read() { while (!m_messagePuffer.isEmpty()) { qDebug() << "Reading from topic " << m_topicName; const QString tempMessage = m_messagePuffer.takeFirst(); m_filter->readMQTTTopic(tempMessage, this); } } //############################################################################## //################## Serialization/Deserialization ########################### //############################################################################## /*! Saves as XML. */ void MQTTTopic::save(QXmlStreamWriter* writer) const { writer->writeStartElement("MQTTTopic"); writeBasicAttributes(writer); writeCommentElement(writer); //general writer->writeStartElement("general"); writer->writeAttribute("topicName", m_topicName); writer->writeAttribute("filterPrepared", QString::number(m_filter->isPrepared())); writer->writeAttribute("filterSeparator", m_filter->separator()); writer->writeAttribute("messagePufferSize", QString::number(m_messagePuffer.size())); for (int i = 0; i < m_messagePuffer.count(); ++i) writer->writeAttribute("message"+QString::number(i), m_messagePuffer[i]); writer->writeEndElement(); //filter m_filter->save(writer); //Columns for (auto* col : children(IncludeHidden)) col->save(writer); writer->writeEndElement(); //MQTTTopic } /*! Loads from XML. */ bool MQTTTopic::load(XmlStreamReader* reader, bool preview) { removeColumns(0, columnCount()); if (!readBasicAttributes(reader)) return false; bool isFilterPrepared = false; QString separator; QString attributeWarning = i18n("Attribute '%1' missing or empty, default value is used"); QXmlStreamAttributes attribs; QString str; while (!reader->atEnd()) { reader->readNext(); if (reader->isEndElement() && reader->name() == "MQTTTopic") break; if (!reader->isStartElement()) continue; if (reader->name() == "comment") { if (!readCommentElement(reader)) return false; } else if (reader->name() == "general") { attribs = reader->attributes(); str = attribs.value("topicName").toString(); if (str.isEmpty()) reader->raiseWarning(attributeWarning.arg("'topicName'")); else { m_topicName = str; setName(str); } str = attribs.value("filterPrepared").toString(); if (str.isEmpty()) reader->raiseWarning(attributeWarning.arg("'filterPrepared'")); else { isFilterPrepared = str.toInt(); } str = attribs.value("filterSeparator").toString(); if (str.isEmpty()) reader->raiseWarning(attributeWarning.arg("'filterSeparator'")); else { separator = str; } int pufferSize = 0; str = attribs.value("messagePufferSize").toString(); if (str.isEmpty()) reader->raiseWarning(attributeWarning.arg("'messagePufferSize'")); else pufferSize = str.toInt(); for (int i = 0; i < pufferSize; ++i) { str = attribs.value("message"+QString::number(i)).toString(); if (str.isEmpty()) reader->raiseWarning(attributeWarning.arg("'message"+QString::number(i)+'\'')); else m_messagePuffer.push_back(str); } } else if (reader->name() == "asciiFilter") { if (!m_filter->load(reader)) return false; } else if (reader->name() == "column") { Column* column = new Column(QString(), AbstractColumn::Text); if (!column->load(reader, preview)) { delete column; setColumnCount(0); return false; } addChild(column); } else {// unknown element reader->raiseWarning(i18n("unknown element '%1'", reader->name().toString())); if (!reader->skipToEndElement()) return false; } } //prepare filter for reading m_filter->setPreparedForMQTT(isFilterPrepared, this, separator); return !reader->hasError(); } diff --git a/src/kdefrontend/datasources/MQTTConnectionManagerWidget.cpp b/src/kdefrontend/datasources/MQTTConnectionManagerWidget.cpp index 034634c91..14978094e 100644 --- a/src/kdefrontend/datasources/MQTTConnectionManagerWidget.cpp +++ b/src/kdefrontend/datasources/MQTTConnectionManagerWidget.cpp @@ -1,708 +1,707 @@ /*************************************************************************** File : MQTTConnectionManagerWidget.cpp Project : LabPlot Description : widget for managing MQTT connections -------------------------------------------------------------------- Copyright : (C) 2018 Ferencz Kovacs (kferike98@gmail.com) Copyright : (C) 2018-2019 Alexander Semke (alexander.semke@web.de) ***************************************************************************/ /*************************************************************************** * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) any later version. * * * * This program is distributed in the hope that it will be useful, * * but WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * * GNU General Public License for more details. * * * * You should have received a copy of the GNU General Public License * * along with this program; if not, write to the Free Software * * Foundation, Inc., 51 Franklin Street, Fifth Floor, * * Boston, MA 02110-1301 USA * * * ***************************************************************************/ #include "MQTTConnectionManagerWidget.h" #include "backend/lib/macros.h" #include #include #include #include #include #include #include -#include #include /*! \class MQTTConnectionManagerWidget \brief widget for managing MQTT connections, embedded in \c MQTTConnectionManagerDialog. \ingroup kdefrontend */ MQTTConnectionManagerWidget::MQTTConnectionManagerWidget(QWidget* parent, const QString& conn) : QWidget(parent), m_initConnName(conn) { ui.setupUi(this); m_configPath = QStandardPaths::standardLocations(QStandardPaths::AppDataLocation).constFirst() + QStringLiteral("MQTT_connections"); ui.lePort->setValidator(new QIntValidator(ui.lePort)); ui.bAdd->setIcon(QIcon::fromTheme(QStringLiteral("list-add"))); ui.bRemove->setIcon(QIcon::fromTheme(QStringLiteral("list-remove"))); ui.bAdd->setToolTip(i18n("Add new MQTT connection")); ui.bRemove->setToolTip(i18n("Remove selected MQTT connection")); ui.bTest->setIcon(QIcon::fromTheme(QStringLiteral("network-connect"))); //SIGNALs/SLOTs connect(ui.leName, &QLineEdit::textChanged, this, &MQTTConnectionManagerWidget::nameChanged); connect(ui.lwConnections, &QListWidget::currentRowChanged, this, &MQTTConnectionManagerWidget::connectionChanged); connect(ui.bAdd, &QPushButton::clicked, this, &MQTTConnectionManagerWidget::addConnection); connect(ui.bRemove, &QPushButton::clicked, this, &MQTTConnectionManagerWidget::deleteConnection); connect(ui.leHost, &QLineEdit::textChanged, this, &MQTTConnectionManagerWidget::hostChanged); connect(ui.lePort, &QLineEdit::textChanged, this, &MQTTConnectionManagerWidget::portChanged); connect(ui.leUserName, &QLineEdit::textChanged, this, &MQTTConnectionManagerWidget::userNameChanged); connect(ui.lePassword, &QLineEdit::textChanged, this, &MQTTConnectionManagerWidget::passwordChanged); connect(ui.leID, &QLineEdit::textChanged, this, &MQTTConnectionManagerWidget::clientIdChanged); connect(ui.chbAuthentication, &QCheckBox::stateChanged, this, &MQTTConnectionManagerWidget::authenticationChecked); connect(ui.chbID, &QCheckBox::stateChanged, this, &MQTTConnectionManagerWidget::idChecked); connect(ui.chbRetain, &QCheckBox::stateChanged, this, &MQTTConnectionManagerWidget::retainChecked); connect(ui.bTest, &QPushButton::clicked, this, &MQTTConnectionManagerWidget::testConnection); ui.lePassword->hide(); ui.lPassword->hide(); ui.lePassword->setToolTip(i18n("Please set a password.")); ui.leUserName->hide(); ui.lUsername->hide(); ui.leUserName->setToolTip(i18n("Please set a username.")); ui.leID->hide(); ui.lID->hide(); ui.leID->setToolTip(i18n("Please set a client ID.")); ui.leHost->setToolTip(i18n("Please set a valid host name.")); ui.leHost->setToolTip(i18n("Please set a valid name.")); QTimer::singleShot(100, this, SLOT(loadConnections())); } MQTTConnectionManagerWidget::~MQTTConnectionManagerWidget() { delete m_client; } /*! * \brief Returns the currently selected connection's name */ QString MQTTConnectionManagerWidget::connection() const { if (ui.lwConnections->currentItem()) return ui.lwConnections->currentItem()->text(); else return QString(); } /*! * \brief Shows the settings of the currently selected connection * \param index the index of the new connection */ void MQTTConnectionManagerWidget::connectionChanged(int index) { if (m_initializing) return; if (index == -1) { m_currentConnection = nullptr; return; } m_initializing = true; m_currentConnection = &m_connections[index]; //show the settings for the selected connection ui.leName->setText(m_currentConnection->name); ui.leHost->setText(m_currentConnection->hostName); ui.lePort->setText(QString::number(m_currentConnection->port)); if (m_currentConnection->useAuthentication) { ui.chbAuthentication->setChecked(true); ui.leUserName->setText(m_currentConnection->userName); ui.lePassword->setText(m_currentConnection->password); } else ui.chbAuthentication->setChecked(false); if (m_currentConnection->useID) { ui.chbID->setChecked(true); ui.leID->setText(m_currentConnection->clientID); } else ui.chbID->setChecked(false); ui.chbRetain->setChecked(m_currentConnection->retain); m_initializing = false; } /*! * \brief Called when the name is changed * Sets the name for the current connection */ void MQTTConnectionManagerWidget::nameChanged(const QString &name) { if (name.isEmpty()) { ui.leName->setStyleSheet(QStringLiteral("QLineEdit{background: red;}")); ui.leHost->setToolTip(i18n("Please set a valid name.")); } else { //check uniqueness of the provided name bool unique = true; for (int i = 0; i < ui.lwConnections->count(); ++i) { if (ui.lwConnections->currentRow() == i) continue; if (name == ui.lwConnections->item(i)->text()) { unique = false; break; } } if (unique) { ui.leName->setStyleSheet(QString()); ui.leName->setToolTip(QString()); ui.lwConnections->currentItem()->setText(name); if (!m_initializing) { m_currentConnection->name = name; emit changed(); } } else { ui.leName->setStyleSheet(QStringLiteral("QLineEdit{background: red;}")); ui.leHost->setToolTip(i18n("Please provide a unique name.")); } } } /*! * \brief Called when the host name is changed * Sets the host name for the current connection */ void MQTTConnectionManagerWidget::hostChanged(const QString& hostName) { if (hostName.isEmpty()) { ui.leHost->setStyleSheet(QStringLiteral("QLineEdit{background: red;}")); ui.leHost->setToolTip(i18n("Please set a valid host name.")); } else { m_currentConnection->hostName = hostName; //check uniqueness of the provided host name bool unique = true; for (auto & c : m_connections) { if (m_currentConnection == &c) continue; if (m_currentConnection->hostName == c.hostName && m_currentConnection->port == c.port) { unique = false; break; } } if (!unique) { ui.leHost->setStyleSheet(QStringLiteral("QLineEdit{background: red;}")); ui.leHost->setToolTip(i18n("Host name and port must be unique.")); ui.lePort->setStyleSheet(QStringLiteral("QLineEdit{background: red;}")); ui.lePort->setToolTip(i18n("Host name and port must be unique.")); } else { ui.leHost->setStyleSheet(QString()); ui.leHost->setToolTip(QString()); ui.lePort->setStyleSheet(QString()); ui.lePort->setToolTip(QString()); if (!m_initializing) emit changed(); } } } /*! * \brief Called when the port is changed * Sets the port for the current connection */ void MQTTConnectionManagerWidget::portChanged(const QString& portString) { if (portString.isEmpty()) { ui.leHost->setStyleSheet(QStringLiteral("QLineEdit{background: red;}")); ui.leHost->setToolTip(i18n("Please set a valid port.")); } else { m_currentConnection->port = portString.simplified().toInt(); //check uniqueness of the provided host name bool unique = true; for (auto & c : m_connections) { if (m_currentConnection == &c) continue; if (m_currentConnection->hostName == c.hostName && m_currentConnection->port == c.port) { unique = false; break; } } if (!unique) { ui.leHost->setStyleSheet(QStringLiteral("QLineEdit{background: red;}")); ui.leHost->setToolTip(i18n("Host name and port must be unique.")); ui.lePort->setStyleSheet(QStringLiteral("QLineEdit{background: red;}")); ui.lePort->setToolTip(i18n("Host name and port must be unique.")); } else { ui.leHost->setStyleSheet(QString()); ui.leHost->setToolTip(QString()); ui.lePort->setStyleSheet(QString()); ui.lePort->setToolTip(QString()); if (!m_initializing) emit changed(); } } } /*! *\brief Called when authentication checkbox's state is changed, * if checked two lineEdits are shown so the user can set the username and password * * \param state the state of the checkbox */ void MQTTConnectionManagerWidget::authenticationChecked(int state) { if (state == Qt::CheckState::Checked) { ui.lPassword->show(); ui.lePassword->show(); ui.lUsername->show(); ui.leUserName->show(); if (m_currentConnection) { ui.lePassword->setText(m_currentConnection->password); ui.leUserName->setText(m_currentConnection->userName); if (!m_initializing) m_currentConnection->useAuthentication = true; } } else if (state == Qt::CheckState::Unchecked) { ui.lPassword->hide(); ui.lePassword->hide(); ui.lePassword->clear(); ui.lUsername->hide(); ui.leUserName->hide(); ui.leUserName->clear(); if (m_currentConnection && !m_initializing) { m_currentConnection->useAuthentication = false; } } if (!m_initializing) emit changed(); } /*! *\brief called when ID checkbox's state is changed, if checked a lineEdit is shown so the user can set the ID * \param state the state of the checkbox */ void MQTTConnectionManagerWidget::idChecked(int state) { if (state == Qt::CheckState::Checked) { ui.lID->show(); ui.leID->show(); if (m_currentConnection) { ui.leID->setText(m_currentConnection->clientID); if (!m_initializing) m_currentConnection->useID = true; } } else if (state == Qt::CheckState::Unchecked) { ui.lID->hide(); ui.leID->hide(); ui.leID->clear(); if (m_currentConnection && !m_initializing) { m_currentConnection->useID = false; } } if (!m_initializing) emit changed(); } /*! * \brief called when retain checkbox's state is changed * \param state the state of the checkbox */ void MQTTConnectionManagerWidget::retainChecked(int state) { if (m_initializing) return; if (m_currentConnection) { if (state == Qt::CheckState::Checked) { m_currentConnection->retain = true; } else if (state == Qt::CheckState::Unchecked) { m_currentConnection->retain = false; } } emit changed(); } /*! * \brief Called when the username is changed * Sets the username for the current connection */ void MQTTConnectionManagerWidget::userNameChanged(const QString& userName) { if (userName.isEmpty()) { ui.leUserName->setStyleSheet(QStringLiteral("QLineEdit{background: red;}")); ui.leUserName->setToolTip(i18n("Please set a username.")); } else { ui.leUserName->setStyleSheet(QString()); ui.leUserName->setToolTip(QString()); } if (m_initializing) return; if (m_currentConnection) m_currentConnection->userName = userName; emit changed(); } /*! * \brief Called when the password is changed * Sets the password for the current connection */ void MQTTConnectionManagerWidget::passwordChanged(const QString& password) { if (password.isEmpty()) { ui.lePassword->setStyleSheet(QStringLiteral("QLineEdit{background: red;}")); ui.lePassword->setToolTip(i18n("Please set a password.")); } else { ui.lePassword->setStyleSheet(QString()); ui.lePassword->setToolTip(QString()); } if (m_initializing) return; if (m_currentConnection) m_currentConnection->password = password; emit changed(); } /*! * \brief Called when the client ID is changed * Sets the client ID for the current connection */ void MQTTConnectionManagerWidget::clientIdChanged(const QString& clientID) { if (clientID.isEmpty()) { ui.leID->setStyleSheet(QStringLiteral("QLineEdit{background: red;}")); ui.leID->setToolTip(i18n("Please set a client ID.")); } else { ui.leID->setStyleSheet(QString()); ui.leID->setToolTip(QString()); } if (m_initializing) return; if (m_currentConnection) m_currentConnection->clientID = clientID; emit changed(); } /*! adds a new sample connection to the end of the list. */ void MQTTConnectionManagerWidget::addConnection() { qDebug() << "Adding new connection"; MQTTConnection conn; conn.name = uniqueName(); conn.hostName = QStringLiteral("localhost"); conn.port = 1883; conn.useAuthentication = false; conn.useID = false; m_connections.append(conn); m_currentConnection = &m_connections.back(); ui.lwConnections->addItem(conn.hostName); ui.lwConnections->setCurrentRow(m_connections.size() - 1); //we have now more than one connection, enable widgets ui.bRemove->setEnabled(true); ui.leHost->setEnabled(true); ui.lePort->setEnabled(true); ui.leUserName->setEnabled(true); ui.lePassword->setEnabled(true); ui.leID->setEnabled(true); ui.leName->setEnabled(true); emit changed(); } /*! removes the current selected connection. */ void MQTTConnectionManagerWidget::deleteConnection() { int ret = KMessageBox::questionYesNo(this, i18n("Do you really want to delete the connection '%1'?", ui.lwConnections->currentItem()->text()), i18n("Delete Connection")); if (ret != KMessageBox::Yes) return; //remove the current selected connection m_connections.removeAt(ui.lwConnections->currentRow()); m_initializing = true; delete ui.lwConnections->takeItem(ui.lwConnections->currentRow()); m_initializing = false; //show the connection for the item that was automatically selected after the deletion connectionChanged(ui.lwConnections->currentRow()); //disable widgets if there are no connections anymore if (!m_currentConnection) { m_initializing = true; ui.leName->clear(); ui.leName->setEnabled(false); ui.bRemove->setEnabled(false); ui.leHost->clear(); ui.leHost->setEnabled(false); ui.lePort->clear(); ui.lePort->setEnabled(false); ui.leUserName->clear(); ui.leUserName->setEnabled(false); ui.lePassword->clear(); ui.lePassword->setEnabled(false); ui.leID->clear(); ui.leID->setEnabled(false); m_initializing = false; } emit changed(); } /*! Loads the saved connections. */ void MQTTConnectionManagerWidget::loadConnections() { qDebug() << "Loading connections from " << m_configPath; m_initializing = true; KConfig config(m_configPath, KConfig::SimpleConfig); for (const auto& groupName : config.groupList()) { const KConfigGroup& group = config.group(groupName); MQTTConnection conn; conn.name = groupName; conn.hostName = group.readEntry("Host", ""); conn.port = group.readEntry("Port", 0); conn.useAuthentication = group.readEntry("UseAuthentication", false); if (conn.useAuthentication) { conn.userName = group.readEntry("UserName", ""); conn.password = group.readEntry("Password", ""); } conn.useID = group.readEntry("UseID", false); if (conn.useID) conn.clientID = group.readEntry("ClientID", ""); conn.retain = group.readEntry("Retain", false); m_connections.append(conn); ui.lwConnections->addItem(conn.name); } //show the first connection if available, create a new connection otherwise if (!m_connections.empty()) { if (!m_initConnName.isEmpty()) { auto items = ui.lwConnections->findItems(m_initConnName, Qt::MatchExactly); if (items.empty()) ui.lwConnections->setCurrentRow(ui.lwConnections->count() - 1); else ui.lwConnections->setCurrentItem(items.constFirst()); } else { ui.lwConnections->setCurrentRow(ui.lwConnections->count() - 1); } } else { addConnection(); } m_initializing = false; //show the settings of the current connection connectionChanged(ui.lwConnections->currentRow()); } /*! * \brief Saves the connections present in the list widget. */ void MQTTConnectionManagerWidget::saveConnections() { qDebug() << "Saving connections to " << m_configPath; //delete saved connections KConfig config(m_configPath, KConfig::SimpleConfig); for (const auto& group : config.groupList()) config.deleteGroup(group); //save connections for (const auto& conn : m_connections) { KConfigGroup group = config.group(conn.name); group.writeEntry("Host", conn.hostName); group.writeEntry("Port", conn.port); group.writeEntry("UseAuthentication", QString::number(conn.useAuthentication)); group.writeEntry("UserName", conn.userName); group.writeEntry("Password", conn.password); group.writeEntry("UseID", QString::number(conn.useID)); group.writeEntry("ClientID", conn.clientID); group.writeEntry("Retain", QString::number(conn.retain)); } config.sync(); } /*! * \brief Checks whether every connection's settings are alright or not */ bool MQTTConnectionManagerWidget::checkConnections() { if (m_connections.isEmpty()) return true; bool connectionsOk = true; for (int i = 0; i < m_connections.size(); ++i) { auto & c1 = m_connections[i]; QList equalNames = ui.lwConnections->findItems(c1.name, Qt::MatchExactly); bool nameOK = (!c1.name.isEmpty()) && (equalNames.size() == 1); bool authenticationUsed = c1.useAuthentication; bool idUsed = c1.useID; bool authenticationFilled = !c1.userName.isEmpty() && !c1.password.isEmpty(); bool idFilled = !c1.clientID.isEmpty(); bool authenticationOK = (!authenticationUsed || authenticationFilled); bool idOK = (!idUsed || idFilled); bool uniqueHost = true; for (int j = 0; j < m_connections.size(); ++j) { if (i == j) continue; auto & c2 = m_connections[j]; if (c2.hostName == c1.hostName && c2.port == c1.port) { uniqueHost = false; break; } } bool hostOK = (!c1.hostName.isEmpty()) && uniqueHost; bool allOk = authenticationOK && idOK && hostOK && nameOK; if (!allOk) { connectionsOk = false; ui.lwConnections->item(i)->setBackground(QBrush(Qt::red)); } else ui.lwConnections->item(i)->setBackground(QBrush()); } return connectionsOk; } /*! * \brief Provides a sample host name, which has to be changed before use. * \return */ QString MQTTConnectionManagerWidget::uniqueName() { QString name = i18n("New connection"); QStringList connectionNames; for (int row = 0; row < ui.lwConnections->count(); row++) connectionNames << ui.lwConnections->item(row)->text(); if (!connectionNames.contains(name)) return name; QString base = name; int lastNonDigit; for (lastNonDigit = base.size()-1; lastNonDigit >= 0 && base[lastNonDigit].category() == QChar::Number_DecimalDigit; --lastNonDigit) base.chop(1); if (lastNonDigit >=0 && base[lastNonDigit].category() != QChar::Separator_Space) base.append(' '); int newNr = name.rightRef(name.size() - base.size()).toInt(); QString newName; do newName = base + QString::number(++newNr); while (connectionNames.contains(newName)); return newName; } /*! * \brief Tests the currently selected connection */ void MQTTConnectionManagerWidget::testConnection() { if (!m_currentConnection) return; WAIT_CURSOR; m_testing = true; if (!m_client) { m_client = new QMqttClient; m_testTimer = new QTimer(this); m_testTimer->setInterval(5000); connect(m_client, &QMqttClient::connected, this, &MQTTConnectionManagerWidget::onConnect); connect(m_client, &QMqttClient::disconnected, this, &MQTTConnectionManagerWidget::onDisconnect); connect(m_testTimer, &QTimer::timeout, this, &MQTTConnectionManagerWidget::testTimeout); } m_client->setHostname(m_currentConnection->hostName); m_client->setPort(m_currentConnection->port); if (m_currentConnection->useID) m_client->setClientId(m_currentConnection->clientID); if (m_currentConnection->useAuthentication) { m_client->setUsername(m_currentConnection->userName); m_client->setPassword(m_currentConnection->password); } m_testTimer->start(); m_client->connectToHost(); } /*! * \brief Called when the client connects to the host, this means the test was successful */ void MQTTConnectionManagerWidget::onConnect() { RESET_CURSOR; m_testTimer->stop(); KMessageBox::information(this, i18n("Connection to the broker '%1:%2' was successful.", m_currentConnection->hostName, m_currentConnection->port), i18n("Connection Successful")); m_client->disconnectFromHost(); } /*! * \brief Called when testTimer times out, this means that the test wasn't successful */ void MQTTConnectionManagerWidget::testTimeout() { RESET_CURSOR; m_testTimer->stop(); KMessageBox::error(this, i18n("Failed to connect to the broker '%1:%2'.", m_currentConnection->hostName, m_currentConnection->port), i18n("Connection Failed")); m_client->disconnectFromHost(); } /*! * \brief Called when the client disconnects from the host */ void MQTTConnectionManagerWidget::onDisconnect() { RESET_CURSOR; if (m_testTimer->isActive()) { KMessageBox::error(this, i18n("Disconnected from the broker '%1:%2' before the connection was successful.", m_currentConnection->hostName, m_currentConnection->port), i18n("Connection Failed")); m_testTimer->stop(); } } diff --git a/src/kdefrontend/datasources/MQTTErrorWidget.h b/src/kdefrontend/datasources/MQTTErrorWidget.h index 2815b728d..508454f1b 100644 --- a/src/kdefrontend/datasources/MQTTErrorWidget.h +++ b/src/kdefrontend/datasources/MQTTErrorWidget.h @@ -1,51 +1,51 @@ /*************************************************************************** File : MQTTErrorWidget.h Project : LabPlot Description : Widget for informing about an MQTT error, and for trying to solve it -------------------------------------------------------------------- Copyright : (C) 2018 by Kovacs Ferencz (kferike98@gmail.com) ***************************************************************************/ /*************************************************************************** * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) any later version. * * * * This program is distributed in the hope that it will be useful, * * but WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * * GNU General Public License for more details. * * * * You should have received a copy of the GNU General Public License * * along with this program; if not, write to the Free Software * * Foundation, Inc., 51 Franklin Street, Fifth Floor, * * Boston, MA 02110-1301 USA * * * ***************************************************************************/ #ifndef MQTTERRORWIDGET_H #define MQTTERRORWIDGET_H -#include - #include #include "ui_mqtterrorwidget.h" +class MQTTClient; + class MQTTErrorWidget : public QWidget { Q_OBJECT public: explicit MQTTErrorWidget(QMqttClient::ClientError error = QMqttClient::NoError, MQTTClient* client = nullptr, QWidget* parent = nullptr); private: Ui::MQTTErrorWidget ui; QMqttClient::ClientError m_error; MQTTClient* m_client; private slots: void tryToReconnect(); }; #endif // MQTTERRORWIDGET_H diff --git a/src/kdefrontend/datasources/MQTTSubscriptionWidget.cpp b/src/kdefrontend/datasources/MQTTSubscriptionWidget.cpp index f613e507a..dd0e505c0 100644 --- a/src/kdefrontend/datasources/MQTTSubscriptionWidget.cpp +++ b/src/kdefrontend/datasources/MQTTSubscriptionWidget.cpp @@ -1,1015 +1,1016 @@ /*************************************************************************** File : MQTTSubscriptionWidget.cpp Project : LabPlot Description : Widget for managing topics and subscribing -------------------------------------------------------------------- Copyright : (C) 2019 by Kovacs Ferencz (kferike98@gmail.com) ***************************************************************************/ /*************************************************************************** * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) any later version. * * * * This program is distributed in the hope that it will be useful, * * but WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * * GNU General Public License for more details. * * * * You should have received a copy of the GNU General Public License * * along with this program; if not, write to the Free Software * * Foundation, Inc., 51 Franklin Street, Fifth Floor, * * Boston, MA 02110-1301 USA * * * ***************************************************************************/ #include "MQTTSubscriptionWidget.h" #include "backend/datasources/MQTTClient.h" #include "ImportFileWidget.h" #include "kdefrontend/dockwidgets/LiveDataDock.h" -#include -#include -#include #include +#include +#include #include #include +#include + /*! \class MQTTSubscriptionWidget \brief Widget for managing topics and subscribing. \ingroup kdefrontend */ MQTTSubscriptionWidget::MQTTSubscriptionWidget( QWidget* parent): QWidget(parent), m_parentWidget(parent), m_searchTimer(new QTimer(this)) { if(dynamic_cast(parent) != nullptr) m_parent = MQTTParentWidget::ImportFileWidget; else m_parent = MQTTParentWidget::LiveDataDock; ui.setupUi(this); m_searchTimer->setInterval(10000); const int size = ui.leTopics->height(); ui.lTopicSearch->setPixmap( QIcon::fromTheme(QLatin1String("go-next")).pixmap(size, size) ); ui.lSubscriptionSearch->setPixmap( QIcon::fromTheme(QLatin1String("go-next")).pixmap(size, size) ); ui.bSubscribe->setIcon(ui.bSubscribe->style()->standardIcon(QStyle::SP_ArrowRight)); ui.bSubscribe->setToolTip(i18n("Subscribe selected topics")); ui.bUnsubscribe->setIcon(ui.bUnsubscribe->style()->standardIcon(QStyle::SP_ArrowLeft)); ui.bUnsubscribe->setToolTip(i18n("Unsubscribe selected topics")); //subscribe/unsubscribe buttons only enabled if something was selected ui.bSubscribe->setEnabled(false); ui.bUnsubscribe->setEnabled(false); QString info = i18n("Enter the name of the topic to navigate to it."); QString placeholder = i18n("Enter the name of the topic"); ui.lTopicSearch->setToolTip(info); ui.leTopics->setToolTip(info); ui.leTopics->setPlaceholderText(placeholder); ui.lSubscriptionSearch->setToolTip(info); ui.leSubscriptions->setToolTip(info); ui.leSubscriptions->setPlaceholderText(placeholder); info = i18n("Set the Quality of Service (QoS) for the subscription to define the guarantee of the message delivery:" "
    " "
  • 0 - deliver at most once
  • " "
  • 1 - deliver at least once
  • " "
  • 2 - deliver exactly once
  • " "
"); ui.cbQos->setToolTip(info); if(m_parent == MQTTParentWidget::ImportFileWidget) { connect(dynamic_cast(m_parentWidget), &ImportFileWidget::newTopic, this, &MQTTSubscriptionWidget::setTopicCompleter); connect(dynamic_cast(m_parentWidget), &ImportFileWidget::updateSubscriptionTree, this, &MQTTSubscriptionWidget::updateSubscriptionTree); connect(dynamic_cast(m_parentWidget), &ImportFileWidget::MQTTClearTopics, this, &MQTTSubscriptionWidget::clearWidgets); } else { connect(dynamic_cast(m_parentWidget), &LiveDataDock::MQTTClearTopics, this, &MQTTSubscriptionWidget::clearWidgets); connect(dynamic_cast(m_parentWidget), &LiveDataDock::newTopic, this, &MQTTSubscriptionWidget::setTopicCompleter); connect(dynamic_cast(m_parentWidget), &LiveDataDock::updateSubscriptionTree, this, &MQTTSubscriptionWidget::updateSubscriptionTree); } connect(ui.bSubscribe, &QPushButton::clicked, this, &MQTTSubscriptionWidget::mqttSubscribe); connect(ui.bUnsubscribe, &QPushButton::clicked, this,&MQTTSubscriptionWidget::mqttUnsubscribe); connect(m_searchTimer, &QTimer::timeout, this, &MQTTSubscriptionWidget::topicTimeout); connect(ui.leTopics, &QLineEdit::textChanged, this, &MQTTSubscriptionWidget::scrollToTopicTreeItem); connect(ui.leSubscriptions, &QLineEdit::textChanged, this, &MQTTSubscriptionWidget::scrollToSubsriptionTreeItem); connect(ui.twTopics, &QTreeWidget::itemDoubleClicked, this, &MQTTSubscriptionWidget::mqttAvailableTopicDoubleClicked); connect(ui.twSubscriptions, &QTreeWidget::itemDoubleClicked, this, &MQTTSubscriptionWidget::mqttSubscribedTopicDoubleClicked); connect(ui.twSubscriptions, &QTreeWidget::currentItemChanged, this, &MQTTSubscriptionWidget::subscriptionChanged); connect(ui.twTopics, &QTreeWidget::itemSelectionChanged, this, [=]() { ui.bSubscribe->setEnabled(!ui.twTopics->selectedItems().isEmpty()); }); connect(ui.twSubscriptions, &QTreeWidget::itemSelectionChanged, this, [=]() { ui.bUnsubscribe->setEnabled(!ui.twSubscriptions->selectedItems().isEmpty()); }); } MQTTSubscriptionWidget::~MQTTSubscriptionWidget() { m_searchTimer->stop(); delete m_searchTimer; } void MQTTSubscriptionWidget::setTopicList(QStringList topicList) { m_topicList = topicList; } QStringList MQTTSubscriptionWidget::getTopicList() { return m_topicList; } int MQTTSubscriptionWidget::subscriptionCount() { return ui.twSubscriptions->topLevelItemCount(); } QTreeWidgetItem* MQTTSubscriptionWidget::topLevelTopic(int index) { return ui.twTopics->topLevelItem(index); } QTreeWidgetItem* MQTTSubscriptionWidget::topLevelSubscription(int index) { return ui.twSubscriptions->topLevelItem(index); } void MQTTSubscriptionWidget::addTopic(QTreeWidgetItem* item) { ui.twTopics->addTopLevelItem(item); } int MQTTSubscriptionWidget::topicCount() { return ui.twTopics->topLevelItemCount(); } void MQTTSubscriptionWidget::setTopicTreeText(const QString &text) { ui.twTopics->headerItem()->setText(0, text); } QTreeWidgetItem* MQTTSubscriptionWidget::currentItem() const { return ui.twSubscriptions->currentItem(); } void MQTTSubscriptionWidget::makeVisible(bool visible) { ui.cbQos->setVisible(visible); ui.twTopics->setVisible(visible); ui.twSubscriptions->setVisible(visible); ui.leTopics->setVisible(visible); ui.leSubscriptions->setVisible(visible); ui.bSubscribe->setVisible(visible); ui.bUnsubscribe->setVisible(visible); ui.lTopicSearch->setVisible(visible); ui.lSubscriptionSearch->setVisible(visible); } void MQTTSubscriptionWidget::testSubscribe(QTreeWidgetItem *item) { ui.twTopics->setCurrentItem(item); mqttSubscribe(); } void MQTTSubscriptionWidget::testUnsubscribe(QTreeWidgetItem *item) { ui.twTopics->setCurrentItem(item); mqttUnsubscribe(); } /*! *\brief Fills the children vector, with the root item's (twSubscriptions) leaf children (meaning no wildcard containing topics) * * \param children vector of TreeWidgetItem pointers * \param root pointer to a TreeWidgetItem of twSubscriptions */ void MQTTSubscriptionWidget::findSubscriptionLeafChildren(QVector& children, QTreeWidgetItem* root) { if (root->childCount() == 0) children.push_back(root); else for (int i = 0; i < root->childCount(); ++i) findSubscriptionLeafChildren(children, root->child(i)); } /*! *\brief Checks if a topic contains another one * * \param superior the name of a topic * \param inferior the name of a topic * \return true if superior is equal to or contains(if superior contains wildcards) inferior, * false otherwise */ bool MQTTSubscriptionWidget::checkTopicContains(const QString& superior, const QString& inferior) { if (superior == inferior) return true; if (!superior.contains('/')) return false; const QStringList& superiorList = superior.split('/', QString::SkipEmptyParts); const QStringList& inferiorList = inferior.split('/', QString::SkipEmptyParts); //a longer topic can't contain a shorter one if (superiorList.size() > inferiorList.size()) return false; bool ok = true; for (int i = 0; i < superiorList.size(); ++i) { if (superiorList.at(i) != inferiorList.at(i)) { if ((superiorList.at(i) != "+") && !(superiorList.at(i) == "#" && i == superiorList.size() - 1)) { //if the two topics differ, and the superior's current level isn't + or #(which can be only in the last position) //then superior can't contain inferior ok = false; break; } else if (i == superiorList.size() - 1 && (superiorList.at(i) == "+" && inferiorList.at(i) == "#") ) { //if the two topics differ at the last level //and the superior's current level is + while the inferior's is #(which can be only in the last position) //then superior can't contain inferior ok = false; break; } } } return ok; } /*! *\brief Starts unsubscribing from the given topic, and signals to ImportFileWidget for further actions * * \param topicName the name of a topic we want to unsubscribe from */ void MQTTSubscriptionWidget::unsubscribeFromTopic(const QString& topicName) { if (topicName.isEmpty()) return; QVector children; findSubscriptionLeafChildren(children, ui.twSubscriptions->topLevelItem(0)); //signals for ImportFileWidget emit MQTTUnsubscribeFromTopic(topicName, children); for (int row = 0; row < ui.twSubscriptions->topLevelItemCount(); row++) { if (ui.twSubscriptions->topLevelItem(row)->text(0) == topicName) { ui.twSubscriptions->topLevelItem(row)->takeChildren(); ui.twSubscriptions->takeTopLevelItem(row); } } } /*! *\brief We search in twSubscriptions for topics that can be represented using + wildcards, then merge them. * We do this until there are no topics to merge */ void MQTTSubscriptionWidget::manageCommonLevelSubscriptions() { bool foundEqual = false; do { foundEqual = false; QMap> equalTopicsMap; QVector equalTopics; //compare the subscriptions present in the TreeWidget for (int i = 0; i < ui.twSubscriptions->topLevelItemCount() - 1; ++i) { for (int j = i + 1; j < ui.twSubscriptions->topLevelItemCount(); ++j) { QString commonTopic = checkCommonLevel(ui.twSubscriptions->topLevelItem(i)->text(0), ui.twSubscriptions->topLevelItem(j)->text(0)); //if there is a common topic for the 2 compared topics, we add them to the map (using the common topic as key) if (!commonTopic.isEmpty()) { if (!equalTopicsMap[commonTopic].contains(ui.twSubscriptions->topLevelItem(i)->text(0))) equalTopicsMap[commonTopic].push_back(ui.twSubscriptions->topLevelItem(i)->text(0)); if (!equalTopicsMap[commonTopic].contains(ui.twSubscriptions->topLevelItem(j)->text(0))) equalTopicsMap[commonTopic].push_back(ui.twSubscriptions->topLevelItem(j)->text(0)); } } } if (!equalTopicsMap.isEmpty()) { DEBUG("Manage common topics"); QVector commonTopics; QMapIterator> topics(equalTopicsMap); //check for every map entry, if the found topics can be merged or not while (topics.hasNext()) { topics.next(); int level = commonLevelIndex(topics.value().last(), topics.value().first()); QStringList commonList = topics.value().first().split('/', QString::SkipEmptyParts); QTreeWidgetItem* currentItem = nullptr; //search the corresponding item to the common topics first level(root) for (int i = 0; i < ui.twTopics->topLevelItemCount(); ++i) { if (ui.twTopics->topLevelItem(i)->text(0) == commonList.first()) { currentItem = ui.twTopics->topLevelItem(i); break; } } if (!currentItem) break; //calculate the number of topics the new + wildcard could replace int childCount = checkCommonChildCount(1, level, commonList, currentItem); if (childCount > 0) { //if the number of topics found and the calculated number of topics is equal, the topics can be merged if (topics.value().size() == childCount) { QDEBUG("Found common topic to manage: " << topics.key()); foundEqual = true; commonTopics.push_back(topics.key()); } } } if (foundEqual) { //if there are more common topics, the topics of which can be merged, we choose the one which has the lowest level new '+' wildcard int lowestLevel = INT_MAX; int topicIdx = -1; for (int i = 0; i < commonTopics.size(); ++i) { int level = commonLevelIndex(equalTopicsMap[commonTopics[i]].first(), commonTopics[i]); if (level < lowestLevel) { topicIdx = i; lowestLevel = level; } } QDEBUG("Manage: " << commonTopics[topicIdx]); equalTopics.append(equalTopicsMap[commonTopics[topicIdx]]); //Add the common topic ("merging") QString commonTopic; commonTopic = checkCommonLevel(equalTopics.first(), equalTopics.last()); QStringList nameList; nameList.append(commonTopic); QTreeWidgetItem* newTopic = new QTreeWidgetItem(nameList); ui.twSubscriptions->addTopLevelItem(newTopic); if(m_parent == MQTTParentWidget::ImportFileWidget) emit makeSubscription(commonTopic, static_cast (ui.cbQos->currentText().toUInt())); //remove the "merged" topics for (int i = 0; i < equalTopics.size(); ++i) { for (int j = 0; j < ui.twSubscriptions->topLevelItemCount(); ++j) { if (ui.twSubscriptions->topLevelItem(j)->text(0) == equalTopics[i]) { newTopic->addChild(ui.twSubscriptions->takeTopLevelItem(j)); if(m_parent == MQTTParentWidget::ImportFileWidget) unsubscribeFromTopic(equalTopics[i]); break; } } } //remove any subscription that the new subscription contains for (int i = 0; i < ui.twSubscriptions->topLevelItemCount(); ++i) { if (checkTopicContains(commonTopic, ui.twSubscriptions->topLevelItem(i)->text(0)) && commonTopic != ui.twSubscriptions->topLevelItem(i)->text(0) ) { if(m_parent == MQTTParentWidget::ImportFileWidget) unsubscribeFromTopic(ui.twSubscriptions->topLevelItem(i)->text(0)); else { ui.twSubscriptions->topLevelItem(i)->takeChildren(); ui.twSubscriptions->takeTopLevelItem(i); } i--; } } if(m_parent == MQTTParentWidget::LiveDataDock) emit makeSubscription(commonTopic, static_cast (ui.cbQos->currentText().toUInt())); } } } while (foundEqual); } /*! *\brief Fills twSubscriptions with the subscriptions made by the client */ void MQTTSubscriptionWidget::updateSubscriptionTree(const QVector& mqttSubscriptions) { DEBUG("ImportFileWidget::updateSubscriptionTree()"); ui.twSubscriptions->clear(); for (int i = 0; i < mqttSubscriptions.size(); ++i) { QStringList name; name.append(mqttSubscriptions[i]); bool found = false; for (int j = 0; j < ui.twSubscriptions->topLevelItemCount(); ++j) { if (ui.twSubscriptions->topLevelItem(j)->text(0) == mqttSubscriptions[i]) { found = true; break; } } if (!found) { //Add the subscription to the tree widget QTreeWidgetItem* newItem = new QTreeWidgetItem(name); ui.twSubscriptions->addTopLevelItem(newItem); name.clear(); name = mqttSubscriptions[i].split('/', QString::SkipEmptyParts); //find the corresponding "root" item in twTopics QTreeWidgetItem* topic = nullptr; for (int j = 0; j < ui.twTopics->topLevelItemCount(); ++j) { if (ui.twTopics->topLevelItem(j)->text(0) == name[0]) { topic = ui.twTopics->topLevelItem(j); break; } } //restore the children of the subscription if (topic != nullptr && topic->childCount() > 0) restoreSubscriptionChildren(topic, newItem, name, 1); } } m_searching = false; } /*! *\brief Adds to a # wildcard containing topic, every topic present in twTopics that the former topic contains * * \param topic pointer to the TreeWidgetItem which was selected before subscribing * \param subscription pointer to the TreeWidgetItem which represents the new subscirption, * we add all of the children to this item */ void MQTTSubscriptionWidget::addSubscriptionChildren(QTreeWidgetItem* topic, QTreeWidgetItem* subscription) { //if the topic doesn't have any children we don't do anything if (topic->childCount() <= 0) return; for (int i = 0; i < topic->childCount(); ++i) { QTreeWidgetItem* temp = topic->child(i); QString name; //if it has children, then we add it as a # wildcrad containing topic if (topic->child(i)->childCount() > 0) { name.append(temp->text(0) + "/#"); while (temp->parent() != nullptr) { temp = temp->parent(); name.prepend(temp->text(0) + '/'); } } //if not then we simply add the topic itself else { name.append(temp->text(0)); while (temp->parent() != nullptr) { temp = temp->parent(); name.prepend(temp->text(0) + '/'); } } QStringList nameList; nameList.append(name); QTreeWidgetItem* childItem = new QTreeWidgetItem(nameList); subscription->addChild(childItem); //we use the function recursively on the given item addSubscriptionChildren(topic->child(i), childItem); } } /*! *\brief Restores the children of a top level item in twSubscriptions if it contains wildcards * * \param topic pointer to a top level item in twTopics which represents the root of the subscription topic * \param subscription pointer to a top level item in twSubscriptions, this is the item whose children will be restored * \param list QStringList containing the levels of the subscription topic * \param level the level's number which is being investigated */ void MQTTSubscriptionWidget::restoreSubscriptionChildren(QTreeWidgetItem * topic, QTreeWidgetItem * subscription, const QStringList& list, int level) { if (list[level] != "+" && list[level] != "#" && level < list.size() - 1) { for (int i = 0; i < topic->childCount(); ++i) { //if the current level isn't + or # wildcard we recursively continue with the next level if (topic->child(i)->text(0) == list[level]) { restoreSubscriptionChildren(topic->child(i), subscription, list, level + 1); break; } } } else if (list[level] == "+") { for (int i = 0; i < topic->childCount(); ++i) { //determine the name of the topic, contained by the subscription QString name; name.append(topic->child(i)->text(0)); for (int j = level + 1; j < list.size(); ++j) name.append('/' + list[j]); QTreeWidgetItem* temp = topic->child(i); while (temp->parent() != nullptr) { temp = temp->parent(); name.prepend(temp->text(0) + '/'); } //Add the topic as child of the subscription QStringList nameList; nameList.append(name); QTreeWidgetItem* newItem = new QTreeWidgetItem(nameList); subscription->addChild(newItem); //Continue adding children recursively to the new item restoreSubscriptionChildren(topic->child(i), newItem, list, level + 1); } } else if (list[level] == "#") { //add the children of the # wildcard containing subscription addSubscriptionChildren(topic, subscription); } } /*! *\brief Returns the amount of topics that the '+' wildcard will replace in the level position * * \param levelIdx the level currently being investigated * \param level the level where the new + wildcard will be placed * \param commonList the topic name split into levels * \param currentItem pointer to a TreeWidgetItem which represents the parent of the level * represented by levelIdx * \return returns the childCount, or -1 if some topics already represented by + wildcard have different * amount of children */ int MQTTSubscriptionWidget::checkCommonChildCount(int levelIdx, int level, QStringList& commonList, QTreeWidgetItem* currentItem) { //we recursively check the number of children, until we get to level-1 if (levelIdx < level - 1) { if (commonList[levelIdx] != "+") { for (int j = 0; j < currentItem->childCount(); ++j) { if (currentItem->child(j)->text(0) == commonList[levelIdx]) { //if the level isn't represented by + wildcard we simply return the amount of children of the corresponding item, recursively return checkCommonChildCount(levelIdx + 1, level, commonList, currentItem->child(j)); } } } else { int childCount = -1; bool ok = true; //otherwise we check if every + wildcard represented topic has the same number of children, recursively for (int j = 0; j < currentItem->childCount(); ++j) { int temp = checkCommonChildCount(levelIdx + 1, level, commonList, currentItem->child(j)); if ((j > 0) && (temp != childCount)) { ok = false; break; } childCount = temp; } //if yes we return this number, otherwise -1 if (ok) return childCount; else return -1; } } else if (levelIdx == level - 1) { if (commonList[levelIdx] != "+") { for (int j = 0; j < currentItem->childCount(); ++j) { if (currentItem->child(j)->text(0) == commonList[levelIdx]) { //if the level isn't represented by + wildcard we simply return the amount of children of the corresponding item return currentItem->child(j)->childCount(); } } } else { int childCount = -1; bool ok = true; //otherwise we check if every + wildcard represented topic has the same number of children for (int j = 0; j < currentItem->childCount(); ++j) { if ((j > 0) && (currentItem->child(j)->childCount() != childCount)) { ok = false; break; } childCount = currentItem->child(j)->childCount(); } //if yes we return this number, otherwise -1 if (ok) return childCount; else return -1; } } else if (level == 1 && levelIdx == 1) return currentItem->childCount(); return -1; } /*! *\brief Returns the index of level where the two topic names differ, if there is a common topic for them * * \param first the name of a topic * \param second the name of a topic * \return The index of the unequal level, if there is a common topic, otherwise -1 */ int MQTTSubscriptionWidget::commonLevelIndex(const QString& first, const QString& second) { QStringList firstList = first.split('/', QString::SkipEmptyParts); QStringList secondtList = second.split('/', QString::SkipEmptyParts); QString commonTopic; int differIndex = -1; if (!firstList.isEmpty()) { //the two topics have to be the same size and can't be identic if (firstList.size() == secondtList.size() && (first != second)) { //the index where they differ for (int i = 0; i < firstList.size(); ++i) { if (firstList.at(i) != secondtList.at(i)) { differIndex = i; break; } } //they can differ at only one level bool differ = false; if (differIndex > 0) { for (int j = differIndex + 1; j < firstList.size(); ++j) { if (firstList.at(j) != secondtList.at(j)) { differ = true; break; } } } else differ = true; if (!differ) { for (int i = 0; i < firstList.size(); ++i) { if (i != differIndex) commonTopic.append(firstList.at(i)); else commonTopic.append('+'); if (i != firstList.size() - 1) commonTopic.append('/'); } } } } //if there is a common topic we return the differIndex if (!commonTopic.isEmpty()) return differIndex; else return -1; } /*! *\brief Returns the '+' wildcard containing topic name, which includes the given topic names * * \param first the name of a topic * \param second the name of a topic * \return The name of the common topic, if it exists, otherwise "" */ QString MQTTSubscriptionWidget::checkCommonLevel(const QString& first, const QString& second) { const QStringList& firstList = first.split('/', QString::SkipEmptyParts); if (firstList.isEmpty()) return QString(); const QStringList& secondtList = second.split('/', QString::SkipEmptyParts); QString commonTopic; //the two topics have to be the same size and can't be identic if (firstList.size() == secondtList.size() && (first != second)) { //the index where they differ int differIndex = -1; for (int i = 0; i < firstList.size(); ++i) { if (firstList.at(i) != secondtList.at(i)) { differIndex = i; break; } } //they can differ at only one level bool differ = false; if (differIndex > 0) { for (int j = differIndex + 1; j < firstList.size(); ++j) { if (firstList.at(j) != secondtList.at(j)) { differ = true; break; } } } else differ = true; if (!differ) { for (int i = 0; i < firstList.size(); ++i) { if (i != differIndex) commonTopic.append(firstList.at(i)); else { //we put '+' wildcard at the level where they differ commonTopic.append('+'); } if (i != firstList.size() - 1) commonTopic.append('/'); } } } // qDebug() << "Common topic for " << first << " and " << second << " is: " << commonTopic; return commonTopic; } /************** SLOTS **************************************************************/ /*! *\brief When a leaf topic is double clicked in the topics tree widget we subscribe on that */ void MQTTSubscriptionWidget::mqttAvailableTopicDoubleClicked(QTreeWidgetItem* item, int column) { Q_UNUSED(column) // Only for leaf topics if (item->childCount() == 0) mqttSubscribe(); } /*! *\brief When a leaf subscription is double clicked in the topics tree widget we unsubscribe */ void MQTTSubscriptionWidget::mqttSubscribedTopicDoubleClicked(QTreeWidgetItem* item, int column) { Q_UNUSED(column) // Only for leaf subscriptions if (item->childCount() == 0) mqttUnsubscribe(); } /*! *\brief called when the subscribe button is pressed * subscribes to the topic represented by the current item of twTopics */ void MQTTSubscriptionWidget::mqttSubscribe() { QTreeWidgetItem* item = ui.twTopics->currentItem(); if (!item) return; //should never happen //determine the topic name that the current item represents QTreeWidgetItem* tempItem = item; QString name = item->text(0); if (item->childCount() != 0) name.append("/#"); while (tempItem->parent()) { tempItem = tempItem->parent(); name.prepend(tempItem->text(0) + '/'); } //check if the subscription already exists const QList& topLevelList = ui.twSubscriptions->findItems(name, Qt::MatchExactly); if (topLevelList.isEmpty() || topLevelList.first()->parent() != nullptr) { QDEBUG("Subscribe to: " << name); bool foundSuperior = false; for (int i = 0; i < ui.twSubscriptions->topLevelItemCount(); ++i) { //if the new subscirptions contains an already existing one, we remove the inferior one if (checkTopicContains(name, ui.twSubscriptions->topLevelItem(i)->text(0)) && name != ui.twSubscriptions->topLevelItem(i)->text(0)) { if(m_parent == MQTTParentWidget::ImportFileWidget) unsubscribeFromTopic(ui.twSubscriptions->topLevelItem(i)->text(0)); else { ui.twSubscriptions->topLevelItem(i)->takeChildren(); ui.twSubscriptions->takeTopLevelItem(i); } --i; continue; } //if there is a subscription containing the new one we set foundSuperior true if (checkTopicContains(ui.twSubscriptions->topLevelItem(i)->text(0), name) && name != ui.twSubscriptions->topLevelItem(i)->text(0)) { foundSuperior = true; QDEBUG("Can't continue subscribing. Found superior for " << name << " : " << ui.twSubscriptions->topLevelItem(i)->text(0)); break; } } //if there wasn't a superior subscription we can subscribe to the new topic if (!foundSuperior) { QStringList toplevelName; toplevelName.push_back(name); QTreeWidgetItem* newTopLevelItem = new QTreeWidgetItem(toplevelName); ui.twSubscriptions->addTopLevelItem(newTopLevelItem); if (name.endsWith('#')) { //adding every topic that the subscription contains to twSubscriptions addSubscriptionChildren(item, newTopLevelItem); } emit makeSubscription(name, static_cast(ui.cbQos->currentText().toUInt())); if (name.endsWith('#')) { //if an already existing subscription contains a topic that the new subscription also contains //we decompose the already existing subscription //by unsubscribing from its topics, that are present in the new subscription as well const QStringList nameList = name.split('/', QString::SkipEmptyParts); const QString& root = nameList.first(); QVector children; for (int i = 0; i < ui.twSubscriptions->topLevelItemCount(); ++i) { if (ui.twSubscriptions->topLevelItem(i)->text(0).startsWith(root) && name != ui.twSubscriptions->topLevelItem(i)->text(0)) { children.clear(); //get the "leaf" children of the inspected subscription findSubscriptionLeafChildren(children, ui.twSubscriptions->topLevelItem(i)); for (int j = 0; j < children.size(); ++j) { if (checkTopicContains(name, children[j]->text(0))) { //if the new subscription contains a topic, we unsubscribe from it if(m_parent == MQTTParentWidget::ImportFileWidget) { ui.twSubscriptions->setCurrentItem(children[j]); mqttUnsubscribe(); --i; } else { QTreeWidgetItem* unsubscribeItem = children[j]; while (unsubscribeItem->parent() != nullptr) { for (int i = 0; i < unsubscribeItem->parent()->childCount(); ++i) { const QString& childText = unsubscribeItem->parent()->child(i)->text(0); if (unsubscribeItem->text(0) != childText) { //add topic as subscription quint8 qos = static_cast(ui.cbQos->currentText().toUInt()); emit addBeforeRemoveSubscription(childText, qos); //also add it to twSubscriptions ui.twSubscriptions->addTopLevelItem(unsubscribeItem->parent()->takeChild(i)); --i; } else { //before we remove the topic, we reparent it to the new subscription //so no data is lost emit reparentTopic(unsubscribeItem->text(0), name); } } unsubscribeItem = unsubscribeItem->parent(); } qDebug()<<"Remove: "<text(0); emit removeMQTTSubscription(unsubscribeItem->text(0)); ui.twSubscriptions->takeTopLevelItem(ui.twSubscriptions->indexOfTopLevelItem(unsubscribeItem)); } } } } } } //implementalj es ird at liveDataDock addsubscription!!!!! manageCommonLevelSubscriptions(); updateSubscriptionCompleter(); emit enableWill(true); } else QMessageBox::warning(this, i18n("Warning"), i18n("You already subscribed to a topic containing this one")); } else QMessageBox::warning(this, i18n("Warning"), i18n("You already subscribed to this topic")); } /*! *\brief Updates the completer for leSubscriptions */ void MQTTSubscriptionWidget::updateSubscriptionCompleter() { QStringList subscriptionList; for (int i = 0; i < ui.twSubscriptions->topLevelItemCount(); ++i) subscriptionList.append(ui.twSubscriptions->topLevelItem(i)->text(0)); if (!subscriptionList.isEmpty()) { m_subscriptionCompleter = new QCompleter(subscriptionList, this); m_subscriptionCompleter->setCompletionMode(QCompleter::PopupCompletion); m_subscriptionCompleter->setCaseSensitivity(Qt::CaseSensitive); ui.leSubscriptions->setCompleter(m_subscriptionCompleter); } else ui.leSubscriptions->setCompleter(nullptr); } /*! *\brief called when the unsubscribe button is pressed * unsubscribes from the topic represented by the current item of twSubscription */ void MQTTSubscriptionWidget::mqttUnsubscribe() { QTreeWidgetItem* unsubscribeItem = ui.twSubscriptions->currentItem(); if (!unsubscribeItem) return; //should never happen QDEBUG("Unsubscribe from: " << unsubscribeItem->text(0)); //if it is a top level item, meaning a topic that we really subscribed to(not one that belongs to a subscription) //we can simply unsubscribe from it if (unsubscribeItem->parent() == nullptr) { if(m_parent == MQTTParentWidget::ImportFileWidget) unsubscribeFromTopic(unsubscribeItem->text(0)); else { emit removeMQTTSubscription(unsubscribeItem->text(0)); ui.twSubscriptions->takeTopLevelItem(ui.twSubscriptions->indexOfTopLevelItem(unsubscribeItem)); } } //otherwise we remove the selected item, but subscribe to every other topic, that was contained by //the selected item's parent subscription(top level item of twSubscriptions) else { while (unsubscribeItem->parent() != nullptr) { for (int i = 0; i < unsubscribeItem->parent()->childCount(); ++i) { const QString& childText = unsubscribeItem->parent()->child(i)->text(0); if (unsubscribeItem->text(0) != childText) { quint8 qos = static_cast(ui.cbQos->currentText().toUInt()); if(m_parent == MQTTParentWidget::ImportFileWidget) emit makeSubscription(childText, qos); else emit addBeforeRemoveSubscription(childText, qos); ui.twSubscriptions->addTopLevelItem(unsubscribeItem->parent()->takeChild(i)); --i; } } unsubscribeItem = unsubscribeItem->parent(); } if(m_parent == MQTTParentWidget::ImportFileWidget) unsubscribeFromTopic(unsubscribeItem->text(0)); else { emit removeMQTTSubscription(unsubscribeItem->text(0)); ui.twSubscriptions->takeTopLevelItem(ui.twSubscriptions->indexOfTopLevelItem(unsubscribeItem)); } //check if any common topics were subscribed, if possible merge them manageCommonLevelSubscriptions(); } updateSubscriptionCompleter(); if (ui.twSubscriptions->topLevelItemCount() <= 0) emit enableWill(false); } /*! *\brief called when a new topic is added to the tree(twTopics) * appends the topic's root to the topicList if it isn't in the list already * then sets the completer for leTopics */ void MQTTSubscriptionWidget::setTopicCompleter(const QString& topic) { if (!m_searching) { const QStringList& list = topic.split('/', QString::SkipEmptyParts); QString tempTopic; if (!list.isEmpty()) tempTopic = list.at(0); else tempTopic = topic; if (!m_topicList.contains(tempTopic)) { m_topicList.append(tempTopic); m_topicCompleter = new QCompleter(m_topicList, this); m_topicCompleter->setCompletionMode(QCompleter::PopupCompletion); m_topicCompleter->setCaseSensitivity(Qt::CaseSensitive); ui.leTopics->setCompleter(m_topicCompleter); } } } /*! *\brief called when leTopics' text is changed * if the rootName can be found in twTopics, then we scroll it to the top of the tree widget * * \param rootName the current text of leTopics */ void MQTTSubscriptionWidget::scrollToTopicTreeItem(const QString& rootName) { m_searching = true; m_searchTimer->start(); int topItemIdx = -1; for (int i = 0; i < ui.twTopics->topLevelItemCount(); ++i) if (ui.twTopics->topLevelItem(i)->text(0) == rootName) { topItemIdx = i; break; } if (topItemIdx >= 0) ui.twTopics->scrollToItem(ui.twTopics->topLevelItem(topItemIdx), QAbstractItemView::ScrollHint::PositionAtTop); } /*! *\brief called when leSubscriptions' text is changed * if the rootName can be found in twSubscriptions, then we scroll it to the top of the tree widget * * \param rootName the current text of leSubscriptions */ void MQTTSubscriptionWidget::scrollToSubsriptionTreeItem(const QString& rootName) { int topItemIdx = -1; for (int i = 0; i < ui.twSubscriptions->topLevelItemCount(); ++i) if (ui.twSubscriptions->topLevelItem(i)->text(0) == rootName) { topItemIdx = i; break; } if (topItemIdx >= 0) ui.twSubscriptions->scrollToItem(ui.twSubscriptions->topLevelItem(topItemIdx), QAbstractItemView::ScrollHint::PositionAtTop); } /*! *\brief called when 10 seconds passed since the last time the user searched for a certain root in twTopics * enables updating the completer for le */ void MQTTSubscriptionWidget::topicTimeout() { m_searching = false; m_searchTimer->stop(); } void MQTTSubscriptionWidget::clearWidgets() { ui.twTopics->clear(); ui.twSubscriptions->clear(); ui.twTopics->headerItem()->setText(0, i18n("Available")); } void MQTTSubscriptionWidget::onDisconnect() { m_searchTimer->stop(); m_searching = false; delete m_topicCompleter; delete m_subscriptionCompleter; } diff --git a/src/kdefrontend/datasources/MQTTSubscriptionWidget.h b/src/kdefrontend/datasources/MQTTSubscriptionWidget.h index e3ae2083a..c92db7ff0 100644 --- a/src/kdefrontend/datasources/MQTTSubscriptionWidget.h +++ b/src/kdefrontend/datasources/MQTTSubscriptionWidget.h @@ -1,108 +1,107 @@ /*************************************************************************** File : MQTTSubscriptionWidget.h Project : LabPlot Description : manage topics and subscribing -------------------------------------------------------------------- Copyright : (C) 2019 by Kovacs Ferencz (kferike98@gmail.com) ***************************************************************************/ /*************************************************************************** * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) any later version. * * * * This program is distributed in the hope that it will be useful, * * but WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * * GNU General Public License for more details. * * * * You should have received a copy of the GNU General Public License * * along with this program; if not, write to the Free Software * * Foundation, Inc., 51 Franklin Street, Fifth Floor, * * Boston, MA 02110-1301 USA * * * ***************************************************************************/ #ifndef MQTTSUBSCRIPTIONWIDGET_H #define MQTTSUBSCRIPTIONWIDGET_H -#include #include #include "ui_mqttsubscriptionwidget.h" class QMqttSubscription; class MQTTSubscriptionWidget : public QWidget { Q_OBJECT public: explicit MQTTSubscriptionWidget(QWidget* parent = nullptr); ~MQTTSubscriptionWidget() override; enum MQTTParentWidget { ImportFileWidget = 0, LiveDataDock = 1 }; void setTopicList (QStringList topicList); QStringList getTopicList(); int subscriptionCount(); QTreeWidgetItem* topLevelTopic(int); QTreeWidgetItem* topLevelSubscription(int); QTreeWidgetItem* currentItem() const; void addTopic(QTreeWidgetItem*); int topicCount(); void setTopicTreeText(const QString&); void makeVisible(bool); void testSubscribe(QTreeWidgetItem*); void testUnsubscribe(QTreeWidgetItem*); static bool checkTopicContains(const QString&, const QString&); static void findSubscriptionLeafChildren(QVector&, QTreeWidgetItem*); signals: void subscriptionChanged(); void makeSubscription(const QString& name, quint8 QoS); void MQTTUnsubscribeFromTopic(const QString&, QVector children); void removeMQTTSubscription(const QString&); void addBeforeRemoveSubscription(const QString&, quint8); void reparentTopic(const QString& topic, const QString& parent); void enableWill(bool); private: Ui::MQTTSubscriptionWidget ui; MQTTParentWidget m_parent; QWidget* m_parentWidget; QCompleter* m_subscriptionCompleter{nullptr}; QCompleter* m_topicCompleter{nullptr}; QStringList m_topicList; bool m_searching{false}; QTimer* m_searchTimer; void unsubscribeFromTopic(const QString&); void manageCommonLevelSubscriptions(); void updateSubscriptionCompleter(); static void addSubscriptionChildren(QTreeWidgetItem*, QTreeWidgetItem*); static void restoreSubscriptionChildren(QTreeWidgetItem * topic, QTreeWidgetItem * subscription, const QStringList& list, int level); static int checkCommonChildCount(int levelIdx, int level, QStringList& namelist, QTreeWidgetItem* currentItem); static int commonLevelIndex(const QString& first, const QString& second); static QString checkCommonLevel(const QString&, const QString&); private slots: void mqttAvailableTopicDoubleClicked(QTreeWidgetItem* item, int column); void mqttSubscribedTopicDoubleClicked(QTreeWidgetItem* item, int column); void mqttSubscribe(); void mqttUnsubscribe(); void setTopicCompleter(const QString&); void scrollToTopicTreeItem(const QString& rootName); void scrollToSubsriptionTreeItem(const QString& rootName); void topicTimeout(); void updateSubscriptionTree(const QVector&); void clearWidgets(); void onDisconnect(); }; #endif // MQTTSUBSCRIPTIONWIDGET_H