Skip to content
Permalink
6d1eb6e6c4
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
42 lines (34 sloc) 1.15 KB
import paho.mqtt.client as mqtt
# Define the MQTT broker details
broker = 'test.mosquitto.org'
port = 1883
topic = "home/garage/door"
username = "user" # Replace with your MQTT broker username
password = "password" # Replace with your MQTT broker password
# Create a new MQTT client instance
client = mqtt.Client()
def on_connect(client, userdata, flags, rc):
if rc == 0:
print("Connected successfully to the broker")
client.subscribe(topic)
else:
print("Connection failed with code ", rc)
def on_message(client, userdata, msg):
command = msg.payload.decode()
if command == "open":
print("Opening the garage door...")
# Simulate opening the garage door
elif command == "close":
print("Closing the garage door...")
# Simulate closing the garage door
else:
print(f"Unknown command received: {command}")
# Set the on_connect and on_message callback functions
client.on_connect = on_connect
client.on_message = on_message
# Set username and password
client.username_pw_set(username, password)
# Connect to the broker
client.connect(broker, port)
# Start the loop
client.loop_forever()