ad-plugins-rs 0.8.2

NDPlugin implementations for areaDetector-rs
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
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
use std::collections::VecDeque;
use std::sync::Arc;

use ad_core_rs::ndarray::NDArray;
use ad_core_rs::ndarray_pool::NDArrayPool;
use ad_core_rs::plugin::runtime::{NDPluginProcess, ProcessResult};

/// Operations supported by CalcExpression.
#[derive(Debug, Clone, Copy)]
enum CalcOp {
    Gt,
    Lt,
    Ge,
    Le,
    Eq,
    Ne,
    And,
    Or,
    Not,
}

/// Token in a parsed CalcExpression (RPN).
#[derive(Debug, Clone)]
enum CalcToken {
    Num(f64),
    VarA,
    VarB,
    Op(CalcOp),
}

/// Raw token used during parsing (before conversion to RPN).
#[derive(Debug, Clone)]
enum RawToken {
    Num(f64),
    VarA,
    VarB,
    Op(CalcOp),
    LParen,
    RParen,
}

/// A simple expression evaluator supporting variables A and B,
/// numeric literals, comparison and logical operators.
///
/// Parsed into reverse-polish notation (RPN) using shunting-yard.
#[derive(Debug, Clone)]
pub struct CalcExpression {
    tokens: Vec<CalcToken>,
}

impl CalcExpression {
    /// Parse an infix expression into RPN.
    ///
    /// Supports: A, B (variables), numeric literals (including decimals and negatives
    /// at start or after open paren), >, <, >=, <=, ==, !=, &&, ||, !, parentheses.
    pub fn parse(expr: &str) -> Option<CalcExpression> {
        let raw_tokens = Self::tokenize(expr)?;
        let rpn = Self::shunting_yard(raw_tokens)?;
        Some(CalcExpression { tokens: rpn })
    }

    /// Evaluate the expression with the given variable values.
    /// Returns the numeric result; nonzero means true for trigger purposes.
    pub fn evaluate(&self, a: f64, b: f64) -> f64 {
        let mut stack: Vec<f64> = Vec::new();
        for tok in &self.tokens {
            match tok {
                CalcToken::Num(n) => stack.push(*n),
                CalcToken::VarA => stack.push(a),
                CalcToken::VarB => stack.push(b),
                CalcToken::Op(op) => match op {
                    CalcOp::Not => {
                        let v = stack.pop().unwrap_or(0.0);
                        stack.push(if v == 0.0 { 1.0 } else { 0.0 });
                    }
                    _ => {
                        let rhs = stack.pop().unwrap_or(0.0);
                        let lhs = stack.pop().unwrap_or(0.0);
                        let result = match op {
                            CalcOp::Gt => {
                                if lhs > rhs {
                                    1.0
                                } else {
                                    0.0
                                }
                            }
                            CalcOp::Lt => {
                                if lhs < rhs {
                                    1.0
                                } else {
                                    0.0
                                }
                            }
                            CalcOp::Ge => {
                                if lhs >= rhs {
                                    1.0
                                } else {
                                    0.0
                                }
                            }
                            CalcOp::Le => {
                                if lhs <= rhs {
                                    1.0
                                } else {
                                    0.0
                                }
                            }
                            CalcOp::Eq => {
                                if (lhs - rhs).abs() < f64::EPSILON {
                                    1.0
                                } else {
                                    0.0
                                }
                            }
                            CalcOp::Ne => {
                                if (lhs - rhs).abs() >= f64::EPSILON {
                                    1.0
                                } else {
                                    0.0
                                }
                            }
                            CalcOp::And => {
                                if lhs != 0.0 && rhs != 0.0 {
                                    1.0
                                } else {
                                    0.0
                                }
                            }
                            CalcOp::Or => {
                                if lhs != 0.0 || rhs != 0.0 {
                                    1.0
                                } else {
                                    0.0
                                }
                            }
                            CalcOp::Not => unreachable!(),
                        };
                        stack.push(result);
                    }
                },
            }
        }
        stack.pop().unwrap_or(0.0)
    }

    fn precedence(op: &CalcOp) -> u8 {
        match op {
            CalcOp::Or => 1,
            CalcOp::And => 2,
            CalcOp::Eq | CalcOp::Ne => 3,
            CalcOp::Gt | CalcOp::Lt | CalcOp::Ge | CalcOp::Le => 4,
            CalcOp::Not => 5,
        }
    }

    fn is_right_assoc(op: &CalcOp) -> bool {
        matches!(op, CalcOp::Not)
    }

    fn tokenize(expr: &str) -> Option<Vec<RawToken>> {
        use RawToken as RT;
        let chars: Vec<char> = expr.chars().collect();
        let mut tokens = Vec::new();
        let mut i = 0;

        while i < chars.len() {
            match chars[i] {
                ' ' | '\t' => {
                    i += 1;
                }
                '(' => {
                    tokens.push(RT::LParen);
                    i += 1;
                }
                ')' => {
                    tokens.push(RT::RParen);
                    i += 1;
                }
                'A' | 'a' => {
                    tokens.push(RT::VarA);
                    i += 1;
                }
                'B' | 'b' => {
                    tokens.push(RT::VarB);
                    i += 1;
                }
                '>' => {
                    if i + 1 < chars.len() && chars[i + 1] == '=' {
                        tokens.push(RT::Op(CalcOp::Ge));
                        i += 2;
                    } else {
                        tokens.push(RT::Op(CalcOp::Gt));
                        i += 1;
                    }
                }
                '<' => {
                    if i + 1 < chars.len() && chars[i + 1] == '=' {
                        tokens.push(RT::Op(CalcOp::Le));
                        i += 2;
                    } else {
                        tokens.push(RT::Op(CalcOp::Lt));
                        i += 1;
                    }
                }
                '=' => {
                    if i + 1 < chars.len() && chars[i + 1] == '=' {
                        tokens.push(RT::Op(CalcOp::Eq));
                        i += 2;
                    } else {
                        return None; // Single '=' not supported
                    }
                }
                '!' => {
                    if i + 1 < chars.len() && chars[i + 1] == '=' {
                        tokens.push(RT::Op(CalcOp::Ne));
                        i += 2;
                    } else {
                        tokens.push(RT::Op(CalcOp::Not));
                        i += 1;
                    }
                }
                '&' => {
                    if i + 1 < chars.len() && chars[i + 1] == '&' {
                        tokens.push(RT::Op(CalcOp::And));
                        i += 2;
                    } else {
                        return None;
                    }
                }
                '|' => {
                    if i + 1 < chars.len() && chars[i + 1] == '|' {
                        tokens.push(RT::Op(CalcOp::Or));
                        i += 2;
                    } else {
                        return None;
                    }
                }
                c if c.is_ascii_digit() || c == '.' => {
                    let start = i;
                    while i < chars.len() && (chars[i].is_ascii_digit() || chars[i] == '.') {
                        i += 1;
                    }
                    let num_str: String = chars[start..i].iter().collect();
                    let num: f64 = num_str.parse().ok()?;
                    tokens.push(RT::Num(num));
                }
                '-' => {
                    // Negative number: at start, or after '(' or after an operator
                    let is_unary_minus = tokens.is_empty()
                        || matches!(tokens.last(), Some(RT::LParen) | Some(RT::Op(_)));
                    if is_unary_minus
                        && i + 1 < chars.len()
                        && (chars[i + 1].is_ascii_digit() || chars[i + 1] == '.')
                    {
                        i += 1; // skip '-'
                        let start = i;
                        while i < chars.len() && (chars[i].is_ascii_digit() || chars[i] == '.') {
                            i += 1;
                        }
                        let num_str: String = chars[start..i].iter().collect();
                        let num: f64 = num_str.parse().ok()?;
                        tokens.push(RT::Num(-num));
                    } else {
                        return None; // Subtraction not supported
                    }
                }
                _ => return None,
            }
        }

        Some(tokens)
    }

    fn shunting_yard(raw: Vec<RawToken>) -> Option<Vec<CalcToken>> {
        use RawToken as RT;
        let mut output: Vec<CalcToken> = Vec::new();
        let mut op_stack: Vec<RawToken> = Vec::new();

        for tok in raw {
            match tok {
                RT::Num(n) => output.push(CalcToken::Num(n)),
                RT::VarA => output.push(CalcToken::VarA),
                RT::VarB => output.push(CalcToken::VarB),
                RT::Op(ref op) => {
                    while let Some(RT::Op(top_op)) = op_stack.last() {
                        let top_prec = Self::precedence(top_op);
                        let cur_prec = Self::precedence(op);
                        if (!Self::is_right_assoc(op) && cur_prec <= top_prec)
                            || (Self::is_right_assoc(op) && cur_prec < top_prec)
                        {
                            if let Some(RT::Op(o)) = op_stack.pop() {
                                output.push(CalcToken::Op(o));
                            }
                        } else {
                            break;
                        }
                    }
                    op_stack.push(tok);
                }
                RT::LParen => op_stack.push(tok),
                RT::RParen => {
                    loop {
                        match op_stack.pop() {
                            Some(RT::LParen) => break,
                            Some(RT::Op(o)) => output.push(CalcToken::Op(o)),
                            _ => return None, // Mismatched parens
                        }
                    }
                }
            }
        }

        // Pop remaining operators
        while let Some(tok) = op_stack.pop() {
            match tok {
                RT::Op(o) => output.push(CalcToken::Op(o)),
                RT::LParen => return None, // Mismatched parens
                _ => return None,
            }
        }

        Some(output)
    }
}

/// Trigger condition for circular buffer.
#[derive(Debug, Clone)]
pub enum TriggerCondition {
    /// Trigger on an attribute value exceeding threshold.
    AttributeThreshold { name: String, threshold: f64 },
    /// External trigger (manual).
    External,
    /// Calculated trigger based on two attribute values and an expression.
    Calc {
        attr_a: String,
        attr_b: String,
        expression: CalcExpression,
    },
}

/// Status of the circular buffer.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum BufferStatus {
    Idle,
    BufferFilling,
    Flushing,
    AcquisitionCompleted,
}

/// Circular buffer state for pre/post-trigger capture.
pub struct CircularBuffer {
    pub(crate) pre_count: usize,
    pub(crate) post_count: usize,
    buffer: VecDeque<Arc<NDArray>>,
    pub(crate) trigger_condition: TriggerCondition,
    triggered: bool,
    post_remaining: usize,
    captured: Vec<Arc<NDArray>>,
    /// Maximum number of triggers before stopping (0 = unlimited).
    preset_trigger_count: usize,
    /// Number of triggers fired so far.
    trigger_count: usize,
    /// If true, flush buffer immediately on soft trigger.
    flush_on_soft_trigger: bool,
    /// Current buffer status.
    pub(crate) status: BufferStatus,
}

impl CircularBuffer {
    pub fn new(pre_count: usize, post_count: usize, condition: TriggerCondition) -> Self {
        Self {
            pre_count,
            post_count,
            buffer: VecDeque::with_capacity(pre_count + 1),
            trigger_condition: condition,
            triggered: false,
            post_remaining: 0,
            captured: Vec::new(),
            preset_trigger_count: 0,
            trigger_count: 0,
            flush_on_soft_trigger: false,
            status: BufferStatus::Idle,
        }
    }

    /// Set the preset trigger count (0 = unlimited).
    pub fn set_preset_trigger_count(&mut self, count: usize) {
        self.preset_trigger_count = count;
    }

    /// Get the current trigger count.
    pub fn trigger_count(&self) -> usize {
        self.trigger_count
    }

    /// Get the current buffer status.
    pub fn status(&self) -> BufferStatus {
        self.status
    }

    /// Set flush_on_soft_trigger flag.
    pub fn set_flush_on_soft_trigger(&mut self, flush: bool) {
        self.flush_on_soft_trigger = flush;
    }

    /// Push an array into the circular buffer.
    /// Returns true if a complete capture sequence is ready.
    pub fn push(&mut self, array: Arc<NDArray>) -> bool {
        // If acquisition is completed, ignore new frames
        if self.status == BufferStatus::AcquisitionCompleted {
            return false;
        }

        // Transition from Idle to BufferFilling on first push
        if self.status == BufferStatus::Idle {
            self.status = BufferStatus::BufferFilling;
        }

        if self.triggered {
            // Post-trigger capture (Flushing state)
            self.captured.push(array);
            self.post_remaining -= 1;
            if self.post_remaining == 0 {
                self.triggered = false;
                // Check if we've reached the preset trigger count
                if self.preset_trigger_count > 0 && self.trigger_count >= self.preset_trigger_count
                {
                    self.status = BufferStatus::AcquisitionCompleted;
                } else {
                    self.status = BufferStatus::BufferFilling;
                }
                return true;
            }
            return false;
        }

        // Check trigger condition
        let trigger = match &self.trigger_condition {
            TriggerCondition::AttributeThreshold { name, threshold } => array
                .attributes
                .get(name)
                .and_then(|a| a.value.as_f64())
                .map(|v| v >= *threshold)
                .unwrap_or(false),
            TriggerCondition::External => false,
            TriggerCondition::Calc {
                attr_a,
                attr_b,
                expression,
            } => {
                let a = array
                    .attributes
                    .get(attr_a)
                    .and_then(|a| a.value.as_f64())
                    .unwrap_or(0.0);
                let b = array
                    .attributes
                    .get(attr_b)
                    .and_then(|a| a.value.as_f64())
                    .unwrap_or(0.0);
                expression.evaluate(a, b) != 0.0
            }
        };

        // Maintain pre-trigger ring buffer
        self.buffer.push_back(array);
        if self.buffer.len() > self.pre_count {
            self.buffer.pop_front();
        }

        if trigger {
            self.trigger();
        }

        false
    }

    /// External trigger.
    pub fn trigger(&mut self) {
        // Don't trigger if acquisition already completed
        if self.status == BufferStatus::AcquisitionCompleted {
            return;
        }

        self.triggered = true;
        self.post_remaining = self.post_count;
        self.trigger_count += 1;
        self.status = BufferStatus::Flushing;
        // Flush pre-trigger buffer to captured
        self.captured.clear();
        self.captured.extend(self.buffer.drain(..));
    }

    /// Take the captured arrays (pre + post trigger).
    pub fn take_captured(&mut self) -> Vec<Arc<NDArray>> {
        std::mem::take(&mut self.captured)
    }

    pub fn is_triggered(&self) -> bool {
        self.triggered
    }

    pub fn pre_buffer_len(&self) -> usize {
        self.buffer.len()
    }

    pub fn reset(&mut self) {
        self.buffer.clear();
        self.captured.clear();
        self.triggered = false;
        self.post_remaining = 0;
        self.trigger_count = 0;
        self.status = BufferStatus::Idle;
    }
}

// --- New CircularBuffProcessor (NDPluginProcess-based) ---

/// CircularBuff processor: maintains ring buffer state, emits captured arrays on trigger.
#[derive(Default)]
struct CBParamIndices {
    control: Option<usize>,
    status: Option<usize>,
    trigger_a: Option<usize>,
    trigger_b: Option<usize>,
    trigger_a_val: Option<usize>,
    trigger_b_val: Option<usize>,
    trigger_calc: Option<usize>,
    trigger_calc_val: Option<usize>,
    pre_trigger: Option<usize>,
    post_trigger: Option<usize>,
    current_image: Option<usize>,
    post_count: Option<usize>,
    soft_trigger: Option<usize>,
    triggered: Option<usize>,
    preset_trigger_count: Option<usize>,
    actual_trigger_count: Option<usize>,
    flush_on_soft_trigger: Option<usize>,
}

pub struct CircularBuffProcessor {
    buffer: CircularBuffer,
    params: CBParamIndices,
    // cached trigger attribute names and calc expression
    trigger_a_name: String,
    trigger_b_name: String,
    trigger_calc_expr: String,
}

impl CircularBuffProcessor {
    pub fn new(pre_count: usize, post_count: usize, condition: TriggerCondition) -> Self {
        Self {
            buffer: CircularBuffer::new(pre_count, post_count, condition),
            params: CBParamIndices::default(),
            trigger_a_name: String::new(),
            trigger_b_name: String::new(),
            trigger_calc_expr: String::new(),
        }
    }

    pub fn trigger(&mut self) {
        self.buffer.trigger();
    }

    pub fn buffer(&self) -> &CircularBuffer {
        &self.buffer
    }

    /// Rebuild the trigger condition from cached attribute names and calc expression.
    fn rebuild_trigger_condition(&mut self) {
        if !self.trigger_calc_expr.is_empty() {
            if let Some(expr) = CalcExpression::parse(&self.trigger_calc_expr) {
                self.buffer.trigger_condition = TriggerCondition::Calc {
                    attr_a: self.trigger_a_name.clone(),
                    attr_b: self.trigger_b_name.clone(),
                    expression: expr,
                };
                return;
            }
        }
        if !self.trigger_a_name.is_empty() {
            self.buffer.trigger_condition = TriggerCondition::AttributeThreshold {
                name: self.trigger_a_name.clone(),
                threshold: 0.5,
            };
        } else {
            self.buffer.trigger_condition = TriggerCondition::External;
        }
    }
}

impl NDPluginProcess for CircularBuffProcessor {
    fn process_array(&mut self, array: &NDArray, _pool: &NDArrayPool) -> ProcessResult {
        use ad_core_rs::plugin::runtime::ParamUpdate;

        let done = self.buffer.push(Arc::new(array.clone()));

        let mut updates = Vec::new();
        if let Some(idx) = self.params.status {
            let status_val = match self.buffer.status() {
                BufferStatus::Idle => 0,
                BufferStatus::BufferFilling => 1,
                BufferStatus::Flushing => 2,
                BufferStatus::AcquisitionCompleted => 3,
            };
            updates.push(ParamUpdate::int32(idx, status_val));
        }
        if let Some(idx) = self.params.current_image {
            updates.push(ParamUpdate::int32(idx, self.buffer.pre_buffer_len() as i32));
        }
        if let Some(idx) = self.params.triggered {
            updates.push(ParamUpdate::int32(
                idx,
                if self.buffer.is_triggered() { 1 } else { 0 },
            ));
        }
        if let Some(idx) = self.params.actual_trigger_count {
            updates.push(ParamUpdate::int32(idx, self.buffer.trigger_count() as i32));
        }

        if done {
            let mut result = ProcessResult::arrays(self.buffer.take_captured());
            result.param_updates = updates;
            result
        } else {
            ProcessResult::sink(updates)
        }
    }

    fn plugin_type(&self) -> &str {
        "NDPluginCircularBuff"
    }

    fn register_params(
        &mut self,
        base: &mut asyn_rs::port::PortDriverBase,
    ) -> asyn_rs::error::AsynResult<()> {
        use asyn_rs::param::ParamType;
        base.create_param("CIRC_BUFF_CONTROL", ParamType::Int32)?;
        base.create_param("CIRC_BUFF_STATUS", ParamType::Int32)?;
        base.create_param("CIRC_BUFF_TRIGGER_A", ParamType::Octet)?;
        base.create_param("CIRC_BUFF_TRIGGER_B", ParamType::Octet)?;
        base.create_param("CIRC_BUFF_TRIGGER_A_VAL", ParamType::Float64)?;
        base.create_param("CIRC_BUFF_TRIGGER_B_VAL", ParamType::Float64)?;
        base.create_param("CIRC_BUFF_TRIGGER_CALC", ParamType::Octet)?;
        base.create_param("CIRC_BUFF_TRIGGER_CALC_VAL", ParamType::Float64)?;
        base.create_param("CIRC_BUFF_PRE_TRIGGER", ParamType::Int32)?;
        base.create_param("CIRC_BUFF_POST_TRIGGER", ParamType::Int32)?;
        base.create_param("CIRC_BUFF_CURRENT_IMAGE", ParamType::Int32)?;
        base.create_param("CIRC_BUFF_POST_COUNT", ParamType::Int32)?;
        base.create_param("CIRC_BUFF_SOFT_TRIGGER", ParamType::Int32)?;
        base.create_param("CIRC_BUFF_TRIGGERED", ParamType::Int32)?;
        base.create_param("CIRC_BUFF_PRESET_TRIGGER_COUNT", ParamType::Int32)?;
        base.create_param("CIRC_BUFF_ACTUAL_TRIGGER_COUNT", ParamType::Int32)?;
        base.create_param("CIRC_BUFF_FLUSH_ON_SOFTTRIGGER", ParamType::Int32)?;

        self.params.control = base.find_param("CIRC_BUFF_CONTROL");
        self.params.status = base.find_param("CIRC_BUFF_STATUS");
        self.params.trigger_a = base.find_param("CIRC_BUFF_TRIGGER_A");
        self.params.trigger_b = base.find_param("CIRC_BUFF_TRIGGER_B");
        self.params.trigger_a_val = base.find_param("CIRC_BUFF_TRIGGER_A_VAL");
        self.params.trigger_b_val = base.find_param("CIRC_BUFF_TRIGGER_B_VAL");
        self.params.trigger_calc = base.find_param("CIRC_BUFF_TRIGGER_CALC");
        self.params.trigger_calc_val = base.find_param("CIRC_BUFF_TRIGGER_CALC_VAL");
        self.params.pre_trigger = base.find_param("CIRC_BUFF_PRE_TRIGGER");
        self.params.post_trigger = base.find_param("CIRC_BUFF_POST_TRIGGER");
        self.params.current_image = base.find_param("CIRC_BUFF_CURRENT_IMAGE");
        self.params.post_count = base.find_param("CIRC_BUFF_POST_COUNT");
        self.params.soft_trigger = base.find_param("CIRC_BUFF_SOFT_TRIGGER");
        self.params.triggered = base.find_param("CIRC_BUFF_TRIGGERED");
        self.params.preset_trigger_count = base.find_param("CIRC_BUFF_PRESET_TRIGGER_COUNT");
        self.params.actual_trigger_count = base.find_param("CIRC_BUFF_ACTUAL_TRIGGER_COUNT");
        self.params.flush_on_soft_trigger = base.find_param("CIRC_BUFF_FLUSH_ON_SOFTTRIGGER");
        Ok(())
    }

    fn on_param_change(
        &mut self,
        reason: usize,
        params: &ad_core_rs::plugin::runtime::PluginParamSnapshot,
    ) -> ad_core_rs::plugin::runtime::ParamChangeResult {
        use ad_core_rs::plugin::runtime::{ParamChangeResult, ParamChangeValue};

        if Some(reason) == self.params.control {
            let v = params.value.as_i32();
            if v == 1 {
                // Start
                self.buffer.reset();
                self.buffer.status = BufferStatus::BufferFilling;
            } else {
                // Stop
                self.buffer.status = BufferStatus::Idle;
            }
        } else if Some(reason) == self.params.pre_trigger {
            self.buffer.pre_count = params.value.as_i32().max(0) as usize;
        } else if Some(reason) == self.params.post_trigger {
            self.buffer.post_count = params.value.as_i32().max(0) as usize;
        } else if Some(reason) == self.params.preset_trigger_count {
            self.buffer
                .set_preset_trigger_count(params.value.as_i32().max(0) as usize);
        } else if Some(reason) == self.params.flush_on_soft_trigger {
            self.buffer
                .set_flush_on_soft_trigger(params.value.as_i32() != 0);
        } else if Some(reason) == self.params.soft_trigger {
            if params.value.as_i32() != 0 {
                self.buffer.trigger();
            }
        } else if Some(reason) == self.params.trigger_a {
            if let ParamChangeValue::Octet(s) = &params.value {
                self.trigger_a_name = s.clone();
                self.rebuild_trigger_condition();
            }
        } else if Some(reason) == self.params.trigger_b {
            if let ParamChangeValue::Octet(s) = &params.value {
                self.trigger_b_name = s.clone();
                self.rebuild_trigger_condition();
            }
        } else if Some(reason) == self.params.trigger_calc {
            if let ParamChangeValue::Octet(s) = &params.value {
                self.trigger_calc_expr = s.clone();
                self.rebuild_trigger_condition();
            }
        }

        ParamChangeResult::updates(vec![])
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use ad_core_rs::attributes::{NDAttrSource, NDAttrValue, NDAttribute};
    use ad_core_rs::ndarray::{NDDataType, NDDimension};

    fn make_array(id: i32) -> Arc<NDArray> {
        let mut arr = NDArray::new(vec![NDDimension::new(4)], NDDataType::UInt8);
        arr.unique_id = id;
        Arc::new(arr)
    }

    fn make_array_with_attr(id: i32, attr_val: f64) -> Arc<NDArray> {
        let mut arr = NDArray::new(vec![NDDimension::new(4)], NDDataType::UInt8);
        arr.unique_id = id;
        arr.attributes.add(NDAttribute {
            name: "trigger".into(),
            description: "".into(),
            source: NDAttrSource::Driver,
            value: NDAttrValue::Float64(attr_val),
        });
        Arc::new(arr)
    }

    fn make_array_with_attrs(id: i32, a_val: f64, b_val: f64) -> Arc<NDArray> {
        let mut arr = NDArray::new(vec![NDDimension::new(4)], NDDataType::UInt8);
        arr.unique_id = id;
        arr.attributes.add(NDAttribute {
            name: "attr_a".into(),
            description: "".into(),
            source: NDAttrSource::Driver,
            value: NDAttrValue::Float64(a_val),
        });
        arr.attributes.add(NDAttribute {
            name: "attr_b".into(),
            description: "".into(),
            source: NDAttrSource::Driver,
            value: NDAttrValue::Float64(b_val),
        });
        Arc::new(arr)
    }

    #[test]
    fn test_pre_trigger_buffering() {
        let mut cb = CircularBuffer::new(3, 2, TriggerCondition::External);

        for i in 0..5 {
            cb.push(make_array(i));
        }
        // Pre-buffer should hold last 3
        assert_eq!(cb.pre_buffer_len(), 3);
    }

    #[test]
    fn test_external_trigger() {
        let mut cb = CircularBuffer::new(2, 2, TriggerCondition::External);

        cb.push(make_array(1));
        cb.push(make_array(2));
        cb.push(make_array(3));
        // Pre-buffer: [2, 3]

        cb.trigger();
        assert!(cb.is_triggered());

        cb.push(make_array(4));
        let done = cb.push(make_array(5));
        assert!(done);

        let captured = cb.take_captured();
        assert_eq!(captured.len(), 4); // 2 pre + 2 post
        assert_eq!(captured[0].unique_id, 2);
        assert_eq!(captured[1].unique_id, 3);
        assert_eq!(captured[2].unique_id, 4);
        assert_eq!(captured[3].unique_id, 5);
    }

    #[test]
    fn test_attribute_trigger() {
        let mut cb = CircularBuffer::new(
            1,
            1,
            TriggerCondition::AttributeThreshold {
                name: "trigger".into(),
                threshold: 5.0,
            },
        );

        cb.push(make_array_with_attr(1, 1.0));
        cb.push(make_array_with_attr(2, 2.0));
        assert!(!cb.is_triggered());

        // This should trigger (attr >= 5.0)
        cb.push(make_array_with_attr(3, 5.0));
        assert!(cb.is_triggered());

        let done = cb.push(make_array(4));
        assert!(done);

        let captured = cb.take_captured();
        assert_eq!(captured.len(), 2); // 1 pre + 1 post
    }

    // --- New tests ---

    #[test]
    fn test_calc_trigger() {
        // Expression: "A>5" — trigger when attribute A exceeds 5
        let expr = CalcExpression::parse("A>5").unwrap();
        let mut cb = CircularBuffer::new(
            1,
            1,
            TriggerCondition::Calc {
                attr_a: "attr_a".into(),
                attr_b: "attr_b".into(),
                expression: expr,
            },
        );

        // A=3, should not trigger
        cb.push(make_array_with_attrs(1, 3.0, 0.0));
        assert!(!cb.is_triggered());

        // A=6, should trigger
        cb.push(make_array_with_attrs(2, 6.0, 0.0));
        assert!(cb.is_triggered());

        let done = cb.push(make_array(3));
        assert!(done);

        let captured = cb.take_captured();
        assert_eq!(captured.len(), 2); // 1 pre + 1 post
    }

    #[test]
    fn test_calc_expression_parse() {
        // Simple comparison
        let expr = CalcExpression::parse("A>5").unwrap();
        assert_eq!(expr.evaluate(6.0, 0.0), 1.0);
        assert_eq!(expr.evaluate(4.0, 0.0), 0.0);
        assert_eq!(expr.evaluate(5.0, 0.0), 0.0); // not >=

        // Greater-or-equal
        let expr = CalcExpression::parse("A>=5").unwrap();
        assert_eq!(expr.evaluate(5.0, 0.0), 1.0);
        assert_eq!(expr.evaluate(4.9, 0.0), 0.0);

        // Logical AND with two variables
        let expr = CalcExpression::parse("A>3&&B<10").unwrap();
        assert_eq!(expr.evaluate(4.0, 5.0), 1.0);
        assert_eq!(expr.evaluate(2.0, 5.0), 0.0);
        assert_eq!(expr.evaluate(4.0, 15.0), 0.0);

        // Parenthesized OR
        let expr = CalcExpression::parse("(A>10)||(B>10)").unwrap();
        assert_eq!(expr.evaluate(11.0, 0.0), 1.0);
        assert_eq!(expr.evaluate(0.0, 11.0), 1.0);
        assert_eq!(expr.evaluate(0.0, 0.0), 0.0);

        // Not-equal
        let expr = CalcExpression::parse("A!=0").unwrap();
        assert_eq!(expr.evaluate(1.0, 0.0), 1.0);
        assert_eq!(expr.evaluate(0.0, 0.0), 0.0);

        // Equality
        let expr = CalcExpression::parse("A==B").unwrap();
        assert_eq!(expr.evaluate(5.0, 5.0), 1.0);
        assert_eq!(expr.evaluate(5.0, 6.0), 0.0);

        // Not operator
        let expr = CalcExpression::parse("!A").unwrap();
        assert_eq!(expr.evaluate(0.0, 0.0), 1.0);
        assert_eq!(expr.evaluate(1.0, 0.0), 0.0);

        // Invalid expression returns None
        assert!(CalcExpression::parse("A=5").is_none()); // single = not supported
        assert!(CalcExpression::parse("A&B").is_none()); // single & not supported
    }

    #[test]
    fn test_preset_trigger_count() {
        let mut cb = CircularBuffer::new(1, 1, TriggerCondition::External);
        cb.set_preset_trigger_count(2);

        assert_eq!(cb.status(), BufferStatus::Idle);

        // First push transitions to BufferFilling
        cb.push(make_array(1));
        assert_eq!(cb.status(), BufferStatus::BufferFilling);

        // First trigger
        cb.trigger();
        assert_eq!(cb.trigger_count(), 1);
        assert_eq!(cb.status(), BufferStatus::Flushing);

        let done = cb.push(make_array(2));
        assert!(done);
        assert_eq!(cb.status(), BufferStatus::BufferFilling); // back to filling after first capture

        cb.take_captured();

        // Refill buffer
        cb.push(make_array(3));

        // Second trigger — should reach preset count
        cb.trigger();
        assert_eq!(cb.trigger_count(), 2);
        assert_eq!(cb.status(), BufferStatus::Flushing);

        let done = cb.push(make_array(4));
        assert!(done);
        assert_eq!(cb.status(), BufferStatus::AcquisitionCompleted);

        cb.take_captured();

        // Further frames should be ignored
        let done = cb.push(make_array(5));
        assert!(!done);
        assert_eq!(cb.status(), BufferStatus::AcquisitionCompleted);

        // Further triggers should be ignored
        cb.trigger();
        assert_eq!(cb.trigger_count(), 2); // unchanged
    }

    #[test]
    fn test_buffer_status_transitions() {
        let mut cb = CircularBuffer::new(2, 1, TriggerCondition::External);

        // Initial state
        assert_eq!(cb.status(), BufferStatus::Idle);

        // First push -> BufferFilling
        cb.push(make_array(1));
        assert_eq!(cb.status(), BufferStatus::BufferFilling);

        cb.push(make_array(2));
        assert_eq!(cb.status(), BufferStatus::BufferFilling);

        // Trigger -> Flushing
        cb.trigger();
        assert_eq!(cb.status(), BufferStatus::Flushing);

        // Post-trigger capture completes -> back to BufferFilling
        let done = cb.push(make_array(3));
        assert!(done);
        assert_eq!(cb.status(), BufferStatus::BufferFilling);

        // Reset -> Idle
        cb.reset();
        assert_eq!(cb.status(), BufferStatus::Idle);
        assert_eq!(cb.trigger_count(), 0);
    }
}