Harden base bring-up against CH340 control-transfer timeouts

The CH340 behind /dev/agvpro_controller rejects USB control transfers for up
to ~60s after a host reboot (kernel: "failed to send control message: -110"),
surfacing as TimeoutError from the TIOCMSET ioctl that clears DTR/RTS. Since
clearing DTR/RTS is what releases the ESP32's reset line, a single failed
attempt leaves the ESP32 held in reset and all its sensors silent.

can_power_on.py:
- open_serial_when_ready(): retry the open with backoff (60s budget) instead
  of dying on the first timeout. open_serial() now closes the fd if setup
  fails partway.
- try_power_on(): report success only when servo power is actually confirmed.
  Previously every failure path returned True ("assuming powered"), so a
  GET_POWER status of 0 followed by an unanswered POWER_ON still counted as
  success and the stack continued with the wheels unpowered.
- Retry the handshake 5 times before falling back to the permissive
  behaviour, and log loudly when it does.
- Never let a dead serial port block CAN bring-up. The wheel drives are on
  CAN and are not powered by this board, so a dead ESP32 must only cost
  IMU/voltage/IO/LED -- never the ability to drive.
- bring_up_can(): set the link down first so it is idempotent. The bitrate
  cannot be set on an already-UP link, so any restart where the link was
  still up aborted the launch and crash-looped the base stack.

agv_pro_hardware_interface.cpp:
- disable_dtr_rts(): retry briefly (2s budget), then continue rather than
  give up instantly. This runs in on_activate after AgvProWheelsSystem is
  already active, so a long block here starves the wheel read cycle until it
  errors out and the controllers lose their interfaces -- hence the small
  budget. can_power_on.py has normally already released the ESP32 by then.
This commit is contained in:
Matt Spencer committed 2026-10-26 07:22:04 -07:00
1 parent 8b0d1c363d
commit e2285c46f0
2 files changed
+138 -60

No files matched your search

@@ -26,6 +26,13 @@ import time
CMD_POWER_ON = 0x10 CMD_POWER_ON = 0x10
CMD_GET_POWER = 0x12 CMD_GET_POWER = 0x12
# After a host reboot the CH340 rejects control transfers (TIOCMSET -> ETIMEDOUT,
# kernel logs "failed to send control message: -110") for up to ~60s while the
# ESP32 behind it is still coming up. Observed window was ~44s. Exceeding this
# budget is non-fatal -- see main().
SERIAL_READY_TIMEOUT = 60.0
POWER_ON_ATTEMPTS = 5
def crc16_ibm(data: bytes) -> int: def crc16_ibm(data: bytes) -> int:
crc = 0xFFFF crc = 0xFFFF
@@ -84,70 +91,102 @@ def read_response(fd: int, expected_header: bytes, payload_size: int, timeout: f
def open_serial(port_name: str) -> int: def open_serial(port_name: str) -> int:
fd = os.open(port_name, os.O_RDWR | os.O_NOCTTY | os.O_NONBLOCK) fd = os.open(port_name, os.O_RDWR | os.O_NOCTTY | os.O_NONBLOCK)
attrs = termios.tcgetattr(fd) try:
# iflag, oflag, cflag, lflag, ispeed, ospeed, cc attrs = termios.tcgetattr(fd)
attrs[0] = 0 # iflag, oflag, cflag, lflag, ispeed, ospeed, cc
attrs[1] = 0 attrs[0] = 0
attrs[2] = termios.CS8 | termios.CREAD | termios.CLOCAL attrs[1] = 0
attrs[3] = 0 attrs[2] = termios.CS8 | termios.CREAD | termios.CLOCAL
attrs[4] = termios.B1000000 attrs[3] = 0
attrs[5] = termios.B1000000 attrs[4] = termios.B1000000
termios.tcsetattr(fd, termios.TCSANOW, attrs) attrs[5] = termios.B1000000
termios.tcflush(fd, termios.TCIOFLUSH) termios.tcsetattr(fd, termios.TCSANOW, attrs)
termios.tcflush(fd, termios.TCIOFLUSH)
# disable_dtr_rts(): release the ESP32 reset line # disable_dtr_rts(): release the ESP32 reset line
status = struct.unpack('i', fcntl.ioctl(fd, termios.TIOCMGET, struct.pack('i', 0)))[0] status = struct.unpack('i', fcntl.ioctl(fd, termios.TIOCMGET, struct.pack('i', 0)))[0]
status &= ~(termios.TIOCM_DTR | termios.TIOCM_RTS) status &= ~(termios.TIOCM_DTR | termios.TIOCM_RTS)
fcntl.ioctl(fd, termios.TIOCMSET, struct.pack('i', status)) fcntl.ioctl(fd, termios.TIOCMSET, struct.pack('i', status))
except Exception:
os.close(fd)
raise
return fd return fd
def open_serial_when_ready(port_name: str, timeout: float = SERIAL_READY_TIMEOUT) -> int:
deadline = time.time() + timeout
delay = 1.0
while True:
try:
return open_serial(port_name)
except (OSError, termios.error) as exc:
if time.time() >= deadline:
raise
print(f"WARNING: {port_name} not ready yet ({exc}); retrying in {delay:.0f}s",
file=sys.stderr)
time.sleep(delay)
delay = min(delay * 2.0, 5.0)
def try_power_on(fd: int) -> bool:
"""One GET_POWER/POWER_ON round trip. True only if power is actually confirmed."""
termios.tcflush(fd, termios.TCIFLUSH)
os.write(fd, build_frame(CMD_GET_POWER))
resp = read_response(fd, bytes([0xFE, 0xFE, 0x0B, CMD_GET_POWER]), 8, 12.0)
if len(resp) != 14:
print("WARNING: no response to GET_POWER query", file=sys.stderr)
return False
if struct.unpack('>H', resp[12:14])[0] != crc16_ibm(resp[:12]):
print("WARNING: CRC mismatch in GET_POWER response", file=sys.stderr)
return False
state = struct.unpack('b', resp[4:5])[0]
print(f"GET_POWER status: {state}")
if state != 0:
print(f"Motors already on (status={state})")
return True
on_cmd = build_frame(CMD_POWER_ON)
os.write(fd, on_cmd)
time.sleep(1.0)
# Mirrors C++ send_and_receive(): writes the command again right before
# reading the response (the firmware only replies to this second send).
os.write(fd, on_cmd)
on_resp = read_response(fd, bytes([0xFE, 0xFE, 0x0B, CMD_POWER_ON]), 8, 5.0)
if len(on_resp) != 14:
print("WARNING: no response to POWER_ON command", file=sys.stderr)
return False
if struct.unpack('>H', on_resp[12:14])[0] != crc16_ibm(on_resp[:12]):
print("WARNING: CRC mismatch in POWER_ON response", file=sys.stderr)
return False
ps = struct.unpack('b', on_resp[4:5])[0]
if ps == 1:
print("Motors powered on successfully")
return True
print(f"WARNING: firmware error code {ps}", file=sys.stderr)
return False
def power_on(port_name: str) -> bool: def power_on(port_name: str) -> bool:
# The serial base controller no longer controls servo power at all once the wheel # The serial base controller no longer controls servo power at all once the wheel
# CAN bus has been rewired to the external USB-CAN adapter, so this handshake isn't # CAN bus has been rewired to the external USB-CAN adapter, so this handshake isn't
# authoritative any more -- treat any failure/non-response as a warning and assume # authoritative any more -- after exhausting the retries below we still assume the
# the servos are already powered, rather than blocking CAN bring-up on it. # servos are powered rather than blocking CAN bring-up forever.
fd = open_serial(port_name) fd = open_serial_when_ready(port_name)
try: try:
print("Waiting 3s for ESP32 to initialise...") print("Waiting 3s for ESP32 to initialise...")
time.sleep(3.0) time.sleep(3.0)
os.write(fd, build_frame(CMD_GET_POWER)) for attempt in range(1, POWER_ON_ATTEMPTS + 1):
resp = read_response(fd, bytes([0xFE, 0xFE, 0x0B, CMD_GET_POWER]), 8, 12.0) print(f"Power-on handshake attempt {attempt}/{POWER_ON_ATTEMPTS}")
if len(resp) != 14: if try_power_on(fd):
print("WARNING: no response to GET_POWER query - assuming powered", file=sys.stderr) return True
return True time.sleep(2.0)
if struct.unpack('>H', resp[12:14])[0] != crc16_ibm(resp[:12]):
print("WARNING: CRC mismatch in GET_POWER response - assuming powered",
file=sys.stderr)
return True
state = struct.unpack('b', resp[4:5])[0]
print(f"GET_POWER status: {state}")
if state == 0: print(f"WARNING: servo power NOT confirmed after {POWER_ON_ATTEMPTS} attempts - "
on_cmd = build_frame(CMD_POWER_ON) "assuming powered; expect no wheel traffic if the base is really off",
os.write(fd, on_cmd) file=sys.stderr)
time.sleep(1.0)
# Mirrors C++ send_and_receive(): writes the command again right before
# reading the response (the firmware only replies to this second send).
os.write(fd, on_cmd)
on_resp = read_response(fd, bytes([0xFE, 0xFE, 0x0B, CMD_POWER_ON]), 8, 5.0)
if len(on_resp) != 14:
print("WARNING: no response to POWER_ON command - assuming powered",
file=sys.stderr)
return True
if struct.unpack('>H', on_resp[12:14])[0] != crc16_ibm(on_resp[:12]):
print("WARNING: CRC mismatch in POWER_ON response - assuming powered",
file=sys.stderr)
return True
ps = struct.unpack('b', on_resp[4:5])[0]
if ps == 1:
print("Motors powered on successfully")
return True
print(f"WARNING: firmware error code {ps} - assuming powered", file=sys.stderr)
return True
print(f"Motors already on (status={state})")
return True return True
finally: finally:
os.close(fd) os.close(fd)
@@ -159,6 +198,11 @@ def bring_up_can(interface: str) -> bool:
return False return False
print(f"Bringing up CAN interface '{interface}'...") print(f"Bringing up CAN interface '{interface}'...")
try: try:
# The link is often still UP from a previous run of this container, and the
# bitrate can't be set on a live link -- so force it down first, exactly as
# can-arm-up.service does. Without this, every restart fails here and the
# launch file refuses to start the whole base stack.
subprocess.run(["ip", "link", "set", interface, "down"], check=False)
subprocess.run(["ip", "link", "set", interface, "txqueuelen", "1000"], check=True) subprocess.run(["ip", "link", "set", interface, "txqueuelen", "1000"], check=True)
subprocess.run( subprocess.run(
["ip", "link", "set", interface, "up", "type", "can", "bitrate", "1000000"], ["ip", "link", "set", interface, "up", "type", "can", "bitrate", "1000000"],
@@ -176,9 +220,15 @@ def main() -> None:
ap.add_argument("--can-interface-name", default="can0") ap.add_argument("--can-interface-name", default="can0")
args = ap.parse_args() args = ap.parse_args()
if not power_on(args.port_name): # The wheel drives sit on CAN and are NOT powered by this serial board, so a dead
print("FATAL: serial power-on failed", file=sys.stderr) # ESP32 link must only cost the base its IMU/voltage/IO/LED -- never its ability to
sys.exit(1) # drive. Bring the CAN link up regardless.
try:
power_on(args.port_name)
except (OSError, termios.error) as exc:
print(f"WARNING: serial power-on unavailable ({exc}); continuing to CAN bring-up "
"-- wheels will still work, ESP32 sensors will not", file=sys.stderr)
if not bring_up_can(args.can_interface_name): if not bring_up_can(args.can_interface_name):
sys.exit(1) sys.exit(1)
sys.exit(0) sys.exit(0)
@@ -3,12 +3,15 @@
#include <poll.h> #include <poll.h>
#include <termios.h> #include <termios.h>
#include <sys/ioctl.h> #include <sys/ioctl.h>
#include <algorithm>
#include <chrono>
#include <cmath> #include <cmath>
#include <cstring> #include <cstring>
#include <iomanip> #include <iomanip>
#include <regex> #include <regex>
#include <sstream> #include <sstream>
#include <stdexcept> #include <stdexcept>
#include <thread>
#include "pluginlib/class_list_macros.hpp" #include "pluginlib/class_list_macros.hpp"
#include "hardware_interface/types/hardware_interface_type_values.hpp" #include "hardware_interface/types/hardware_interface_type_values.hpp"
@@ -129,14 +132,39 @@ void AgvProHardwareInterface::clear_serial_buffer(int fd)
} }
} }
// Clearing DTR/RTS is what releases the ESP32's reset line, and the CH340 sometimes
// rejects the ioctl (kernel: "failed to send control message: -110").
//
// This runs inside on_activate, AFTER AgvProWheelsSystem is already active, so blocking
// here starves the wheel read cycle until it errors and gets deactivated -- which
// releases the interfaces the controllers need and fails the whole base stack. Keep the
// budget small and give up rather than stall: can_power_on.py has already opened the port
// and cleared these lines moments earlier, so the ESP32 is normally out of reset anyway.
void AgvProHardwareInterface::disable_dtr_rts(int fd) void AgvProHardwareInterface::disable_dtr_rts(int fd)
{ {
int status; constexpr std::chrono::milliseconds kBudget{2000};
if (::ioctl(fd, TIOCMGET, &status) == 0) { const auto deadline = std::chrono::steady_clock::now() + kBudget;
status &= ~(TIOCM_DTR | TIOCM_RTS); auto delay = std::chrono::milliseconds(100);
if (::ioctl(fd, TIOCMSET, &status) != 0) {
RCLCPP_WARN(get_logger(), "Failed to clear DTR/RTS: %s", std::strerror(errno)); for (;;) {
int status;
if (::ioctl(fd, TIOCMGET, &status) == 0) {
status &= ~(TIOCM_DTR | TIOCM_RTS);
if (::ioctl(fd, TIOCMSET, &status) == 0) {
return;
}
} }
if (std::chrono::steady_clock::now() >= deadline) {
RCLCPP_WARN(get_logger(),
"Failed to clear DTR/RTS within %ld ms: %s -- continuing anyway; if the ESP32 was "
"not already released by can_power_on.py, its IMU/voltage/IO will be unavailable",
static_cast<long>(kBudget.count()), std::strerror(errno));
return;
}
std::this_thread::sleep_for(delay);
delay = std::min(delay * 2, std::chrono::milliseconds(400));
} }
} }