Client doesn't return when you create a client class ROS2
Hi community, I would like to write a client and server node using classes. I started writing the client in a class "form" using the tutorial in the documentation and I used the same messages and the same identical code for the server node. I wanted to create a client class which is querying each 500ms the same msg to the server. Searching on the ROS Answer I found a similar question. And using a solution like that I got that the client now is stuck in a deadlock or similar because send the first request but later no and the code continue to run.
The client that I had written is this:
#include "rclcpp/rclcpp.hpp"
#include "example_interfaces/srv/add_two_ints.hpp"
#include <chrono>
#include <cstdlib>
#include <memory>
#include <functional>
using namespace std::chrono_literals;
class client_foo : public rclcpp::Node
{
public:
client_foo(const std::string &node_name) : rclcpp::Node(node_name)
{
client_ = this->create_client<example_interfaces::srv::AddTwoInts>("servizio", rmw_qos_profile_services_default);
cb_grp_client_ = this->create_callback_group(rclcpp::callback_group::CallbackGroupType::MutuallyExclusive);
while (!client_->wait_for_service(1s))
{
if (!rclcpp::ok())
{
RCLCPP_ERROR(get_logger(), "Errore mentre aspetto");
exit(1);
}
RCLCPP_INFO(get_logger(), "Servizio non disponibile aspetta...");
}
timer_cb_ = create_wall_timer(500ms, std::bind(&client_foo::start, this));
}
private:
rclcpp::Client<example_interfaces::srv::AddTwoInts>::SharedPtr client_;
rclcpp::callback_group::CallbackGroup::SharedPtr cb_grp_client_;
// Timer per il callback
rclcpp::TimerBase::SharedPtr timer_cb_;
example_interfaces::srv::AddTwoInts::Response::SharedPtr start()
{
auto request = std::make_shared<example_interfaces::srv::AddTwoInts::Request>();
request->a = 1;
request->b = 2;
auto result = client_->async_send_request(request);
result.wait();
RCLCPP_INFO(get_logger(), "Results!");
return result.get();
}
};
int main(int argc, char *argv[])
{
rclcpp::init(argc, argv);
rclcpp::executors::MultiThreadedExecutor exe;
std::shared_ptr<client_foo> client_node =
std::make_shared<client_foo>("client_foo");
exe.add_node(client_node);
exe.spin();
return 0;
}
Probably the question is very silly but I don't get the point where the code fails. Someone can help me?
Thank you so much.