Skip to main content

dahua_camera_mqtt/
lib.rs

1//! MQTT publisher: events, health and capabilities.
2//!
3//! # Topic layout
4//!
5//! ```text
6//!   dahua/{camera}/event/{kind}      detections, retained=false
7//!   dahua/{camera}/health            latest verdict, retained=true
8//!   dahua/{camera}/capability        what the device confirmed, retained=true
9//!   dahua/{camera}/status            online/offline, retained=true + LWT
10//! ```
11//!
12//! # Retain, and when not to
13//!
14//! Health, capabilities and status are **retained**: a dashboard connecting
15//! ten minutes after the service started should immediately know the current
16//! state rather than waiting for the next change.
17//!
18//! Events are **not retained**. A retained detection is a detection that stays
19//! true on the broker forever — a subscriber connecting tomorrow would be told
20//! about motion from yesterday as though it were happening now. That is the
21//! MQTT equivalent of the latched-alarm trap, and it is worse, because the
22//! broker keeps telling everyone.
23//!
24//! # Last Will
25//!
26//! The publisher registers a Last Will on `status` so that a subscriber can
27//! tell "the service says nothing is happening" from "the service is gone".
28//! Without it those are indistinguishable, which — given the safety notice
29//! below — is exactly the confusion to avoid.
30//!
31//! # ⚠ Safety
32//!
33//! Detections published here are an **operator aid** and are **not
34//! safety-rated**. Every event payload carries the notice inline. **Absence of
35//! a message means nothing**: no detection, a dead link, and a stopped service
36//! all look identical to a subscriber. Never drive machine motion from this
37//! feed. See `SAFETY.md`.
38
39#![warn(missing_docs)]
40#![forbid(unsafe_code)]
41
42use dahua_camera_core::{CapabilitySet, Event, EventState};
43use dahua_camera_health::HealthReport;
44use serde::{Deserialize, Serialize};
45
46/// Root of every topic this crate publishes.
47pub const TOPIC_ROOT: &str = "dahua";
48
49/// The notice carried inline in every detection payload.
50pub const SAFETY_NOTICE: &str = "NOT SAFETY-RATED. Operator aid only; no SIL, no EN 50128/50129. \
51     MUST NOT gate machine motion. Absence of a message means nothing.";
52
53/// Delivery guarantee for a message.
54#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
55pub enum Qos {
56    /// Fire and forget.
57    AtMostOnce,
58    /// Redelivered until acknowledged; may duplicate.
59    AtLeastOnce,
60}
61
62/// A message ready to publish.
63#[derive(Debug, Clone, PartialEq, Eq)]
64pub struct Message {
65    /// Full topic.
66    pub topic: String,
67    /// JSON payload.
68    pub payload: String,
69    /// Delivery guarantee.
70    pub qos: Qos,
71    /// Whether the broker should keep this as the topic's last known value.
72    pub retain: bool,
73}
74
75/// The `status` topic for a camera, used for both liveness and the Last Will.
76pub fn status_topic(camera_id: &str) -> String {
77    format!("{TOPIC_ROOT}/{}/status", sanitize(camera_id))
78}
79
80/// The Last Will message for a camera.
81///
82/// Retained, so a subscriber that connects after the service died still learns
83/// that it died.
84pub fn last_will(camera_id: &str) -> Message {
85    Message {
86        topic: status_topic(camera_id),
87        payload: r#"{"status":"offline"}"#.to_owned(),
88        qos: Qos::AtLeastOnce,
89        retain: true,
90    }
91}
92
93/// The message announcing that a camera's publisher is live.
94pub fn online(camera_id: &str) -> Message {
95    Message {
96        topic: status_topic(camera_id),
97        payload: r#"{"status":"online"}"#.to_owned(),
98        qos: Qos::AtLeastOnce,
99        retain: true,
100    }
101}
102
103/// A detection message.
104///
105/// **Never retained** — see the module docs.
106pub fn event_message(event: &Event) -> Message {
107    #[derive(Serialize)]
108    struct Payload<'a> {
109        camera_id: &'a str,
110        kind: &'a str,
111        state: &'a str,
112        active: bool,
113        severity: dahua_camera_core::Severity,
114        at_unix_ms: u64,
115        #[serde(skip_serializing_if = "Option::is_none")]
116        region: Option<dahua_camera_core::BoundingBox>,
117        safety_notice: &'a str,
118    }
119
120    let state = match event.state {
121        EventState::Start => "start",
122        EventState::Stop => "stop",
123        EventState::Pulse => "pulse",
124    };
125
126    let payload = Payload {
127        camera_id: event.camera_id.as_str(),
128        kind: event.kind.name(),
129        state,
130        active: event.state.is_active(),
131        severity: event.severity,
132        at_unix_ms: event.at_unix_ms,
133        region: event.region,
134        safety_notice: SAFETY_NOTICE,
135    };
136
137    Message {
138        topic: format!(
139            "{TOPIC_ROOT}/{}/event/{}",
140            sanitize(event.camera_id.as_str()),
141            event.kind.name()
142        ),
143        payload: serde_json::to_string(&payload).unwrap_or_else(|_| "{}".to_owned()),
144        qos: Qos::AtLeastOnce,
145        // A retained detection is a detection that stays true on the broker
146        // forever. See the module docs.
147        retain: false,
148    }
149}
150
151/// A health message. Retained: current state matters more than its history.
152pub fn health_message(report: &HealthReport) -> Message {
153    Message {
154        topic: format!("{TOPIC_ROOT}/{}/health", sanitize(report.camera_id.as_str())),
155        payload: serde_json::to_string(report).unwrap_or_else(|_| "{}".to_owned()),
156        qos: Qos::AtLeastOnce,
157        retain: true,
158    }
159}
160
161/// A capability message. Retained: it changes essentially never.
162pub fn capability_message(camera_id: &str, caps: &CapabilitySet) -> Message {
163    Message {
164        topic: format!("{TOPIC_ROOT}/{}/capability", sanitize(camera_id)),
165        payload: serde_json::to_string(caps).unwrap_or_else(|_| "{}".to_owned()),
166        qos: Qos::AtLeastOnce,
167        retain: true,
168    }
169}
170
171/// Make a camera id safe for a topic level.
172///
173/// `/`, `+` and `#` are MQTT syntax: a camera id containing one would silently
174/// create extra topic levels or a wildcard, so they are replaced rather than
175/// escaped.
176fn sanitize(camera_id: &str) -> String {
177    camera_id
178        .chars()
179        .map(|c| if c.is_ascii_alphanumeric() || c == '-' || c == '_' { c } else { '_' })
180        .collect()
181}
182
183/// The transport under the publisher.
184///
185/// Abstract so the topic layout, retain policy and payload shape — everything
186/// that decides whether a subscriber is misled — are testable without a broker.
187pub trait MqttTransport: Send + Sync {
188    /// Publish one message.
189    fn publish(&self, message: &Message) -> Result<(), String>;
190}
191
192/// Publish an event through a transport.
193pub fn publish_event(transport: &dyn MqttTransport, event: &Event) -> Result<(), String> {
194    transport.publish(&event_message(event))
195}
196
197#[cfg(test)]
198mod tests {
199    use super::*;
200    use dahua_camera_core::{BoundingBox, EventKind, Severity};
201    use std::sync::Mutex;
202
203    fn event(kind: EventKind, state: EventState) -> Event {
204        Event::new("front", kind, state)
205    }
206
207    fn payload(message: &Message) -> serde_json::Value {
208        serde_json::from_str(&message.payload).expect("valid JSON")
209    }
210
211    #[test]
212    fn topics_follow_the_documented_layout() {
213        let message = event_message(&event(EventKind::Motion, EventState::Start));
214        assert_eq!(message.topic, "dahua/front/event/motion");
215        assert_eq!(status_topic("front"), "dahua/front/status");
216    }
217
218    /// A retained detection stays true on the broker forever, and the broker
219    /// keeps telling every new subscriber about it.
220    #[test]
221    fn detections_are_never_retained() {
222        for state in [EventState::Start, EventState::Stop, EventState::Pulse] {
223            let message = event_message(&event(EventKind::Motion, state));
224            assert!(!message.retain, "{state:?} must not be retained");
225        }
226    }
227
228    #[test]
229    fn state_topics_are_retained_so_a_late_subscriber_learns_the_truth() {
230        let report = HealthReport {
231            camera_id: "front".into(),
232            health: dahua_camera_health::Health::Healthy,
233            issues: Vec::new(),
234            since_last_frame_ms: Some(0),
235            since_last_change_ms: Some(0),
236        };
237
238        assert!(health_message(&report).retain);
239        assert!(capability_message("front", &CapabilitySet::default()).retain);
240        assert!(online("front").retain);
241        assert!(last_will("front").retain);
242    }
243
244    /// Without a Last Will, "nothing is happening" and "the service is gone"
245    /// are indistinguishable to a subscriber.
246    #[test]
247    fn the_last_will_shares_the_status_topic_and_says_offline() {
248        let will = last_will("front");
249        assert_eq!(will.topic, status_topic("front"));
250        assert_eq!(payload(&will)["status"], "offline");
251        assert_eq!(payload(&online("front"))["status"], "online");
252    }
253
254    #[test]
255    fn an_event_payload_carries_the_edge_and_whether_it_is_active() {
256        let start = payload(&event_message(&event(EventKind::Motion, EventState::Start)));
257        assert_eq!(start["state"], "start");
258        assert_eq!(start["active"], true);
259
260        let stop = payload(&event_message(&event(EventKind::Motion, EventState::Stop)));
261        assert_eq!(stop["state"], "stop");
262        assert_eq!(stop["active"], false);
263    }
264
265    /// A pulse is momentary, so it must not be reported as an active
266    /// condition a subscriber would wait to see cleared.
267    #[test]
268    fn a_pulse_is_published_as_not_active() {
269        let pulse = payload(&event_message(&event(EventKind::SceneChange, EventState::Pulse)));
270        assert_eq!(pulse["state"], "pulse");
271        assert_eq!(pulse["active"], false);
272    }
273
274    #[test]
275    fn every_detection_payload_carries_the_safety_notice() {
276        let message = event_message(&event(EventKind::CrossLine, EventState::Start));
277        let notice = payload(&message)["safety_notice"].as_str().unwrap_or_default().to_owned();
278
279        assert!(notice.contains("NOT SAFETY-RATED"), "{notice}");
280        assert!(notice.contains("MUST NOT gate machine motion"), "{notice}");
281        assert!(notice.contains("Absence of a message means nothing"), "{notice}");
282    }
283
284    #[test]
285    fn geometry_is_published_normalized() {
286        let event = event(EventKind::CrossLine, EventState::Start)
287            .with_region(BoundingBox::new(0.25, 0.5, 0.25, 0.25));
288        let region = &payload(&event_message(&event))["region"];
289
290        assert_eq!(region["x"], 0.25);
291        assert_eq!(region["width"], 0.25);
292    }
293
294    #[test]
295    fn an_event_with_no_geometry_omits_the_field() {
296        let message = event_message(&event(EventKind::Motion, EventState::Start));
297        assert!(payload(&message).get("region").is_none());
298    }
299
300    /// `/`, `+` and `#` are MQTT syntax. An unsanitised id would create extra
301    /// topic levels or, worse, a wildcard.
302    #[test]
303    fn camera_ids_cannot_inject_topic_levels_or_wildcards() {
304        for hostile in ["front/../admin", "front+", "front#", "a/b/c"] {
305            let topic = status_topic(hostile);
306            let tail = topic.trim_start_matches("dahua/").trim_end_matches("/status");
307
308            assert!(!tail.contains('/'), "{topic}");
309            assert!(!tail.contains('+'), "{topic}");
310            assert!(!tail.contains('#'), "{topic}");
311        }
312    }
313
314    #[test]
315    fn an_unknown_event_code_publishes_to_a_single_topic() {
316        // Otherwise novel firmware codes would grow the topic space without
317        // bound and defeat any subscriber's wildcard.
318        let a = event(EventKind::Unknown { code: "A".into(), raw: String::new() }, EventState::Start);
319        let b = event(EventKind::Unknown { code: "B".into(), raw: String::new() }, EventState::Start);
320        assert_eq!(event_message(&a).topic, event_message(&b).topic);
321    }
322
323    #[test]
324    fn severity_is_published() {
325        let critical = event(EventKind::VideoLoss, EventState::Start);
326        assert_eq!(critical.severity, Severity::Critical);
327        assert_eq!(payload(&event_message(&critical))["severity"], "critical");
328    }
329
330    #[derive(Default)]
331    struct RecordingTransport {
332        sent: Mutex<Vec<Message>>,
333    }
334
335    impl MqttTransport for RecordingTransport {
336        fn publish(&self, message: &Message) -> Result<(), String> {
337            self.sent.lock().expect("mutex").push(message.clone());
338            Ok(())
339        }
340    }
341
342    #[test]
343    fn publishing_goes_through_the_transport_unchanged() {
344        let transport = RecordingTransport::default();
345        let event = event(EventKind::Motion, EventState::Start);
346
347        publish_event(&transport, &event).expect("publishes");
348
349        let sent = transport.sent.lock().expect("mutex");
350        assert_eq!(sent.len(), 1);
351        assert_eq!(sent[0], event_message(&event));
352    }
353}