# Python MQTT Publisher Example
import paho.mqtt.client as mqtt
import time
import random

# MQTT Broker settings
BROKER = "127.0.0.1"  # Local lab broker
PORT = 1883
TOPIC = "iotclass/sensors/temperature"

# Create MQTT client (paho-mqtt 2.0+ API)
client = mqtt.Client(mqtt.CallbackAPIVersion.VERSION2, client_id="TempSensor_001")

# Connect to broker
print(f"Connecting to {BROKER}...")
client.connect(BROKER, PORT)
client.loop_start()

# Publish temperature readings
try:
    while True:
        # Simulate temperature sensor
        temp = round(20 + random.uniform(-5, 5), 2)

        # Publish message
        message = client.publish(TOPIC, f"{temp}")
        message.wait_for_publish()
        print(f"Published: {temp}C to {TOPIC}")

        time.sleep(5)  # Wait 5 seconds

except KeyboardInterrupt:
    print("Stopping publisher...")
finally:
    client.disconnect()
    client.loop_stop()
