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
from random import randint
from datetime import date, datetime
import time
from time import strftime
def on_log(client, userdata, level, buf): #log the subscriber considering the buffer
print("Log: ",buf)
def on_publish(client, userdata, mid):
print("Data published to broker") #print when data is successfully sent
print("publish mid:", mid, "\n") #print the message id of the publisher
# The callback for when the client receives a CONNACK response from the server.
def on_connect(client, userdata, flags, rc):
if rc == 0:
client.connected_flag = True #set the flag to true once connected
print("Connected with result code "+str(rc)) #check to know if we are connected to broker
print("Status[ON, OFF]")
else:
print("Bad connection, returned code= ", rc) #if connection failed
print("client disconnected ok")
def on_disconnect(client, userdata, rc):
print("Client disconnected")
client.connected_flag = False #set flag to false if disconnected
time.sleep(1) #wait before retrying connection
client1 = mqtt.Client(mqtt.CallbackAPIVersion.VERSION1, "motion-detector light sensor") # Create an MQTT client object
client1.connect("broker.hivemq.com", 1883)
client1.on_publish = on_publish
client1.on_log = on_log #set log function to print the messages
#client1.on_message = on_message #assign the on_messsage function
client1.on_connect = on_connect #assign the on_connect function to the callback attribute
client1.on_disconnect = on_disconnect
while True:
client1.loop_start()
result = randint(0,1)
if (result == 1):
lightStatus = "GREEN" #signify there is someone or a movement in the room
else:
lightStatus = "RED" #Signify no one or movement seen in the room
#print(status)
client1.publish("House/Light", lightStatus)
time.sleep(2) #wait for 2 seconds and then change the state of bulb