epics-base-rs 0.20.2

Pure Rust EPICS IOC core — record system, database, iocsh, calc engine
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
use crate::error::CaResult;
use crate::server::record::{AlarmSeverity, ProcessAction, Record, RecordInstance, ScanType};

/// Check if a DTYP string represents a soft/built-in device support
/// that doesn't require an explicit device support registration.
/// Matches C EPICS built-in soft device support names.
pub fn is_soft_dtyp(dtyp: &str) -> bool {
    dtyp.is_empty()
        || dtyp == "Soft Channel"
        || dtyp == "Raw Soft Channel"
        || dtyp == "Async Soft Channel"
        || dtyp == "Soft Timestamp"
        || dtyp == "Sec Past Epoch"
}

/// Handle for waiting on asynchronous write completion.
/// Returned by [`DeviceSupport::write_begin`] when the write is submitted
/// to a worker queue rather than executed synchronously.
pub trait WriteCompletion: Send + 'static {
    /// Block until the write completes or timeout expires.
    fn wait(&self, timeout: std::time::Duration) -> CaResult<()>;
}

/// Outcome of a device support read() call.
///
/// Allows device support to return side-effect actions (link writes,
/// delayed reprocess) and signal that it has already performed the
/// Result of a device support `read()` call.
///
/// # `ok()` vs `computed()`
///
/// This mirrors the C EPICS `read_ai()` return convention:
///
/// - **`ok()`** (C return 0): Device support wrote to RVAL. The record's
///   `process()` will run its built-in conversion (e.g., ai applies
///   `ROFF → ASLO/AOFF → LINR/ESLO/EOFF → smoothing` to produce VAL
///   from RVAL).
///
/// - **`computed()`** (C return 2): Device support wrote to VAL directly.
///   The record's `process()` will **skip** its conversion and use the
///   VAL as-is. Use this when the device support provides engineering
///   units directly (e.g., soft channel, asyn, custom drivers that
///   call `record.put_field("VAL", ...)`).
///
/// **Common mistake:** returning `ok()` when VAL is set directly causes
/// the record's conversion to overwrite VAL with a value derived from
/// RVAL (typically 0), making the read appear broken.
#[derive(Default)]
pub struct DeviceReadOutcome {
    /// Actions for the framework to execute (WriteDbLink, ReprocessAfter, etc.)
    pub actions: Vec<ProcessAction>,
    /// If true, the record's built-in conversion (e.g., ai RVAL→VAL)
    /// is skipped. Set this when device support writes VAL directly.
    pub did_compute: bool,
}

impl DeviceReadOutcome {
    /// Device support wrote RVAL; record will run its conversion to produce VAL.
    ///
    /// C equivalent: `read_ai()` returns 0.
    pub fn ok() -> Self {
        Self::default()
    }

    /// Device support wrote VAL directly; record will skip conversion.
    ///
    /// C equivalent: `read_ai()` returns 2.
    pub fn computed() -> Self {
        Self {
            did_compute: true,
            actions: Vec::new(),
        }
    }

    /// Shorthand for a computed read with actions.
    pub fn computed_with(actions: Vec<ProcessAction>) -> Self {
        Self {
            did_compute: true,
            actions,
        }
    }
}

/// Trait for custom device support implementations.
/// When DTYP is set to something other than "" or "Soft Channel",
/// the registered DeviceSupport is used instead of link resolution.
pub trait DeviceSupport: Send + Sync + 'static {
    fn init(&mut self, _record: &mut dyn Record) -> CaResult<()> {
        Ok(())
    }

    /// Read from hardware into the record.
    ///
    /// Returns a `DeviceReadOutcome` containing:
    /// - `actions`: side-effect actions (link writes, delayed reprocess)
    ///   that the framework will execute after process()
    /// - `did_compute`: if true, the record's built-in compute was already
    ///   performed (e.g., device support ran PID), so process() should skip it
    fn read(&mut self, record: &mut dyn Record) -> CaResult<DeviceReadOutcome> {
        let _ = record;
        Ok(DeviceReadOutcome::ok())
    }

    fn write(&mut self, record: &mut dyn Record) -> CaResult<()>;
    fn dtyp(&self) -> &str;

    /// Return the last alarm (status, severity) from the driver.
    /// None means the driver does not override alarms.
    fn last_alarm(&self) -> Option<(u16, u16)> {
        None
    }

    /// Return the last timestamp from the driver.
    /// None means the driver does not override timestamps.
    fn last_timestamp(&self) -> Option<std::time::SystemTime> {
        None
    }

    /// Return the userTag the driver attached to its reading, as the
    /// 64-bit `epicsUTag`. `None` means the driver provides no userTag
    /// and `common.utag` is left untouched.
    ///
    /// This is the channel a timing receiver (event system) uses to
    /// deliver a pulse-id / event tag: `epicsTimeStamp` itself carries
    /// no tag and the generalTime event path (`epicsTimeGetEvent`)
    /// delivers only the timestamp, so the tag must come through device
    /// support — mirroring C device support writing `prec->utag`
    /// directly during `read()` (alongside `prec->time`, TSE=-2).
    fn last_utag(&self) -> Option<u64> {
        None
    }

    /// Called by the framework immediately before [`read()`](DeviceSupport::read)
    /// to push a read-only snapshot of framework-owned `CommonFields`
    /// state ([`crate::server::record::ProcessContext`]) that the device
    /// support needs.
    ///
    /// `read()` receives only `&mut dyn Record`; it cannot reach
    /// `RecordInstance.common`. C device support reads `dbCommon`
    /// directly — `devTimeOfDay.c:122` selects its time format from
    /// `psi->phas`. A driver that needs `phas`/`udf`/`tse`/`tsel`
    /// overrides this to stash the values before `read()` runs.
    ///
    /// Additive framework-set-hook (same shape as
    /// [`DeviceSupport::set_record_info`]). Default: ignore.
    fn set_process_context(&mut self, _ctx: &crate::server::record::ProcessContext) {}

    /// Called after init() with the record name and scan type.
    fn set_record_info(&mut self, _name: &str, _scan: ScanType) {}

    /// Forward parsed `info("key", "value")` directives from the .db
    /// file to the device support. Default is a no-op; drivers that
    /// react to specific tags (asyn `asyn:READBACK`, EtherCAT terminal
    /// hints, etc.) override this. Called once after `set_record_info`
    /// during builder wiring; not called again at runtime.
    fn apply_record_info(&mut self, _info: &std::collections::HashMap<String, String>) {}

    /// Return a receiver for I/O Intr scan notifications.
    /// Called for records with `SCAN="I/O Intr"`, and for any device that
    /// reports [`io_intr_scan_independent`](Self::io_intr_scan_independent).
    fn io_intr_receiver(&mut self) -> Option<crate::runtime::sync::mpsc::Receiver<()>> {
        None
    }

    /// Return a receiver of out-of-band PROPERTY-class field posts.
    ///
    /// C parity: `registerInterruptUser(callbackEnum)` (devAsynInt32.c:319)
    /// plus the per-record enum callback
    /// (`interruptCallbackEnumMbbi`/`…Bi`, devAsynInt32.c:711-762), which
    /// calls `setEnums` to re-key the record's state strings/values/
    /// severities and then `db_post_events(precord, &precord->val,
    /// DBE_PROPERTY)` so CA/PVA clients re-read the enum choices. This is
    /// driven by the driver's `doCallbacksEnum`, independent of the
    /// record's `SCAN` (it is not a value scan, so it does not process the
    /// record).
    ///
    /// Each delivered message is the full `(field, value)` set to
    /// write-and-post (the C `setEnums` field block). The framework drains
    /// this receiver and calls
    /// [`crate::server::database::PvDatabase::post_property_fields`].
    /// Mirrors [`io_intr_receiver`](Self::io_intr_receiver): the device owns
    /// the source subscription, the framework owns the post. Default:
    /// `None` (device drives no property posts).
    fn property_post_receiver(
        &mut self,
    ) -> Option<crate::runtime::sync::mpsc::Receiver<Vec<(String, crate::types::EpicsValue)>>> {
        None
    }

    /// Whether this device drives record processing from its own callback
    /// channel independently of the runtime `SCAN` menu.
    ///
    /// C parity: a `motorRecord` device callback (`statusCallback`) does its
    /// own `dbScanLock` + `dbProcess` on every poll readback regardless of
    /// `SCAN`, and the record stays `SCAN="Passive"` so a `dbPutField` to a
    /// `pp(TRUE)` field (VAL/DVAL/...) still re-processes it
    /// (`dbAccess.c:1263-1268`). asyn readback records behave the same way
    /// (upstream PRs #60/#208 — output records follow driver-side changes
    /// regardless of `SCAN`).
    ///
    /// When `true`, the I/O Intr wiring processes the record on every pulse
    /// even when `SCAN != "I/O Intr"`. When `false` (default), processing is
    /// gated on the record's current `SCAN` being `"I/O Intr"`, matching C
    /// `scanIoRequest`, which honors scan-list membership.
    fn io_intr_scan_independent(&self) -> bool {
        false
    }

    /// Begin an asynchronous write (submit only, no blocking).
    /// Returns `Some(handle)` if the write was submitted to a worker queue —
    /// the caller should wait on the handle outside any record lock.
    /// Returns `None` to fall back to synchronous [`write()`](DeviceSupport::write).
    fn write_begin(
        &mut self,
        _record: &mut dyn Record,
    ) -> CaResult<Option<Box<dyn WriteCompletion>>> {
        Ok(None)
    }

    /// Handle a named command from the record's process() via
    /// `ProcessAction::DeviceCommand`. This allows records to request
    /// driver operations (e.g., scaler reset/arm/write_preset) without
    /// holding a direct driver reference.
    ///
    /// `handle_command` runs AFTER the process snapshot has already been
    /// built and notified, so any record field it mutates would not be
    /// diffed by the snapshot path. The returned `Vec` names the record
    /// fields the command changed; the framework posts a `DBE_VALUE`
    /// monitor event for each, mirroring the explicit `db_post_events`
    /// calls a C record makes from inside `process()` (e.g.
    /// `scalerRecord.c:425-430` posts PR1/TP/FREQ after the driver
    /// write-back). Return an empty `Vec` when no record field changed.
    ///
    /// Default: ignore, no fields changed.
    fn handle_command(
        &mut self,
        _record: &mut dyn Record,
        _command: &str,
        _args: &[crate::types::EpicsValue],
    ) -> CaResult<Vec<&'static str>> {
        Ok(Vec::new())
    }
}

/// Canonical device-support init sequence — the single owner of the
/// "attach device support to a record" contract.
///
/// Both build paths ([`crate::server::ioc_app::wire_device_support`]
/// and [`crate::server::ioc_builder::IocBuilder::build`]) MUST call
/// this so a driver author can write one correct `init()`.
///
/// Order (C parity — `recGblInitConstantLink`-style field setup runs
/// before `init_record`; `set_record_info` / `apply_record_info` are
/// Rust extensions that supply that field context and therefore
/// precede `init`):
///
/// 1. `set_record_info(name, scan)` — give the driver its record
///    identity and scan mode.
/// 2. `apply_record_info(info)` — forward `info(...)` tags so a
///    driver that reads them inside `init()` sees a populated map.
/// 3. `init(record)` — driver `init_record` equivalent.
///
/// On `init()` failure the record is flagged `INVALID` severity with
/// a `SOFT` status and a diagnostic is logged — matching C
/// `initDevSup`/`init_record` failure handling (the record is marked,
/// not silently attached as healthy). On success, UDF is cleared if
/// the driver produced a value.
///
/// The device is attached (`instance.device = Some(dev)`) regardless
/// of init outcome so the record is addressable; a failed init leaves
/// the alarm set.
pub fn wire_device_to_record(instance: &mut RecordInstance, mut dev: Box<dyn DeviceSupport>) {
    let name = instance.name.clone();
    dev.set_record_info(&name, instance.common.scan);
    dev.apply_record_info(&instance.info);
    match dev.init(&mut *instance.record) {
        Ok(()) => {
            // Clear UDF if init successfully produced a value
            // (e.g. an initial readback).
            if instance.record.val().is_some() {
                instance.common.udf = false;
            }
        }
        Err(e) => {
            eprintln!(
                "device support init failed for record '{name}' (DTYP '{}'): {e}",
                instance.common.dtyp
            );
            // Flag the record so the failure is observable rather
            // than presenting a healthy-looking record.
            instance.common.sevr = AlarmSeverity::Invalid;
            instance.common.stat = crate::server::recgbl::alarm_status::SOFT_ALARM;
        }
    }
    instance.device = Some(dev);
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::error::CaError;
    use crate::server::record::{AlarmSeverity, Record, RecordInstance, ScanType};
    use crate::server::records::ai::AiRecord;
    use std::collections::HashMap;
    use std::sync::{Arc, Mutex};

    /// Observed wiring state, shared with the test via `Arc` so it is
    /// inspectable after the device is moved into the record.
    #[derive(Default)]
    struct WireObservation {
        /// Info keys visible to `init()`.
        info_at_init: Vec<String>,
        /// Whether `set_record_info` ran before `init()`.
        record_info_before_init: bool,
        /// Whether `set_record_info` had run by the time `init` ran.
        init_ran: bool,
    }

    /// Device support that records the wiring order and fails `init`.
    struct ProbeDev {
        obs: Arc<Mutex<WireObservation>>,
        info: HashMap<String, String>,
        record_info_set: bool,
        fail_init: bool,
    }
    impl DeviceSupport for ProbeDev {
        fn dtyp(&self) -> &str {
            "ProbeDev"
        }
        fn write(&mut self, _record: &mut dyn Record) -> CaResult<()> {
            Ok(())
        }
        fn set_record_info(&mut self, _name: &str, _scan: ScanType) {
            self.record_info_set = true;
        }
        fn apply_record_info(&mut self, info: &HashMap<String, String>) {
            self.info = info.clone();
        }
        fn init(&mut self, _record: &mut dyn Record) -> CaResult<()> {
            let mut o = self.obs.lock().unwrap();
            o.init_ran = true;
            o.record_info_before_init = self.record_info_set;
            o.info_at_init = self.info.keys().cloned().collect();
            if self.fail_init {
                Err(CaError::InvalidValue("device init failed".into()))
            } else {
                Ok(())
            }
        }
    }

    /// M2 regression: a device support whose `init()` returns `Err`
    /// must NOT be attached as a healthy record — the record is
    /// flagged INVALID severity with a SOFT status. (Pre-fix the
    /// IocBuilder path discarded the error with `let _ =`.)
    #[test]
    fn wire_device_init_failure_flags_record_invalid() {
        let mut instance = RecordInstance::new("TEST:AI".to_string(), AiRecord::new(0.0));
        instance.common.dtyp = "ProbeDev".to_string();
        let obs = Arc::new(Mutex::new(WireObservation::default()));
        let dev = Box::new(ProbeDev {
            obs: obs.clone(),
            info: HashMap::new(),
            record_info_set: false,
            fail_init: true,
        });

        wire_device_to_record(&mut instance, dev);

        assert_eq!(
            instance.common.sevr,
            AlarmSeverity::Invalid,
            "failed device init must flag the record INVALID"
        );
        assert_eq!(
            instance.common.stat,
            crate::server::recgbl::alarm_status::SOFT_ALARM,
        );
        assert!(
            instance.device.is_some(),
            "device is still attached so the record is addressable"
        );
    }

    /// M1 regression: the canonical wiring order is
    /// set_record_info → apply_record_info → init. A driver reading
    /// `info(...)` tags inside `init()` must see a populated map, and
    /// `set_record_info` must have run first.
    #[test]
    fn wire_device_applies_info_and_record_info_before_init() {
        let mut instance = RecordInstance::new("TEST:AI2".to_string(), AiRecord::new(0.0));
        instance.common.dtyp = "ProbeDev".to_string();
        instance.set_info("asyn:READBACK", "1");
        let obs = Arc::new(Mutex::new(WireObservation::default()));
        let dev = Box::new(ProbeDev {
            obs: obs.clone(),
            info: HashMap::new(),
            record_info_set: false,
            fail_init: false,
        });

        wire_device_to_record(&mut instance, dev);

        let o = obs.lock().unwrap();
        assert!(o.init_ran, "init must have run");
        assert!(
            o.record_info_before_init,
            "set_record_info must run before init"
        );
        assert!(
            o.info_at_init.iter().any(|k| k == "asyn:READBACK"),
            "info(...) tags must be visible inside init()"
        );
    }
}