Sunday, March 6, 2016

MQTT & Mosquitto Server Setup Notes

Overview
I've been playing around with the MQTT protocol. As a learning exercise I wrote a client for MQTT: climqtt [1]. A lot has already been written about MQTT so below are just some of my notes and links to stuff that helped me.


MQTT
MQTT is a simple publish/subscribe protocol. A client connects to a MQTT server and then sends a 'connect' message and the server responds with a 'connection acknowledgement'. At that point the client may subscribe to one or more topics or publish to topics. When subscribing to a topic a client may choose to specify wildcards. The topic matching mechanism is handled on the server-side.

Another interesting aspect of MQTT is the last will & testament (LWT) where if a client disconnects it may have preconfigured a LWT to emit a message on a predetermined topic. This is useful to indicate that client has gone offline.

Default MQTT Unsecure Port: 1883
Default MQTT Secure Port: 8883


Mosquitto
Mosquitto[2] is a library/server/client combo that handles all things MQTT. It seems to be pretty mature.

Install Mosquitto

  • Installing Mosquitto on a Raspberry Pi [4]
  • Useful information on generating certificates & setup can be found here [3]
  • Mosquitto provides some sparse docs on certificates here [5]

Mosquitto Server .conf file
listener 8883
cafile /etc/mosquitto/certs/ca.crt
certfile /etc/mosquitto/certs/grant.crt
keyfile /etc/mosquitto/certs/grant.key
require_certificate true



Mosquitto Pub
Use mosquitto to publish to the "/test" topic and also set a LWT:
mosquitto_pub -t "/test" -l -r --will-topic "/test" --will-retain --will-payload "goodbye..." -h 127.0.0.1 -q 2 -p 8883 --cafile ca.crt --cert grantscomp.crt --key grantscomp.key

Mosquitto Sub
Use mosquitto to subscribe to all topics (i.e. the "#" matches all topics):

mosquitto_sub -t "#" -v -v -h 127.0.0.1 -q 2 -p 8883 --cafile ca.crt --cert grantscomp.crt --key grantscomp.key




Links:
  1. https://bitbucket.org/grantj/climqtt/overview
  2. http://mosquitto.org
  3. http://rockingdlabs.dunmire.org/exercises-experiments/ssl-client-certs-to-secure-mqtt
  4. http://jpmens.net/2013/09/01/installing-mosquitto-on-a-raspberry-pi/
  5. http://mosquitto.org/man/mosquitto-tls-7.html