Resilient Pi Recording Architecture

Complete Reference Guide for Synchronous Video & Audio Loop Logging

1. System Hardware & Specifications

This deployment turns a mobile Raspberry Pi system running Kali Linux (Rolling arm64) into a highly resilient, independent loop recorder configured to mitigate storage exhaustion and recover instantly from arbitrary power disruptions.

Hardware Profile

System Performance Metrics

Resource Stream Data Consumption File Segment Duration Format Boundary
Video Loop (Motion) ~4.68 GB / hour 10 Minutes (600s) Matroska (.mkv)
Audio Loop (arecord) ~318 MB / hour 10 Minutes (600s) Waveform Audio (.wav)
Combined System Total ~5.00 GB / hour -- --
Storage Ceiling Estimate: At a custom safety execution boundary of 90% disk space (205 GB of usable headroom), the system maintains a running log window of approximately 41 to 42 hours before loop truncation processes execute.

2. OS Preparation & Storage Configuration

To avoid severe data corruption during aggressive power termination (pulling the plug), the external storage media must be provisioned with a journaling filesystem (ext4) rather than standard legacy Windows types (FAT32/exFAT).

Step 2.1: Resolve Kali Rolling Keyring & Repository Collapses

If local package trees throw validation faults or dead repository paths (such as legacy re4son mirrors) halt standard package installations, download the valid modern infrastructure signature and drop the legacy repository layout maps:

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: Establish File System Journaling

Warning: This step initializes raw blocks on partition /dev/sda2. Ensure any localized staging files have been mirrored off onto internal system space first.
sudo umount /mnt/usb
sudo mkfs.ext4 /dev/sda2

Step 2.3: Implement Persistent Multi-User Mount Mappings

Query the unique block identification token of your newly formatted storage partition:

sudo blkid /dev/sda2

Incorporate the identified UUID inside your persistent configuration table. Open the layout template file:

sudo nano /etc/fstab

Add the following configuration string directly at the bottom of the table file, ensuring any stale reference rules referencing /mnt/usb are fully removed:

UUID=4cd7c315-6a80-4fdb-a339-6dd8530ce3f2    /mnt/usb    ext4    defaults,nofail,noatime    0    2
Resilience Design Optimization: The nofail flag is critical for physical implementations. If the external drive is stripped away or encounters interface alignment damage, the operating system will step past the storage mounting tree and safely continue its primary core system boot process rather than throwing a system halt error.

Verify that the storage matrix resolves and binds into position flawlessly:

sudo mount -a

3. Continuous Video Loop Recorder

Continuous video pipeline compilation relies on the Motion software daemon to encode non-stop streaming frames straight to structural MKV segments. It fires a targeted housekeeping daemon automatically as each segment completes structural writing blocks.

Step 3.1: Package Provisioning

sudo apt install motion -y

Step 3.2: Construct the Storage Pruning Engine

Create the functional cleanup automation routine script:

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

Incorporate the precise structural logic script block below:

#!/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
' | 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

Lock structural execution capability to the file:

sudo chmod +x /usr/local/bin/cam_cleanup.sh

Step 3.3: Configuration Structure Injection

Completely flush out and overwrite the standard installation profile of your core video capture system configuration file:

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

Populate the file with this clean, optimized configuration:

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 your_username:your_password

on_movie_end /usr/local/bin/cam_cleanup.sh

Step 3.4: Resolve Device Mount Race Conditions

To avoid initialization failures where Motion fires up before the kernel completes device block registration, inject explicit dependencies via system entry overrides:

sudo systemctl edit motion

Drop the following parameter block rules directly into the configuration overlay:

[Unit]
RequiresMountsFor=/mnt/usb

[Service]
Restart=on-failure
RestartSec=10s

Enforce directory access requirements for the background isolated system user profile:

sudo mkdir -p /mnt/usb/dashcam
sudo chown -R motion:motion /mnt/usb/dashcam
sudo chmod 775 /mnt/usb/dashcam
sudo nano /etc/default/motion  # Set start_motion_daemon=yes
sudo systemctl daemon-reload

4. Continuous Audio Loop Recorder

The system runs audio stream recording in parallel, using the native system architecture profile under user space environment controls.

Step 4.1: Assign Directory Permission Mappings

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: Audit System Service Layer Configuration

For your records, verify that your service template file configuration accurately matches the blueprint structure located at /etc/systemd/system/audiorecorder.service:

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

[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

5. Operations & Control Guide

Use these operational controls to interact with your recording system during active deployment scenarios.

One-Touch Master Video Recording Switch

This localized script dynamically captures the current status of the recording engine, allowing you to easily toggle it on or off:

nano ~/toggle_video.sh

Inject the following script content:

#!/bin/bash
if systemctl is-active --quiet motion; then
    echo "🔴 Video recording is currently active. Disabling and stopping..."
    sudo systemctl stop motion
    sudo systemctl disable motion
    echo "❌ Disabled! Video service is stopped and will NOT run on reboot."
else
    echo "🟢 Video recording is currently stopped. Enabling and starting..."
    sudo systemctl enable motion
    sudo systemctl start motion
    echo "✅ Enabled! Video service is running and will survive reboots."
fi
chmod +x ~/toggle_video.sh

How to Adjust the Storage Thresholds

To scale back the storage window limit on the fly, edit the tracking ceiling line inside the script directly without restarting services:

sudo nano /usr/local/bin/cam_cleanup.sh
# Alter line variable: MAX_USAGE=90

Connecting via VLC Media Player

To watch the live video feed securely from any system connected to the local subnet:

  1. Open VLC Media Player.
  2. Press Ctrl+N (Network Stream).
  3. Input the secure network access URI:
http://your_username:your_password@<RASPBERRY_PI_IP>:8081

6. Comprehensive Troubleshooting Matrix

Consult this operational lookup index if the automated system tracking health states drop below functional limits.

Diagnostic Commands

Common Execution Failures

Symptom: Video recordings halt at 0 Bytes / Stream Failure error

Root Cause: Motion launched before device attachment loops closed, or folder write privileges were reset by an administrator task change.

Correction Steps: Confirm your override parameters match using systemctl cat motion. Re-assert absolute ownership parameters using:

sudo chown -R motion:motion /mnt/usb/dashcam

Symptom: Audio engine crashes with 'Permission Denied' fault logs

Root Cause: Storage formatting shifted core path folder properties directly back to root control, blocking write permission access for the lower-privilege system user account.

Correction Steps: Force execution environment space clearance settings back to the operational user:

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

Symptom: Audio service fails with 'No such file or directory' hardware target flags

Root Cause: Interface alignment shifts or system reboot cycles swapped the order of your USB capture devices, reassigned the audio target device index away from card 2.

Correction Steps: Audit your attached hardware configuration layers using:

arecord -l

Locate the index number assigned next to the device string labeled [USB Audio] and modify the plughw:X,0 statement target inside your system initialization service template configuration block accordingly.