I was thinking about how to control my Aeroponic system remotely via the Internet. The Raspberry Pi controlling the system is connected to the Internet via a router. I could access the Raspberry Pi by Port forwarding and stuff like that but it’s complicated. My next option could be using Websockets but I felt it’s overkill for the applications running in the Pi.

Recently I received a Refcard from DZone regarding a protocol called MQTT. I was not aware of this Protocol before. So I thought of doing some experiments with it. I am not going much deeper into the protocol, the DZone refcard did a great job of explaining it well.

In a nutshell, MQTT consist of three parts.

Broker

Subscribers

Publishers

The Publisher publishes a message to a specific topic and any Subscriber subscribed to that topic receives the message. The Broker is the central hub. Both Publishers and Subscribers are connected to the Broker and it takes care of delivering the message to all the subscribers subscribed for the topic.

Brokers

We can implement our own broker using RabitMQ or a Mosca plugin for Node.js or any other MQTT brokers available in the market. To experiment with it, I used the CloudMQTT addon in Heroku. I used Heroku just to manage every thing from one central place.

Dev Environment

I created two sets of Node.js applications, one running in my computer as a publisher and another running in my RaspberryPi as a subscriber. Both had no direct connection; instead they were connected to the CloudMQTT broker. Below is some test code.

The above code acts as a Publisher as well as a Subscriber. For e.g. the above code can be a piece running on the Internet and the Pi can Publish the temperature readings in a periodic interval and log it in a central database. We can see the readings via a webapp or whichever way we need. Also if required we can set a temperature to all the connected Raspberry Pis by publishing a message to topic ‘SET_TEMPERATURE’.

The code is very minimal and we could achieve easy communication to all the connected devices. In the above scenario, clients are always connected. If you want to end the connection then call ‘client.end()’.

Later I implemented a Broker using Mosca, and in both scenarios the system worked really well.