SMACC2
Loading...
Searching...
No Matches
cp_calendar_poller.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 <boost/regex.hpp>
18#include <ctime>
19#include <iomanip>
20#include <sstream>
21
22namespace cl_gcalcli
23{
24
25CpCalendarPoller::CpCalendarPoller() : connection_(nullptr), initialized_(false) {}
26
28{
29 if (!initialized_)
30 {
32
33 if (connection_ == nullptr)
34 {
35 RCLCPP_ERROR(getLogger(), "[CpCalendarPoller] CpGcalcliConnection component not found!");
36 return;
37 }
38
39 last_poll_attempt_ = std::chrono::steady_clock::now();
40 initialized_ = true;
41
42 RCLCPP_INFO(getLogger(), "[CpCalendarPoller] Initialized");
43 }
44}
45
47{
49 {
50 RCLCPP_WARN(getLogger(), "[CpCalendarPoller] Cannot refresh - not connected");
51 return false;
52 }
53
54 const auto & config = connection_->getConfig();
55
56 // Build the agenda command with TSV output
57 std::stringstream args;
58 args << "agenda --tsv --nocolor";
59 args << " --nodeclined";
60
61 // Add date range
62 auto now = std::chrono::system_clock::now();
63 auto end = now + std::chrono::hours(24 * config.agenda_days);
64
65 auto now_t = std::chrono::system_clock::to_time_t(now);
66 auto end_t = std::chrono::system_clock::to_time_t(end);
67
68 std::tm now_tm{}, end_tm{};
69 localtime_r(&now_t, &now_tm);
70 localtime_r(&end_t, &end_tm);
71
72 args << " \"" << std::put_time(&now_tm, "%m/%d/%Y") << "\"";
73 args << " \"" << std::put_time(&end_tm, "%m/%d/%Y") << "\"";
74
75 auto result = connection_->executeGcalcli(args.str(), 30000);
76
77 if (result.exit_code != 0 || result.timed_out)
78 {
79 RCLCPP_WARN(
80 getLogger(), "[CpCalendarPoller] Agenda fetch failed: %s", result.stdout_output.c_str());
81 return false;
82 }
83
84 // Parse the TSV output
85 auto events = parseTsvOutput(result.stdout_output);
86
87 {
88 std::lock_guard<std::mutex> lock(events_mutex_);
89 cached_events_ = events;
90 last_poll_time_ = std::chrono::system_clock::now();
91 }
92
93 RCLCPP_DEBUG(getLogger(), "[CpCalendarPoller] Refreshed agenda: %zu events", events.size());
94
95 // Emit signal and post event
96 onAgendaUpdated_(events);
98 {
100 }
101
102 return true;
103}
104
105std::vector<CalendarEvent> CpCalendarPoller::getEvents() const
106{
107 std::lock_guard<std::mutex> lock(events_mutex_);
108 return cached_events_;
109}
110
111std::vector<CalendarEvent> CpCalendarPoller::findEvents(
112 const std::string & pattern, bool use_regex) const
113{
114 std::lock_guard<std::mutex> lock(events_mutex_);
115
116 std::vector<CalendarEvent> matches;
117
118 if (use_regex)
119 {
120 try
121 {
122 boost::regex regex(pattern, boost::regex::icase);
123 for (const auto & event : cached_events_)
124 {
125 if (boost::regex_search(event.title, regex))
126 {
127 matches.push_back(event);
128 }
129 }
130 }
131 catch (const boost::regex_error & e)
132 {
133 RCLCPP_ERROR(getLogger(), "[CpCalendarPoller] Invalid regex pattern: %s", e.what());
134 }
135 }
136 else
137 {
138 for (const auto & event : cached_events_)
139 {
140 if (event.title.find(pattern) != std::string::npos)
141 {
142 matches.push_back(event);
143 }
144 }
145 }
146
147 return matches;
148}
149
150std::vector<CalendarEvent> CpCalendarPoller::getEventsInWindow(
151 std::chrono::system_clock::time_point start, std::chrono::system_clock::time_point end) const
152{
153 std::lock_guard<std::mutex> lock(events_mutex_);
154
155 std::vector<CalendarEvent> matches;
156 for (const auto & event : cached_events_)
157 {
158 // Event overlaps with window if it starts before window end and ends after window start
159 if (event.start_time < end && event.end_time > start)
160 {
161 matches.push_back(event);
162 }
163 }
164
165 return matches;
166}
167
168std::vector<CalendarEvent> CpCalendarPoller::getActiveEvents() const
169{
170 std::lock_guard<std::mutex> lock(events_mutex_);
171
172 std::vector<CalendarEvent> active;
173 for (const auto & event : cached_events_)
174 {
175 if (event.isActiveNow())
176 {
177 active.push_back(event);
178 }
179 }
180
181 return active;
182}
183
184std::chrono::system_clock::time_point CpCalendarPoller::getLastPollTime() const
185{
186 std::lock_guard<std::mutex> lock(events_mutex_);
187 return last_poll_time_;
188}
189
191{
192 if (!initialized_ || !connection_)
193 {
194 return;
195 }
196
197 if (!connection_->isConnected())
198 {
199 return;
200 }
201
202 const auto & config = connection_->getConfig();
203 auto now = std::chrono::steady_clock::now();
204 auto elapsed = std::chrono::duration_cast<std::chrono::seconds>(now - last_poll_attempt_);
205
206 if (elapsed >= config.poll_interval)
207 {
209 last_poll_attempt_ = now;
210 }
211}
212
213std::vector<CalendarEvent> CpCalendarPoller::parseTsvOutput(const std::string & output)
214{
215 std::vector<CalendarEvent> events;
216 std::istringstream stream(output);
217 std::string line;
218
219 while (std::getline(stream, line))
220 {
221 // Skip empty lines
222 if (line.empty() || line.find_first_not_of(" \t\r\n") == std::string::npos)
223 {
224 continue;
225 }
226
227 auto event = parseTsvLine(line);
228 if (event.has_value())
229 {
230 events.push_back(event.value());
231 }
232 }
233
234 return events;
235}
236
237std::optional<CalendarEvent> CpCalendarPoller::parseTsvLine(const std::string & line)
238{
239 // TSV columns: Start_Date | Start_Time | End_Date | End_Time | Title | Location | Description | Calendar
240 std::vector<std::string> fields;
241 std::istringstream stream(line);
242 std::string field;
243
244 while (std::getline(stream, field, '\t'))
245 {
246 fields.push_back(field);
247 }
248
249 // We need at least 5 fields (date/time + title)
250 if (fields.size() < 5)
251 {
252 RCLCPP_DEBUG(
253 getLogger(), "[CpCalendarPoller] Skipping line with insufficient fields: %s", line.c_str());
254 return std::nullopt;
255 }
256
257 CalendarEvent event;
258
259 // Parse start time
260 auto start = parseDateTime(fields[0], fields[1]);
261 if (!start.has_value())
262 {
263 RCLCPP_DEBUG(
264 getLogger(), "[CpCalendarPoller] Failed to parse start time: %s %s", fields[0].c_str(),
265 fields[1].c_str());
266 return std::nullopt;
267 }
268 event.start_time = start.value();
269
270 // Parse end time
271 auto end = parseDateTime(fields[2], fields[3]);
272 if (!end.has_value())
273 {
274 RCLCPP_DEBUG(
275 getLogger(), "[CpCalendarPoller] Failed to parse end time: %s %s", fields[2].c_str(),
276 fields[3].c_str());
277 return std::nullopt;
278 }
279 event.end_time = end.value();
280
281 // Title (required)
282 event.title = fields[4];
283
284 // Optional fields
285 if (fields.size() > 5) event.location = fields[5];
286 if (fields.size() > 6) event.description = fields[6];
287 if (fields.size() > 7) event.calendar_name = fields[7];
288
289 // Check for all-day event (typically has no time or 00:00)
290 event.is_all_day = (fields[1].empty() || fields[1] == "00:00" || fields[1] == "12:00am");
291
292 // Generate ID
293 event.id = generateEventId(event);
294
295 return event;
296}
297
298std::optional<std::chrono::system_clock::time_point> CpCalendarPoller::parseDateTime(
299 const std::string & date_str, const std::string & time_str)
300{
301 std::tm tm = {};
302
303 // Parse date - gcalcli TSV uses YYYY-MM-DD format
304 std::istringstream date_stream(date_str);
305 char sep1, sep2;
306 int year, month, day;
307
308 if (date_stream >> year >> sep1 >> month >> sep2 >> day && sep1 == '-' && sep2 == '-')
309 {
310 // YYYY-MM-DD format (gcalcli TSV)
311 tm.tm_year = year - 1900;
312 tm.tm_mon = month - 1;
313 tm.tm_mday = day;
314 }
315 else
316 {
317 // Try MM/DD/YYYY format as fallback
318 date_stream.clear();
319 date_stream.str(date_str);
320 if (date_stream >> month >> sep1 >> day >> sep2 >> year && sep1 == '/' && sep2 == '/')
321 {
322 tm.tm_mon = month - 1;
323 tm.tm_mday = day;
324 tm.tm_year = year - 1900;
325 }
326 else
327 {
328 RCLCPP_DEBUG(getLogger(), "[CpCalendarPoller] Failed to parse date: %s", date_str.c_str());
329 return std::nullopt;
330 }
331 }
332
333 // Parse time - gcalcli TSV uses 24-hour HH:MM format
334 if (!time_str.empty())
335 {
336 std::istringstream time_stream(time_str);
337 char colon;
338 int hour, minute;
339
340 if (time_stream >> hour >> colon >> minute && colon == ':')
341 {
342 tm.tm_hour = hour;
343 tm.tm_min = minute;
344
345 // Check for am/pm suffix (for non-TSV formats)
346 std::string rest;
347 std::getline(time_stream, rest);
348 if (!rest.empty())
349 {
350 // Remove leading spaces
351 size_t start = rest.find_first_not_of(" ");
352 if (start != std::string::npos)
353 {
354 rest = rest.substr(start);
355 }
356 // Check for am/pm
357 if (rest == "pm" || rest == "PM" || rest == "p" || rest == "P")
358 {
359 if (hour != 12) tm.tm_hour += 12;
360 }
361 else if (rest == "am" || rest == "AM" || rest == "a" || rest == "A")
362 {
363 if (hour == 12) tm.tm_hour = 0;
364 }
365 }
366 }
367 else
368 {
369 RCLCPP_DEBUG(getLogger(), "[CpCalendarPoller] Failed to parse time: %s", time_str.c_str());
370 return std::nullopt;
371 }
372 }
373
374 tm.tm_sec = 0;
375 tm.tm_isdst = -1; // Let mktime determine DST
376
377 std::time_t time = std::mktime(&tm);
378 if (time == -1)
379 {
380 return std::nullopt;
381 }
382
383 return std::chrono::system_clock::from_time_t(time);
384}
385
387{
388 // Generate a unique ID based on title and start time
389 auto start_t = std::chrono::system_clock::to_time_t(event.start_time);
390 std::stringstream ss;
391 ss << event.title << "_" << start_t << "_" << event.calendar_name;
392 return ss.str();
393}
394
395} // namespace cl_gcalcli
std::optional< std::chrono::system_clock::time_point > parseDateTime(const std::string &date_str, const std::string &time_str)
Parse date and time strings into time_point.
smacc2::SmaccSignal< void(const std::vector< CalendarEvent > &)> onAgendaUpdated_
std::vector< CalendarEvent > getEventsInWindow(std::chrono::system_clock::time_point start, std::chrono::system_clock::time_point end) const
Get events happening within a time window.
std::chrono::system_clock::time_point last_poll_time_
bool refreshAgenda()
Force an immediate agenda refresh.
void update() override
Periodic update for polling (called by SignalDetector)
std::vector< CalendarEvent > findEvents(const std::string &pattern, bool use_regex=false) const
Get events matching a title pattern.
std::vector< CalendarEvent > getActiveEvents() const
Get currently active events.
std::vector< CalendarEvent > getEvents() const
Get cached list of calendar events.
std::string generateEventId(const CalendarEvent &event)
Generate a unique ID for an event.
std::optional< CalendarEvent > parseTsvLine(const std::string &line)
Parse a single TSV line into a CalendarEvent.
std::chrono::steady_clock::time_point last_poll_attempt_
std::function< void(const std::vector< CalendarEvent > &)> postAgendaUpdatedEvent_
std::vector< CalendarEvent > parseTsvOutput(const std::string &output)
Parse TSV output into CalendarEvent structures.
std::chrono::system_clock::time_point getLastPollTime() const
Get the time of the last successful poll.
std::vector< CalendarEvent > cached_events_
const GcalcliConfig & getConfig() const
Get the gcalcli configuration.
bool isConnected() const
Check if connected to Google Calendar.
smacc2::client_core_components::SubprocessResult executeGcalcli(const std::string &args, int timeout_ms=30000)
Execute a gcalcli command.
rclcpp::Logger getLogger() const
void requiresComponent(TComponent *&requiredComponentStorage, ComponentRequirement requirementType=ComponentRequirement::SOFT)
Represents a Google Calendar event.
Definition types.hpp:40
std::chrono::system_clock::time_point start_time
Definition types.hpp:46