SMACC2
Loading...
Searching...
No Matches
cb_wait_connection.cpp
Go to the documentation of this file.
1// Copyright 2024 RobosoftAI Inc.
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7// http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
16
17#include <thread>
18
19namespace cl_gcalcli
20{
21
22CbWaitConnection::CbWaitConnection(std::chrono::seconds timeout)
23: timeout_(timeout), client_(nullptr)
24{
25}
26
28{
29 RCLCPP_INFO(
30 getLogger(), "[CbWaitConnection] Waiting for gcalcli connection (timeout: %lds)",
31 timeout_.count());
32
34
35 if (!client_)
36 {
37 RCLCPP_ERROR(getLogger(), "[CbWaitConnection] ClGcalcli client not available");
38 this->postFailureEvent();
39 return;
40 }
41
42 auto * connection = client_->getConnection();
43 if (!connection)
44 {
45 RCLCPP_ERROR(getLogger(), "[CbWaitConnection] CpGcalcliConnection not available");
46 this->postFailureEvent();
47 return;
48 }
49
50 auto start = std::chrono::steady_clock::now();
51 auto deadline = start + timeout_;
52
53 // Poll for connection with increasing backoff
54 std::chrono::milliseconds poll_interval{500};
55 const std::chrono::milliseconds max_interval{5000};
56
57 while (std::chrono::steady_clock::now() < deadline)
58 {
59 // Check if we should force finish
60 if (this->isShutdownRequested())
61 {
62 RCLCPP_INFO(getLogger(), "[CbWaitConnection] Shutdown requested");
63 return;
64 }
65
66 if (connection->checkConnection())
67 {
68 RCLCPP_INFO(getLogger(), "[CbWaitConnection] Connection established");
69 this->postSuccessEvent();
70 return;
71 }
72
73 // Wait before next attempt
74 std::this_thread::sleep_for(poll_interval);
75
76 // Increase interval with backoff
77 poll_interval = std::min(poll_interval * 2, max_interval);
78 }
79
80 RCLCPP_ERROR(getLogger(), "[CbWaitConnection] Connection timeout after %lds", timeout_.count());
81 this->postFailureEvent();
82}
83
84} // namespace cl_gcalcli
CbWaitConnection(std::chrono::seconds timeout=std::chrono::seconds{30})
Construct with optional timeout.
CpGcalcliConnection * getConnection()
virtual rclcpp::Logger getLogger() const
void requiresClient(SmaccClientType *&storage)
bool isShutdownRequested()
onEntry is executed in a new thread. However the current state cannot be left until the onEntry threa...