MQTT is a messaging protocol for the “Internet of Things” (IoT). It allows devices to communicate easily with minimal overheads. The Raspberry Pi of course makes an excellent low cost platform for managing IoT. Not only is it cheap to buy, it is also cheap to keep running.
To use MQTT, you need a “broker” which is simply a service running in the background. Mosquitto is one of the more popular brokers, partly because it is pretty small and therefore ideal for running on a Pi.
If you want to use MQTT from the browser however, you also need the broker to support something called “websockets” since browsers cannot directly talk using the MQTT protocol. In the past, Mosquitto didn’t have websockets compiled in by default and compiling your own version on a Pi is painful to say the least.
Thankfully, this is no longer a problem since the authors of Mosquitto now provide a repository containing ARM versions which work fine on the Pi. See mosquitto.org for the details.
Once installed from the repository, you will need to add a suitable configuration since websockets are not part of the default configuration.
To turn it on, you should add a new file to
/etc/mosquitto/conf.d/ containing something like:
# See: http://mm011106.github.io/reference/mosquitto_conf.html # Standard Listener listener 1883 protocol mqtt allow_anonymous false password_file /etc/mosquitto/passwords.txt # Websockets Listener listener 9001 http_dir Set the protocol to accept for this listener. Can be mqtt (the default), or websockets. protocol websockets
Note that you can create more than one listener of the same type. You might, for example, want to create another listener that is restricted to a subset of topics so that you can allow access to that over the Internet. Perhaps you would restrict it to listing only sensor data but not control messages for your home automation project for example.
Once you have enabled websockets access to Mosquitto, you can do some interesting things directly from web pages. Get hold of MQTT.js for the browser and you can both listen to and send messages from/to the broker. Combined with a framework such as REACT allows you to, with only a few lines of code, display all the messages that arrive at your broker.
Updated 2018-04-24 21:20:16 - Tidy output after migration from WordPress.