[SOLVED] Access subscribed variables without looping

I have read it somewhere that MQTT doesn’t do the polling process, unlike http.
If you subscribe() to a variable, your Arduino receives an event and the Event-function is executed.
That’s it. No polling. No CheckButtons() every x seconds. No HTTP traffic.

Can I get a sample code for that?
Code in which we are subscribe to a variable and when there is a change in that particular variable, an event is sent to arduino and event like function is executed?

Hello @Rehanbabar17,

Please take a look to this video for an example: https://www.youtube.com/watch?v=ynhJ4YhhQEM

Here is our MQTT API: https://ubidots.com/docs/api/mqtt.html

Regards

Hello @jotathebest

I am confused about few things, for instance, isn’t the bold line used for polling to access server again and again to see if there is any change in the variable?

  • Why is callback function used for?
    -What if we want to monitor the change in more than 1 variables?
    void setup() {
    // put your setup code here, to run once:
    Serial.begin(74800);
    client.wifiConnection(WIFINAME, WIFIPASS);
    client.begin(callback);
    client.ubidotsSubscribe(“IoT_Project”,“Humidity”); //Insert the dataSource and Variable’s Labels
    }

    void loop() {
    // put your main code here, to run repeatedly:
    if(!client.connected()){
    client.reconnect();
    client.ubidotsSubscribe(“IoT_Project”,“Humidity”);//Insert the dataSource and Variable’s Labels
    client.print(Humidity)
    }
    client.loop();
    }

Hello @Rehanbabar17,

The callback is the function that processes the incoming data when there is a change on your variables, as you would see in the switch video I modify the callback to parse if I receive ‘1’ or ‘0’ in my routine and to make an action based on that value.

If you want to monitor more than one variable, just call the subscribe() function again, here is an example to multiple calls to the subscribe() function: http://blog.ubidots.com/digital-piano-with-ubidots-and-nodemcu, in the example are declared multiple clients but you can subscribe to different topics with only one client too. You should parse the message string in the callback too for knowing what variable changed.

Regards

Thank you so much @jotathebest
But how will we differentiate the payload of each topic?

And when we write the following line in loop function, doesn’t it poll the MQTT broker again and again to see if there is any change in the variable?
client.ubidotsSubscribe("piano", "do");

regards,

In your callback, print the topic or the entire message and you should get something like this: api/v1.6/devices/YOUR_DEVICE/YOUR_VARIABLE , you should parse this to know which variable has changed.

Regards

Thank you so much @jotathebest
Everything is working the way I wanted.
I couldn’t have been possible without your help.