|
|
|
@@ -1,8 +1,13 @@
|
|
|
|
|
import os, logging
|
|
|
|
|
DEBUG = os.environ.get('DEBUG')
|
|
|
|
|
logging.basicConfig(
|
|
|
|
|
format='[%(asctime)s] %(levelname)s %(module)s/%(funcName)s - %(message)s',
|
|
|
|
|
level=logging.DEBUG if DEBUG else logging.INFO)
|
|
|
|
|
logging.getLogger('aiohttp').setLevel(logging.DEBUG if DEBUG else logging.WARNING)
|
|
|
|
|
|
|
|
|
|
import asyncio
|
|
|
|
|
import aiohttp
|
|
|
|
|
from aiohttp import web
|
|
|
|
|
import logging
|
|
|
|
|
import os
|
|
|
|
|
import io
|
|
|
|
|
from datetime import datetime
|
|
|
|
|
|
|
|
|
@@ -11,16 +16,13 @@ import torch.nn.functional as F
|
|
|
|
|
from torchvision import transforms
|
|
|
|
|
from PIL import Image
|
|
|
|
|
|
|
|
|
|
import mysecrets
|
|
|
|
|
from model import (CropLowerRightTriangle, GarageDoorCNN, TRIANGLE_CROP_WIDTH,
|
|
|
|
|
TRIANGLE_CROP_HEIGHT, RESIZE_DIM)
|
|
|
|
|
|
|
|
|
|
# --- Configuration ---
|
|
|
|
|
logging.basicConfig(level=logging.DEBUG, format='%(asctime)s - %(levelname)s - %(message)s')
|
|
|
|
|
|
|
|
|
|
BLUEIRIS_KEY = os.getenv('BLUEIRIS_KEY')
|
|
|
|
|
if not BLUEIRIS_KEY:
|
|
|
|
|
raise ValueError("BLUEIRIS_KEY environment variable not set.")
|
|
|
|
|
|
|
|
|
|
CAMERA_URL = "http://cameras.dns.t0.vc/image/SE-S?&w=9999&decode=1"
|
|
|
|
|
MODEL_PATH = 'garage_door_cnn.pth'
|
|
|
|
|
CLASS_NAMES = ['closed', 'open'] # From training, sorted alphabetically
|
|
|
|
@@ -29,6 +31,7 @@ REQUEST_TIMEOUT_SECONDS = 5
|
|
|
|
|
UNSURE_CONFIDENCE_THRESHOLD = 0.97
|
|
|
|
|
PREDICTION_HISTORY = []
|
|
|
|
|
PREDICTION_HISTORY_MAX_LENGTH = 3
|
|
|
|
|
PREVIOUS_STATE = "unknown"
|
|
|
|
|
|
|
|
|
|
# --- Model Inference ---
|
|
|
|
|
def get_prediction(model, image_bytes, device):
|
|
|
|
@@ -62,7 +65,7 @@ async def monitor_garage_door(app):
|
|
|
|
|
session = app['client_session']
|
|
|
|
|
model = app['model']
|
|
|
|
|
device = app['device']
|
|
|
|
|
headers = {'Authorization': 'Basic ' + BLUEIRIS_KEY}
|
|
|
|
|
headers = {'Authorization': 'Basic ' + mysecrets.BLUEIRIS_KEY}
|
|
|
|
|
|
|
|
|
|
while True:
|
|
|
|
|
try:
|
|
|
|
@@ -124,21 +127,44 @@ async def monitor_garage_door(app):
|
|
|
|
|
await asyncio.sleep(5)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
async def monitor_state_transitions(app):
|
|
|
|
|
"""Periodically checks for state transitions and logs them."""
|
|
|
|
|
global PREVIOUS_STATE
|
|
|
|
|
logging.info("Starting state transition monitoring task.")
|
|
|
|
|
while True:
|
|
|
|
|
try:
|
|
|
|
|
await asyncio.sleep(5)
|
|
|
|
|
current_state = get_derived_state()
|
|
|
|
|
if current_state != "unknown" and current_state != PREVIOUS_STATE:
|
|
|
|
|
logging.info(f"State transitioned from '{PREVIOUS_STATE}' to '{current_state}'.")
|
|
|
|
|
PREVIOUS_STATE = current_state
|
|
|
|
|
except asyncio.CancelledError:
|
|
|
|
|
logging.info("State transition monitoring task cancelled.")
|
|
|
|
|
break
|
|
|
|
|
except Exception as e:
|
|
|
|
|
logging.error(f"An unexpected error occurred in the state monitoring task: {e}", exc_info=True)
|
|
|
|
|
await asyncio.sleep(5)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
# --- Web Server ---
|
|
|
|
|
def get_derived_state():
|
|
|
|
|
"""Derives the state from the prediction history."""
|
|
|
|
|
state = "unknown"
|
|
|
|
|
if len(PREDICTION_HISTORY) == PREDICTION_HISTORY_MAX_LENGTH:
|
|
|
|
|
if all(s == "open" for s in PREDICTION_HISTORY):
|
|
|
|
|
state = "open"
|
|
|
|
|
elif all(s == "closed" for s in PREDICTION_HISTORY):
|
|
|
|
|
state = "closed"
|
|
|
|
|
return state
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
async def handle_root(request):
|
|
|
|
|
"""Handler for the root GET request."""
|
|
|
|
|
return web.Response(text="hello world")
|
|
|
|
|
|
|
|
|
|
async def handle_state(request):
|
|
|
|
|
"""Handler for the /state GET request."""
|
|
|
|
|
state = "unknown"
|
|
|
|
|
|
|
|
|
|
if len(PREDICTION_HISTORY) == PREDICTION_HISTORY_MAX_LENGTH:
|
|
|
|
|
if all(s == "open" for s in PREDICTION_HISTORY):
|
|
|
|
|
state = "open"
|
|
|
|
|
elif all(s == "closed" for s in PREDICTION_HISTORY):
|
|
|
|
|
state = "closed"
|
|
|
|
|
|
|
|
|
|
state = get_derived_state()
|
|
|
|
|
return web.Response(text=state)
|
|
|
|
|
|
|
|
|
|
async def on_startup(app):
|
|
|
|
@@ -160,13 +186,16 @@ async def on_startup(app):
|
|
|
|
|
|
|
|
|
|
# Start background task
|
|
|
|
|
app['monitor_task'] = asyncio.create_task(monitor_garage_door(app))
|
|
|
|
|
app['state_monitor_task'] = asyncio.create_task(monitor_state_transitions(app))
|
|
|
|
|
|
|
|
|
|
async def on_cleanup(app):
|
|
|
|
|
"""Actions to perform on application cleanup."""
|
|
|
|
|
logging.info("Cleaning up...")
|
|
|
|
|
app['monitor_task'].cancel()
|
|
|
|
|
app['state_monitor_task'].cancel()
|
|
|
|
|
try:
|
|
|
|
|
await app['monitor_task']
|
|
|
|
|
await app['state_monitor_task']
|
|
|
|
|
except asyncio.CancelledError:
|
|
|
|
|
pass
|
|
|
|
|
await app['client_session'].close()
|
|
|
|
|