Initial commit

This commit is contained in:
MattMa
2026-07-10 16:58:17 +08:00
commit 7222ba1107
56 changed files with 8433 additions and 0 deletions
+121
View File
@@ -0,0 +1,121 @@
#!/usr/bin/env bash
# -----------------------------------------------------------------------------
# One-shot launcher for the SRU navigation node on Go2 NX.
#
# Combines a conda python env (onnxruntime, scipy, ...) with the system
# ROS Noetic installation (rospy, cv_bridge). The trick:
# 1) source /opt/ros/noetic/setup.bash -> ROS env
# 2) source <catkin_ws>/devel/setup.bash -> our package
# 3) conda activate sru_nav -> python with onnxruntime
# 4) export PYTHONPATH=<ros dist-packages>:$PYTHONPATH so conda python
# can still import rospy / cv_bridge / sensor_msgs / etc.
#
# Usage:
# bash launch_sru_nav.sh # full launch (joy + static TF + node)
# bash launch_sru_nav.sh --no-joy # if /joy is already provided elsewhere
# bash launch_sru_nav.sh --no-deadman # TESTING: skip joystick deadman entirely
# # (cmd_vel_ratio=1.0, no /joy needed).
# # Robot WILL move on /goal_pose alone.
# bash launch_sru_nav.sh --node-only # run just sru_nav_node (assume joy + TF already up)
# -----------------------------------------------------------------------------
set -eu
ENV_NAME="${ENV_NAME:-sru_nav}"
ROS_DISTRO="${ROS_DISTRO:-noetic}"
CATKIN_WS="${CATKIN_WS:-$HOME/code/odin_sru_nav}"
EXTRA_ARGS=""
NODE_ONLY=0
for arg in "$@"; do
case "$arg" in
--no-joy) EXTRA_ARGS="$EXTRA_ARGS launch_joy:=false" ;;
--no-tf) EXTRA_ARGS="$EXTRA_ARGS launch_static_tf:=false" ;;
--no-deadman) EXTRA_ARGS="$EXTRA_ARGS require_joystick:=false launch_joy:=false" ;;
--node-only) NODE_ONLY=1 ;;
*) EXTRA_ARGS="$EXTRA_ARGS $arg" ;;
esac
done
# ---- 1) ROS env -------------------------------------------------------------
if [ ! -f "/opt/ros/${ROS_DISTRO}/setup.bash" ]; then
echo "[ERROR] /opt/ros/${ROS_DISTRO}/setup.bash not found"; exit 1
fi
# shellcheck disable=SC1091
source "/opt/ros/${ROS_DISTRO}/setup.bash"
if [ -f "${CATKIN_WS}/devel/setup.bash" ]; then
# shellcheck disable=SC1091
source "${CATKIN_WS}/devel/setup.bash"
else
echo "[WARN] ${CATKIN_WS}/devel/setup.bash not found. Did you catkin_make?"
fi
# ---- 2) conda env -----------------------------------------------------------
if ! command -v conda >/dev/null 2>&1; then
echo "[ERROR] conda not found. Run setup_conda_env.sh first."; exit 1
fi
CONDA_BASE="$(conda info --base)"
# shellcheck disable=SC1091
source "${CONDA_BASE}/etc/profile.d/conda.sh"
conda activate "${ENV_NAME}"
# ---- 3) Make rospy / cv_bridge importable from the conda python -------------
ROS_PY_DIST="/opt/ros/${ROS_DISTRO}/lib/python3/dist-packages"
export PYTHONPATH="${ROS_PY_DIST}:${PYTHONPATH:-}"
# Fix conda<->system libffi ABI conflict that breaks cv_bridge:
# "libp11-kit.so.0: undefined symbol: ffi_type_pointer, version LIBFFI_BASE_7.0"
# Force the system libffi (used to build libp11-kit) to load first.
for _sys_libffi in \
/lib/aarch64-linux-gnu/libffi.so.7 \
/usr/lib/aarch64-linux-gnu/libffi.so.7 \
/lib/x86_64-linux-gnu/libffi.so.7 \
/usr/lib/x86_64-linux-gnu/libffi.so.7; do
if [ -f "${_sys_libffi}" ]; then
export LD_PRELOAD="${_sys_libffi}${LD_PRELOAD:+:${LD_PRELOAD}}"
echo "[INFO] LD_PRELOAD += ${_sys_libffi}"
break
fi
done
echo "[INFO] python = $(which python)"
echo "[INFO] PYTHONPATH = ${PYTHONPATH}"
echo "[INFO] ROS_DISTRO = ${ROS_DISTRO}"
echo "[INFO] CATKIN_WS = ${CATKIN_WS}"
# ---- Sanity: catkin wrapper must call conda's python (not system /usr/bin) ---
WRAPPER="${CATKIN_WS}/devel/lib/sru_nav_go2_ros1/sru_nav_node"
if [ -f "${WRAPPER}" ]; then
WRAPPER_SHEBANG="$(head -n1 "${WRAPPER}")"
CONDA_PY="$(which python)"
case "${WRAPPER_SHEBANG}" in
*"${CONDA_PY}"*|*"/usr/bin/env python"*)
: # OK
;;
*)
cat >&2 <<EOF
[WARN] Catkin-generated wrapper shebang is NOT the conda python:
wrapper : ${WRAPPER}
shebang : ${WRAPPER_SHEBANG}
conda py: ${CONDA_PY}
It will likely fail with 'No module named cv2 / onnxruntime'.
Fix:
conda activate ${ENV_NAME}
cd ${CATKIN_WS}
catkin_make clean
catkin_make -DPYTHON_EXECUTABLE=\$(which python3)
EOF
;;
esac
fi
# ---- 4) Launch --------------------------------------------------------------
if [ "$NODE_ONLY" -eq 1 ]; then
exec rosrun sru_nav_go2_ros1 sru_nav_node \
__ns:= \
_vae_model_path:="" _policy_model_path:=""
else
# shellcheck disable=SC2086
exec roslaunch sru_nav_go2_ros1 sru_nav_go2.launch $EXTRA_ARGS
fi
+214
View File
@@ -0,0 +1,214 @@
#!/usr/bin/env bash
# -----------------------------------------------------------------------------
# Conda environment bootstrap for sru_nav_go2_ros1 on Go2 NX (Jetson Xavier NX)
# -----------------------------------------------------------------------------
# Goal: create a python env containing onnxruntime + cv2 + scipy + numpy that
# works alongside system ROS Noetic (which provides rospy / cv_bridge).
#
# We do NOT install rospy / cv_bridge into conda. They come from /opt/ros/noetic
# (system python3.8). To make them importable from the conda env we expose the
# ROS site-packages via PYTHONPATH at run time (see launch_sru_nav.sh).
#
# Usage:
# bash setup_conda_env.sh # create env and install deps
# bash setup_conda_env.sh --gpu # try to install Jetson onnxruntime-gpu wheel
# bash setup_conda_env.sh --check # just run sanity checks
# -----------------------------------------------------------------------------
set -eu
ENV_NAME="${ENV_NAME:-sru_nav}"
PY_VER="${PY_VER:-3.8}" # match Noetic's system python so rospy works
USE_GPU=0
CHECK_ONLY=0
SKIP_TIME_CHECK=0
# Silence anaconda.org's noisy "aau_token_host" telemetry warnings.
export ANACONDA_ANON_USAGE=false
for arg in "$@"; do
case "$arg" in
--gpu) USE_GPU=1 ;;
--check) CHECK_ONLY=1 ;;
--skip-time-check) SKIP_TIME_CHECK=1 ;;
*) echo "Unknown arg: $arg"; exit 1 ;;
esac
done
# -----------------------------------------------------------------------------
# 0. System clock sanity. SSL fails with "certificate is not yet valid" when
# the Jetson clock is rolled back (no RTC battery). Detect early.
# -----------------------------------------------------------------------------
if [ "$SKIP_TIME_CHECK" -eq 0 ]; then
NOW_EPOCH=$(date +%s)
# 2025-01-01 UTC = 1735689600. Treat anything before that as suspicious.
if [ "$NOW_EPOCH" -lt 1735689600 ]; then
cat >&2 <<EOF
[ERROR] System clock looks wrong: $(date)
This will break HTTPS/pip with "certificate is not yet valid".
Fix it before continuing:
sudo timedatectl set-ntp true
sudo systemctl restart systemd-timesyncd
# or, offline:
sudo date -s "$(date -u +'%Y-%m-%d %H:%M:%S' -d '@1748400000')"
sudo hwclock --systohc
Then re-run this script. To override (NOT recommended) pass:
bash $0 --skip-time-check
EOF
exit 1
fi
fi
# -----------------------------------------------------------------------------
# 1. Locate conda
# -----------------------------------------------------------------------------
if ! command -v conda >/dev/null 2>&1; then
echo "[ERROR] conda not found. Install miniforge (recommended for aarch64):"
echo " wget https://github.com/conda-forge/miniforge/releases/latest/download/Miniforge3-Linux-aarch64.sh"
echo " bash Miniforge3-Linux-aarch64.sh -b -p \$HOME/miniforge3"
echo " source \$HOME/miniforge3/etc/profile.d/conda.sh"
exit 1
fi
CONDA_BASE="$(conda info --base)"
# shellcheck disable=SC1091
source "${CONDA_BASE}/etc/profile.d/conda.sh"
# -----------------------------------------------------------------------------
# 2. Create env if missing
# -----------------------------------------------------------------------------
if [ "$CHECK_ONLY" -eq 0 ]; then
if conda env list | awk '{print $1}' | grep -qx "${ENV_NAME}"; then
echo "[INFO] Conda env '${ENV_NAME}' already exists. Skipping creation."
else
echo "[INFO] Creating conda env '${ENV_NAME}' with python=${PY_VER}"
conda create -y -n "${ENV_NAME}" "python=${PY_VER}" pip
fi
fi
conda activate "${ENV_NAME}"
if [ "$CHECK_ONLY" -eq 0 ]; then
echo "[INFO] Installing Python dependencies into '${ENV_NAME}'"
# Optional: use a faster mirror (Tsinghua) if PIP_INDEX_URL is not already set.
: "${PIP_INDEX_URL:=}"
export PIP_INDEX_URL
echo "[INFO] PIP_INDEX_URL=${PIP_INDEX_URL}"
python -m pip install --upgrade pip
# Pin versions that are known to work on python 3.8 + ARM.
# netifaces / defusedxml are needed by rospy at runtime (the system ROS
# python gets them via apt 'python3-netifaces / python3-defusedxml', but
# the conda python does not).
python -m pip install \
"numpy<2.0" \
"scipy>=1.7,<1.11" \
"opencv-python>=4.5,<5.0" \
"rospkg" \
"pyyaml" \
"empy==3.3.4" \
"netifaces" \
"defusedxml"
if [ "$USE_GPU" -eq 1 ]; then
cat <<'EOF'
[INFO] --gpu requested. Standard pip onnxruntime-gpu does NOT work on Jetson.
Download the JetPack-matched wheel from NVIDIA's Jetson Zoo:
https://elinux.org/Jetson_Zoo#ONNX_Runtime
Then install with e.g.:
pip install ./onnxruntime_gpu-<ver>-cp38-cp38-linux_aarch64.whl
Skipping automatic GPU wheel install.
EOF
python -m pip install "onnxruntime>=1.15,<1.18" # CPU fallback so node still runs
else
python -m pip install "onnxruntime>=1.15,<1.18"
fi
fi
# -----------------------------------------------------------------------------
# 3. Sanity checks
# -----------------------------------------------------------------------------
echo
echo "============================================================"
echo " Sanity check: conda env '${ENV_NAME}'"
echo "============================================================"
python - <<'PYEOF'
import sys, platform
print(f"python : {sys.version.split()[0]} ({platform.machine()})")
fail = []
def check(name, importer):
try:
mod = importer()
ver = getattr(mod, "__version__", "?")
print(f" [OK] {name:18s} {ver}")
except Exception as e:
print(f" [FAIL] {name}: {e}")
fail.append(name)
check("numpy", lambda: __import__("numpy"))
check("scipy", lambda: __import__("scipy"))
check("cv2", lambda: __import__("cv2"))
check("rospkg", lambda: __import__("rospkg"))
check("netifaces", lambda: __import__("netifaces"))
check("defusedxml", lambda: __import__("defusedxml"))
check("onnxruntime", lambda: __import__("onnxruntime"))
try:
import onnxruntime as ort
print(f" ORT providers : {ort.get_available_providers()}")
except Exception:
pass
# rospy / cv_bridge come from /opt/ros/noetic; only succeed when PYTHONPATH is set.
import os
ros_path = "/opt/ros/noetic/lib/python3/dist-packages"
if os.path.isdir(ros_path) and ros_path not in sys.path:
sys.path.insert(0, ros_path)
check("rospy", lambda: __import__("rospy"))
check("cv_bridge", lambda: __import__("cv_bridge"))
if fail:
print(f"\n[WARN] Missing modules: {fail}")
sys.exit(1)
print("\n[OK] All imports passed.")
PYEOF
echo
echo "[INFO] Try loading the policy ONNX files (if present)..."
# Resolve the package's models/ directory relative to THIS script.
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
PKG_MODELS_DIR="$(cd "${SCRIPT_DIR}/../models" 2>/dev/null && pwd || echo '')"
export PKG_MODELS_DIR
python - <<'PYEOF'
import os, sys
candidates = [
os.environ.get("PKG_MODELS_DIR", ""),
os.path.expanduser("~/sru_ws/src/sru_nav_go2_ros1/models"),
]
candidates = [c for c in candidates if c]
import onnxruntime as ort
for d in candidates:
vae = os.path.join(d, "vae_encoder.onnx")
pol = os.path.join(d, "nav_policy.onnx")
if os.path.exists(vae) and os.path.exists(pol):
print(f" Found models in {d}")
try:
s1 = ort.InferenceSession(vae, providers=["CPUExecutionProvider"])
s2 = ort.InferenceSession(pol, providers=["CPUExecutionProvider"])
print(f" vae inputs : {[i.name+str(i.shape) for i in s1.get_inputs()]}")
print(f" vae outputs : {[o.name+str(o.shape) for o in s1.get_outputs()]}")
print(f" pol inputs : {[i.name+str(i.shape) for i in s2.get_inputs()]}")
print(f" pol outputs : {[o.name+str(o.shape) for o in s2.get_outputs()]}")
except Exception as e:
print(f" [FAIL] {e}")
break
else:
print(" (No models found; skipping ORT smoke test.)")
PYEOF
echo
echo "[DONE] Activate with: conda activate ${ENV_NAME}"
+107
View File
@@ -0,0 +1,107 @@
#!/usr/bin/env python3
"""ROS1 entry point for the SRU navigation controller on Go2 + Odin1."""
import os
import sys
import rospkg
import rospy
from sru_nav_go2.navigation_policy_node import NavigationPolicyNode
from sru_nav_go2 import constants
def _resolve_model_path(param_value, default_basename):
"""Resolve a model path: absolute path if given, else look under
<package>/models/<default_basename>, else fall back to the original
sru-robot-deployment/rl_nav_controller/deployment_policies/ folder if
present alongside this package's workspace.
"""
if param_value and os.path.isabs(param_value) and os.path.exists(param_value):
return param_value
rp = rospkg.RosPack()
try:
pkg_path = rp.get_path('sru_nav_go2_ros1')
except rospkg.ResourceNotFound:
pkg_path = None
candidates = []
if param_value:
candidates.append(param_value)
if pkg_path:
candidates.append(os.path.join(pkg_path, 'models', default_basename))
# Sibling deployment_policies folder (when sources are checked out together)
candidates.append(os.path.join(
pkg_path, '..', '..', 'sru-robot-deployment',
'rl_nav_controller', 'deployment_policies', default_basename))
for c in candidates:
if c and os.path.exists(c):
return os.path.abspath(c)
raise FileNotFoundError(
'Could not locate {} (checked: {})'.format(default_basename, candidates)
)
def main():
rospy.init_node('sru_nav_node', anonymous=False)
# --- Topics ---------------------------------------------------------
depth_topic = rospy.get_param('~depth_topic', '/odin1/depth_img_competetion')
odom_topic = rospy.get_param('~odom_topic', '/odin1/odometry_highfreq')
joy_topic = rospy.get_param('~joy_topic', '/joy')
goal_topic = rospy.get_param('~goal_topic', '/goal_pose')
cmd_vel_topic = rospy.get_param('~cmd_vel_topic', '/cmd_vel')
# --- Models ---------------------------------------------------------
vae_param = rospy.get_param('~vae_model_path', '')
pol_param = rospy.get_param('~policy_model_path', '')
try:
vae_model_path = _resolve_model_path(vae_param, 'vae_encoder.onnx')
policy_model_path = _resolve_model_path(pol_param, 'nav_policy.onnx')
except FileNotFoundError as exc:
rospy.logerr(str(exc))
sys.exit(1)
rospy.loginfo('VAE encoder: {}'.format(vae_model_path))
rospy.loginfo('Policy model: {}'.format(policy_model_path))
# --- Numeric params -------------------------------------------------
min_depth = rospy.get_param('~min_depth', constants.DEFAULT_MIN_DEPTH)
max_depth = rospy.get_param('~max_depth', constants.DEFAULT_MAX_DEPTH)
control_frequency = rospy.get_param(
'~control_frequency', constants.DEFAULT_CONTROL_FREQUENCY)
policy_scale = rospy.get_param('~policy_scale', list(constants.POLICY_SCALE))
use_sim = rospy.get_param('~use_sim', False)
require_joystick = rospy.get_param('~require_joystick', True)
if not isinstance(policy_scale, (list, tuple)) or len(policy_scale) != 3:
rospy.logwarn('Invalid ~policy_scale, falling back to {}'.format(
list(constants.POLICY_SCALE)))
policy_scale = list(constants.POLICY_SCALE)
NavigationPolicyNode(
preprocess_model_path=vae_model_path,
policy_model_path=policy_model_path,
depth_topic=depth_topic,
odom_topic=odom_topic,
joy_topic=joy_topic,
goal_topic=goal_topic,
cmd_vel_topic=cmd_vel_topic,
min_depth=min_depth,
max_depth=max_depth,
control_frequency=control_frequency,
policy_scale=policy_scale,
use_sim=use_sim,
require_joystick=require_joystick,
)
rospy.loginfo(
'SRU navigation node spinning (sim={}, require_joystick={}).'
.format(use_sim, require_joystick))
rospy.spin()
if __name__ == '__main__':
main()
+291
View File
@@ -0,0 +1,291 @@
#!/usr/bin/env bash
# -----------------------------------------------------------------------------
# verify_port.sh — automated acceptance checks for sru_nav_go2_ros1
#
# Run after generating (or updating) the package to confirm the port is
# self-consistent and ready for hardware testing.
#
# Usage:
# bash scripts/verify_port.sh # full check
# bash scripts/verify_port.sh --skip-roslaunch # skip the live node test
# ENV_NAME=my_env CATKIN_WS=/path bash scripts/verify_port.sh
#
# Exit code: 0 if everything passes, 1 otherwise.
# -----------------------------------------------------------------------------
set -u
ENV_NAME="${ENV_NAME:-sru_nav}"
ROS_DISTRO="${ROS_DISTRO:-noetic}"
CATKIN_WS="${CATKIN_WS:-$HOME/code/odin_sru_nav}"
PKG_DIR="$(cd "$(dirname "$0")/.." && pwd)"
SKIP_ROSLAUNCH=0
for arg in "$@"; do
case "$arg" in
--skip-roslaunch) SKIP_ROSLAUNCH=1 ;;
-h|--help)
sed -n '2,15p' "$0"; exit 0 ;;
esac
done
PASS=0
FAIL=0
WARN=0
c_red() { printf "\033[31m%s\033[0m" "$1"; }
c_green() { printf "\033[32m%s\033[0m" "$1"; }
c_yellow() { printf "\033[33m%s\033[0m" "$1"; }
ok() { echo " [$(c_green PASS)] $1"; PASS=$((PASS+1)); }
fail() { echo " [$(c_red FAIL)] $1"; FAIL=$((FAIL+1)); }
warn() { echo " [$(c_yellow WARN)] $1"; WARN=$((WARN+1)); }
info() { echo " [INFO] $1"; }
section() { echo; echo "=== $1 ==="; }
# -----------------------------------------------------------------------------
section "0. Environment"
# -----------------------------------------------------------------------------
info "PKG_DIR = ${PKG_DIR}"
info "CATKIN_WS = ${CATKIN_WS}"
info "ENV_NAME = ${ENV_NAME}"
info "ROS_DISTRO = ${ROS_DISTRO}"
# OS
if grep -q "Ubuntu 20.04" /etc/os-release 2>/dev/null; then
ok "Ubuntu 20.04 (Noetic-compatible)"
else
warn "OS is not Ubuntu 20.04 — Noetic may not run cleanly"
fi
# ROS
if [ -f "/opt/ros/${ROS_DISTRO}/setup.bash" ]; then
ok "ROS ${ROS_DISTRO} installed"
else
fail "/opt/ros/${ROS_DISTRO}/setup.bash not found"
fi
# Conda
if command -v conda >/dev/null 2>&1; then
ok "conda available ($(conda --version))"
else
fail "conda not found in PATH"
fi
# System clock
year=$(date +%Y)
if [ "$year" -ge 2024 ] && [ "$year" -le 2099 ]; then
ok "system clock looks sane ($(date '+%Y-%m-%d %H:%M:%S'))"
else
fail "system clock implausible ($(date)) — pip TLS will fail"
fi
# libffi
if ls /lib/*-linux-gnu/libffi.so.7 2>/dev/null >/dev/null; then
ok "system libffi.so.7 present (LD_PRELOAD target)"
elif ls /lib/*-linux-gnu/libffi.so.8 2>/dev/null >/dev/null; then
warn "only libffi.so.8 found — update launch_sru_nav.sh accordingly"
else
fail "no system libffi.so.* — cv_bridge will likely fail"
fi
# -----------------------------------------------------------------------------
section "1. Package layout"
# -----------------------------------------------------------------------------
req_files=(
"package.xml"
"CMakeLists.txt"
"setup.py"
"launch/sru_nav_go2.launch"
"config/sru_nav.yaml"
"scripts/sru_nav_node"
"scripts/launch_sru_nav.sh"
"scripts/setup_conda_env.sh"
"src/sru_nav_go2/__init__.py"
"src/sru_nav_go2/constants.py"
"src/sru_nav_go2/model.py"
"src/sru_nav_go2/utils.py"
"src/sru_nav_go2/visualization.py"
"src/sru_nav_go2/waypoint_manager.py"
"src/sru_nav_go2/navigation_policy_node.py"
"models/vae_encoder.onnx"
"models/nav_policy.onnx"
)
for f in "${req_files[@]}"; do
if [ -e "${PKG_DIR}/${f}" ]; then
ok "${f}"
else
fail "missing: ${f}"
fi
done
# -----------------------------------------------------------------------------
section "2. YAML config — required parameters"
# -----------------------------------------------------------------------------
YAML="${PKG_DIR}/config/sru_nav.yaml"
if [ -f "$YAML" ]; then
for key in depth_topic odom_topic joy_topic goal_topic cmd_vel_topic \
min_depth max_depth control_frequency policy_scale \
use_sim require_joystick; do
if grep -E "^[[:space:]]*${key}[[:space:]]*:" "$YAML" >/dev/null; then
ok "yaml has ${key}"
else
fail "yaml missing ${key}"
fi
done
else
fail "yaml not found"
fi
# -----------------------------------------------------------------------------
section "3. Constants — training-aligned numerics"
# -----------------------------------------------------------------------------
CONSTS="${PKG_DIR}/src/sru_nav_go2/constants.py"
if [ -f "$CONSTS" ]; then
declare -A want=(
[DEFAULT_CONTROL_FREQUENCY]="5"
[DEFAULT_MIN_DEPTH]="0.25"
[DEFAULT_MAX_DEPTH]="10"
[JOYSTICK_TIMEOUT]="15"
)
for k in "${!want[@]}"; do
if grep -E "^${k}\s*=\s*${want[$k]}" "$CONSTS" >/dev/null; then
ok "${k} = ${want[$k]}"
else
warn "${k} not exactly ${want[$k]} — verify against training cfg"
fi
done
else
fail "constants.py not found"
fi
# -----------------------------------------------------------------------------
section "4. Launch script — coexistence fixes"
# -----------------------------------------------------------------------------
LAUNCH_SH="${PKG_DIR}/scripts/launch_sru_nav.sh"
if [ -f "$LAUNCH_SH" ]; then
grep -q "LD_PRELOAD" "$LAUNCH_SH" && ok "LD_PRELOAD libffi fix present" \
|| fail "no LD_PRELOAD libffi fix"
grep -q "PYTHONPATH" "$LAUNCH_SH" && ok "ROS dist-packages injected to PYTHONPATH" \
|| fail "no PYTHONPATH injection"
grep -q "conda activate" "$LAUNCH_SH" && ok "conda activate in launcher" \
|| fail "no conda activate"
grep -q -- "--no-deadman" "$LAUNCH_SH" && ok "--no-deadman bypass present" \
|| warn "no --no-deadman flag"
fi
SETUP_SH="${PKG_DIR}/scripts/setup_conda_env.sh"
if [ -f "$SETUP_SH" ]; then
for pkg in onnxruntime netifaces defusedxml opencv-python rospkg empy; do
grep -q "$pkg" "$SETUP_SH" \
&& ok "setup installs ${pkg}" \
|| fail "setup script missing ${pkg}"
done
fi
# -----------------------------------------------------------------------------
section "5. ONNX models — load test"
# -----------------------------------------------------------------------------
if command -v python >/dev/null && python -c "import onnxruntime" 2>/dev/null; then
for f in "models/vae_encoder.onnx" "models/nav_policy.onnx"; do
full="${PKG_DIR}/${f}"
if [ -f "$full" ]; then
if python - <<EOF 2>/dev/null
import onnxruntime as ort, sys
s = ort.InferenceSession("${full}", providers=["CPUExecutionProvider"])
print(" ${f} inputs:", [(i.name, i.shape) for i in s.get_inputs()])
print(" ${f} outputs:", [(o.name, o.shape) for o in s.get_outputs()])
EOF
then
ok "${f} loads in onnxruntime"
else
fail "${f} failed to load (corrupt or wrong opset?)"
fi
fi
done
else
warn "onnxruntime not importable in current shell — skipping load test"
warn " hint: 'conda activate ${ENV_NAME}' before running verify_port.sh"
fi
# -----------------------------------------------------------------------------
section "6. catkin build artifacts (optional)"
# -----------------------------------------------------------------------------
WRAPPER="${CATKIN_WS}/devel/lib/sru_nav_go2_ros1/sru_nav_node"
if [ -f "$WRAPPER" ]; then
ok "catkin wrapper exists: ${WRAPPER}"
shebang=$(head -n1 "$WRAPPER")
if echo "$shebang" | grep -qE "miniconda|anaconda|envs/${ENV_NAME}"; then
ok "wrapper shebang points at conda python"
info " shebang: ${shebang}"
else
fail "wrapper shebang is NOT conda python: ${shebang}"
info " fix: 'conda activate ${ENV_NAME} && cd ${CATKIN_WS} && \\"
info " catkin_make clean && catkin_make -DPYTHON_EXECUTABLE=\$(which python3)'"
fi
else
warn "no catkin build artifact — run catkin_make in conda env first"
fi
# -----------------------------------------------------------------------------
section "7. Live roslaunch smoke test"
# -----------------------------------------------------------------------------
if [ "$SKIP_ROSLAUNCH" -eq 1 ]; then
info "skipped (--skip-roslaunch)"
elif [ ! -f "${CATKIN_WS}/devel/setup.bash" ]; then
warn "catkin workspace not built — skipping roslaunch test"
else
# shellcheck disable=SC1090
source "/opt/ros/${ROS_DISTRO}/setup.bash" || true
source "${CATKIN_WS}/devel/setup.bash" || true
if ! command -v roslaunch >/dev/null; then
fail "roslaunch not on PATH after sourcing"
else
LOG=$(mktemp)
timeout 12 roslaunch sru_nav_go2_ros1 sru_nav_go2.launch \
launch_joy:=false launch_static_tf:=false \
require_joystick:=false >"$LOG" 2>&1 &
RPID=$!
sleep 8
if grep -q "Navigation policy node is ready" "$LOG"; then
ok "node became ready within 8 s"
else
fail "node did not reach 'ready' state within 8 s"
info " last 20 log lines:"
tail -n 20 "$LOG" | sed 's/^/ /'
fi
kill "$RPID" 2>/dev/null
wait "$RPID" 2>/dev/null
rm -f "$LOG"
fi
fi
# -----------------------------------------------------------------------------
section "Summary"
# -----------------------------------------------------------------------------
echo " PASS=${PASS} FAIL=${FAIL} WARN=${WARN}"
if [ "$FAIL" -gt 0 ]; then
echo
c_red "RESULT: FAIL"; echo
exit 1
elif [ "$WARN" -gt 0 ]; then
echo
c_yellow "RESULT: PASS WITH WARNINGS"; echo
exit 0
else
echo
c_green "ALL CHECKS PASSED"; echo
exit 0
fi
+331
View File
@@ -0,0 +1,331 @@
#!/usr/bin/env python3
"""Sequential waypoint runner for sru_nav_go2_ros1.
Publishes a list of goals to /goal_pose one at a time, monitors the robot
odometry to decide when each goal is reached (or has timed out, or the robot
is stuck), then moves on to the next. After the last waypoint, optionally
returns to the pose captured at script start.
Does NOT modify any code in sru_nav_go2_ros1. Works purely as an external
client on top of the existing /goal_pose + /odin1/odometry_highfreq contract.
Usage
-----
# YAML file
rosrun sru_nav_go2_ros1 waypoint_runner.py --file waypoints.yaml
# Command line (x,y[,z] tuples separated by spaces)
rosrun sru_nav_go2_ros1 waypoint_runner.py \
--waypoints "3,0 3,2 0,2" --return-home
YAML format
-----------
frame_id: odom
arrive_threshold: 0.75 # meters, XY distance to consider 'arrived'
settle_time: 1.5 # seconds the robot must stay within threshold
per_goal_timeout: 60.0 # seconds before giving up on a goal
stuck_window: 10.0 # seconds of trailing window for stuck check
stuck_displacement: 0.10 # meters; below this in `stuck_window` -> skip
republish_interval: 5.0 # seconds; re-publish the same goal periodically
return_home: true
waypoints:
- [3.0, 0.0, 0.0]
- [3.0, 2.0, 0.0]
- [0.0, 2.0, 0.0]
"""
import argparse
import collections
import math
import os
import sys
import time
import rospy
import yaml
from geometry_msgs.msg import PoseStamped
from nav_msgs.msg import Odometry
# ---------------------------------------------------------------------------
# Defaults (mirror sru_nav_go2_ros1/constants.py where applicable)
# ---------------------------------------------------------------------------
DEFAULTS = dict(
frame_id='odom',
arrive_threshold=0.75, # matches constants.ARRIVE_GOAL_THRESHOLD
settle_time=1.5,
per_goal_timeout=60.0,
stuck_window=10.0,
stuck_displacement=0.10,
republish_interval=5.0,
return_home=True,
odom_topic='/odin1/odometry_highfreq',
goal_topic='/goal_pose',
)
# ---------------------------------------------------------------------------
# Parsing
# ---------------------------------------------------------------------------
def _parse_inline_waypoints(text):
"""Parse "x,y[,z] x,y[,z] ..." into list[list[float]]."""
out = []
if not text:
return out
for tok in text.split():
parts = tok.split(',')
if len(parts) not in (2, 3):
raise ValueError(
"Bad waypoint '{}': expected 'x,y' or 'x,y,z'".format(tok))
xyz = [float(parts[0]), float(parts[1]),
float(parts[2]) if len(parts) == 3 else 0.0]
out.append(xyz)
return out
def _load_yaml(path):
with open(path, 'r') as f:
data = yaml.safe_load(f) or {}
if 'waypoints' not in data or not data['waypoints']:
raise ValueError("YAML '{}' has no 'waypoints' list.".format(path))
norm = []
for wp in data['waypoints']:
if len(wp) not in (2, 3):
raise ValueError("Bad waypoint {} (need 2 or 3 floats).".format(wp))
x = float(wp[0]); y = float(wp[1])
z = float(wp[2]) if len(wp) == 3 else 0.0
norm.append([x, y, z])
data['waypoints'] = norm
return data
def build_config(args):
cfg = dict(DEFAULTS)
if args.file:
cfg.update({k: v for k, v in _load_yaml(args.file).items() if v is not None})
# Command-line overrides win over YAML
if args.waypoints:
cfg['waypoints'] = _parse_inline_waypoints(args.waypoints)
if args.frame_id is not None:
cfg['frame_id'] = args.frame_id
if args.timeout is not None:
cfg['per_goal_timeout'] = float(args.timeout)
if args.arrive_threshold is not None:
cfg['arrive_threshold'] = float(args.arrive_threshold)
if args.return_home is not None:
cfg['return_home'] = args.return_home
if 'waypoints' not in cfg or not cfg['waypoints']:
raise ValueError("No waypoints provided (use --file or --waypoints).")
return cfg
# ---------------------------------------------------------------------------
# Runner
# ---------------------------------------------------------------------------
class WaypointRunner(object):
def __init__(self, cfg):
self.cfg = cfg
self._pose = None # latest (x, y, z, t)
self._pose_history = collections.deque() # entries: (t, x, y)
self._home = None # (x, y, z) captured at first odom
self.goal_pub = rospy.Publisher(
cfg['goal_topic'], PoseStamped, queue_size=1, latch=True)
self.odom_sub = rospy.Subscriber(
cfg['odom_topic'], Odometry, self._odom_cb, queue_size=20)
rospy.loginfo("waypoint_runner: waiting for first odom on '%s' ...",
cfg['odom_topic'])
self._wait_for_odom(timeout=30.0)
self._home = (self._pose[0], self._pose[1], self._pose[2])
rospy.loginfo("waypoint_runner: home pose captured at "
"x=%.3f y=%.3f z=%.3f", *self._home)
# Give the latched publisher a moment so the first goal isn't lost.
time.sleep(0.5)
# --------------------------------------------------------------- callbacks
def _odom_cb(self, msg):
t = msg.header.stamp.to_sec() or rospy.get_time()
p = msg.pose.pose.position
self._pose = (p.x, p.y, p.z, t)
self._pose_history.append((t, p.x, p.y))
# Trim history to a bit more than stuck_window
cutoff = t - max(self.cfg['stuck_window'] * 2.0, 5.0)
while self._pose_history and self._pose_history[0][0] < cutoff:
self._pose_history.popleft()
def _wait_for_odom(self, timeout):
t0 = time.time()
rate = rospy.Rate(20)
while not rospy.is_shutdown() and self._pose is None:
if time.time() - t0 > timeout:
raise RuntimeError(
"No odometry received on '{}' within {:.1f}s.".format(
self.cfg['odom_topic'], timeout))
rate.sleep()
# ------------------------------------------------------------------ goals
def _publish_goal(self, xyz):
msg = PoseStamped()
msg.header.stamp = rospy.Time.now()
msg.header.frame_id = self.cfg['frame_id']
msg.pose.position.x = float(xyz[0])
msg.pose.position.y = float(xyz[1])
msg.pose.position.z = float(xyz[2])
msg.pose.orientation.w = 1.0
self.goal_pub.publish(msg)
def _xy_dist(self, ax, ay, bx, by):
return math.hypot(ax - bx, ay - by)
def _displacement_in_window(self, window):
"""Max XY distance between any two samples within trailing `window` s."""
# Snapshot first: _odom_cb runs in the subscriber thread and may
# append/popleft while we iterate, which raises
# "deque mutated during iteration".
snapshot = list(self._pose_history)
if not snapshot:
return 0.0
now = snapshot[-1][0]
cutoff = now - window
pts = [(x, y) for (t, x, y) in snapshot if t >= cutoff]
if len(pts) < 2:
return 0.0
xs = [p[0] for p in pts]; ys = [p[1] for p in pts]
# Bounding box diagonal is a cheap, monotone proxy for "did it move".
return math.hypot(max(xs) - min(xs), max(ys) - min(ys))
def _run_goal(self, idx, total, xyz, label):
cfg = self.cfg
rospy.loginfo("\033[96m[%d/%d %s] -> x=%.3f y=%.3f z=%.3f\033[0m",
idx, total, label, xyz[0], xyz[1], xyz[2])
self._publish_goal(xyz)
t_start = time.time()
t_last_pub = t_start
within_since = None
rate = rospy.Rate(10)
while not rospy.is_shutdown():
now = time.time()
elapsed = now - t_start
# 1) Timeout
if elapsed > cfg['per_goal_timeout']:
rospy.logwarn("[%d/%d %s] TIMEOUT after %.1fs; skipping.",
idx, total, label, elapsed)
return 'timeout'
# 2) Stuck check (only after the window has elapsed)
if elapsed > cfg['stuck_window']:
disp = self._displacement_in_window(cfg['stuck_window'])
if disp < cfg['stuck_displacement']:
rospy.logwarn(
"[%d/%d %s] STUCK (disp=%.3fm < %.3fm in last %.1fs); "
"skipping.", idx, total, label, disp,
cfg['stuck_displacement'], cfg['stuck_window'])
return 'stuck'
# 3) Arrived?
x, y, _z, _t = self._pose
d = self._xy_dist(x, y, xyz[0], xyz[1])
if d <= cfg['arrive_threshold']:
if within_since is None:
within_since = now
elif (now - within_since) >= cfg['settle_time']:
rospy.loginfo(
"\033[92m[%d/%d %s] ARRIVED (d=%.2fm, settled %.1fs)"
"\033[0m", idx, total, label, d, cfg['settle_time'])
return 'arrived'
else:
within_since = None
# 4) Periodic re-publish (protects against missed first publish)
if (cfg['republish_interval'] > 0
and (now - t_last_pub) >= cfg['republish_interval']):
self._publish_goal(xyz)
t_last_pub = now
rospy.loginfo_throttle(
5.0, "[%d/%d %s] re-published goal (d=%.2fm, t=%.1fs)",
idx, total, label, d, elapsed)
rate.sleep()
return 'shutdown'
def run(self):
cfg = self.cfg
wps = list(cfg['waypoints'])
if cfg['return_home']:
wps.append(list(self._home))
total = len(wps)
results = []
for i, wp in enumerate(wps, start=1):
label = 'HOME' if (cfg['return_home'] and i == total) else 'WP'
res = self._run_goal(i, total, wp, label)
results.append((i, label, wp, res))
if rospy.is_shutdown():
break
# Summary
rospy.loginfo("\033[95m===== waypoint_runner summary =====\033[0m")
for i, label, wp, res in results:
rospy.loginfo(" %2d/%d %s (%.2f, %.2f, %.2f) -> %s",
i, total, label, wp[0], wp[1], wp[2], res)
rospy.loginfo("\033[95m===================================\033[0m")
# ---------------------------------------------------------------------------
# Entry point
# ---------------------------------------------------------------------------
def parse_args(argv):
p = argparse.ArgumentParser(description=__doc__,
formatter_class=argparse.RawDescriptionHelpFormatter)
p.add_argument('--file', '-f', type=str, default=None,
help='YAML file with waypoints and (optional) parameters.')
p.add_argument('--waypoints', '-w', type=str, default=None,
help='Space-separated "x,y[,z]" tuples (overrides YAML).')
p.add_argument('--frame-id', type=str, default=None,
help="Goal frame_id (default 'odom').")
p.add_argument('--timeout', type=float, default=None,
help='Per-goal timeout in seconds.')
p.add_argument('--arrive-threshold', type=float, default=None,
help='XY arrival threshold in meters.')
g = p.add_mutually_exclusive_group()
g.add_argument('--return-home', dest='return_home', action='store_true',
default=None, help='Append start pose as final goal.')
g.add_argument('--no-return-home', dest='return_home', action='store_false',
help='Do not return to start pose after last waypoint.')
return p.parse_args(argv)
def main():
args = parse_args(rospy.myargv()[1:])
try:
cfg = build_config(args)
except (ValueError, OSError) as exc:
sys.stderr.write('[waypoint_runner] config error: {}\n'.format(exc))
sys.exit(2)
rospy.init_node('waypoint_runner', anonymous=False)
rospy.loginfo('waypoint_runner config:')
for k in ('frame_id', 'arrive_threshold', 'settle_time',
'per_goal_timeout', 'stuck_window', 'stuck_displacement',
'republish_interval', 'return_home', 'odom_topic', 'goal_topic'):
rospy.loginfo(' %s = %r', k, cfg[k])
rospy.loginfo(' waypoints (%d):', len(cfg['waypoints']))
for i, wp in enumerate(cfg['waypoints'], 1):
rospy.loginfo(' %2d: (%.3f, %.3f, %.3f)', i, *wp)
runner = WaypointRunner(cfg)
try:
runner.run()
except rospy.ROSInterruptException:
pass
if __name__ == '__main__':
main()