MQTT Installed In Raspberry Pi & Using Python

In this tutorial, we will learn on how to write a Python program for MQTT.

As far as we know, the MQTT has 3 components which is publisher, broker(server) and subscriber. The communication between them happens over a particular topic.

In this example, lets see how the MQTT communication happens between them for read temperature data. The communication happens like this.

  1. Publisher  – It will read the temperature value and publish over the topic called “temp”
  2. Broker receives the temperature value over a topic called “temp”. Then, its immediately distributes / sends the value to all the subscribers of the topic “temp”.
  3. All the subscribers of topic “temp” receives the value.

ITEM NEEDED

  1. A MQTT server –  It is called MQTT broker. We can used raspberry pi as our server. Mosquitto is one example server that can be run in raspberry pi.
  2. A publisher – A python program that read a temperature and send the data to MQTT server.
  3. A subscriber –  A python program that will receive the values from publisher through MQTT server.

INSTALLATION MQTT BROKER LIBRARY for Raspberry Pi

Two steps need to be done:

  1. Install MQTT broker/server named Mosquitto with below command. It will installed the MQTT broker and client libraries on raspberry pi and will run it automatically in the background.
   sudo apt-get install -y mosquitto mosquitto-clients

2. Run the MQTT Mosquitto broker by type below command. It will run the broker on raspberry pi.

  sudo systemctl enable mosquitto

3.  To stop the MQTT Mosquitto broker by type below command. It will run the broker on raspberry pi.

sudo service mosquitto stop
sudo systemctl stop mosquitto.service

INSTALLATION MQTT Python LIBRARY

In order to use MQTT functionalities through python code, we have to install the mqtt python libraries. The most popular mqtt library for python is paho-mqtt library which can be installed with this command. It will install in python3 library using terminal or cmd window.

sudo pip3 install paho-mqtt

 

Publisher example

Below show an example coding for Publisher:

import paho.mqtt.client as mqtt
BROKER_HOST = "localhost"
BROKER_PORT = 1883
TOPIC = "TEST"


def on_connect(client, userdata, rc):
if rc == 0:
print("Connected successfully.")
else:
print("Connection failed. rc= "+str(rc))

def on_publish(client, userdata, mid):
print("Message "+str(mid)+" published.")

mqttclient = mqtt.Client()
# Connect
mqttclient.connect(BROKER_HOST,BROKER_PORT)

# Assign event callbacks
mqttclient.on_connect = on_connect
mqttclient.on_publish = on_publish

# Publish a message
mqttclient.publish(TOPIC,"TRY!!!!!")

 

Subscriber example

Below show an example coding for Subscriber:

import paho.mqtt.client as mqtt
BROKER_HOST = "localhost"
BROKER_PORT = 1883
TOPIC = "TEST"

def on_connect(client, userdata, rc):
    if rc == 0:
        print("Connected successfully.")
    else:
        print("Connection failed. rc= "+str(rc))

def on_publish(client, userdata, mid):
    print("Message "+str(mid)+" published.")

def on_subscribe(client, userdata, mid, granted_qos):
    print("Subscribe with mid "+str(mid)+" received.")

def on_message(client, userdata, msg):
    print("Message received on topic: "+str(msg.topic))
    print("QoS: "+str(msg.qos))
    print("Payload: "+str(msg.payload))


mqttclient = mqtt.Client()

# Connect
mqttclient.connect(BROKER_HOST,BROKER_PORT)

# Assign event callbacks
mqttclient.on_message = on_message
mqttclient.on_connect = on_connect
mqttclient.on_subscribe = on_subscribe

# Start subscription
mqttclient.subscribe(TOPIC)

# Continue monitoring the incoming messages for subscribed topic
mqttclient.loop_forever()