Communication in between two raspberry pi's using MQTT on local network

Hi guys,
I hope you all are fine and doing well. I want to ask about two raspberry pi’s communication using MQTT when both are connected with the same wifi. Is it possible or not? I don’t want to use the cloud. I want to use one raspberry pi to publish messages on the local network and another to receive them. Is it something that is possible or not?
Thanks
Regards,
Ans

Hello @ans

Welcome to HiveMQ Community! It’s completely possible, you have to install the HiveMQ broker locally and these Raspberry PI’s devices can connect to it and publish and subscribe messages easily.

Our HiveMQ Community Edition is a good start for you.

Kind regards,
Diego from HiveMQ Team

So, your mean first installing HiveMQ broker on both raspberry pi and then running the scripts? I already did it with paho-mqtt and mosquito broker. Let me show you the script.
this is a script for the server side. when I run with host=‘localhost’ it works fine and publishes a message but when I run with host='client IP address it doesn’t work and gives me an error of IP is not reachable or something like that. You can view the script.

importing the mqtt library instance and time library

import sys
import paho.mqtt.client as mqtt
import time

client = mqtt.Client() # here we are getting the instance of the Client class
#exitFlag = True # this is taken for the authentication purpose
client.username_pw_set(username=“roger”,password=“password”) # username and password set by me for connection

========================Call Backs==========================================================================

def on_publish(client,userdata,mid): # call back for the published data
print("Payload Published: "+str(mid)) # printing the message id of the published message

def on_connect(pvtClient,userdata,flags,rc): # call back for the connection acknowledgement
#global exitFlag # here I am setting the exitFlag based on connection status, we will use this flag later on
if(rc == 0): # on successful connection
print(“publisher Connected”) # printing the data
print(“Connected to client! Return Code:”+str(rc)) # printing the data on the screen
#exitFlag = False
elif(rc ==5): # in case of authentication error
print("Authentication Error! Return Code: "+str(rc)) # printing the data on the screen
client.disconnect()
#exitFlag = True

here we are using this call back for the logs generation, these logs are helpful to us while debugging

def on_log(client, userdata, level, buf): # call backs for the logs,
print("Logs: "+str(buf)) # printing the logs on the screen, this will show the logs
#about the flags that will used by the publisher and subscriber
def on_disconnect(pvtClient, userdata, rc): # this call back will run, when a disconnect() is received
print("disconnecting reason " +str(rc))
client.disconnect()

============================================================================================================

important part

=================== Associating the functions with the call backs===========================================

client.on_publish = on_publish
client.on_connect = on_connect
client.on_log = on_log
client.on_disconnect = on_disconnect

============================================================================================================

======= Establishing Connection ========

host = “localhost”
port = 1883
keepAlive = 60
client.connect(host,port,keepAlive)

=========================================

starting the loop

we are using this loop and sleep in-between client.connect(…) and client.publish(…)

so we can observe the call backs

client.loop_start(); # starting a loop in order to observe the call backs
time.sleep(2) # giving a sleep time for the connection to setup

once connected, publish the message

============Publishing the message ======

topic_name = “aman/cdac/test”
QOS = 2 # here we can use different Quality of service, based on our requirement
retain = True
time.sleep(.5)
payload=“Attendance Marked!”
client.publish(topic_name,payload,QOS,retain) # publishing the message (payload)
time.sleep(5)
client.disconnect()

if the connection is successful then this while loop will run

while(exitFlag == False): # here we are using the flags which we have set earlier,

time.sleep(.5) # giving some time for the call backs to process

payload = input("\nMessage: ")

client.publish(topic_name,payload,QOS,retain) # publishing the message (payload)

if(payload == “exit(0)”): # in case user has entered “exit(0)” then exit and disconnect

client.disconnect()

‘’’
Using the QOS we can set the Quality of Service of the given client connection
and the message published for the same.

======= Establishing Connection ========

Based on this QOS, the times our client is receiving the message may differ,
Furthermore, we may confirm the acknowledgements involved between
Publisher — broker ---- subscriber, are more.
For a given MQTT setup we can set this value of either 0, 1, 2, wherein
different QOS have different properties
Also, in our case, we can use the functionality of retaining the last known message
in case the given client (subscriber) is not present, or unable to receive the message
(payload), Hence, setting the value of retain parameter as True or 1 will make sure that
in case of undelivered message, the given message is retained
‘’’

=========================================

If you use the loop_start() or loop_forever functions then the loop runs in a separate thread,

and it is the loop that processes the incoming and outgoing messages.

client.loop_stop() # stopping the time loop

make sure to use client.loop_stop() function too, if we have used client.loop_start() function

And this is the script for client side. it also working fine with host=‘localhost’ but not receiving any text and it giving me an error when i put host=‘server ip’.

importing the library and creating the instance of the same

import sys
#import pandas as pd
import paho.mqtt.client as mqtt
import time

Taking the variables for the methods

client = mqtt.Client()
topicName = “aman/cdac/test”
QOS_val = 2
client.username_pw_set(username=“roger”,password=“password”)

--------------- Defining call backs---------------------------------------------------------------

def on_connect(pvtClient,userdata,flags,rc):
if(rc == 0): # on successful connection
print(“Connected to client! Return Code:”+str(rc)) # printing the data on the screen
# Once connection is established, subscribe to the topic
# important, here we are subscribing to a topic only after getting the authentication done
# further we are setting the QOS in the .subscribe(…) method
result = client.subscribe(topicName, QOS_val) # getting the Tuple from the call back
elif(rc ==5): # in case of authentication error
print("Authentication Error! Return Code: "+str(rc)) # printing the data on the screen
client.disconnect()

Call back for the message

This call-back will run whenever there is a message (payload) published on the given topic

def on_message(pvtClient, userdata, msg):
# here we are extracting details from the msg parameter,
print(“\n============================================”)
print("Payload : "+str(msg.payload.decode()))
print("Qos of message: "+str(msg.qos))
print("Message Topic : "+str(msg.topic))
print(“Message retain: “+str(msg.retain))
print(”============================================\n”)
if (str(msg.payload.decode()) == “exit(0)”):
client.disconnect()
sys.exit()
‘’’

currently not using this callback

def will_set(pvtClient, payload=“disconnected!!!”, qos=2, retain=False):
print("status: "+payload)
‘’’

this call back is used for the log generation

def on_log(topic, userdata, level, buf):
print("Logs: "+str(buf))

-------------------------------------------------------------------------------------------------------------

======== Associating the methods with the given callbacks of the MQTT ======

client.on_connect = on_connect
client.on_message = on_message
client.on_log = on_log
#client.will_set = will_set

============================================================================

host = “localhost”
port = 1883
keepAlive = 60
client.connect(host,port,keepAlive) # establishing the connection
time.sleep(2) # giving a sleep time for the connection to setup
client.loop_forever()

But both scripts are working when I’m using my laptop for running both client and server script. It also receiving message.

Please view it and let me know if you can do any help. thanks in advance.

@ans

You can install the HiveMQ broker on your laptop just for testing purposes but since you are already using Mosquito broker you can just change the host variable to the IP address where the broker is installed on your local network.

host = “YOU_MOSQUITTO_BROKER_IP_ADDRESS”

Kind regards,
Diego from HiveMQ Team

1 Like

I installed mosquitto broker on both raspberry pi’s. On one I’m running server script and on the second I’m running client script. And you are saying " change the host variable to the IP address where the broker is installed on your local network". So, the broker is installed on both pi’s. Now you want me to put the IP of raspberry pi on which I’m running a server in the client script and vise versa?

@ans

I think you are misunderstanding the MQTT Broker concepts here. You don’t need to install a broker on each Raspberry PI, MQTT Broker is not a “client/server” concept. The connection between both Raspberry PI’s devices is handled by one broker. The task of the broker is to filter all incoming messages and distribute them correctly to the subscribers. A client doesn’t have to pull the information it needs, the broker pushes the information to the client whenever something new is available.

Please refer to the article bellow for more information regarding MQTT.

Kind regards,
Diego from HiveMQ Team