Improve logging, disable relays on exit

This commit is contained in:
Tanner Collin 2021-10-15 15:18:27 -06:00
parent eed4d6f63b
commit 8874a80ae2

33
main.py
View File

@ -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 os
import sys import sys
import asyncio import asyncio
@ -10,9 +17,6 @@ import settings
from pyunifiprotect.unifi_protect_server import UpvServer from pyunifiprotect.unifi_protect_server import UpvServer
import logging
logger = logging.getLogger(__name__)
RELAY_ON = False RELAY_ON = False
RELAY_OFF = True RELAY_OFF = True
@ -23,14 +27,14 @@ def ring_bell(mac):
time.sleep(0.5) time.sleep(0.5)
GPIO.output(doorbell['gpio'], RELAY_OFF) GPIO.output(doorbell['gpio'], RELAY_OFF)
except KeyError: except KeyError:
logger.error('Doorbell %s not found!', mac) logging.error('Doorbell %s not found!', mac)
def subscriber(updated): def subscriber(updated):
logger.debug('Subscription: updated=%s', updated) logging.debug('Subscription: updated=%s', updated)
for _, data in updated.items(): for _, data in updated.items():
if data['event_type'] == 'ring' and data['event_ring_on']: 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']) ring_bell(data['mac'])
async def ws_listener(): async def ws_listener():
@ -55,16 +59,29 @@ async def ws_listener():
await session.close() await session.close()
unsub() 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.setmode(GPIO.BCM)
GPIO.setwarnings(False) GPIO.setwarnings(False)
for _, doorbell in settings.DOORBELLS.items(): for _, doorbell in settings.DOORBELLS.items():
GPIO.setup(doorbell['gpio'], GPIO.OUT) GPIO.setup(doorbell['gpio'], GPIO.OUT)
GPIO.output(doorbell['gpio'], RELAY_OFF) 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__': if __name__ == '__main__':
logging.basicConfig(level=logging.INFO) init()
loop = asyncio.get_event_loop() loop = asyncio.get_event_loop()
loop.run_until_complete(ws_listener()) loop.run_until_complete(ws_listener())
loop.close() loop.close()