diff --git a/main.py b/main.py index 1b022b3..ea6e08a 100644 --- a/main.py +++ b/main.py @@ -1,3 +1,10 @@ +import os +import logging +logging.basicConfig( + format='[%(asctime)s] %(levelname)s %(module)s/%(funcName)s - %(message)s', + level=logging.DEBUG if os.environ.get('DEBUG') else logging.INFO) +logging.getLogger('aiohttp').setLevel(logging.DEBUG if os.environ.get('DEBUG') else logging.WARNING) + import os import sys import asyncio @@ -10,9 +17,6 @@ import settings from pyunifiprotect.unifi_protect_server import UpvServer -import logging -logger = logging.getLogger(__name__) - RELAY_ON = False RELAY_OFF = True @@ -23,14 +27,14 @@ def ring_bell(mac): time.sleep(0.5) GPIO.output(doorbell['gpio'], RELAY_OFF) except KeyError: - logger.error('Doorbell %s not found!', mac) + logging.error('Doorbell %s not found!', mac) def subscriber(updated): - logger.debug('Subscription: updated=%s', updated) + logging.debug('Subscription: updated=%s', updated) for _, data in updated.items(): if data['event_type'] == 'ring' and data['event_ring_on']: - logger.info('%s: %s is ringing!', data['mac'], data['name']) + logging.info('%s: %s is ringing!', data['mac'], data['name']) ring_bell(data['mac']) async def ws_listener(): @@ -55,16 +59,29 @@ async def ws_listener(): await session.close() unsub() -def init_relays(): +def disable_relays_on_exit(*args): + logging.info('Exiting, disabling relays...') + for _, doorbell in settings.DOORBELLS.items(): + GPIO.output(doorbell['gpio'], RELAY_OFF) + logging.info('Goodbye.') + os._exit(0) + +def init(): GPIO.setmode(GPIO.BCM) GPIO.setwarnings(False) for _, doorbell in settings.DOORBELLS.items(): GPIO.setup(doorbell['gpio'], GPIO.OUT) GPIO.output(doorbell['gpio'], RELAY_OFF) + logging.info('GPIO initialized') + + for sig in (SIGABRT, SIGILL, SIGINT, SIGSEGV, SIGTERM): + signal(sig, disable_relays_on_exit) + logging.info('Signals initialized') if __name__ == '__main__': - logging.basicConfig(level=logging.INFO) + init() + loop = asyncio.get_event_loop() loop.run_until_complete(ws_listener()) loop.close()