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?
4005D.O/DoorSubscriber.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 (34 sloc)
1.15 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 | |
# 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() |