Skip to main content

dahua_camera_alarms/
lib.rs

1//! Alarm lifecycle: latch on START, clear on STOP, acknowledge, and history.
2//!
3//! # The trap this crate exists to close
4//!
5//! Camera events come in pairs. `Code=VideoMotion;action=Start` is followed,
6//! eventually, by `action=Stop`. Code that treats every event as "something
7//! happened" latches every alarm on forever, and an operator faced with a
8//! panel that is permanently red learns to ignore it — which is worse than
9//! having no panel.
10//!
11//! So [`AlarmRegistry`] models the pair explicitly:
12//!
13//! ```text
14//!   START ────────────▶ Active ────── STOP ──────▶ Cleared
15//!                          │
16//!                          └── auto_clear elapsed ──▶ Cleared (timed out)
17//! ```
18//!
19//! **A STOP is not guaranteed.** The camera reboots mid-incident, the link
20//! drops, a firmware bug swallows the edge. So every active alarm also carries
21//! an auto-clear deadline, and an alarm that outlives it is cleared with
22//! [`ClearReason::Timeout`] — recorded distinctly, because "the condition
23//! ended" and "we stopped believing the condition" are different facts and an
24//! operator needs to tell them apart.
25//!
26//! # No background task
27//!
28//! Expiry is evaluated lazily, when events arrive or the registry is read,
29//! against a clock the caller supplies. That is deliberate: the workspace
30//! budget allows **no feature more than one task per camera**, and the event
31//! link already spends it. A timer wheel here would spend a second.
32//!
33//! # Safety
34//!
35//! An alarm raised by camera analytics is an **operator aid** and is **not
36//! safety-rated**. The absence of an alarm means nothing. See `SAFETY.md` at
37//! the workspace root.
38
39#![warn(missing_docs)]
40#![forbid(unsafe_code)]
41
42use dahua_camera_core::{CameraId, Event, EventKind, EventState, Severity};
43use serde::{Deserialize, Serialize};
44use std::collections::BTreeMap;
45use std::time::Duration;
46
47/// How long an active alarm survives without a matching STOP.
48///
49/// Two minutes: long enough that an ordinary motion incident closes on its own
50/// STOP, short enough that a lost STOP does not leave the panel red through a
51/// whole shift.
52pub const DEFAULT_AUTO_CLEAR: Duration = Duration::from_secs(120);
53
54/// Why an alarm stopped being active.
55#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
56#[serde(rename_all = "snake_case")]
57pub enum ClearReason {
58    /// The camera sent the matching STOP. The condition genuinely ended.
59    Stop,
60    /// No STOP arrived within the auto-clear window.
61    ///
62    /// **This is not the same as the condition ending.** It means the service
63    /// stopped believing an unconfirmed active state. The incident may still
64    /// be in progress behind a dead link.
65    Timeout,
66}
67
68/// A latched condition on one camera.
69#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
70pub struct Alarm {
71    /// Monotonic identifier, unique within this registry.
72    pub id: u64,
73    /// Which camera raised it.
74    pub camera_id: CameraId,
75    /// What kind of condition.
76    ///
77    /// Flattened, exactly as on [`Event`], so an alarm and the event that
78    /// raised it serialise the same shape. Without this the two differ —
79    /// `"kind":"motion"` on one and `"kind":{"kind":"motion"}` on the other —
80    /// and every client has to special-case which it is looking at.
81    #[serde(flatten)]
82    pub kind: EventKind,
83    /// How much an operator should care.
84    pub severity: Severity,
85    /// When it was raised, Unix milliseconds.
86    pub raised_at_unix_ms: u64,
87    /// When it cleared, if it has.
88    #[serde(skip_serializing_if = "Option::is_none", default)]
89    pub cleared_at_unix_ms: Option<u64>,
90    /// Why it cleared, if it has.
91    #[serde(skip_serializing_if = "Option::is_none", default)]
92    pub cleared_by: Option<ClearReason>,
93    /// Whether an operator has acknowledged it.
94    pub acknowledged: bool,
95}
96
97impl Alarm {
98    /// Whether the condition is still latched.
99    pub fn is_active(&self) -> bool {
100        self.cleared_at_unix_ms.is_none()
101    }
102
103    /// Whether this alarm still wants an operator's attention: active, or
104    /// cleared but never acknowledged.
105    pub fn needs_attention(&self) -> bool {
106        self.is_active() || !self.acknowledged
107    }
108}
109
110/// What changed as a result of feeding in an event.
111#[derive(Debug, Clone, PartialEq)]
112pub enum AlarmChange {
113    /// A new alarm latched.
114    Raised(Alarm),
115    /// An existing alarm cleared.
116    Cleared(Alarm),
117    /// Nothing changed — a STOP for something that was never active, or a
118    /// repeated START for something already latched.
119    None,
120}
121
122/// Tuning for [`AlarmRegistry`].
123#[derive(Debug, Clone)]
124pub struct AlarmConfig {
125    /// How long an active alarm survives without a matching STOP.
126    pub auto_clear: Duration,
127    /// How many cleared alarms to retain.
128    ///
129    /// Bounded so a camera in a fault loop cannot grow the history without
130    /// limit — the same reasoning as the bounded frame bus.
131    pub history_limit: usize,
132}
133
134impl Default for AlarmConfig {
135    fn default() -> Self {
136        Self { auto_clear: DEFAULT_AUTO_CLEAR, history_limit: 500 }
137    }
138}
139
140/// Tracks which conditions are currently latched, and what happened before.
141///
142/// ```
143/// use dahua_camera_alarms::{AlarmChange, AlarmConfig, AlarmRegistry, ClearReason};
144/// use dahua_camera_core::{Event, EventKind, EventState};
145///
146/// let mut alarms = AlarmRegistry::new(AlarmConfig::default());
147///
148/// let start = Event::new("front", EventKind::Motion, EventState::Start).at(1_000);
149/// assert!(matches!(alarms.observe(&start, 1_000), AlarmChange::Raised(_)));
150/// assert_eq!(alarms.active(1_000).len(), 1);
151///
152/// let stop = Event::new("front", EventKind::Motion, EventState::Stop).at(5_000);
153/// assert!(matches!(alarms.observe(&stop, 5_000), AlarmChange::Cleared(_)));
154/// assert!(alarms.active(5_000).is_empty());
155/// ```
156#[derive(Debug)]
157pub struct AlarmRegistry {
158    config: AlarmConfig,
159    /// Latched alarms, keyed by `(camera, kind name)` — the same key
160    /// [`Event::matches`] pairs on.
161    active: BTreeMap<(CameraId, &'static str), Alarm>,
162    history: Vec<Alarm>,
163    next_id: u64,
164}
165
166impl AlarmRegistry {
167    /// An empty registry.
168    pub fn new(config: AlarmConfig) -> Self {
169        Self { config, active: BTreeMap::new(), history: Vec::new(), next_id: 1 }
170    }
171
172    /// Feed in an event. `now_unix_ms` is the current time.
173    ///
174    /// Expiry is swept first, so a STOP that arrives after the auto-clear
175    /// deadline finds nothing to clear rather than resurrecting an alarm.
176    pub fn observe(&mut self, event: &Event, now_unix_ms: u64) -> AlarmChange {
177        self.sweep_expired(now_unix_ms);
178
179        let key = (event.camera_id.clone(), event.kind.name());
180
181        match event.state {
182            EventState::Start => {
183                if self.active.contains_key(&key) {
184                    // A repeated START for a condition already latched. Not a
185                    // new alarm: re-raising would produce a second entry that
186                    // the eventual single STOP could never clear.
187                    return AlarmChange::None;
188                }
189                let alarm = Alarm {
190                    id: self.take_id(),
191                    camera_id: event.camera_id.clone(),
192                    kind: event.kind.clone(),
193                    severity: event.severity,
194                    raised_at_unix_ms: now_unix_ms,
195                    cleared_at_unix_ms: None,
196                    cleared_by: None,
197                    acknowledged: false,
198                };
199                self.active.insert(key, alarm.clone());
200                AlarmChange::Raised(alarm)
201            }
202
203            EventState::Stop => match self.active.remove(&key) {
204                Some(mut alarm) => {
205                    alarm.cleared_at_unix_ms = Some(now_unix_ms);
206                    alarm.cleared_by = Some(ClearReason::Stop);
207                    self.push_history(alarm.clone());
208                    AlarmChange::Cleared(alarm)
209                }
210                // A STOP with no matching START. Common after a reconnect:
211                // the START happened while the link was down.
212                None => AlarmChange::None,
213            },
214
215            // A pulse has no duration, so it must never latch. It is recorded
216            // as an already-cleared alarm so it appears in history without
217            // ever showing as active.
218            EventState::Pulse => {
219                let alarm = Alarm {
220                    id: self.take_id(),
221                    camera_id: event.camera_id.clone(),
222                    kind: event.kind.clone(),
223                    severity: event.severity,
224                    raised_at_unix_ms: now_unix_ms,
225                    cleared_at_unix_ms: Some(now_unix_ms),
226                    cleared_by: Some(ClearReason::Stop),
227                    acknowledged: false,
228                };
229                self.push_history(alarm.clone());
230                AlarmChange::Raised(alarm)
231            }
232        }
233    }
234
235    /// Clear any alarm that has outlived the auto-clear window.
236    ///
237    /// Returns the alarms that were cleared. Called automatically by
238    /// [`observe`](Self::observe) and [`active`](Self::active); call it
239    /// directly only when nothing else is driving the registry.
240    pub fn sweep_expired(&mut self, now_unix_ms: u64) -> Vec<Alarm> {
241        let window = self.config.auto_clear.as_millis() as u64;
242
243        let expired: Vec<_> = self
244            .active
245            .iter()
246            .filter(|(_, alarm)| now_unix_ms.saturating_sub(alarm.raised_at_unix_ms) >= window)
247            .map(|(key, _)| key.clone())
248            .collect();
249
250        let mut cleared = Vec::with_capacity(expired.len());
251        for key in expired {
252            let Some(mut alarm) = self.active.remove(&key) else { continue };
253            alarm.cleared_at_unix_ms = Some(now_unix_ms);
254            alarm.cleared_by = Some(ClearReason::Timeout);
255
256            tracing::warn!(
257                camera = %alarm.camera_id,
258                kind = alarm.kind.name(),
259                alarm = alarm.id,
260                "alarm auto-cleared: no STOP arrived within the timeout. \
261                 The condition may still be in progress."
262            );
263
264            self.push_history(alarm.clone());
265            cleared.push(alarm);
266        }
267        cleared
268    }
269
270    /// Currently latched alarms, oldest first, after sweeping expiries.
271    pub fn active(&mut self, now_unix_ms: u64) -> Vec<Alarm> {
272        self.sweep_expired(now_unix_ms);
273        let mut active: Vec<_> = self.active.values().cloned().collect();
274        active.sort_by_key(|a| a.id);
275        active
276    }
277
278    /// Cleared alarms, oldest first, capped at the configured limit.
279    pub fn history(&self) -> &[Alarm] {
280        &self.history
281    }
282
283    /// Acknowledge one alarm by id, active or historical.
284    ///
285    /// Returns `false` if no such alarm exists. Acknowledging does **not**
286    /// clear: an operator confirming they have seen an ongoing condition is
287    /// not the same as the condition ending.
288    pub fn acknowledge(&mut self, id: u64) -> bool {
289        for alarm in self.active.values_mut() {
290            if alarm.id == id {
291                alarm.acknowledged = true;
292                return true;
293            }
294        }
295        for alarm in &mut self.history {
296            if alarm.id == id {
297                alarm.acknowledged = true;
298                return true;
299            }
300        }
301        false
302    }
303
304    /// Acknowledge every alarm, active and historical.
305    pub fn acknowledge_all(&mut self) -> usize {
306        let mut count = 0;
307        for alarm in self.active.values_mut().filter(|a| !a.acknowledged) {
308            alarm.acknowledged = true;
309            count += 1;
310        }
311        for alarm in self.history.iter_mut().filter(|a| !a.acknowledged) {
312            alarm.acknowledged = true;
313            count += 1;
314        }
315        count
316    }
317
318    fn take_id(&mut self) -> u64 {
319        let id = self.next_id;
320        self.next_id += 1;
321        id
322    }
323
324    /// Append to history, evicting the oldest entries past the limit.
325    fn push_history(&mut self, alarm: Alarm) {
326        self.history.push(alarm);
327        if self.history.len() > self.config.history_limit {
328            let excess = self.history.len() - self.config.history_limit;
329            self.history.drain(..excess);
330        }
331    }
332}
333
334#[cfg(test)]
335mod tests {
336    use super::*;
337
338    const MINUTE: u64 = 60_000;
339
340    fn registry() -> AlarmRegistry {
341        AlarmRegistry::new(AlarmConfig::default())
342    }
343
344    fn event(camera: &str, kind: EventKind, state: EventState) -> Event {
345        Event::new(camera, kind, state)
346    }
347
348    #[test]
349    fn a_start_latches_an_alarm() {
350        let mut alarms = registry();
351        let change = alarms.observe(&event("front", EventKind::Motion, EventState::Start), 0);
352
353        assert!(matches!(change, AlarmChange::Raised(_)));
354        assert_eq!(alarms.active(0).len(), 1);
355        assert!(alarms.active(0)[0].is_active());
356    }
357
358    #[test]
359    fn a_stop_clears_the_matching_alarm() {
360        let mut alarms = registry();
361        alarms.observe(&event("front", EventKind::Motion, EventState::Start), 0);
362
363        let change = alarms.observe(&event("front", EventKind::Motion, EventState::Stop), 5_000);
364        match change {
365            AlarmChange::Cleared(alarm) => {
366                assert_eq!(alarm.cleared_by, Some(ClearReason::Stop));
367                assert_eq!(alarm.cleared_at_unix_ms, Some(5_000));
368            }
369            other => panic!("expected Cleared, got {other:?}"),
370        }
371        assert!(alarms.active(5_000).is_empty());
372    }
373
374    /// **The trap.** A camera that reboots mid-incident never sends its STOP.
375    /// Without auto-clear the panel stays red forever.
376    #[test]
377    fn an_alarm_auto_clears_when_the_stop_never_arrives() {
378        let mut alarms = registry();
379        alarms.observe(&event("front", EventKind::Motion, EventState::Start), 0);
380        assert_eq!(alarms.active(0).len(), 1);
381
382        // Just before the deadline it is still latched.
383        assert_eq!(alarms.active(MINUTE).len(), 1, "must not clear early");
384
385        // Past the deadline it clears itself.
386        assert!(alarms.active(3 * MINUTE).is_empty(), "no STOP ever came");
387
388        let cleared = alarms.history().last().expect("recorded in history");
389        assert_eq!(cleared.cleared_by, Some(ClearReason::Timeout));
390    }
391
392    /// A timeout and a real STOP must be distinguishable: one means the
393    /// condition ended, the other means we stopped believing it.
394    #[test]
395    fn a_timeout_is_recorded_differently_from_a_real_stop() {
396        let mut alarms = AlarmRegistry::new(AlarmConfig {
397            auto_clear: Duration::from_secs(10),
398            ..AlarmConfig::default()
399        });
400
401        alarms.observe(&event("a", EventKind::Motion, EventState::Start), 0);
402        alarms.observe(&event("b", EventKind::Motion, EventState::Start), 0);
403        alarms.observe(&event("b", EventKind::Motion, EventState::Stop), 1_000);
404
405        alarms.sweep_expired(60_000);
406
407        let reasons: Vec<_> = alarms.history().iter().map(|a| a.cleared_by).collect();
408        assert!(reasons.contains(&Some(ClearReason::Stop)));
409        assert!(reasons.contains(&Some(ClearReason::Timeout)));
410    }
411
412    #[test]
413    fn the_auto_clear_window_is_configurable() {
414        let mut alarms = AlarmRegistry::new(AlarmConfig {
415            auto_clear: Duration::from_secs(1),
416            ..AlarmConfig::default()
417        });
418        alarms.observe(&event("front", EventKind::Motion, EventState::Start), 0);
419
420        assert_eq!(alarms.active(500).len(), 1);
421        assert!(alarms.active(1_500).is_empty(), "a one-second window must expire in one second");
422    }
423
424    #[test]
425    fn a_stop_arriving_after_the_auto_clear_finds_nothing_and_does_not_resurrect() {
426        let mut alarms = AlarmRegistry::new(AlarmConfig {
427            auto_clear: Duration::from_secs(1),
428            ..AlarmConfig::default()
429        });
430        alarms.observe(&event("front", EventKind::Motion, EventState::Start), 0);
431
432        let change = alarms.observe(&event("front", EventKind::Motion, EventState::Stop), 10_000);
433        assert_eq!(change, AlarmChange::None);
434        assert!(alarms.active(10_000).is_empty());
435    }
436
437    /// A pulse has no duration. Latching one would need a STOP that is never
438    /// coming — the other way to leave an alarm on forever.
439    #[test]
440    fn a_pulse_never_latches() {
441        let mut alarms = registry();
442        alarms.observe(&event("front", EventKind::SceneChange, EventState::Pulse), 0);
443
444        assert!(alarms.active(0).is_empty(), "a pulse must never show as active");
445        assert_eq!(alarms.history().len(), 1, "but it is still recorded");
446    }
447
448    #[test]
449    fn a_repeated_start_does_not_stack_alarms() {
450        let mut alarms = registry();
451        alarms.observe(&event("front", EventKind::Motion, EventState::Start), 0);
452        let second = alarms.observe(&event("front", EventKind::Motion, EventState::Start), 100);
453
454        assert_eq!(second, AlarmChange::None);
455        assert_eq!(alarms.active(100).len(), 1, "one condition, one alarm");
456    }
457
458    #[test]
459    fn a_stop_with_no_start_is_ignored_not_an_error() {
460        // Common after a reconnect: the START happened while the link was down.
461        let mut alarms = registry();
462        let change = alarms.observe(&event("front", EventKind::Motion, EventState::Stop), 0);
463        assert_eq!(change, AlarmChange::None);
464    }
465
466    #[test]
467    fn alarms_from_different_cameras_are_independent() {
468        let mut alarms = registry();
469        alarms.observe(&event("front", EventKind::Motion, EventState::Start), 0);
470        alarms.observe(&event("back", EventKind::Motion, EventState::Start), 0);
471
472        alarms.observe(&event("front", EventKind::Motion, EventState::Stop), 100);
473
474        let active = alarms.active(100);
475        assert_eq!(active.len(), 1);
476        assert_eq!(active[0].camera_id, "back", "one camera's stop must not clear another's");
477    }
478
479    #[test]
480    fn different_kinds_on_one_camera_are_independent() {
481        let mut alarms = registry();
482        alarms.observe(&event("front", EventKind::Motion, EventState::Start), 0);
483        alarms.observe(&event("front", EventKind::CrossLine, EventState::Start), 0);
484        alarms.observe(&event("front", EventKind::Motion, EventState::Stop), 100);
485
486        let active = alarms.active(100);
487        assert_eq!(active.len(), 1);
488        assert_eq!(active[0].kind, EventKind::CrossLine);
489    }
490
491    #[test]
492    fn an_unknown_event_code_still_produces_a_normal_alarm() {
493        let mut alarms = registry();
494        let kind = EventKind::Unknown { code: "NewThing".into(), raw: "raw".into() };
495
496        assert!(matches!(
497            alarms.observe(&event("front", kind.clone(), EventState::Start), 0),
498            AlarmChange::Raised(_)
499        ));
500        assert!(matches!(
501            alarms.observe(&event("front", kind, EventState::Stop), 100),
502            AlarmChange::Cleared(_)
503        ));
504    }
505
506    #[test]
507    fn severity_comes_from_the_event() {
508        let mut alarms = registry();
509        alarms.observe(&event("front", EventKind::VideoLoss, EventState::Start), 0);
510        assert_eq!(alarms.active(0)[0].severity, Severity::Critical);
511    }
512
513    #[test]
514    fn acknowledging_does_not_clear_an_ongoing_condition() {
515        let mut alarms = registry();
516        alarms.observe(&event("front", EventKind::Motion, EventState::Start), 0);
517        let id = alarms.active(0)[0].id;
518
519        assert!(alarms.acknowledge(id));
520
521        let active = alarms.active(0);
522        assert_eq!(active.len(), 1, "still happening");
523        assert!(active[0].acknowledged);
524        assert!(active[0].is_active());
525    }
526
527    #[test]
528    fn acknowledging_an_unknown_id_reports_failure() {
529        assert!(!registry().acknowledge(9999));
530    }
531
532    #[test]
533    fn acknowledge_all_covers_active_and_historical_alarms() {
534        let mut alarms = registry();
535        alarms.observe(&event("front", EventKind::Motion, EventState::Start), 0);
536        alarms.observe(&event("front", EventKind::Motion, EventState::Stop), 100);
537        alarms.observe(&event("back", EventKind::Motion, EventState::Start), 100);
538
539        assert_eq!(alarms.acknowledge_all(), 2);
540        assert_eq!(alarms.acknowledge_all(), 0, "already acknowledged");
541    }
542
543    #[test]
544    fn a_cleared_but_unacknowledged_alarm_still_wants_attention() {
545        let mut alarms = registry();
546        alarms.observe(&event("front", EventKind::Motion, EventState::Start), 0);
547        alarms.observe(&event("front", EventKind::Motion, EventState::Stop), 100);
548
549        assert!(alarms.history()[0].needs_attention(), "nobody has seen it yet");
550    }
551
552    #[test]
553    fn ids_are_unique_and_increasing() {
554        let mut alarms = registry();
555        alarms.observe(&event("a", EventKind::Motion, EventState::Start), 0);
556        alarms.observe(&event("b", EventKind::Motion, EventState::Start), 0);
557
558        let active = alarms.active(0);
559        assert!(active[0].id < active[1].id);
560    }
561
562    /// A camera stuck in a fault loop must not grow memory without bound —
563    /// the same reasoning as the bounded frame bus.
564    #[test]
565    fn history_is_bounded() {
566        let mut alarms =
567            AlarmRegistry::new(AlarmConfig { auto_clear: DEFAULT_AUTO_CLEAR, history_limit: 10 });
568
569        for i in 0..100 {
570            let at = i * 10;
571            alarms.observe(&event("front", EventKind::Motion, EventState::Start), at);
572            alarms.observe(&event("front", EventKind::Motion, EventState::Stop), at + 1);
573        }
574
575        assert_eq!(alarms.history().len(), 10, "oldest entries are evicted");
576    }
577
578    /// An alarm and the event that raised it must serialise the same shape.
579    #[test]
580    fn an_alarm_reports_its_kind_the_same_way_an_event_does() {
581        let mut alarms = registry();
582        let raising = event("front", EventKind::Motion, EventState::Start);
583        alarms.observe(&raising, 0);
584
585        let alarm_json = serde_json::to_value(&alarms.active(0)[0]).expect("serialises");
586        let event_json = serde_json::to_value(&raising).expect("serialises");
587
588        assert_eq!(alarm_json["kind"], "motion");
589        assert_eq!(alarm_json["kind"], event_json["kind"]);
590    }
591
592    #[test]
593    fn an_unknown_alarm_carries_its_code_alongside_the_kind() {
594        let mut alarms = registry();
595        let kind = EventKind::Unknown { code: "NewThing".into(), raw: "raw".into() };
596        alarms.observe(&event("front", kind, EventState::Start), 0);
597
598        let json = serde_json::to_value(&alarms.active(0)[0]).expect("serialises");
599        assert_eq!(json["kind"], "unknown");
600        assert_eq!(json["code"], "NewThing");
601    }
602
603    #[test]
604    fn an_alarm_round_trips_through_json() {
605        let mut alarms = registry();
606        alarms.observe(&event("front", EventKind::CrossLine, EventState::Start), 1_000);
607
608        let alarm = &alarms.active(1_000)[0];
609        let json = serde_json::to_string(alarm).expect("serialises");
610        let back: Alarm = serde_json::from_str(&json).expect("deserialises");
611        assert_eq!(*alarm, back);
612    }
613
614    #[test]
615    fn an_active_alarm_omits_the_cleared_fields() {
616        let mut alarms = registry();
617        alarms.observe(&event("front", EventKind::Motion, EventState::Start), 0);
618
619        let json = serde_json::to_value(&alarms.active(0)[0]).expect("serialises");
620        assert!(json.get("cleared_at_unix_ms").is_none(), "{json}");
621        assert!(json.get("cleared_by").is_none(), "{json}");
622    }
623}