TechTheTime-HighLevel 0.0.1
The high level robot's code using ros2-foxy for the robotics competition(Erobot-2022)
ClientT.hpp
Go to the documentation of this file.
1#ifndef CLIENT_CLASS_HPP
2#define CLIENT_CLASS_HPP
3
4#include "rclcpp/rclcpp.hpp"
5
6#include <chrono>
7#include <cstdlib>
8#include <memory>
9#include <string>
10#include "struct_wrapper.hpp"
11#include <stdexcept>
12
13using namespace std::chrono_literals;
14
22template<class T, class Treq, class... Rs>
23class ClientT : public rclcpp::Node {
24
25public:
26
27 using shared_ptr_T = typename rclcpp::Client<T>::SharedPtr;
28 using shared_future_T = typename rclcpp::Client<T>::SharedFuture;
29
30 ClientT(const std::string& client_name) : Node(client_name) {
31 this->client_name = client_name;
32 this->client = this->create_client<T>(client_name);
33 }
34
35 void set_shared(std::shared_ptr<ClientT<T, Treq, Rs...>> ptr) {
36 this->self_ptr = ptr;
37 }
38
40 while (!client->wait_for_service(1s)) {
41 if (!rclcpp::ok()) {
42 RCLCPP_ERROR(rclcpp::get_logger("rclcpp"), "Interrupted while waiting for the service. Exiting...");
43 exit(1);
44 }
45 RCLCPP_INFO(rclcpp::get_logger("rclcpp"), this->client_name + " client is waiting for service...");
46 }
47 }
48
49 auto send(Rs... args) {
50 request.set_values(args...);
51 auto result = client->async_send_request(request.value);
52 if (rclcpp::spin_until_future_complete(this->self_ptr, result) ==
53 rclcpp::FutureReturnCode::SUCCESS)
54 {
55 return result;
56 } else {
57 RCLCPP_ERROR(rclcpp::get_logger("rclcpp"), "Failed to call service");
58 throw std::runtime_error("Failed to call service");
59 }
60 }
61
62private:
63 std::shared_ptr<ClientT<T, Treq, Rs...>> self_ptr;
64 std::string client_name;
66 struct_wrapper<Treq, Rs...> request;
67};
68
71#endif
ClientT class.
Definition: ClientT.hpp:23
std::shared_ptr< ClientT< T, Treq, Rs... > > self_ptr
Definition: ClientT.hpp:63
ClientT(const std::string &client_name)
Definition: ClientT.hpp:30
std::string client_name
Definition: ClientT.hpp:64
void wait_for_connection()
Definition: ClientT.hpp:39
struct_wrapper< Treq, Rs... > request
Definition: ClientT.hpp:66
auto send(Rs... args)
Definition: ClientT.hpp:49
typename rclcpp::Client< T >::SharedFuture shared_future_T
Definition: ClientT.hpp:28
typename rclcpp::Client< T >::SharedPtr shared_ptr_T
Definition: ClientT.hpp:27
shared_ptr_T client
Definition: ClientT.hpp:65
void set_shared(std::shared_ptr< ClientT< T, Treq, Rs... > > ptr)
Definition: ClientT.hpp:35
Definition: struct_wrapper.hpp:5
void set_values(Ts... args)
Definition: struct_wrapper.hpp:14
std::shared_ptr< T > value
Definition: struct_wrapper.hpp:8