22
33#include < chrono>
44#include < cstddef>
5- #include < cstdlib>
65#include < memory>
76#include < mutex>
87#include < string>
@@ -145,7 +144,7 @@ RobotClient::~RobotClient() {
145144
146145void RobotClient::close () {
147146 should_refresh_.store (false );
148- should_check_connection_ = false ;
147+ should_check_connection_. store ( false ) ;
149148
150149 if (refresh_thread_.joinable ()) {
151150 refresh_thread_.join ();
@@ -238,12 +237,20 @@ void RobotClient::refresh_every() {
238237};
239238
240239void RobotClient::check_connection () {
241- std::exception connection_error;
240+ unsigned int check_every = check_every_interval_;
241+ unsigned int reconnect_every = reconnect_every_interval_;
242+ if (check_every == 0 ) {
243+ check_every = reconnect_every;
244+ }
245+ if (check_every == 0 && reconnect_every == 0 ) {
246+ should_check_connection_.store (false );
247+ }
242248 bool connected (true );
243249 while (should_check_connection_) {
250+ std::exception connection_error;
244251 for (int i = 0 ; i < 3 ; ++i) {
245252 try {
246- std::this_thread::sleep_for (std::chrono::seconds{10 });
253+ std::this_thread::sleep_for (std::chrono::seconds{check_every });
247254 impl::client_helper (impl_, &RobotService::Stub::ResourceNames).invoke ([](auto &) {
248255 return ;
249256 });
@@ -258,9 +265,10 @@ void RobotClient::check_connection() {
258265 if (connected) {
259266 continue ;
260267 }
261- const auto * uri = viam_channel_.uri_ ;
262- VIAM_SDK_LOG (error)
263- << " Lost connection to machine. Attempting to reconnect to every second" ;
268+ const auto * uri = viam_channel_.get_channel_addr ();
269+ VIAM_SDK_LOG (error) << " Lost connection to machine at address " << uri << " with error "
270+ << connection_error.what () << " . Attempting to reconnect to every "
271+ << reconnect_every << " second(s)" ;
264272 viam_channel_.close ();
265273
266274 for (int i = 0 ; i < 3 ; ++i) {
@@ -274,12 +282,12 @@ void RobotClient::check_connection() {
274282 connected = true ;
275283 } catch (const std::exception& e) {
276284 viam_channel_.close ();
277- std::this_thread::sleep_for (std::chrono::seconds{1 });
285+ std::this_thread::sleep_for (std::chrono::seconds{reconnect_every });
278286 }
279287 }
280288 if (!connected) {
281289 // NOLINTNEXTLINE
282- exit ( 0 );
290+ close ( );
283291 }
284292 }
285293}
@@ -334,6 +342,9 @@ std::shared_ptr<RobotClient> RobotClient::with_channel(ViamChannel channel,
334342
335343 robot->should_check_connection_ = true ;
336344
345+ robot->check_every_interval_ = options.check_every_interval ();
346+ robot->reconnect_every_interval_ = options.reconnect_every_interval ();
347+
337348 robot->check_connection_thread_ = std::thread{&RobotClient::check_connection, robot.get ()};
338349
339350 robot->refresh ();
0 commit comments