Getting Started with MQTT

Sunday, July 22, 2012

Tags: programming, mqtt

I wanted to play around with MQTT this evening so I put together a little tutorial on how to get started using Ubuntu and Mosquitto.

Installing Mosquitto

Enter the following into your terminal. Remember to replace YOUR_UBUNTU_VERSION_HERE with the version of ubuntu you’re using, I was using Maverick Meerkat at the time so I replaced it with just maverick. First add the following two lines to /etc/apt/sources.list

deb http://ppa.launchpad.net/mosquitto-dev/mosquitto-ppa/ubuntu YOUR_UBUNTU_VERSION_HERE main
deb-src http://ppa.launchpad.net/mosquitto-dev/mosquitto-ppa/ubuntu YOUR_UBUNTU_VERSION_HERE main

Then we need to verify the newly added packages:

$ sudo apt-key adv --keyserver keyserver.ubuntu.com --recv-keys 262C4500

Lets update Aptitude so we have the latest packages to choose from:

$ sudo aptitude update

And now lets install the Mosquitto server and clients:

$ sudo aptitude install mosquitto
$ sudo aptitude install mosquitto-clients

Subscribing to a Topic

$ mosquitto_sub -d -t hello/world

Mosquitto uses slashes as a way to organize topics. It also provides ways to subscribe to groups of topics if you dig around their documentation.

Publishing to a Topic

In another terminal window execute:

$ mosquitto_pub -d -t hello/world -m "Hello World"

You should see the text “Hello World” in the other window.

To get the full effect you can install Mosquitto on your Mac using Homebrew and then connect to your Ubuntu machine…

$ mosquitto_sub -h YOUR_HOST_IP_ADDRESS -d -t hello/world

You should now see messages from your host sent to your local machine. You’ll probably need to open up port 1883 on your Ubuntu machine to make this actually work. I just used iptables to do so:

sudo iptables -A INPUT -p tcp -m tcp --dport 1883 -j ACCEPT