std_rs/records/timestamp.rs
1use epics_base_rs::error::{CaError, CaResult};
2use epics_base_rs::server::record::{
3 EPICS_TIME_EVENT_DEVICE_TIME, FieldDesc, ProcessContext, ProcessOutcome, Record, ValuePostGate,
4};
5use epics_base_rs::types::{EpicsValue, PvString};
6
7use super::dbd_generated;
8use chrono::{Local, TimeZone};
9
10/// EPICS epoch: 1990-01-01 00:00:00 UTC
11const EPICS_EPOCH_OFFSET: i64 = 631152000;
12
13/// Maximum number of visible (non-NUL) bytes in the VAL/OVAL fields.
14///
15/// `timestampRecord.dbd` declares `VAL`/`OVAL` as `char val[40]`, and C
16/// `timestampRecord.c:140` calls `epicsTimeToStrftime(val, sizeof(val), ...)`.
17/// `epicsTimeToStrftime` wraps `strftime`, which writes at most
18/// `sizeof(val)` bytes *including* the terminating NUL — so the buffer
19/// holds at most 39 visible characters. A Rust `String` carries no NUL
20/// terminator, so the visible-byte bound is 39, not 40.
21const VAL_VISIBLE_MAX: usize = 39;
22
23/// Timestamp format strings indexed by TST field value.
24///
25/// Mirrors the `switch(tst)` in `timestampRecord.c:100-138`. Any TST value
26/// outside `0..=10` falls through C's `default:` branch to format 0
27/// (`YY/MM/DD HH:MM:SS`).
28const TIMESTAMP_FORMATS: &[&str] = &[
29 "%y/%m/%d %H:%M:%S", // 0 timestampTST_YY_MM_DD_HH_MM_SS
30 "%m/%d/%y %H:%M:%S", // 1 timestampTST_MM_DD_YY_HH_MM_SS
31 "%b %d %H:%M:%S %y", // 2 timestampTST_MM_DD_HH_MM_SS_YY
32 "%b %d %H:%M:%S", // 3 timestampTST_MM_DD_HH_MM_SS
33 "%H:%M:%S", // 4 timestampTST_HH_MM_SS
34 "%H:%M", // 5 timestampTST_HH_MM
35 "%d/%m/%y %H:%M:%S", // 6 timestampTST_DD_MM_YY_HH_MM_SS
36 "%d %b %H:%M:%S %y", // 7 timestampTST_DD_MM_HH_MM_SS_YY
37 "%d-%b-%Y %H:%M:%S", // 8 timestampTST_VMS
38];
39
40/// Timestamp record — generates formatted timestamp strings.
41///
42/// Ported from EPICS std module `timestampRecord.c`.
43pub struct TimestampRecord {
44 /// Current formatted timestamp string (VAL).
45 pub val: PvString,
46 /// Previous value for change detection (OVAL).
47 pub oval: PvString,
48 /// Seconds past EPICS epoch (RVAL). DBF_ULONG in C; the Rust value
49 /// model has no unsigned-32 scalar, so this follows the project
50 /// convention of mapping DBF_ULONG to `i32`/`EpicsValue::Long`.
51 /// `field(RVAL,DBF_ULONG)` (`timestampRecord.dbd:28`) — C
52 /// `ptimestamp->rval = ptimestamp->time.secPastEpoch` (`timestampRecord.c:94`),
53 /// and `secPastEpoch` is an `epicsUInt32`. Stored `i32` and served
54 /// `EpicsValue::Long` while the port hand-wrote its own field table.
55 pub rval: u32,
56 /// Timestamp format selector (TST), a DBF_MENU. Values `0..=10`
57 /// select an explicit format; any other value is rendered with
58 /// format 0 (C `switch` `default:` branch).
59 pub tst: i16,
60 /// Framework-owned `dbCommon.tse`, pushed via
61 /// [`Record::set_process_context`] before `process()`. C
62 /// `timestampRecord.c:90` branches on
63 /// `tse == epicsTimeEventDeviceTime`: device-time takes the raw OS
64 /// clock (`epicsTimeFromTime_t(&time, time(0))`, whole seconds, no
65 /// fraction); any other value uses the EPICS time-stamp framework.
66 tse: i16,
67}
68
69impl Default for TimestampRecord {
70 fn default() -> Self {
71 Self {
72 val: PvString::new(),
73 oval: PvString::new(),
74 rval: 0,
75 tst: 0,
76 tse: 0,
77 }
78 }
79}
80
81impl TimestampRecord {
82 fn format_timestamp(&self) -> (PvString, u32) {
83 // C `timestampRecord.c:90-93`: `tse == epicsTimeEventDeviceTime`
84 // takes the raw OS clock via `epicsTimeFromTime_t(&time, time(0))`
85 // — whole seconds only, the nanosecond field is zero. Any other
86 // TSE value goes through `recGblGetTimeStamp`, which carries
87 // sub-second precision. The Rust port mirrors the observable
88 // difference: device-time truncates `now` to whole seconds so
89 // the `.%03f` formats (TST 9/10) render `.000`.
90 let now = if self.tse == EPICS_TIME_EVENT_DEVICE_TIME {
91 let secs = Local::now().timestamp();
92 // `timestamp_opt(secs, 0)` is always `Single` for any
93 // in-range Unix second; fall back to the un-truncated clock
94 // on the impossible `None`/`Ambiguous` case rather than
95 // panicking.
96 Local
97 .timestamp_opt(secs, 0)
98 .single()
99 .unwrap_or_else(Local::now)
100 } else {
101 Local::now()
102 };
103 let unix_secs = now.timestamp();
104 let sec_past_epoch = (unix_secs - EPICS_EPOCH_OFFSET) as u32;
105
106 // C `timestampRecord.c:96`: `if (time.secPastEpoch == 0)` — the
107 // "-NULL-" sentinel is emitted only when the EPICS-epoch second
108 // count is exactly zero (an uninitialised/unset time stamp), not
109 // for any non-positive value.
110 if sec_past_epoch == 0 {
111 return (PvString::from("-NULL-"), sec_past_epoch);
112 }
113
114 // C `timestampRecord.c:100-138`: any TST outside the valid menu
115 // range falls through `default:` to format 0. The raw TST value
116 // is preserved (the field is a plain menu); only the format
117 // *selection* is bounded here.
118 let tst = self.tst;
119
120 let formatted = match tst {
121 0..=8 => now.format(TIMESTAMP_FORMATS[tst as usize]).to_string(),
122 // Formats 9 (timestampTST_MM_DD_YYYY) and 10
123 // (timestampTST_MM_DD_YY) carry `.%03f` fractional seconds.
124 // C `timestampRecord.c:130,133`. EPICS `%03f` is the
125 // 3-digit fractional-seconds field derived from the time
126 // stamp's nanoseconds; `subsec_millis()` is the equivalent
127 // 3-digit truncation of the same fraction.
128 9 | 10 => {
129 // C `epicsTime.cpp:234-239`: the `%03f` fractional field
130 // ROUNDS to the nearest millisecond (see
131 // `round_subsec_to_millis`). `timestamp_subsec_millis()`
132 // (= nsec / 1e6) truncates instead, shifting every value
133 // on a half-ms boundary down by one.
134 let ms = round_subsec_to_millis(now.timestamp_subsec_nanos());
135 let base = if tst == 9 {
136 now.format("%b %d %Y %H:%M:%S").to_string()
137 } else {
138 now.format("%m/%d/%y %H:%M:%S").to_string()
139 };
140 format!("{base}.{ms:03}")
141 }
142 // C `default:` branch — format 0 (`YY/MM/DD HH:MM:SS`).
143 _ => now.format(TIMESTAMP_FORMATS[0]).to_string(),
144 };
145
146 // C `timestampRecord.c:140` `epicsTimeToStrftime(val, sizeof(val), ...)`
147 // bounds the result to the `char val[40]` buffer; `strftime` keeps
148 // one byte for the NUL terminator, so at most 39 visible chars.
149 (
150 truncate_to(PvString::from(formatted), VAL_VISIBLE_MAX),
151 sec_past_epoch,
152 )
153 }
154}
155
156/// Truncate `s` to at most `max` bytes.
157///
158/// C stores VAL/OVAL in a fixed `char[40]` buffer whose last byte is the
159/// NUL terminator, so at most 39 visible bytes survive. C `strftime`
160/// truncates the buffer byte for byte, so this cut is on a raw byte
161/// boundary and a non-UTF-8 VAL written by a client round-trips verbatim.
162fn truncate_to(s: PvString, max: usize) -> PvString {
163 if s.len() > max {
164 PvString::from_bytes(s.as_bytes()[..max].to_vec())
165 } else {
166 s
167 }
168}
169
170/// Round a sub-second nanosecond count to a 3-digit millisecond field.
171///
172/// C `epicsTime.cpp:234-239` renders the `%03f` fractional field by
173/// ROUNDING the nanoseconds to the nearest millisecond, with a clamp
174/// that prevents the rounded value from carrying into whole seconds:
175/// ```text
176/// frac = nsec + div[fracWid]/2; // div[3] = 1e6, so +5e5
177/// if (frac >= 1000000000) frac = 1000000000 - 1;
178/// frac /= div[fracWid]; // /1e6 -> 0..=999
179/// ```
180/// A naive `nsec / 1_000_000` truncates, biasing every value on a
181/// half-millisecond boundary down by one (e.g. 1.7 ms → `.001` instead
182/// of `.002`). The `min` clamp keeps a near-`1e9` nanosecond count from
183/// rounding up to `1000` ms (which would need a carry into the seconds
184/// field C never performs here).
185fn round_subsec_to_millis(nsec: u32) -> u32 {
186 let frac = (nsec + 500_000).min(1_000_000_000 - 1);
187 frac / 1_000_000
188}
189
190impl Record for TimestampRecord {
191 fn record_type(&self) -> &'static str {
192 "timestamp"
193 }
194
195 fn process(&mut self) -> CaResult<ProcessOutcome> {
196 let (formatted, sec_past_epoch) = self.format_timestamp();
197 // RVAL is refreshed on every process (`timestampRecord.c:94`) — a caget
198 // of RVAL between posts reads the current second — so only the
199 // *posting* is gated, never the value. The OVAL compare and copy are
200 // C's `monitor()`'s, and live in `monitor_value_changed`.
201 self.val = formatted;
202 self.rval = sec_past_epoch;
203 Ok(ProcessOutcome::complete())
204 }
205
206 fn get_field(&self, name: &str) -> Option<EpicsValue> {
207 match name {
208 "VAL" => Some(EpicsValue::String(self.val.clone())),
209 "OVAL" => Some(EpicsValue::String(self.oval.clone())),
210 "RVAL" => Some(EpicsValue::ULong(self.rval)),
211 "TST" => Some(EpicsValue::Short(self.tst)),
212 _ => None,
213 }
214 }
215
216 fn put_field(&mut self, name: &str, value: EpicsValue) -> CaResult<()> {
217 match name {
218 "VAL" => match value {
219 EpicsValue::String(v) => {
220 // VAL is a `char[40]` field in C; the last byte is the
221 // NUL terminator, so 39 visible bytes at most.
222 self.val = truncate_to(v, VAL_VISIBLE_MAX);
223 Ok(())
224 }
225 _ => Err(CaError::TypeMismatch(name.into())),
226 },
227 "RVAL" => match value {
228 EpicsValue::ULong(v) => {
229 self.rval = v;
230 Ok(())
231 }
232 _ => Err(CaError::TypeMismatch(name.into())),
233 },
234 "TST" => match value {
235 EpicsValue::Short(v) => {
236 // TST is a plain DBF_MENU field — C stores whatever
237 // value is written and `format_timestamp` selects
238 // the format via a `switch` whose `default:` branch
239 // covers any out-of-range value. Do NOT clamp here:
240 // C `timestampRecord.dbd` declares no field range,
241 // and a read-back must reflect the raw value.
242 self.tst = v;
243 Ok(())
244 }
245 _ => Err(CaError::TypeMismatch(name.into())),
246 },
247 "OVAL" => Err(CaError::ReadOnlyField(name.into())),
248 _ => Err(CaError::FieldNotFound(name.into())),
249 }
250 }
251
252 fn declared_fields(&self) -> &'static [FieldDesc] {
253 dbd_generated::TIMESTAMP_FIELDS
254 }
255
256 /// C `timestampRecord.c:90` reads `ptimestamp->tse`. The framework
257 /// owns `dbCommon.tse`; this hook captures it so `process()` can
258 /// take the device-time branch.
259 fn set_process_context(&mut self, ctx: &ProcessContext) {
260 self.tse = ctx.tse;
261 }
262
263 /// The timestamp record has NO value deadband: its monitored
264 /// quantity is the formatted `VAL` string, and `timestampRecord.dbd`
265 /// declares no MDEL/ADEL. C `monitor()` (`timestampRecord.c:152-163`)
266 /// posts `VAL` (and `RVAL`) only inside
267 /// `if (strncmp(oval, val, sizeof(val)))` — i.e. exactly when the
268 /// formatted string changed since the previous process — then copies
269 /// `val` into `oval`. That is plain change-detection, not a deadband.
270 ///
271 /// The framework's snapshot builders force-post the deadband field on
272 /// every cycle the deadband gate fires (and the gate always fires for
273 /// a non-numeric value — see [`epics_base_rs::server::record::RecordInstance::check_deadband_ext`],
274 /// whose `to_f64()` returns `None` for a string `VAL`). Returning the
275 /// default `"VAL"` here would therefore re-post `VAL` on every scan,
276 /// even when the rendered string is unchanged — diverging from C's
277 /// `strncmp` gate. Returning `""` (a name no field resolves to)
278 /// suppresses that force-post (`resolve_field("")` is `None`, so the
279 /// `if let Some(val) = dval` push is skipped) and routes `VAL`
280 /// through the generic change-detection loop, which posts it only
281 /// when it differs from the last posted value — matching C exactly.
282 fn monitor_deadband_field(&self) -> &'static str {
283 ""
284 }
285
286 /// C `monitor()`'s single gate: the `strncmp(oval, val)` string change
287 /// (`timestampRecord.c:158`). Reported here so the framework's VAL monitor
288 /// mask is live only on a cycle that re-rendered a different string — which
289 /// is also the gate `RVAL` hangs off (see
290 /// [`Self::fields_posted_with_value_mask`]).
291 /// C `timestampRecord.c:158-162` `monitor()`: the `strncmp(oval, val)`
292 /// mismatch posts VAL *and* RVAL and then copies VAL into OVAL. Compared
293 /// and committed HERE, at C's position, never captured during `process()`.
294 fn monitor_value_changed(&mut self) -> Option<bool> {
295 let changed = self.oval != self.val;
296 if changed {
297 self.oval = self.val.clone();
298 }
299 Some(changed)
300 }
301
302 /// C posts `RVAL` from *inside* the VAL-string-change guard, with VAL's own
303 /// monitor mask and with no test of RVAL's own value
304 /// (`db_post_events(&ptimestamp->rval, monitor_mask)`,
305 /// `timestampRecord.c:160`) — so the seconds count reaches monitors exactly
306 /// when the rendered string moves, and no more often.
307 ///
308 /// Left to the generic change-detection loop instead, `RVAL` posts on every
309 /// process that crosses a second — ~59 spurious `DBE_VALUE|DBE_LOG` events a
310 /// minute per subscriber under a coarse TST such as `HH:MM`, whose VAL only
311 /// changes once a minute.
312 fn fields_posted_with_value_mask(&self) -> &'static [(&'static str, ValuePostGate)] {
313 &[("RVAL", ValuePostGate::WithValue)]
314 }
315
316 fn clears_udf(&self) -> bool {
317 true
318 }
319}
320
321#[cfg(test)]
322mod subsec_round_tests {
323 use super::round_subsec_to_millis;
324
325 // C `epicsTime.cpp:234-239` rounds the `%03f` fractional field to
326 // the nearest millisecond; the previous `nsec / 1e6` truncated.
327 #[test]
328 fn rounds_to_nearest_millisecond() {
329 // Below the half-ms point: rounds down.
330 assert_eq!(round_subsec_to_millis(0), 0);
331 assert_eq!(round_subsec_to_millis(499_999), 0);
332 assert_eq!(round_subsec_to_millis(1_400_000), 1);
333 // Exactly half a millisecond: C's `+ div/2` rounds up.
334 assert_eq!(round_subsec_to_millis(500_000), 1);
335 assert_eq!(round_subsec_to_millis(1_500_000), 2);
336 // Above the half-ms point: rounds up — the case truncation got
337 // wrong (1.7 ms truncated to .001, now rounds to .002).
338 assert_eq!(round_subsec_to_millis(1_700_000), 2);
339 }
340
341 // The clamp keeps a near-1e9 nanosecond count from rounding up to
342 // 1000 ms (C `if (frac >= 1e9) frac = 1e9 - 1`), which would need a
343 // carry into the seconds field the record never performs.
344 #[test]
345 fn clamps_instead_of_carrying_into_seconds() {
346 assert_eq!(round_subsec_to_millis(999_500_000), 999);
347 assert_eq!(round_subsec_to_millis(999_999_999), 999);
348 }
349}
350
351#[cfg(test)]
352mod menu_choice_tests {
353 use super::{TimestampRecord, dbd_generated};
354 use epics_base_rs::server::record::FieldDeclaration;
355 use epics_base_rs::server::record::{Record, RecordInstance};
356 use epics_base_rs::types::EpicsValue;
357
358 // TST is menu(timestampTST) served as Short; the base snapshot path
359 // promotes it to DBR_ENUM and attaches the wire-visible format labels.
360 #[test]
361 fn timestamp_tst_snapshot_is_enum_with_labels() {
362 let mut rec = TimestampRecord::default();
363 rec.put_field("TST", EpicsValue::Short(4)).unwrap(); // HH:MM:SS
364 let inst = RecordInstance::new("TS:TST".into(), rec);
365
366 let snap = inst.snapshot_for_field("TST").unwrap();
367 assert_eq!(snap.value, EpicsValue::Enum(4));
368 let strings = &snap.enums.as_ref().unwrap().strings;
369 assert_eq!(strings.len(), 11);
370 assert_eq!(strings[4], "HH:MM:SS");
371 }
372
373 /// The choices are the DECLARATION's, not a record hook's: `TST` is
374 /// `DBF_MENU menu(timestampTST)` in `timestampRecord.dbd`, so its
375 /// `FieldDesc` carries the choices and every consumer reads them from
376 /// there. This used to assert a hand-written `TIMESTAMP_TST_CHOICES` that
377 /// `menu_field_choices` returned — a second declaration of the same menu.
378 #[test]
379 fn timestamp_tst_choices_come_from_the_declaration() {
380 let rec = TimestampRecord::default();
381 let tst = rec
382 .field_list()
383 .iter()
384 .find(|f| f.name == "TST")
385 .expect("TST is declared");
386 assert_eq!(tst.menu, Some(dbd_generated::MENU_TIMESTAMP_TST));
387 let val = rec
388 .field_list()
389 .iter()
390 .find(|f| f.name == "VAL")
391 .expect("VAL is declared");
392 assert_eq!(val.menu, None);
393 }
394
395 // C `timestampRecord.c:152-163`: `monitor()` posts VAL (and RVAL)
396 // only inside `if (strncmp(oval, val))` — when the formatted string
397 // changed. There is no value deadband. The record routes VAL through
398 // the framework's generic change-detection loop by reporting an
399 // empty deadband field; the framework's deadband force-post is then
400 // skipped because that name resolves to nothing.
401 #[test]
402 fn timestamp_has_no_deadband_field_so_val_change_detects() {
403 let rec = TimestampRecord::default();
404 // No numeric value deadband — the sentinel routes VAL to the
405 // change-detection loop (cf. motor's "RBV").
406 assert_eq!(rec.monitor_deadband_field(), "");
407
408 // The framework's deadband force-post fires only
409 // `if let Some(val) = resolve_field(deadband_field)`. The "" name
410 // must resolve to None so VAL is never force-posted on an
411 // unchanged-string cycle.
412 let inst = RecordInstance::new("TS:DB".into(), TimestampRecord::default());
413 assert_eq!(inst.resolve_field(""), None);
414 }
415}