Files

75 lines
2.9 KiB
Bash
Executable File

#!/usr/bin/env bash
# Deterministic discovery of DUT (Heltec V4.3) and SDR (Nooelec NESDR SMArt v5).
# Prints selected devices; exits nonzero on ambiguity or absence.
# ./tools/discover_devices.sh [--dut-only|-v]
# --dut-only prints only DUT_PORT and does not inspect or require an SDR.
#
# Output (eval-able):
# DUT_PORT=/dev/serial/by-id/...
# SDR_INDEX=0
# SDR_SERIAL=33999948
set -euo pipefail
fail() { echo "DISCOVER_ERROR: $*" >&2; exit 1; }
# --- DUT: Heltec WiFi LoRa 32 V4 (ESP32-S3 native USB CDC) ---
shopt -s nullglob
dut_candidates=(/dev/serial/by-id/*heltec_wifi_lora_32_v4*)
if [ ${#dut_candidates[@]} -eq 0 ]; then
# fall back to any Espressif device, but require uniqueness
dut_candidates=(/dev/serial/by-id/usb-Espressif*)
fi
[ ${#dut_candidates[@]} -eq 0 ] && fail "no Heltec/Espressif serial device found in /dev/serial/by-id/"
[ ${#dut_candidates[@]} -gt 1 ] && fail "ambiguous DUT: ${dut_candidates[*]}"
DUT_PORT="${dut_candidates[0]}"
[ -e "$DUT_PORT" ] || fail "DUT path vanished: $DUT_PORT"
if [ "${1:-}" = "--dut-only" ]; then
printf 'DUT_PORT=%q\n' "$DUT_PORT"
exit 0
fi
# --- SDR: Nooelec NESDR SMArt v5 (RTL2832U, USB 0bda:2838) ---
# Identity is established by USB VID:PID, because this dongle sometimes
# enumerates with empty descriptor strings after a fault (rtl_test then
# prints "0: , , SN: "). A usbreset restores them, but discovery must not
# fail on it. Ambiguity (more than one RTL dongle) is still fatal.
if command -v lsusb >/dev/null 2>&1; then
usb_count=$(lsusb 2>/dev/null | grep -c '0bda:2838' || true)
else
# sysfs fallback: works without usbutils
usb_count=0
for v in /sys/bus/usb/devices/*/idVendor; do
[ -r "$v" ] || continue
p="${v%idVendor}idProduct"
[ "$(cat "$v" 2>/dev/null)" = "0bda" ] &&
[ "$(cat "$p" 2>/dev/null)" = "2838" ] &&
usb_count=$((usb_count + 1))
done
fi
[ "${usb_count:-0}" -eq 0 ] && fail "no RTL2832U (0bda:2838) on the USB bus"
[ "${usb_count:-0}" -gt 1 ] && fail "ambiguous SDR: $usb_count RTL2832U devices present"
sdr_list=$(timeout 10 rtl_test -t 2>&1 | grep -E '^\s+[0-9]+:' || true)
[ -z "$sdr_list" ] && fail "RTL2832U on USB but librtlsdr cannot enumerate it"
[ "$(echo "$sdr_list" | wc -l)" -gt 1 ] && fail "ambiguous SDR: $sdr_list"
sdr_matches="$sdr_list"
SDR_INDEX=$(echo "$sdr_matches" | sed -E 's/^\s*([0-9]+):.*/\1/')
SDR_SERIAL=$(echo "$sdr_matches" | sed -E 's/.*SN: ([^ ]*).*/\1/')
[ -z "$SDR_SERIAL" ] && SDR_SERIAL="unknown(descriptor_fault)"
if ! echo "$sdr_matches" | grep -qi "Nooelec"; then
echo "DISCOVER_WARN: RTL dongle descriptors unreadable ($sdr_matches);" \
"identified by VID:PID 0bda:2838" >&2
fi
echo "DUT_PORT=$DUT_PORT"
echo "SDR_INDEX=$SDR_INDEX"
echo "SDR_SERIAL=$SDR_SERIAL"
if [ "${1:-}" = "-v" ]; then
echo "---" >&2
echo "DUT: $DUT_PORT -> $(readlink -f "$DUT_PORT")" >&2
echo "SDR: index $SDR_INDEX, serial $SDR_SERIAL" >&2
echo "$sdr_matches" >&2
fi