Planned maintenance: From Sunday 8th December 10:00 CET there will be changes to try and solve the caching issues that have been experienced. If anyone has a problem connecting after this period then please PM @AndyS or any of the moderators.

Subscriptions in MQTT



  • Hi,

    I built QMQTT module for the community version of the ide. I did a simple program to connect to a broker and publish some frames. It worked.

    I tried to add a subscription to receive frames from another client and I came across a problem and I am not able to figure it out.

    In all examples I see on the Internet, I see things like:

    auto subs = m_client->subscribe("topic"); //Being "topic" a QString.
    if(!subs){
       qDebug() << "can't subscribe!";
    }
    

    But, once I try that, I get an error. subscribe mandatory param is a QMqttTopicFilter.

    I tried something like:

    QMqttTopicFilter topic;
    topic.setFilter("topic");
    auto subs = m_client->subscribe(topic, 1);
    if(!subs){
        qDebug() << "can't subs";
    }
    

    But I get always the message "can't subs". Neither do I receibe frames with this:

    connect(m_client, &QMqttClient::messageReceived, this, [this](const QByteArray &message, const QMqttTopicName &topic) {
            const QString content = QDateTime::currentDateTime().toString()
                        + QLatin1String(" Received Topic: ")
                        + topic.name()
                        + QLatin1String(" Message: ")
                        + message
                        + QLatin1Char('\n');
            qDebug() << (content);
        });
    

    I guess that subscription is not made at all. Debugging I get that subs value is 0x0. It does not create QMqttSubscription object as it should.

    Can you give me an idea about what I can try? This is my first time with QT and I am still reading tutorials.


  • Lifetime Qt Champion

    Hi and welcome to devnet,

    What broker are you using ?
    How is it setup ?



  • I tested with 2 instances of Mosquitto Broker with MQTT 3.1

    Configuration is the standard one. I have not modified anything but user, password and port in one of them. The other remain as default.

    I can publish with this program and subscribe&publish with other clients.


  • Lifetime Qt Champion

    Ok, can you provide a minimal compilable sample that shows the situation you have ?



  • Well I found the solution.

    It seems that in some version of the MQTT module something changed:

    QMqttTopicFilter topic;
    
    topic.setFilter("hello");
    auto subs = m_client->subscribe(topic, 1);
    qDebug() << "Subs state: " << subs->Subscribed;
    

    Now you need to check with the "Subscribed" property and not with the response in "subs".


  • Lifetime Qt Champion

    Glad you found out and thanks for sharing !