.Implement MQTT communication using both an online MQTT broker (HiveMQ) and a local offline MQTT broker (Eclipse Mosquitto)  to publish, receive, and display IoT sensor data.


mqtt_broker_demo/
│
├── publisher.py
└── subscriber.py

pip install paho-mqtt

publisher.py

import paho.mqtt.client as mqtt
import random
import json
import time

# Online HiveMQ broker
BROKER = "broker.hivemq.com"
PORT = 1883

TOPIC = "iot/environment/mca2026_demo"

def on_connect(client, userdata, flags, reason_code, properties):
    if reason_code == 0:
        print("Connected to HiveMQ Broker!")
    else:
        print("Connection failed:", reason_code)


# Create MQTT client
client = mqtt.Client(
    callback_api_version=mqtt.CallbackAPIVersion.VERSION2,
    protocol=mqtt.MQTTv311
)

client.on_connect = on_connect

try:
    print("Connecting to:", BROKER)

    client.connect(BROKER, PORT, 60)
    client.loop_start()

    while not client.is_connected():
        time.sleep(0.5)

    while True:

        # Generate sensor readings
        temperature = round(random.uniform(20, 40), 2)
        humidity = round(random.uniform(40, 90), 2)

        # Convert data into JSON
        data = {
            "temperature": temperature,
            "humidity": humidity
        }

        payload = json.dumps(data)

        # Publish sensor data
        result = client.publish(TOPIC, payload, qos=1)
        result.wait_for_publish()

        print("Published:", payload)

        time.sleep(5)

except KeyboardInterrupt:
    print("\nPublisher stopped.")

except Exception as e:
    print("Error:", e)

finally:
    client.loop_stop()
    client.disconnect()


subscriber.py

import paho.mqtt.client as mqtt
import json

# Online HiveMQ broker
BROKER = "broker.hivemq.com"
PORT = 1883

TOPIC = "iot/environment/mca2026_demo"


# Called when connected
def on_connect(client, userdata, flags, reason_code, properties):

    if reason_code == 0:
        print("Connected to HiveMQ Broker!")

        client.subscribe(TOPIC)
        print("Subscribed to:", TOPIC)

    else:
        print("Connection failed:", reason_code)


# Called when a message is received
def on_message(client, userdata, msg):

    try:
        data = json.loads(msg.payload.decode())

        temperature = data["temperature"]
        humidity = data["humidity"]

        print("\nReceived Sensor Data")
        print("Temperature:", temperature, "°C")
        print("Humidity:", humidity, "%")
        print("------------------------")

    except Exception as e:
        print("Error:", e)


# Create MQTT client
client = mqtt.Client(
    callback_api_version=mqtt.CallbackAPIVersion.VERSION2,
    protocol=mqtt.MQTTv311
)

client.on_connect = on_connect
client.on_message = on_message

print("Connecting to:", BROKER)

client.connect(BROKER, PORT, 60)

print("Waiting for messages...")

client.loop_forever()
