#!/usr/bin/env bash # Run a CAN benchmark AND a diagnostic battery that says *why* the number is what # it is — not just what it is. # # Usage: # ./run_test.sh [duration] [master_if] [slave_if] [flags] # ./run_test.sh [duration] [master_if] --monitor-only (slave_if not needed) # # e.g. ./run_test.sh 500000 60 can_com3 can_com4 --configure --monitor # ./run_test.sh 1000000 600 can0 can1 --full # ./run_test.sh 500000 0 can0 can1 --probe-only # dien giai nhanh ~90s # # Flags (throughput run): # --configure set the bitrate via setup_can.sh first (needs sudo) # --monitor run can-utils in parallel as a cross-check (canbusload, candump -e, ip -s) # --monitor-only PASSIVE observation only; transmits nothing. Safe on a live bus. # # Flags (diagnostic battery — all of these TRANSMIT, never valid with --monitor-only): # --gap inter-frame gap histogram on the wire -> what paces the link # --burst burst probe: does the adapter buffer frames, or is every # frame serialised? (separates a driver limit from a firmware wall) # --dlc-sweep fps vs DLC 0/1/2/4/8 -> is the limit per-BIT or per-FRAME? # --duplex both interfaces transmit at once -> per-channel or per-link limit? # --rate-sweep[=L] fps vs bitrate (default 125000,250000,500000,1000000). # Needs --configure (sudo) because it reconfigures the link. # --full = --monitor --gap --burst --dlc-sweep --duplex # --probe-only skip the C# throughput run, do the battery only (fast triage) # --probe-secs N seconds per probe point (default 6) # # An adapter/driver/USB fingerprint is ALWAYS captured (read-only, harmless), and # a verdict.md is written classifying the bottleneck from the measurements. # # Every file from one invocation lands in a single per-run directory: # results/-__/ set -euo pipefail ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)" RESULTS="$ROOT/results" mkdir -p "$RESULTS" # ---------------------------------------------------------------- flag parsing CONFIGURE=""; MONITOR=""; MONITOR_ONLY="" DO_GAP=""; DO_BURST=""; DO_DLC=""; DO_DUPLEX=""; DO_RATE=""; PROBE_ONLY="" RATE_LIST="125000,250000,500000,1000000" PROBE_SECS=6 POS=() for a in "$@"; do case "$a" in --configure) CONFIGURE="--configure" ;; --monitor) MONITOR="1" ;; --monitor-only) MONITOR_ONLY="1"; MONITOR="1" ;; --gap) DO_GAP="1" ;; --burst) DO_BURST="1" ;; --dlc-sweep) DO_DLC="1" ;; --duplex) DO_DUPLEX="1" ;; --rate-sweep) DO_RATE="1" ;; --rate-sweep=*) DO_RATE="1"; RATE_LIST="${a#*=}" ;; --probe-secs=*) PROBE_SECS="${a#*=}" ;; --probe-only) PROBE_ONLY="1"; DO_GAP="1"; DO_BURST="1"; DO_DLC="1"; DO_DUPLEX="1" ;; --full) MONITOR="1"; DO_GAP="1"; DO_BURST="1"; DO_DLC="1"; DO_DUPLEX="1" ;; --*) echo "!! unknown flag: $a" >&2; exit 2 ;; *) POS+=("$a") ;; esac done BITRATE="${POS[0]:?usage: run_test.sh [duration] [master_if] [slave_if] [--full|--probe-only|...]}" DURATION="${POS[1]:-60}" MASTER_IF="${POS[2]:-can_com3}" SLAVE_IF="${POS[3]:-can_com4}" # The battery transmits. Refusing here is the whole point of --monitor-only. if [ -n "$MONITOR_ONLY" ] && [ -n "${DO_GAP}${DO_BURST}${DO_DLC}${DO_DUPLEX}${DO_RATE}${PROBE_ONLY}" ]; then echo "!! --monitor-only is passive; it cannot be combined with probes that transmit." >&2 exit 2 fi if [ -n "$DO_RATE" ] && [ -z "$CONFIGURE" ]; then echo ">> --rate-sweep needs --configure (it changes the link bitrate); skipping the sweep." DO_RATE="" fi HAVE_PROBES="${DO_GAP}${DO_BURST}${DO_DLC}${DO_DUPLEX}${DO_RATE}" if [ -n "$HAVE_PROBES" ]; then for t in cangen candump; do command -v "$t" >/dev/null || { echo "!! '$t' not found (install can-utils) — probes disabled." >&2; HAVE_PROBES=""; DO_GAP=""; DO_BURST=""; DO_DLC=""; DO_DUPLEX=""; DO_RATE=""; break; } done fi RUN_TS="$(date +%Y%m%d-%H%M%S)" RUN_DIR="$RESULTS/${MASTER_IF}-${SLAVE_IF}_${BITRATE}_${RUN_TS}" # Two subdirectories per run: # log/ every raw artefact (C# logs, candump captures, ip counters, probe dumps) # report/ short markdown written FROM those artefacts, so nobody has to read them LOG_DIR="$RUN_DIR/log" REPORT_DIR="$RUN_DIR/report" mkdir -p "$LOG_DIR" "$REPORT_DIR" echo ">> run directory: $RUN_DIR" echo " log/ raw artefacts" echo " report/ quick-read markdown" MASTER_BIN="$ROOT/CanMaster/bin/Release/net10.0/CanMaster" SLAVE_BIN="$ROOT/CanSlave/bin/Release/net10.0/CanSlave" # ------------------------------------------------------------------- CAN maths # Classic CAN 2.0A data frame, standard ID, incl. the 3-bit inter-frame space: # SOF 1 + ID 11 + RTR 1 + IDE 1 + r0 1 + DLC 4 + data 8d + CRC 15 + CRCdel 1 # + ACK 1 + ACKdel 1 + EOF 7 + IFS 3 = 47 + 8d # Worst-case bit stuffing adds floor((34 + 8d - 1) / 4) stuff bits. nominal_bits() { awk -v d="$1" 'BEGIN{printf "%d", 47 + 8*d}'; } worst_bits() { awk -v d="$1" 'BEGIN{printf "%d", 47 + 8*d + int((34 + 8*d - 1)/4)}'; } theo_fps() { awk -v b="$1" -v n="$2" 'BEGIN{ if(n>0) printf "%.0f", b/n; else print 0 }'; } # ------------------------------------------------------- sysfs / driver probing txpkts() { ip -s link show "$1" 2>/dev/null | awk '/TX:/{getline; print $2; exit}'; } rxpkts() { ip -s link show "$1" 2>/dev/null | awk '/RX:/{getline; print $2; exit}'; } # Walk up the device tree until a node carrying a USB vendor id is found. usb_root_of() { local p; p="$(readlink -f "/sys/class/net/$1/device" 2>/dev/null)" || return 1 while [ -n "$p" ] && [ "$p" != "/" ]; do [ -f "$p/idVendor" ] && { echo "$p"; return 0; } p="$(dirname "$p")" done return 1 } driver_of() { basename "$(readlink -f "/sys/class/net/$1/device/driver" 2>/dev/null)" 2>/dev/null || echo unknown; } # The fingerprint answers "what am I actually talking to?" — the question the old # script never asked, which is how a FINTEK adapter ended up labelled "PEAK USB". DIAG_FILE="$LOG_DIR/adapter_diag.txt" fingerprint() { local IFS_LIST=("$@") { echo "=============== ADAPTER / DRIVER FINGERPRINT ===============" echo "captured: $(date '+%Y-%m-%d %H:%M:%S')" echo for IF in "${IFS_LIST[@]}"; do [ -e "/sys/class/net/$IF" ] || { echo "--- $IF: no such interface"; echo; continue; } echo "--- $IF" echo " driver : $(driver_of "$IF")" local root="" if root="$(usb_root_of "$IF")"; then local spd; spd="$(cat "$root/speed" 2>/dev/null || echo '?')" local spdname="unknown" case "$spd" in 1.5) spdname="USB low-speed 1.5 Mbit/s (frame 1 ms)" ;; 12) spdname="USB full-speed 12 Mbit/s (frame 1 ms)" ;; 480) spdname="USB high-speed 480 Mbit/s (microframe 125 us)" ;; 5000|10000|20000) spdname="USB SuperSpeed ${spd} Mbit/s" ;; esac echo " usb id : $(cat "$root/idVendor" 2>/dev/null):$(cat "$root/idProduct" 2>/dev/null)" echo " usb product : $(cat "$root/product" 2>/dev/null || echo '?') / $(cat "$root/manufacturer" 2>/dev/null || echo '?')" echo " usb speed : $spd Mbit/s -> $spdname" echo " usb sysfs : $root" # Endpoint descriptors. bInterval on an interrupt IN endpoint is a HARD # floor on how fast a per-frame TX-done status can come back. local intf; intf="$(readlink -f "/sys/class/net/$IF/device" 2>/dev/null)" echo " usb interface : $(basename "$intf") (shared by all channels of this device)" for ep in "$intf"/ep_*; do [ -d "$ep" ] || continue printf " %-8s type=%-9s dir=%-4s wMaxPacketSize=%-6s bInterval=%s\n" \ "$(basename "$ep")" "$(cat "$ep/type" 2>/dev/null)" "$(cat "$ep/direction" 2>/dev/null)" \ "$(cat "$ep/wMaxPacketSize" 2>/dev/null)" "$(cat "$ep/bInterval" 2>/dev/null)" done else echo " bus : not USB (PCI / platform / virtual)" fi echo " link :" ip -d link show "$IF" 2>/dev/null | sed 's/^/ /' echo done # Two channels behind one USB device share the host link and its bandwidth. if [ "${#IFS_LIST[@]}" -ge 2 ]; then local r1 r2 r1="$(usb_root_of "${IFS_LIST[0]}" 2>/dev/null || echo A)" r2="$(usb_root_of "${IFS_LIST[1]}" 2>/dev/null || echo B)" if [ "$r1" = "$r2" ]; then echo "!! NOTE: ${IFS_LIST[0]} and ${IFS_LIST[1]} are two channels of the SAME USB device." echo " They share one host link; a duplex test measures that link, not two independent buses." fi fi } > "$DIAG_FILE" 2>&1 echo ">> adapter fingerprint -> $(basename "$DIAG_FILE")" } fingerprint "$MASTER_IF" "$SLAVE_IF" M_DRIVER="$(driver_of "$MASTER_IF")" M_USBSPEED="$(cat "$(usb_root_of "$MASTER_IF" 2>/dev/null)/speed" 2>/dev/null || echo "")" SAME_USB="no" if [ "$(usb_root_of "$MASTER_IF" 2>/dev/null || echo A)" = "$(usb_root_of "$SLAVE_IF" 2>/dev/null || echo B)" ]; then SAME_USB="yes"; fi # ------------------------------------------------------------------- configure if [ -n "$CONFIGURE" ] && [ -n "$MONITOR_ONLY" ]; then echo ">> --monitor-only: ignoring --configure (won't touch a possibly-live interface)" CONFIGURE="" fi if [ -n "$CONFIGURE" ]; then echo ">> configuring interfaces via setup_can.sh (sudo)" sudo "$ROOT/scripts/setup_can.sh" "$BITRATE" "$MASTER_IF" "$SLAVE_IF" fi # ------------------------------------------------------ can-utils monitors if [ -n "$MONITOR_ONLY" ]; then MON_IFS=("$MASTER_IF"); else MON_IFS=("$MASTER_IF" "$SLAVE_IF"); fi MON_PIDS=() start_monitors() { echo ">> monitor: capturing can-utils for [${MON_IFS[*]}] into $LOG_DIR" for IF in "${MON_IFS[@]}"; do ip -s -d link show "$IF" > "$LOG_DIR/ipstat_${IF}_before.txt" 2>&1 || true done local cbl=(); for IF in "${MON_IFS[@]}"; do cbl+=("${IF}@${BITRATE}"); done canbusload "${cbl[@]}" -t > "$LOG_DIR/canbusload.txt" 2>&1 & MON_PIDS+=("$!") for IF in "${MON_IFS[@]}"; do if [ -n "$MONITOR_ONLY" ]; then candump -e -t A "$IF" > "$LOG_DIR/traffic_${IF}.txt" 2>&1 & else candump -e -t A "$IF,0~0,#FFFFFFFF" > "$LOG_DIR/errframes_${IF}.txt" 2>&1 & fi MON_PIDS+=("$!") done } stop_monitors() { [ ${#MON_PIDS[@]} -gt 0 ] && kill "${MON_PIDS[@]}" 2>/dev/null || true for IF in "${MON_IFS[@]}"; do ip -s -d link show "$IF" > "$LOG_DIR/ipstat_${IF}_after.txt" 2>&1 || true done echo ">> monitor: stopped (files in $LOG_DIR)" } trap '[ ${#MON_PIDS[@]} -gt 0 ] && kill "${MON_PIDS[@]}" 2>/dev/null || true; jobs -p | xargs -r kill 2>/dev/null || true' EXIT # --------------------------------------------------- monitor-only (passive) if [ -n "$MONITOR_ONLY" ]; then IF="$MASTER_IF" echo ">> MONITOR-ONLY on $IF for ${DURATION}s — NOT transmitting; live bus load (received traffic):" ip -s -d link show "$IF" > "$LOG_DIR/ipstat_${IF}_before.txt" 2>&1 || true candump -e -t A "$IF" > "$LOG_DIR/traffic_${IF}.txt" 2>&1 & MON_PIDS+=("$!") timeout "$DURATION" canbusload "${IF}@${BITRATE}" -t 2>&1 \ | tee "$LOG_DIR/canbusload.txt" \ | awk '/@/{p=$5; sub(/%/,"",p); printf " %-16s rx=%-6s fps payload=%6.3f Mbps bus=%s%%\n", $1, $2, $4/1000000, p; fflush()}' \ || true [ ${#MON_PIDS[@]} -gt 0 ] && kill "${MON_PIDS[@]}" 2>/dev/null || true ip -s -d link show "$IF" > "$LOG_DIR/ipstat_${IF}_after.txt" 2>&1 || true echo ">> monitor-only complete. Files in $LOG_DIR" exit 0 fi # ========================================================================= # SECTION 1 — sustained throughput run (the original test, unchanged) # ========================================================================= MAIN_TX_FPS="" if [ -z "$PROBE_ONLY" ]; then [ -n "$MONITOR" ] && start_monitors SLAVE_DURATION=$((DURATION + 3)) echo ">> starting slave on $SLAVE_IF (${SLAVE_DURATION}s) ..." "$SLAVE_BIN" --interface "$SLAVE_IF" --bitrate "$BITRATE" --duration "$SLAVE_DURATION" --results "$LOG_DIR" >/dev/null 2>&1 & SLAVE_PID=$! sleep 1 echo ">> starting master on $MASTER_IF (${DURATION}s) ..." "$MASTER_BIN" --interface "$MASTER_IF" --bitrate "$BITRATE" --duration "$DURATION" --results "$LOG_DIR" wait "$SLAVE_PID" || true [ -n "$MONITOR" ] && stop_monitors echo ">> throughput run complete." MLOG="$(ls -t "$LOG_DIR"/can_master_*.log 2>/dev/null | head -1 || true)" [ -n "$MLOG" ] && MAIN_TX_FPS="$(grep '^SUMMARY' "$MLOG" 2>/dev/null | tr ' ' '\n' | grep '^tx_frames_per_s=' | cut -d= -f2 || true)" fi # ========================================================================= # SECTION 2 — diagnostic battery # ========================================================================= # measure_fps -> frames/s actually put on the wire measure_fps() { local IF="$1" SECS="$2"; shift 2 local b a b="$(txpkts "$IF")" timeout "$SECS" cangen "$IF" "$@" >/dev/null 2>&1 || true a="$(txpkts "$IF")" awk -v b="${b:-0}" -v a="${a:-0}" -v s="$SECS" 'BEGIN{ if(s>0) printf "%.1f", (a-b)/s; else print "0" }' } # gap_stats -> "n mean min p50 p90 p99 max" in microseconds gap_stats() { awk '{ gsub(/[()]/,"",$1); d=($1-p)*1e6; if (NR>1 && d>0 && d<1e6) print d; p=$1 }' "$1" \ | sort -n \ | awk '{v[NR]=$1; s+=$1} END{ if(NR<2){print "0 0 0 0 0 0 0"; exit} printf "%d %.0f %.0f %.0f %.0f %.0f %.0f", NR, s/NR, v[1], v[int(NR*0.50)+0], v[int(NR*0.90)+0], v[int(NR*0.99)+0], v[NR] }' } gap_hist() { # local B="${2:-100}" awk -v B="$B" '{ gsub(/[()]/,"",$1); d=($1-p)*1e6; if (NR>1 && d>0 && d<20000) printf "%d\n", int(d/B)*B; p=$1 }' "$1" \ | sort -n | uniq -c \ | awk -v B="$B" '{c[NR]=$1; v[NR]=$2; if($1>mx) mx=$1} END{ for(i=1;i<=NR;i++){ n=int(c[i]*50/mx); bar=""; for(j=0;j -> "count total pct" (gaps below threshold) short_frac() { awk -v T="$2" '{ gsub(/[()]/,"",$1); d=($1-p)*1e6; if (NR>1 && d>0 && d<1e6){ n++; if (d0) printf "%d %d %.2f", s+0, n, (s+0)*100/n; else printf "0 0 0" }' "$1" } GAP_P50=""; BURST_MIN=""; BURST_PCT=""; CTRL_PCT=""; DLC_FLAT=""; DUPLEX_SUM="" NOM8="$(nominal_bits 8)"; FRAME_US_8="$(awk -v n="$NOM8" -v b="$BITRATE" 'BEGIN{printf "%.0f", n*1e6/b}')" # ---- 2a. inter-frame gap on the wire ------------------------------------- # What actually paces the link? Compare the measured gap against the time the # frame itself occupies the bus. A gap far larger than the frame time means the # bus is idling while something upstream (adapter / driver / USB) is the pacer. if [ -n "$DO_GAP" ]; then echo ">> probe: inter-frame gap ($MASTER_IF -> $SLAVE_IF, DLC=8, ${PROBE_SECS}s)" OUT="$LOG_DIR/gap_${MASTER_IF}-to-${SLAVE_IF}.txt" DUMP="$(mktemp)" candump -ta "$SLAVE_IF" > "$DUMP" 2>/dev/null & DPID=$! sleep 0.3 timeout "$PROBE_SECS" cangen "$MASTER_IF" -g 0 -I 123 -L 8 -D AAAAAAAAAAAAAAAA >/dev/null 2>&1 || true sleep 0.3; kill "$DPID" 2>/dev/null || true; wait "$DPID" 2>/dev/null || true read -r GN GMEAN GMIN GP50 GP90 GP99 GMAX <<<"$(gap_stats "$DUMP")" GAP_P50="$GP50" { echo "=== INTER-FRAME GAP ON THE WIRE ===" echo "tx=$MASTER_IF rx=$SLAVE_IF bitrate=$BITRATE DLC=8 samples=$GN" echo echo " frame occupies the bus : ${FRAME_US_8} us (${NOM8} bit nominal @ ${BITRATE} bit/s)" printf " measured gap : mean=%s min=%s p50=%s p90=%s p99=%s max=%s (us)\n" "$GMEAN" "$GMIN" "$GP50" "$GP90" "$GP99" "$GMAX" awk -v g="$GP50" -v f="$FRAME_US_8" 'BEGIN{ if(g>0) printf " bus idle between frames: %.1f%% (%.1f us of every %.0f us is dead time)\n", (g-f)*100/g, g-f, g }' echo echo " --- distribution (100 us buckets) ---" } > "$OUT" gap_hist "$DUMP" 100 >> "$OUT" rm -f "$DUMP" sed -n '2,8p' "$OUT" | sed 's/^/ /' fi # ---- 2b. burst probe ------------------------------------------------------ # THE test for "driver limit or firmware wall": can the adapter ever put two # frames on the wire closer together than its steady-state pacing? # # Judging this from the single smallest gap is unsafe — RX timestamps are taken # in software and two frames delivered in one USB poll can look artificially # close. So the probe runs its own STEADY-STATE CONTROL first: in steady state # every frame is known to be one pacing interval apart, therefore any short gap # measured there is pure artefact. That gives a baseline to compare the burst # against, and the verdict keys on the FRACTION of short gaps, not on one sample. if [ -n "$DO_BURST" ]; then echo ">> probe: burst behaviour (does the adapter buffer? incl. steady-state control)" OUT="$LOG_DIR/burst_${MASTER_IF}.txt" CTRL="$(mktemp)"; BRST="$(mktemp)" # (i) steady-state control — continuous send, every frame one interval apart candump -ta "$SLAVE_IF" > "$CTRL" 2>/dev/null & DPID=$! sleep 0.3 timeout "$PROBE_SECS" cangen "$MASTER_IF" -g 0 -I 123 -L 8 -D AAAAAAAAAAAAAAAA >/dev/null 2>&1 || true sleep 0.3; kill "$DPID" 2>/dev/null || true; wait "$DPID" 2>/dev/null || true # (ii) burst — 16 frames handed to the kernel at once, then 50 ms of idle candump -ta "$SLAVE_IF" > "$BRST" 2>/dev/null & DPID=$! sleep 0.3 timeout "$PROBE_SECS" cangen "$MASTER_IF" -g 50 -c 16 -I 123 -L 8 -D AAAAAAAAAAAAAAAA >/dev/null 2>&1 || true sleep 0.3; kill "$DPID" 2>/dev/null || true; wait "$DPID" 2>/dev/null || true read -r CN CMEAN CMIN CP50 CP90 CP99 CMAX <<<"$(gap_stats "$CTRL")" read -r BN BMEAN BMIN BP50 BP90 BP99 BMAX <<<"$(gap_stats "$BRST")" # "Short" = comfortably under the steady-state pacing interval. SHORT_T="$(awk -v p="$CP50" 'BEGIN{ printf "%d", (p>0? p*0.6 : 600) }')" read -r CS CT CPCT <<<"$(short_frac "$CTRL" "$SHORT_T")" read -r BS BT BPCT <<<"$(short_frac "$BRST" "$SHORT_T")" BURST_MIN="$BMIN"; BURST_PCT="$BPCT"; CTRL_PCT="$CPCT" { echo "=== BURST PROBE — can the adapter emit frames closer than its pacing interval? ===" echo echo " frame occupies the bus : ${FRAME_US_8} us" echo " steady-state pacing : ${CP50} us (median)" echo " \"short gap\" threshold : < ${SHORT_T} us" echo printf " %-34s %8s %8s %10s\n" "" "samples" "short" "short %" printf " %-34s %8s %8s %9s%%\n" "steady-state control (artefact)" "$CT" "$CS" "$CPCT" printf " %-34s %8s %8s %9s%%\n" "16-frame bursts" "$BT" "$BS" "$BPCT" echo printf " smallest gap: control %s us burst %s us\n" "$CMIN" "$BMIN" echo awk -v c="$CPCT" -v b="$BPCT" -v mn="$BMIN" -v f="$FRAME_US_8" -v p="$CP50" 'BEGIN{ if (b >= 1.0 && b > c*5) { printf " => The adapter DOES hold more than one frame.\n"; printf " %.2f%% of burst gaps are short vs %.2f%% in the control, and the smallest\n", b, c; printf " burst gap (%d us) is near the %d us frame time. Frames CAN leave back-to-back,\n", mn, f; printf " so the %d us steady-state pacing is imposed by the DRIVER, not by the device.\n", p; printf " Buffering looks shallow though (only %.1f%% of gaps, not the ~94%% a fully\n", b; printf " buffered 16-frame burst would give), so expect a bounded win, not 8x.\n"; } else if (b < 1.0) { printf " => The adapter does NOT buffer: burst gaps look the same as steady-state\n"; printf " (%.2f%% short vs %.2f%% control). Every frame waits a full %d us interval\n", b, c, p; printf " even when 16 are queued. This is a device/firmware wall a driver patch\n"; printf " cannot pipeline around.\n"; } else { printf " => INCONCLUSIVE: burst %.2f%% short vs control %.2f%% — not a wide enough\n", b, c; printf " margin to separate real buffering from RX timestamp clustering.\n"; printf " Settle it with a usbmon capture (needs root):\n"; printf " sudo modprobe usbmon && sudo cat /sys/kernel/debug/usb/usbmon/u\n"; } }' echo echo " --- burst gap distribution (100 us buckets) ---" } > "$OUT" gap_hist "$BRST" 100 >> "$OUT" { echo echo " --- steady-state control distribution (100 us buckets) ---" } >> "$OUT" gap_hist "$CTRL" 100 >> "$OUT" rm -f "$CTRL" "$BRST" sed -n '/^ =>/,/^$/p' "$OUT" | sed 's/^/ /' fi # ---- 2c. DLC sweep -------------------------------------------------------- # A bus-limited link carries fewer frames per second as frames grow. A link # limited by fixed per-frame overhead carries the SAME fps regardless of size. if [ -n "$DO_DLC" ]; then echo ">> probe: fps vs DLC (0/1/2/4/8, ${PROBE_SECS}s each)" OUT="$LOG_DIR/sweep_dlc.txt" { echo "=== fps vs DLC @ ${BITRATE} bit/s on $MASTER_IF ===" printf "%5s %12s %12s %12s %10s\n" "DLC" "wire bits" "theo fps" "measured fps" "% of theo" } > "$OUT" FIRST=""; LAST="" for L in 0 1 2 4 8; do NB="$(nominal_bits "$L")"; TF="$(theo_fps "$BITRATE" "$NB")" F="$(measure_fps "$MASTER_IF" "$PROBE_SECS" -g 0 -I 123 -L "$L")" awk -v l="$L" -v nb="$NB" -v tf="$TF" -v f="$F" \ 'BEGIN{ printf "%5d %12d %12d %12.1f %9.1f%%\n", l, nb, tf, f, (tf>0? f*100/tf : 0) }' >> "$OUT" [ -z "$FIRST" ] && FIRST="$F"; LAST="$F" done # Flat across a 2.4x change in frame length => the limit is per-frame, not per-bit. DLC_FLAT="$(awk -v a="$FIRST" -v b="$LAST" 'BEGIN{ if(a>0 && b/a > 0.85 && b/a < 1.15) print "flat"; else print "scales" }')" { echo if [ "$DLC_FLAT" = "flat" ]; then echo " => FLAT: a DLC=0 frame is 2.4x shorter on the wire than DLC=8, yet fps is unchanged." echo " The bottleneck is a fixed PER-FRAME cost, not CAN bus bandwidth." else echo " => SCALES with frame size: shorter frames give more fps, which is what a" echo " genuinely bus-limited link does. The CAN bus is the constraint." fi } >> "$OUT" sed -n '2,20p' "$OUT" | sed 's/^/ /' fi # ---- 2d. duplex ----------------------------------------------------------- # Both channels transmit at once. If each still reaches its solo rate, the limit # is per-channel; if the total is capped near the solo rate, it is per-link. if [ -n "$DO_DUPLEX" ]; then echo ">> probe: both channels transmitting simultaneously (${PROBE_SECS}s)" OUT="$LOG_DIR/duplex.txt" SOLO="$(measure_fps "$MASTER_IF" "$PROBE_SECS" -g 0 -I 123 -L 8)" b0="$(txpkts "$MASTER_IF")"; b1="$(txpkts "$SLAVE_IF")" timeout "$PROBE_SECS" cangen "$MASTER_IF" -g 0 -I 123 -L 8 >/dev/null 2>&1 & timeout "$PROBE_SECS" cangen "$SLAVE_IF" -g 0 -I 124 -L 8 >/dev/null 2>&1 & wait || true a0="$(txpkts "$MASTER_IF")"; a1="$(txpkts "$SLAVE_IF")" read -r D0 D1 DSUM <<<"$(awk -v b0="$b0" -v a0="$a0" -v b1="$b1" -v a1="$a1" -v s="$PROBE_SECS" \ 'BEGIN{ f0=(a0-b0)/s; f1=(a1-b1)/s; printf "%.1f %.1f %.1f", f0, f1, f0+f1 }')" DUPLEX_SUM="$DSUM" { echo "=== DUPLEX — $MASTER_IF and $SLAVE_IF transmitting at the same time ===" echo "same USB device: $SAME_USB" echo printf " %s solo : %s fps\n" "$MASTER_IF" "$SOLO" printf " %s (duplex) : %s fps\n" "$MASTER_IF" "$D0" printf " %s (duplex) : %s fps\n" "$SLAVE_IF" "$D1" printf " aggregate : %s fps\n" "$DSUM" echo awk -v solo="$SOLO" -v sum="$DSUM" 'BEGIN{ if (solo<=0) { print " => solo measurement failed; cannot classify."; exit } if (sum > solo*1.6) printf " => PER-CHANNEL limit: the aggregate (%.0f fps) is %.1fx the solo rate,\n so the shared host link is NOT the constraint.\n", sum, sum/solo; else printf " => PER-LINK limit: the aggregate (%.0f fps) barely exceeds the solo rate (%.0f fps).\n The two channels are competing for one shared resource.\n", sum, solo }' } > "$OUT" grep -E '^ ' "$OUT" | sed 's/^/ /' fi # ---- 2e. bitrate sweep ---------------------------------------------------- # The cleanest test of all: if fps does not move when the CAN bitrate doubles, # nothing about CAN is the limit. if [ -n "$DO_RATE" ]; then echo ">> probe: fps vs bitrate [$RATE_LIST] (${PROBE_SECS}s each, reconfigures the link)" OUT="$LOG_DIR/sweep_rate.txt" { echo "=== fps vs CAN bitrate on $MASTER_IF (DLC=8, ${NOM8} bit/frame) ===" printf "%12s %12s %12s %10s %12s\n" "bitrate" "theo fps" "measured fps" "% of theo" "bus load %" } > "$OUT" RFIRST=""; RLAST="" IFS=',' read -ra RATES <<<"$RATE_LIST" for R in "${RATES[@]}"; do sudo "$ROOT/scripts/setup_can.sh" "$R" "$MASTER_IF" "$SLAVE_IF" >/dev/null 2>&1 || { echo " (skip $R: setup failed)" >> "$OUT"; continue; } sleep 0.5 TF="$(theo_fps "$R" "$NOM8")" F="$(measure_fps "$MASTER_IF" "$PROBE_SECS" -g 0 -I 123 -L 8)" awk -v r="$R" -v tf="$TF" -v f="$F" -v nb="$NOM8" \ 'BEGIN{ printf "%12d %12d %12.1f %9.1f%% %11.1f%%\n", r, tf, f, (tf>0? f*100/tf:0), f*nb*100/r }' >> "$OUT" [ -z "$RFIRST" ] && RFIRST="$F"; RLAST="$F" done { echo awk -v a="$RFIRST" -v b="$RLAST" 'BEGIN{ if (a>0 && b/a > 0.85 && b/a < 1.15) print " => FLAT across the whole bitrate range: fps does not depend on the CAN bitrate at all.\n Whatever limits this link is not CAN."; else print " => fps SCALES with bitrate — the CAN bus is the constraint, which is the healthy case." }' } >> "$OUT" # Leave the link at the bitrate the run was asked for. sudo "$ROOT/scripts/setup_can.sh" "$BITRATE" "$MASTER_IF" "$SLAVE_IF" >/dev/null 2>&1 || true sed -n '2,20p' "$OUT" | sed 's/^/ /' fi # ========================================================================= # SECTION 3 — reports # # Everything above wrote raw artefacts into log/. This section reads them back # and writes short markdown into report/ so the run can be understood without # opening a single log file. # ========================================================================= # --- digest helpers: turn hundreds of log lines into a handful of numbers --- # fps_digest -> "n min mean max" (from the per-second "inst N fps" lines) # # Edge samples are trimmed before the statistics are taken, otherwise a perfectly # steady run looks unstable. Two effects produce those edges: the first and last # second of any run are partial, and the slave deliberately outlives the master # (SLAVE_DURATION = DURATION + 3) so its log ends with seconds where nothing was # being sent at all. # # Trimming only walks inward from the two ends while samples sit below half the # median, then drops one more from each side. A genuine mid-run stall is not at # an edge, so it still shows up in min. fps_digest() { grep -oE 'inst +[0-9]+ fps' "$1" 2>/dev/null | grep -oE '[0-9]+' \ | awk '{ v[NR]=$1; c[NR]=$1 } END{ if(NR==0){ printf "0 0 0 0"; exit } # insertion sort — asort() is a gawk extension and this must also # run under mawk, the default awk on many Debian/Ubuntu images for(i=2;i<=NR;i++){ x=c[i]; j=i-1 while(j>0 && c[j]>x){ c[j+1]=c[j]; j-- } c[j+1]=x } med=(NR%2 ? c[(NR+1)/2] : (c[NR/2]+c[NR/2+1])/2) lo=1; hi=NR while (lolo && v[hi] < med*0.5) hi-- if (hi-lo >= 2) { lo++; hi-- } k=0 for(i=lo;i<=hi;i++){ x=v[i] if(k==0||xmx) mx=x; s+=x; k++ } if(k>0) printf "%d %d %.0f %d", k, mn, s/k, mx; else printf "0 0 0 0" }' } # busload_digest -> "n min mean max" (percent, idle rows skipped) busload_digest() { [ -f "$1" ] || { printf "0 0 0 0"; return; } awk -v ifc="$2" '$1 ~ "^"ifc"@" && $2+0>0 { p=$NF; sub(/%/,"",p); v[++k]=p+0 } END{ lo=(k>2?2:1); hi=(k>2?k-1:k); n=0 for(i=lo;i<=hi;i++){ p=v[i] if(n==0||pmx) mx=p; s+=p; n++ } if(n>0) printf "%d %.0f %.1f %.0f", n, mn, s/n, mx; else printf "0 0 0 0" }' "$1" } # ipnum -> counter value ipnum() { [ -f "$1" ] || { echo 0; return; } awk -v want="$2" -v c="$3" '$1==want":" && $2=="bytes" { getline; print $(c); exit }' "$1" } # canerr_row -> "restarted buserr arblost errwarn errpass busoff" canerr_row() { [ -f "$1" ] || { echo "0 0 0 0 0 0"; return; } awk '/re-started/{ getline; printf "%s %s %s %s %s %s", $1,$2,$3,$4,$5,$6; exit }' "$1" } # delta -> after - before delta() { awk -v b="$(ipnum "$1" "$3" "$4")" -v a="$(ipnum "$2" "$3" "$4")" \ 'BEGIN{ printf "%d", (a+0)-(b+0) }' } # embed <file> -> a fenced block, or a note when the file is absent embed() { echo "### $1"; echo if [ -s "$2" ]; then echo '```'; cat "$2"; echo '```' else echo "_(không có — probe này không chạy)_"; fi echo } BITLABEL="$(awk -v b="$BITRATE" 'BEGIN{ if(b>=1000000) printf "%.3g Mbps", b/1000000; else printf "%d kbps", b/1000 }')" THEO8="$(theo_fps "$BITRATE" "$NOM8")" MLOG="$(ls -t "$LOG_DIR"/can_master_*.log 2>/dev/null | head -1 || true)" SLOG="$(ls -t "$LOG_DIR"/can_slave_*.log 2>/dev/null | head -1 || true)" sumval() { [ -n "${1:-}" ] && grep '^SUMMARY' "$1" 2>/dev/null | tr ' ' '\n' | grep "^$2=" | cut -d= -f2- || true; } ACH="${MAIN_TX_FPS:-}" if [ -z "$ACH" ] && [ -f "$LOG_DIR/sweep_dlc.txt" ]; then ACH="$(awk '$1==8{print $4}' "$LOG_DIR/sweep_dlc.txt" 2>/dev/null || true)" fi EFF="" [ -n "$ACH" ] && EFF="$(awk -v a="$ACH" -v t="$THEO8" 'BEGIN{ if(t>0) printf "%.0f", a*100/t; else print "" }')" # One-line headline verdict reused across the report files. HEADLINE="chưa đủ dữ liệu để kết luận" if [ -n "$EFF" ]; then if [ "$EFF" -ge 80 ]; then HEADLINE="✅ **Bus CAN là giới hạn** — đang chạy ${EFF}% trần lý thuyết. Đây là kết quả lành mạnh." elif [ "$DLC_FLAT" = "flat" ]; then HEADLINE="⚠️ **Adapter/driver là nút thắt, không phải bus CAN** — chỉ dùng ${EFF}% bus, và fps không đổi theo kích thước frame." else HEADLINE="⚠️ **Mới dùng ${EFF}% bus, chưa xác định được nguyên nhân** — chạy thêm \`--full\` để phân loại." fi fi # ---------------------------------------------------------------- 03-adapter { echo "# Adapter / driver" echo echo "Trả lời câu \"đang nói chuyện với thiết bị gì\" — đọc thẳng từ sysfs lúc chạy," echo "không suy từ tên interface." echo echo '```' cat "$DIAG_FILE" 2>/dev/null || echo "(không có)" echo '```' echo echo "**Vì sao \`bInterval\` quan trọng:** trên endpoint interrupt-IN, đây là chu kỳ host" echo "hỏi thăm thiết bị. Nếu driver phải đợi trạng thái \"TX xong\" quay về qua endpoint đó" echo "mới gửi frame kế tiếp, thì \`bInterval\` chính là sàn cứng cho tốc độ frame." echo echo "[← Báo cáo nhanh](00-BAOCAO.md)" } > "$REPORT_DIR/03-adapter.md" 2>/dev/null || true # ------------------------------------------------------------ 01-thongluong { echo "# Thông lượng" echo if [ -n "$MLOG" ]; then m_sent="$(sumval "$MLOG" frames_sent)"; m_dur="$(sumval "$MLOG" duration_s)" m_fps="$(sumval "$MLOG" tx_frames_per_s)"; m_err="$(sumval "$MLOG" tx_errors)" m_mbps="$(sumval "$MLOG" payload_mbps)"; m_bus="$(sumval "$MLOG" bus_load_pct)" s_valid="$(sumval "$SLOG" valid_frames)"; s_inv="$(sumval "$SLOG" invalid_frames)" s_cerr="$(sumval "$SLOG" can_errors)" : "${m_sent:=0}" "${s_valid:=0}" "${s_inv:=0}" "${m_err:=0}" "${s_cerr:=0}" lost=$(( m_sent - s_valid )) echo "## Kết quả" echo echo "| Chỉ số | Giá trị |" echo "|---|---|" echo "| Thời lượng | ${m_dur:-?} s |" echo "| Frame gửi | $m_sent |" echo "| Frame nhận hợp lệ | $s_valid |" echo "| **Mất** | **$lost** ($(awk -v l="$lost" -v s="$m_sent" 'BEGIN{ if(s>0) printf "%.4f%%", l*100/s; else print "n/a" }')) |" echo "| Frame sai nội dung | $s_inv |" echo "| TX f/s | ${m_fps:-?} |" echo "| Payload | ${m_mbps:-?} Mbps |" echo "| Bus load (nominal) | ${m_bus:-?}% |" echo "| Lỗi TX / lỗi CAN | $m_err / $s_cerr |" echo read -r MN MMIN MMEAN MMAX <<<"$(fps_digest "$MLOG")" if [ "${MN:-0}" -gt 0 ]; then echo "## Ổn định theo thời gian" echo echo "Rút gọn từ thống kê mỗi giây trong log master/slave ($MN mẫu sau khi cắt rìa) — thay cho việc đọc hết log." echo echo "| | min | trung bình | max |" echo "|---|---:|---:|---:|" echo "| TX f/s (master) | $MMIN | $MMEAN | $MMAX |" if [ -n "$SLOG" ]; then read -r SN SMIN SMEAN SMAX <<<"$(fps_digest "$SLOG")" [ "${SN:-0}" -gt 0 ] && echo "| RX f/s (slave) | $SMIN | $SMEAN | $SMAX |" fi read -r BN BMIN BMEAN BMAX <<<"$(busload_digest "$LOG_DIR/canbusload.txt" "$MASTER_IF")" [ "${BN:-0}" -gt 0 ] && echo "| Bus load % (canbusload, $BN mẫu) | $BMIN | $BMEAN | $BMAX |" echo # Spread is measured against the mean, not the min, and the batch size is # noted: the master hands the kernel 64 frames per syscall, so a per-second # count lands on a multiple of 64 and jitters by roughly one batch even # when the link is perfectly steady. awk -v mn="$MMIN" -v mx="$MMAX" -v av="$MMEAN" 'BEGIN{ sp = (av>0 ? (mx-mn)*100/av : 0) if (sp < 25) printf "Biên độ %.0f%% quanh trung bình — đều, nằm trong mức lượng tử hoá của batch 64 frame/syscall.\n", sp else printf "**Biên độ %.0f%% quanh trung bình** — rộng hơn mức lượng tử hoá batch, nên xem log theo giây để tìm thời điểm sụt tải.\n", sp }' echo fi else echo "_Không chạy benchmark (chế độ \`--probe-only\`)._" echo fi # Driver counters straight from the kernel, before vs after. if [ -f "$LOG_DIR/ipstat_${MASTER_IF}_before.txt" ] && [ -f "$LOG_DIR/ipstat_${MASTER_IF}_after.txt" ]; then echo "## Bộ đếm driver (trước → sau)" echo echo "| Interface | TX gói | TX lỗi | TX drop | RX gói | RX lỗi | RX drop |" echo "|---|---:|---:|---:|---:|---:|---:|" for IF in "${MON_IFS[@]}"; do B="$LOG_DIR/ipstat_${IF}_before.txt"; A="$LOG_DIR/ipstat_${IF}_after.txt" [ -f "$A" ] || continue echo "| $IF | $(delta "$B" "$A" TX 2) | $(delta "$B" "$A" TX 3) | $(delta "$B" "$A" TX 4) | $(delta "$B" "$A" RX 2) | $(delta "$B" "$A" RX 3) | $(delta "$B" "$A" RX 4) |" done echo echo "| Interface | re-started | bus-errors | arbit-lost | error-warn | error-pass | bus-off |" echo "|---|---:|---:|---:|---:|---:|---:|" for IF in "${MON_IFS[@]}"; do A="$LOG_DIR/ipstat_${IF}_after.txt"; [ -f "$A" ] || continue read -r c1 c2 c3 c4 c5 c6 <<<"$(canerr_row "$A")" printf "| %s | %s | %s | %s | %s | %s | %s |\n" "$IF" "$c1" "$c2" "$c3" "$c4" "$c5" "$c6" done echo ERRF=0 for f in "$LOG_DIR"/errframes_*.txt; do [ -f "$f" ] && ERRF=$(( ERRF + $(wc -l < "$f") )); done echo "Error frame bắt được bởi \`candump -e\`: **$ERRF**" echo fi echo "Log thô: [\`../log/\`](../log/)" echo echo "[← Báo cáo nhanh](00-BAOCAO.md)" } > "$REPORT_DIR/01-thongluong.md" 2>/dev/null || true # --------------------------------------------------------------- 02-nutthat { echo "# Nút thắt nằm ở đâu" echo echo "$HEADLINE" echo echo "## Bằng chứng từ các probe" echo NCLUE=0 if [ -n "$GAP_P50" ] && [ "$GAP_P50" -gt 0 ] 2>/dev/null; then awk -v g="$GAP_P50" -v f="$FRAME_US_8" 'BEGIN{ printf "- **Khoảng cách frame trên dây**: trung vị %d us, trong khi một frame chỉ chiếm %d us — bus nằm không %.0f%% thời gian.\n", g, f, (g-f)*100/g }' awk -v g="$GAP_P50" 'BEGIN{ r=g/1000; if (r>0.93 && r<1.07) print " Nhịp bám gần như đúng 1000 us — dấu hiệu của đồng hồ khung USB full-speed, không phải thứ gì thuộc CAN." }' NCLUE=$((NCLUE+1)) fi if [ -n "$DLC_FLAT" ]; then if [ "$DLC_FLAT" = "flat" ]; then echo "- **Quét DLC**: fps phẳng từ DLC=0 tới DLC=8 — chi phí cố định mỗi frame chi phối, không phải băng thông bus." else echo "- **Quét DLC**: fps tăng khi frame ngắn lại — đúng hành vi của một link thật sự bị giới hạn bởi bus." fi NCLUE=$((NCLUE+1)) fi if [ -n "$DUPLEX_SUM" ]; then echo "- **Duplex**: tổng $DUPLEX_SUM fps trên cả hai kênh (cùng một thiết bị USB: $SAME_USB)." NCLUE=$((NCLUE+1)) fi if [ -n "$BURST_PCT" ]; then awk -v b="$BURST_PCT" -v c="$CTRL_PCT" -v mn="$BURST_MIN" -v f="$FRAME_US_8" 'BEGIN{ if (b >= 1.0 && b > c*5) printf "- **Burst**: %.2f%% gap trong burst ngắn hơn nhịp, so với %.2f%% ở control steady-state (vốn là nhiễu đo thuần tuý). Gap nhỏ nhất %d us so với %d us thời gian frame — thiết bị *có* giữ nhiều hơn một frame, nên việc tuần tự hoá là lựa chọn của DRIVER. Đệm nông nên cải thiện sẽ có giới hạn.\n", b, c, mn, f; else if (b < 1.0) printf "- **Burst**: gap trong burst giống hệt control (%.2f%% vs %.2f%%). Kể cả khi dồn 16 frame, thiết bị vẫn nhả từng frame một nhịp — tường cứng firmware, không phải lỗi driver.\n", b, c; else printf "- **Burst**: chưa kết luận được (%.2f%% vs %.2f%% control). Cần usbmon để phân định.\n", b, c }' NCLUE=$((NCLUE+1)) fi [ "$NCLUE" -eq 0 ] && echo "_Không probe nào được chạy. Thêm \`--full\` hoặc \`--probe-only\` để phân loại nút thắt._" echo echo "## Kết luận" echo if [ -n "$EFF" ] && [ "$EFF" -ge 80 ] 2>/dev/null; then echo "Link đang chạy ${EFF}% những gì $BITLABEL có thể tải được với frame DLC=8." echo "Không có gì phải sửa." elif [ "$DLC_FLAT" = "flat" ]; then echo "Chỉ ${EFF}% bus được dùng, và fps không nhúc nhích khi đổi kích thước frame," echo "nên chi phí là **cố định trên mỗi frame** chứ không theo số bit." [ -n "$BURST_PCT" ] && awk -v b="$BURST_PCT" -v c="$CTRL_PCT" 'BEGIN{ if (b >= 1.0 && b > c*5) print "Burst probe cho thấy adapter thỉnh thoảng nhả được frame liền nhau, nên chỗ tuần tự hoá nằm trong driver và đáng để tấn công vào đó."; else if (b < 1.0) print "Burst probe cho thấy chính adapter không chịu nhanh hơn, nên chỉ vá driver sẽ không gỡ được."; else print "Burst probe chưa kết luận được; một bản ghi usbmon sẽ phân định driver hay thiết bị đang giữ nhịp." }' echo echo "**Việc tiếp theo** — soi đường truyền TX của driver:" echo "- cho phép bao nhiêu frame in-flight (\`echo_skb_max\` trong \`alloc_candev()\`)" echo "- có gọi \`netif_stop_queue()\` mỗi frame không" echo "- trạng thái TX-xong có phải quay về qua endpoint interrupt bị hỏi thăm theo chu kỳ không" echo echo "\`bInterval\` của endpoint nằm trong [03-adapter.md](03-adapter.md), đó là sàn cứng cho vòng lặp này." elif [ -n "$EFF" ]; then echo "Mới dùng ${EFF}% bus nhưng chưa khoanh được nguyên nhân." echo "Chạy lại với \`--full\` để probe DLC, burst và duplex phân loại giúp." else echo "_Không đủ dữ liệu — chạy benchmark hoặc \`--probe-only\`._" fi echo echo "[← Báo cáo nhanh](00-BAOCAO.md) · [Probe chi tiết →](04-probe.md)" } > "$REPORT_DIR/02-nutthat.md" 2>/dev/null || true # ----------------------------------------------------------------- 04-probe if [ -n "$HAVE_PROBES" ]; then { echo "# Probe chi tiết" echo echo "Kết quả thô của từng phép đo. Phần diễn giải nằm ở [02-nutthat.md](02-nutthat.md)." echo [ -n "$DO_GAP" ] && embed "Khoảng cách frame trên dây" "$LOG_DIR/gap_${MASTER_IF}-to-${SLAVE_IF}.txt" [ -n "$DO_BURST" ] && embed "Burst vs control steady-state" "$LOG_DIR/burst_${MASTER_IF}.txt" [ -n "$DO_DLC" ] && embed "fps theo DLC" "$LOG_DIR/sweep_dlc.txt" [ -n "$DO_DUPLEX" ] && embed "Hai kênh phát đồng thời" "$LOG_DIR/duplex.txt" [ -n "$DO_RATE" ] && embed "fps theo bitrate" "$LOG_DIR/sweep_rate.txt" echo "[← Báo cáo nhanh](00-BAOCAO.md)" } > "$REPORT_DIR/04-probe.md" 2>/dev/null || true fi # ------------------------------------------------------------------ table # The comparison row belongs with the reports; logs stay in log/. if [ -z "$PROBE_ONLY" ] && [ -n "$MLOG" ]; then "$ROOT/scripts/make_report.sh" "$BITRATE" "$LOG_DIR" "$REPORT_DIR" fi # --------------------------------------------------------------- 00-BAOCAO { echo "# Báo cáo nhanh — $MASTER_IF → $SLAVE_IF @ $BITLABEL" echo printf "Chạy \`%s\` · driver \`%s\`" "$RUN_TS" "$M_DRIVER" [ -n "$M_USBSPEED" ] && printf " · USB %s Mbit/s" "$M_USBSPEED" echo; echo echo "> $HEADLINE" echo echo "## Số chính" echo echo "| | |" echo "|---|---|" printf "| Trần lý thuyết CAN (DLC=8, %s bit/frame) | %s fps |\n" "$NOM8" "$THEO8" if [ -n "$ACH" ]; then printf "| Đạt được | %s fps |\n" "$ACH" printf "| Hiệu suất | %s%% bus |\n" "$EFF" awk -v a="$ACH" 'BEGIN{ printf "| Payload | %.4f Mbps |\n", a*64/1e6 }' fi if [ -n "$MLOG" ]; then m_sent="$(sumval "$MLOG" frames_sent)"; s_valid="$(sumval "$SLOG" valid_frames)" m_err="$(sumval "$MLOG" tx_errors)"; s_cerr="$(sumval "$SLOG" can_errors)" : "${m_sent:=0}" "${s_valid:=0}" "${m_err:=0}" "${s_cerr:=0}" lost=$(( m_sent - s_valid )) printf "| Mất frame | %s / %s (%s) |\n" "$lost" "$m_sent" \ "$(awk -v l="$lost" -v s="$m_sent" 'BEGIN{ if(s>0) printf "%.4f%%", l*100/s; else print "n/a" }')" printf "| Lỗi TX / lỗi CAN | %s / %s |\n" "$m_err" "$s_cerr" if [ "$lost" -le 0 ] && [ "$m_err" -eq 0 ] && [ "$s_cerr" -eq 0 ]; then echo "| Trạng thái | ✅ OK |" else echo "| Trạng thái | ❌ FAIL |" fi fi echo echo "> Cột payload chỉ đếm bit dữ liệu. Một frame CAN chở 8 byte tốn $NOM8 bit trên dây cho" printf "> 64 bit dữ liệu, nên kể cả bus %s chạy đầy tải cũng chỉ tới khoảng %.4f Mbps payload —\n" "$BITLABEL" "$(awk -v t="$THEO8" 'BEGIN{printf "%.4f", t*64/1e6}')" echo "> con số đó nhỏ là bình thường." echo echo "## Đọc tiếp" echo [ -f "$REPORT_DIR/01-thongluong.md" ] && echo "- [01 — Thông lượng](01-thongluong.md) — kết quả, độ ổn định theo thời gian, bộ đếm driver" [ -f "$REPORT_DIR/02-nutthat.md" ] && echo "- [02 — Nút thắt](02-nutthat.md) — nghẽn ở đâu và vì sao" [ -f "$REPORT_DIR/03-adapter.md" ] && echo "- [03 — Adapter](03-adapter.md) — driver, USB, endpoint" [ -f "$REPORT_DIR/04-probe.md" ] && echo "- [04 — Probe chi tiết](04-probe.md) — số liệu thô từng phép đo" [ -f "$REPORT_DIR/results_table.md" ] && echo "- [Bảng so sánh](results_table.md) — một hàng để ghép với các run khác" echo echo "Log thô nằm ở [\`../log/\`](../log/) — báo cáo này đã rút gọn sẵn, thường không cần mở tới." } > "$REPORT_DIR/00-BAOCAO.md" 2>/dev/null || true echo echo "=============== BÁO CÁO NHANH ===============" echo "$HEADLINE" | sed 's/\*\*//g' echo echo ">> $RUN_DIR" echo " report/00-BAOCAO.md <- đọc cái này" ls "$REPORT_DIR" 2>/dev/null | sed 's/^/ report\//' echo " log/ ($(ls "$LOG_DIR" 2>/dev/null | wc -l) file thô)"