#!/bin/sh
# iemi-soak: the CricketOne board under load for a whole match day, logging heat, speed, lag and battery every minute.
# The same profiles as iemi-test (board-a1.env, board-pi.env). Plain POSIX sh, busybox and the tools iemi-test uses.
#
#   iemi-soak [--hours 10] [--load match|max] [--peer <address>] [--board a1|pi]
#
#   match  the camera streams at full rate all day, and the stump program runs if SOAK_PROGRAM names it
#          (for example SOAK_PROGRAM="python3 /home/pi/cricketone/clip_keeper.py");
#   max    the margin case: the camera at full rate, four busy cores, and the AI engine if SOAK_NPU_CMD names a
#          benchmark (for example the RKNN benchmark on a pose model); harder than any real program.
#   --peer an address on the same Wi-Fi (a phone or laptop) to time the network round trip every minute.
#
# Every SOAK_STEP seconds (60) it appends one line to soak-log.jsonl: the hottest chip zone, the CPU clock against its
# top (throttling), the camera's frame rate and lost frames, the Wi-Fi signal and round trip, the cell voltage, current
# and charge, and free memory. At the end, or on Ctrl-C, it judges the day and writes soak-result.json; the last line
# is PASS or FAIL.
#   heat     hottest zone never over SOAK_TEMP_MAX (90 C: the heat guard's start) and never over 95 C
#   speed    the camera at CAM_FPS_MIN (119) fps or more in every minute, no frame lost; the CPU never throttled
#   lag      Wi-Fi round trip 95 % under SOAK_RTT_MS (20 ms) when --peer is given
#   battery  the hours a full pack (PACK_MAH) lasts at the day's average draw from the gauge, SOAK_HOURS_MIN (10) or
#            more (needs the gauge, and the cells discharging; on a charger it is not judged)
# Throttling is the CPU's or the AI engine's top clock held below its rated top (the kernel's thermal cap), not the
# clock of the moment, which the governor lowers whenever the load is light.
# IEMI_SYSFS and IEMI_PROCFS (default /sys, /proc) point the readings at a stand-in tree (standin/run-standin).
set -u
VERSION="1.2 (8 Nov 2026)"
HERE=$(cd "$(dirname "$0")" && pwd)
HOURS=10; LOAD=match; PEER=""; BOARD=""
while [ $# -gt 0 ]; do
  case "$1" in
    --hours) HOURS="$2"; shift ;;
    --load) LOAD="$2"; shift ;;
    --peer) PEER="$2"; shift ;;
    --board) BOARD="$2"; shift ;;
    -h|--help) sed -n '2,24p' "$0"; exit 0 ;;
    *) echo "unknown option $1"; exit 2 ;;
  esac; shift
done
if [ -z "$BOARD" ]; then
  if grep -qi "raspberry" "${IEMI_PROCFS:-/proc}/device-tree/model" 2>/dev/null; then BOARD=pi; else BOARD=a1; fi
fi
PROFILE=""
for p in "$HERE/board-$BOARD.env" "/etc/iemi/board-$BOARD.env"; do [ -f "$p" ] && PROFILE="$p" && break; done
[ -n "$PROFILE" ] || { echo "no board profile board-$BOARD.env"; exit 2; }
# shellcheck disable=SC1090
. "$PROFILE"
OUT=${IEMI_OUT:-.}; LOGJ="$OUT/soak-log.jsonl"; RES="$OUT/soak-result.json"; TMP=${TMPDIR:-/tmp}/iemi-soak.$$
STEP=${SOAK_STEP:-60}; TOTAL=${SOAK_SECONDS:-$(awk "BEGIN{printf \"%d\", $HOURS * 3600}")}
TMAX=${SOAK_TEMP_MAX:-90}; RTT_MS=${SOAK_RTT_MS:-20}; FPS_MIN=${CAM_FPS_MIN:-119}
HMIN=${SOAK_HOURS_MIN:-10}; PACK=${PACK_MAH:-0}; SYS=${IEMI_SYSFS:-/sys}; PROC=${IEMI_PROCFS:-/proc}
mkdir -p "$TMP"; : > "$LOGJ"
PIDS=""
say() { echo "$(date '+%F %T') $*"; }
have() { command -v "$1" >/dev/null 2>&1; }

# ---------------------------------------------------------------- the load
cam_node=""; for c in ${CAMERAS:-}; do r=${c#*=}; cam_node=${r%%:*}; break; done
if [ -n "$cam_node" ] && have v4l2-ctl; then
  [ -n "${CAM_SETUP:-}" ] && sh -c "$CAM_SETUP A" > /dev/null 2>&1
  v4l2-ctl -d "$cam_node" --set-fmt-video=width="${CAM_W:-1280}",height="${CAM_H:-800}",pixelformat="${CAM_FMT:-GREY}" > /dev/null 2>&1
  v4l2-ctl -d "$cam_node" --stream-mmap=8 --stream-count=0 --stream-to=/dev/null > "$TMP/cam.txt" 2>&1 &
  PIDS="$PIDS $!"; say "camera $cam_node streaming at full rate"
else say "no camera in the profile: the camera is not loaded"; fi
if [ "$LOAD" = max ]; then
  for i in 1 2 3 4; do (while :; do :; done) & PIDS="$PIDS $!"; done; say "four busy cores"
  [ -n "${SOAK_NPU_CMD:-}" ] && { sh -c "while :; do $SOAK_NPU_CMD; done" > "$TMP/npu.txt" 2>&1 & PIDS="$PIDS $!"; say "AI engine: $SOAK_NPU_CMD"; }
elif [ -n "${SOAK_PROGRAM:-}" ]; then sh -c "$SOAK_PROGRAM" > "$OUT/soak-program.log" 2>&1 & PIDS="$PIDS $!"; say "program: $SOAK_PROGRAM"; fi
stop() { for p in $PIDS; do kill "$p" 2>/dev/null; done; }

# ---------------------------------------------------------------- one sample
hottest() { t=0; for z in "$SYS"/class/thermal/thermal_zone*/temp; do [ -r "$z" ] || continue; v=$(cat "$z" 2>/dev/null); [ "${v:-0}" -gt "$t" ] && t=$v; done; echo $((t / 1000)); }
clock_ratio() {  # the lowest allowed/rated top clock over the CPU policies and the AI engine, in %; 100 when unread
  # cpufreq: scaling_max_freq carries the thermal cap (freq QoS) and cpuinfo_max_freq is the rated top;
  # devfreq (the NPU): max_freq against the highest of available_frequencies. scaling_cur_freq is not used: the
  # governor lowers it whenever the load is light, which is not throttling.
  r=100; for p in "$SYS"/devices/system/cpu/cpufreq/policy*; do [ -r "$p/scaling_max_freq" ] && [ -r "$p/cpuinfo_max_freq" ] || continue
    c=$(cat "$p/scaling_max_freq"); m=$(cat "$p/cpuinfo_max_freq"); [ "$m" -gt 0 ] && q=$((100 * c / m)) && [ "$q" -lt "$r" ] && r=$q; done
  for d in "$SYS"/class/devfreq/*; do [ -r "$d/max_freq" ] && [ -r "$d/available_frequencies" ] || continue
    case "$(cat "$d/name" 2>/dev/null) ${d##*/}" in *npu*|*rknn*) ;; *) continue ;; esac
    c=$(cat "$d/max_freq"); m=$(tr ' ' '\n' < "$d/available_frequencies" | sort -n | tail -1)
    [ "${m:-0}" -gt 0 ] && q=$((100 * c / m)) && [ "$q" -lt "$r" ] && r=$q; done
  if have vcgencmd; then th=$(vcgencmd get_throttled 2>/dev/null | sed 's/.*=//'); [ -n "$th" ] && [ $((th & 0x6)) -ne 0 ] && r=0; fi
  echo "$r"
}
cam_last() {  # the last frame rate v4l2-ctl printed, and the frames lost so far
  tr '<\r' '\n\n' < "$TMP/cam.txt" 2>/dev/null | grep 'fps' > "$TMP/cam-lines.txt"
  f=$(grep -o '[0-9.]* fps' "$TMP/cam-lines.txt" | tail -1 | awk '{print $1}')
  l=$(grep -o 'dropped buffers: [0-9]*' "$TMP/cam-lines.txt" | awk '{s += $3} END {print s + 0}')   # per print: v4l2-ctl's fps_timestamps::dropped() resets
  echo "${f:-0} ${l:-0}"
}
word() { i2cget -y -f "$1" "$2" "$3" w 2>/dev/null; }   # -f: a bound gauge driver (max17042) must not hide the battery
gauge() {  # mV mA percent, or "- - -"
  [ -n "${GAUGE_ADDR:-}" ] && have i2cget || { echo "- - -"; return; }
  v=$(word "$MAIN_BUS" "$GAUGE_ADDR" 0x09); s=$(word "$MAIN_BUS" "$GAUGE_ADDR" 0x06); c=$(word "$MAIN_BUS" "$GAUGE_ADDR" 0x0A)
  [ -n "$v" ] || { echo "- - -"; return; }
  ci=$(printf '%d' "$c"); [ "$ci" -ge 32768 ] && ci=$((ci - 65536))
  echo "$(( $(printf '%d' "$v") * 78125 / 1000000 )) $(( ci * 15625 / (${RSENSE_MOHM:-10} * 10000) )) $(( $(printf '%d' "$s") / 256 ))"
}
wifi_signal() { have iw && [ -n "${WIFI_IF:-}" ] && iw dev "$WIFI_IF" link 2>/dev/null | grep -o 'signal: -[0-9]*' | grep -o '\-[0-9]*'; }
rtt() { [ -n "$PEER" ] && ping -c 3 -q "$PEER" 2>/dev/null | sed -n 's/.*= [0-9.]*\/\([0-9.]*\)\/.*/\1/p'; }
memfree() { awk '/MemAvailable/ {printf "%d", $2 / 1024}' "$PROC/meminfo" 2>/dev/null; }

# ---------------------------------------------------------------- the day
judge() {
  stop
  awk -v tmax="$TMAX" -v hmin="$HMIN" -v pack="$PACK" -v fmin="$FPS_MIN" -v rttms="$RTT_MS" -v peer="$PEER" -v ver="$VERSION" -v board="$BOARD" -v ld="$LOAD" '
    { n++
      t = $0; sub(/.*"temp":/, "", t); t += 0; if (t > T) T = t
      c = $0; sub(/.*"clock":/, "", c); c += 0; if (n == 1 || c < C) C = c
      f = $0; sub(/.*"fps":/, "", f); f += 0; if (n > 1) { if (nf == 0 || f < F) F = f; nf++ }
      l = $0; sub(/.*"lost":/, "", l); L = l + 0
      if ($0 ~ /"rtt":[0-9]/) { r = $0; sub(/.*"rtt":/, "", r); R[++nr] = r + 0 }
      if ($0 ~ /"ma":-?[0-9]/) { a = $0; sub(/.*"ma":/, "", a); A += a + 0; na++ }
      if ($0 ~ /"pct":[0-9]/) { p = $0; sub(/.*"pct":/, "", p); p += 0; if (np == 0) P0 = p; P1 = p; np++ }
      s = $0; sub(/.*"t":/, "", s); S = s + 0 }
    END {
      ok = 1; why = ""
      if (T > tmax) { ok = 0; why = why " hottest " T " C over " tmax " C;" }
      if (C < 95) { ok = 0; why = why " top clock (CPU or AI engine) capped at " C " % (throttled);" }
      if (nf > 0 && F < fmin) { ok = 0; why = why " camera fell to " F " fps;" }
      if (L > 0) { ok = 0; why = why " " L " frames lost;" }
      p95 = "null"
      if (nr > 0) { for (i = 1; i <= nr; i++) for (j = i + 1; j <= nr; j++) if (R[j] < R[i]) { x = R[i]; R[i] = R[j]; R[j] = x }
        k = int(0.95 * nr + 0.999); if (k < 1) k = 1; p95 = R[k]; if (p95 > rttms) { ok = 0; why = why " Wi-Fi round trip p95 " p95 " ms;" } }
      hours = "null"; socHours = "null"; mA = "null"
      if (np > 1 && S > 0 && P0 > P1) socHours = sprintf("%.1f", 100 / ((P0 - P1) / (S / 3600)))
      if (na > 0) { mA = sprintf("%.0f", A / na)
        if (pack > 0 && A / na < 0) { hours = sprintf("%.1f", pack / (-A / na)); if (hours + 0 < hmin) { ok = 0; why = why " a full pack lasts " hours " h at " (-mA) " mA, " hmin " h needed;" } } }
      printf "{\"tool\":\"iemi-soak\",\"version\":\"%s\",\"board\":\"%s\",\"load\":\"%s\",\"samples\":%d,\"seconds\":%d,\"hottestC\":%d,\"lowestClockPct\":%d,\"lowestFps\":%s,\"framesLost\":%d,\"rttP95ms\":%s,\"averageMa\":%s,\"projectedHours\":%s,\"socProjectedHours\":%s,\"verdict\":\"%s\",\"why\":\"%s\"}\n",
        ver, board, ld, n, S, T, C, (nf ? F : "null"), L, p95, mA, hours, socHours, (ok ? "PASS" : "FAIL"), why
    }' "$LOGJ" > "$RES"
  say "$(sed 's/.*"verdict":"\([A-Z]*\)".*"why":"\(.*\)"}/\1 \2/' "$RES")  -> $RES"
  rm -rf "$TMP"
  grep -q '"verdict":"PASS"' "$RES"
}
trap 'judge; exit $?' INT TERM

say "iemi-soak $VERSION on board $BOARD, load $LOAD, $TOTAL s, a sample every $STEP s -> $LOGJ"
t0=$(date +%s); next=$t0
while :; do
  now=$(date +%s); el=$((now - t0))
  set -- $(cam_last); fps=$1; lost=$2
  set -- $(gauge); mv=$1; ma=$2; pct=$3
  sig=$(wifi_signal); r=$(rtt); mem=$(memfree)
  printf '{"t":%d,"temp":%d,"clock":%d,"fps":%s,"lost":%d,"signal":%s,"rtt":%s,"mv":%s,"ma":%s,"pct":%s,"memMB":%s}\n' \
    "$el" "$(hottest)" "$(clock_ratio)" "${fps:-0}" "${lost:-0}" "${sig:-null}" "${r:-null}" \
    "$( [ "$mv" = - ] && echo null || echo "$mv")" "$( [ "$ma" = - ] && echo null || echo "$ma")" "$( [ "$pct" = - ] && echo null || echo "$pct")" "${mem:-null}" >> "$LOGJ"
  [ "$el" -ge "$TOTAL" ] && break
  next=$((next + STEP)); w=$((next - $(date +%s))); [ "$w" -gt 0 ] && sleep "$w"
done
judge
