Handling MQTT subscription

Handle MQTT subscription on chosen topics within your MQTT message template

Writing your MQTT subscription handler

MQTT is a bidirectional communication protocol and any client can publish as well as subscribe to any topic.
Often you would need to subscribe to a topic to take some actions e.g. for simulating a Traffic light, you will publish the current ambient light intensity to the backend and subscribe to a command to turn on or off the light from the backend.
This can be easily handled using subscription handlers in MQTT templates.

Handling subscription

The subscription handler can be enabled by clicking on the checkbox below message contents.
For MQTT subscription, you will need a topic to subscribe and write a handler function in Javascript. The function is invoked with following arguments:-

Also following parameters are available in this context for the function

Note: The helper function such as chance, drive, moment are not available in the subscription handler function

The only purpose of the subscription handler function is to allow you to set last object based upon received parameters.
Therefore, we don’t allow any helper function except Javascript native libraries in the context.

Please note that the last object is passed as a reference, any changes you make to the object will be persistent for next publish.


Here is a simple example of showcasing the usage of Subscription handler.

Let’s create a simple MQTT template which publishes on the topic /iotify/demo with following contents

if (state.key === undefined ) state.key = chance.integer({min:0, max:100});
return JSON.stringify(state);

Now let’s create a subscription handler on the same topic /iotify/demo with following function body


What will happen when you run this?

Without a subscription handler, the publisher will choose a random value initially and publish the same value everytime it runs.

However, now with subscription handler, everytime it publishes this value, the handler will get invoked and will increment the key by one.

As a result, the published key will increment by one upon every publish.