#!/usr/bin/env bash # cam-capture.sh — BULLETPROOF interval camera capture (systemd-supervised). # Runs as cam-capture.service (Restart=always). Works fully OFFLINE — needs no # internet, no dashboard, no Claude session. This is the "floor" (Layer 1) that # keeps the experiment's frames landing no matter what else on the board is up. # # Frame source, in order of preference: # 1) high-quality snapshot from the live-stream (ustreamer :8080) if it's up # — same single-camera-owner path the dashboard uses (best image quality); # 2) direct fswebcam grab from /dev/video0 (fallback: stream stopped/busy). # Either way the loop NEVER exits; systemd would respawn it in 5 s regardless. # # WHY THIS EXISTS: before 2026-07-03 capture was an unsupervised `tmux -s cap` # loop that grabbed ONLY via the stream. `systemctl stop cam-stream` during # dashboard work (07-01 13:32) silently starved it and killed a 26-day series # for ~2 days. A supervised service + real fallback makes that impossible. # See SYSTEM-STATE.md and memory data-capture-alert-protocol. set -u RES="${CAP_RES:-1920x1080}" DEV="${CAP_DEV:-/dev/video0}" IV="${CAP_INTERVAL:-600}" # seconds between frames (default 10 min) BASE="${CAP_BASE:-$HOME/captures}" MARK="$BASE/.last-capture" # cheap heartbeat marker for the watchdog RESUME_WINDOW=$(( IV * 3 )) # continue last session dir if it's this fresh mkdir -p "$BASE" # A service restart should CONTINUE the run, not fragment it into a new folder # (the user hated the many-folders mess). Reuse the newest session dir if it's warm. newest_dir=$(ls -dt "$BASE"/*/ 2>/dev/null | head -1) now=$(date +%s) if [ -n "$newest_dir" ]; then last=$(ls -t "$newest_dir"*.jpg 2>/dev/null | head -1) if [ -n "$last" ] && [ $(( now - $(stat -c %Y "$last") )) -lt "$RESUME_WINDOW" ]; then SESSION="${newest_dir%/}" n=$(ls "$SESSION"/*.jpg 2>/dev/null | sed -E 's#.*/0*([0-9]+)_.*#\1#' | sort -n | tail -1) n=$((10#${n:-0})) echo "resuming warm session $SESSION at frame $n" fi fi if [ -z "${SESSION:-}" ]; then SESSION="$BASE/$(date +%Y-%m-%d_%H%M%S)"; mkdir -p "$SESSION"; n=0 echo "new session $SESSION" fi grab() { # $1 = target file; 0 on a valid jpeg local f="$1" curl -sf --max-time 8 -o "$f" http://localhost:8080/snapshot 2>/dev/null \ && [ "$(stat -c%s "$f" 2>/dev/null || echo 0)" -gt 2000 ] && return 0 fswebcam -q -d "$DEV" -r "$RES" -p MJPEG --no-banner --jpeg 92 -S 5 "$f" 2>/dev/null \ && [ "$(stat -c%s "$f" 2>/dev/null || echo 0)" -gt 2000 ] && return 0 return 1 } echo "cam-capture up: $RES every ${IV}s -> $SESSION" while :; do n=$((n+1)) f="$SESSION/$(printf '%05d' "$n")_$(date +%Y-%m-%d_%H-%M-%S).jpg" if grab "$f"; then date +%s > "$MARK" echo "[$n] ${f##*/}" else rm -f "$f" # never leave a truncated/zero frame n=$((n-1)) # retry this index next tick echo "$(date '+%F %T') capture FAILED (stream + fswebcam both errored)" >&2 fi sleep "$IV" done