Skip to content
Permalink
main
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
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")
else:
print("Connection failed with code ", rc)
# Set the on_connect callback function
client.on_connect = on_connect
# Set username and password
client.username_pw_set(username, password)
# Connect to the broker
client.connect(broker, port)
# Start the loop
client.loop_start()
# Function to publish a message
def send_command(command):
result = client.publish(topic, command)
status = result[0]
if status == 0:
print(f"Send `{command}` to topic `{topic}`")
else:
print(f"Failed to send message to topic {topic}")
if __name__ == "__main__":
try:
while True:
command = input("Enter command (open/close): ").strip().lower()
if command in ["open", "close"]:
send_command(command)
else:
print("Invalid command. Please enter 'open' or 'close'.")
except KeyboardInterrupt:
print("Disconnecting from broker")
client.loop_stop()
client.disconnect()