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
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
use std::collections::HashMap;
use std::sync::Arc;
use std::sync::atomic::AtomicBool;
use crate::runtime::sync::mpsc;
use crate::error::{CaError, CaResult};
use crate::server::pv::{MonitorEvent, Subscriber};
use crate::types::{DbFieldType, EpicsValue};
use super::alarm::{AlarmSeverity, AnalogAlarmConfig};
use super::common_fields::CommonFields;
use super::link::{ParsedLink, parse_link_v2};
use super::record_trait::{
CommonFieldPutResult, ProcessSnapshot, Record, RecordProcessResult, SubroutineFn,
};
use super::scan::ScanType;
/// A type-erased record instance stored in the database.
pub struct RecordInstance {
pub name: String,
pub record: Box<dyn Record>,
pub common: CommonFields,
pub subscribers: HashMap<String, Vec<Subscriber>>,
// Link parse cache
pub parsed_inp: ParsedLink,
pub parsed_out: ParsedLink,
pub parsed_flnk: ParsedLink,
pub parsed_sdis: ParsedLink,
pub parsed_tsel: ParsedLink,
// Device support
pub device: Option<Box<dyn super::super::device_support::DeviceSupport>>,
// Subroutine (for sub records)
pub subroutine: Option<Arc<SubroutineFn>>,
// Re-entrancy guard
pub processing: AtomicBool,
// Deferred put_notify completion (fires when async processing completes)
pub put_notify_tx: Option<crate::runtime::sync::oneshot::Sender<()>>,
// Last posted values for subscribed fields (generic change detection)
pub last_posted: HashMap<String, EpicsValue>,
/// Generation counter for ReprocessAfter timer cancellation.
/// Bumped each process cycle. Spawned timers check this to avoid
/// stale re-processes from accumulated timers.
pub reprocess_generation: Arc<std::sync::atomic::AtomicU64>,
}
impl RecordInstance {
pub fn new(name: String, record: impl Record) -> Self {
Self::new_boxed(name, Box::new(record))
}
pub fn new_boxed(name: String, record: Box<dyn Record>) -> Self {
let rtype = record.record_type();
let analog_alarm = match rtype {
"ai" | "ao" | "longin" | "longout" => Some(AnalogAlarmConfig::default()),
_ => None,
};
let mut common = CommonFields::default();
common.analog_alarm = analog_alarm;
Self {
name,
record,
common,
subscribers: HashMap::new(),
parsed_inp: ParsedLink::None,
parsed_out: ParsedLink::None,
parsed_flnk: ParsedLink::None,
parsed_sdis: ParsedLink::None,
parsed_tsel: ParsedLink::None,
device: None,
subroutine: None,
processing: AtomicBool::new(false),
put_notify_tx: None,
last_posted: HashMap::new(),
reprocess_generation: Arc::new(std::sync::atomic::AtomicU64::new(0)),
}
}
/// Check if the record is currently processing (PACT equivalent).
pub fn is_processing(&self) -> bool {
self.processing.load(std::sync::atomic::Ordering::Acquire)
}
/// Unified field resolution: record fields → common fields → virtual fields.
pub fn resolve_field(&self, name: &str) -> Option<EpicsValue> {
let name = name.to_ascii_uppercase();
self.record
.get_field(&name)
.or_else(|| self.get_common_field(&name))
.or_else(|| self.get_virtual_field(&name))
}
/// Build a Snapshot with full metadata for the given field.
pub fn snapshot_for_field(&self, field: &str) -> Option<super::super::snapshot::Snapshot> {
let value = self.resolve_field(field)?;
let mut snap = super::super::snapshot::Snapshot::new(
value,
self.common.stat,
self.common.sevr as u16,
self.common.time,
);
self.populate_display_info(&mut snap);
self.populate_control_info(&mut snap);
self.populate_enum_info(&mut snap);
self.populate_common_enum_info(field, &mut snap);
Some(snap)
}
/// Populate DisplayInfo from record fields if applicable.
fn populate_display_info(&self, snap: &mut super::super::snapshot::Snapshot) {
let rtype = self.record.record_type();
match rtype {
"ai" | "ao" | "calc" | "calcout" => {
let egu = self
.record
.get_field("EGU")
.and_then(|v| {
if let EpicsValue::String(s) = v {
Some(s)
} else {
None
}
})
.unwrap_or_default();
let prec = self
.record
.get_field("PREC")
.and_then(|v| v.to_f64())
.unwrap_or(0.0) as i16;
let hopr = self
.record
.get_field("HOPR")
.and_then(|v| v.to_f64())
.unwrap_or(0.0);
let lopr = self
.record
.get_field("LOPR")
.and_then(|v| v.to_f64())
.unwrap_or(0.0);
let (hihi, high, low, lolo) = self.alarm_limits();
snap.display = Some(super::super::snapshot::DisplayInfo {
units: egu,
precision: prec,
upper_disp_limit: hopr,
lower_disp_limit: lopr,
upper_alarm_limit: hihi,
upper_warning_limit: high,
lower_warning_limit: low,
lower_alarm_limit: lolo,
});
}
"longin" | "longout" => {
let egu = self
.record
.get_field("EGU")
.and_then(|v| {
if let EpicsValue::String(s) = v {
Some(s)
} else {
None
}
})
.unwrap_or_default();
let hopr = self
.record
.get_field("HOPR")
.and_then(|v| v.to_f64())
.unwrap_or(0.0);
let lopr = self
.record
.get_field("LOPR")
.and_then(|v| v.to_f64())
.unwrap_or(0.0);
let (hihi, high, low, lolo) = self.alarm_limits();
snap.display = Some(super::super::snapshot::DisplayInfo {
units: egu,
precision: 0,
upper_disp_limit: hopr,
lower_disp_limit: lopr,
upper_alarm_limit: hihi,
upper_warning_limit: high,
lower_warning_limit: low,
lower_alarm_limit: lolo,
});
}
"motor" => {
let egu = self
.record
.get_field("EGU")
.and_then(|v| {
if let EpicsValue::String(s) = v {
Some(s)
} else {
None
}
})
.unwrap_or_default();
let prec = self
.record
.get_field("PREC")
.and_then(|v| v.to_f64())
.unwrap_or(0.0) as i16;
let hlm = self
.record
.get_field("HLM")
.and_then(|v| v.to_f64())
.unwrap_or(0.0);
let llm = self
.record
.get_field("LLM")
.and_then(|v| v.to_f64())
.unwrap_or(0.0);
snap.display = Some(super::super::snapshot::DisplayInfo {
units: egu,
precision: prec,
upper_disp_limit: hlm,
lower_disp_limit: llm,
upper_alarm_limit: 0.0,
upper_warning_limit: 0.0,
lower_warning_limit: 0.0,
lower_alarm_limit: 0.0,
});
}
_ => {}
}
}
/// Populate ControlInfo from record fields if applicable.
fn populate_control_info(&self, snap: &mut super::super::snapshot::Snapshot) {
let rtype = self.record.record_type();
match rtype {
"ao" | "longout" => {
// Output records use DRVH/DRVL, fallback to HOPR/LOPR
let drvh = self.record.get_field("DRVH").and_then(|v| v.to_f64());
let drvl = self.record.get_field("DRVL").and_then(|v| v.to_f64());
let hopr = self
.record
.get_field("HOPR")
.and_then(|v| v.to_f64())
.unwrap_or(0.0);
let lopr = self
.record
.get_field("LOPR")
.and_then(|v| v.to_f64())
.unwrap_or(0.0);
snap.control = Some(super::super::snapshot::ControlInfo {
upper_ctrl_limit: drvh.unwrap_or(hopr),
lower_ctrl_limit: drvl.unwrap_or(lopr),
});
}
"motor" => {
// Motor records use HLM/LLM as control limits
let hlm = self
.record
.get_field("HLM")
.and_then(|v| v.to_f64())
.unwrap_or(0.0);
let llm = self
.record
.get_field("LLM")
.and_then(|v| v.to_f64())
.unwrap_or(0.0);
snap.control = Some(super::super::snapshot::ControlInfo {
upper_ctrl_limit: hlm,
lower_ctrl_limit: llm,
});
}
"ai" | "longin" | "calc" | "calcout" => {
// Input records use HOPR/LOPR as control limits
let hopr = self
.record
.get_field("HOPR")
.and_then(|v| v.to_f64())
.unwrap_or(0.0);
let lopr = self
.record
.get_field("LOPR")
.and_then(|v| v.to_f64())
.unwrap_or(0.0);
snap.control = Some(super::super::snapshot::ControlInfo {
upper_ctrl_limit: hopr,
lower_ctrl_limit: lopr,
});
}
_ => {}
}
}
/// Populate EnumInfo from record fields if applicable.
fn populate_enum_info(&self, snap: &mut super::super::snapshot::Snapshot) {
let rtype = self.record.record_type();
match rtype {
"bi" | "bo" | "busy" => {
let znam = self
.record
.get_field("ZNAM")
.and_then(|v| {
if let EpicsValue::String(s) = v {
Some(s)
} else {
None
}
})
.unwrap_or_default();
let onam = self
.record
.get_field("ONAM")
.and_then(|v| {
if let EpicsValue::String(s) = v {
Some(s)
} else {
None
}
})
.unwrap_or_default();
snap.enums = Some(super::super::snapshot::EnumInfo {
strings: vec![znam, onam],
});
}
"mbbi" | "mbbo" => {
let state_fields = [
"ZRST", "ONST", "TWST", "THST", "FRST", "FVST", "SXST", "SVST", "EIST", "NIST",
"TEST", "ELST", "TVST", "TTST", "FTST", "FFST",
];
let strings: Vec<String> = state_fields
.iter()
.map(|f| {
self.record
.get_field(f)
.and_then(|v| {
if let EpicsValue::String(s) = v {
Some(s)
} else {
None
}
})
.unwrap_or_default()
})
.collect();
snap.enums = Some(super::super::snapshot::EnumInfo { strings });
}
_ => {}
}
}
/// Populate enum strings for common fields accessed via CA (e.g. .SCAN).
fn populate_common_enum_info(&self, field: &str, snap: &mut super::super::snapshot::Snapshot) {
match field {
"SCAN" => {
snap.enums = Some(super::super::snapshot::EnumInfo {
strings: vec![
"Passive".into(),
"Event".into(),
"I/O Intr".into(),
"10 second".into(),
"5 second".into(),
"2 second".into(),
"1 second".into(),
".5 second".into(),
".2 second".into(),
".1 second".into(),
],
});
}
_ => {}
}
}
/// Extract analog alarm limits from CommonFields.
fn alarm_limits(&self) -> (f64, f64, f64, f64) {
if let Some(ref aa) = self.common.analog_alarm {
(aa.hihi, aa.high, aa.low, aa.lolo)
} else {
(0.0, 0.0, 0.0, 0.0)
}
}
/// Get a common field value.
pub fn get_common_field(&self, name: &str) -> Option<EpicsValue> {
match name {
"SEVR" => Some(EpicsValue::Short(self.common.sevr as i16)),
"STAT" => Some(EpicsValue::Short(self.common.stat as i16)),
"NSEV" => Some(EpicsValue::Short(self.common.nsev as i16)),
"NSTA" => Some(EpicsValue::Short(self.common.nsta as i16)),
"ACKS" => Some(EpicsValue::Short(self.common.acks as i16)),
"ACKT" => Some(EpicsValue::Char(if self.common.ackt { 1 } else { 0 })),
"UDF" => Some(EpicsValue::Char(if self.common.udf { 1 } else { 0 })),
"UDFS" => Some(EpicsValue::Short(self.common.udfs as i16)),
"SCAN" => Some(EpicsValue::Enum(self.common.scan as u16)),
"SSCN" => Some(EpicsValue::Enum(self.common.sscn as u16)),
"PINI" => Some(EpicsValue::Char(if self.common.pini { 1 } else { 0 })),
"TPRO" => Some(EpicsValue::Char(if self.common.tpro { 1 } else { 0 })),
"BKPT" => Some(EpicsValue::Char(self.common.bkpt)),
"FLNK" => Some(EpicsValue::String(self.common.flnk.clone())),
"INP" => Some(EpicsValue::String(self.common.inp.clone())),
"OUT" => Some(EpicsValue::String(self.common.out.clone())),
"DTYP" => Some(EpicsValue::String(self.common.dtyp.clone())),
"TSE" => Some(EpicsValue::Short(self.common.tse)),
"TSEL" => Some(EpicsValue::String(self.common.tsel.clone())),
"ASG" => Some(EpicsValue::String(self.common.asg.clone())),
"DESC" => Some(EpicsValue::String(self.common.desc.clone())),
"PHAS" => Some(EpicsValue::Short(self.common.phas)),
"EVNT" => Some(EpicsValue::Short(self.common.evnt)),
"PRIO" => Some(EpicsValue::Short(self.common.prio)),
"DISV" => Some(EpicsValue::Short(self.common.disv)),
"DISA" => Some(EpicsValue::Short(self.common.disa)),
"SDIS" => Some(EpicsValue::String(self.common.sdis.clone())),
"DISS" => Some(EpicsValue::Short(self.common.diss as i16)),
"HYST" => Some(EpicsValue::Double(self.common.hyst)),
"LCNT" => Some(EpicsValue::Short(self.common.lcnt)),
"DISP" => Some(EpicsValue::Char(if self.common.disp { 1 } else { 0 })),
"PUTF" => Some(EpicsValue::Char(if self.common.putf { 1 } else { 0 })),
"RPRO" => Some(EpicsValue::Char(if self.common.rpro { 1 } else { 0 })),
"PACT" => Some(EpicsValue::Char(
if self.processing.load(std::sync::atomic::Ordering::Acquire) {
1
} else {
0
},
)),
"PROC" => Some(EpicsValue::Char(0)), // Always 0 (trigger-only)
// Analog alarm fields
"HIHI" => self
.common
.analog_alarm
.as_ref()
.map(|a| EpicsValue::Double(a.hihi)),
"HIGH" => self
.common
.analog_alarm
.as_ref()
.map(|a| EpicsValue::Double(a.high)),
"LOW" => self
.common
.analog_alarm
.as_ref()
.map(|a| EpicsValue::Double(a.low)),
"LOLO" => self
.common
.analog_alarm
.as_ref()
.map(|a| EpicsValue::Double(a.lolo)),
"HHSV" => self
.common
.analog_alarm
.as_ref()
.map(|a| EpicsValue::Short(a.hhsv as i16)),
"HSV" => self
.common
.analog_alarm
.as_ref()
.map(|a| EpicsValue::Short(a.hsv as i16)),
"LSV" => self
.common
.analog_alarm
.as_ref()
.map(|a| EpicsValue::Short(a.lsv as i16)),
"LLSV" => self
.common
.analog_alarm
.as_ref()
.map(|a| EpicsValue::Short(a.llsv as i16)),
_ => None,
}
}
/// Set a common field value. Returns what scan index changes are needed.
pub fn put_common_field(
&mut self,
name: &str,
value: EpicsValue,
) -> CaResult<CommonFieldPutResult> {
let name = name.to_ascii_uppercase();
self.record.validate_put(&name, &value)?;
self.record.special(&name, false)?;
match name.as_str() {
"SEVR" => {
if let EpicsValue::Short(v) = value {
self.common.sevr = AlarmSeverity::from_u16(v as u16);
}
}
"STAT" => {
if let EpicsValue::Short(v) = value {
self.common.stat = v as u16;
}
}
"NSEV" => {
if let EpicsValue::Short(v) = value {
self.common.nsev = AlarmSeverity::from_u16(v as u16);
}
}
"NSTA" => {
if let EpicsValue::Short(v) = value {
self.common.nsta = v as u16;
}
}
"ACKS" => {
if let EpicsValue::Short(v) = value {
let sev = AlarmSeverity::from_u16(v as u16);
// Writing ACKS clears alarm acknowledge if written severity >= current
if sev >= self.common.sevr {
self.common.acks = AlarmSeverity::NoAlarm;
}
}
}
"ACKT" => match value {
EpicsValue::Char(v) => self.common.ackt = v != 0,
EpicsValue::Short(v) => self.common.ackt = v != 0,
_ => {}
},
"UDF" => {
if let EpicsValue::Char(v) = value {
self.common.udf = v != 0;
}
}
"UDFS" => {
if let EpicsValue::Short(v) = value {
self.common.udfs = AlarmSeverity::from_u16(v as u16);
}
}
"SCAN" => {
let old_scan = self.common.scan;
let new_scan = match &value {
EpicsValue::Short(v) => ScanType::from_u16(*v as u16),
EpicsValue::Enum(v) => ScanType::from_u16(*v),
EpicsValue::String(s) => ScanType::from_str(s)?,
_ => return Ok(CommonFieldPutResult::NoChange),
};
self.common.scan = new_scan;
if old_scan != new_scan {
let phas = self.common.phas;
self.record.on_put(&name);
let _ = self.record.special(&name, true);
return Ok(CommonFieldPutResult::ScanChanged {
old_scan,
new_scan,
phas,
});
}
}
"SSCN" => {
let new_sscn = match &value {
EpicsValue::Short(v) => ScanType::from_u16(*v as u16),
EpicsValue::Enum(v) => ScanType::from_u16(*v),
EpicsValue::String(s) => ScanType::from_str(s)?,
_ => return Ok(CommonFieldPutResult::NoChange),
};
self.common.sscn = new_sscn;
}
"PINI" => {
if let EpicsValue::Char(v) = value {
self.common.pini = v != 0;
} else if let EpicsValue::String(s) = &value {
self.common.pini = s == "YES" || s == "1" || s == "true";
}
}
"TPRO" => {
if let EpicsValue::Char(v) = value {
self.common.tpro = v != 0;
}
}
"BKPT" => {
if let EpicsValue::Char(v) = value {
self.common.bkpt = v;
}
}
"FLNK" => {
if let EpicsValue::String(s) = value {
self.common.flnk = s;
self.parsed_flnk = parse_link_v2(&self.common.flnk);
}
}
"INP" => {
if let EpicsValue::String(s) = value {
self.common.inp = s;
self.parsed_inp = parse_link_v2(&self.common.inp);
}
}
"OUT" => {
if let EpicsValue::String(s) = value {
self.common.out = s;
self.parsed_out = parse_link_v2(&self.common.out);
}
}
"DTYP" => {
if let EpicsValue::String(s) = value {
self.common.dtyp = s;
}
}
"TSE" => {
if let EpicsValue::Short(v) = value {
self.common.tse = v;
}
}
"TSEL" => {
if let EpicsValue::String(s) = value {
self.common.tsel = s;
self.parsed_tsel = parse_link_v2(&self.common.tsel);
}
}
"ASG" => {
if let EpicsValue::String(s) = value {
self.common.asg = s;
}
}
"DESC" => {
if let EpicsValue::String(s) = value {
self.common.desc = s;
}
}
"PHAS" => {
if let EpicsValue::Short(v) = value {
let old_phas = self.common.phas;
self.common.phas = v;
if old_phas != v && self.common.scan != ScanType::Passive {
let scan = self.common.scan;
self.record.on_put(&name);
let _ = self.record.special(&name, true);
return Ok(CommonFieldPutResult::PhasChanged {
scan,
old_phas,
new_phas: v,
});
}
}
}
"EVNT" => {
if let EpicsValue::Short(v) = value {
self.common.evnt = v;
}
}
"PRIO" => {
if let EpicsValue::Short(v) = value {
self.common.prio = v;
}
}
"DISV" => {
if let EpicsValue::Short(v) = value {
self.common.disv = v;
}
}
"DISA" => {
if let EpicsValue::Short(v) = value {
self.common.disa = v;
}
}
"SDIS" => {
if let EpicsValue::String(s) = value {
self.common.sdis = s;
self.parsed_sdis = parse_link_v2(&self.common.sdis);
}
}
"DISS" => {
if let EpicsValue::Short(v) = value {
self.common.diss = AlarmSeverity::from_u16(v as u16);
}
}
"HYST" => {
if let EpicsValue::Double(v) = value {
self.common.hyst = v;
}
}
"LCNT" => {
if let EpicsValue::Short(v) = value {
self.common.lcnt = v;
}
}
"DISP" => match value {
EpicsValue::Char(v) => self.common.disp = v != 0,
EpicsValue::Short(v) => self.common.disp = v != 0,
_ => {}
},
"PUTF" => return Err(CaError::ReadOnlyField("PUTF".into())),
"RPRO" => {
if let EpicsValue::Char(v) = value {
self.common.rpro = v != 0;
}
}
"PACT" => return Err(CaError::ReadOnlyField("PACT".into())),
"PROC" => { /* Trigger handled by put_record_field_from_ca; no-op here */ }
// Analog alarm fields
"HIHI" => {
if let (Some(a), EpicsValue::Double(v)) = (&mut self.common.analog_alarm, value) {
a.hihi = v;
}
}
"HIGH" => {
if let (Some(a), EpicsValue::Double(v)) = (&mut self.common.analog_alarm, value) {
a.high = v;
}
}
"LOW" => {
if let (Some(a), EpicsValue::Double(v)) = (&mut self.common.analog_alarm, value) {
a.low = v;
}
}
"LOLO" => {
if let (Some(a), EpicsValue::Double(v)) = (&mut self.common.analog_alarm, value) {
a.lolo = v;
}
}
"HHSV" => {
if let (Some(a), EpicsValue::Short(v)) = (&mut self.common.analog_alarm, value) {
a.hhsv = AlarmSeverity::from_u16(v as u16);
}
}
"HSV" => {
if let (Some(a), EpicsValue::Short(v)) = (&mut self.common.analog_alarm, value) {
a.hsv = AlarmSeverity::from_u16(v as u16);
}
}
"LSV" => {
if let (Some(a), EpicsValue::Short(v)) = (&mut self.common.analog_alarm, value) {
a.lsv = AlarmSeverity::from_u16(v as u16);
}
}
"LLSV" => {
if let (Some(a), EpicsValue::Short(v)) = (&mut self.common.analog_alarm, value) {
a.llsv = AlarmSeverity::from_u16(v as u16);
}
}
_ => {}
}
self.record.on_put(&name);
let _ = self.record.special(&name, true);
Ok(CommonFieldPutResult::NoChange)
}
/// Get virtual fields (NAME, RTYP).
pub fn get_virtual_field(&self, name: &str) -> Option<EpicsValue> {
match name {
"NAME" => Some(EpicsValue::String(self.name.clone())),
"RTYP" => Some(EpicsValue::String(self.record.record_type().to_string())),
_ => None,
}
}
/// Evaluate alarms based on record type and current value.
/// Uses rec_gbl_set_sevr to accumulate into nsta/nsev.
pub fn evaluate_alarms(&mut self) {
use crate::server::recgbl::{self, alarm_status};
// Check UDF first
recgbl::rec_gbl_check_udf(&mut self.common);
let rtype = self.record.record_type();
match rtype {
"ai" | "ao" | "longin" | "longout" => {
if let Some(ref alarm_cfg) = self.common.analog_alarm.clone() {
let val = match self.record.val() {
Some(EpicsValue::Double(v)) => v,
Some(EpicsValue::Long(v)) => v as f64,
_ => return,
};
self.evaluate_analog_alarm(val, alarm_cfg);
}
}
"bi" | "bo" | "busy" => {
let val = match self.record.val() {
Some(EpicsValue::Enum(v)) => v,
_ => return,
};
let zsv = self
.record
.get_field("ZSV")
.and_then(|v| {
if let EpicsValue::Short(s) = v {
Some(s)
} else {
None
}
})
.unwrap_or(0);
let osv = self
.record
.get_field("OSV")
.and_then(|v| {
if let EpicsValue::Short(s) = v {
Some(s)
} else {
None
}
})
.unwrap_or(0);
let cosv = self
.record
.get_field("COSV")
.and_then(|v| {
if let EpicsValue::Short(s) = v {
Some(s)
} else {
None
}
})
.unwrap_or(0);
let state_sev = if val == 0 { zsv } else { osv };
let sev = AlarmSeverity::from_u16(state_sev as u16);
let cos_sev = AlarmSeverity::from_u16(cosv as u16);
let final_sev = if cos_sev as u16 > sev as u16 {
cos_sev
} else {
sev
};
if final_sev != AlarmSeverity::NoAlarm {
recgbl::rec_gbl_set_sevr(
&mut self.common,
alarm_status::STATE_ALARM,
final_sev,
);
}
}
"mbbi" | "mbbo" => {
let val = match self.record.val() {
Some(EpicsValue::Enum(v)) => v as usize,
_ => return,
};
let sv_fields = [
"ZRSV", "ONSV", "TWSV", "THSV", "FRSV", "FVSV", "SXSV", "SVSV", "EISV", "NISV",
"TESV", "ELSV", "TVSV", "TTSV", "FTSV", "FFSV",
];
let unsv = self
.record
.get_field("UNSV")
.and_then(|v| {
if let EpicsValue::Short(s) = v {
Some(s)
} else {
None
}
})
.unwrap_or(0);
let cosv = self
.record
.get_field("COSV")
.and_then(|v| {
if let EpicsValue::Short(s) = v {
Some(s)
} else {
None
}
})
.unwrap_or(0);
let state_sev = if val < 16 {
self.record
.get_field(sv_fields[val])
.and_then(|v| {
if let EpicsValue::Short(s) = v {
Some(s)
} else {
None
}
})
.unwrap_or(unsv)
} else {
unsv
};
let sev = AlarmSeverity::from_u16(state_sev as u16);
let cos_sev = AlarmSeverity::from_u16(cosv as u16);
let final_sev = if cos_sev as u16 > sev as u16 {
cos_sev
} else {
sev
};
if final_sev != AlarmSeverity::NoAlarm {
recgbl::rec_gbl_set_sevr(
&mut self.common,
alarm_status::STATE_ALARM,
final_sev,
);
}
}
_ => {} // no-op for other types
}
}
fn evaluate_analog_alarm(&mut self, val: f64, cfg: &AnalogAlarmConfig) {
use crate::server::recgbl::{self, alarm_status};
let hyst = self.common.hyst;
let lalm = self
.record
.get_field("LALM")
.and_then(|v| v.to_f64())
.unwrap_or(val);
let (new_sevr, new_stat) =
if cfg.hhsv != AlarmSeverity::NoAlarm && val >= cfg.hihi && cfg.hihi != 0.0 {
(cfg.hhsv, alarm_status::HIHI_ALARM)
} else if cfg.llsv != AlarmSeverity::NoAlarm && val <= cfg.lolo && cfg.lolo != 0.0 {
(cfg.llsv, alarm_status::LOLO_ALARM)
} else if cfg.hsv != AlarmSeverity::NoAlarm && val >= cfg.high && cfg.high != 0.0 {
(cfg.hsv, alarm_status::HIGH_ALARM)
} else if cfg.lsv != AlarmSeverity::NoAlarm && val <= cfg.low && cfg.low != 0.0 {
(cfg.lsv, alarm_status::LOW_ALARM)
} else {
(AlarmSeverity::NoAlarm, alarm_status::NO_ALARM)
};
// Apply hysteresis: only change alarm if value moved enough from LALM
if hyst > 0.0 && self.common.sevr != AlarmSeverity::NoAlarm {
if new_sevr == AlarmSeverity::NoAlarm && (val - lalm).abs() < hyst {
// Stay in current alarm (hysteresis prevents clearing)
// Re-raise the current alarm into nsta/nsev
let cur_stat = self.common.stat;
let cur_sevr = self.common.sevr;
recgbl::rec_gbl_set_sevr(&mut self.common, cur_stat, cur_sevr);
return;
}
}
if new_sevr != AlarmSeverity::NoAlarm {
recgbl::rec_gbl_set_sevr(&mut self.common, new_stat, new_sevr);
let _ = self.record.put_field("LALM", EpicsValue::Double(val));
}
}
/// Basic process: process record, evaluate alarms, timestamp, build snapshot.
/// This does NOT handle links — see process_with_context in database.rs.
pub fn process_local(&mut self) -> CaResult<ProcessSnapshot> {
use crate::server::recgbl::{self, EventMask};
const LCNT_ALARM_THRESHOLD: i16 = 10;
if self
.processing
.swap(true, std::sync::atomic::Ordering::AcqRel)
{
self.common.lcnt = self.common.lcnt.saturating_add(1);
if self.common.lcnt >= LCNT_ALARM_THRESHOLD {
self.common.sevr = AlarmSeverity::Invalid;
self.common.stat = recgbl::alarm_status::SCAN_ALARM;
}
return Ok(ProcessSnapshot {
changed_fields: Vec::new(),
event_mask: EventMask::NONE,
});
}
self.common.lcnt = 0;
struct ProcessGuard(*const AtomicBool);
unsafe impl Send for ProcessGuard {}
impl Drop for ProcessGuard {
fn drop(&mut self) {
unsafe { &*self.0 }.store(false, std::sync::atomic::Ordering::Release);
}
}
let _guard = ProcessGuard(&self.processing as *const AtomicBool);
// Call subroutine if registered (for sub records)
if let Some(ref sub_fn) = self.subroutine {
sub_fn(&mut *self.record)?;
}
let outcome = self.record.process()?;
let process_result = outcome.result;
// Note: process_local() does not execute ProcessActions — those are
// handled by the full process_record_with_links() path in processing.rs.
if process_result == RecordProcessResult::AsyncPending {
// Async: PACT stays set, no further processing this cycle
// Don't clear processing flag (guard won't run — we leak it intentionally)
std::mem::forget(_guard);
return Ok(ProcessSnapshot {
changed_fields: Vec::new(),
event_mask: EventMask::NONE,
});
}
if let RecordProcessResult::AsyncPendingNotify(fields) = process_result {
// Intermediate notification (e.g. DMOV=0 at move start).
// Unlike AsyncPending, we DO release the processing flag so
// subsequent I/O Intr cycles can continue processing normally.
self.common.time = crate::runtime::general_time::get_current();
// Filter out fields that haven't actually changed, and update
// MLST/last_posted for those that have.
let mut changed_fields = Vec::new();
for (name, val) in fields {
let changed = match self.last_posted.get(&name) {
Some(prev) => prev != &val,
None => true,
};
if changed {
if name == "VAL" {
if let Some(f) = val.to_f64() {
if self
.record
.put_field("MLST", EpicsValue::Double(f))
.is_err()
{
self.common.mlst = Some(f);
}
}
}
self.last_posted.insert(name.clone(), val.clone());
changed_fields.push((name, val));
}
}
let event_mask = if changed_fields.is_empty() {
EventMask::NONE
} else {
EventMask::VALUE | EventMask::ALARM
};
// _guard drops here, clearing the processing flag
return Ok(ProcessSnapshot {
changed_fields,
event_mask,
});
}
// Evaluate alarms (accumulates into nsta/nsev)
self.evaluate_alarms();
// Transfer nsta/nsev → sevr/stat, detect alarm change
let alarm_result = recgbl::rec_gbl_reset_alarms(&mut self.common);
self.common.time = crate::runtime::general_time::get_current();
if self.record.clears_udf() {
self.common.udf = false;
}
// Compute event mask
let mut event_mask = EventMask::NONE;
// Deadband check for VAL monitor filtering
let (include_val, include_archive) = self.check_deadband_ext();
if include_val {
event_mask |= EventMask::VALUE;
}
if include_archive {
event_mask |= EventMask::LOG;
}
if alarm_result.alarm_changed {
event_mask |= EventMask::ALARM;
}
// Build snapshot
let mut changed_fields = Vec::new();
if include_val {
if let Some(val) = self.record.val() {
changed_fields.push(("VAL".to_string(), val));
}
}
if alarm_result.alarm_changed {
changed_fields.push((
"SEVR".to_string(),
EpicsValue::Short(self.common.sevr as i16),
));
changed_fields.push((
"STAT".to_string(),
EpicsValue::Short(self.common.stat as i16),
));
}
// Add subscribed fields that actually changed since last notification.
let mut sub_updates: Vec<(String, EpicsValue)> = Vec::new();
for (field, subs) in &self.subscribers {
if !subs.is_empty() && field != "VAL" && field != "SEVR" && field != "STAT" {
if let Some(val) = self.resolve_field(field) {
let changed = match self.last_posted.get(field) {
Some(prev) => prev != &val,
None => true,
};
if changed {
sub_updates.push((field.clone(), val));
}
}
}
}
if !sub_updates.is_empty() {
for (field, val) in &sub_updates {
self.last_posted.insert(field.clone(), val.clone());
}
changed_fields.extend(sub_updates);
event_mask |= EventMask::VALUE;
}
Ok(ProcessSnapshot {
changed_fields,
event_mask,
})
}
/// Check deadband (MDEL/ADEL) for VAL monitor/archive filtering.
/// Returns (monitor_trigger, archive_trigger).
/// Updates ALST/MLST in the record when triggered.
/// For records without MDEL/ADEL fields (e.g. motor), defaults to MDEL=0
/// (trigger on any actual change) and uses CommonFields.mlst/alst as fallback.
pub fn check_deadband_ext(&mut self) -> (bool, bool) {
let val = match self.record.val().and_then(|v| v.to_f64()) {
Some(v) => v,
None => return (true, true),
};
let mdel = self
.record
.get_field("MDEL")
.and_then(|v| v.to_f64())
.unwrap_or(0.0);
let adel = self
.record
.get_field("ADEL")
.and_then(|v| v.to_f64())
.unwrap_or(0.0);
// Use record's MLST/ALST fields if available, otherwise fall back to CommonFields
let mlst = self
.record
.get_field("MLST")
.and_then(|v| v.to_f64())
.or(self.common.mlst)
.unwrap_or(f64::NAN);
let alst = self
.record
.get_field("ALST")
.and_then(|v| v.to_f64())
.or(self.common.alst)
.unwrap_or(f64::NAN);
let monitor_trigger = mdel < 0.0 || mlst.is_nan() || (val - mlst).abs() > mdel;
let archive_trigger = adel < 0.0 || alst.is_nan() || (val - alst).abs() > adel;
if archive_trigger {
if self
.record
.put_field("ALST", EpicsValue::Double(val))
.is_err()
{
self.common.alst = Some(val);
}
}
if monitor_trigger {
if self
.record
.put_field("MLST", EpicsValue::Double(val))
.is_err()
{
self.common.mlst = Some(val);
}
}
(monitor_trigger, archive_trigger)
}
/// Build a Snapshot for a given value, populated with the record's display metadata.
fn make_monitor_snapshot(&self, value: EpicsValue) -> super::super::snapshot::Snapshot {
let mut snap = super::super::snapshot::Snapshot::new(
value,
self.common.stat,
self.common.sevr as u16,
self.common.time,
);
self.populate_display_info(&mut snap);
self.populate_control_info(&mut snap);
self.populate_enum_info(&mut snap);
snap
}
/// Notify subscribers from a snapshot (call outside lock).
/// Uses event_mask to filter: only notify subscribers whose mask intersects.
pub fn notify_from_snapshot(&self, snapshot: &ProcessSnapshot) {
use crate::server::recgbl::EventMask;
let posting_mask = snapshot.event_mask;
for (field, value) in &snapshot.changed_fields {
if let Some(subs) = self.subscribers.get(field) {
// Build a full snapshot once per field (with display metadata)
let mon_snap = self.make_monitor_snapshot(value.clone());
for sub in subs {
let sub_mask = EventMask::from_bits(sub.mask);
// Only send when posting mask intersects subscriber mask.
// Empty posting mask means nothing changed — skip.
if !posting_mask.is_empty() && sub_mask.intersects(posting_mask) {
let _ = sub.tx.try_send(MonitorEvent {
snapshot: mon_snap.clone(),
origin: 0,
});
}
}
}
}
}
/// Notify subscribers of a specific field, filtering by event mask.
pub fn notify_field(&self, field: &str, mask: crate::server::recgbl::EventMask) {
self.notify_field_with_origin(field, mask, 0);
}
/// Notify subscribers with an origin tag for self-write filtering.
pub fn notify_field_with_origin(
&self,
field: &str,
mask: crate::server::recgbl::EventMask,
origin: u64,
) {
if let Some(subs) = self.subscribers.get(field) {
if let Some(value) = self.resolve_field(field) {
let mon_snap = self.make_monitor_snapshot(value);
for sub in subs {
let sub_mask = crate::server::recgbl::EventMask::from_bits(sub.mask);
if mask.is_empty() || sub_mask.intersects(mask) {
let _ = sub.tx.try_send(MonitorEvent {
snapshot: mon_snap.clone(),
origin,
});
}
}
}
}
}
/// Add a subscriber for a specific field.
pub fn add_subscriber(
&mut self,
field: &str,
sid: u32,
data_type: DbFieldType,
mask: u16,
) -> mpsc::Receiver<MonitorEvent> {
let (tx, rx) = mpsc::channel(64);
let sub = Subscriber {
sid,
data_type,
mask,
tx,
};
let field_str = field.to_string();
self.subscribers
.entry(field_str.clone())
.or_default()
.push(sub);
// Initialize last_posted with current value so the first process cycle
// doesn't treat it as "changed" (the initial value is already sent
// to the client as part of EVENT_ADD response).
if !self.last_posted.contains_key(&field_str) {
if let Some(val) = self.resolve_field(&field_str) {
self.last_posted.insert(field_str, val);
}
}
rx
}
/// Remove a subscriber by subscription ID from all fields.
pub fn remove_subscriber(&mut self, sid: u32) {
for subs in self.subscribers.values_mut() {
subs.retain(|s| s.sid != sid);
}
}
/// Clean up closed subscriber channels.
pub fn cleanup_subscribers(&mut self) {
for subs in self.subscribers.values_mut() {
subs.retain(|s| !s.tx.is_closed());
}
}
}