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
import time
def on_connect(client, userdata, flags, rc): #client method to connect
if rc == 0:
client.connected_flag = True #set the flag
print("Connected, returned code ", rc) #check to know if we are connected to broker
else:
print("Bad connection, returned code= ", rc) #if connection failed
def on_disconnect(client, userdata, mid):
print("Client disconnected ok")
time.sleep(1) #wait before retrying connection
# callback function when a PUBLISH message is received from the MQTT server
def on_message(client, userdata, message):
print("Received message: ", str(message.payload.decode("utf-8")))
if message.payload.decode("utf-8") == "GREEN" :
print("Turning Light bulb ON now...")
else :
print("Turning Light bulb OFF now...")
client2 = mqtt.Client(mqtt.CallbackAPIVersion.VERSION1,"light-sensor bulbs")
client2.on_connect = on_connect #registers the on_connect function with the client
client2.connect('broker.hivemq.com',1883) #connect the client to the broker at an appropriate project
client2.disconnect = on_disconnect
client2.on_message = on_message
while True:
client2.loop_start() #start the loop
client2.subscribe("House/Light")