Python as Publisher and Subscriber

MQTT CLIENT

In order to implement a mqtt client using python you need a Python 2.7 or any higher version. Assuming you have Python 2.7 or any higher version. Before you start publishing or subscribing using Python , you need a Broker. Broker can be install on Windows machine or Linux machine or Raspberry pi or VM instance of Google cloud ( Installing MQTT Broker on Windows or Installing MQTT Broker on Linux or Installing MQTT Broker on Raspberry PI or Installing on VM instance of Google Cloud ) etc. You also need to install paho mqtt library. If paho mqtt is already installed on your PC or machine then you can directly use the codes given below.




Steps for installing paho mqtt library on Windows machine :
1)Open Command Prompt as Administrator. Steps given below.
Search command Prompt in your computer -> Right click on command prompt -> Run as Administrator

2)Go to Your Python installed Folder or path from the command prompt using following command

cd C:\Program Files\Python37


3)Then inside Python folder, go to Scripts Folder using following command .

cd Scripts


4)Execute the following command to install paho-mqtt
Use following command for below python 3 version( Example: python2.7).

pip install paho-mqtt

Use following command for python 3 and higher version( Example: python3.7).

pip3 install paho-mqtt

It’s saying Requirement already satisfied because paho mqtt is already installed. Here pip3 install paho-mqtt used because machine has python 3.7 version.




Steps for installing paho mqtt library on Linux machine :
1)Open the Linux terminal.
2)Execute the Following command
Use following command for below python 3 version( Example: python2.7 ).

sudo pip install paho-mqtt

Use following command for python 3 and higher version( Example: python3.7 ).

sudo pip3 install paho-mqtt
Following publisher and Subscriber codes are  same for python 2.7 and any higher version on Windows machine as well as Linux machine. only paho mqtt installation is different.

Assuming you have Python 2.7 or any higher version and you have Successfully installed above paho MQTT library. To use python as Publisher please download and extract the following code and modify the following things.
1)Replace broker with IP address of machine on which broker is installed.
2)Replace topic with topic  you want to post data .
3)If you want to modify message or data please modify payload.

In the Following code broker value is localhost means Publisher and broker are running on the same machine.
Download Python as Publisher code (204 downloads)

import paho.mqtt.client as paho #mqtt library
import os
import json
import time
from datetime import datetime

#host name is localhost because both broker and python are Running on same 
#machine/Computer.
broker="localhost" #host name , Replace with your IP address.
topic="test";
port=1883 #MQTT data listening port
ACCESS_TOKEN='M7OFDCmemyKoi461BJ4j' #not manditory


def on_publish(client,userdata,result): #create function for callback
  print("published data is : ")
  pass

client1= paho.Client("control1") #create client object
client1.on_publish = on_publish #assign function to callback
client1.username_pw_set(ACCESS_TOKEN) #access token from thingsboard device
client1.connect(broker,port,keepalive=60) #establishing connection

#publishing after every 5 secs
while True:

  payload="{"
  payload+="\"Temperature\":10";payload+=",";
  payload+="\"Humidity\":50";
  payload+="}"
  ret= client1.publish(topic,payload) #topic name is test
  print(payload);
  print("Please check data on your Subscriber Code \n")
  time.sleep(5)

Python publisher Output

Note: when You use above code and If you are getting error as invalid character in identifier, Please replace all & with your keyboards Double and Single quote respectively. # represents comment.

Assuming you have Python 2.7 or any higher version and you have Successfully installed above paho MQTT library. To use python as Subscriber please download and extract the following code and modify the following things.
1)Replace broker with IP address of machine on which broker is installed.
2)Replace topic  with topic you want to subscribe.

In following code  broker value is localhost means Subscriber and broker are running on the same machine or computer.
Download Python as Subscriber code (138 downloads)

import paho.mqtt.client as paho
import time
import sys
import datetime
import time
broker="localhost"  #host name
topic="test" #topic name
        
def on_message(client, userdata, message):
  print("received data is :")  
  print(str(message.payload.decode("utf-8")) ) #printing Received message
  print("")
    
client= paho.Client("user") #create client object 
client.on_message=on_message
   
print("connecting to broker host",broker)
client.connect(broker)#connection establishment with broker
print("subscribing begins here")    
client.subscribe(topic)#subscribe topic test

while 1:
    client.loop_start() #contineously checking for message 

Python subscriber Output

You may also like...

Leave a Reply