diff --git a/server.py b/server.py index 70da40e..de5b1a2 100644 --- a/server.py +++ b/server.py @@ -38,13 +38,18 @@ OPEN_ALERT_THRESHOLDS_MINUTES = [5, 15, 30, 60, 120] OPEN_ALERTS_SENT_FOR_CURRENT_OPENING = [] -def controller_message(message): +async def controller_message(app, message): payload = {mysecrets.CONTROLLER_KEY: message} logging.info('Controller message: %s', message) - r = requests.post(mysecrets.CONTROLLER_URL, data=payload, timeout=10) - if r.status_code == 200: - return True - else: + session = app['client_session'] + try: + async with session.post(mysecrets.CONTROLLER_URL, data=payload, timeout=10) as response: + if response.status == 200: + return True + else: + logging.error(f'Unable to communicate with controller! Message: {message}, Status: {response.status}') + return False + except Exception: logging.exception('Unable to communicate with controller! Message: ' + message) return False @@ -199,7 +204,7 @@ async def monitor_state_transitions(app): for threshold in OPEN_ALERT_THRESHOLDS_MINUTES: if open_duration_minutes >= threshold and threshold not in OPEN_ALERTS_SENT_FOR_CURRENT_OPENING: msg = f"ALERT: Garage door has been open for {threshold} minutes." - controller_message(msg) + await controller_message(app, msg) logging.info(msg) OPEN_ALERTS_SENT_FOR_CURRENT_OPENING.append(threshold) elif current_state == 'closed':