# in rc.local:
#   su pi -c 'python3 /home/pi/freezer.py >> /home/pi/freezer.log 2>&1 &'

import RPi.GPIO as GPIO
import urllib.request
import logging
import logging.handlers as handlers
import time
import cherrypy # https://docs.cherrypy.org/en/latest/tutorials.html#tutorial-1-a-basic-web-application
import requests, json


cherrypy.config.update({
    'server.socket_host' : '192.168.178.111',
    'server.socket_port' : 8081,
})

logger = logging.getLogger('Rotating Log')
logger.setLevel(logging.INFO)
logHandler = handlers.RotatingFileHandler('/home/pi/freezer.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)


PIN_REED_SENSOR = 21

GPIO.setmode(GPIO.BCM)
GPIO.setup(PIN_REED_SENSOR, GPIO.IN, GPIO.PUD_UP)


def door_change(channel):
    logger.info('open: ' + str(GPIO.input(PIN_REED_SENSOR) == 1).lower())


class FreezerService(object):
    @cherrypy.expose
    def index(self):

GPIO.add_event_detect(PIN_REED_SENSOR, GPIO.BOTH, callback=door_change, bouncetime=250)

logger.info('Initializing')

cherrypy.quickstart(FreezerService())
logger.info('Shutdown')
logger.info('Reset GPIO configuration and close')
GPIO.cleanup()
