Permalink
Cannot retrieve contributors at this time
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?
Cartrax/aircon.py
Go to fileThis commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
42 lines (36 sloc)
1.29 KB
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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() |