import RPi.GPIO as GPIO
import Adafruit_DHT as dht
import time
import paho.mqtt.client as mqtt
# Set GPIO PIN NUMBER
BUTTON = 19
LED = 21
DHT = 26
FAN = 20
press = False
def on_connect(client, userdata, flags, rc):
print("Connected with result code" + str(rc))
client.subscribe("homenet/Sensor1/phone")
def on_message(client, userdata, msg):
temp = str(msg.payload)
print(msg.topic+" "+temp)
if temp == "b\'off\'":
GPIO.output(LED, GPIO.LOW)
GPIO.output(FAN, GPIO.HIGH)
elif temp == "b\'on\'":
GPIO.output(LED, GPIO.HIGH)
GPIO.output(FAN, GPIO.LOW)
else:
print("wrong msg. send again\n")
def press_button_callback(channel):
global press
press = 1 - press
if press:
print("button ON")
GPIO.output(LED, GPIO.HIGH)
GPIO.output(FAN, GPIO.LOW)
# Send msg to mqtt
client.publish("homenet/Sensor1/LED", 'ON')
else:
print("button OFF")
GPIO.output(LED, GPIO.LOW)
GPIO.output(FAN, GPIO.HIGH)
client.publish("homenet/Sensor1/LED", 'OFF')
# Set GPIO
GPIO.setmode(GPIO.BCM)
GPIO.setwarnings(False)
GPIO.setup(LED, GPIO.OUT, initial=GPIO.LOW)
GPIO.setup(BUTTON, GPIO.IN)
GPIO.add_event_detect(BUTTON, GPIO.FALLING,callback=press_button_callback, bouncetime=10)
GPIO.setup(FAN, GPIO.OUT, initial=GPIO.HIGH)
try:
# Set mqtt
client = mqtt.Client()
client.on_connect = on_connect
client.on_message = on_message
# Set up mqtt IP address
client.connect("192.168.*.*", 1883, 60)
while 1:
#mqtt msg listen!
client.loop()
humidity, temperature = dht.read_retry(dht.DHT11, DHT)
print("temp:{}, hum:{}".format(temperature, humidity))
# send dht data to mqtt
client.publish("homenet/Sensor1/temperature", temperature)
client.publish("homenet/Sensor1/humidity", humidity)
if temperature < 23:
GPIO.output(LED, GPIO.LOW)
GPIO.output(FAN, GPIO.HIGH) # motor off
finally:
GPIO.cleanup()