# https://www.instructables.com/id/Arduino-Python-Communication-via-USB/
# in /etc/systemd/system/startup-commands.service (s. https://www.nodebucket.de/index.php/apps/cms_pico/pico/server/setup):
#   ExecStart = su tilman -c 'python3 /media/hd/admin/doorbell/doorbell.py >> /media/hd/admin/doorbell/doorbell.log 2>&1 &'

import serial
import urllib.request
import logging
import logging.handlers as handlers
import time
import json

logger = logging.getLogger('Rotating Log')
logger.setLevel(logging.INFO)
logHandler = handlers.RotatingFileHandler('/media/hd/admin/doorbell/doorbell.log', maxBytes=1000000, backupCount=2)
logHandler.setLevel(logging.INFO)
logHandler.setFormatter(logging.Formatter('%(asctime)s %(levelname)s - %(message)s', '%Y-%m-%d %H:%M:%S'))
logger.addHandler(logHandler)

logger.info('Initializing')


arduino = serial.Serial('/dev/Doorbell', 9600, timeout=.1)

while True:
    data = arduino.readline()[:-2] #the last bit gets rid of the new-line chars
    if data:
        try:
            data = data.decode('utf8')
        except (UnicodeDecodeError) as ude:
            logger.error(ude)
        else:
            logger.info(data)
        
        if (data == 'RING'):
            try:
                response = urllib.request.urlopen('http://192.168.178.60/bell/on', timeout=5).read().decode('utf-8')

                # send MQTT
                headers = {
                    "Authorization": "Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJjYjY5NjA5NmY0N2E0NmZlOGEzYjczOGYzYmUzOTk5ZSIsImlhdCI6MTY2MTM0NDgxOSwiZXhwIjoxOTc2NzA0ODE5fQ.z9fzbVOA1Pbur3Zb07481n-SoYesj8cetw-CX6WPmTs",
                    "Content-Type": "application/json"
                }
                data = json.dumps({'payload': 'RING', 'topic': 'lewe/doorbell', 'retain': 'False'}).encode('utf8')
                request = urllib.request.Request("https://www.nodebucket.de:8123/api/services/mqtt/publish", data, headers)
                response = urllib.request.urlopen(request)
            except Exception:
                logger.error("Could not ring doorbell")
                time.sleep(300)