bacnet-server 0.15.0

BACnet server: APDU dispatch and service handlers
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
//! Event Enrollment algorithmic evaluation.
//!
//! Unlike intrinsic reporting (built into object types), Event Enrollment is a
//! separate object that monitors another object's property and evaluates an
//! algorithm against it.
//!
//! Supported algorithms: OUT_OF_RANGE, FLOATING_LIMIT, CHANGE_OF_STATE,
//! CHANGE_OF_BITSTRING, CHANGE_OF_VALUE.
//!
//! Delay model (#163): `Event_Parameters.Time_Delay` (pTimeDelay, Table 12-15)
//! gates every indicated transition into an OFFNORMAL state; the EE object's
//! optional `Time_Delay_Normal` property (pTimeDelayNormal, Table 12-14 O —
//! falling back to pTimeDelay per Clause 13.3) gates transitions to NORMAL.
//! Both delays measure condition persistence in SECONDS (e.g. 13.3.1),
//! and this evaluator
//! keeps them in seconds: the pending countdown (owned by the EE object,
//! in-memory only) is seeded with `ceil(delay_secs / interval_secs)` —
//! never-fire-early ceiling semantics, so at the default 10s
//! `event_enrollment_interval_secs` a 5s delay fires on the second pass
//! (~10s elapsed), not after five passes (~50s) — and advances once per
//! evaluation pass. Semantics otherwise mirror the intrinsic detectors'
//! probe/tick (`bacnet_objects::event`, #120/#225) — condition reverted
//! cancels, same target never restarts, changed target re-seeds — without
//! sharing code across the objects/server boundary.
//!
//! Residual countdown behavior: the interval is builder configuration, not
//! runtime-mutable, and the countdown is in-memory, so no mid-run rescale
//! exists; a restart re-evaluates from the confirmed `Event_State` and a
//! fresh `ceil` conversion, like the intrinsic detectors.
//!
//! Transition actions (#166): an *indicated* transition executes Clause
//! 13.2.2.1.4's actions even when its target equals the current state — the
//! specific returned state is stored in `Event_State`, the corresponding
//! `Acked_Transitions` bit is set/cleared per the referenced Notification
//! Class's `Ack_Required` (Clause 13.2.3), and the transition is emitted with
//! its `Event_Enable`-scoped `distribute` flag. What is NOT here, by design:
//! `Event_Time_Stamps` and `Event_Message_Texts` are committed atomically
//! with `Event_State` and `Acked_Transitions`. The server has no message text
//! of its own for an enrollment, so a transition's text is the matching
//! `Event_Message_Texts_Config` entry, sent as written (no substitution
//! codes), or none when that entry is empty (#1507).
//!
//! `Event_Algorithm_Inhibit` (#1507) gates the algorithm as it does the
//! intrinsic reporters: see `algorithms::inhibited_arm`. A pass that can't
//! read the monitored value at all is an observation gap and changes no
//! state, inhibited or not, so a forced return to NORMAL waits for the next
//! readable pass: its notification carries that value. An enrollment whose
//! parameters this evaluator doesn't run (Opaque, Extended, or another
//! algorithm without an evaluator here) still gets
//! the forced NORMAL, since leaving the OffNormal state under the inhibit
//! doesn't depend on the algorithm (Clause 13.2.2.1.2). With
//! `Event_Algorithm_Inhibit_Ref` set, the value is the referenced property's
//! as of the last refresh: each write of the enrollment, the server's
//! one-second tick and the start of each evaluation pass.
//! The server lifecycle projects successful commits into its shared
//! notification sender without repeating these transition actions.

mod algorithms;
mod api;
mod commit;
mod fault;
mod reference;
mod support;

use std::collections::{HashMap, HashSet};

pub use algorithms::{
    encode_change_of_bitstring_params, encode_change_of_state_params,
    encode_change_of_value_params, encode_floating_limit_params, encode_out_of_range_params,
};
pub use api::{
    EventEnrollmentTransition, evaluate_event_enrollments, evaluate_event_enrollments_report,
};
pub use commit::{
    EventEnrollmentEvaluationDiagnostic, EventEnrollmentEvaluationOutcome,
    EventEnrollmentEvaluationReport, EventEnrollmentEvaluationStage,
    EventEnrollmentReliabilityCause, EventEnrollmentReliabilityResult,
};

use algorithms::{
    ArmEvaluation, eval_change_of_bitstring_struct, eval_change_of_state_struct,
    eval_change_of_value_struct, eval_floating_limit_struct, eval_legacy_le_arm, eval_none_arm,
    eval_out_of_range_struct, extract_bitstring, extract_property_state_value, extract_real,
    inhibited_arm,
};
#[cfg(test)]
use commit::apply_updates;
pub(crate) use commit::log_evaluation_report;
pub(crate) use commit::{
    CommittedEventEnrollmentDelivery, CommittedEventEnrollmentResult,
    EventEnrollmentEvaluationBatch,
};
use commit::{EnrollmentUpdate, FiredTransition, apply_updates_for_delivery};
use fault::{
    FaultAlgorithmEvaluation, MonitoredReliability, SupportedFaultAlgorithm,
    evaluate_fault_algorithm, read_event_parameters, read_fault_algorithm,
    read_monitored_reliability,
};
#[cfg(test)]
use reference::MonitoredReference;
pub(crate) use reference::decode_reference_value;
use reference::{params_fingerprint, read_object_property_ref};
use support::*;

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum LocalConfigurationReadError {
    Malformed,
    Unavailable,
}

use crate::server::event_notification_payload::{
    CapturedReferencedValue, EventEnrollmentProjectionSnapshot, capture_status_flags,
};
use bacnet_objects::database::ObjectDatabase;
#[cfg(test)]
use bacnet_objects::event::EventStateChange;
use bacnet_objects::event::EventTransition;
use bacnet_objects::event_enrollment::{EventEnrollmentEvalState, EventEnrollmentPending};
#[cfg(test)]
use bacnet_objects::traits::BACnetObject;
use bacnet_types::bitstring::EventTransitionBits;
use bacnet_types::constructed::BACnetEventParameter;
use bacnet_types::enums::{EventState, EventType, ObjectType, PropertyIdentifier, Reliability};
use bacnet_types::primitives::{ObjectIdentifier, PropertyValue};

/// Evaluate and retain the private commit-order stream for server delivery.
pub(crate) fn evaluate_event_enrollments_for_delivery(
    db: &mut ObjectDatabase,
    interval_secs: u64,
) -> EventEnrollmentEvaluationBatch {
    let interval_secs = interval_secs.max(1);
    let oids = db.find_by_type(ObjectType::EVENT_ENROLLMENT);
    // Event_Algorithm_Inhibit follows its reference as of this pass too, on
    // top of the server's one-second tick (#1507).
    for oid in &oids {
        db.follow_event_algorithm_inhibit(oid);
    }
    // The monitored, setpoint and fault references all resolve through this
    // one rule: unqualified or naming this device is local (#1184).
    let local_device = db.local_device();

    let mut updates: HashMap<ObjectIdentifier, EnrollmentUpdate> = HashMap::new();
    let mut database_eval_sources = HashSet::new();

    for oid in &oids {
        let Some(enrollment) = db.get(oid) else {
            continue;
        };

        // Configuration-read exits are classified below. A valid monitored
        // or supporting observation gap applies repository-local D4: private
        // continuity is reset before its typed diagnostic is returned.
        let eval_state_supported = enrollment.enrollment_eval_state_internal().is_some();
        let mut eval_state = enrollment
            .enrollment_eval_state_internal()
            .unwrap_or_default();
        let eval_source = match enrollment.enrollment_eval_source_internal() {
            Some(source) => Some(source),
            None if eval_state_supported => {
                database_eval_sources.insert(*oid);
                Some(db.enrollment_eval_source(oid))
            }
            None => None,
        };
        let force_state_reset = db.enrollment_eval_state_invalidated(oid);

        // Clause 13.2.2.1 suspends evaluation and prohibits transitions while
        // Event_Detection_Enable is FALSE. The accompanying reset is applied by the
        // object when the property is written (Clause 12.12 states the disabled
        // condition as an invariant), so skipping here cannot strand a stale
        // non-NORMAL state the way the pre-#136 Event_Enable gate did, nor a
        // stale countdown — the object-side reset clears the pending state.
        //
        // An object that does not model the property at all reads as an error
        // here and is treated as enabled. The property is required (R) on both
        // Event Enrollment (Table 12-14) and Alert Enrollment (Table 12-61) and
        // optional on most other types, so absence is common and must not
        // silently disable detection.
        if let Ok(PropertyValue::Boolean(false)) =
            enrollment.read_property(PropertyIdentifier::EVENT_DETECTION_ENABLE, None)
        {
            continue;
        }

        let event_type = match enrollment.read_property(PropertyIdentifier::EVENT_TYPE, None) {
            Ok(PropertyValue::Enumerated(v)) => EventType::from_raw(v),
            _ => continue,
        };

        let current_state = match enrollment.read_property(PropertyIdentifier::EVENT_STATE, None) {
            Ok(PropertyValue::Enumerated(v)) => EventState::from_raw(v),
            _ => continue,
        };

        let event_enable = match enrollment.read_property(PropertyIdentifier::EVENT_ENABLE, None) {
            Ok(PropertyValue::BitString { data, .. }) => EventTransitionBits::from_bacnet(&data),
            _ => EventTransitionBits::empty(),
        };

        let current_reliability =
            match enrollment.read_property(PropertyIdentifier::RELIABILITY, None) {
                Ok(PropertyValue::Enumerated(value)) => Reliability::from_raw(value),
                _ => {
                    queue_observation_unavailable(&mut updates, *oid);
                    continue;
                }
            };
        let subject = ReliabilitySubject {
            db,
            enrollment,
            enrollment_oid: *oid,
            previous: current_reliability,
            current_state,
            event_enable,
        };

        // Local configuration is resolved before any target observation. A
        // malformed/missing required reference, malformed parameters, or an
        // unsupported configured fault alternative therefore wins the
        // Reliability precedence chain deterministically.
        let reference = read_object_property_ref(enrollment);
        let params = read_event_parameters(enrollment);
        let fault_algorithm = read_fault_algorithm(enrollment, local_device);
        if matches!(reference, Err(LocalConfigurationReadError::Malformed))
            || matches!(params, Err(LocalConfigurationReadError::Malformed))
            || matches!(fault_algorithm, Err(LocalConfigurationReadError::Malformed))
        {
            let monitored_oid = reference
                .as_ref()
                .ok()
                .map(|reference| reference.object_identifier);
            queue_eval_state_reset(
                &mut updates,
                *oid,
                eval_state_supported,
                &eval_state,
                force_state_reset,
            );
            if matches!(reference, Err(LocalConfigurationReadError::Malformed)) {
                queue_eval_source_reset(&mut updates, *oid, eval_source);
            }
            queue_reliability_transition(
                &mut updates,
                &subject,
                monitored_oid,
                Reliability::CONFIGURATION_ERROR,
                EventEnrollmentReliabilityCause::Configuration,
                CapturedReferencedValue::Unavailable,
            );
            continue;
        }

        if matches!(reference, Err(LocalConfigurationReadError::Unavailable)) {
            queue_observation_gap(&mut updates, *oid, eval_state_supported, eval_source);
            continue;
        }
        if matches!(params, Err(LocalConfigurationReadError::Unavailable)) {
            queue_pending_cancellation(&mut updates, *oid, eval_state_supported, &mut eval_state);
            continue;
        }
        if matches!(
            fault_algorithm,
            Err(LocalConfigurationReadError::Unavailable)
        ) {
            queue_observation_unavailable(&mut updates, *oid);
            continue;
        }

        let monitored = reference.expect("validated reference");
        let params = params.expect("validated Event_Parameters");
        let fault_algorithm = fault_algorithm.expect("validated Fault_Parameters");

        // A well-formed remote target is temporarily unobservable in this
        // local-only slice. D4 clears only private continuity; no persistent
        // target-loss Reliability policy is inferred.
        if !local_device.is_local(monitored.device_identifier) {
            queue_observation_gap(&mut updates, *oid, eval_state_supported, eval_source);
            continue;
        }

        let monitored_oid = monitored.object_identifier;
        let monitored_prop = monitored.property_identifier;
        let monitored_reference = (monitored_oid, monitored_prop, monitored.array_index);
        // Private evaluation state belongs to one exact monitored source. A
        // nonempty ownerless state cannot be adopted safely. Mutations remain
        // staged until phase 2; a later observation gap overwrites them with
        // the D4 ownerless default.
        let source_changed = match eval_source {
            Some(Some(current)) => current != monitored_reference,
            Some(None) => eval_state != EventEnrollmentEvalState::default(),
            None => false,
        };
        let reset_evaluation_state = source_changed || force_state_reset;
        if reset_evaluation_state {
            eval_state = EventEnrollmentEvalState::default();
        }

        let Some(monitored_obj) = db.get(&monitored_oid) else {
            queue_observation_gap(&mut updates, *oid, eval_state_supported, eval_source);
            continue;
        };
        if monitored.array_index.is_some() && !monitored_obj.is_array_property(monitored_prop) {
            queue_invalid_reference(&mut updates, *oid, eval_state_supported, eval_source);
            queue_reliability_transition(
                &mut updates,
                &subject,
                Some(monitored_oid),
                Reliability::CONFIGURATION_ERROR,
                EventEnrollmentReliabilityCause::Configuration,
                CapturedReferencedValue::Unavailable,
            );
            continue;
        }

        match read_monitored_reliability(monitored_obj) {
            MonitoredReliability::ConfigurationError => {
                queue_evaluation_ownership(
                    &mut updates,
                    *oid,
                    eval_state_supported,
                    reset_evaluation_state,
                    eval_source,
                    monitored_reference,
                );
                queue_reliability_transition(
                    &mut updates,
                    &subject,
                    Some(monitored_oid),
                    Reliability::CONFIGURATION_ERROR,
                    EventEnrollmentReliabilityCause::Configuration,
                    CapturedReferencedValue::NotEvaluated,
                );
                continue;
            }
            MonitoredReliability::ObservationUnavailable => {
                queue_observation_gap(&mut updates, *oid, eval_state_supported, eval_source);
                continue;
            }
            MonitoredReliability::Value(reliability)
                if reliability != Reliability::NO_FAULT_DETECTED =>
            {
                queue_evaluation_ownership(
                    &mut updates,
                    *oid,
                    eval_state_supported,
                    reset_evaluation_state,
                    eval_source,
                    monitored_reference,
                );
                queue_reliability_transition(
                    &mut updates,
                    &subject,
                    Some(monitored_oid),
                    Reliability::MONITORED_OBJECT_FAULT,
                    EventEnrollmentReliabilityCause::MonitoredObject,
                    CapturedReferencedValue::NotEvaluated,
                );
                continue;
            }
            MonitoredReliability::Absent | MonitoredReliability::Value(_) => {}
        }

        let mut monitored_value = None;
        if matches!(fault_algorithm, SupportedFaultAlgorithm::OutOfRange { .. }) {
            match monitored_obj.read_property(monitored_prop, monitored.array_index) {
                Ok(value) => monitored_value = Some(value),
                Err(error)
                    if monitored.array_index.is_some() && invalid_indexed_target_error(&error) =>
                {
                    queue_invalid_reference(&mut updates, *oid, eval_state_supported, eval_source);
                    queue_reliability_transition(
                        &mut updates,
                        &subject,
                        Some(monitored_oid),
                        Reliability::CONFIGURATION_ERROR,
                        EventEnrollmentReliabilityCause::Configuration,
                        CapturedReferencedValue::Unavailable,
                    );
                    continue;
                }
                Err(_) => {
                    queue_observation_gap(&mut updates, *oid, eval_state_supported, eval_source);
                    continue;
                }
            }
        }

        match evaluate_fault_algorithm(db, &fault_algorithm, monitored_value.as_ref()) {
            FaultAlgorithmEvaluation::ConfigurationError => {
                queue_evaluation_ownership(
                    &mut updates,
                    *oid,
                    eval_state_supported,
                    reset_evaluation_state,
                    eval_source,
                    monitored_reference,
                );
                queue_reliability_transition(
                    &mut updates,
                    &subject,
                    Some(monitored_oid),
                    Reliability::CONFIGURATION_ERROR,
                    EventEnrollmentReliabilityCause::Configuration,
                    CapturedReferencedValue::from_evaluated(monitored_value.as_ref()),
                );
                continue;
            }
            FaultAlgorithmEvaluation::ObservationUnavailable => {
                queue_observation_gap(&mut updates, *oid, eval_state_supported, eval_source);
                continue;
            }
            FaultAlgorithmEvaluation::Fault(reliability) => {
                queue_evaluation_ownership(
                    &mut updates,
                    *oid,
                    eval_state_supported,
                    reset_evaluation_state,
                    eval_source,
                    monitored_reference,
                );
                queue_reliability_transition(
                    &mut updates,
                    &subject,
                    Some(monitored_oid),
                    reliability,
                    EventEnrollmentReliabilityCause::FaultAlgorithm,
                    CapturedReferencedValue::from_evaluated(monitored_value.as_ref()),
                );
                continue;
            }
            FaultAlgorithmEvaluation::Healthy => {}
        }

        if current_reliability != Reliability::NO_FAULT_DETECTED
            || current_state == EventState::FAULT
        {
            eval_state = EventEnrollmentEvalState::default();
            queue_evaluation_ownership(
                &mut updates,
                *oid,
                eval_state_supported,
                true,
                eval_source,
                monitored_reference,
            );
            let cause = if current_reliability == Reliability::CONFIGURATION_ERROR {
                EventEnrollmentReliabilityCause::Configuration
            } else if current_reliability == Reliability::MONITORED_OBJECT_FAULT {
                EventEnrollmentReliabilityCause::MonitoredObject
            } else {
                EventEnrollmentReliabilityCause::FaultAlgorithm
            };
            queue_reliability_transition(
                &mut updates,
                &subject,
                Some(monitored_oid),
                Reliability::NO_FAULT_DETECTED,
                cause,
                CapturedReferencedValue::from_evaluated(monitored_value.as_ref()),
            );
            continue;
        }

        let monitored_value = match monitored_value {
            Some(value) => value,
            None => match monitored_obj.read_property(monitored_prop, monitored.array_index) {
                Ok(value) => value,
                Err(error)
                    if monitored.array_index.is_some() && invalid_indexed_target_error(&error) =>
                {
                    queue_invalid_reference(&mut updates, *oid, eval_state_supported, eval_source);
                    queue_reliability_transition(
                        &mut updates,
                        &subject,
                        Some(monitored_oid),
                        Reliability::CONFIGURATION_ERROR,
                        EventEnrollmentReliabilityCause::Configuration,
                        CapturedReferencedValue::Unavailable,
                    );
                    continue;
                }
                Err(_) => {
                    queue_observation_gap(&mut updates, *oid, eval_state_supported, eval_source);
                    continue;
                }
            },
        };

        queue_evaluation_ownership(
            &mut updates,
            *oid,
            eval_state_supported,
            reset_evaluation_state,
            eval_source,
            monitored_reference,
        );

        // The effective normal-direction delay: the EE object's read arm
        // applies the Clause 13.3 fallback (Time_Delay_Normal absent → the
        // Event_Parameters Time_Delay), so this read IS pTimeDelayNormal.
        let normal_delay =
            match enrollment.read_property(PropertyIdentifier::TIME_DELAY_NORMAL, None) {
                Ok(PropertyValue::Unsigned(v)) => u32::try_from(v).unwrap_or(u32::MAX),
                _ => 0,
            };

        // An object whose trait implementation predates the private state
        // channel evaluates without a durable countdown or COV baseline.
        let mut eval_state_dirty = false;

        // Event_Algorithm_Inhibit (Clauses 12.12.18 and 13.2.2.1.5) sets the
        // algorithm aside; fault handling above has already run. It is read
        // before any exit that the algorithm's own inputs could take (a
        // parameter fingerprint, a monitored value of the wrong datatype, a
        // setpoint gap), so an offnormal enrollment returns to NORMAL whenever
        // its monitored value can be read. See `inhibited_arm`.
        let inhibited = matches!(
            enrollment.read_property(PropertyIdentifier::EVENT_ALGORITHM_INHIBIT, None),
            Ok(PropertyValue::Boolean(true))
        );

        // A parameter (or reference) change mid-pending cancels the countdown
        // and re-gates from the current parameters; no partial countdown is
        // resumed. An inhibited pass seeds no countdown, so it needs none.
        let fingerprint =
            match params_fingerprint(&params, normal_delay as u64, event_type, &monitored) {
                Ok(fingerprint) => Some(fingerprint),
                Err(_) if inhibited => None,
                Err(_) => {
                    queue_pending_cancellation(
                        &mut updates,
                        *oid,
                        eval_state_supported,
                        &mut eval_state,
                    );
                    continue;
                }
            };
        if eval_state
            .pending
            .as_ref()
            .is_some_and(|p| Some(p.params_fingerprint) != fingerprint)
        {
            eval_state.pending = None;
            if eval_state_supported {
                updates
                    .entry(*oid)
                    .or_default()
                    .set_eval_state(eval_state.clone());
            }
        }

        let mut projection_setpoint = None;
        let (time_delay, arm) = match &params {
            _ if inhibited => {
                // The forced NORMAL's notification wants the setpoint too,
                // when it can be read; a gap only leaves it out.
                if let BACnetEventParameter::FloatingLimit {
                    setpoint_reference, ..
                } = &params
                    && let SetpointRead::Value(setpoint) =
                        read_setpoint(db, local_device, setpoint_reference)
                {
                    projection_setpoint = Some(setpoint);
                }
                (0, inhibited_arm(&params, &monitored_value, current_state))
            }
            BACnetEventParameter::OutOfRange {
                high_limit,
                low_limit,
                deadband,
                time_delay,
            } => {
                let Some(val) = extract_real(&monitored_value) else {
                    queue_pending_cancellation(
                        &mut updates,
                        *oid,
                        eval_state_supported,
                        &mut eval_state,
                    );
                    continue;
                };
                (
                    *time_delay,
                    eval_out_of_range_struct(
                        *low_limit,
                        *high_limit,
                        *deadband,
                        val,
                        current_state,
                    ),
                )
            }
            BACnetEventParameter::FloatingLimit {
                setpoint_reference,
                low_diff_limit,
                high_diff_limit,
                deadband,
                time_delay,
            } => {
                let Some(val) = extract_real(&monitored_value) else {
                    queue_pending_cancellation(
                        &mut updates,
                        *oid,
                        eval_state_supported,
                        &mut eval_state,
                    );
                    continue;
                };
                let setpoint = match read_setpoint(db, local_device, setpoint_reference) {
                    SetpointRead::Value(value) => value,
                    SetpointRead::Unusable => {
                        queue_pending_cancellation(
                            &mut updates,
                            *oid,
                            eval_state_supported,
                            &mut eval_state,
                        );
                        continue;
                    }
                    SetpointRead::Transient => {
                        queue_observation_gap(
                            &mut updates,
                            *oid,
                            eval_state_supported,
                            eval_source,
                        );
                        continue;
                    }
                };
                projection_setpoint = Some(setpoint);
                (
                    *time_delay,
                    eval_floating_limit_struct(
                        setpoint,
                        *high_diff_limit,
                        *low_diff_limit,
                        *deadband,
                        val,
                        current_state,
                    ),
                )
            }
            BACnetEventParameter::ChangeOfState {
                list_of_values,
                time_delay,
            } => {
                let Some(val) = extract_property_state_value(&monitored_value) else {
                    queue_pending_cancellation(
                        &mut updates,
                        *oid,
                        eval_state_supported,
                        &mut eval_state,
                    );
                    continue;
                };
                (
                    *time_delay,
                    eval_change_of_state_struct(
                        list_of_values,
                        val,
                        current_state,
                        eval_state.last_offnormal_value,
                    ),
                )
            }
            BACnetEventParameter::ChangeOfBitstring {
                bitmask,
                list_of_values,
                time_delay,
            } => {
                let Some(bits) = extract_bitstring(&monitored_value) else {
                    queue_pending_cancellation(
                        &mut updates,
                        *oid,
                        eval_state_supported,
                        &mut eval_state,
                    );
                    continue;
                };
                (
                    *time_delay,
                    eval_change_of_bitstring_struct(bitmask, list_of_values, &bits, current_state),
                )
            }
            BACnetEventParameter::ChangeOfValue {
                criteria,
                time_delay,
            } => {
                let Some(eval) = eval_change_of_value_struct(
                    criteria,
                    &monitored_value,
                    eval_state.cov_baseline.as_ref(),
                    current_state,
                ) else {
                    queue_pending_cancellation(
                        &mut updates,
                        *oid,
                        eval_state_supported,
                        &mut eval_state,
                    );
                    continue;
                };
                (*time_delay, eval)
            }
            // Legacy raw-octet writes are stored under the sentinel tag 0xFF
            // with the private little-endian payload — only those route to
            // the byte-layout evaluator. A framed write of an alternative
            // under an unassigned tag decodes to `Opaque` too, but its
            // payload is a context-tagged TLV body: feeding tag bytes to the
            // LE evaluator would reinterpret them as IEEE-754 limits and
            // fabricate spurious HIGH/LOW_LIMIT transitions from a peer's
            // configuration. Such alternatives are preserved for read-back
            // but never evaluated.
            //
            // The LE layouts carry no Time_Delay field: delay 0 keeps this
            // path's historical immediate-transition behavior.
            BACnetEventParameter::Opaque { tag: 0xFF, data } => (
                0,
                eval_legacy_le_arm(data, &monitored_value, current_state, event_type),
            ),
            // `none` [20] has no offnormal states (#1868).
            BACnetEventParameter::None => (0, eval_none_arm(current_state)),
            BACnetEventParameter::Opaque { .. } => continue,
            // Extended [9] and the algorithms this evaluator doesn't run
            // (command-failure, change-of-life-safety, buffer-ready,
            // unsigned-range, access-event, the typed out-of-range forms,
            // change-of-characterstring, change-of-status-flags,
            // change-of-discrete-value, change-of-timer) produce no
            // transition here, as when they were kept as `Opaque` (#2090).
            _ => continue,
        };

        let ArmEvaluation {
            indication,
            establish_baseline,
        } = arm;
        if let Some(baseline) = establish_baseline {
            eval_state.cov_baseline = Some(baseline);
            eval_state_dirty = true;
        }

        let Some(ind) = indication else {
            // No condition true — or the condition that seeded the countdown
            // reverted: cancel any pending transition without firing.
            if eval_state.pending.is_some() {
                eval_state.pending = None;
                eval_state_dirty = true;
            }
            if eval_state_dirty && eval_state_supported {
                updates.entry(*oid).or_default().set_eval_state(eval_state);
            }
            continue;
        };
        // Direction-selected delay: pTimeDelay toward OFFNORMAL states,
        // pTimeDelayNormal (already the fallback-composed effective value)
        // toward NORMAL — the Clause 13.3 split, mirroring the intrinsic
        // detectors' `delay_toward` without sharing code across the boundary.
        let delay = if inhibited {
            0
        } else if ind.target == EventState::NORMAL {
            normal_delay
        } else {
            time_delay
        };

        let fired = if let (false, Some(fingerprint)) = (delay == 0, fingerprint) {
            let mut fire = None;
            match &mut eval_state.pending {
                // In flight to the same target under the same condition: the
                // countdown advances; a redundant qualifying observation does
                // NOT re-seed it (Clause 13.3 counts the delay from when the
                // condition began to hold, the same rule the intrinsic
                // detectors document at `OutOfRangeDetector::probe`).
                Some(p) if p.state == ind.target && p.condition == ind.condition => {
                    p.remaining = p.remaining.saturating_sub(1);
                    eval_state_dirty = true;
                    if p.remaining == 0 {
                        fire = Some(ind);
                    }
                }
                // No countdown, or the condition's target changed mid-delay:
                // (re-)seed with the current target's direction-appropriate
                // delay, converted from seconds with never-fire-early ceiling
                // semantics.
                _ => {
                    eval_state.pending = Some(EventEnrollmentPending {
                        state: ind.target,
                        remaining: passes_for_delay(delay, interval_secs),
                        condition: ind.condition,
                        params_fingerprint: fingerprint,
                    });
                    eval_state_dirty = true;
                }
            }
            if fire.is_some() {
                eval_state.pending = None;
            }
            fire
        } else {
            // A transition that fires at once leaves no countdown behind,
            // whichever target it was counting toward (an inhibited pass
            // always fires at once).
            if eval_state.pending.take().is_some() {
                eval_state_dirty = true;
            }
            Some(ind)
        };

        let Some(fired) = fired else {
            if eval_state_dirty && eval_state_supported {
                updates.entry(*oid).or_default().set_eval_state(eval_state);
            }
            continue;
        };

        // The transition fired. Its side-effect state lands now: the COV
        // baseline becomes the value at the indicated NORMAL transition
        // (Clause 13.3.3), and a fired OFFNORMAL records its causing value
        // for CHANGE_OF_STATE condition (c).
        if let Some(baseline) = fired.new_baseline {
            eval_state.cov_baseline = Some(baseline);
            eval_state_dirty = true;
        }
        if let Some(causing) = fired.offnormal_value {
            eval_state.last_offnormal_value = Some(causing);
            eval_state_dirty = true;
        }

        // `Event_Enable` governs distribution only (Clause 12.12). The
        // transition is recorded either way; the flag rides along so the
        // notification pipeline can suppress the send (#127).
        let transition_bit = EventTransition::for_target_state(fired.target).bit_mask();
        let distribute = event_enable.contains(transition_bit);
        let ack_required = ack_required_for_transition(db, enrollment, transition_bit);

        let update = updates.entry(*oid).or_default();
        if eval_state_dirty && eval_state_supported {
            update.set_eval_state(eval_state);
        }
        update.fire(FiredTransition {
            monitored_oid,
            event_type,
            from: current_state,
            to: fired.target,
            distribute,
            ack_required,
            projection: EventEnrollmentProjectionSnapshot::new(
                monitored.object_identifier,
                monitored.property_identifier,
                monitored.array_index,
                monitored_value,
                params,
                capture_status_flags(monitored_obj),
                projection_setpoint,
            ),
        });
    }

    apply_updates_for_delivery(db, &oids, updates, &database_eval_sources)
}

#[cfg(test)]
mod tests;