4 Commits
Author SHA1 Message Date
Matthew Spencer 900d2de8b6 Update can poier up script 2026-12-02 12:46:37 +00:00
Matthew Spencer 179606910a Make the serial POWER_ON handshake optional in can_power_on.py
The serial base controller no longer powers the wheel servos now that the
wheels are on the external USB-CAN adapter, so GET_POWER/POWER_ON guards
nothing. With an unresponsive ESP32 it cost ~70 s of timeouts on every boot
before the script gave up and assumed power anyway.

Add --serial-handshake {true,false} (default true, unchanged). With false,
the serial port is still opened once, bounded to 5 s, so DTR/RTS are cleared
before the CAN link comes up, then CAN is brought up immediately.
2026-11-05 13:28:32 +00:00
Matt Spencer e2285c46f0 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.
2026-10-26 07:22:04 -07:00
Matt Spencer 8b0d1c363d Update wheel configuration in URDF 2026-10-20 14:01:10 -07:00
4 changed files with 161 additions and 37 deletions

No files matched your search

+3 -2
View File
@@ -104,8 +104,9 @@ package, after empirically confirming real CAN communication with the wheel driv
to confirm it applies the same convention end-to-end.
- [ ] Determine real `gear_ratio` (currently 1.0 placeholder) from the drivetrain so
commanded/measured velocity is in correct SI units at the wheel.
- [ ] Tune `kp`/`kd` velocity-mode gains (currently placeholder `kp=0.0 kd=0.8`) for the
real mecanum drivetrain.
- [ ] Finish tuning `kp`/`kd` velocity-mode gains for the real mecanum drivetrain.
`kp=0.0 kd=2.0` could not sustain a continuous in-place yaw against scrub friction;
`kd=3.5` is the next live-test value (RS01 maximum is 5.0).
- [ ] Confirm `can_timeout_ticks` (currently the package default, 4000 ticks = 200 ms) is an
appropriate watchdog window for this platform.
- [ ] Build-test: `colcon build` will build `robstride_ros2` and `ros2_socketcan` from
@@ -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
@@ -26,6 +27,16 @@ import time
CMD_POWER_ON = 0x10
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
# Without the handshake the serial port is only opened to release the ESP32 reset line,
# so don't hold up CAN bring-up for the full post-reboot CH340 window.
NO_HANDSHAKE_SERIAL_TIMEOUT = 5.0
def crc16_ibm(data: bytes) -> int:
crc = 0xFFFF
@@ -84,6 +95,7 @@ def read_response(fd: int, expected_header: bytes, payload_size: int, timeout: f
def open_serial(port_name: str) -> int:
fd = os.open(port_name, os.O_RDWR | os.O_NOCTTY | os.O_NONBLOCK)
try:
attrs = termios.tcgetattr(fd)
# iflag, oflag, cflag, lflag, ispeed, ospeed, cc
attrs[0] = 0
@@ -99,32 +111,46 @@ def open_serial(port_name: str) -> int:
status = struct.unpack('i', fcntl.ioctl(fd, termios.TIOCMGET, struct.pack('i', 0)))[0]
status &= ~(termios.TIOCM_DTR | termios.TIOCM_RTS)
fcntl.ioctl(fd, termios.TIOCMSET, struct.pack('i', status))
except Exception:
os.close(fd)
raise
return fd
def power_on(port_name: str) -> bool:
# 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
# authoritative any more -- treat any failure/non-response as a warning and assume
# the servos are already powered, rather than blocking CAN bring-up on it.
fd = open_serial(port_name)
def open_serial_when_ready(port_name: str, timeout: float = SERIAL_READY_TIMEOUT) -> int:
deadline = time.time() + timeout
delay = 1.0
while True:
try:
print("Waiting 3s for ESP32 to initialise...")
time.sleep(3.0)
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 - assuming powered", file=sys.stderr)
return True
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 - assuming powered",
file=sys.stderr)
return True
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:
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)
@@ -133,32 +159,87 @@ def power_on(port_name: str) -> bool:
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
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 - assuming powered",
file=sys.stderr)
return True
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} - assuming powered", file=sys.stderr)
return True
print(f"WARNING: firmware error code {ps}", file=sys.stderr)
return False
print(f"Motors already on (status={state})")
def power_on(port_name: str) -> bool:
# 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
# authoritative any more -- after exhausting the retries below we still assume the
# servos are powered rather than blocking CAN bring-up forever.
fd = open_serial_when_ready(port_name)
try:
print("Waiting 3s for ESP32 to initialise...")
time.sleep(3.0)
for attempt in range(1, POWER_ON_ATTEMPTS + 1):
print(f"Power-on handshake attempt {attempt}/{POWER_ON_ATTEMPTS}")
if try_power_on(fd):
return True
time.sleep(2.0)
print(f"WARNING: servo power NOT confirmed after {POWER_ON_ATTEMPTS} attempts - "
"assuming powered; expect no wheel traffic if the base is really off",
file=sys.stderr)
return True
finally:
os.close(fd)
def release_esp32_reset(port_name: str) -> None:
"""Clear DTR/RTS (via open_serial) before CAN comes up, without any handshake."""
try:
os.close(open_serial_when_ready(port_name, NO_HANDSHAKE_SERIAL_TIMEOUT))
except (OSError, termios.error) as exc:
print(f"WARNING: could not open {port_name} to release the ESP32 ({exc}); "
"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
# 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, "up", "type", "can", "bitrate", "1000000"],
@@ -174,11 +255,24 @@ def main() -> None:
ap = argparse.ArgumentParser()
ap.add_argument("--port-name", default="/dev/agvpro_controller")
ap.add_argument("--can-interface-name", default="can0")
ap.add_argument("--serial-handshake", choices=["true", "false"], default="true",
help="false skips GET_POWER/POWER_ON (the serial board no longer controls "
"servo power) and only releases the ESP32 reset line")
args = ap.parse_args()
if not power_on(args.port_name):
print("FATAL: serial power-on failed", file=sys.stderr)
sys.exit(1)
if args.serial_handshake == "false":
release_esp32_reset(args.port_name)
sys.exit(0 if bring_up_can(args.can_interface_name) else 1)
# The wheel drives sit on CAN and are NOT powered by this serial board, so a dead
# ESP32 link must only cost the base its IMU/voltage/IO/LED -- never its ability to
# 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):
sys.exit(1)
sys.exit(0)
@@ -142,9 +142,10 @@
flipped to -1 so a positive command consistently means "forward" on every wheel.
This assumes robstride_ros2's `direction` negates both command and feedback
consistently; not yet live-validated by commanding a wheel and watching it spin.
kp/kd and command_velocity_min/max are placeholder starting gains/limits — tune for
the real mecanum drivetrain. mecanum_drive_controller only commands velocity, so Kp
is zeroed automatically by the driver in velocity mode (see robstride_ros2 README).
mecanum_drive_controller only commands velocity, so Kp is zeroed automatically by
the driver in velocity mode. Kd=2.0 could not sustain in-place rotation against
mecanum scrub friction during a continuous -0.4 rad/s yaw test; use 3.5 as the next
bounded tuning step. RS01 permits Kd up to 5.0.
-->
<xacro:include filename="$(find robstride_ros2_control)/description/robstride_motor_profiles.xacro"/>
@@ -158,22 +159,22 @@
<param name="feedback_timeout_ms">8000</param>
</hardware>
<joint name="${prefix}front_left_wheel_joint">
<xacro:robstride_rs01_params can_id="1" direction="-1" kp="0.0" kd="0.8"
<xacro:robstride_rs01_params can_id="1" direction="-1" kp="0.0" kd="3.5"
command_velocity_min="-30.0" command_velocity_max="30.0"/>
<xacro:robstride_joint_interfaces/>
</joint>
<joint name="${prefix}front_right_wheel_joint">
<xacro:robstride_rs01_params can_id="2" direction="1" kp="0.0" kd="0.8"
<xacro:robstride_rs01_params can_id="2" direction="1" kp="0.0" kd="3.5"
command_velocity_min="-30.0" command_velocity_max="30.0"/>
<xacro:robstride_joint_interfaces/>
</joint>
<joint name="${prefix}rear_left_wheel_joint">
<xacro:robstride_rs01_params can_id="3" direction="-1" kp="0.0" kd="0.8"
<xacro:robstride_rs01_params can_id="3" direction="-1" kp="0.0" kd="3.5"
command_velocity_min="-30.0" command_velocity_max="30.0"/>
<xacro:robstride_joint_interfaces/>
</joint>
<joint name="${prefix}rear_right_wheel_joint">
<xacro:robstride_rs01_params can_id="4" direction="1" kp="0.0" kd="0.8"
<xacro:robstride_rs01_params can_id="4" direction="1" kp="0.0" kd="3.5"
command_velocity_min="-30.0" command_velocity_max="30.0"/>
<xacro:robstride_joint_interfaces/>
</joint>
@@ -3,12 +3,15 @@
#include <poll.h>
#include <termios.h>
#include <sys/ioctl.h>
#include <algorithm>
#include <chrono>
#include <cmath>
#include <cstring>
#include <iomanip>
#include <regex>
#include <sstream>
#include <stdexcept>
#include <thread>
#include "pluginlib/class_list_macros.hpp"
#include "hardware_interface/types/hardware_interface_type_values.hpp"
@@ -129,15 +132,40 @@ 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)
{
constexpr std::chrono::milliseconds kBudget{2000};
const auto deadline = std::chrono::steady_clock::now() + kBudget;
auto delay = std::chrono::milliseconds(100);
for (;;) {
int status;
if (::ioctl(fd, TIOCMGET, &status) == 0) {
status &= ~(TIOCM_DTR | TIOCM_RTS);
if (::ioctl(fd, TIOCMSET, &status) != 0) {
RCLCPP_WARN(get_logger(), "Failed to clear DTR/RTS: %s", std::strerror(errno));
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));
}
}
// Bringing can_interface_name_ UP while it was already up is what causes the sibling