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
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
use crate::calc::StringInputs;
use crate::calc::engine::value::StackValue;
use crate::calc::{CompiledExpr, scalc_compile, scalc_eval};
use crate::error::{CaError, CaResult};
use crate::server::record::{
FieldDesc, ProcessAction, ProcessOutcome, Record, RecordProcessResult,
};
use crate::types::{DbFieldType, EpicsValue};
// swait (string wait) record from synApps calc module.
// Functionally equivalent to scalcout, but uses INxN/INxP naming for input links
// (INxN = link name, INxP = process passive flag) instead of INPx.
// Supports 12 numeric inputs (A-L), a CALC expression, and a single output link.
// DOL/DOLD: desired output; DOPT: 0=use CALC, 1=use DOLD; OOPT: output condition.
pub struct SwaitRecord {
pub val: f64,
pub calc: String,
compiled_calc: Option<CompiledExpr>,
pub oopt: i16,
pub dopt: i16,
pub dold: f64,
pub oval: f64,
// OEVT ("Output Event") — C `swaitRecord.c` `pwait->oevt` (DBF_USHORT).
// When output fires and `oevt > 0`, `execOutput` posts the numeric
// software event (`post_event((int)oevt)`, swaitRecord.c:797); see
// [`Record::output_event`]. swait has no IVOA field, so the post is
// never suppressed by the framework Don't_drive veto.
pub oevt: u16,
// ODLY ("Output Execute Delay", seconds) — C `swaitRecord.c` `pwait->odly`
// (DBF_FLOAT). When output fires and `odly > 0`, `schedOutput`
// (swaitRecord.c:719) defers the OUT write + forward link + OEVT post by
// `odly` seconds via the watchdog, holding the record active (PACT=1); when
// `odly == 0` it calls `execOutput` immediately. `f32` mirrors the C
// `float` field so a CA client sees DBR_FLOAT (not DBR_DOUBLE).
pub odly: f32,
pub out: String,
pub prec: i16,
// INxN: input link names; INxP: process passive flags (0/1)
pub inp_names: [String; 12], // INAN..INLN
pub inp_passive: [i16; 12], // INAP..INLP
// numeric input values A-L
pub num_vals: [f64; 12],
prev_val: f64,
cached_should_output: bool,
// ODLY delay state (C `cbStruct.outputWait`, an internal flag — swait has
// no DLYA database field, unlike scalcout). `output_wait` marks that the
// current `process()` call is the watchdog continuation re-entry; on it the
// captured `pending_output` decision is restored so the framework writes
// OUT + posts OEVT exactly once after the delay.
output_wait: bool,
pending_output: bool,
}
impl Default for SwaitRecord {
fn default() -> Self {
Self {
val: 0.0,
calc: String::new(),
compiled_calc: None,
oopt: 0,
dopt: 0,
dold: 0.0,
oval: 0.0,
oevt: 0,
odly: 0.0,
out: String::new(),
prec: 0,
inp_names: Default::default(),
inp_passive: [0; 12],
num_vals: [0.0; 12],
prev_val: 0.0,
cached_should_output: true,
output_wait: false,
pending_output: false,
}
}
}
// Channel letters A-L in order
const CHAN: [char; 12] = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L'];
impl SwaitRecord {
fn recompile(&mut self) {
self.compiled_calc = scalc_compile(&self.calc).ok();
}
fn build_inputs(&self) -> StringInputs {
let mut inputs = StringInputs::new();
for i in 0..12 {
inputs.num_vars[i] = self.num_vals[i];
}
inputs
}
fn eval_should_output(&self) -> bool {
match self.oopt {
0 => true,
1 => self.val != self.prev_val,
2 => self.val == 0.0,
3 => self.val != 0.0,
4 => self.prev_val != 0.0 && self.val == 0.0,
5 => self.prev_val == 0.0 && self.val != 0.0,
_ => false,
}
}
fn inp_name_index(name: &str) -> Option<usize> {
// INxN: INAN, INBN, INCN, INDN, INEN, INFN, INGN, INHN, ININ, INJN, INKN, INLN
let bytes = name.as_bytes();
if bytes.len() == 4 && bytes[0] == b'I' && bytes[1] == b'N' && bytes[3] == b'N' {
CHAN.iter().position(|&c| c == bytes[2] as char)
} else {
None
}
}
fn inp_passive_index(name: &str) -> Option<usize> {
// INxP: INAP, INBP, INCP, ...
let bytes = name.as_bytes();
if bytes.len() == 4 && bytes[0] == b'I' && bytes[1] == b'N' && bytes[3] == b'P' {
CHAN.iter().position(|&c| c == bytes[2] as char)
} else {
None
}
}
fn num_val_index(name: &str) -> Option<usize> {
// Single letter A-L
if name.len() == 1 {
CHAN.iter().position(|&c| c.to_string() == name)
} else {
None
}
}
}
static SWAIT_FIELDS_SCALAR: &[FieldDesc] = &[
FieldDesc {
name: "VAL",
dbf_type: DbFieldType::Double,
read_only: false,
},
FieldDesc {
name: "CALC",
dbf_type: DbFieldType::String,
read_only: false,
},
FieldDesc {
name: "OOPT",
dbf_type: DbFieldType::Short,
read_only: false,
},
FieldDesc {
name: "DOPT",
dbf_type: DbFieldType::Short,
read_only: false,
},
FieldDesc {
name: "DOLD",
dbf_type: DbFieldType::Double,
read_only: false,
},
FieldDesc {
name: "OVAL",
dbf_type: DbFieldType::Double,
read_only: true,
},
FieldDesc {
name: "OEVT",
dbf_type: DbFieldType::UShort,
read_only: false,
},
FieldDesc {
name: "ODLY",
dbf_type: DbFieldType::Float,
read_only: false,
},
// OUT and OUTN are intentionally absent: both route to RecordInstance::common.out
// via put_common_field so that parsed_out is populated for output dispatch.
// OUTN is swait's output link field name; RecordInstance handles the alias.
FieldDesc {
name: "PREC",
dbf_type: DbFieldType::Short,
read_only: false,
},
FieldDesc {
name: "A",
dbf_type: DbFieldType::Double,
read_only: false,
},
FieldDesc {
name: "B",
dbf_type: DbFieldType::Double,
read_only: false,
},
FieldDesc {
name: "C",
dbf_type: DbFieldType::Double,
read_only: false,
},
FieldDesc {
name: "D",
dbf_type: DbFieldType::Double,
read_only: false,
},
FieldDesc {
name: "E",
dbf_type: DbFieldType::Double,
read_only: false,
},
FieldDesc {
name: "F",
dbf_type: DbFieldType::Double,
read_only: false,
},
FieldDesc {
name: "G",
dbf_type: DbFieldType::Double,
read_only: false,
},
FieldDesc {
name: "H",
dbf_type: DbFieldType::Double,
read_only: false,
},
FieldDesc {
name: "I",
dbf_type: DbFieldType::Double,
read_only: false,
},
FieldDesc {
name: "J",
dbf_type: DbFieldType::Double,
read_only: false,
},
FieldDesc {
name: "K",
dbf_type: DbFieldType::Double,
read_only: false,
},
FieldDesc {
name: "L",
dbf_type: DbFieldType::Double,
read_only: false,
},
FieldDesc {
name: "INAN",
dbf_type: DbFieldType::String,
read_only: false,
},
FieldDesc {
name: "INBN",
dbf_type: DbFieldType::String,
read_only: false,
},
FieldDesc {
name: "INCN",
dbf_type: DbFieldType::String,
read_only: false,
},
FieldDesc {
name: "INDN",
dbf_type: DbFieldType::String,
read_only: false,
},
FieldDesc {
name: "INEN",
dbf_type: DbFieldType::String,
read_only: false,
},
FieldDesc {
name: "INFN",
dbf_type: DbFieldType::String,
read_only: false,
},
FieldDesc {
name: "INGN",
dbf_type: DbFieldType::String,
read_only: false,
},
FieldDesc {
name: "INHN",
dbf_type: DbFieldType::String,
read_only: false,
},
FieldDesc {
name: "ININ",
dbf_type: DbFieldType::String,
read_only: false,
},
FieldDesc {
name: "INJN",
dbf_type: DbFieldType::String,
read_only: false,
},
FieldDesc {
name: "INKN",
dbf_type: DbFieldType::String,
read_only: false,
},
FieldDesc {
name: "INLN",
dbf_type: DbFieldType::String,
read_only: false,
},
FieldDesc {
name: "INAP",
dbf_type: DbFieldType::Short,
read_only: false,
},
FieldDesc {
name: "INBP",
dbf_type: DbFieldType::Short,
read_only: false,
},
FieldDesc {
name: "INCP",
dbf_type: DbFieldType::Short,
read_only: false,
},
FieldDesc {
name: "INDP",
dbf_type: DbFieldType::Short,
read_only: false,
},
FieldDesc {
name: "INEP",
dbf_type: DbFieldType::Short,
read_only: false,
},
FieldDesc {
name: "INFP",
dbf_type: DbFieldType::Short,
read_only: false,
},
FieldDesc {
name: "INGP",
dbf_type: DbFieldType::Short,
read_only: false,
},
FieldDesc {
name: "INHP",
dbf_type: DbFieldType::Short,
read_only: false,
},
FieldDesc {
name: "INIP",
dbf_type: DbFieldType::Short,
read_only: false,
},
FieldDesc {
name: "INJP",
dbf_type: DbFieldType::Short,
read_only: false,
},
FieldDesc {
name: "INKP",
dbf_type: DbFieldType::Short,
read_only: false,
},
FieldDesc {
name: "INLP",
dbf_type: DbFieldType::Short,
read_only: false,
},
];
/// Choice labels for the `swait` output-execute-option menu, in index
/// order. C `menu(swaitOOPT)` (`swaitRecord.dbd`): the six `longoutOOPT`
/// choices plus a trailing "Never" (index 6) that suppresses output.
const SWAIT_OOPT_CHOICES: &[&str] = &[
"Every Time",
"On Change",
"When Zero",
"When Non-zero",
"Transition To Zero",
"Transition To Non-zero",
"Never",
];
/// Choice labels for the `swait` output-data-option menu, in index order.
/// C `menu(swaitDOPT)` (`swaitRecord.dbd`): 0="Use VAL" (the calculated
/// result), 1="Use DOL" (the value fetched through the `DOL` link).
const SWAIT_DOPT_CHOICES: &[&str] = &["Use VAL", "Use DOL"];
impl Record for SwaitRecord {
fn record_type(&self) -> &'static str {
"swait"
}
fn field_list(&self) -> &'static [FieldDesc] {
SWAIT_FIELDS_SCALAR
}
/// Record-specific `DBF_MENU` fields, served as `DBR_ENUM` with the
/// menu's choice labels in `.dbd` index order (`swaitRecord.dbd`):
/// `OOPT` is `menu(swaitOOPT)`, `DOPT` is `menu(swaitDOPT)`.
fn menu_field_choices(&self, field: &str) -> Option<&'static [&'static str]> {
match field {
"OOPT" => Some(SWAIT_OOPT_CHOICES),
"DOPT" => Some(SWAIT_DOPT_CHOICES),
_ => None,
}
}
fn uses_monitor_deadband(&self) -> bool {
true
}
fn init_record(&mut self, pass: u8) -> CaResult<()> {
if pass == 0 {
self.recompile();
}
Ok(())
}
fn process(&mut self) -> CaResult<ProcessOutcome> {
// ODLY continuation: this is the watchdog re-process scheduled by a
// previous cycle (C `swaitRecord.c::process` `if (pact && outputWait)
// execOutput`, line 394). Do NOT re-evaluate CALC / OOPT — C runs
// `execOutput` directly. Restore the captured output decision so the
// framework writes the OUT link + posts OEVT this cycle, then clear the
// wait flag. Mirrors scalcout's `dlya == 1` branch (swait has no DLYA
// field — the wait state is the internal `output_wait` flag, as C uses
// `cbStruct.outputWait`).
if self.output_wait {
self.output_wait = false;
self.cached_should_output = self.pending_output;
self.pending_output = false;
return Ok(ProcessOutcome::complete());
}
self.prev_val = self.val;
if let Some(ref compiled) = self.compiled_calc {
let mut inputs = self.build_inputs();
if let Ok(result) = scalc_eval(compiled, &mut inputs) {
self.val = match result {
StackValue::Double(v) => v,
StackValue::Str(s) => s.parse::<f64>().unwrap_or(0.0),
};
}
}
// Cache before framework calls should_output() via trait dispatch.
self.cached_should_output = self.eval_should_output();
if self.cached_should_output {
self.oval = if self.dopt == 1 { self.dold } else { self.val };
}
// ODLY (C `swaitRecord.c::schedOutput`, lines 719-729): when output
// should fire and ODLY > 0, defer ONLY the OUT write + OEVT + forward
// link by ODLY seconds via the watchdog, holding the record active
// (C keeps PACT=1). The value side (VAL + changed inputs + alarm fields)
// is NOT deferred: C `process` calls `monitor()` (line 475) on THIS
// (delay-start) cycle, before returning async — only `execOutput`
// (delay-end) is delayed, and it posts no monitors. The delaying cycle
// captures the output decision and suppresses this cycle's OUT/OEVT
// (`cached_should_output = false`), then re-processes after the delay;
// the `output_wait` branch above emits the output exactly once.
if self.cached_should_output && self.odly > 0.0 {
self.pending_output = self.cached_should_output;
self.output_wait = true;
self.cached_should_output = false;
let delay = std::time::Duration::from_secs_f64(self.odly as f64);
// `CompleteDeferOutput`, NOT bare `AsyncPending`: swait posts the
// value side at the START of the delay (C `monitor()` at line 475,
// reached because `schedOutput` set `async=TRUE` but `process` falls
// through to `monitor()` before the `if(!async)` forward-link tail).
// The framework therefore runs its full monitor epilogue this cycle
// (VAL with MDEL/ADEL deadband + alarm mask, changed inputs) and
// defers only the OUT/OEVT/FLNK tail, holding PACT for the watchdog
// window via the `ReprocessAfter` continuation that releases it —
// matching C `swaitRecord.c:716` "THE RECORD REMAINS ACTIVE WHILE
// WAITING ON THE WATCHDOG". A bare `AsyncPending` would have deferred
// the value side to delay-end too (the calcout/scalcout/acalcout
// shape, whose C `process` returns BEFORE `monitor()`); swait's C
// does not, so VAL must post now.
return Ok(ProcessOutcome {
result: RecordProcessResult::CompleteDeferOutput,
actions: vec![ProcessAction::ReprocessAfter(delay)],
device_did_compute: false,
});
}
Ok(ProcessOutcome::complete())
}
fn should_output(&self) -> bool {
self.cached_should_output
}
/// `OEVT` ("Output Event"): post the numeric output event when output
/// fires. C `swaitRecord.c` `execOutput` runs `if (pwait->oevt > 0)
/// post_event((int)pwait->oevt);` (swaitRecord.c:797) right after the OUT
/// write / forward link, on every cycle where output fires
/// (`cached_should_output`). swait has no IVOA field, so — like its C —
/// the post is never IVOA-suppressed. Stringified so the numeric event
/// matches a `SCAN="Event"` record's `EVNT`.
fn output_event(&self) -> Option<String> {
if self.cached_should_output && self.oevt > 0 {
Some(self.oevt.to_string())
} else {
None
}
}
fn val(&self) -> Option<EpicsValue> {
Some(EpicsValue::Double(self.val))
}
fn get_field(&self, name: &str) -> Option<EpicsValue> {
match name {
"VAL" => Some(EpicsValue::Double(self.val)),
"CALC" => Some(EpicsValue::String(self.calc.clone().into())),
"OOPT" => Some(EpicsValue::Short(self.oopt)),
"DOPT" => Some(EpicsValue::Short(self.dopt)),
"DOLD" => Some(EpicsValue::Double(self.dold)),
"OVAL" => Some(EpicsValue::Double(self.oval)),
"OEVT" => Some(EpicsValue::UShort(self.oevt)),
"ODLY" => Some(EpicsValue::Float(self.odly)),
// OUTN is aliased to common.out via RecordInstance; not stored locally.
"PREC" => Some(EpicsValue::Short(self.prec)),
_ => {
if let Some(idx) = Self::num_val_index(name) {
return Some(EpicsValue::Double(self.num_vals[idx]));
}
if let Some(idx) = Self::inp_name_index(name) {
return Some(EpicsValue::String(self.inp_names[idx].clone().into()));
}
if let Some(idx) = Self::inp_passive_index(name) {
return Some(EpicsValue::Short(self.inp_passive[idx]));
}
None
}
}
}
fn put_field(&mut self, name: &str, value: EpicsValue) -> CaResult<()> {
match name {
"VAL" => {
self.val = value
.to_f64()
.ok_or_else(|| CaError::TypeMismatch("VAL".into()))?;
}
"CALC" => {
if let EpicsValue::String(s) = value {
self.calc = s.as_str_lossy().into_owned();
self.recompile();
} else {
return Err(CaError::TypeMismatch("CALC".into()));
}
}
"OOPT" => {
if let EpicsValue::Short(v) = value {
self.oopt = v;
}
}
"DOPT" => {
if let EpicsValue::Short(v) = value {
self.dopt = v;
}
}
"DOLD" => {
self.dold = value
.to_f64()
.ok_or_else(|| CaError::TypeMismatch("DOLD".into()))?;
}
"OEVT" => {
self.oevt = value
.to_f64()
.ok_or_else(|| CaError::TypeMismatch("OEVT".into()))?
as u16;
}
"ODLY" => {
self.odly = value
.to_f64()
.ok_or_else(|| CaError::TypeMismatch("ODLY".into()))?
as f32;
}
// OUTN falls through to put_common_field which mirrors to common.out.
"PREC" => {
if let EpicsValue::Short(v) = value {
self.prec = v;
}
}
_ => {
if let Some(idx) = Self::num_val_index(name) {
self.num_vals[idx] = value
.to_f64()
.ok_or_else(|| CaError::TypeMismatch(name.into()))?;
} else if let Some(idx) = Self::inp_name_index(name) {
if let EpicsValue::String(s) = value {
self.inp_names[idx] = s.as_str_lossy().into_owned();
} else {
return Err(CaError::TypeMismatch(name.into()));
}
} else if let Some(idx) = Self::inp_passive_index(name) {
if let EpicsValue::Short(v) = value {
self.inp_passive[idx] = v;
} else {
return Err(CaError::TypeMismatch(name.into()));
}
} else {
return Err(CaError::FieldNotFound(name.to_string()));
}
}
}
Ok(())
}
fn multi_input_links(&self) -> &[(&'static str, &'static str)] {
&[
("INAN", "A"),
("INBN", "B"),
("INCN", "C"),
("INDN", "D"),
("INEN", "E"),
("INFN", "F"),
("INGN", "G"),
("INHN", "H"),
("ININ", "I"),
("INJN", "J"),
("INKN", "K"),
("INLN", "L"),
]
}
}