#!/usr/bin/env bash set -euo pipefail usage() { cat <<'USAGE' Usage: sudo scripts/ethercat/stop_ethercat.sh [iface] [--restore-network] Before unloading the drivers, the script asks cmvr_es processes using an EtherCAT master to exit. Suspended instances are resumed to finish shutdown. Examples: sudo scripts/ethercat/stop_ethercat.sh eno1 sudo scripts/ethercat/stop_ethercat.sh eno1 --restore-network Environment: IGH_ROOT=... Override bundled IgH install path. ETHERCAT_CONF=... Override ethercatctl config path. USAGE } if [[ "${1:-}" == "-h" || "${1:-}" == "--help" ]]; then usage exit 0 fi if [[ "$(id -u)" -ne 0 ]]; then echo "error: please run with sudo." >&2 exit 1 fi IFACE="eno1" RESTORE_NETWORK="false" for arg in "$@"; do case "${arg}" in --restore-network) RESTORE_NETWORK="true" ;; -*) echo "error: unknown option: ${arg}" >&2 usage >&2 exit 1 ;; *) IFACE="${arg}" ;; esac done SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" REPO_ROOT="$(cd "${SCRIPT_DIR}/../.." && pwd)" IGH_ROOT="${IGH_ROOT:-${REPO_ROOT}/dependency/x86/third_party/ethercat/v1.7.0}" ETHERCAT_CONF="${ETHERCAT_CONF:-${IGH_ROOT}/etc/ethercat.conf}" ETHERCATCTL="${IGH_ROOT}/sbin/ethercatctl" if [[ ! -x "${ETHERCATCTL}" ]]; then echo "error: ethercatctl not found: ${ETHERCATCTL}" >&2 exit 1 fi stop_cmvr_clients() { (( $# > 0 )) || return 0 if ! command -v fuser >/dev/null; then echo "error: fuser (psmisc) is required to check EtherCAT device usage." >&2 return 1 fi local pid exe deadline local -A seen=() for pid in $(fuser "$@" 2>/dev/null); do [[ -z "${seen[$pid]:-}" ]] || continue seen[$pid]=1 exe=$(readlink "/proc/$pid/exe") || continue case "$exe" in */cmvr_es|*/'cmvr_es (deleted)') ;; *) continue ;; esac echo "Requesting shutdown of cmvr_es (PID $pid)..." if kill -TERM "$pid" && [[ $(ps -o state= -p "$pid") == T ]]; then kill -CONT "$pid" || true fi done deadline=$((SECONDS + 15)) while fuser -s "$@"; do if (( SECONDS >= deadline )); then echo "error: EtherCAT devices are still in use after 15s. Current holders:" >&2 fuser -v "$@" >&2 || true return 1 fi sleep 0.2 done } shopt -s nullglob stop_cmvr_clients /dev/EtherCAT[0-9]* "${ETHERCATCTL}" -c "${ETHERCAT_CONF}" stop if [[ "${RESTORE_NETWORK}" == "true" ]]; then ip link set "${IFACE}" up if command -v nmcli >/dev/null 2>&1; then nmcli device connect "${IFACE}" || true fi echo "Stopped EtherCAT and requested normal network restore on ${IFACE}." else echo "Stopped EtherCAT. Normal network restore skipped." echo "Use '--restore-network' if this interface should return to NetworkManager." fi