2424#include < endian.h>
2525#include < netinet/tcp.h>
2626#include < unistd.h>
27+ #include < chrono>
2728#include < cstring>
2829#include < sstream>
2930#include < thread>
@@ -55,8 +56,19 @@ void TCPSocket::setupOptions()
5556 }
5657}
5758
58- bool TCPSocket::setup (std::string& host, int port)
59+ bool TCPSocket::setup (const std::string& host, const int port, const size_t max_num_tries,
60+ const std::chrono::milliseconds reconnection_time)
5961{
62+ // This can be removed once we remove the setReconnectionTime() method
63+ auto reconnection_time_resolved = reconnection_time;
64+ if (reconnection_time_modified_deprecated_)
65+ {
66+ URCL_LOG_WARN (" TCPSocket::setup(): Reconnection time was modified using `setReconnectionTime()` which is "
67+ " deprecated. Please change your code to set reconnection_time through the `setup()` method "
68+ " directly. The value passed to this function will be ignored." );
69+ reconnection_time_resolved = reconnection_time_;
70+ }
71+
6072 if (state_ == SocketState::Connected)
6173 return false ;
6274
@@ -74,6 +86,7 @@ bool TCPSocket::setup(std::string& host, int port)
7486 hints.ai_socktype = SOCK_STREAM;
7587 hints.ai_flags = AI_PASSIVE;
7688
89+ size_t connect_counter = 0 ;
7790 bool connected = false ;
7891 while (!connected)
7992 {
@@ -96,15 +109,25 @@ bool TCPSocket::setup(std::string& host, int port)
96109
97110 freeaddrinfo (result);
98111
112+ if (max_num_tries > 0 )
113+ {
114+ if (connect_counter++ >= max_num_tries)
115+ {
116+ URCL_LOG_ERROR (" Failed to establish connection for %s:%d after %d tries" , host.c_str (), port, max_num_tries);
117+ state_ = SocketState::Invalid;
118+ return false ;
119+ }
120+ }
121+
99122 if (!connected)
100123 {
101124 state_ = SocketState::Invalid;
102125 std::stringstream ss;
103126 ss << " Failed to connect to robot on IP " << host_name
104127 << " . Please check that the robot is booted and reachable on " << host_name << " . Retrying in "
105- << reconnection_time_ .count () << " seconds" ;
128+ << std::chrono::duration_cast<std::chrono::duration< float >>(reconnection_time_resolved) .count () << " seconds" ;
106129 URCL_LOG_ERROR (" %s" , ss.str ().c_str ());
107- std::this_thread::sleep_for (reconnection_time_ );
130+ std::this_thread::sleep_for (reconnection_time_resolved );
108131 }
109132 }
110133 setupOptions ();
@@ -210,5 +233,13 @@ void TCPSocket::setReceiveTimeout(const timeval& timeout)
210233 }
211234}
212235
236+ void TCPSocket::setReconnectionTime (const std::chrono::milliseconds reconnection_time)
237+ {
238+ URCL_LOG_ERROR (" Calling setReconnectionTime is deprecated. Reconnection timeout is passed to the setup method "
239+ " directly." );
240+ reconnection_time_ = reconnection_time;
241+ reconnection_time_modified_deprecated_ = true ;
242+ }
243+
213244} // namespace comm
214245} // namespace urcl
0 commit comments