Sponsors

STATS

Todays date:
Monday 02nd of August 2021 05:49:17 PM

You are visitor

33974


Your IP address is 3.231.230.177


Page last updated
15 July 2017

MQTT

Raspberry Pi     After experimenting with our automation, solar and robotics projects, we decided to try communicating between our projects using MQTT.

We will not go into detail about what MQTT is or what it does. There is already plenty of information around t'net describing this already.

Here we will explain the steps we needed to take to install MQTT on our devices.


PLEASE NOTE:

During our testing of the instructions on this page, we found some things have changed.

Please be patient with us. It takes many hours for us to test, roll back and test again, to make sure this information is accurate.

the broker

The broker can be considered the centre of our system, the hub if you like.

Since our web server (Raspberry Pi) is on 24/7, it would make sense to install our MQTT broker on this, so that it will be available to all clients, all of the time.

Log into the RPi console as user pi. Then enter the following command:

sudo apt-get install mosquitto

The Mosquitto Broker should now be installed and running on our Raspberry Pi.

The clients

The Mosquitto Client software is used to connect to our Broker. It is also required to add users and passwords for the MQTT Broker. Clients must be installed on each machine you wish to connect to your broker.

simply enter the following command:

sudo apt-get install mosquitto-clients

Now we will set up passwords

sudo nano /etc/mosquitto/passwords.txt
testuser:testpassword
CTRL-X
sudo mosquitto_passwd -U passwords.txt
sudo nano /etc/mosquitto/conf.d/mqtt.conf
allow_anonymous false password_file /etc/mosquitto/passwords.txt
CTRL-X

If on_connect() takes exactly 3 arguments error:
add 'flags' as fourth parameter to on _connect callback. I.E.

def on_connect(client, userdata, flags, rc)


We can now move onto testing our MQTT operation.

NOTES:

sudo apt-get install python-mysqldb
sudo nano /etc/mysql/my.cnf
comment bind-address = 127.0.0.1 using the # symbol
sudo pip install paho-mqtt

Testing MQTT

In order to test that our MQTT system is working, all we need to do is subscribe to a topic

Open a console window and login as user pi. Then type the following command:


mosquitto_sub -h 192.168.1.5 -t testmqtt
`
You will need to substitute the ip address of the server which is running your MQTT broker.
Note. If you are running the broker and clients on the same Raspberry Pi, The IP address will be 127.0.0.1

This will create a client, which is listening to the topic 'testmqtt'.

Next we will publish some data to the same topic.
Open another console window and log in.
This time, type:


mosquitto_pub -h 192.168.1.5 -t testmqtt -m "It works."

This command will publish some text to the topic 'testmqtt'.
The message "It works." should appear in the client window.