multiple fixes and improvements. ready to deploy

This commit is contained in:
2023-09-22 02:19:14 +03:30
parent 86091bdafb
commit 828fe5385d

View File

@@ -3,9 +3,9 @@ import time
import requests import requests
import numpy as np import numpy as np
from datetime import datetime from datetime import datetime
import os
import json import json
import logging as lg import logging as lg
import logging.handlers as lg_handlers
import argparse import argparse
class CameraMonitor: class CameraMonitor:
@@ -13,20 +13,28 @@ class CameraMonitor:
self.config = config self.config = config
self.logger = logger self.logger = logger
self.last_detection = 0 self.last_detection = 0
self.capture = self.initialize_camera()
def initialize_camera(self): def initialize_camera(self):
""" """
Initialize the camera and return the VideoCapture object. Initialize the camera and return the VideoCapture object.
""" """
cap = cv2.VideoCapture(self.config['camera_address']) cap = cv2.VideoCapture(
self.config['camera_address'],
cv2.CAP_V4L2
)
if not cap.isOpened(): if not cap.isOpened():
raise Exception(f"Failed to open camera at {self.config['camera_address']}") raise Exception(f"Failed to open camera at {self.config['camera_address']}")
self.logger.info("Camera initialized")
print("Camera initialized")
return cap return cap
def log_scene_change(self): def log_scene_change(self):
""" """
Log a scene change notification to the Scenesense server. Log a scene change notification to the Scenesense server.
""" """
self.logger.info(f'Scene change detected')
# print("Scene change detected")
current_time = int(time.time()) current_time = int(time.time())
human_readable_time = datetime.utcfromtimestamp( human_readable_time = datetime.utcfromtimestamp(
current_time current_time
@@ -49,11 +57,20 @@ class CameraMonitor:
headers=headers headers=headers
) )
response.raise_for_status() response.raise_for_status()
self.logger.info(f'Scene change logged: {description}') self.logger.info(
f'Scene change logged to server db: {description}'
)
# print(f'Scene change logged: {description}')
self.last_detection = current_time
except requests.exceptions.RequestException as e: except requests.exceptions.RequestException as e:
self.logger.error(f'Error connecting to Scenesense server: {e}') self.logger.error(f'Error connecting to Scenesense server: {e}')
# print(f'Error connecting to Scenesense server: {e}')
except requests.exceptions.HTTPError as e: except requests.exceptions.HTTPError as e:
self.logger.error(f'HTTP error: {e}') self.logger.error(f'HTTP error: {e}')
# print(f'HTTP error: {e}')
def detect_scene_change(self, previous_frame, current_frame): def detect_scene_change(self, previous_frame, current_frame):
""" """
@@ -61,29 +78,42 @@ class CameraMonitor:
""" """
frame_diff = cv2.absdiff(previous_frame, current_frame) frame_diff = cv2.absdiff(previous_frame, current_frame)
mean_diff = np.mean(frame_diff) mean_diff = np.mean(frame_diff)
return mean_diff > self.config['sensitivity_threshold'] threshold = self.config['sensitivity_threshold']
# self.logger.info(
# f'Frame Diff: {frame_diff}\nMean Diff: {mean_diff}\nSensitivity Threshold: {threshold}'
# )
# print(
# f'Frame Diff: {frame_diff}\nMean Diff: {mean_diff}\nSensitivity Threshold: {threshold}'
# )
return mean_diff > threshold
def run(self): def run(self):
self.logger.info("Camera Monitor started")
print("Camera Monitor started")
try: try:
with self.initialize_camera() as cap: previous_frame = None
previous_frame = None
while True: while True:
ret, current_frame = cap.read() ret, current_frame = self.capture.read()
if not ret: if not ret:
raise Exception("Failed to read frame") raise Exception("Failed to read frame")
if previous_frame is not None: if previous_frame is not None:
if self.detect_scene_change(previous_frame, current_frame): if self.detect_scene_change(previous_frame, current_frame):
self.log_scene_change() self.log_scene_change()
previous_frame = current_frame
previous_frame = current_frame
except KeyboardInterrupt: except KeyboardInterrupt:
self.logger.info("Camera monitoring stopped by user.") self.logger.info("Camera monitoring stopped by user.")
print("Camera monitoring stopped by user.")
except Exception as e: except Exception as e:
self.logger.error(f"An error occurred: {e}") self.logger.error(f"An error occurred: {e}")
# print(f"An error occurred: {e}")
finally:
self.capture.release()
def parse_command_line_args(): def parse_command_line_args():
parser = argparse.ArgumentParser(description='Camera Monitor for Scenesense') parser = argparse.ArgumentParser(description='Camera Monitor for Scenesense')
@@ -100,14 +130,12 @@ def load_config(config_path):
raise Exception(f"Invalid JSON format in config file: {config_path}") raise Exception(f"Invalid JSON format in config file: {config_path}")
def setup_logging(log_file='logs/camera_monitor.log'): def setup_logging(log_file='logs/camera_monitor.log'):
# logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(name)s - %(levelname)s - %(message)s')
# return logging.getLogger('CameraMonitor')
# Configure the logger # Configure the logger
logger = lg.getLogger('CameraMonitor') logger = lg.getLogger('CameraMonitor')
logger.setLevel(lg.INFO) logger.setLevel(lg.INFO)
# Create a TimedRotatingFileHandler for log rotation # Create a TimedRotatingFileHandler for log rotation
file_handler = lg.handlers.TimedRotatingFileHandler( file_handler = lg_handlers.TimedRotatingFileHandler(
log_file, when='midnight', backupCount=7 log_file, when='midnight', backupCount=7
) # Keeps logs for 7 days ) # Keeps logs for 7 days
file_handler.suffix = '%Y-%m-%d' # Append date to log file names file_handler.suffix = '%Y-%m-%d' # Append date to log file names