Publishing messages with MQTT, using Clojure and the Eclipse Paho client

As alluded in my last post I have found that MQTT (MQ Telemetry Protocol) is quite simple to use, and especially so when compared to most other messaging protocols. In particular it’s a great fit for embedded devices or whenever resources are limited, since it’s quite lightweight. From the MQTT page:

 

MQTT is a machine-to-machine (M2M)/”Internet of Things” connectivity protocol. It was designed as an extremely lightweight publish/subscribe messaging transport. It is useful for connections with remote locations where a small code footprint is required and/or network bandwidth is at a premium. For example, it has been used in sensors communicating to a broker via satellite link, over occasional dial-up connections with healthcare providers, and in a range of home automation and small device scenarios. It is also ideal for mobile applications because of its small size, low power usage, minimised data packets, and efficient distribution of information to one or many receivers

 

On top of that I can see it being used when the needs themselves are straightforward, which is often the case: just publish a payload to a topic somewhere and avoid worrying with keeping up connection state, error handling, etc. Additionally it has been proposed as an OASIS standard which is good news for those looking for a messaging (and M2M in particular)

There are many implementation options to choose from  (see the MQTT software page for more details), this example code is based on the Eclipse Paho implementation. See the full code on the github gist, the following is a snippet:

Usage is trivial, here’s an example:

$ java -cp ~/.m2/repository/org/clojure/clojure/1.5.1/clojure-1.5.1.jar:/tmp/dummy/org.eclipse.paho.client.mqttv3.jar clojure.main mqtt.clj
Connected to tcp://m2m.eclipse.org:1883
*** PUBLISHING TO TOPIC cljtest ***
*** DELIVERY COMPLETE ***
$

… and seeing the publishing using the Mosquitto MQTT client to subscribe to the topic:

$ mosquitto_sub -h m2m.eclipse.org -t "cljtest" -v
cljtest But at least, out of my bitterness at what I'll never be, There's the quick calligraphy of these lines, The broken archway to the Impossible.
^C
$

Yet again Clojure presents itself as a good way to take advantage of the Java libs, even when one doesn’t use most of other Clojure’s strengths.

Fernando Pessoa

 

PS: For the curious the standard message is from Fernando Pessoa‘s “Tobacco Shop“, part of his English Poems. Well worth exploring.

One thought on “Publishing messages with MQTT, using Clojure and the Eclipse Paho client”

Comments are closed.