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?
MQTT/Lovepreet Individual contribution
Go to fileThis commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
37 lines (28 sloc)
1.31 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
# 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 | |
# 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 ( manraj preet and lovepreet (me) ) worked together on this topic | |
# 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() |