runtime error after trying to set parameters in ROS2
When I try to set parameters, I'm getting the following error:
terminate called after throwing an instance of 'std::runtime_error'
what(): Node has already been added to an executor.
I was able to get around this problem by creating another node within my constructor. I'm wondering if there is a better way to get around this problem. Please look at the code snippet below. Thanks.
main.cpp
int main(int argc, char **argv)
{
rclcpp::init(argc, argv);
rclcpp::spin(std::make_shared<TestParameter>());
rclcpp::shutdown();
return 0;
}
test_parameter.hpp
class TestParameter : public rclcpp::Node
{
public:
TestParameter();
~TestParameter();
void subCB();
void saveParamToServer();
private:
rclcpp::SyncParametersClient::SharedPtr parameters_client_;
rclcpp::Subscription<geometry_msgs::msg::PoseWithCovarianceStamped>::ConstSharedPtr test_sub_;
};
test_parameter.cpp
TestParameter::TestParameter()
: Node("TestParameter")
{
parameters_client_ = std::make_shared<rclcpp::SyncParametersClient>(std::shared_ptr<rclcpp::Node>(this));
test_sub_ = this->create_subscription<geometry_msgs::msg::PoseWithCovarianceStamped>(
"testsub", std::bind(&TestParameter::initialPoseReceived, this, std::placeholders::_1));
}
TestParameter::~TestParameter()
{
}
void TestParameter::subCB()
{
this->saveParamToServer();
}
void TestParameter::saveParamToServer()
{
parameters_client_->set_parameters({
rclcpp::Parameter("x", 0),
rclcpp::Parameter("y", 0),
});
}
To fix this issue, I created another node for parameters within my constructor.
test_node = rclcpp::Node::make_shared("TestNode");
parameters_client_ = std::make_shared<rclcpp::SyncParametersClient>(std::shared_ptr<rclcpp::Node>(test_node));