From 04522e73b591957c21490a74f2426b095d734198 Mon Sep 17 00:00:00 2001 From: Erik Andresen Date: Sun, 11 Oct 2026 11:45:42 +0200 Subject: [PATCH] CHanges by opencode/Qwen-3.8: - Ported to ros2_control - renamed to a4wd3_open_manipulator --- .gitignore | 2 +- AGENTS.md | 42 ++ CMakeLists.txt | 255 +++----- a4wd3_open_manipulator.xml | 9 + .../a4wd3_open_manipulator_controllers.yaml | 27 + config/control.yaml | 17 - .../a4wd3_open_manipulator_i2c.hpp | 139 +++++ hardware/src/a4wd3_open_manipulator_i2c.cpp | 485 ++++++++++++++++ include/open_manipulator_i2c.h | 377 ------------ launch/display_urdf.launch | 15 - launch/display_urdf.launch.py | 55 ++ launch/open_manipulator.launch | 12 - launch/open_manipulator.launch.py | 64 ++ msg/HardwareError.msg | 8 +- package.xml | 80 +-- .../move_group_python_interface_tutorial.py | 546 ++++++++++++++++++ scripts/test_arm_pos.sh | 13 +- src/wt_open_manipulator_node.cpp | 61 -- srv/GetError.srv | 2 +- tools/fake_i2c.c | 167 ++++++ tools/smoke_test.sh | 150 +++++ urdf/open_manipulator.ros2_control.xacro | 52 ++ urdf/open_manipulator.urdf | 2 +- urdf/open_manipulator.urdf.xacro | 44 +- urdf/wild_thumper_with_manipulator.urdf.xacro | 12 - 25 files changed, 1874 insertions(+), 762 deletions(-) create mode 100644 AGENTS.md create mode 100644 a4wd3_open_manipulator.xml create mode 100644 config/a4wd3_open_manipulator_controllers.yaml delete mode 100644 config/control.yaml create mode 100644 hardware/include/a4wd3_open_manipulator/a4wd3_open_manipulator_i2c.hpp create mode 100644 hardware/src/a4wd3_open_manipulator_i2c.cpp delete mode 100644 include/open_manipulator_i2c.h delete mode 100644 launch/display_urdf.launch create mode 100644 launch/display_urdf.launch.py delete mode 100644 launch/open_manipulator.launch create mode 100644 launch/open_manipulator.launch.py create mode 100644 scripts/move_group_python_interface_tutorial.py delete mode 100644 src/wt_open_manipulator_node.cpp create mode 100644 tools/fake_i2c.c create mode 100755 tools/smoke_test.sh create mode 100644 urdf/open_manipulator.ros2_control.xacro delete mode 100644 urdf/wild_thumper_with_manipulator.urdf.xacro diff --git a/.gitignore b/.gitignore index 0925c8b..c18ae36 100644 --- a/.gitignore +++ b/.gitignore @@ -1 +1 @@ -CATKIN_IGNORE +COLCON_IGNORE diff --git a/AGENTS.md b/AGENTS.md new file mode 100644 index 0000000..1dea3b8 --- /dev/null +++ b/AGENTS.md @@ -0,0 +1,42 @@ +# AGENTS.md + +ROS 2 (Jazzy) `ros2_control` hardware plugin + controller stack for the "Wild Thumper" 5-DOF I2C-Dynamixel arm. Single ament_cmake package; no README, no tests. + +## Build / run + +- Colcon workspace root is `/root/ros2_ws` (NOT this dir). Build from there: + - `colcon build --packages-select a4wd3_open_manipulator` (add `--cmake-args -DCMAKE_BUILD_TYPE=Release` for release) + - `source /root/ros2_ws/install/setup.bash` +- Bringup: `ros2 launch a4wd3_open_manipulator open_manipulator.launch.py` +- Send a preset pose: `ros2 run a4wd3_open_manipulator test_arm_pos.sh [cam_aft]` +- External apt deps (outside the workspace, required to build/run): `ros-jazzy-open-manipulator-description`, `ros-jazzy-realsense2-description`, `ros-jazzy-joint-trajectory-controller`, `ros-jazzy-parallel-gripper-controller` (plus rviz2, joint_state_publisher, robot_state_publisher, xacro). + +## Layout + +- `hardware/` — C++ plugin `A4wd3OpenManipulatorI2C` (`hardware_interface::SystemInterface`). Exported via `a4wd3_open_manipulator.xml` as class `a4wd3_open_manipulator/A4wd3OpenManipulatorI2C`, library path `a4wd3_open_manipulator_hardware` (**no `lib` prefix** — pluginlib needs the un-prefixed path). +- `msg/HardwareError.msg`, `srv/GetError.srv` — rosidl interfaces (field names are snake_case). +- `config/a4wd3_open_manipulator_controllers.yaml` — controller_manager + 3 controllers. +- `urdf/open_manipulator.urdf.xacro` + `open_manipulator.ros2_control.xacro` — meshes come from `open_manipulator_description` (`meshes/open_manipulator_x/*.stl`), camera macro from `realsense2_description`; materials are inlined. +- `launch/open_manipulator.launch.py` = core bringup (robot_state_publisher + ros2_control_node + spawner). `display_urdf.launch.py` = rviz. **`moveit.launch` / `realsense.launch` are ROS 1 XML leftovers, deliberately not ported — do not "fix" them into ROS 2.** + +## Non-obvious + +- Joints: order `{joint1..joint4, gripper}` == Dynamixel IDs `{11..14, 15}`. `on_init` enforces the URDF joint names/order to match exactly. Arm joints are radians; gripper is meters (prismatic, `GRIPPER_RADIAN_TO_METER = -0.015`). +- I2C: `/dev/i2c-7`, addr `0x60>>1` (USI slave; reads return one extra byte). No device ⇒ hardware `on_configure` fails and the controller_manager aborts — expected on a dev box without hardware. +- `JOINT_LIMITS` in `hardware/include/.../a4wd3_open_manipulator_i2c.hpp` is a hardcoded duplicate of the URDF limits — keep them in sync. +- **Safety (do not remove):** with no active trajectory the JTC leaves stale/garbage values in the command interfaces; `write()` validates every command against `JOINT_LIMITS` + NaN before writing to the motors. `on_activate` seeds commands with the current position so the arm holds. +- Jazzy quirks: JTC needs explicit `command_interfaces`/`state_interfaces` (default empty → init fails); gripper plugin is `parallel_gripper_action_controller/GripperActionController` (the `position_controllers`/`gripper_controller` variants are deprecated); hardware API is `on_init(HardwareComponentInterfaceParams)` + lifecycle callbacks, with `get_node()` for services and `set_state`/`get_command` helpers. +- controller_manager reads `robot_description` only from the `/robot_description` topic → the launch passes the URDF via `robot_state_publisher`, not via CM node params. +- **CM node name must stay the default `controller_manager`** (do NOT add `name=` to the `ros2_control_node` in the launch). The config's `controller_manager:` block (`update_rate: 10`, JSB `type`) is applied by node name, and the spawner targets a node named `controller_manager`. Renaming the node (e.g. to `a4wd3_open_manipulator`) silently breaks both → CM runs at the 100 Hz default (overruns the ~41 ms I2C read of the 5 servos) and the spawner can't find the CM. +- The I2C read of all 5 servos takes ~41 ms, so the CM update rate **must stay 10 Hz** (100 ms cycle). Do not raise `update_rate` above ~20 Hz. +- Services on the hardware node: `torque_enable` (std_srvs/SetBool), `get_error` (GetError). +- No automated tests and no lint/format config (only `-Wall -Wextra`). Verification = clean colcon build + `tools/smoke_test.sh` (no-hardware end-to-end check using the LD_PRELOAD fake-Dynamixel emulator `tools/fake_i2c.c`) + manual on hardware. `log/` is `COLCON_IGNORE`d — don't build it. + +## Code style + +- **C++ source & header files use TABS for indentation** (one tab per level; the code is 2-space-level, so 2 spaces per level → 1 tab). Keep new/edited C++ consistent — don't introduce space indentation. (Convert spaces→tabs with `unexpand --tabs=2 `.) + +## Gotchas + +- git: files are owned by `ubuntu`, shell runs as `root` ⇒ "dubious ownership" on git commands. `git config --global --add safe.directory ` if needed. +- `ros2 run` strips `LD_PRELOAD` — for a no-hardware smoke test launch the node binary directly (e.g. `/opt/ros/jazzy/lib/controller_manager/ros2_control_node`). The hardware calls `open64`, so any LD_PRELOAD shim must export `open64` (not just `open`). diff --git a/CMakeLists.txt b/CMakeLists.txt index 1eba409..c0e0d61 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -1,198 +1,87 @@ -cmake_minimum_required(VERSION 2.8.3) -project(wt_open_manipulator) - -## Compile as C++11, supported in ROS Kinetic and newer -# add_compile_options(-std=c++11) - -## Find catkin macros and libraries -## if COMPONENTS list like find_package(catkin REQUIRED COMPONENTS xyz) -## is used, also find other catkin packages -find_package(catkin REQUIRED COMPONENTS - roscpp - joint_trajectory_controller - controller_manager - message_generation +cmake_minimum_required(VERSION 3.16) +project(a4wd3_open_manipulator LANGUAGES C CXX) + +if(CMAKE_CXX_COMPILER_ID MATCHES "(GNU|Clang)") + add_compile_options(-Wall -Wextra) +endif() + +find_package(ament_cmake REQUIRED) +find_package(builtin_interfaces REQUIRED) +find_package(controller_manager REQUIRED) +find_package(hardware_interface REQUIRED) +find_package(pluginlib REQUIRED) +find_package(rclcpp REQUIRED) +find_package(rclcpp_lifecycle REQUIRED) +find_package(std_msgs REQUIRED) +find_package(std_srvs REQUIRED) +find_package(rosidl_default_generators REQUIRED) + +rosidl_generate_interfaces(${PROJECT_NAME} + msg/HardwareError.msg + srv/GetError.srv + DEPENDENCIES + std_msgs ) -## System dependencies are found with CMake's conventions -# find_package(Boost REQUIRED COMPONENTS system) - - -## Uncomment this if the package has a setup.py. This macro ensures -## modules and global scripts declared therein get installed -## See http://ros.org/doc/api/catkin/html/user_guide/setup_dot_py.html -# catkin_python_setup() - -################################################ -## Declare ROS messages, services and actions ## -################################################ - -## To declare and build messages, services or actions from within this -## package, follow these steps: -## * Let MSG_DEP_SET be the set of packages whose message types you use in -## your messages/services/actions (e.g. std_msgs, actionlib_msgs, ...). -## * In the file package.xml: -## * add a build_depend tag for "message_generation" -## * add a build_depend and a exec_depend tag for each package in MSG_DEP_SET -## * If MSG_DEP_SET isn't empty the following dependency has been pulled in -## but can be declared for certainty nonetheless: -## * add a exec_depend tag for "message_runtime" -## * In this file (CMakeLists.txt): -## * add "message_generation" and every package in MSG_DEP_SET to -## find_package(catkin REQUIRED COMPONENTS ...) -## * add "message_runtime" and every package in MSG_DEP_SET to -## catkin_package(CATKIN_DEPENDS ...) -## * uncomment the add_*_files sections below as needed -## and list every .msg/.srv/.action file to be processed -## * uncomment the generate_messages entry below -## * add every package in MSG_DEP_SET to generate_messages(DEPENDENCIES ...) +rosidl_get_typesupport_target(${PROJECT_NAME}_typesupport_cpp ${PROJECT_NAME} "rosidl_typesupport_cpp") +if(NOT TARGET ${${PROJECT_NAME}_typesupport_cpp}) + message(FATAL_ERROR "Generated typesupport target ${${PROJECT_NAME}_typesupport_cpp} not found") +endif() -## Generate messages in the 'msg' folder -add_message_files( - FILES - HardwareError.msg +add_library(${PROJECT_NAME}_hardware SHARED + hardware/src/a4wd3_open_manipulator_i2c.cpp ) -## Generate services in the 'srv' folder -add_service_files( - FILES - GetError.srv +target_compile_features(${PROJECT_NAME}_hardware PUBLIC cxx_std_17) +target_include_directories(${PROJECT_NAME}_hardware PUBLIC + $ + $ ) - -## Generate actions in the 'action' folder -# add_action_files( -# FILES -# Action1.action -# Action2.action -# ) - -## Generate added messages and services with any dependencies listed here -generate_messages( - DEPENDENCIES +ament_target_dependencies(${PROJECT_NAME}_hardware + builtin_interfaces + hardware_interface + pluginlib + rclcpp + rclcpp_lifecycle std_msgs + std_srvs ) - -################################################ -## Declare ROS dynamic reconfigure parameters ## -################################################ - -## To declare and build dynamic reconfigure parameters within this -## package, follow these steps: -## * In the file package.xml: -## * add a build_depend and a exec_depend tag for "dynamic_reconfigure" -## * In this file (CMakeLists.txt): -## * add "dynamic_reconfigure" to -## find_package(catkin REQUIRED COMPONENTS ...) -## * uncomment the "generate_dynamic_reconfigure_options" section below -## and list every .cfg file to be processed - -## Generate dynamic reconfigure parameters in the 'cfg' folder -# generate_dynamic_reconfigure_options( -# cfg/DynReconf1.cfg -# cfg/DynReconf2.cfg -# ) - -################################### -## catkin specific configuration ## -################################### -## The catkin_package macro generates cmake config files for your package -## Declare things to be passed to dependent projects -## INCLUDE_DIRS: uncomment this if your package contains header files -## LIBRARIES: libraries you create in this project that dependent projects also need -## CATKIN_DEPENDS: catkin_packages dependent projects also need -## DEPENDS: system dependencies of this project that dependent projects also need -catkin_package( - INCLUDE_DIRS include -# LIBRARIES wt_open_manipulator -# CATKIN_DEPENDS other_catkin_pkg -# DEPENDS system_lib +target_link_libraries(${PROJECT_NAME}_hardware + ${${PROJECT_NAME}_typesupport_cpp} ) -########### -## Build ## -########### +pluginlib_export_plugin_description_file(hardware_interface ${PROJECT_NAME}.xml) -## Specify additional locations of header files -## Your package locations should be listed before other locations -include_directories( - include - ${catkin_INCLUDE_DIRS} +install( + DIRECTORY hardware/include/ + DESTINATION include/${PROJECT_NAME} ) - -## Declare a C++ library -# add_library(${PROJECT_NAME} -# src/${PROJECT_NAME}/wt_open_manipulator.cpp -# ) - -## Add cmake target dependencies of the library -## as an example, code may need to be generated before libraries -## either from message generation or dynamic reconfigure -# add_dependencies(${PROJECT_NAME} ${${PROJECT_NAME}_EXPORTED_TARGETS} ${catkin_EXPORTED_TARGETS}) - -## Declare a C++ executable -## With catkin_make all packages are built within a single CMake context -## The recommended prefix ensures that target names across packages don't collide -add_executable(${PROJECT_NAME}_node src/wt_open_manipulator_node.cpp) - -## Rename C++ executable without prefix -## The above recommended prefix causes long target names, the following renames the -## target back to the shorter version for ease of user use -## e.g. "rosrun someones_pkg node" instead of "rosrun someones_pkg someones_pkg_node" -# set_target_properties(${PROJECT_NAME}_node PROPERTIES OUTPUT_NAME node PREFIX "") - -## Add cmake target dependencies of the executable -## same as for the library above -add_dependencies(${PROJECT_NAME}_node ${${PROJECT_NAME}_EXPORTED_TARGETS} ${catkin_EXPORTED_TARGETS}) - -## Specify libraries to link a library or executable target against -target_link_libraries(${PROJECT_NAME}_node - ${catkin_LIBRARIES} +install( + TARGETS ${PROJECT_NAME}_hardware + ARCHIVE DESTINATION lib + LIBRARY DESTINATION lib + RUNTIME DESTINATION bin +) +install( + DIRECTORY launch config urdf + DESTINATION share/${PROJECT_NAME} +) +install( + PROGRAMS scripts/test_arm_pos.sh + DESTINATION lib/${PROJECT_NAME} ) -############# -## Install ## -############# - -# all install targets should use catkin DESTINATION variables -# See http://ros.org/doc/api/catkin/html/adv_user_guide/variables.html - -## Mark executable scripts (Python etc.) for installation -## in contrast to setup.py, you can choose the destination -# install(PROGRAMS -# scripts/my_python_script -# DESTINATION ${CATKIN_PACKAGE_BIN_DESTINATION} -# ) - -## Mark executables and/or libraries for installation -# install(TARGETS ${PROJECT_NAME} ${PROJECT_NAME}_node -# ARCHIVE DESTINATION ${CATKIN_PACKAGE_LIB_DESTINATION} -# LIBRARY DESTINATION ${CATKIN_PACKAGE_LIB_DESTINATION} -# RUNTIME DESTINATION ${CATKIN_PACKAGE_BIN_DESTINATION} -# ) - -## Mark cpp header files for installation -# install(DIRECTORY include/${PROJECT_NAME}/ -# DESTINATION ${CATKIN_PACKAGE_INCLUDE_DESTINATION} -# FILES_MATCHING PATTERN "*.h" -# PATTERN ".svn" EXCLUDE -# ) - -## Mark other files for installation (e.g. launch and bag files, etc.) -# install(FILES -# # myfile1 -# # myfile2 -# DESTINATION ${CATKIN_PACKAGE_SHARE_DESTINATION} -# ) - -############# -## Testing ## -############# - -## Add gtest based cpp test target and link libraries -# catkin_add_gtest(${PROJECT_NAME}-test test/test_wt_open_manipulator.cpp) -# if(TARGET ${PROJECT_NAME}-test) -# target_link_libraries(${PROJECT_NAME}-test ${PROJECT_NAME}) -# endif() +ament_export_include_directories(include/${PROJECT_NAME}) +ament_export_libraries(${PROJECT_NAME}_hardware) +ament_export_dependencies( + builtin_interfaces + hardware_interface + pluginlib + rclcpp + rclcpp_lifecycle + std_msgs + std_srvs + ${PROJECT_NAME} +) -## Add folders to be run by python nosetests -# catkin_add_nosetests(test) +ament_package() diff --git a/a4wd3_open_manipulator.xml b/a4wd3_open_manipulator.xml new file mode 100644 index 0000000..ae96c6a --- /dev/null +++ b/a4wd3_open_manipulator.xml @@ -0,0 +1,9 @@ + + + + I2C Dynamixel hardware interface for the Wild Thumper open manipulator arm. + + + diff --git a/config/a4wd3_open_manipulator_controllers.yaml b/config/a4wd3_open_manipulator_controllers.yaml new file mode 100644 index 0000000..e0c8f2f --- /dev/null +++ b/config/a4wd3_open_manipulator_controllers.yaml @@ -0,0 +1,27 @@ +controller_manager: + ros__parameters: + update_rate: 10 # Hz + + joint_state_broadcaster: + type: joint_state_broadcaster/JointStateBroadcaster + +arm_controller: + ros__parameters: + type: joint_trajectory_controller/JointTrajectoryController + joints: + - joint1 + - joint2 + - joint3 + - joint4 + command_interfaces: + - position + state_interfaces: + - position + - velocity + constraints: + goal_time: 0.3 + +gripper_controller: + ros__parameters: + type: parallel_gripper_action_controller/GripperActionController + joint: gripper diff --git a/config/control.yaml b/config/control.yaml deleted file mode 100644 index 75e7d3b..0000000 --- a/config/control.yaml +++ /dev/null @@ -1,17 +0,0 @@ -arm_joint_state_controller: - type: "joint_state_controller/JointStateController" - publish_rate: 20 - -arm_controller: - type: "position_controllers/JointTrajectoryController" - joints: - - joint1 - - joint2 - - joint3 - - joint4 - constraints: - goal_time: 0.3 - -gripper_controller: - type: "position_controllers/GripperActionController" - joint: gripper diff --git a/hardware/include/a4wd3_open_manipulator/a4wd3_open_manipulator_i2c.hpp b/hardware/include/a4wd3_open_manipulator/a4wd3_open_manipulator_i2c.hpp new file mode 100644 index 0000000..cbbc061 --- /dev/null +++ b/hardware/include/a4wd3_open_manipulator/a4wd3_open_manipulator_i2c.hpp @@ -0,0 +1,139 @@ +// I2C Dynamixel hardware interface for the Wild Thumper open manipulator arm. +// +// ros2_control SystemInterface implementation replacing the ROS 1 +// hardware_interface::RobotHW class of the same name. + +#ifndef A4WD3_OPEN_MANIPULATOR__A4WD3_OPEN_MANIPULATOR_I2C_HPP_ +#define A4WD3_OPEN_MANIPULATOR__A4WD3_OPEN_MANIPULATOR_I2C_HPP_ + +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include + +#include "hardware_interface/hardware_info.hpp" +#include "hardware_interface/system_interface.hpp" +#include "hardware_interface/types/hardware_interface_return_values.hpp" +#include "hardware_interface/types/hardware_interface_type_values.hpp" +#include "rclcpp/rclcpp.hpp" +#include "rclcpp_lifecycle/state.hpp" +#include "std_srvs/srv/set_bool.hpp" +#include "a4wd3_open_manipulator/srv/get_error.hpp" + +#define I2C_FILE "/dev/i2c-7" +#define I2C_ADDR (0x60 >> 1) +#define XM_OPERATING_MODE 11 +#define XM_HOMING_OFFSET 20 +#define XM_CURRENT_LIMIT 38 +#define XM_SHUTDOWN 63 +#define XM_TORQUE_ENABLE 64 +#define XM_HARDWARE_ERROR_STATUS 70 +#define XM_GOAL_CURRENT 102 +#define XM_PROFILE_ACCELERATION 108 +#define XM_PROFILE_VELOCITY 112 +#define XM_GOAL_POSITION 116 +#define XM_PRESENT_POSITION 132 +#define XM_PRESENT_CURRENT 126 +#define XM_PRESENT_VELOCITY 128 +#define CMD_EOF 0xaa +#define STEPS_TO_RADIAN (2 * M_PI / 4096) +#define GRIPPER_RADIAN_TO_METER -0.015 +#define VELOCITY_STEPS_TO_RADS (0.229 * 2 * M_PI / 60) + +namespace a4wd3_open_manipulator +{ + +class A4wd3OpenManipulatorI2C : public hardware_interface::SystemInterface +{ +public: + hardware_interface::CallbackReturn on_init( + const hardware_interface::HardwareComponentInterfaceParams & params) override; + + hardware_interface::CallbackReturn on_configure( + const rclcpp_lifecycle::State & previous_state) override; + + hardware_interface::CallbackReturn on_activate( + const rclcpp_lifecycle::State & previous_state) override; + + hardware_interface::CallbackReturn on_deactivate( + const rclcpp_lifecycle::State & previous_state) override; + + hardware_interface::CallbackReturn on_shutdown( + const rclcpp_lifecycle::State & previous_state) override; + + hardware_interface::CallbackReturn on_error( + const rclcpp_lifecycle::State & previous_state) override; + + hardware_interface::return_type read( + const rclcpp::Time & time, const rclcpp::Duration & period) override; + + hardware_interface::return_type write( + const rclcpp::Time & time, const rclcpp::Duration & period) override; + +private: + static constexpr size_t NUM_JOINTS = 5; + static const std::vector JOINT_NAMES; + + // must match the joint limits in the URDF + static constexpr double JOINT_LIMITS[NUM_JOINTS][2] = { + {-M_PI, M_PI}, // joint1 + {-0.64 * M_PI, 0.64 * M_PI}, // joint2 + {-0.64 * M_PI, 0.48 * M_PI}, // joint3 + {-0.57 * M_PI, 0.65 * M_PI}, // joint4 + {-0.010, 0.019}, // gripper + }; + static constexpr double kLimitTolerance = 1e-3; + + void cbTorqueEnable( + const std::shared_ptr req, + std::shared_ptr res); + + void cbGetError( + const std::shared_ptr req, + std::shared_ptr res); + + bool torque_enable(bool enable); + + bool setup_dynamixels(); + + bool read_current_positions(); + + int dynamixel_write( + uint8_t * write_data, int write_num, uint8_t * read_data, int read_num); + + uint8_t dynamixel_writebyte(uint8_t id, uint8_t cmd, uint8_t value); + + uint8_t dynamixel_writeword(uint8_t id, uint8_t cmd, int16_t value); + + uint8_t dynamixel_writedword(uint8_t id, uint8_t cmd, int32_t value); + + uint8_t dynamixel_readbyte(uint8_t id, uint8_t cmd, uint8_t * value); + + uint8_t dynamixel_readword(uint8_t id, uint8_t cmd, int16_t * value); + + uint8_t dynamixel_readdword(uint8_t id, uint8_t cmd, int32_t * value); + + rclcpp::Service::SharedPtr torque_enable_service_; + rclcpp::Service::SharedPtr get_error_service_; + + double cmd[NUM_JOINTS] = {NAN, NAN, NAN, NAN, NAN}; + double cmd_pre[NUM_JOINTS] = {NAN, NAN, NAN, NAN, NAN}; + double pos[NUM_JOINTS] = {0, 0, 0, 0, 0}; + double vel[NUM_JOINTS] = {0, 0, 0, 0, 0}; + double eff[NUM_JOINTS] = {0, 0, 0, 0, 0}; + + std::mutex comm_mutex; + std::set ignore_ids; +}; + +} // namespace a4wd3_open_manipulator + +#endif // A4WD3_OPEN_MANIPULATOR__A4WD3_OPEN_MANIPULATOR_I2C_HPP_ diff --git a/hardware/src/a4wd3_open_manipulator_i2c.cpp b/hardware/src/a4wd3_open_manipulator_i2c.cpp new file mode 100644 index 0000000..9965b91 --- /dev/null +++ b/hardware/src/a4wd3_open_manipulator_i2c.cpp @@ -0,0 +1,485 @@ +// I2C Dynamixel hardware interface for the Wild Thumper open manipulator arm. +// +// ros2_control SystemInterface implementation replacing the ROS 1 +// hardware_interface::RobotHW class of the same name. + +#include "a4wd3_open_manipulator/a4wd3_open_manipulator_i2c.hpp" + +#include +#include + +namespace a4wd3_open_manipulator +{ + +const std::vector A4wd3OpenManipulatorI2C::JOINT_NAMES = +{"joint1", "joint2", "joint3", "joint4", "gripper"}; + +hardware_interface::CallbackReturn A4wd3OpenManipulatorI2C::on_init( + const hardware_interface::HardwareComponentInterfaceParams & params) +{ + if ( + hardware_interface::SystemInterface::on_init(params) != + hardware_interface::CallbackReturn::SUCCESS) + { + return hardware_interface::CallbackReturn::ERROR; + } + + if (info_.joints.size() != NUM_JOINTS) { + RCLCPP_ERROR( + get_logger(), "Expected %zu joints in URDF, got %zu", NUM_JOINTS, info_.joints.size()); + return hardware_interface::CallbackReturn::ERROR; + } + for (size_t i = 0; i < NUM_JOINTS; i++) { + if (info_.joints[i].name != JOINT_NAMES[i]) { + RCLCPP_ERROR( + get_logger(), "Expected joint '%s' at index %zu, got '%s'", JOINT_NAMES[i].c_str(), i, + info_.joints[i].name.c_str()); + return hardware_interface::CallbackReturn::ERROR; + } + } + + return hardware_interface::CallbackReturn::SUCCESS; +} + +hardware_interface::CallbackReturn A4wd3OpenManipulatorI2C::on_configure( + const rclcpp_lifecycle::State & /*previous_state*/) +{ + RCLCPP_INFO(get_logger(), "Configuring %s", info_.name.c_str()); + + if (!setup_dynamixels()) { + return hardware_interface::CallbackReturn::ERROR; + } + + torque_enable_service_ = get_node()->create_service( + "torque_enable", std::bind( + &A4wd3OpenManipulatorI2C::cbTorqueEnable, this, std::placeholders::_1, + std::placeholders::_2)); + get_error_service_ = get_node()->create_service( + "get_error", std::bind( + &A4wd3OpenManipulatorI2C::cbGetError, this, std::placeholders::_1, + std::placeholders::_2)); + + RCLCPP_INFO(get_logger(), "Configuration successful"); + return hardware_interface::CallbackReturn::SUCCESS; +} + +hardware_interface::CallbackReturn A4wd3OpenManipulatorI2C::on_activate( + const rclcpp_lifecycle::State & /*previous_state*/) +{ + RCLCPP_INFO(get_logger(), "Activating %s", info_.name.c_str()); + + if (!torque_enable(true)) { + return hardware_interface::CallbackReturn::ERROR; + } + + // initialize the position commands to the current position so the arm + // holds its position until a controller sends a valid trajectory + if (read_current_positions()) { + for (size_t i = 0; i < NUM_JOINTS; i++) { + set_command(JOINT_NAMES[i] + "/" + hardware_interface::HW_IF_POSITION, pos[i]); + } + } else { + RCLCPP_WARN(get_logger(), "Could not read current positions, keeping previous commands"); + } + + RCLCPP_INFO(get_logger(), "Activation successful"); + return hardware_interface::CallbackReturn::SUCCESS; +} + +bool A4wd3OpenManipulatorI2C::read_current_positions() +{ + int32_t value; + bool ok = true; + for (int i = 0, id = 11; id <= 14; id++, i++) { + if (dynamixel_readdword(id, XM_PRESENT_POSITION, &value) == 1) { + pos[i] = STEPS_TO_RADIAN * (value - 2048); + } else { + RCLCPP_ERROR(get_logger(), "I2C dynamixel id=%d position read error", id); + ok = false; + } + } + if (dynamixel_readdword(15, XM_PRESENT_POSITION, &value) == 1) { + pos[4] = STEPS_TO_RADIAN * (value - 2048) * GRIPPER_RADIAN_TO_METER; + } else { + RCLCPP_ERROR(get_logger(), "I2C dynamixel id=15 position read error"); + ok = false; + } + return ok; +} + +hardware_interface::CallbackReturn A4wd3OpenManipulatorI2C::on_deactivate( + const rclcpp_lifecycle::State & /*previous_state*/) +{ + RCLCPP_INFO(get_logger(), "Deactivating %s", info_.name.c_str()); + torque_enable(false); + RCLCPP_INFO(get_logger(), "Deactivation successful"); + return hardware_interface::CallbackReturn::SUCCESS; +} + +hardware_interface::CallbackReturn A4wd3OpenManipulatorI2C::on_shutdown( + const rclcpp_lifecycle::State & /*previous_state*/) +{ + RCLCPP_INFO(get_logger(), "Shutting down %s", info_.name.c_str()); + torque_enable(false); + RCLCPP_INFO(get_logger(), "Shutdown successful"); + return hardware_interface::CallbackReturn::SUCCESS; +} + +hardware_interface::CallbackReturn A4wd3OpenManipulatorI2C::on_error( + const rclcpp_lifecycle::State & /*previous_state*/) +{ + RCLCPP_ERROR(get_logger(), "Error in %s", info_.name.c_str()); + torque_enable(false); + return hardware_interface::CallbackReturn::SUCCESS; +} + +bool A4wd3OpenManipulatorI2C::setup_dynamixels() +{ + uint8_t mode = 255; + int32_t homing_offset = 0; + + if (dynamixel_readdword(11, XM_HOMING_OFFSET, &homing_offset) != 1) { + RCLCPP_ERROR(get_logger(), "I2C dynamixel id=11 read homing offset error"); + return false; + } + if (homing_offset != 64) { + if (dynamixel_writedword(11, XM_HOMING_OFFSET, 64) != 1) { + RCLCPP_ERROR(get_logger(), "I2C dynamixel id=11 write homing offset error"); + return false; + } + } + if (dynamixel_writeword(15, XM_GOAL_CURRENT, 600) != 1) { // 0..1193, 2.69mA/value + RCLCPP_ERROR(get_logger(), "I2C dynamixel id=15 write goal current error"); + return false; + } + if (dynamixel_readbyte(15, XM_OPERATING_MODE, &mode) != 1) { + RCLCPP_ERROR(get_logger(), "I2C dynamixel id=15 read operating Mode error"); + return false; + } + if (mode != 5) { + if (!torque_enable(false)) { + return false; + } + if (dynamixel_writebyte(15, XM_OPERATING_MODE, 5) != 1) { // Current-based Position Control Mode + RCLCPP_ERROR(get_logger(), "I2C dynamixel id=15 write operating Mode error"); + return false; + } + } + if (dynamixel_writedword(15, XM_PROFILE_ACCELERATION, 20) != 1) { + RCLCPP_ERROR(get_logger(), "I2C dynamixel id=15 write profile Acceleration error"); + return false; + } + if (dynamixel_writedword(15, XM_PROFILE_VELOCITY, 200) != 1) { + RCLCPP_ERROR(get_logger(), "I2C dynamixel id=15 write profile Velocity error"); + return false; + } + return true; +} + +hardware_interface::return_type A4wd3OpenManipulatorI2C::read( + const rclcpp::Time & /*time*/, const rclcpp::Duration & /*period*/) +{ + int32_t value; + auto t1 = std::chrono::high_resolution_clock::now(); + int num_error = 0; + + // arm + for (int i = 0, id = 11; id <= 14; id++, i++) { + if (ignore_ids.count(i) > 0) { + RCLCPP_ERROR_THROTTLE(get_logger(), *get_clock(), 10000, "Ignoring dynamixel %d", id); + continue; + } + + if (dynamixel_readdword(id, XM_PRESENT_POSITION, &value) == 1) { + pos[i] = STEPS_TO_RADIAN * (value - 2048); + } else { + RCLCPP_ERROR(get_logger(), "I2C dynamixel id=%d position read error", id); + num_error++; + } + + if (dynamixel_readdword(id, XM_PRESENT_VELOCITY, &value) == 1) { + vel[i] = value * VELOCITY_STEPS_TO_RADS; + } else { + RCLCPP_ERROR(get_logger(), "I2C dynamixel id=%d velocity read error", id); + num_error++; + } + +#ifdef READ_EFFORT + int16_t current; + if (dynamixel_readword(id, XM_PRESENT_CURRENT, ¤t) == 1) { + eff[i] = current * 2.69e-3; + } else { + RCLCPP_ERROR(get_logger(), "I2C dynamixel id=%d current read error", id); + num_error++; + } +#endif + + if (num_error >= 3) { + ignore_ids.insert(i); + } + } + + // gripper + if (dynamixel_readdword(15, XM_PRESENT_POSITION, &value) == 1) { + pos[4] = STEPS_TO_RADIAN * (value - 2048) * GRIPPER_RADIAN_TO_METER; + } else { + RCLCPP_ERROR(get_logger(), "I2C dynamixel id=15 position read error"); + } + if (dynamixel_readdword(15, XM_PRESENT_VELOCITY, &value) == 1) { + vel[4] = value * VELOCITY_STEPS_TO_RADS * GRIPPER_RADIAN_TO_METER; + } else { + RCLCPP_ERROR(get_logger(), "I2C dynamixel id=15 velocity read error"); + } +#ifdef READ_EFFORT + int16_t current; + if (dynamixel_readword(15, XM_PRESENT_CURRENT, ¤t) == 1) { + eff[4] = current * 2.69e-3; + } else { + RCLCPP_ERROR(get_logger(), "I2C dynamixel id=15 current read error"); + } +#endif + + RCLCPP_DEBUG( + get_logger(), "pos: %.2f %.2f %.2f %.2f %.2f", pos[0] * 180 / M_PI, pos[1] * 180 / M_PI, + pos[2] * 180 / M_PI, pos[3] * 180 / M_PI, pos[4]); + RCLCPP_DEBUG( + get_logger(), "velocity: %.2f %.2f %.2f %.2f %.2f", vel[0] * 30 / M_PI, vel[1] * 30 / M_PI, + vel[2] * 30 / M_PI, vel[3] * 30 / M_PI, vel[4]); +#ifdef READ_EFFORT + RCLCPP_DEBUG(get_logger(), "current: %.2f %.2f %.2f %.2f %.2f", eff[0], eff[1], eff[2], eff[3], eff[4]); +#endif + auto t2 = std::chrono::high_resolution_clock::now(); + int64_t duration = std::chrono::duration_cast(t2 - t1).count(); + RCLCPP_DEBUG(get_logger(), "read duration: %lldms", static_cast(duration)); + + for (size_t i = 0; i < NUM_JOINTS; i++) { + set_state(JOINT_NAMES[i] + "/" + hardware_interface::HW_IF_POSITION, pos[i]); + set_state(JOINT_NAMES[i] + "/" + hardware_interface::HW_IF_VELOCITY, vel[i]); + set_state(JOINT_NAMES[i] + "/" + hardware_interface::HW_IF_EFFORT, eff[i]); + } + + return hardware_interface::return_type::OK; +} + +hardware_interface::return_type A4wd3OpenManipulatorI2C::write( + const rclcpp::Time & /*time*/, const rclcpp::Duration & /*period*/) +{ + int32_t value; + + for (size_t i = 0; i < NUM_JOINTS; i++) { + cmd[i] = get_command(JOINT_NAMES[i] + "/" + hardware_interface::HW_IF_POSITION); + } + + if (memcmp(cmd, cmd_pre, sizeof(cmd)) != 0) { // Only write new position when changed + RCLCPP_DEBUG( + get_logger(), "cmd: %.2f %.2f %.2f %.2f %.2f", cmd[0] * 180 / M_PI, cmd[1] * 180 / M_PI, + cmd[2] * 180 / M_PI, cmd[3] * 180 / M_PI, cmd[4]); + + // arm + for (int i = 0, id = 11; id <= 14; id++, i++) { + if (std::isnan(cmd[i]) || + cmd[i] < JOINT_LIMITS[i][0] - kLimitTolerance || + cmd[i] > JOINT_LIMITS[i][1] + kLimitTolerance) { + RCLCPP_WARN_THROTTLE( + get_logger(), *get_clock(), 1000, + "Desired angle for id=%d is invalid or outside joint limit, skipping write.", id); + continue; + } + + value = cmd[i] / STEPS_TO_RADIAN + 2048; + + if (dynamixel_writedword(id, XM_GOAL_POSITION, value) == 1) { + cmd_pre[i] = cmd[i]; + } else { + RCLCPP_ERROR(get_logger(), "I2C dynamixel id=%d write error", id); + } + } + + // gripper + if (std::isnan(cmd[4]) || + cmd[4] < JOINT_LIMITS[4][0] - kLimitTolerance || + cmd[4] > JOINT_LIMITS[4][1] + kLimitTolerance) { + RCLCPP_WARN_THROTTLE( + get_logger(), *get_clock(), 1000, + "Desired angle for id=15 is invalid or outside joint limit, skipping write."); + } else { + value = cmd[4] / GRIPPER_RADIAN_TO_METER / STEPS_TO_RADIAN + 2048; + if (dynamixel_writedword(15, XM_GOAL_POSITION, value) == 1) { + cmd_pre[4] = cmd[4]; + } else { + RCLCPP_ERROR(get_logger(), "I2C dynamixel id=15 write error"); + } + } + } + + return hardware_interface::return_type::OK; +} + +bool A4wd3OpenManipulatorI2C::torque_enable(bool enable) +{ + bool ret = true; + for (int id = 11; id <= 15; id++) { + if (dynamixel_writebyte(id, XM_TORQUE_ENABLE, enable) != 1) { + RCLCPP_ERROR(get_logger(), "I2C dynamixel id=%d torque change", id); + ret = false; + } + } + return ret; +} + +int A4wd3OpenManipulatorI2C::dynamixel_write( + uint8_t * write_data, int write_num, uint8_t * read_data, int read_num) +{ + int file = -1; + int ret = -1; + uint8_t read_buf[read_num + 1]; // for unknown reason need to read one more byte with USI Slave + + comm_mutex.lock(); + if ((file = open(I2C_FILE, O_RDWR)) < 0) { + perror("open"); + goto error; + } + + if (ioctl(file, I2C_SLAVE, I2C_ADDR) < 0) { + perror("ioctl"); + goto error; + } + + if ((ret = ::write(file, write_data, write_num)) != write_num) { + perror("i2c write"); + goto error; + } + + // wait at least the half duplex transmission time, assume 29 (=14+15) bytes send/received: + // 1/(115200.0/10/29) <= 2.6ms + //usleep(3.2*1e3); + if (read_num > 0) { + if ((ret = ::read(file, read_buf, read_num + 1)) != read_num + 1) { + perror("i2c read"); + goto error; + } + ret--; // remove extra byte + memcpy(read_data, read_buf, ret); + } + +error: + if (file >= 0) { + close(file); + } + comm_mutex.unlock(); + return ret; +} + +uint8_t A4wd3OpenManipulatorI2C::dynamixel_writebyte(uint8_t id, uint8_t cmd, uint8_t value) +{ + uint8_t write_data[5] = {id, cmd, 1, value, CMD_EOF}; + uint8_t read_data[2]; + int ret = dynamixel_write(write_data, 5, read_data, 2); + if (ret == 2 && read_data[1] == id) { + return read_data[0]; + } + return 255; +} + +uint8_t A4wd3OpenManipulatorI2C::dynamixel_writeword(uint8_t id, uint8_t cmd, int16_t value) +{ + uint8_t write_data[6] = {id, cmd, 2, (uint8_t)(value >> 8), (uint8_t)value, CMD_EOF}; + uint8_t read_data[2]; + int ret = dynamixel_write(write_data, 6, read_data, 2); + if (ret == 2 && read_data[1] == id) { + return read_data[0]; + } + return 255; +} + +uint8_t A4wd3OpenManipulatorI2C::dynamixel_writedword(uint8_t id, uint8_t cmd, int32_t value) +{ + uint8_t write_data[8] = { + id, cmd, 4, (uint8_t)(value >> 24), (uint8_t)(value >> 16), (uint8_t)(value >> 8), + (uint8_t)value, CMD_EOF}; + uint8_t read_data[2]; + int ret = dynamixel_write(write_data, 8, read_data, 2); + if (ret == 2 && read_data[1] == id) { + return read_data[0]; + } + return 255; +} + +uint8_t A4wd3OpenManipulatorI2C::dynamixel_readbyte(uint8_t id, uint8_t cmd, uint8_t * value) +{ + uint8_t write_data[4] = {id, cmd, 0x11, CMD_EOF}; + uint8_t read_data[3]; + int ret = dynamixel_write(write_data, 4, read_data, 3); + if (ret == 3 && read_data[1] == id) { + *value = read_data[2]; + return read_data[0]; + } + if (read_data[0] != 1) { + RCLCPP_ERROR(get_logger(), "I2C dynamixel id=%d alert value: %d", id, read_data[0]); + } + return 255; +} + +uint8_t A4wd3OpenManipulatorI2C::dynamixel_readword(uint8_t id, uint8_t cmd, int16_t * value) +{ + uint8_t write_data[4] = {id, cmd, 0x12, CMD_EOF}; + uint8_t read_data[4]; + int ret = dynamixel_write(write_data, 4, read_data, 4); + if (ret == 4 && read_data[1] == id) { + *value = (read_data[2] << 8) | read_data[3]; + return read_data[0]; + } + return 255; +} + +uint8_t A4wd3OpenManipulatorI2C::dynamixel_readdword(uint8_t id, uint8_t cmd, int32_t * value) +{ + uint8_t write_data[4] = {id, cmd, 0x14, CMD_EOF}; + uint8_t read_data[6]; + int ret = dynamixel_write(write_data, 4, read_data, 6); + if (ret == 6 && read_data[0] == 1 && read_data[1] == id) { + *value = (read_data[2] << 24) | (read_data[3] << 16) | (read_data[4] << 8) | read_data[5]; + return read_data[0]; + } + if (read_data[0] != 1) { + RCLCPP_ERROR(get_logger(), "I2C dynamixel id=%d alert value: %d", id, read_data[0]); + } + return 255; +} + +void A4wd3OpenManipulatorI2C::cbTorqueEnable( + const std::shared_ptr req, + std::shared_ptr res) +{ + RCLCPP_INFO(get_logger(), "Setting torque enable=%d", (int)req->data); + res->success = torque_enable(req->data); +} + +void A4wd3OpenManipulatorI2C::cbGetError( + const std::shared_ptr /*req*/, + std::shared_ptr res) +{ + RCLCPP_INFO(get_logger(), "Reading Hardware Error Status"); + + for (int id = 11, i = 0; id <= 15; id++, i++) { + a4wd3_open_manipulator::msg::HardwareError hw_error; + uint8_t value; + if (dynamixel_readbyte(id, XM_HARDWARE_ERROR_STATUS, &value) != 1) { + RCLCPP_ERROR(get_logger(), "I2C dynamixel id=%d reading hardware error status", id); + } + hw_error.id = id; + hw_error.input_voltage = value & (1 << 0); + hw_error.over_heating = value & (1 << 2); + hw_error.motor_encoder = value & (1 << 3); + hw_error.electrical_shock = value & (1 << 4); + hw_error.overload = value & (1 << 5); + res->errors.push_back(hw_error); + } +} + +} // namespace a4wd3_open_manipulator + +#include "pluginlib/class_list_macros.hpp" + +PLUGINLIB_EXPORT_CLASS( + a4wd3_open_manipulator::A4wd3OpenManipulatorI2C, hardware_interface::SystemInterface) diff --git a/include/open_manipulator_i2c.h b/include/open_manipulator_i2c.h deleted file mode 100644 index 3d041c7..0000000 --- a/include/open_manipulator_i2c.h +++ /dev/null @@ -1,377 +0,0 @@ -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include "std_srvs/SetBool.h" -#include "wt_open_manipulator/GetError.h" - -#define I2C_FILE "/dev/i2c-2" -#define I2C_ADDR (0x60>>1) -#define XM_OPERATING_MODE 11 -#define XM_HOMING_OFFSET 20 -#define XM_CURRENT_LIMIT 38 -#define XM_SHUTDOWN 63 -#define XM_TORQUE_ENABLE 64 -#define XM_HARDWARE_ERROR_STATUS 70 -#define XM_GOAL_CURRENT 102 -#define XM_PROFILE_ACCELERATION 108 -#define XM_PROFILE_VELOCITY 112 -#define XM_GOAL_POSITION 116 -#define XM_PRESENT_POSITION 132 -#define XM_PRESENT_CURRENT 126 -#define XM_PRESENT_VELOCITY 128 -#define CMD_EOF 0xaa -#define STEPS_TO_RADIAN (2*M_PI/4096) -#define GRIPPER_RADIAN_TO_METER -0.015 -#define VELOCITY_STEPS_TO_RADS (0.229*2*M_PI/60) - -class WtOpenManipulatorI2C : public hardware_interface::RobotHW -{ - public: - WtOpenManipulatorI2C(ros::NodeHandle nh) { - uint8_t mode=255; - int32_t homing_offset=0; - this->nh = nh; - torque_enable_service = nh.advertiseService("torque_enable", &WtOpenManipulatorI2C::cbTorqueEnable, this); - get_error_service = nh.advertiseService("get_error", &WtOpenManipulatorI2C::cbGetError, this); - - // connect and register the joint state interface - hardware_interface::JointStateHandle state_handle_1("joint1", &pos[0], &vel[0], &eff[0]); - jnt_state_interface.registerHandle(state_handle_1); - hardware_interface::JointStateHandle state_handle_2("joint2", &pos[1], &vel[1], &eff[1]); - jnt_state_interface.registerHandle(state_handle_2); - hardware_interface::JointStateHandle state_handle_3("joint3", &pos[2], &vel[2], &eff[2]); - jnt_state_interface.registerHandle(state_handle_3); - hardware_interface::JointStateHandle state_handle_4("joint4", &pos[3], &vel[3], &eff[3]); - jnt_state_interface.registerHandle(state_handle_4); - hardware_interface::JointStateHandle state_handle_gripper("gripper", &pos[4], &vel[4], &eff[4]); - jnt_state_interface.registerHandle(state_handle_gripper); - registerInterface(&jnt_state_interface); - - // connect and register the joint position interface - hardware_interface::JointHandle pos_handle_1(state_handle_1, &cmd[0]); - jnt_pos_interface.registerHandle(pos_handle_1); - hardware_interface::JointHandle pos_handle_2(state_handle_2, &cmd[1]); - jnt_pos_interface.registerHandle(pos_handle_2); - hardware_interface::JointHandle pos_handle_3(state_handle_3, &cmd[2]); - jnt_pos_interface.registerHandle(pos_handle_3); - hardware_interface::JointHandle pos_handle_4(state_handle_4, &cmd[3]); - jnt_pos_interface.registerHandle(pos_handle_4); - hardware_interface::JointHandle pos_handle_gripper(state_handle_gripper, &cmd[4]); - jnt_pos_interface.registerHandle(pos_handle_gripper); - registerInterface(&jnt_pos_interface); - - // Settings - if (dynamixel_readdword(11, XM_HOMING_OFFSET, &homing_offset) != 1) { - ROS_ERROR("I2C dynamixel id=11 read homing offset error"); - exit(1); - } - if (homing_offset != 64) { - if (dynamixel_writedword(11, XM_HOMING_OFFSET, 64) != 1) { - ROS_ERROR("I2C dynamixel id=11 write homing offset error"); - exit(1); - } - } - if (dynamixel_writeword(15, XM_GOAL_CURRENT, 600) != 1) { // 0..1193, 2.69mA/value - ROS_ERROR("I2C dynamixel id=15 write goal current error"); - exit(1); - } - if (dynamixel_readbyte(15, XM_OPERATING_MODE, &mode) != 1) { - ROS_ERROR("I2C dynamixel id=15 read operating Mode error"); - exit(1); - } - if (mode != 5) { - if (!torque_enable(false)) { - exit(1); - } - if (dynamixel_writebyte(15, XM_OPERATING_MODE, 5) != 1) { // Current-based Position Control Mode - ROS_ERROR("I2C dynamixel id=15 write operating Mode error"); - exit(1); - } - } - if (dynamixel_writedword(15, XM_PROFILE_ACCELERATION, 20) != 1) { - ROS_ERROR("I2C dynamixel id=15 write profile Acceleration error"); - exit(1); - } - if (dynamixel_writedword(15, XM_PROFILE_VELOCITY, 200) != 1) { - ROS_ERROR("I2C dynamixel id=15 write profile Velocity error"); - exit(1); - } - if (!torque_enable(true)) { - exit(1); - } - } - - // Converts pos_encoder from wheels to wheel angles - void read(ros::Duration period) { - int32_t value; - int16_t current; - auto t1 = std::chrono::high_resolution_clock::now(); - int num_error = 0; - - // arm - for(int i=0, id=11; id<=14; id++, i++) { - if (ignore_ids.count(i) > 0) { - ROS_ERROR_THROTTLE(10, "Ignoring dynamixel %d", id); - continue; - } - - if (dynamixel_readdword(id, XM_PRESENT_POSITION, &value) == 1) { - pos[i] = STEPS_TO_RADIAN*(value-2048); - } else { - ROS_ERROR("I2C dynamixel id=%d position read error", id); - num_error++; - } - - if (dynamixel_readdword(id, XM_PRESENT_VELOCITY, &value) == 1) { - vel[i] = value*VELOCITY_STEPS_TO_RADS; - } else { - ROS_ERROR("I2C dynamixel id=%d velocity read error", id); - num_error++; - } - -#ifdef READ_EFFORT - if (dynamixel_readword(id, XM_PRESENT_CURRENT, ¤t) == 1) { - eff[i] = current*2.69e-3; - } else { - ROS_ERROR("I2C dynamixel id=%d current read error", id); - num_error++; - } -#endif - - if (num_error >= 3) { - ignore_ids.insert(i); - } - } - - // gripper - if (dynamixel_readdword(15, XM_PRESENT_POSITION, &value) == 1) { - pos[4] = STEPS_TO_RADIAN*(value-2048)*GRIPPER_RADIAN_TO_METER; - } else { - ROS_ERROR("I2C dynamixel id=15 position read error"); - } - if (dynamixel_readdword(15, XM_PRESENT_VELOCITY, &value) == 1) { - vel[4] = value*VELOCITY_STEPS_TO_RADS*GRIPPER_RADIAN_TO_METER; - } else { - ROS_ERROR("I2C dynamixel id=15 velocity read error"); - } -#ifdef READ_EFFORT - if (dynamixel_readword(15, XM_PRESENT_CURRENT, ¤t) == 1) { - eff[4] = current*2.69e-3; - } else { - ROS_ERROR("I2C dynamixel id=15 current read error"); - } -#endif - - ROS_DEBUG("pos: %.2f %.2f %.2f %.2f %.2f", pos[0]*180/M_PI, pos[1]*180/M_PI, pos[2]*180/M_PI, pos[3]*180/M_PI, pos[4]); - ROS_DEBUG("velocity: %.2f %.2f %.2f %.2f %.2f", vel[0]*30/M_PI, vel[1]*30/M_PI, vel[2]*30/M_PI, vel[3]*30/M_PI, vel[4]); -#ifdef READ_EFFORT - ROS_DEBUG("current: %.2f %.2f %.2f %.2f %.2f", eff[0], eff[1], eff[2], eff[3], eff[4]); -#endif - auto t2 = std::chrono::high_resolution_clock::now(); - int64_t duration = std::chrono::duration_cast( t2 - t1 ).count(); - ROS_DEBUG("read duration: %lldms", duration); - } - - // Writes current velocity command to hardware - void write() { - int32_t value; - - if (memcmp(cmd, cmd_pre, sizeof(cmd)) != 0) { // Only write new position when changed - ROS_DEBUG("cmd: %.2f %.2f %.2f %.2f %.2f", cmd[0]*180/M_PI, cmd[1]*180/M_PI, cmd[2]*180/M_PI, cmd[3]*180/M_PI, cmd[4]); - - // arm - for(int i=0, id=11; id<=14; id++, i++) { - if (isnan(cmd[i])) { - ROS_WARN("Desired angle for id=%d is NaN, skipping write.", id); - continue; - } - - value = cmd[i]/STEPS_TO_RADIAN + 2048; - - if (dynamixel_writedword(id, XM_GOAL_POSITION, value) == 1) { - cmd_pre[i] = cmd[i]; - } else { - ROS_ERROR("I2C dynamixel id=%d write error", id); - } - } - - // gripper - if (isnan(cmd[4]) || cmd[4] < -0.010 || cmd[4] > 0.019) { - ROS_WARN("Desired angle for id=15 is NaN or outside joint limit, skipping write."); - } else { - value = cmd[4]/GRIPPER_RADIAN_TO_METER/STEPS_TO_RADIAN + 2048; - if (dynamixel_writedword(15, XM_GOAL_POSITION, value) == 1) { - cmd_pre[4] = cmd[4]; - } else { - ROS_ERROR("I2C dynamixel id=15 write error"); - } - } - } - } - - bool torque_enable(bool enable) { - bool ret = true; - for(int id=11; id<=15; id++) { - if (dynamixel_writebyte(id, XM_TORQUE_ENABLE, enable) != 1) { - ROS_ERROR("I2C dynamixel id=%d torque change", id); - ret = false; - } - } - return ret; - } - - private: - hardware_interface::JointStateInterface jnt_state_interface; - hardware_interface::PositionJointInterface jnt_pos_interface; - ros::NodeHandle nh; - double cmd[5] = {NAN, NAN, NAN, NAN, NAN}; - double cmd_pre[5] = {NAN, NAN, NAN, NAN, NAN}; // determine if cmd changed - double pos[5] = {0, 0, 0, 0, 0}; - double vel[5] = {0, 0, 0, 0, 0}; - double eff[5] = {0, 0, 0, 0, 0}; - ros::ServiceServer torque_enable_service, get_error_service; - std::mutex comm_mutex; - std::set ignore_ids; - - int dynamixel_write(uint8_t *write_data, int write_num, uint8_t *read_data, int read_num) { - int file; - int ret; - uint8_t read_buf[read_num+1]; // for unknown reason need to read one more byte with USI Slave - - comm_mutex.lock(); - if ((file = open(I2C_FILE, O_RDWR)) < 0) { - perror("open"); - goto error; - } - - if (ioctl(file, I2C_SLAVE, I2C_ADDR) < 0) { - perror("ioctl"); - goto error; - } - - if ((ret = ::write(file, write_data, write_num)) != write_num) { - perror("i2c write"); - goto error; - } - - // wait at least the half duplex transmission time, assume 29 (=14+15) bytes send/received: 1/(115200.0/10/29) <= 2.6ms - //usleep(3.2*1e3); - if (read_num > 0) { - if ((ret = ::read(file, read_buf, read_num+1)) != read_num+1) { - perror("i2c read"); - goto error; - } - ret--; // remove extra byte - memcpy(read_data, read_buf, ret); - } - - error: - close(file); - comm_mutex.unlock(); - return ret; - } - - uint8_t dynamixel_writebyte(uint8_t id, uint8_t cmd, uint8_t value) { - uint8_t write_data[5] = {id, cmd, 1, value, CMD_EOF}; - uint8_t read_data[2]; - int ret = dynamixel_write(write_data, 5, read_data, 2); - if (ret == 2 && read_data[1] == id) { - return read_data[0]; - } - return 255; - } - - uint8_t dynamixel_writeword(uint8_t id, uint8_t cmd, int16_t value) { - uint8_t write_data[6] = {id, cmd, 2, (uint8_t)(value>>8), (uint8_t)value, CMD_EOF}; - uint8_t read_data[2]; - int ret = dynamixel_write(write_data, 6, read_data, 2); - if (ret == 2 && read_data[1] == id) { - return read_data[0]; - } - return 255; - } - - uint8_t dynamixel_writedword(uint8_t id, uint8_t cmd, int32_t value) { - uint8_t write_data[8] = {id, cmd, 4, (uint8_t)(value>>24), (uint8_t)(value>>16), (uint8_t)(value>>8), (uint8_t)value, CMD_EOF}; - uint8_t read_data[2]; - int ret = dynamixel_write(write_data, 8, read_data, 2); - if (ret == 2 && read_data[1] == id) { - return read_data[0]; - } - return 255; - } - - uint8_t dynamixel_readbyte(uint8_t id, uint8_t cmd, uint8_t *value) { - uint8_t write_data[4] = {id, cmd, 0x11, CMD_EOF}; - uint8_t read_data[3]; - int ret = dynamixel_write(write_data, 4, read_data, 3); - if (ret == 3 && read_data[1] == id) { - *value = read_data[2]; - return read_data[0]; - } - if (read_data[0] != 1) { - ROS_ERROR("I2C dynamixel id=%d alert value: %d", id, read_data[0]); - } - return 255; - } - - uint8_t dynamixel_readword(uint8_t id, uint8_t cmd, int16_t *value) { - uint8_t write_data[4] = {id, cmd, 0x12, CMD_EOF}; - uint8_t read_data[4]; - int ret = dynamixel_write(write_data, 4, read_data, 4); - if (ret == 4 && read_data[1] == id) { - *value = (read_data[2]<<8) | read_data[3]; - return read_data[0]; - } - return 255; - } - - uint8_t dynamixel_readdword(uint8_t id, uint8_t cmd, int32_t *value) { - uint8_t write_data[4] = {id, cmd, 0x14, CMD_EOF}; - uint8_t read_data[6]; - int ret = dynamixel_write(write_data, 4, read_data, 6); - if (ret == 6 && read_data[0] == 1 && read_data[1] == id) { - *value = (read_data[2]<<24) | (read_data[3]<<16) | (read_data[4]<<8) | read_data[5]; - return read_data[0]; - } - if (read_data[0] != 1) { - ROS_ERROR("I2C dynamixel id=%d alert value: %d", id, read_data[0]); - } - return 255; - } - - bool cbTorqueEnable(std_srvs::SetBool::Request &req, std_srvs::SetBool::Response &res) { - ROS_INFO("Setting torque enable=%d", req.data); - res.success = torque_enable(req.data); - return true; - } - - bool cbGetError(wt_open_manipulator::GetError::Request &req, wt_open_manipulator::GetError::Response &res) { - ROS_INFO("Reading Hardware Error Status"); - - for(int id=11, i=0; id<=15; id++, i++) { - wt_open_manipulator::HardwareError hw_error; - uint8_t value; - if (dynamixel_readbyte(id, XM_HARDWARE_ERROR_STATUS, &value) != 1) { - ROS_ERROR("I2C dynamixel id=%d reading hardware error status", id); - } - hw_error.id = id; - hw_error.inputVoltage = value & (1<<0); - hw_error.overHeating = value & (1<<2); - hw_error.motorEncoder = value & (1<<3); - hw_error.electricalShock = value & (1<<4); - hw_error.overload = value & (1<<5); - res.errors.push_back(hw_error); - } - - return true; - } -}; diff --git a/launch/display_urdf.launch b/launch/display_urdf.launch deleted file mode 100644 index 3520220..0000000 --- a/launch/display_urdf.launch +++ /dev/null @@ -1,15 +0,0 @@ - - - - - - - - - - - - - - - diff --git a/launch/display_urdf.launch.py b/launch/display_urdf.launch.py new file mode 100644 index 0000000..27a0712 --- /dev/null +++ b/launch/display_urdf.launch.py @@ -0,0 +1,55 @@ +# Display the open manipulator URDF in rviz2 with interactive joint state publishing. + +from launch import LaunchDescription +from launch.actions import DeclareLaunchArgument +from launch.conditions import IfCondition +from launch.substitutions import Command, LaunchConfiguration, PathSubstitution + +from launch_ros.actions import Node +from launch_ros.parameter_descriptions import ParameterValue +from launch_ros.substitutions import FindPackageShare + + +def generate_launch_description(): + pkg_share = FindPackageShare("a4wd3_open_manipulator") + + robot_description = Command( + [ + "xacro", + " ", + PathSubstitution(pkg_share / "urdf" / "open_manipulator.urdf.xacro"), + ] + ) + + return LaunchDescription( + [ + DeclareLaunchArgument( + "gui", + default_value="true", + description="Use the GUI version of joint_state_publisher.", + ), + Node( + package="joint_state_publisher", + executable="joint_state_publisher", + output="both", + parameters=[{"use_gui": LaunchConfiguration("gui")}], + ), + Node( + package="robot_state_publisher", + executable="robot_state_publisher", + output="both", + # Jazzy: a bare substitution value is parsed as yaml, which the URDF is + # not; ParameterValue(value_type=str) keeps it as a plain string. + parameters=[ + {"robot_description": ParameterValue(robot_description, value_type=str)} + ], + ), + Node( + package="rviz2", + executable="rviz2", + name="rviz2", + output="log", + condition=IfCondition(LaunchConfiguration("gui")), + ), + ] + ) diff --git a/launch/open_manipulator.launch b/launch/open_manipulator.launch deleted file mode 100644 index 0cca044..0000000 --- a/launch/open_manipulator.launch +++ /dev/null @@ -1,12 +0,0 @@ - - - - - - - - - - - - diff --git a/launch/open_manipulator.launch.py b/launch/open_manipulator.launch.py new file mode 100644 index 0000000..c9f936c --- /dev/null +++ b/launch/open_manipulator.launch.py @@ -0,0 +1,64 @@ +# Launch the open manipulator hardware interface, controller manager and controllers. + +from launch import LaunchDescription +from launch.substitutions import Command, PathSubstitution + +from launch_ros.actions import Node +from launch_ros.parameter_descriptions import ParameterValue +from launch_ros.substitutions import FindPackageShare + + +def generate_launch_description(): + pkg_share = FindPackageShare("a4wd3_open_manipulator") + + robot_description = Command( + [ + "xacro", + " ", + PathSubstitution(pkg_share / "urdf" / "open_manipulator.urdf.xacro"), + ] + ) + + controllers_config = PathSubstitution( + pkg_share / "config" / "a4wd3_open_manipulator_controllers.yaml" + ) + + return LaunchDescription( + [ + Node( + package="robot_state_publisher", + executable="robot_state_publisher", + output="both", + # Jazzy: a bare substitution value is parsed as yaml, which the URDF is + # not; ParameterValue(value_type=str) keeps it as a plain string. + parameters=[ + {"robot_description": ParameterValue(robot_description, value_type=str)} + ], + ), + # ros2_control hardware interface + controller manager + # NOTE: keep the default node name 'controller_manager' — the config's + # 'controller_manager:' block (update_rate etc.) and the spawner both key + # off that name. Renaming the node breaks both. + Node( + package="controller_manager", + executable="ros2_control_node", + output="screen", + emulate_tty=True, + parameters=[controllers_config], + ), + # load the controllers + Node( + package="controller_manager", + executable="spawner", + name="controller_spawner", + output="screen", + arguments=[ + "joint_state_broadcaster", + "arm_controller", + "gripper_controller", + "--param-file", + controllers_config, + ], + ), + ] + ) diff --git a/msg/HardwareError.msg b/msg/HardwareError.msg index 1a02a64..4389489 100644 --- a/msg/HardwareError.msg +++ b/msg/HardwareError.msg @@ -1,6 +1,6 @@ int32 id -bool inputVoltage -bool overHeating -bool motorEncoder -bool electricalShock +bool input_voltage +bool over_heating +bool motor_encoder +bool electrical_shock bool overload diff --git a/package.xml b/package.xml index 0c9f3a0..c04b83a 100644 --- a/package.xml +++ b/package.xml @@ -1,65 +1,45 @@ - - wt_open_manipulator + + + a4wd3_open_manipulator 0.0.0 - The wt_open_manipulator package + ros2_control hardware interface and control stack for the Wild Thumper open manipulator arm (I2C Dynamixel based). - - - erik - - - - TODO + ament_cmake - - - - - + rosidl_default_generators + rosidl_default_runtime - - - - + builtin_interfaces + controller_manager + hardware_interface + pluginlib + rclcpp + rclcpp_lifecycle + std_msgs + std_srvs - - - - - - - - - - - - - - - - - - - - - - catkin - controller_manager - joint_trajectory_controller - libi2c-dev - message_generation - controller_manager + joint_state_broadcaster open_manipulator_description - message_runtime + realsense2_description + joint_state_publisher + joint_trajectory_controller + parallel_gripper_controller + launch + launch_ros + robot_state_publisher + ros2launch + rviz2 + urdf + xacro + + rosidl_interface_packages - - - + ament_cmake diff --git a/scripts/move_group_python_interface_tutorial.py b/scripts/move_group_python_interface_tutorial.py new file mode 100644 index 0000000..1eaed1e --- /dev/null +++ b/scripts/move_group_python_interface_tutorial.py @@ -0,0 +1,546 @@ +#!/usr/bin/env python + +# Software License Agreement (BSD License) +# +# Copyright (c) 2013, SRI International +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions +# are met: +# +# * Redistributions of source code must retain the above copyright +# notice, this list of conditions and the following disclaimer. +# * Redistributions in binary form must reproduce the above +# copyright notice, this list of conditions and the following +# disclaimer in the documentation and/or other materials provided +# with the distribution. +# * Neither the name of SRI International nor the names of its +# contributors may be used to endorse or promote products derived +# from this software without specific prior written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS +# FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE +# COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, +# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, +# BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER +# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT +# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN +# ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE +# POSSIBILITY OF SUCH DAMAGE. +# +# Author: Acorn Pooley, Mike Lautman + +## BEGIN_SUB_TUTORIAL imports +## +## To use the Python MoveIt interfaces, we will import the `moveit_commander`_ namespace. +## This namespace provides us with a `MoveGroupCommander`_ class, a `PlanningSceneInterface`_ class, +## and a `RobotCommander`_ class. More on these below. We also import `rospy`_ and some messages that we will use: +## + +import sys +import copy +import rospy +import moveit_commander +import moveit_msgs.msg +import geometry_msgs.msg +from math import pi +from std_msgs.msg import String +from moveit_commander.conversions import pose_to_list +## END_SUB_TUTORIAL + + +def all_close(goal, actual, tolerance): + """ + Convenience method for testing if a list of values are within a tolerance of their counterparts in another list + @param: goal A list of floats, a Pose or a PoseStamped + @param: actual A list of floats, a Pose or a PoseStamped + @param: tolerance A float + @returns: bool + """ + all_equal = True + if type(goal) is list: + for index in range(len(goal)): + if abs(actual[index] - goal[index]) > tolerance: + return False + + elif type(goal) is geometry_msgs.msg.PoseStamped: + return all_close(goal.pose, actual.pose, tolerance) + + elif type(goal) is geometry_msgs.msg.Pose: + return all_close(pose_to_list(goal), pose_to_list(actual), tolerance) + + return True + + +class MoveGroupPythonIntefaceTutorial(object): + """MoveGroupPythonIntefaceTutorial""" + def __init__(self): + super(MoveGroupPythonIntefaceTutorial, self).__init__() + + ## BEGIN_SUB_TUTORIAL setup + ## + ## First initialize `moveit_commander`_ and a `rospy`_ node: + moveit_commander.roscpp_initialize(sys.argv) + rospy.init_node('move_group_python_interface_tutorial', anonymous=True) + + ## Instantiate a `RobotCommander`_ object. Provides information such as the robot's + ## kinematic model and the robot's current joint states + robot = moveit_commander.RobotCommander() + + ## Instantiate a `PlanningSceneInterface`_ object. This provides a remote interface + ## for getting, setting, and updating the robot's internal understanding of the + ## surrounding world: + scene = moveit_commander.PlanningSceneInterface() + + ## Instantiate a `MoveGroupCommander`_ object. This object is an interface + ## to a planning group (group of joints). In this tutorial the group is the primary + ## arm joints in the Panda robot, so we set the group's name to "panda_arm". + ## If you are using a different robot, change this value to the name of your robot + ## arm planning group. + ## This interface can be used to plan and execute motions: + group_name = "panda_arm" + move_group = moveit_commander.MoveGroupCommander(group_name) + + ## Create a `DisplayTrajectory`_ ROS publisher which is used to display + ## trajectories in Rviz: + display_trajectory_publisher = rospy.Publisher('/move_group/display_planned_path', + moveit_msgs.msg.DisplayTrajectory, + queue_size=20) + + ## END_SUB_TUTORIAL + + ## BEGIN_SUB_TUTORIAL basic_info + ## + ## Getting Basic Information + ## ^^^^^^^^^^^^^^^^^^^^^^^^^ + # We can get the name of the reference frame for this robot: + planning_frame = move_group.get_planning_frame() + print "============ Planning frame: %s" % planning_frame + + # We can also print the name of the end-effector link for this group: + eef_link = move_group.get_end_effector_link() + print "============ End effector link: %s" % eef_link + + # We can get a list of all the groups in the robot: + group_names = robot.get_group_names() + print "============ Available Planning Groups:", robot.get_group_names() + + # Sometimes for debugging it is useful to print the entire state of the + # robot: + print "============ Printing robot state" + print robot.get_current_state() + print "" + ## END_SUB_TUTORIAL + + # Misc variables + self.box_name = '' + self.robot = robot + self.scene = scene + self.move_group = move_group + self.display_trajectory_publisher = display_trajectory_publisher + self.planning_frame = planning_frame + self.eef_link = eef_link + self.group_names = group_names + + + def go_to_joint_state(self): + # Copy class variables to local variables to make the web tutorials more clear. + # In practice, you should use the class variables directly unless you have a good + # reason not to. + move_group = self.move_group + + ## BEGIN_SUB_TUTORIAL plan_to_joint_state + ## + ## Planning to a Joint Goal + ## ^^^^^^^^^^^^^^^^^^^^^^^^ + ## The Panda's zero configuration is at a `singularity `_ so the first + ## thing we want to do is move it to a slightly better configuration. + # We can get the joint values from the group and adjust some of the values: + joint_goal = move_group.get_current_joint_values() + joint_goal[0] = 0 + joint_goal[1] = -pi/4 + joint_goal[2] = 0 + joint_goal[3] = -pi/2 + joint_goal[4] = 0 + joint_goal[5] = pi/3 + joint_goal[6] = 0 + + # The go command can be called with joint values, poses, or without any + # parameters if you have already set the pose or joint target for the group + move_group.go(joint_goal, wait=True) + + # Calling ``stop()`` ensures that there is no residual movement + move_group.stop() + + ## END_SUB_TUTORIAL + + # For testing: + current_joints = move_group.get_current_joint_values() + return all_close(joint_goal, current_joints, 0.01) + + + def go_to_pose_goal(self): + # Copy class variables to local variables to make the web tutorials more clear. + # In practice, you should use the class variables directly unless you have a good + # reason not to. + move_group = self.move_group + + ## BEGIN_SUB_TUTORIAL plan_to_pose + ## + ## Planning to a Pose Goal + ## ^^^^^^^^^^^^^^^^^^^^^^^ + ## We can plan a motion for this group to a desired pose for the + ## end-effector: + pose_goal = geometry_msgs.msg.Pose() + pose_goal.orientation.w = 1.0 + pose_goal.position.x = 0.4 + pose_goal.position.y = 0.1 + pose_goal.position.z = 0.4 + + move_group.set_pose_target(pose_goal) + + ## Now, we call the planner to compute the plan and execute it. + plan = move_group.go(wait=True) + # Calling `stop()` ensures that there is no residual movement + move_group.stop() + # It is always good to clear your targets after planning with poses. + # Note: there is no equivalent function for clear_joint_value_targets() + move_group.clear_pose_targets() + + ## END_SUB_TUTORIAL + + # For testing: + # Note that since this section of code will not be included in the tutorials + # we use the class variable rather than the copied state variable + current_pose = self.move_group.get_current_pose().pose + return all_close(pose_goal, current_pose, 0.01) + + + def plan_cartesian_path(self, scale=1): + # Copy class variables to local variables to make the web tutorials more clear. + # In practice, you should use the class variables directly unless you have a good + # reason not to. + move_group = self.move_group + + ## BEGIN_SUB_TUTORIAL plan_cartesian_path + ## + ## Cartesian Paths + ## ^^^^^^^^^^^^^^^ + ## You can plan a Cartesian path directly by specifying a list of waypoints + ## for the end-effector to go through. If executing interactively in a + ## Python shell, set scale = 1.0. + ## + waypoints = [] + + wpose = move_group.get_current_pose().pose + wpose.position.z -= scale * 0.1 # First move up (z) + wpose.position.y += scale * 0.2 # and sideways (y) + waypoints.append(copy.deepcopy(wpose)) + + wpose.position.x += scale * 0.1 # Second move forward/backwards in (x) + waypoints.append(copy.deepcopy(wpose)) + + wpose.position.y -= scale * 0.1 # Third move sideways (y) + waypoints.append(copy.deepcopy(wpose)) + + # We want the Cartesian path to be interpolated at a resolution of 1 cm + # which is why we will specify 0.01 as the eef_step in Cartesian + # translation. We will disable the jump threshold by setting it to 0.0, + # ignoring the check for infeasible jumps in joint space, which is sufficient + # for this tutorial. + (plan, fraction) = move_group.compute_cartesian_path( + waypoints, # waypoints to follow + 0.01, # eef_step + 0.0) # jump_threshold + + # Note: We are just planning, not asking move_group to actually move the robot yet: + return plan, fraction + + ## END_SUB_TUTORIAL + + + def display_trajectory(self, plan): + # Copy class variables to local variables to make the web tutorials more clear. + # In practice, you should use the class variables directly unless you have a good + # reason not to. + robot = self.robot + display_trajectory_publisher = self.display_trajectory_publisher + + ## BEGIN_SUB_TUTORIAL display_trajectory + ## + ## Displaying a Trajectory + ## ^^^^^^^^^^^^^^^^^^^^^^^ + ## You can ask RViz to visualize a plan (aka trajectory) for you. But the + ## group.plan() method does this automatically so this is not that useful + ## here (it just displays the same trajectory again): + ## + ## A `DisplayTrajectory`_ msg has two primary fields, trajectory_start and trajectory. + ## We populate the trajectory_start with our current robot state to copy over + ## any AttachedCollisionObjects and add our plan to the trajectory. + display_trajectory = moveit_msgs.msg.DisplayTrajectory() + display_trajectory.trajectory_start = robot.get_current_state() + display_trajectory.trajectory.append(plan) + # Publish + display_trajectory_publisher.publish(display_trajectory); + + ## END_SUB_TUTORIAL + + + def execute_plan(self, plan): + # Copy class variables to local variables to make the web tutorials more clear. + # In practice, you should use the class variables directly unless you have a good + # reason not to. + move_group = self.move_group + + ## BEGIN_SUB_TUTORIAL execute_plan + ## + ## Executing a Plan + ## ^^^^^^^^^^^^^^^^ + ## Use execute if you would like the robot to follow + ## the plan that has already been computed: + move_group.execute(plan, wait=True) + + ## **Note:** The robot's current joint state must be within some tolerance of the + ## first waypoint in the `RobotTrajectory`_ or ``execute()`` will fail + ## END_SUB_TUTORIAL + + + def wait_for_state_update(self, box_is_known=False, box_is_attached=False, timeout=4): + # Copy class variables to local variables to make the web tutorials more clear. + # In practice, you should use the class variables directly unless you have a good + # reason not to. + box_name = self.box_name + scene = self.scene + + ## BEGIN_SUB_TUTORIAL wait_for_scene_update + ## + ## Ensuring Collision Updates Are Received + ## ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + ## If the Python node dies before publishing a collision object update message, the message + ## could get lost and the box will not appear. To ensure that the updates are + ## made, we wait until we see the changes reflected in the + ## ``get_attached_objects()`` and ``get_known_object_names()`` lists. + ## For the purpose of this tutorial, we call this function after adding, + ## removing, attaching or detaching an object in the planning scene. We then wait + ## until the updates have been made or ``timeout`` seconds have passed + start = rospy.get_time() + seconds = rospy.get_time() + while (seconds - start < timeout) and not rospy.is_shutdown(): + # Test if the box is in attached objects + attached_objects = scene.get_attached_objects([box_name]) + is_attached = len(attached_objects.keys()) > 0 + + # Test if the box is in the scene. + # Note that attaching the box will remove it from known_objects + is_known = box_name in scene.get_known_object_names() + + # Test if we are in the expected state + if (box_is_attached == is_attached) and (box_is_known == is_known): + return True + + # Sleep so that we give other threads time on the processor + rospy.sleep(0.1) + seconds = rospy.get_time() + + # If we exited the while loop without returning then we timed out + return False + ## END_SUB_TUTORIAL + + + def add_box(self, timeout=4): + # Copy class variables to local variables to make the web tutorials more clear. + # In practice, you should use the class variables directly unless you have a good + # reason not to. + box_name = self.box_name + scene = self.scene + + ## BEGIN_SUB_TUTORIAL add_box + ## + ## Adding Objects to the Planning Scene + ## ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + ## First, we will create a box in the planning scene at the location of the left finger: + box_pose = geometry_msgs.msg.PoseStamped() + box_pose.header.frame_id = "panda_leftfinger" + box_pose.pose.orientation.w = 1.0 + box_pose.pose.position.z = 0.07 # slightly above the end effector + box_name = "box" + scene.add_box(box_name, box_pose, size=(0.1, 0.1, 0.1)) + + ## END_SUB_TUTORIAL + # Copy local variables back to class variables. In practice, you should use the class + # variables directly unless you have a good reason not to. + self.box_name=box_name + return self.wait_for_state_update(box_is_known=True, timeout=timeout) + + + def attach_box(self, timeout=4): + # Copy class variables to local variables to make the web tutorials more clear. + # In practice, you should use the class variables directly unless you have a good + # reason not to. + box_name = self.box_name + robot = self.robot + scene = self.scene + eef_link = self.eef_link + group_names = self.group_names + + ## BEGIN_SUB_TUTORIAL attach_object + ## + ## Attaching Objects to the Robot + ## ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + ## Next, we will attach the box to the Panda wrist. Manipulating objects requires the + ## robot be able to touch them without the planning scene reporting the contact as a + ## collision. By adding link names to the ``touch_links`` array, we are telling the + ## planning scene to ignore collisions between those links and the box. For the Panda + ## robot, we set ``grasping_group = 'hand'``. If you are using a different robot, + ## you should change this value to the name of your end effector group name. + grasping_group = 'hand' + touch_links = robot.get_link_names(group=grasping_group) + scene.attach_box(eef_link, box_name, touch_links=touch_links) + ## END_SUB_TUTORIAL + + # We wait for the planning scene to update. + return self.wait_for_state_update(box_is_attached=True, box_is_known=False, timeout=timeout) + + + def detach_box(self, timeout=4): + # Copy class variables to local variables to make the web tutorials more clear. + # In practice, you should use the class variables directly unless you have a good + # reason not to. + box_name = self.box_name + scene = self.scene + eef_link = self.eef_link + + ## BEGIN_SUB_TUTORIAL detach_object + ## + ## Detaching Objects from the Robot + ## ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + ## We can also detach and remove the object from the planning scene: + scene.remove_attached_object(eef_link, name=box_name) + ## END_SUB_TUTORIAL + + # We wait for the planning scene to update. + return self.wait_for_state_update(box_is_known=True, box_is_attached=False, timeout=timeout) + + + def remove_box(self, timeout=4): + # Copy class variables to local variables to make the web tutorials more clear. + # In practice, you should use the class variables directly unless you have a good + # reason not to. + box_name = self.box_name + scene = self.scene + + ## BEGIN_SUB_TUTORIAL remove_object + ## + ## Removing Objects from the Planning Scene + ## ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + ## We can remove the box from the world. + scene.remove_world_object(box_name) + + ## **Note:** The object must be detached before we can remove it from the world + ## END_SUB_TUTORIAL + + # We wait for the planning scene to update. + return self.wait_for_state_update(box_is_attached=False, box_is_known=False, timeout=timeout) + + +def main(): + try: + print "" + print "----------------------------------------------------------" + print "Welcome to the MoveIt MoveGroup Python Interface Tutorial" + print "----------------------------------------------------------" + print "Press Ctrl-D to exit at any time" + print "" + print "============ Press `Enter` to begin the tutorial by setting up the moveit_commander ..." + raw_input() + tutorial = MoveGroupPythonIntefaceTutorial() + + print "============ Press `Enter` to execute a movement using a joint state goal ..." + raw_input() + tutorial.go_to_joint_state() + + print "============ Press `Enter` to execute a movement using a pose goal ..." + raw_input() + tutorial.go_to_pose_goal() + + print "============ Press `Enter` to plan and display a Cartesian path ..." + raw_input() + cartesian_plan, fraction = tutorial.plan_cartesian_path() + + print "============ Press `Enter` to display a saved trajectory (this will replay the Cartesian path) ..." + raw_input() + tutorial.display_trajectory(cartesian_plan) + + print "============ Press `Enter` to execute a saved path ..." + raw_input() + tutorial.execute_plan(cartesian_plan) + + print "============ Press `Enter` to add a box to the planning scene ..." + raw_input() + tutorial.add_box() + + print "============ Press `Enter` to attach a Box to the Panda robot ..." + raw_input() + tutorial.attach_box() + + print "============ Press `Enter` to plan and execute a path with an attached collision object ..." + raw_input() + cartesian_plan, fraction = tutorial.plan_cartesian_path(scale=-1) + tutorial.execute_plan(cartesian_plan) + + print "============ Press `Enter` to detach the box from the Panda robot ..." + raw_input() + tutorial.detach_box() + + print "============ Press `Enter` to remove the box from the planning scene ..." + raw_input() + tutorial.remove_box() + + print "============ Python tutorial demo complete!" + except rospy.ROSInterruptException: + return + except KeyboardInterrupt: + return + +if __name__ == '__main__': + main() + +## BEGIN_TUTORIAL +## .. _moveit_commander: +## http://docs.ros.org/melodic/api/moveit_commander/html/namespacemoveit__commander.html +## +## .. _MoveGroupCommander: +## http://docs.ros.org/melodic/api/moveit_commander/html/classmoveit__commander_1_1move__group_1_1MoveGroupCommander.html +## +## .. _RobotCommander: +## http://docs.ros.org/melodic/api/moveit_commander/html/classmoveit__commander_1_1robot_1_1RobotCommander.html +## +## .. _PlanningSceneInterface: +## http://docs.ros.org/melodic/api/moveit_commander/html/classmoveit__commander_1_1planning__scene__interface_1_1PlanningSceneInterface.html +## +## .. _DisplayTrajectory: +## http://docs.ros.org/melodic/api/moveit_msgs/html/msg/DisplayTrajectory.html +## +## .. _RobotTrajectory: +## http://docs.ros.org/melodic/api/moveit_msgs/html/msg/RobotTrajectory.html +## +## .. _rospy: +## http://docs.ros.org/melodic/api/rospy/html/ +## CALL_SUB_TUTORIAL imports +## CALL_SUB_TUTORIAL setup +## CALL_SUB_TUTORIAL basic_info +## CALL_SUB_TUTORIAL plan_to_joint_state +## CALL_SUB_TUTORIAL plan_to_pose +## CALL_SUB_TUTORIAL plan_cartesian_path +## CALL_SUB_TUTORIAL display_trajectory +## CALL_SUB_TUTORIAL execute_plan +## CALL_SUB_TUTORIAL add_box +## CALL_SUB_TUTORIAL wait_for_scene_update +## CALL_SUB_TUTORIAL attach_object +## CALL_SUB_TUTORIAL detach_object +## CALL_SUB_TUTORIAL remove_object +## END_TUTORIAL diff --git a/scripts/test_arm_pos.sh b/scripts/test_arm_pos.sh index f43cc67..a009a98 100755 --- a/scripts/test_arm_pos.sh +++ b/scripts/test_arm_pos.sh @@ -8,19 +8,12 @@ if [ "$1" == "cam_aft" ]; then POS=$CAM_AFT_POS fi -rostopic pub /arm_controller/command trajectory_msgs/JointTrajectory "header: - seq: 0 - stamp: - secs: 0 - nsecs: 0 +ros2 topic pub --once /arm_controller/joint_trajectory trajectory_msgs/msg/JointTrajectory "header: frame_id: '' joint_names: ['joint1', 'joint2', 'joint3', 'joint4'] points: - positions: $POS - velocities: [] - accelerations: [] - effort: [] time_from_start: - secs: 5 - nsecs: 0" --once + sec: 5 + nanosec: 0" diff --git a/src/wt_open_manipulator_node.cpp b/src/wt_open_manipulator_node.cpp deleted file mode 100644 index e07ec0d..0000000 --- a/src/wt_open_manipulator_node.cpp +++ /dev/null @@ -1,61 +0,0 @@ -#include -#include "ros/ros.h" -#include "open_manipulator_i2c.h" -#include "controller_manager/controller_manager.h" -#include "std_srvs/SetBool.h" - -static ros::ServiceClient enableManip; - -void enableManippulator(bool enable) { - std_srvs::SetBool srv; - srv.request.data = enable; - - if (enableManip.call(srv)) { - if (enable) { - ROS_INFO("Manipulator enabled"); - } else { - ROS_INFO("Manipulator disabled"); - } - } else { - ROS_ERROR("Failed to call service manipulator_enable"); - } -} - -void handleSigint(int sig) { - enableManippulator(false); - ros::shutdown(); -} - -int main(int argc, char **argv) { - ros::init(argc, argv, "wt_open_manipulator_i2c", ros::init_options::NoSigintHandler); - - ros::NodeHandle nh("~"); - - enableManip = nh.serviceClient("/wild_thumper/manipulator_enable"); - enableManippulator(true); - sleep(1); // wait to power up - signal(SIGINT, handleSigint); - - WtOpenManipulatorI2C robot(nh); - controller_manager::ControllerManager cm(&robot); - - ros::AsyncSpinner spinner(1); - spinner.start(); - - ros::Time prev_time = ros::Time::now(); - ros::Rate loop_rate(10); - while(ros::ok()) { - const ros::Time time = ros::Time::now(); - const ros::Duration period = time - prev_time; - - robot.read(period); - cm.update(time, period); - robot.write(); - - prev_time = time; - loop_rate.sleep(); - } - spinner.stop(); - - return 0; -} diff --git a/srv/GetError.srv b/srv/GetError.srv index 97c21d5..fb57cd4 100644 --- a/srv/GetError.srv +++ b/srv/GetError.srv @@ -1,2 +1,2 @@ --- -wt_open_manipulator/HardwareError[] errors +a4wd3_open_manipulator/HardwareError[] errors diff --git a/tools/fake_i2c.c b/tools/fake_i2c.c new file mode 100644 index 0000000..13b5e0f --- /dev/null +++ b/tools/fake_i2c.c @@ -0,0 +1,167 @@ +// Fake I2C Dynamixel emulator for smoke-testing a4wd3_open_manipulator without hardware. +// Intercepts open/ioctl/read/write/close on /dev/i2c-7 and answers the +// simplified USI-slave dynamixel protocol used by the hardware interface. +#define _GNU_SOURCE +#include +#include +#include +#include +#include +#include +#include + +#ifndef I2C_SLAVE +#define I2C_SLAVE 0x0600 +#endif + +static int (*real_open)(const char *, int, ...) = NULL; +static int (*real_close)(int) = NULL; +static int (*real_ioctl)(int, unsigned long, ...) = NULL; +static ssize_t (*real_read)(int, void *, size_t) = NULL; +static ssize_t (*real_write)(int, const void *, size_t) = NULL; + +static int cur_fd = -1; +static unsigned char resp[16]; +static int resp_len = 0; +static int resp_pos = 0; + +static void prep(const unsigned char *req, size_t n) +{ + resp_len = 0; + resp_pos = 0; + if (n < 4) { + return; + } + unsigned char id = req[0]; + unsigned char cmd = req[1]; + unsigned char len = req[2]; + int value = 0; + int vbytes = 0; + if (len == 0x11) { + vbytes = 1; + } else if (len == 0x12) { + vbytes = 2; + } else if (len == 0x14) { + vbytes = 4; + } + if (id == 11 && cmd == 20) { + value = 64; // homing offset already configured + } else if (id == 15 && cmd == 11) { + value = 5; // current-based position control mode + } else if (cmd == 132) { + value = 2048 + 100 * (int)(id - 11); // present position + } else if (cmd == 128 || cmd == 70) { + value = 0; // present velocity / hardware error status + } + resp[0] = 1; // status ok + resp[1] = id; + for (int i = 0; i < vbytes; i++) { + resp[2 + i] = (value >> (8 * i)) & 0xff; + } + resp_len = 2 + vbytes + 1; // + one extra byte (USI slave quirk) + if (resp_len < 3) { + resp_len = 3; // write commands: status, id, extra + } +} + +static int my_open(const char *path, int flags, mode_t mode, int (*real)(const char *, int, ...)) +{ + if (path && strcmp(path, "/dev/i2c-7") == 0) { + int fd = real("/dev/null", O_RDWR, 0); + if (fd >= 0) { + cur_fd = fd; + } + return fd; + } + return real(path, flags, mode); +} + +int open(const char *path, int flags, ...) +{ + if (!real_open) { + real_open = (int (*)(const char *, int, ...))dlsym(RTLD_NEXT, "open"); + } + mode_t mode = 0; + va_list ap; + va_start(ap, flags); + mode = (mode_t)va_arg(ap, int); + va_end(ap); + return my_open(path, flags, mode, real_open); +} + +int open64(const char *path, int flags, ...) +{ + if (!real_open) { + real_open = (int (*)(const char *, int, ...))dlsym(RTLD_NEXT, "open"); + } + mode_t mode = 0; + va_list ap; + va_start(ap, flags); + mode = (mode_t)va_arg(ap, int); + va_end(ap); + return my_open(path, flags, mode, real_open); +} + +int close(int fd) +{ + if (!real_close) { + real_close = (int (*)(int))dlsym(RTLD_NEXT, "close"); + } + if (fd == cur_fd) { + cur_fd = -1; + } + return real_close(fd); +} + +int ioctl(int fd, unsigned long request, ...) +{ + if (!real_ioctl) { + real_ioctl = (int (*)(int, unsigned long, ...))dlsym(RTLD_NEXT, "ioctl"); + } + va_list ap; + va_start(ap, request); + void *arg = va_arg(ap, void *); + va_end(ap); + if (fd == cur_fd) { + return 0; + } + return real_ioctl(fd, request, arg); +} + +ssize_t write(int fd, const void *buf, size_t n) +{ + if (!real_write) { + real_write = (ssize_t (*)(int, const void *, size_t))dlsym(RTLD_NEXT, "write"); + } + if (fd == cur_fd) { + const unsigned char *req = (const unsigned char *)buf; + if (n >= 8) { + int v = ((int)req[3] << 24) | ((int)req[4] << 16) | ((int)req[5] << 8) | (int)req[6]; + fprintf(stderr, "[fake_i2c] write id=%d cmd=%d value=%d\n", req[0], req[1], v); + } else if (n >= 5) { + fprintf(stderr, "[fake_i2c] write id=%d cmd=%d\n", req[0], req[1]); + } + prep(req, n); + return (ssize_t)n; + } + return real_write(fd, buf, n); +} + +ssize_t read(int fd, void *buf, size_t n) +{ + if (!real_read) { + real_read = (ssize_t (*)(int, void *, size_t))dlsym(RTLD_NEXT, "read"); + } + if (fd == cur_fd) { + int c = resp_pos < resp_len ? resp_len - resp_pos : 0; + if (c > (int)n) { + c = (int)n; + } + if (c > 0) { + memcpy(buf, resp + resp_pos, (size_t)c); + } + resp_pos += c; + return c; + } + return real_read(fd, buf, n); +} diff --git a/tools/smoke_test.sh b/tools/smoke_test.sh new file mode 100755 index 0000000..324d329 --- /dev/null +++ b/tools/smoke_test.sh @@ -0,0 +1,150 @@ +#!/bin/bash +# No-hardware smoke test for a4wd3_open_manipulator. +# +# Emulates the I2C Dynamixel bus with an LD_PRELOAD shim (tools/fake_i2c.c), +# so the ros2_control hardware plugin configures/activates as if real motors +# were present. Verifies: plugin load, configure/activate, all 3 controllers, +# /joint_states, trajectory flow through the JTC to the (fake) motors, the +# safety guard that rejects uninitialized commands, and the two services. +# +# Prerequisites: ROS 2 Jazzy, package built (colcon build --packages-select +# a4wd3_open_manipulator), gcc. +# +# Usage: bash tools/smoke_test.sh [workspace_root] +# workspace_root defaults to /root/ros2_ws + +# NOTE: `set -u` is intentionally NOT used: sourcing the ROS setup.bash +# references AMENT_TRACE_SETUP_FILES without a default and aborts under nounset. +WS="${1:-/root/ros2_ws}" +PKG="a4wd3_open_manipulator" +SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" +WORK="$(mktemp -d /tmp/wt_smoke.XXXXXX)" +FAIL=0 +RSP_PID="" +CM_PID="" + +cleanup() { + [ -n "$RSP_PID" ] && kill "$RSP_PID" 2>/dev/null + [ -n "$CM_PID" ] && kill "$CM_PID" 2>/dev/null + wait 2>/dev/null + return 0 +} +trap cleanup EXIT + +pass() { echo "PASS: $1"; } +fail() { echo "FAIL: $1"; FAIL=1; } + +source /opt/ros/jazzy/setup.bash +source "$WS/install/setup.bash" + +CFG="$WS/install/$PKG/share/$PKG/config/a4wd3_open_manipulator_controllers.yaml" +if [ ! -f "$CFG" ]; then + echo "ERROR: $PKG not built/installed. Run: cd $WS && colcon build --packages-select $PKG" + exit 1 +fi + +echo "== [1/7] building fake I2C shim ==" +gcc -shared -fPIC -o "$WORK/libfake_i2c.so" "$SCRIPT_DIR/fake_i2c.c" -ldl \ + || { echo "shim build failed"; exit 1; } + +echo "== [2/7] processing xacro ==" +"$(ros2 pkg prefix xacro)/lib/xacro/xacro" \ + "$WS/install/$PKG/share/$PKG/urdf/open_manipulator.urdf.xacro" \ + > "$WORK/processed.urdf" 2> "$WORK/xacro.log" \ + || { echo "xacro failed:"; cat "$WORK/xacro.log"; exit 1; } + +echo "== [3/7] starting robot_state_publisher + ros2_control_node (fake I2C) ==" +pkill -9 -f "lib/controller_manager/ros2_control_node" 2>/dev/null +pkill -9 -f "lib/robot_state_publisher/robot_state_publisher" 2>/dev/null +sleep 1 +"$(ros2 pkg prefix robot_state_publisher)/lib/robot_state_publisher/robot_state_publisher" \ + --ros-args -p robot_description:="$(cat "$WORK/processed.urdf")" \ + > "$WORK/rsp.log" 2>&1 & +RSP_PID=$! +sleep 2 +LD_PRELOAD="$WORK/libfake_i2c.so" \ + "$(ros2 pkg prefix controller_manager)/lib/controller_manager/ros2_control_node" \ + --ros-args --params-file "$CFG" > "$WORK/cm.log" 2>&1 & +CM_PID=$! +sleep 5 + +grep -q "Configuration successful" "$WORK/cm.log" && pass "hardware configure" || { fail "hardware configure"; echo "--- cm.log tail ---"; tail -5 "$WORK/cm.log"; } +grep -q "Activation successful" "$WORK/cm.log" && pass "hardware activate" || { fail "hardware activate"; tail -5 "$WORK/cm.log"; } + +echo "== [4/7] spawning controllers ==" +SPAWNER="$(ros2 pkg prefix controller_manager)/lib/controller_manager/spawner" +for c in joint_state_broadcaster arm_controller gripper_controller; do + OUT="$(timeout 25 "$SPAWNER" "$c" --param-file "$CFG" 2>&1)" + echo "$OUT" | grep -q "Configured and activated" \ + && pass "spawner $c" \ + || { fail "spawner $c"; echo "$OUT" | head -3; } +done + +echo "== [5/7] checking /joint_states + pre-trajectory safety guard ==" +sleep 2 +# first line of the echo is the name list ('---' and any repeats are ignored) +JSNAMES="$(timeout 5 ros2 topic echo /joint_states --once --field name 2>/dev/null | head -1)" +JS_OK=1 +for n in gripper joint1 joint2 joint3 joint4; do + echo "$JSNAMES" | grep -q "$n" || JS_OK=0 +done +[ "$JS_OK" -eq 1 ] && pass "/joint_states has all 5 joints" || fail "/joint_states (got: ${JSNAMES:-})" + +PRE="$(grep -c "cmd=116" "$WORK/cm.log" || true)" +[ "${PRE:-0}" -eq 0 ] \ + && pass "no goal-position writes before trajectory (garbage commands rejected)" \ + || fail "unexpected goal writes before trajectory ($PRE)" + +echo "== [6/7] sending arm trajectory (0.5/0.3 rad on joint1/joint2, 3 s) ==" +timeout 10 ros2 topic pub --once /arm_controller/joint_trajectory trajectory_msgs/msg/JointTrajectory "header: + frame_id: '' +joint_names: ['joint1', 'joint2', 'joint3', 'joint4'] +points: + - + positions: [0.5, 0.3, 0.0, 0.0] + time_from_start: + sec: 3 + nanosec: 0" > /dev/null 2>&1 +sleep 5 +# expected steps = 2048 + rad * 4096/(2*pi): j1 2373, j2 2243, j3/j4 2048 +last() { grep "id=$1 cmd=116" "$WORK/cm.log" | sed 's/.*value=//' | tail -1; } +for pair in "11:2373:joint1" "12:2243:joint2" "13:2048:joint3" "14:2048:joint4"; do + id="${pair%%:*}"; rest="${pair#*:}"; want="${rest%%:*}"; name="${rest#*:}" + got="$(last "$id")" + [ "$got" = "$want" ] && pass "$name reached goal steps ($want)" || fail "$name last write=${got:-none} (want $want)" +done + +echo "== [7/7] gripper action + services ==" +# parallel_gripper_action_controller uses control_msgs/action/ParallelGripperCommand; +# goal = {command: sensor_msgs/JointState{name, position, ...}} +# NOTE: the fake motor never actually moves (fixed present position), so the action +# result will not reach SUCCEEDED. Assert goal acceptance + the goal write below. +AOUT="$(timeout 20 ros2 action send_goal /gripper_controller/gripper_cmd control_msgs/action/ParallelGripperCommand \ + "{command: {name: ['gripper'], position: [0.01]}}" --timeout 8 2>&1)" +if echo "$AOUT" | grep -q "Sending goal" && ! echo "$AOUT" | grep -q "REJECTED"; then + pass "gripper goal accepted by action server" +else + fail "gripper goal (rejected or no server)"; echo "$AOUT" | head -5 +fi +LAST15="$(last 15)" +if [ -n "$LAST15" ] && [ "$LAST15" -ge 1611 ] && [ "$LAST15" -le 1615 ]; then + pass "gripper goal steps written to fake motor ($LAST15, want ~1613)" +else + fail "gripper last write=${LAST15:-none} (want ~1613)" +fi + +SOUT="$(timeout 8 ros2 service call /torque_enable std_srvs/srv/SetBool "{data: true}" 2>&1)" +echo "$SOUT" | grep -q "success=True" && pass "torque_enable service" || { fail "torque_enable service"; echo "$SOUT" | head -3; } +GOUT="$(timeout 8 ros2 service call /get_error "$PKG/srv/GetError" "{}" 2>&1)" +echo "$GOUT" | grep -q "id=15" && pass "get_error service" || { fail "get_error service"; echo "$GOUT" | head -3; } + +echo "" +echo "======================================" +if [ "$FAIL" -eq 0 ]; then + echo "SMOKE TEST: ALL PASSED" +else + echo "SMOKE TEST: FAILURES DETECTED (see FAIL lines above)" +fi +echo "Logs kept in: $WORK" +echo "======================================" +exit "$FAIL" diff --git a/urdf/open_manipulator.ros2_control.xacro b/urdf/open_manipulator.ros2_control.xacro new file mode 100644 index 0000000..0150edd --- /dev/null +++ b/urdf/open_manipulator.ros2_control.xacro @@ -0,0 +1,52 @@ + + + + + + + + + + a4wd3_open_manipulator/A4wd3OpenManipulatorI2C + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/urdf/open_manipulator.urdf b/urdf/open_manipulator.urdf index 9461acf..58a3a8f 100644 --- a/urdf/open_manipulator.urdf +++ b/urdf/open_manipulator.urdf @@ -1,6 +1,6 @@ - + diff --git a/urdf/open_manipulator.urdf.xacro b/urdf/open_manipulator.urdf.xacro index bbc923d..f2745ee 100644 --- a/urdf/open_manipulator.urdf.xacro +++ b/urdf/open_manipulator.urdf.xacro @@ -2,11 +2,16 @@ - - - - + + + + + + + + + @@ -36,7 +41,7 @@ - + @@ -44,7 +49,7 @@ - + @@ -81,14 +86,14 @@ - + - + @@ -126,7 +131,7 @@ - + @@ -134,7 +139,7 @@ - + @@ -172,7 +177,7 @@ - + @@ -180,7 +185,7 @@ - + @@ -218,7 +223,7 @@ - + @@ -226,7 +231,7 @@ - + @@ -252,7 +257,7 @@ - + @@ -260,7 +265,7 @@ - + @@ -298,7 +303,7 @@ - + @@ -306,7 +311,7 @@ - + @@ -367,4 +372,7 @@ + + + diff --git a/urdf/wild_thumper_with_manipulator.urdf.xacro b/urdf/wild_thumper_with_manipulator.urdf.xacro deleted file mode 100644 index 1451f50..0000000 --- a/urdf/wild_thumper_with_manipulator.urdf.xacro +++ /dev/null @@ -1,12 +0,0 @@ - - - - - - - - - - - - -- 2.39.5