Install MQTT on Raspberry Pi

MQTT is a machine-to-machine (M2M)/”Internet of Things” connectivity protocol. It is lightweight and simple for use. Read more about MQTT at mqtt.org

Now we will show you how to make it working on your Raspberry Pi with a few steps.

Install MQTT on Raspberry Pi

Install broker and client at Raspberry

$sudo apt-get update
$ sudo apt-get install mosquitto mosquitto-clients

Stop Mosquitto service

 $ sudo /etc/init.d/mosquitto stop

Configure Mosquitto

 $ sudo nano /etc/mosquitto/mosquitto.conf

And update file this way:

# Place your local configuration in /etc/mosquitto/conf.d/
#
# A full description of the configuration file is at
# /usr/share/doc/mosquitto/examples/mosquitto.conf.example

pid_file /var/run/mosquitto.pid

persistence true
persistence_location /var/lib/mosquitto/

log_dest topic

log_type error
log_type warning
log_type notice
log_type information

connection_messages true
log_timestamp true

include_dir /etc/mosquitto/conf.d

Start Mosquitto

$ sudo /etc/init.d/mosquitto start

Test Mosquitto Open two terminals for one Raspberry.

In one window type:

$ mosquitto_sub -d -t hello/world

In second window type:

$ mosquitto_pub -d -t hello/world -m "Hello from Terminal window 2!"

In the first window you should see:

~ $ sudo mosquitto_sub -d -t hello/world
Client mosqsub/1837-LightSwarm sending CONNECT
Client mosqsub/1837-LightSwarm received CONNACK
Client mosqsub/1837-LightSwarm sending SUBSCRIBE (Mid: 1, Topic: hello/world, QoS: 0)
Client mosqsub/1837-LightSwarm received SUBACK
Subscribed (mid: 1): 0
Client mosqsub/1837-LightSwarm received PUBLISH (d0, q0, r0, m0, 'hello/world', ... (29 bytes))
Hello from Terminal window 2!

Understand what we did

In example above we installed broker and client on the same Raspberry pi. Broker is routing messages and keeps topics management and clients are sending messages through broker.

Anybody from clients can subscribe to any MQTT topic and publish to any MQTT topic. The MQTT topic is something like a header of message with post address.

Install MQTT client on next Raspberry Pi

You can do it similarly as on previous Raspberry:

$ sudo apt-get install mosquitto-clients

If you will publish MQTT message from this second Raspberry Pi, do not forget to insert an IP address of the broker e.g.:

$ mosquitto_pub -h 192.168.1.188 -d -t hello/world -m "Hello from Raspberry Pi 2 Terminal window!"

Need to know more about MQTT

Here is a good post dealing with more options of publishing/subscribing MQTT messages.

You may also like...

Follow by Email
LinkedIn
LinkedIn
Share