Skip to content

Commit 9607c69

Browse files
committed
Keep headless tests compatible with ROS 2 Humble
Signed-off-by: Lionel Gulich <lgulich@nvidia.com>
1 parent 894af33 commit 9607c69

4 files changed

Lines changed: 232 additions & 16 deletions

File tree

‎mujoco_ros2_control/include/mujoco_ros2_control/mujoco_system_interface.hpp‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -30,11 +30,11 @@
3030
#include <vector>
3131

3232
#include <hardware_interface/version.h>
33+
#include <geometry_msgs/msg/transform_stamped.hpp>
3334
#include <hardware_interface/handle.hpp>
3435
#include <hardware_interface/hardware_info.hpp>
3536
#include <hardware_interface/system_interface.hpp>
3637
#include <hardware_interface/types/hardware_interface_return_values.hpp>
37-
#include <geometry_msgs/msg/transform_stamped.hpp>
3838
#include <nav_msgs/msg/odometry.hpp>
3939
#include <rclcpp/macros.hpp>
4040
#include <rclcpp/rclcpp.hpp>

‎mujoco_ros2_control/src/mujoco_simulation.cpp‎

Lines changed: 6 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -597,9 +597,10 @@ bool MujocoSimulation::initialize(rclcpp::Node::SharedPtr node, const std::strin
597597
{
598598
// Launch the UI loop in the background
599599
ui_thread_ = std::thread([this, sim_ready]() {
600-
sim_ = std::make_unique<mj::Simulate>(std::make_unique<ROS2ControlGlfwAdapter>(keyboard_step_requested_, key_callback_mutex_, key_callback_), &cam_,
601-
&opt_, &pert_,
602-
/* is_passive = */ false);
600+
sim_ = std::make_unique<mj::Simulate>(
601+
std::make_unique<ROS2ControlGlfwAdapter>(keyboard_step_requested_, key_callback_mutex_, key_callback_), &cam_,
602+
&opt_, &pert_,
603+
/* is_passive = */ false);
603604

604605
// Add ros2 control icon for the taskbar
605606
#if AMENT_INDEX_CPP_VERSION_GTE(1, 13, 2)
@@ -813,8 +814,8 @@ void MujocoSimulation::configure_lockstep(bool enabled)
813814
}
814815
}
815816

816-
MujocoSimulation::SimulationStepResult MujocoSimulation::request_simulation_steps(
817-
uint32_t steps, std::chrono::milliseconds timeout)
817+
MujocoSimulation::SimulationStepResult MujocoSimulation::request_simulation_steps(uint32_t steps,
818+
std::chrono::milliseconds timeout)
818819
{
819820
std::lock_guard<std::mutex> request_lock(step_request_mutex_);
820821
if (steps == 0)

‎mujoco_ros2_control/src/mujoco_system_interface.cpp‎

Lines changed: 9 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -26,6 +26,7 @@
2626
#include <fmt/compile.h>
2727
#include <fmt/ranges.h>
2828

29+
#include <unistd.h>
2930
#include <chrono>
3031
#include <cmath>
3132
#include <cstdint>
@@ -40,7 +41,6 @@
4041
#include <stdexcept>
4142
#include <string>
4243
#include <thread>
43-
#include <unistd.h>
4444

4545
#include <tinyxml2.h>
4646
#include <unordered_map>
@@ -406,11 +406,11 @@ MujocoSystemInterface::on_init(const hardware_interface::HardwareComponentInterf
406406
#endif
407407
}
408408

409-
const double lockstep_period =
410-
static_cast<double>(lockstep_steps_per_update_) * simulation_->model()->opt.timestep;
411-
RCLCPP_INFO(get_logger(),
412-
"MuJoCo lockstep uses %u physics step(s) per ros2_control update: timestep %.6f s, effective period %.6f s",
413-
lockstep_steps_per_update_, simulation_->model()->opt.timestep, lockstep_period);
409+
const double lockstep_period = static_cast<double>(lockstep_steps_per_update_) * simulation_->model()->opt.timestep;
410+
RCLCPP_INFO(
411+
get_logger(),
412+
"MuJoCo lockstep uses %u physics step(s) per ros2_control update: timestep %.6f s, effective period %.6f s",
413+
lockstep_steps_per_update_, simulation_->model()->opt.timestep, lockstep_period);
414414
#if !ROS_DISTRO_HUMBLE
415415
const double controller_period = 1.0 / static_cast<double>(get_hardware_info().rw_rate);
416416
RCLCPP_WARN_EXPRESSION(get_logger(), std::abs(lockstep_period - controller_period) > 1e-9,
@@ -1125,8 +1125,7 @@ hardware_interface::return_type MujocoSystemInterface::write(const rclcpp::Time&
11251125
std::isnan(actuator.effort_interface.command_) ? 0.0 : actuator.effort_interface.command_;
11261126
const double velocity_command =
11271127
std::isnan(actuator.velocity_interface.command_) ? 0.0 : actuator.velocity_interface.command_;
1128-
const double position_error =
1129-
actuator.position_interface.command_ - control_state_.qpos[actuator.mj_pos_adr];
1128+
const double position_error = actuator.position_interface.command_ - control_state_.qpos[actuator.mj_pos_adr];
11301129
const double velocity_error = velocity_command - control_state_.qvel[actuator.mj_vel_adr];
11311130
control_data->ctrl[actuator.mj_actuator_id] = effort_ff + kp * position_error + kd * velocity_error;
11321131
}
@@ -1169,8 +1168,8 @@ hardware_interface::return_type MujocoSystemInterface::write(const rclcpp::Time&
11691168

11701169
if (lockstep_)
11711170
{
1172-
const auto timeout = std::chrono::milliseconds(
1173-
std::max<uint64_t>(1000, static_cast<uint64_t>(lockstep_steps_per_update_) * 100));
1171+
const auto timeout =
1172+
std::chrono::milliseconds(std::max<uint64_t>(1000, static_cast<uint64_t>(lockstep_steps_per_update_) * 100));
11741173
const auto result = simulation_->request_simulation_steps(lockstep_steps_per_update_, timeout);
11751174
if (result != MujocoSimulation::SimulationStepResult::Completed)
11761175
{

‎mujoco_ros2_control/tests/test_headless_init.cpp‎

Lines changed: 216 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -131,6 +131,60 @@ class HeadlessInitTest : public ::testing::Test
131131
return info;
132132
}
133133

134+
hardware_interface::HardwareInfo create_impedance_hardware_info()
135+
{
136+
std::ofstream file(test_model_path_);
137+
file << R"(<?xml version="1.0"?>
138+
<mujoco model="test_impedance_control">
139+
<option timestep="0.002" gravity="0 0 0"/>
140+
<worldbody>
141+
<body name="link" pos="0 0 0">
142+
<joint name="hinge" type="hinge" axis="0 1 0"/>
143+
<geom type="capsule" size="0.02" fromto="0 0 0 0.3 0 0" mass="1"/>
144+
</body>
145+
</worldbody>
146+
<actuator>
147+
<motor name="hinge" joint="hinge"/>
148+
</actuator>
149+
</mujoco>
150+
)";
151+
file.close();
152+
153+
hardware_interface::HardwareInfo info;
154+
info.name = "test_mujoco_impedance";
155+
info.type = "system";
156+
#if !ROS_DISTRO_HUMBLE
157+
info.rw_rate = 100;
158+
#endif
159+
info.hardware_parameters["mujoco_model"] = test_model_path_;
160+
info.hardware_parameters["headless"] = "true";
161+
162+
hardware_interface::ComponentInfo joint;
163+
joint.name = "hinge";
164+
joint.type = "joint";
165+
const auto make_interface = [](const std::string& name) {
166+
hardware_interface::InterfaceInfo interface;
167+
interface.name = name;
168+
interface.size = 1;
169+
#if !ROS_DISTRO_HUMBLE
170+
interface.enable_limits = false;
171+
#endif
172+
return interface;
173+
};
174+
joint.state_interfaces = {
175+
make_interface(hardware_interface::HW_IF_POSITION),
176+
make_interface(hardware_interface::HW_IF_VELOCITY),
177+
make_interface(hardware_interface::HW_IF_EFFORT),
178+
};
179+
joint.command_interfaces = {
180+
make_interface(hardware_interface::HW_IF_POSITION), make_interface(hardware_interface::HW_IF_VELOCITY),
181+
make_interface(hardware_interface::HW_IF_EFFORT), make_interface(mujoco_ros2_control::HW_IF_KP),
182+
make_interface(mujoco_ros2_control::HW_IF_KD),
183+
};
184+
info.joints.push_back(joint);
185+
return info;
186+
}
187+
134188
std::string test_model_path_;
135189
hardware_interface::HardwareInfo hardware_info_;
136190
std::shared_ptr<mujoco_ros2_control::MujocoSystemInterface> interface_;
@@ -258,6 +312,168 @@ TEST_F(HeadlessInitTest, SpeedFactorParamInitialization)
258312
EXPECT_GT(test_data->time, 0.0) << "Simulation time did not advance with sim_speed_factor=0.5";
259313
}
260314

315+
TEST_F(HeadlessInitTest, ImpedanceInterfacesDriveMotorControl)
316+
{
317+
const auto info = create_impedance_hardware_info();
318+
#if ROS_DISTRO_HUMBLE
319+
const auto init_result = interface_->on_init(info);
320+
#else
321+
hardware_interface::HardwareComponentInterfaceParams params;
322+
params.hardware_info = info;
323+
const auto init_result = interface_->on_init(params);
324+
#endif
325+
ASSERT_EQ(init_result, hardware_interface::CallbackReturn::SUCCESS);
326+
327+
auto command_interfaces = interface_->export_command_interfaces();
328+
auto state_interfaces = interface_->export_state_interfaces();
329+
const auto find_command = [&command_interfaces](const std::string& name) -> hardware_interface::CommandInterface& {
330+
auto it = std::find_if(command_interfaces.begin(), command_interfaces.end(),
331+
[&name](const auto& interface) { return interface.get_name() == name; });
332+
if (it == command_interfaces.end())
333+
{
334+
throw std::runtime_error("Missing command interface: " + name);
335+
}
336+
return *it;
337+
};
338+
const auto find_state = [&state_interfaces](const std::string& name) -> hardware_interface::StateInterface& {
339+
auto it = std::find_if(state_interfaces.begin(), state_interfaces.end(),
340+
[&name](const auto& interface) { return interface.get_name() == name; });
341+
if (it == state_interfaces.end())
342+
{
343+
throw std::runtime_error("Missing state interface: " + name);
344+
}
345+
return *it;
346+
};
347+
348+
ASSERT_EQ(interface_->read(rclcpp::Time(0), rclcpp::Duration::from_seconds(0.01)),
349+
hardware_interface::return_type::OK);
350+
double position_state;
351+
double velocity_state;
352+
#if ROS_DISTRO_HUMBLE
353+
position_state = find_state("hinge/position").get_value();
354+
velocity_state = find_state("hinge/velocity").get_value();
355+
#else
356+
const auto position_state_optional = find_state("hinge/position").get_optional<double>();
357+
const auto velocity_state_optional = find_state("hinge/velocity").get_optional<double>();
358+
ASSERT_TRUE(position_state_optional.has_value());
359+
ASSERT_TRUE(velocity_state_optional.has_value());
360+
position_state = *position_state_optional;
361+
velocity_state = *velocity_state_optional;
362+
#endif
363+
364+
#if ROS_DISTRO_HUMBLE
365+
find_command("hinge/position").set_value(0.5);
366+
find_command("hinge/velocity").set_value(0.25);
367+
find_command("hinge/effort").set_value(0.1);
368+
find_command("hinge/kp").set_value(20.0);
369+
find_command("hinge/kd").set_value(4.0);
370+
#else
371+
ASSERT_TRUE(find_command("hinge/position").set_value(0.5));
372+
ASSERT_TRUE(find_command("hinge/velocity").set_value(0.25));
373+
ASSERT_TRUE(find_command("hinge/effort").set_value(0.1));
374+
ASSERT_TRUE(find_command("hinge/kp").set_value(20.0));
375+
ASSERT_TRUE(find_command("hinge/kd").set_value(4.0));
376+
#endif
377+
378+
ASSERT_EQ(interface_->perform_command_mode_switch(
379+
{ "hinge/position", "hinge/velocity", "hinge/effort", "hinge/kp", "hinge/kd" }, {}),
380+
hardware_interface::return_type::OK);
381+
ASSERT_EQ(interface_->write(rclcpp::Time(0), rclcpp::Duration::from_seconds(0.01)),
382+
hardware_interface::return_type::OK);
383+
384+
const double expected_effort = 0.1 + 20.0 * (0.5 - position_state) + 4.0 * (0.25 - velocity_state);
385+
double observed_effort = 0.0;
386+
for (size_t attempt = 0; attempt < 1000; ++attempt)
387+
{
388+
mjData* data = nullptr;
389+
interface_->get_data(data);
390+
ASSERT_NE(data, nullptr);
391+
observed_effort = data->ctrl[0];
392+
mj_deleteData(data);
393+
if (std::abs(observed_effort - expected_effort) <= 1e-9)
394+
{
395+
break;
396+
}
397+
std::this_thread::sleep_for(std::chrono::milliseconds(1));
398+
}
399+
EXPECT_NEAR(observed_effort, expected_effort, 1e-9);
400+
}
401+
402+
TEST_F(HeadlessInitTest, LockstepWriteAdvancesConfiguredStepCount)
403+
{
404+
auto info = create_hardware_info();
405+
info.hardware_parameters["lockstep"] = "true";
406+
info.hardware_parameters["lockstep_steps_per_update"] = "2";
407+
#if ROS_DISTRO_HUMBLE
408+
const auto init_result = interface_->on_init(info);
409+
#else
410+
hardware_interface::HardwareComponentInterfaceParams params;
411+
params.hardware_info = info;
412+
const auto init_result = interface_->on_init(params);
413+
#endif
414+
ASSERT_EQ(init_result, hardware_interface::CallbackReturn::SUCCESS);
415+
416+
std::this_thread::sleep_for(std::chrono::milliseconds(50));
417+
mjData* before = nullptr;
418+
mjModel* model = nullptr;
419+
interface_->get_data(before);
420+
interface_->get_model(model);
421+
ASSERT_NE(before, nullptr);
422+
ASSERT_NE(model, nullptr);
423+
const double start_time = before->time;
424+
425+
ASSERT_EQ(interface_->write(rclcpp::Time(0), rclcpp::Duration::from_seconds(0.01)),
426+
hardware_interface::return_type::OK);
427+
428+
mjData* after = nullptr;
429+
interface_->get_data(after);
430+
ASSERT_NE(after, nullptr);
431+
EXPECT_NEAR(after->time, start_time + 2 * model->opt.timestep, 1e-9);
432+
mj_deleteData(before);
433+
mj_deleteData(after);
434+
mj_deleteModel(model);
435+
}
436+
437+
TEST_F(HeadlessInitTest, FloatingBasePublishesConfiguredTransform)
438+
{
439+
auto info = create_hardware_info();
440+
info.hardware_parameters["odom_free_joint_name"] = "box1_joint";
441+
info.hardware_parameters["odom_frame"] = "world";
442+
info.hardware_parameters["publish_floating_base_tf"] = "true";
443+
#if ROS_DISTRO_HUMBLE
444+
const auto init_result = interface_->on_init(info);
445+
#else
446+
hardware_interface::HardwareComponentInterfaceParams params;
447+
params.hardware_info = info;
448+
const auto init_result = interface_->on_init(params);
449+
#endif
450+
ASSERT_EQ(init_result, hardware_interface::CallbackReturn::SUCCESS);
451+
452+
auto listener = rclcpp::Node::make_shared("floating_base_tf_test_listener");
453+
std::atomic<bool> received{ false };
454+
auto subscription = listener->create_subscription<tf2_msgs::msg::TFMessage>(
455+
"/tf", 10, [&received](const tf2_msgs::msg::TFMessage& message) {
456+
for (const auto& transform : message.transforms)
457+
{
458+
if (transform.header.frame_id == "world" && transform.child_frame_id == "box1")
459+
{
460+
received.store(true);
461+
}
462+
}
463+
});
464+
465+
const auto deadline = std::chrono::steady_clock::now() + std::chrono::seconds(1);
466+
while (!received.load() && std::chrono::steady_clock::now() < deadline)
467+
{
468+
ASSERT_EQ(interface_->read(rclcpp::Time(0), rclcpp::Duration::from_seconds(0.01)),
469+
hardware_interface::return_type::OK);
470+
rclcpp::spin_some(listener);
471+
std::this_thread::sleep_for(std::chrono::milliseconds(10));
472+
}
473+
EXPECT_TRUE(received.load());
474+
(void)subscription;
475+
}
476+
261477
TEST(SimDisplayTextTest, ComposesAllRowsWhenRunning)
262478
{
263479
const auto [title, content] = mujoco_ros2_control::compose_sim_display_text(

0 commit comments

Comments
 (0)