You are on page 1of 5

LAB ASSIGNMENT 3-

(MQTT)

By- Suyash Agarwal


20BBS0123
Q1 MQTT

 Used MyMQTT app


 Code in python

Publisher

 I am publishing to my subscriber

MQTT broker settings


broker_address = "mqtt.eclipseprojects.io"
broker_port = 1883
topic = "test"
Code

import paho.mqtt.client as mqtt


# MQTT broker settings
broker_address = "mqtt.eclipseprojects.io"
broker_port = 1883
topic = "test"

# Callback when the client connects to the broker


def on_connect(client, userdata, flags, rc):
print("Connected with result code " + str(rc))

# Create a MQTT client


client = mqtt.Client()

# Set the callback


client.on_connect = on_connect

# Connect to the broker


client.connect(broker_address, broker_port, 60)

# Start the loop to maintain the connection


client.loop_start()

message = "Suyash da 20BBS0123"


client.publish(topic, message)
print("Message published:", message)

# Stop the MQTT client loop when done


client.loop_stop()
CONSUMER

 I am receiving from my subscriber

MQTT broker settings


broker_address = "mqtt.eclipseprojects.io"
broker_port = 1883
topic = "test"
Code

import paho.mqtt.client as mqtt

# MQTT broker settings


broker_address = "mqtt.eclipseprojects.io"
broker_port = 1883
topic = "test"

# Callback when the client connects to the broker


def on_connect(client, userdata, flags, rc):
print("Connected with result code " + str(rc))
client.subscribe(topic)

# Callback when a message is received from the subscribed topic


def on_message(client, userdata, msg):
print(f"Received message: {msg.payload.decode()}")

# Create a MQTT client


client = mqtt.Client()

# Set the callbacks


client.on_connect = on_connect
client.on_message = on_message

# Connect to the broker


client.connect(broker_address, broker_port, 60)

# Start the loop to process incoming messages


client.loop_forever()

You might also like