Skip to content

Commit

Permalink
updated script for usage with magnet reed sensor
Browse files Browse the repository at this point in the history
  • Loading branch information
infinitel8p committed Sep 27, 2023
1 parent f544a3e commit cb2c86c
Show file tree
Hide file tree
Showing 2 changed files with 94 additions and 71 deletions.
53 changes: 53 additions & 0 deletions functions.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
import logging
import subprocess
from datetime import datetime

import bluetooth


def update_annotation(camera):
"""Update the annotation text on the camera."""
camera.annotate_text = datetime.now().strftime('%Y-%m-%d %H:%M:%S')


def is_device_connected_to_bt(bt_addresses):
"""Check if any of the given Bluetooth addresses are visible."""
for addr in bt_addresses:
status = bluetooth.lookup_name(addr, timeout=5)
if status:
logging.info(f"Device with Bluetooth address {addr} is connected.")
return True
return False


def is_in_ap_mode():
"""Check if the device is in AP mode."""
try:
output = subprocess.check_output(
"ip addr show ap0 | grep '192.168.10.1'", shell=True).decode('utf-8').strip()
return bool(output)
except Exception:
return False


def is_device_connected_to_ap(mac_addresses):
"""Check if any of the given MAC addresses are connected to the AP."""
if not is_in_ap_mode():
logging.warning("Device is not in AP mode.")
return False

try:
# Use the 'iw' command to get a list of connected devices
output = subprocess.check_output(
"iw dev ap0 station dump", shell=True).decode('utf-8').strip()

for mac in mac_addresses:
if mac in output:
logging.info(
f"Device with MAC address {mac} is connected to AP.")
return True

return False
except Exception as e:
logging.error(f"Error checking connected devices: {e}")
return False
112 changes: 41 additions & 71 deletions main.py
Original file line number Diff line number Diff line change
@@ -1,13 +1,17 @@
import bluetooth
import picamera
import time
import subprocess
from datetime import datetime
import logging
import json
import logging
import os
import time
from datetime import datetime

import picamera
import RPi.GPIO as GPIO
from dotenv import load_dotenv

from functions import *

logging.info("Initializing...")

# Set up logging with custom timestamp format
logging.basicConfig(level=logging.INFO,
format='%(asctime)s - %(levelname)s - %(message)s',
Expand Down Expand Up @@ -36,85 +40,51 @@

# Initialize the camera
camera = picamera.PiCamera()
filename = datetime.now().strftime('%Y-%m-%d_%H-%M-%S.h264')
camera.start_recording(filename)
recording = True
logging.info("Recording started.")


def update_annotation(camera):
"""Update the annotation text on the camera."""
camera.annotate_text = datetime.now().strftime('%Y-%m-%d %H:%M:%S')


def is_device_connected_to_bt(bt_addresses):
"""Check if any of the given Bluetooth addresses are visible."""
for addr in bt_addresses:
status = bluetooth.lookup_name(addr, timeout=5)
if status:
logging.info(f"Device with Bluetooth address {addr} is connected.")
return True
return False


def is_in_ap_mode():
"""Check if the device is in AP mode."""
try:
output = subprocess.check_output(
"ip addr show ap0 | grep '192.168.10.1'", shell=True).decode('utf-8').strip()
return bool(output)
except Exception:
return False


def is_device_connected_to_ap(mac_addresses):
"""Check if any of the given MAC addresses are connected to the AP."""
if not is_in_ap_mode():
return False

try:
# Use the 'iw' command to get a list of connected devices
output = subprocess.check_output(
"iw dev ap0 station dump", shell=True).decode('utf-8').strip()

for mac in mac_addresses:
if mac in output:
logging.info(
f"Device with MAC address {mac} is connected to AP.")
return True

return False
except Exception as e:
logging.error(f"Error checking connected devices: {e}")
return False
recording = False

# Set up GPIO
GPIO.setmode(GPIO.BCM)
GPIO.setwarnings(False)
Digital_Pin = 22
GPIO.setup(Digital_Pin, GPIO.IN)

# Enable timestamp on the video
camera.annotate_background = picamera.Color('black')
update_annotation(camera)

try:
while True:
# Update annotation
update_annotation(camera)
if GPIO.input(Digital_Pin):
logging.info("Door is closed.")

# Check if any of the smartphones' Bluetooth addresses are connected or if they're connected to the AP
if is_device_connected_to_bt(TARGET_BT_ADDRESSES) or is_device_connected_to_ap(TARGET_AP_MAC_ADDRESSES):
if recording:
logging.info("Device detected. Pausing recording.")
camera.stop_recording() # Pause recording
logging.info("Recording was in progress. Pausing recording.")
camera.stop_recording()
recording = False

else:
if not recording:
logging.info("No devices detected. Resuming recording.")
camera.start_recording(datetime.now().strftime(
'%Y-%m-%d_%H-%M-%S.h264')) # Resume recording
recording = True
logging.warning("Door is open.")

# Check if any of the smartphones' Bluetooth addresses are visible or if they're connected to the AP
if is_device_connected_to_bt(TARGET_BT_ADDRESSES) or is_device_connected_to_ap(TARGET_AP_MAC_ADDRESSES):
if recording:
logging.info("Device detected. Stop recording.")
camera.stop_recording()
recording = False
# If no device is connected, start recording
else:
if not recording:
logging.info("Device not detected. Start recording.")
camera.start_recording(
f"video_{datetime.now().strftime('%Y-%m-%d_%H-%M-%S')}.h264")
recording = True
time.sleep(1)

logging.info("Waiting for 5 seconds before checking again...")
time.sleep(5)

except KeyboardInterrupt:
camera.stop_recording()
camera.close()
logging.info("\nRecording stopped.")
logging.info("\nScript manually interrupted! Recording stopped.")

finally:
GPIO.cleanup()

0 comments on commit cb2c86c

Please sign in to comment.