Handling MQTT subscription
Handle MQTT subscription on chosen topics within your MQTT message template
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.
The subscription handler can be enabled by clicking on the checkbox below message contents.
- topic: The MQTT topic you are subscribing to
- message: The received message content for that topic in string form. If you are publishing JSON, you will need to call JSON.parse() to convert this to a JSON object.
- last: The last state of the current sensor object (the same last state as available to publish function). This will only make sense if your publisher is using JSON format.
Also following parameters are available in this context for the function
- this.clientId : The current client ID for the client
- this.index : The count of the iteration which has already been published
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.
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
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.