diff --git a/relay.py b/relay.py new file mode 100644 index 0000000..913cdb0 --- /dev/null +++ b/relay.py @@ -0,0 +1,68 @@ +import RPi.GPIO as gpio +import time,sys +from paho.mqtt import client as mqtt_client + +#mqtt settings +broker = '192.168.2.2' +port = 1883 +uname = 'ecyhass' +pw = 'ecyhass1216' +topic_sensor = 'garage/door_sensor' +topic_control = 'garage/door_control' +client_id = str(210) + +#GPIO settings +relay_pin = 15 +sensor_pin = 19 +#gpio setup +gpio.setmode(gpio.BOARD) +gpio.setup(relay_pin,gpio.OUT) +gpio.setup(sensor_pin,gpio.IN,pull_up_down=gpio.PUD_DOWN) + +def mqtt_connect(): + def on_connect(client, userdata, flags, rc): + if rc == 0: + print("Connected to MQTT Broker") + else: + print("Failed to Connect MQTT") + + client = mqtt_client.Client(client_id) + client.username_pw_set(uname,pw) + client.on_connect = on_connect + client.connect(broker,port) + return client + +def mqtt_subscribe(client): + def on_message(client, userdata, msg): + print(f"Received `{msg.payload.decode()}` from `{msg.topic}` topic") + + client.subscribe(topic_control) + client.on_message = on_message + +def set_relay(value): + if value==1: + gpio.output(relay_pin,gpio.HIGH) + else: + gpio.output(relay_pin,gpio.LOW) + +def get_sensor(): + return gpio.input(sensor_pin) + +def set_from_sensor(): + set_relay(get_sensor()) + +def end(): + gpio.cleanup() + exit() + +def main(): + mqtt_subscribe(mqtt_connect()) + while(1): + continue +# set_from_sensor() +# time.sleep(.25) + + + +if __name__=="__main__": + main()