First test of direct can control on the wheels

This commit is contained in:
Matt Spencer committed 2026-10-13 16:22:44 +00:00
1 parent e317c10f7f
commit 3f12a62044
20 files changed
+1101 -127

No files matched your search

@@ -102,6 +102,12 @@ private:
void clear_serial_buffer(int fd);
void disable_dtr_rts(int fd);
// Brings up can_interface_name_ (e.g. "ip link set can0 up type can bitrate 1000000")
// right after power_on() succeeds -- i.e. only once 24V is confirmed applied to the
// servos. Only used in sensors-only mode (enable_wheels=false) when wheels are driven by
// a separate CAN hardware component. No-op (returns true) if can_interface_name_ is empty.
bool bring_up_can_interface();
// ── Background serial reader ────────────────────────────────────────────────
void reader_thread_func();
void process_byte(uint8_t byte);
@@ -130,6 +136,17 @@ private:
// ── Configuration (from <hardware><param> in URDF) ─────────────────────────
std::string port_name_;
// When false (hardware param enable_wheels=false), no wheel joints are exported and
// read()/write() skip all wheel velocity logic — only IMU/voltage/IO/LED run. Used when
// wheels are controlled by a separate hardware component (e.g. robstride_ros2/RobStrideSystem
// over CAN) instead.
bool wheels_enabled_{true};
// CAN interface to bring up after serial power-on succeeds (enable_wheels=false only).
// Empty string disables this (e.g. wheel_interface=serial, no separate CAN bus to manage).
std::string can_interface_name_;
double wheel_radius_; // metres
double lx_; // half wheelbase: robot centre → axle (x-axis), metres
double ly_; // half track: robot centre → wheel (y-axis), metres
@@ -176,6 +193,12 @@ private:
std::array<double, 4> wheel_velocities_{0.0, 0.0, 0.0, 0.0};
std::array<double, 4> wheel_commands_{0.0, 0.0, 0.0, 0.0};
// Exported as a "power_status/connected" GPIO state interface -- controller_manager
// skips configure/activate entirely for a hardware component with zero interfaces, so
// this also guarantees enable_wheels=false (sensors-only) components actually get
// activated (which is where power_on()/CAN bring-up happen).
double power_status_connected_{0.0};
// ── ROS publishers and services (created in on_configure via get_node()) ─────
rclcpp::Publisher<sensor_msgs::msg::Imu>::SharedPtr imu_pub_;
rclcpp::Publisher<std_msgs::msg::Float32>::SharedPtr voltage_pub_;
@@ -6,6 +6,7 @@
#include <cmath>
#include <cstring>
#include <iomanip>
#include <regex>
#include <sstream>
#include <stdexcept>
@@ -139,19 +140,59 @@ void AgvProHardwareInterface::disable_dtr_rts(int fd)
}
}
// Bringing can_interface_name_ UP while it was already up is what causes the sibling
// USB-serial port's DTR/RTS ioctl (see disable_dtr_rts / on_activate) to hang on this rig --
// so the CAN link must stay down until AFTER the serial power-on handshake below completes.
// This is only called post power-on, so it is the natural, event-driven place to do it
// (vs. guessing a fixed delay in the launch file).
bool AgvProHardwareInterface::bring_up_can_interface()
{
if (can_interface_name_.empty()) {
return true;
}
// Defence in depth: this string ends up in a shell command below, so reject anything
// that isn't a plain interface name before building it.
static const std::regex kValidIfaceName("^[a-zA-Z0-9_]+$");
if (!std::regex_match(can_interface_name_, kValidIfaceName)) {
RCLCPP_ERROR(get_logger(), "Refusing to bring up CAN interface with unsafe name: '%s'",
can_interface_name_.c_str());
return false;
}
std::string cmd =
"ip link set " + can_interface_name_ + " txqueuelen 1000 && " +
"ip link set " + can_interface_name_ + " up type can bitrate 1000000";
RCLCPP_INFO(get_logger(), "Motors powered on — bringing up CAN interface '%s'…",
can_interface_name_.c_str());
int rc = std::system(cmd.c_str());
if (rc != 0) {
RCLCPP_ERROR(get_logger(),
"Failed to bring up CAN interface '%s' (exit code %d) — it may already be up, or this "
"process may be missing NET_ADMIN", can_interface_name_.c_str(), rc);
return false;
}
RCLCPP_INFO(get_logger(), "CAN interface '%s' is up", can_interface_name_.c_str());
return true;
}
bool AgvProHardwareInterface::power_on()
{
// 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 activation/CAN bring-up on it.
auto query = build_frame(CMD_GET_POWER, {});
auto resp = send_and_receive(query, {0xFE, 0xFE, 0x0B, CMD_GET_POWER}, 8, 12.0);
if (resp.size() != 14) {
RCLCPP_ERROR(get_logger(), "power_on: no response to GET_POWER query");
return false;
RCLCPP_WARN(get_logger(), "power_on: no response to GET_POWER query — assuming powered");
return true;
}
uint16_t rx_crc = (resp[12] << 8) | resp[13];
if (rx_crc != crc16_ibm(resp.data(), 12)) {
RCLCPP_ERROR(get_logger(), "power_on: CRC mismatch in GET_POWER response");
return false;
RCLCPP_WARN(get_logger(), "power_on: CRC mismatch in GET_POWER response — assuming powered");
return true;
}
int state = static_cast<int8_t>(resp[4]);
@@ -166,21 +207,21 @@ bool AgvProHardwareInterface::power_on()
auto on_resp = send_and_receive(on_cmd, {0xFE, 0xFE, 0x0B, CMD_POWER_ON}, 8, 5.0);
if (on_resp.size() != 14) {
RCLCPP_ERROR(get_logger(), "power_on: no response to POWER_ON command");
return false;
RCLCPP_WARN(get_logger(), "power_on: no response to POWER_ON command — assuming powered");
return true;
}
uint16_t crc2 = (on_resp[12] << 8) | on_resp[13];
if (crc2 != crc16_ibm(on_resp.data(), 12)) {
RCLCPP_ERROR(get_logger(), "power_on: CRC mismatch in POWER_ON response");
return false;
RCLCPP_WARN(get_logger(), "power_on: CRC mismatch in POWER_ON response — assuming powered");
return true;
}
int ps = static_cast<int8_t>(on_resp[4]);
if (ps == 1) {
RCLCPP_INFO(get_logger(), "Motors powered on successfully");
return true;
}
RCLCPP_ERROR(get_logger(), "power_on: firmware error code %d", ps);
return false;
RCLCPP_WARN(get_logger(), "power_on: firmware error code %d — assuming powered", ps);
return true;
}
RCLCPP_INFO(get_logger(), "Motors already on (status=%d)", state);
@@ -490,18 +531,37 @@ hardware_interface::CallbackReturn AgvProHardwareInterface::on_init(
return hardware_interface::CallbackReturn::ERROR;
}
if (info_.joints.size() != 4) {
RCLCPP_FATAL(get_logger(),
"Expected exactly 4 joints in <ros2_control>, got %zu", info_.joints.size());
return hardware_interface::CallbackReturn::ERROR;
}
// ── Parse hardware parameters ──────────────────────────────────────────────
auto get_param = [&](const std::string & key, const std::string & def) -> std::string {
auto it = info_.hardware_parameters.find(key);
return (it != info_.hardware_parameters.end()) ? it->second : def;
};
// When false, this interface runs in "sensors-only" mode: no wheel joints are exported
// and velocity commands are not sent, because wheel control has moved to a separate
// hardware component (e.g. robstride_ros2/RobStrideSystem wired to a CAN bus).
// IMU/voltage/IO/LED keep working unchanged either way.
wheels_enabled_ = get_param("enable_wheels", "true") == "true";
if (wheels_enabled_ && info_.joints.size() != 4) {
RCLCPP_FATAL(get_logger(),
"Expected exactly 4 joints in <ros2_control>, got %zu", info_.joints.size());
return hardware_interface::CallbackReturn::ERROR;
}
if (!wheels_enabled_ && !info_.joints.empty()) {
RCLCPP_FATAL(get_logger(),
"enable_wheels=false expects 0 joints in <ros2_control>, got %zu", info_.joints.size());
return hardware_interface::CallbackReturn::ERROR;
}
if (!wheels_enabled_) {
port_name_ = get_param("port_name", "/dev/agvpro_controller");
can_interface_name_ = get_param("can_interface_name", "");
RCLCPP_INFO(get_logger(),
"Wheel control disabled — running in sensors-only mode (IMU/voltage/IO/LED only)");
return hardware_interface::CallbackReturn::SUCCESS;
}
port_name_ = get_param("port_name", "/dev/agvpro_controller");
wheel_radius_ = std::stod(get_param("wheel_radius", "0.072"));
lx_ = std::stod(get_param("lx", "0.172"));
@@ -613,15 +673,24 @@ hardware_interface::CallbackReturn AgvProHardwareInterface::on_activate(
RCLCPP_INFO(get_logger(), "Waiting 3 s for ESP32 to initialise …");
std::this_thread::sleep_for(std::chrono::seconds(3));
// ── Power on motors ────────────────────────────────────────────────────────
if (!power_on()) {
RCLCPP_FATAL(get_logger(), "Motor power-on failed");
serial_port_->close();
return hardware_interface::CallbackReturn::ERROR;
// ── Power on motors / bring up CAN ────────────────────────────────────────
// In CAN mode (can_interface_name_ set), the launch-level can_power_on.py pre-step
// already did both of these before controller_manager even started, and the serial
// board no longer controls servo power at all once the wheel CAN bus is rewired to
// the external USB-CAN adapter -- so skip this slow (and now pointless) serial
// handshake here, rather than stalling the cyclic read/write loop for ~15-30s on an
// unresponsive command and risking a read-cycle overrun/deactivation.
if (can_interface_name_.empty()) {
if (!power_on()) {
RCLCPP_FATAL(get_logger(), "Motor power-on failed");
serial_port_->close();
return hardware_interface::CallbackReturn::ERROR;
}
}
// ── Start auto-report stream from ESP32 ───────────────────────────────────
set_auto_report(true);
power_status_connected_ = 1.0;
// ── Reset state and start reader thread ───────────────────────────────────
wheel_positions_.fill(0.0);
@@ -642,8 +711,10 @@ hardware_interface::CallbackReturn AgvProHardwareInterface::on_deactivate(
const rclcpp_lifecycle::State & /*previous_state*/)
{
// ── Send zero velocity before deactivating ─────────────────────────────────
auto zero_frame = build_frame(CMD_VELOCITY_CMD, {0, 0, 0, 0, 0, 0, 0, 0});
send_frame(zero_frame);
if (wheels_enabled_) {
auto zero_frame = build_frame(CMD_VELOCITY_CMD, {0, 0, 0, 0, 0, 0, 0, 0});
send_frame(zero_frame);
}
// ── Stop reader thread ─────────────────────────────────────────────────────
reader_running_ = false;
@@ -655,6 +726,7 @@ hardware_interface::CallbackReturn AgvProHardwareInterface::on_deactivate(
// ── Disable auto-report ────────────────────────────────────────────────────
set_auto_report(false);
power_status_connected_ = 0.0;
RCLCPP_INFO(get_logger(), "AGV Pro hardware interface deactivated");
return hardware_interface::CallbackReturn::SUCCESS;
@@ -687,6 +759,8 @@ AgvProHardwareInterface::on_export_state_interfaces()
hardware_interface::HW_IF_VELOCITY,
&wheel_velocities_[i]));
}
interfaces.push_back(std::make_shared<const hardware_interface::StateInterface>(
"power_status", "connected", &power_status_connected_));
return interfaces;
}
@@ -709,6 +783,10 @@ hardware_interface::return_type AgvProHardwareInterface::read(
const rclcpp::Time & /*time*/,
const rclcpp::Duration & period)
{
if (!wheels_enabled_) {
return hardware_interface::return_type::OK;
}
double vx, vy, vtheta;
{
std::lock_guard<std::mutex> lock(data_mutex_);
@@ -753,6 +831,10 @@ hardware_interface::return_type AgvProHardwareInterface::write(
const rclcpp::Time & /*time*/,
const rclcpp::Duration & /*period*/)
{
if (!wheels_enabled_) {
return hardware_interface::return_type::OK;
}
// Mecanum forward kinematics: wheel velocity commands → body frame
//
// vx = (r/4) · (ω_FL + ω_FR + ω_RL + ω_RR)