Illustrated C/C++ source sheets, symbol index, API relationship graph, compiler console and debug trace

LIVE AI / FLEXIBLE SENSING / FLIGHT CONTEXT

Sensoraia API

Live AI and sensing, connected to the flight.
See, listen, inspect and return supported results while airborne.

Loading...
Searching...
No Matches
utc_time.h
Go to the documentation of this file.
1/*
2 * Copyright 2026 OpenUAS
3 * SPDX-License-Identifier: Apache-2.0
4 *
5 * Licensed under the Apache License, Version 2.0 (the "License");
6 * you may not use this file except in compliance with the License.
7 * You may obtain a copy of the License at
8 *
9 * http://www.apache.org/licenses/LICENSE-2.0
10 *
11 * Unless required by applicable law or agreed to in writing, software
12 * distributed under the License is distributed on an "AS IS" BASIS,
13 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 * See the License for the specific language governing permissions and
15 * limitations under the License.
16 */
17
18/**
19 * @file utc_time.h
20 * @brief Validate Gregorian UTC targets and qualify simulator time samples.
21 * @details The UTC lock is based on repeated simulator clock writes and
22 * readback; it is deliberately not treated as the camera's shutter clock.
23 * Frame-age and monotonic timestamp checks prevent stale readbacks from being
24 * promoted into capture metadata.
25 */
26#ifndef PANGEA_UTC_TIME_H
27#define PANGEA_UTC_TIME_H
28
29#include <array>
30#include <charconv>
31#include <cmath>
32#include <cstdint>
33#include <iomanip>
34#include <sstream>
35#include <stdexcept>
36#include <string>
37#include <string_view>
38
39namespace pangea_survey {
40/** @brief One simulator event/value pair used to set the Zulu clock. */
41struct UtcEvent {
42 const char* name;
43 std::uint32_t value;
44};
45
46/**
47 * @brief A Gregorian UTC minute and its simulator clock-matching rules.
48 * @details `text` is canonical `YYYY-MM-DDTHH:MMZ`; absolute seconds are a
49 * calendar coordinate, not a monotonic or exposure timestamp.
50 */
52 int year = 1, month = 1, day = 1, hour = 0, minute = 0;
53 std::string text;
54
55 /** @brief Return whether a Gregorian calendar year has 366 days. */
56 static bool leapYear(int value) {
57 return value % 4 == 0 && (value % 100 != 0 || value % 400 == 0);
58 }
59 /** @brief Get the length of a Gregorian calendar month.
60 * @param year Calendar year.
61 * @param month Validated one-based month (1 through 12).
62 * @return Days in the requested month.
63 * @details Only February varies under the Gregorian leap-year rule. */
64 static int daysInMonth(int year, int month) {
65 constexpr int days[] = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
66 return days[month - 1] + (month == 2 && leapYear(year) ? 1 : 0);
67 }
68 /** @brief Return the one-based ordinal day used by simulator clock events. */
69 int dayOfYear() const {
70 int result = day;
71 for (int m = 1; m < month; ++m) result += daysInMonth(year, m);
72 return result;
73 }
74 /** @brief Build the ordered simulator event sequence for this UTC minute. */
75 std::array<UtcEvent, 5> events() const {
76 // ZULU_DAY_SET uses 1-based ordinal days, unlike the ZULU DAY OF YEAR SimVar.
77 return {{{"ZULU_YEAR_SET", static_cast<std::uint32_t>(year)},
78 {"ZULU_DAY_SET", static_cast<std::uint32_t>(dayOfYear())},
79 {"ZULU_HOURS_SET", static_cast<std::uint32_t>(hour)},
80 {"ZULU_MINUTES_SET", static_cast<std::uint32_t>(minute)},
81 {"CLOCK_SECONDS_ZERO", 0}}};
82 }
83 /** @brief Convert the calendar minute to a monotonically increasing calendar coordinate. */
84 double absoluteSeconds() const {
85 const long long previousYears = year - 1;
86 const long long days = previousYears * 365 + previousYears / 4 -
87 previousYears / 100 + previousYears / 400 + dayOfYear() - 1;
88 return static_cast<double>(days) * 86400 + hour * 3600 + minute * 60;
89 }
90 /** @brief Check whether the simulator clock is in the requested UTC minute.
91 * @param actual Absolute calendar seconds, in the same epoch as absoluteSeconds().
92 * @return True for a finite time in the half-open minute.
93 * @details A reading exactly at the next minute belongs to that minute. */
94 bool matchesAbsoluteTime(double actual) const {
95 const double expected = absoluteSeconds();
96 return std::isfinite(actual) && actual >= expected && actual < expected + 60;
97 }
98 /** @brief Check the stricter time window used for capture.
99 * @param actual Absolute calendar seconds.
100 * @return True only during the first second of the requested minute.
101 * @details Minute-level matching is sufficient for date validation but
102 * not for confirming a capture immediately after zeroing the clock. */
103 bool matchesCaptureTime(double actual) const {
104 return std::isfinite(actual) && actual >= absoluteSeconds() &&
105 actual < absoluteSeconds() + 1;
106 }
107};
108
109/**
110 * @brief Parse a strict Gregorian UTC minute in `YYYY-MM-DDTHH:MMZ` form.
111 * @param[in] text Candidate ASCII date/time.
112 * @return Validated date/time preserving the canonical input string.
113 * @throws std::invalid_argument If syntax or any calendar field is invalid.
114 */
115inline UtcDateTime parseUtcDateTime(std::string_view text) {
116 const auto invalid = [] {
117 return std::invalid_argument("UTC must be a valid Gregorian date/time YYYY-MM-DDTHH:MMZ "
118 "(years 0001-9999, hours 00-23, minutes 00-59)");
119 };
120 if (text.size() != 17 || text[4] != '-' || text[7] != '-' ||
121 text[10] != 'T' || text[13] != ':' || text[16] != 'Z')
122 throw invalid();
123 const auto digits = [&](std::size_t start, std::size_t count) {
124 const auto part = text.substr(start, count);
125 int value = 0;
126 const auto parsed = std::from_chars(part.data(), part.data() + part.size(), value);
127 if (part.find_first_not_of("0123456789") != std::string_view::npos ||
128 parsed.ec != std::errc{} || parsed.ptr != part.data() + part.size())
129 throw invalid();
130 return value;
131 };
132 UtcDateTime result{digits(0, 4), digits(5, 2), digits(8, 2),
133 digits(11, 2), digits(14, 2), std::string(text)};
134 if (result.year < 1 || result.month < 1 || result.month > 12 || result.day < 1 ||
135 result.day > UtcDateTime::daysInMonth(result.year, result.month) ||
136 result.hour > 23 || result.minute > 59)
137 throw invalid();
138 return result;
139}
140
141/**
142 * @brief Convert simulator calendar seconds to their containing UTC minute.
143 * @param[in] actual Finite, nonnegative simulator calendar seconds.
144 * @return Canonical UTC minute containing @p actual.
145 * @throws std::runtime_error If the value lies outside years 0001 through 9999.
146 */
148 if (!std::isfinite(actual) || actual < 0 ||
149 actual >= UtcDateTime{9999, 12, 31, 23, 59, {}}.absoluteSeconds() + 60)
150 throw std::runtime_error("Simulator UTC is outside the supported Gregorian calendar");
151 int low = 1, high = 9999;
152 while (low < high) {
153 const int middle = (low + high + 1) / 2;
154 if (UtcDateTime{middle, 1, 1, 0, 0, {}}.absoluteSeconds() <= actual) low = middle;
155 else high = middle - 1;
156 }
157 UtcDateTime result{low, 1, 1, 0, 0, {}};
158 const auto wholeSeconds = static_cast<long long>(std::floor(actual - result.absoluteSeconds()));
159 int days = static_cast<int>(wholeSeconds / 86400);
160 while (days >= UtcDateTime::daysInMonth(result.year, result.month)) {
161 days -= UtcDateTime::daysInMonth(result.year, result.month);
162 ++result.month;
163 }
164 result.day = days + 1;
165 result.hour = static_cast<int>(wholeSeconds % 86400 / 3600);
166 result.minute = static_cast<int>(wholeSeconds % 3600 / 60);
167 std::ostringstream text;
168 text << std::setfill('0') << std::setw(4) << result.year << '-'
169 << std::setw(2) << result.month << '-' << std::setw(2) << result.day << 'T'
170 << std::setw(2) << result.hour << ':' << std::setw(2) << result.minute << 'Z';
171 result.text = text.str();
172 return result;
173}
174
175/**
176 * @brief Decide whether simulator UTC is stable enough to admit a capture.
177 * @param[in] target Requested UTC minute.
178 * @param[in] actual Latest simulator clock readback in absolute seconds.
179 * @param[in] readAgeSeconds Age of that readback in seconds.
180 * @param[in] verifiedFrame Frame number at which the target was last verified.
181 * @param[in] frame Current frame number.
182 * @param[in] pending Whether another time-setting event remains pending.
183 * @return True only for a fresh matching readback after at least three frames.
184 */
185inline bool captureUtcReady(const UtcDateTime& target, double actual, double readAgeSeconds,
186 unsigned long long verifiedFrame, unsigned long long frame,
187 bool pending) {
188 return !pending && target.matchesCaptureTime(actual) &&
189 std::isfinite(readAgeSeconds) && readAgeSeconds >= 0 && readAgeSeconds < 0.5 &&
190 frame >= verifiedFrame && frame - verifiedFrame >= 3;
191}
192
193/**
194 * @brief Validate that a frame's UTC readback is recent and in the locked second.
195 * @param[in] target Requested UTC minute.
196 * @param[in] actual Simulator calendar time sampled for the frame.
197 * @param[in] read100ns Monotonic clock count when UTC was read.
198 * @param[in] frame100ns Monotonic clock count associated with the rendered frame.
199 * @return True when the sample is ordered, less than one second old, and in target.
200 * @note Valid simulator-clock provenance does not imply exposure synchronization.
201 */
202inline bool captureUtcSampleValid(const UtcDateTime& target, double actual,
203 long long read100ns, long long frame100ns) {
204 return target.matchesCaptureTime(actual) && read100ns > 0 &&
205 frame100ns >= read100ns && frame100ns - read100ns < 10000000;
206}
207}
208#endif
bool invalid
Definition chdk_pipe.c:145
static bool start(uint32_t session)
Admit a nonzero session and discard correlation from the previous one.
static bool pending
uint8_t frame[LWIR_MAX_FRAME_BYTES]
Definition lwir_mock.c:58
bool captureUtcReady(const UtcDateTime &target, double actual, double readAgeSeconds, unsigned long long verifiedFrame, unsigned long long frame, bool pending)
Decide whether simulator UTC is stable enough to admit a capture.
Definition utc_time.h:185
bool captureUtcSampleValid(const UtcDateTime &target, double actual, long long read100ns, long long frame100ns)
Validate that a frame's UTC readback is recent and in the locked second.
Definition utc_time.h:202
UtcDateTime parseUtcDateTime(std::string_view text)
Parse a strict Gregorian UTC minute in YYYY-MM-DDTHH:MMZ form.
Definition utc_time.h:115
UtcDateTime utcMinuteFromAbsoluteTime(double actual)
Convert simulator calendar seconds to their containing UTC minute.
Definition utc_time.h:147
static size_t count
Definition pose_log.c:79
A Gregorian UTC minute and its simulator clock-matching rules.
Definition utc_time.h:51
double absoluteSeconds() const
Convert the calendar minute to a monotonically increasing calendar coordinate.
Definition utc_time.h:84
std::array< UtcEvent, 5 > events() const
Build the ordered simulator event sequence for this UTC minute.
Definition utc_time.h:75
static int daysInMonth(int year, int month)
Get the length of a Gregorian calendar month.
Definition utc_time.h:64
bool matchesCaptureTime(double actual) const
Check the stricter time window used for capture.
Definition utc_time.h:103
bool matchesAbsoluteTime(double actual) const
Check whether the simulator clock is in the requested UTC minute.
Definition utc_time.h:94
static bool leapYear(int value)
Return whether a Gregorian calendar year has 366 days.
Definition utc_time.h:56
int dayOfYear() const
Return the one-based ordinal day used by simulator clock events.
Definition utc_time.h:69
One simulator event/value pair used to set the Zulu clock.
Definition utc_time.h:41
std::uint32_t value
Definition utc_time.h:43
const char * name
Definition utc_time.h:42
struct usher_control_result result
Definition usher.c:377