Resilient Pi Recording Architecture

Production Reference Manual for Hotplug-Safe Video & Audio Loop Logging

1. System Hardware & Metrics

This deployment outlines a headless, hardened Raspberry Pi architecture running Kali Linux (Rolling arm64). The system simultaneously captures standalone video and audio streams, writing directly to an external block storage device. It features full immunity to improper hard shutdowns, boot race conditions, and violent physical USB disconnects.

Hardware Blueprint

System Footprint Metrics

Subsystem Stream Data Bitrate / Wear Rate File Segment Boundary File Container Format
Video Loop (Motion) ~4.68 GB / hour 10 Minutes (600 seconds) Matroska (.mkv)
Audio Loop (arecord) ~318 MB / hour 10 Minutes (600 seconds) Waveform Audio (.wav)
Combined System Metrics ~5.00 GB / hour -- --
Storage Life Retention: Operating under a programmatic limit of 90% disk capacity (205 GB of working headroom), the system retains a running history window of approximately 41 hours before loop-recycling logic triggers.

2. Storage & Kernel Configuration

To eliminate file table breakdown and index corruption common during unexpected power losses, standard consumer filesystems (exFAT/FAT32) must be scrubbed in favor of an ext4 journaling layout.

Step 2.1: Purge Broken Kali Repository Infrastructure Keys

Inject valid security keyrings and strip broken legacy Raspberry Pi kernel mirrors that freeze the local package manager update processes:

sudo wget https://archive.kali.org/archive-keyring.gpg -O /usr/share/keyrings/kali-archive-keyring.gpg
sudo rm -f /etc/apt/sources.list.d/re4son.list
sudo apt clean && sudo apt update

Step 2.2: Apply Journaled File System Layout

sudo umount /mnt/usb
sudo mkfs.ext4 /dev/sda2

Step 2.3: Establish Static Filesystem Table Entry

Query the newly generated structural block UUID:

sudo blkid /dev/sda2

Open the system mount blueprint:

sudo nano /etc/fstab

Ensure any legacy lines targeting /mnt/usb are fully replaced with the following production entry:

UUID=4cd7c315-6a80-4fdb-a339-6dd8530ce3f2    /mnt/usb    ext4    defaults,nofail,noatime    0    2
Resilience Design: The nofail option guarantees that if the USB drive is detached during startup, the kernel continues to boot up fully rather than halting the entire operating system into an un-accessible rescue shell.

3. Video Loop Architecture

Video tracking leverages the Motion binary core to handle high-resolution hardware encoding. An embedded event handler automates storage monitoring loops.

Step 3.1: Install Motion Platform

sudo apt install motion -y

Step 3.2: Deploy Continuous Storage Pruning Engine

Create the file manager execution script:

sudo nano /usr/local/bin/cam_cleanup.sh

Paste the following automated management block:

#!/bin/bash
TARGET_DIR="/mnt/usb/dashcam"
MAX_USAGE=90 

CURRENT_USAGE=$(df "$TARGET_DIR" | awk 'NR==2 {print $5}' | tr -d '%')

while [ "$CURRENT_USAGE" -gt "$MAX_USAGE" ]; do
    OLDEST_FILE=$(find "$TARGET_DIR" -type f -name "*.mkv" -printf '%T@ %p\n' | sort -n | head -n 1 | cut -d' ' -f2-)
    
    if [ -n "$OLDEST_FILE" ]; then
        rm "$OLDEST_FILE"
        CURRENT_USAGE=$(df "$TARGET_DIR" | awk 'NR==2 {print $5}' | tr -d '%')
    else
        break
    fi
done
sudo chmod +x /usr/local/bin/cam_cleanup.sh

Step 3.3: Overwrite System Configuration

sudo truncate -s 0 /etc/motion/motion.conf
sudo nano /etc/motion/motion.conf

Inject this clean, optimized production structure:

daemon off
setup_mode off
log_level 6
log_type all

videodevice /dev/video0
v4l2_palette 17

width 1920
height 1080
framerate 15

emulate_motion on
threshold 0

movie_output on
movie_codec mkv
movie_max_time 600
movie_filename %Y%m%d_%H%M%S
picture_output off
webcontrol_port 0

target_dir /mnt/usb/dashcam

stream_port 8081
stream_localhost off
stream_maxrate 15
stream_auth_method 1
stream_authentication zsk009:chazambaa

on_movie_end /usr/local/bin/cam_cleanup.sh

Step 3.4: Configure Video Service Resiliency Overrides

Strip systemd dependency checking and configure a baseline aggressive restart policy:

sudo systemctl edit motion

Inject the following execution configuration properties exactly:

[Service]
Restart=always
RestartSec=10s

Set appropriate directory access mappings for the unprivileged system daemon profile account:

sudo mkdir -p /mnt/usb/dashcam
sudo chown -R motion:motion /mnt/usb/dashcam
sudo chmod 775 /mnt/usb/dashcam
sudo sed -i 's/start_motion_daemon=no/start_motion_daemon=yes/g' /etc/default/motion
sudo systemctl daemon-reload

4. Audio Loop Architecture

Audio recording runs via a native service capture thread isolated to user workspace spaces.

Step 4.1: Directory Workspace Execution Maps

sudo mkdir -p /mnt/usb/audio_logs
sudo chown -R kali:kali /mnt/usb/audio_logs
sudo chmod 775 /mnt/usb/audio_logs

Step 4.2: Build System Service Layer

sudo nano /etc/systemd/system/audiorecorder.service

Incorporate the target structural logic blueprint:

[Unit]
Description=Continuous USB Audio Recording
After=network.target local-fs.target

[Service]
Type=simple
User=kali
ExecStart=/usr/bin/arecord -D plughw:2,0 -f S16_LE -r 44100 -c 1 --max-file-time=600 --use-strftime /mnt/usb/audio_logs/audio-%%Y-%%m-%%d-%%H-%%M.wav
Restart=always
RestartSec=10

[Install]
WantedBy=multi-user.target
sudo systemctl daemon-reload

5. Hardware Hotplug Engine

To support unannounced physical storage removal without causing a system freeze, a custom udev rule fires a privileged host service to destroy stale open file locks and instantly restart the tracking pipelines on drive return.

Step 5.1: Deploy Host-Level Unplug Cleanup Service

sudo nano /etc/systemd/system/usb-unplug-cleanup.service
[Unit]
Description=Clear Zombie USB Mounts on Unplug
DefaultDependencies=no

[Service]
Type=oneshot
ExecStart=/bin/umount -l /mnt/usb

Step 5.2: Deploy Host-Level Plug Mount & Wake Service

sudo nano /etc/systemd/system/usb-plug-mount.service
[Unit]
Description=Mount USB and Force Restart Recorders on Plug
DefaultDependencies=no

[Service]
Type=oneshot
ExecStart=/bin/mount -a
ExecStart=/bin/systemctl restart motion audiorecorder.service

Step 5.3: Implement the Core Hardware Monitoring Rules

Create the udev routing logic:

sudo nano /etc/udev/rules.d/99-usb-zombie-clear.rules

Bind the physical hardware events directly to the systemd global host context services:

SUBSYSTEM=="block", ACTION=="remove", RUN+="/bin/systemctl start usb-unplug-cleanup.service"
SUBSYSTEM=="block", ACTION=="add", RUN+="/bin/systemctl start usb-plug-mount.service"

Force kernel hardware subsystem updates:

sudo systemctl daemon-reload
sudo udevadm control --reload-rules && sudo udevadm trigger

6. Operations & User Guide

Operational runbook for field manipulation and interaction with the live capture array.

Master Recording Toggle

Use the deployment switch script to completely control background service operation parameters:

~/toggle_video.sh

Running this script will dynamically reverse system execution profiles:

Altering loop retention thresholds

To scale storage thresholds, adjust the MAX_USAGE integer inside the cleanup file without taking the system offline:

sudo nano /usr/local/bin/cam_cleanup.sh
# Modify boundary value: MAX_USAGE=90

Accessing the Live Secure Video Feed

To securely access the camera feed over the local network via VLC Media Player, press Ctrl+N (Network Stream) and open the following authenticated endpoint:

http://zsk009:chazambaa@pipad.local:8081

7. Engineering Troubleshooting Matrix

Reference checklist for diagnostic assessment and system auditing.

Diagnostic Commands

Known Operational Failure States

Symptom: Target path reads as an un-readable 'Input/output error'

Root Cause: The external drive was disconnected while live write operations were running, trapping the system filesystem in a kernel zombie lock. Udev rules failed to escape their local daemon sandboxing container profiles.

Correction: Verify that the host service orchestration bridge is properly deployed under /etc/systemd/system/usb-unplug-cleanup.service and can be successfully triggered manually via sudo systemctl start usb-unplug-cleanup.service.

Symptom: Files look frozen (sizes are flat) following an un-announced physical re-plug

Root Cause: Systemd identified rapid failure loops during the unplug window and activated protective system rate-limiting restrictions (StartLimitBurst), which blocks automated system service retry attempts.

Correction: Upgrade the plug response script layer to pass manual execution overrides directly back to the daemons on reconnect. Ensure your usb-plug-mount.service file includes the necessary sequential reset instruction:

ExecStart=/bin/systemctl restart motion audiorecorder.service

Symptom: Audio stream crashes out with 'Permission Denied' errors

Root Cause: Re-partitioning tasks shifted the base folder level ownership attributes directly back to the administrative root account, blocking environment write execution clearance parameters for the lower-privilege standard user profile.

Correction: Restore specific storage tracking permissions for the operational user:

sudo chown -R kali:kali /mnt/usb/audio_logs