Skip to content
Permalink
main
Switch branches/tags

Name already in use

A tag already exists with the provided branch name. Many Git commands accept both tag and branch names, so creating this branch may cause unexpected behavior. Are you sure you want to create this branch?
Go to file
 
 
Cannot retrieve contributors at this time
import paho.mqtt.client as mqtt
import json
import random
import time
# MQTT broker details
broker_address = "broker.hivemq.com"
broker_port = 1883
topic = "home/temperature"
# Function to simulate temperature reading
def read_temperature():
# Simulate temperature reading between 20°C to 30°C
return round(random.uniform(20, 30), 2)
# Function to handle message received
def on_message(client, userdata, msg):
temperature_data = json.loads(msg.payload.decode())
temperature = temperature_data["temperature"]
print("Received temperature:", temperature, "°C")
if temperature > 25:
print("Temperature is high. Turn on AC?")
else:
print("Temperature is normal.")
# Main function to publish temperature
def publish_temperature():
client = mqtt.Client("Temperature_Client")
client.on_message = on_message
client.connect(broker_address, broker_port)
client.subscribe(topic)
client.loop_start()
while True:
temperature = read_temperature()
message = {"temperature": temperature}
client.publish(topic, json.dumps(message))
print("Published temperature:", temperature, "°C")
time.sleep(5) # Publish temperature every 5 seconds (adjust as needed)
# Run the function to publish temperature
publish_temperature()