Skip to content

MQTT PROJECT CODING #4

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open

MQTT PROJECT CODING #4

wants to merge 1 commit into from

Conversation

kaurm105
Copy link
Owner

@kaurm105 kaurm105 commented Aug 1, 2024

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

broker = "broker.hivemq.com"
port = 1883
energy_topic = "home/energy"
temperature_topic = "home/temperature"

Publisher function for energy

def publish_energy_data(client):
while True:
energy_usage = random.uniform(0.5, 2.0) # Simulate energy usage in kWh
message = f"{energy_usage:.2f}"
client.publish(energy_topic, message)
print(f"Published Energy: {message} kWh")
time.sleep(5) # Publish every 5 seconds

Publisher function for temperature

def publish_temperature_data(client):
while True:
temperature = random.uniform(18.0, 30.0) # Simulate temperature in Celsius
message = f"{temperature:.2f}"
client.publish(temperature_topic, message)
print(f"Published Temperature: {message} °C")
time.sleep(5) # Publish every 5 seconds

Subscriber callback

def on_message(client, userdata, message):
topic = message.topic
payload = message.payload.decode()
if topic == energy_topic:
energy_usage = float(payload)
print(f"Received Energy: {energy_usage} kWh")
if energy_usage > 1.5:
print("High energy usage detected! Turning off non-essential devices.")
else:
print("Energy usage is within the normal range.")
elif topic == temperature_topic:
temperature = float(payload)
print(f"Received Temperature: {temperature} °C")
# Add any specific handling for temperature data here

def on_connect(client, userdata, flags, rc):
if rc == 0:
print("Connected to MQTT broker")
client.subscribe(energy_topic)
client.subscribe(temperature_topic)
else:
print(f"Failed to connect, return code {rc}")

Create and configure the subscriber client

subscriber_client = mqtt.Client()
subscriber_client.on_connect = on_connect
subscriber_client.on_message = on_message

Create and configure the publisher client

publisher_client = mqtt.Client()

Connect both clients to the broker

subscriber_client.connect(broker, port, 60)
publisher_client.connect(broker, port, 60)

Run the MQTT loop for the subscriber in a separate thread subscriber_thread = threading.Thread(target=subscriber_client.loop_forever) subscriber_thread.start()

Run the publisher functions in separate threads

energy_thread = threading.Thread(target=publish_energy_data, args=(publisher_client,)) temperature_thread = threading.Thread(target=publish_temperature_data, args=(publisher_client,))

energy_thread.start()
temperature_thread.start()

Wait for the threads to complete

energy_thread.join()
temperature_thread.join()

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

broker = "broker.hivemq.com"
port = 1883
energy_topic = "home/energy"
temperature_topic = "home/temperature"

# Publisher function for energy
def publish_energy_data(client):
    while True:
        energy_usage = random.uniform(0.5, 2.0)  # Simulate energy usage in kWh
        message = f"{energy_usage:.2f}"
        client.publish(energy_topic, message)
        print(f"Published Energy: {message} kWh")
        time.sleep(5)  # Publish every 5 seconds

# Publisher function for temperature
def publish_temperature_data(client):
    while True:
        temperature = random.uniform(18.0, 30.0)  # Simulate temperature in Celsius
        message = f"{temperature:.2f}"
        client.publish(temperature_topic, message)
        print(f"Published Temperature: {message} °C")
        time.sleep(5)  # Publish every 5 seconds

# Subscriber callback
def on_message(client, userdata, message):
    topic = message.topic
    payload = message.payload.decode()
    if topic == energy_topic:
        energy_usage = float(payload)
        print(f"Received Energy: {energy_usage} kWh")
        if energy_usage > 1.5:
            print("High energy usage detected! Turning off non-essential devices.")
        else:
            print("Energy usage is within the normal range.")
    elif topic == temperature_topic:
        temperature = float(payload)
        print(f"Received Temperature: {temperature} °C")
        # Add any specific handling for temperature data here

def on_connect(client, userdata, flags, rc):
    if rc == 0:
        print("Connected to MQTT broker")
        client.subscribe(energy_topic)
        client.subscribe(temperature_topic)
    else:
        print(f"Failed to connect, return code {rc}")

# Create and configure the subscriber client
subscriber_client = mqtt.Client()
subscriber_client.on_connect = on_connect
subscriber_client.on_message = on_message

# Create and configure the publisher client
publisher_client = mqtt.Client()

# Connect both clients to the broker
subscriber_client.connect(broker, port, 60)
publisher_client.connect(broker, port, 60)

# Run the MQTT loop for the subscriber in a separate thread
subscriber_thread = threading.Thread(target=subscriber_client.loop_forever)
subscriber_thread.start()

# Run the publisher functions in separate threads
energy_thread = threading.Thread(target=publish_energy_data, args=(publisher_client,))
temperature_thread = threading.Thread(target=publish_temperature_data, args=(publisher_client,))

energy_thread.start()
temperature_thread.start()

# Wait for the threads to complete
energy_thread.join()
temperature_thread.join()
Sign in to join this conversation on GitHub.
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

None yet

1 participant