diff --git a/src/elephant_robotics/agv_pro_bringup/scripts/can_power_on.py b/src/elephant_robotics/agv_pro_bringup/scripts/can_power_on.py index cd35cbf..d700a80 100755 --- a/src/elephant_robotics/agv_pro_bringup/scripts/can_power_on.py +++ b/src/elephant_robotics/agv_pro_bringup/scripts/can_power_on.py @@ -15,6 +15,7 @@ stay in sync if the firmware protocol ever changes. """ import argparse import fcntl +import json import os import re import struct @@ -204,10 +205,34 @@ def release_esp32_reset(port_name: str) -> None: "continuing to CAN bring-up", file=sys.stderr) +def can_link_already_up(interface: str) -> bool: + """True if the link is already UP at 1 Mbit/s in normal mode. + + The interface may be shared with another controller (the arm's CANopen stack + on the same adapter); taking it down here would drop that traffic. + """ + result = subprocess.run(["ip", "-details", "-json", "link", "show", interface], + capture_output=True, text=True) + if result.returncode != 0: + return False + try: + link = json.loads(result.stdout)[0] + info = link["linkinfo"]["info_data"] + return ("UP" in link.get("flags", []) + and info.get("bittiming", {}).get("bitrate") == 1000000 + and "LISTEN-ONLY" not in info.get("ctrlmode", []) + and info.get("state") not in ("BUS-OFF", "STOPPED")) + except (ValueError, KeyError, IndexError): + return False + + def bring_up_can(interface: str) -> bool: if not re.match(r"^[a-zA-Z0-9_]+$", interface): print(f"ERROR: refusing unsafe interface name '{interface}'", file=sys.stderr) return False + if can_link_already_up(interface): + print(f"CAN interface '{interface}' is already up at 1 Mbit/s; leaving it as is") + return True print(f"Bringing up CAN interface '{interface}'...") try: # The link is often still UP from a previous run of this container, and the