diff --git a/camdetect.py b/camdetect.py index 5069f10..d89f480 100755 --- a/camdetect.py +++ b/camdetect.py @@ -17,6 +17,7 @@ from jpeg2dct.numpy import loads from math import inf from motor.motor_asyncio import AsyncIOMotorClient from prometheus_client import Counter, Gauge, Histogram +from pymongo import ReturnDocument from sanic import Sanic, response from sanic_json_logging import setup_json_logging from sanic.log import logger @@ -256,17 +257,24 @@ async def motion_detector(reference_frame, download_queue, upload_queue): # Handle event start if motion_detected and not event_id: - result = await app.ctx.coll.insert_one({ - "timestamp": dt, - "event": "motion-detected", - "started": dt, - "finished": dt + timedelta(minutes=2), - "component": "camdetect", - "source": SOURCE_NAME, - "screenshots": [], - "action": "event", - }) - app.ctx.event_id = event_id = result.inserted_id + result = await app.ctx.coll.find_one_and_update({ + "timestamp": dt, # TODO: Account for clock skew + "source": SOURCE_NAME, + }, { + "$setOnInsert": { + "timestamp": dt, + "source": SOURCE_NAME, + "event": "motion-detected", + "started": dt, + "finished": dt + timedelta(minutes=2), + "component": "camdetect", + "screenshots": [], + "action": "event", + } + }, + upsert = True, + return_document=ReturnDocument.AFTER) + app.ctx.event_id = event_id = result["_id"] # Handle buffering frames prior event start if hold_queue.full(): @@ -507,6 +515,9 @@ def handler(signum, frame): async def setup_db(app, loop): app.ctx.db = AsyncIOMotorClient(MONGO_URI).get_default_database() app.ctx.coll = app.ctx.db[MONGO_COLLECTION] + app.ctx.coll.create_index([ + ("timestamp", pymongo.ASCENDING), + ("source", pymongo.ASCENDING)], unique=True) app.ctx.last_frame = None app.ctx.event_frame = asyncio.Event() app.ctx.event_id = None