First test of direct can control on the wheels
This commit is contained in:
1 parent
e317c10f7f
commit
3f12a62044
20 files changed
+1101
-127
No files matched your search
@@ -14,6 +14,11 @@ install(DIRECTORY
|
||||
DESTINATION share/${PROJECT_NAME}/
|
||||
)
|
||||
|
||||
install(PROGRAMS
|
||||
scripts/can_power_on.py
|
||||
DESTINATION lib/${PROJECT_NAME}
|
||||
)
|
||||
|
||||
if(BUILD_TESTING)
|
||||
find_package(ament_lint_auto REQUIRED)
|
||||
set(ament_cmake_copyright_FOUND TRUE)
|
||||
|
||||
@@ -1,12 +1,19 @@
|
||||
import os
|
||||
from launch import LaunchDescription
|
||||
from launch.conditions import IfCondition
|
||||
from launch.conditions import IfCondition, UnlessCondition
|
||||
from launch_ros.actions import Node, PushRosNamespace
|
||||
from launch.actions import DeclareLaunchArgument, IncludeLaunchDescription, TimerAction
|
||||
from launch.actions import (
|
||||
DeclareLaunchArgument,
|
||||
ExecuteProcess,
|
||||
IncludeLaunchDescription,
|
||||
RegisterEventHandler,
|
||||
TimerAction,
|
||||
)
|
||||
from launch.event_handlers import OnProcessExit
|
||||
from launch.substitutions import Command, LaunchConfiguration, PythonExpression
|
||||
from launch.launch_description_sources import PythonLaunchDescriptionSource
|
||||
from launch.launch_description_sources import AnyLaunchDescriptionSource, PythonLaunchDescriptionSource
|
||||
from launch_ros.parameter_descriptions import ParameterValue
|
||||
from ament_index_python.packages import get_package_share_directory
|
||||
from ament_index_python.packages import get_package_prefix, get_package_share_directory
|
||||
|
||||
def include_lidar(pkg_name, launch_file, enable_lidar, lidar_type, expected_type):
|
||||
|
||||
@@ -32,6 +39,8 @@ def generate_launch_description():
|
||||
namespace = LaunchConfiguration('namespace')
|
||||
lidar_type = LaunchConfiguration('lidar_type')
|
||||
enable_lidar = LaunchConfiguration('enable_lidar')
|
||||
wheel_interface = LaunchConfiguration('wheel_interface')
|
||||
can_interface_name = LaunchConfiguration('can_interface_name')
|
||||
|
||||
urdf_file = os.path.join(
|
||||
get_package_share_directory('agv_pro_description'),
|
||||
@@ -49,6 +58,10 @@ def generate_launch_description():
|
||||
PythonExpression(['"', namespace, '" + "/" if "', namespace, '" != "" else ""']),
|
||||
' port_name:=',
|
||||
port_name_arg,
|
||||
' wheel_interface:=',
|
||||
wheel_interface,
|
||||
' can_interface_name:=',
|
||||
can_interface_name,
|
||||
]),
|
||||
value_type=str
|
||||
)
|
||||
@@ -77,6 +90,44 @@ def generate_launch_description():
|
||||
description='Lidar type: n10p | mid360 | l2'
|
||||
)
|
||||
|
||||
declare_wheel_interface_arg = DeclareLaunchArgument(
|
||||
'wheel_interface',
|
||||
default_value='serial',
|
||||
description=(
|
||||
"Wheel control path: 'serial' (default, exact current behaviour -- wheels + "
|
||||
"IMU/voltage/IO/LED all via port_name) or 'can' (wheels via CAN using the "
|
||||
"RobStride private protocol, driven by robstride_ros2 + a ros2_socketcan "
|
||||
"bridge on can_interface_name; IMU/voltage/IO/LED still via port_name)."
|
||||
)
|
||||
)
|
||||
|
||||
declare_can_interface_name_arg = DeclareLaunchArgument(
|
||||
'can_interface_name',
|
||||
default_value='can0',
|
||||
description="SocketCAN interface name, used only when wheel_interface:=can"
|
||||
)
|
||||
|
||||
# Bridges can0 <-> can_msgs/msg/Frame on to_can_bus/from_can_bus, the topics
|
||||
# robstride_ros2/RobStrideSystem talks to by default. Binds the CAN socket at startup
|
||||
# even while the link is still administratively down -- it starts seeing frames once
|
||||
# the can_power_on launch pre-step (below) brings the link up. Only
|
||||
# `sudo modprobe gs_usb` needs to happen on the host ahead of time (creates the
|
||||
# can_interface_name node in the down state) -- see top-level README; do NOT bring the
|
||||
# link up manually, it must stay down until the pre-step runs.
|
||||
can_bridge = IncludeLaunchDescription(
|
||||
AnyLaunchDescriptionSource(
|
||||
os.path.join(
|
||||
get_package_share_directory('ros2_socketcan'),
|
||||
'launch',
|
||||
'socket_can_bridge.launch.xml'
|
||||
)
|
||||
),
|
||||
launch_arguments={'interface': can_interface_name}.items(),
|
||||
condition=IfCondition(
|
||||
PythonExpression(["'", wheel_interface, "' == 'can'"])
|
||||
)
|
||||
)
|
||||
|
||||
ns_action = PushRosNamespace(namespace)
|
||||
|
||||
ros2_controllers_yaml = os.path.join(
|
||||
@@ -85,60 +136,96 @@ def generate_launch_description():
|
||||
'ros2_controllers.yaml'
|
||||
)
|
||||
|
||||
# controller_manager loads the hardware plugin (serial comms, wheel states)
|
||||
# and manages the controllers.
|
||||
controller_manager = Node(
|
||||
package='controller_manager',
|
||||
executable='ros2_control_node',
|
||||
parameters=[
|
||||
{'robot_description': robot_description_content},
|
||||
ros2_controllers_yaml,
|
||||
is_can = PythonExpression(["'", wheel_interface, "' == 'can'"])
|
||||
|
||||
def make_core_nodes(condition=None):
|
||||
# controller_manager loads the hardware plugin (serial comms, wheel states)
|
||||
# and manages the controllers.
|
||||
controller_manager = Node(
|
||||
package='controller_manager',
|
||||
executable='ros2_control_node',
|
||||
parameters=[
|
||||
{'robot_description': robot_description_content},
|
||||
ros2_controllers_yaml,
|
||||
],
|
||||
output='screen',
|
||||
condition=condition,
|
||||
)
|
||||
|
||||
robot_state_pub = Node(
|
||||
package='robot_state_publisher',
|
||||
executable='robot_state_publisher',
|
||||
name='robot_state_publisher',
|
||||
parameters=[{'robot_description': robot_description_content}],
|
||||
output='screen',
|
||||
condition=condition,
|
||||
)
|
||||
|
||||
# joint_state_broadcaster publishes /joint_states from the hardware interface.
|
||||
# Replaces the old static joint_state_publisher.
|
||||
joint_state_broadcaster_spawner = Node(
|
||||
package='controller_manager',
|
||||
executable='spawner',
|
||||
arguments=[
|
||||
'joint_state_broadcaster',
|
||||
'--controller-manager', 'controller_manager',
|
||||
],
|
||||
output='screen',
|
||||
condition=condition,
|
||||
)
|
||||
|
||||
# mecanum_drive_controller subscribes to ~/reference (TwistStamped). Remap it
|
||||
# to the standard /cmd_vel so nav2 and teleop work without extra flags
|
||||
# (teleop still needs stamped:=true).
|
||||
# NOTE: the remap key MUST be the private name '~/reference' — a bare
|
||||
# 'reference:=/cmd_vel' is silently ignored and the controller stays on
|
||||
# /mecanum_drive_controller/reference.
|
||||
# Delayed slightly so controller_manager is ready before spawning.
|
||||
mecanum_drive_controller_spawner = TimerAction(
|
||||
period=2.0,
|
||||
actions=[
|
||||
Node(
|
||||
package='controller_manager',
|
||||
executable='spawner',
|
||||
arguments=[
|
||||
'mecanum_drive_controller',
|
||||
'--controller-manager', 'controller_manager',
|
||||
'--controller-ros-args', '-r ~/reference:=/cmd_vel',
|
||||
],
|
||||
output='screen',
|
||||
)
|
||||
],
|
||||
condition=condition,
|
||||
)
|
||||
return [controller_manager, robot_state_pub, joint_state_broadcaster_spawner,
|
||||
mecanum_drive_controller_spawner]
|
||||
|
||||
# In 'can' mode, bring up the wheel CAN interface BEFORE controller_manager starts, as
|
||||
# a launch-level pre-step -- ros2_control does not guarantee hardware component
|
||||
# activation order, so AgvProWheelsSystem (over CAN) can otherwise race ahead of
|
||||
# can0 actually being up. See /memories/repo/agv_can_serial_hw_notes.md.
|
||||
can_power_on = ExecuteProcess(
|
||||
cmd=[
|
||||
os.path.join(
|
||||
get_package_prefix('agv_pro_bringup'), 'lib', 'agv_pro_bringup',
|
||||
'can_power_on.py'
|
||||
),
|
||||
'--port-name', port_name_arg,
|
||||
'--can-interface-name', can_interface_name,
|
||||
],
|
||||
output='screen',
|
||||
condition=IfCondition(is_can),
|
||||
)
|
||||
|
||||
robot_state_pub = Node(
|
||||
package='robot_state_publisher',
|
||||
executable='robot_state_publisher',
|
||||
name='robot_state_publisher',
|
||||
parameters=[{'robot_description': robot_description_content}],
|
||||
output='screen'
|
||||
start_core_after_can_power_on = RegisterEventHandler(
|
||||
OnProcessExit(
|
||||
target_action=can_power_on,
|
||||
on_exit=make_core_nodes(),
|
||||
),
|
||||
condition=IfCondition(is_can),
|
||||
)
|
||||
|
||||
# joint_state_broadcaster publishes /joint_states from the hardware interface.
|
||||
# Replaces the old static joint_state_publisher.
|
||||
joint_state_broadcaster_spawner = Node(
|
||||
package='controller_manager',
|
||||
executable='spawner',
|
||||
arguments=[
|
||||
'joint_state_broadcaster',
|
||||
'--controller-manager', 'controller_manager',
|
||||
],
|
||||
output='screen',
|
||||
)
|
||||
|
||||
# mecanum_drive_controller subscribes to ~/reference (TwistStamped). Remap it
|
||||
# to the standard /cmd_vel so nav2 and teleop work without extra flags
|
||||
# (teleop still needs stamped:=true).
|
||||
# NOTE: the remap key MUST be the private name '~/reference' — a bare
|
||||
# 'reference:=/cmd_vel' is silently ignored and the controller stays on
|
||||
# /mecanum_drive_controller/reference.
|
||||
# Delayed slightly so controller_manager is ready before spawning.
|
||||
mecanum_drive_controller_spawner = TimerAction(
|
||||
period=2.0,
|
||||
actions=[
|
||||
Node(
|
||||
package='controller_manager',
|
||||
executable='spawner',
|
||||
arguments=[
|
||||
'mecanum_drive_controller',
|
||||
'--controller-manager', 'controller_manager',
|
||||
'--controller-ros-args', '-r ~/reference:=/cmd_vel',
|
||||
],
|
||||
output='screen',
|
||||
)
|
||||
]
|
||||
)
|
||||
core_nodes_immediate = make_core_nodes(condition=UnlessCondition(is_can))
|
||||
|
||||
lidar_launchs = [
|
||||
include_lidar('lslidar_driver', 'lsn10p_launch.py', enable_lidar, lidar_type, 'n10p'),
|
||||
@@ -152,11 +239,13 @@ def generate_launch_description():
|
||||
declare_namespace_arg,
|
||||
declare_enable_lidar_arg,
|
||||
declare_lidar_type_arg,
|
||||
declare_wheel_interface_arg,
|
||||
declare_can_interface_name_arg,
|
||||
ns_action,
|
||||
controller_manager,
|
||||
robot_state_pub,
|
||||
joint_state_broadcaster_spawner,
|
||||
mecanum_drive_controller_spawner,
|
||||
can_bridge,
|
||||
can_power_on,
|
||||
start_core_after_can_power_on,
|
||||
*core_nodes_immediate,
|
||||
*lidar_launchs,
|
||||
]
|
||||
)
|
||||
@@ -14,6 +14,7 @@
|
||||
<exec_depend>joint_state_broadcaster</exec_depend>
|
||||
<exec_depend>agv_pro_hardware</exec_depend>
|
||||
<exec_depend>agv_pro_description</exec_depend>
|
||||
<exec_depend>ros2_socketcan</exec_depend>
|
||||
<exec_depend>rviz2</exec_depend>
|
||||
<exec_depend>cartographer_ros</exec_depend>
|
||||
<exec_depend>livox_ros_driver2</exec_depend>
|
||||
|
||||
@@ -0,0 +1,188 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Serial POWER_ON handshake, then bring up the wheel CAN interface.
|
||||
|
||||
Run ONCE, by the launch file, BEFORE controller_manager starts -- so
|
||||
AgvProWheelsSystem (over CAN) can never race ahead of the serial base
|
||||
controller's power-on sequence (ros2_control does not guarantee hardware
|
||||
component activation order). The CAN link must stay administratively DOWN
|
||||
until this succeeds: on this hardware, bringing it up earlier blocks the
|
||||
serial port's DTR/RTS ioctl (shared USB bus). See
|
||||
/memories/repo/agv_can_serial_hw_notes.md for the full story.
|
||||
|
||||
Mirrors agv_pro_hardware/AgvProHardwareInterface's power_on()/
|
||||
bring_up_can_interface() C++ logic exactly (same wire protocol), so the two
|
||||
stay in sync if the firmware protocol ever changes.
|
||||
"""
|
||||
import argparse
|
||||
import fcntl
|
||||
import os
|
||||
import re
|
||||
import struct
|
||||
import subprocess
|
||||
import sys
|
||||
import termios
|
||||
import time
|
||||
|
||||
CMD_POWER_ON = 0x10
|
||||
CMD_GET_POWER = 0x12
|
||||
|
||||
|
||||
def crc16_ibm(data: bytes) -> int:
|
||||
crc = 0xFFFF
|
||||
for b in data:
|
||||
crc ^= b
|
||||
for _ in range(8):
|
||||
crc = (crc >> 1) ^ 0xA001 if (crc & 1) else (crc >> 1)
|
||||
return crc
|
||||
|
||||
|
||||
def build_frame(cmd_id: int, payload: bytes = b"") -> bytes:
|
||||
frame = bytearray(14)
|
||||
frame[0] = 0xFE
|
||||
frame[1] = 0xFE
|
||||
frame[2] = 0x0B
|
||||
frame[3] = cmd_id
|
||||
for i, b in enumerate(payload[:8]):
|
||||
frame[4 + i] = b
|
||||
crc = crc16_ibm(bytes(frame[:12]))
|
||||
frame[12] = (crc >> 8) & 0xFF
|
||||
frame[13] = crc & 0xFF
|
||||
return bytes(frame)
|
||||
|
||||
|
||||
def read_response(fd: int, expected_header: bytes, payload_size: int, timeout: float) -> bytes:
|
||||
start = time.time()
|
||||
window = bytearray()
|
||||
all_bytes = bytearray()
|
||||
rest_needed = payload_size + 2
|
||||
while time.time() - start < timeout:
|
||||
try:
|
||||
chunk = os.read(fd, 1)
|
||||
except BlockingIOError:
|
||||
time.sleep(0.01)
|
||||
continue
|
||||
if not chunk:
|
||||
time.sleep(0.005)
|
||||
continue
|
||||
all_bytes += chunk
|
||||
window += chunk
|
||||
if len(window) > len(expected_header):
|
||||
window = window[-len(expected_header):]
|
||||
if bytes(window) == expected_header:
|
||||
rest = b""
|
||||
rest_start = time.time()
|
||||
while len(rest) < rest_needed and time.time() - rest_start < timeout:
|
||||
try:
|
||||
rest += os.read(fd, rest_needed - len(rest))
|
||||
except BlockingIOError:
|
||||
time.sleep(0.01)
|
||||
return expected_header + rest
|
||||
if os.environ.get("DEBUG_SERIAL"):
|
||||
print(f"DEBUG raw bytes seen in window: {bytes(all_bytes).hex()}", file=sys.stderr)
|
||||
return b""
|
||||
|
||||
|
||||
def open_serial(port_name: str) -> int:
|
||||
fd = os.open(port_name, os.O_RDWR | os.O_NOCTTY | os.O_NONBLOCK)
|
||||
attrs = termios.tcgetattr(fd)
|
||||
# iflag, oflag, cflag, lflag, ispeed, ospeed, cc
|
||||
attrs[0] = 0
|
||||
attrs[1] = 0
|
||||
attrs[2] = termios.CS8 | termios.CREAD | termios.CLOCAL
|
||||
attrs[3] = 0
|
||||
attrs[4] = termios.B1000000
|
||||
attrs[5] = termios.B1000000
|
||||
termios.tcsetattr(fd, termios.TCSANOW, attrs)
|
||||
termios.tcflush(fd, termios.TCIOFLUSH)
|
||||
|
||||
# disable_dtr_rts(): release the ESP32 reset line
|
||||
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))
|
||||
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)
|
||||
try:
|
||||
print("Waiting 3s for ESP32 to initialise...")
|
||||
time.sleep(3.0)
|
||||
|
||||
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
|
||||
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:
|
||||
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 - 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
|
||||
finally:
|
||||
os.close(fd)
|
||||
|
||||
|
||||
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
|
||||
print(f"Bringing up CAN interface '{interface}'...")
|
||||
try:
|
||||
subprocess.run(["ip", "link", "set", interface, "txqueuelen", "1000"], check=True)
|
||||
subprocess.run(
|
||||
["ip", "link", "set", interface, "up", "type", "can", "bitrate", "1000000"],
|
||||
check=True)
|
||||
except subprocess.CalledProcessError as e:
|
||||
print(f"ERROR: failed to bring up CAN interface: {e}", file=sys.stderr)
|
||||
return False
|
||||
print(f"CAN interface '{interface}' is up")
|
||||
return True
|
||||
|
||||
|
||||
def main() -> None:
|
||||
ap = argparse.ArgumentParser()
|
||||
ap.add_argument("--port-name", default="/dev/agvpro_controller")
|
||||
ap.add_argument("--can-interface-name", default="can0")
|
||||
args = ap.parse_args()
|
||||
|
||||
if not power_on(args.port_name):
|
||||
print("FATAL: serial power-on failed", file=sys.stderr)
|
||||
sys.exit(1)
|
||||
if not bring_up_can(args.can_interface_name):
|
||||
sys.exit(1)
|
||||
sys.exit(0)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
Reference in new issue
Block a user