# Python MQTT Subscriber Example
import paho.mqtt.client as mqtt

BROKER = "127.0.0.1"
PORT = 1883
TOPIC = "iotclass/sensors/temperature"

# Callback when connection is established (paho-mqtt 2.0+ signature)
def on_connect(client, userdata, flags, reason_code, properties):
    print(f"Connected with reason code {reason_code}")
    client.subscribe(TOPIC)
    print(f"Subscribed to {TOPIC}")

# Callback when message is received
def on_message(client, userdata, msg):
    temp = float(msg.payload.decode())
    print(f"Received: {temp}C from {msg.topic}")

    # Alert if temperature is too high
    if temp > 25:
        print("Warning: High temperature detected!")

# Create and configure client (paho-mqtt 2.0+ API)
client = mqtt.Client(mqtt.CallbackAPIVersion.VERSION2, client_id="Dashboard_001")
client.on_connect = on_connect
client.on_message = on_message

# Connect and start listening
client.connect(BROKER, PORT)
client.loop_forever()  # Block and listen for messages
