Mercurial > code > home > repos > doorbell
diff doorbell_to_mqtt.py @ 0:7bd85b962845
start
author | drewp@bigasterisk.com |
---|---|
date | Sat, 21 Jan 2023 21:59:14 -0800 |
parents | |
children | f822e7fe7120 |
line wrap: on
line diff
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/doorbell_to_mqtt.py Sat Jan 21 21:59:14 2023 -0800 @@ -0,0 +1,60 @@ +import time +import logging +import sys +import paho.mqtt.client as mqtt +from pyfirmata import Arduino, INPUT + +PULLUP = 0x0b + +MIN_REPEAT_SEC = .5 + +logging.basicConfig(level=logging.INFO) +log = logging.getLogger() + +dev, = sys.argv[1:] + +client = mqtt.Client() +client.will_set('doorbell/online', '0', qos=0, retain=False) +client.connect('bang') + +log.info(f'connecting to {dev}') +# note that I set StandardFirmata to double baud rate +board = Arduino(dev, baudrate=115200) +log.info('done') + +pin = board.get_pin('d:2:i') +pin.mode = PULLUP # config msg to send to firmata +pin._mode = INPUT # fake value so pyfirmata still reads this pin + +log.info('running mqtt client') +client.loop_start() +log.info('done') + +client.publish('doorbell/online', '1') + +last_value = None +last_edge = 0 + + +def on_press(t): + global last_edge + if t > last_edge + MIN_REPEAT_SEC: + log.info(f'press {t=}') + client.publish('doorbell/button', 'press') + log.info('published') + last_edge = t + + +try: + while True: + now = time.time() + board.iterate() + value = pin.read() + if value == 0 and last_value == 1: + on_press(now) + last_value = value + client.loop() +except Exception: + client.publish('doorbell/online', '0') + client.disconnect() + raise \ No newline at end of file