Skip to main content

dahua_camera_opcua/
lib.rs

1//! OPC UA address space for the camera stack.
2//!
3//! # ⚠ READ THIS BEFORE EXPOSING ANY NODE
4//!
5//! OPC UA is how this data reaches a PLC. A PLC is how machinery moves. That
6//! combination is exactly the mistake this crate is built to make hard.
7//!
8//! **Camera IVS/SMD detection is an OPERATOR AID. It is not safety-rated: no
9//! SIL level, no EN 50128 / EN 50129 assessment.** It degrades in fog, rain,
10//! backlight and at range. It **MUST NOT** be used as an interlock, a
11//! permissive, or a condition for machine motion. **Absence of a detection
12//! means nothing.**
13//!
14//! So the node naming here is deliberately unambiguous, and deliberately ugly:
15//!
16//! ```text
17//!   Camera_front_Detection_Motion_NotSafetyRated
18//!   Camera_front_Health_NotSafetyRated
19//! ```
20//!
21//! An integrator browsing the address space cannot reach one of these values
22//! without reading `NotSafetyRated` in the identifier itself. A comfortable
23//! name like `Camera1.MotionDetected` invites exactly the wiring this notice
24//! forbids, and a description field does not help — nobody reads descriptions
25//! while dragging a tag into a ladder rung.
26//!
27//! Every node also carries the full notice in its `description`, and
28//! [`NodeSpec::is_safe_for_interlock`] returns `false` for **all** of them.
29//!
30//! # Scope
31//!
32//! This crate models the address space: node ids, browse names, descriptions,
33//! data types and the mapping from workspace types to OPC UA values. The
34//! transport is supplied by an [`OpcUaBackend`] implementation, so the model —
35//! which is where the safety-critical naming decisions live — is testable
36//! without standing up a server.
37
38#![warn(missing_docs)]
39#![forbid(unsafe_code)]
40
41use dahua_camera_core::{Capability, CapabilitySet, Event, EventKind, EventState, Severity};
42use dahua_camera_health::{Health, HealthReport};
43use serde::{Deserialize, Serialize};
44
45/// The suffix every detection and health node carries.
46///
47/// Load-bearing, not decorative: it is the last line of defence against a node
48/// being wired into a safety function by someone who never read the docs.
49pub const NOT_SAFETY_RATED: &str = "NotSafetyRated";
50
51/// The notice attached to every node's description.
52pub const SAFETY_NOTICE: &str = "NOT SAFETY-RATED. Camera IVS/SMD detection is an operator aid \
53     with no SIL level and no EN 50128/EN 50129 assessment. It degrades in fog, rain, backlight \
54     and at range. MUST NOT be used as an interlock, a permissive, or a condition for machine \
55     motion. Absence of a detection means nothing.";
56
57/// The OPC UA data type of a node's value.
58#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
59#[serde(rename_all = "PascalCase")]
60pub enum NodeType {
61    /// `Boolean`.
62    Boolean,
63    /// `String`.
64    String,
65    /// `Int64`.
66    Int64,
67    /// `DateTime`, as Unix milliseconds.
68    DateTime,
69}
70
71/// One node in the address space.
72#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
73pub struct NodeSpec {
74    /// The string identifier within the namespace.
75    pub node_id: String,
76    /// The browse name shown in a client's address-space tree.
77    pub browse_name: String,
78    /// Human-readable description, always carrying [`SAFETY_NOTICE`].
79    pub description: String,
80    /// The value's data type.
81    pub node_type: NodeType,
82}
83
84impl NodeSpec {
85    /// Whether this node may be used in a safety function.
86    ///
87    /// Always `false`. It exists as a method rather than a constant so that
88    /// any future node has to answer the question explicitly, and so an
89    /// integrator's own tooling can assert it.
90    pub fn is_safe_for_interlock(&self) -> bool {
91        false
92    }
93
94    /// Whether the identifier itself warns the reader.
95    pub fn is_marked_unsafe(&self) -> bool {
96        self.node_id.contains(NOT_SAFETY_RATED) && self.browse_name.contains(NOT_SAFETY_RATED)
97    }
98}
99
100/// A value published to a node.
101#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
102#[serde(untagged)]
103pub enum NodeValue {
104    /// A boolean.
105    Boolean(bool),
106    /// A string.
107    Text(String),
108    /// A signed integer.
109    Int64(i64),
110}
111
112/// The transport under the address space.
113///
114/// Implemented by whatever OPC UA server stack is in use. Keeping it abstract
115/// is what lets the naming and mapping rules — the parts that matter for
116/// safety — be tested exhaustively without a running server.
117pub trait OpcUaBackend: Send + Sync {
118    /// Create or replace a node.
119    fn declare(&self, spec: &NodeSpec) -> Result<(), String>;
120    /// Publish a value to an existing node.
121    fn publish(&self, node_id: &str, value: NodeValue) -> Result<(), String>;
122}
123
124/// Build the node identifier for one camera and leaf.
125fn node_id(camera_id: &str, leaf: &str) -> String {
126    let safe: String = camera_id
127        .chars()
128        .map(|c| if c.is_ascii_alphanumeric() { c } else { '_' })
129        .collect();
130    format!("Camera_{safe}_{leaf}")
131}
132
133/// A node carrying a detection, named so it cannot be mistaken for safe.
134///
135/// ```
136/// use dahua_camera_opcua::detection_node;
137/// use dahua_camera_core::EventKind;
138///
139/// let node = detection_node("front", &EventKind::Motion);
140///
141/// assert_eq!(node.node_id, "Camera_front_Detection_motion_NotSafetyRated");
142/// assert!(node.is_marked_unsafe());
143/// assert!(!node.is_safe_for_interlock());
144/// ```
145pub fn detection_node(camera_id: &str, kind: &EventKind) -> NodeSpec {
146    let leaf = format!("Detection_{}_{NOT_SAFETY_RATED}", kind.name());
147    NodeSpec {
148        node_id: node_id(camera_id, &leaf),
149        browse_name: leaf,
150        description: format!(
151            "Camera '{camera_id}' reports '{}' detection state. {SAFETY_NOTICE}",
152            kind.name()
153        ),
154        node_type: NodeType::Boolean,
155    }
156}
157
158/// A node carrying a camera's health verdict.
159pub fn health_node(camera_id: &str) -> NodeSpec {
160    let leaf = format!("Health_{NOT_SAFETY_RATED}");
161    NodeSpec {
162        node_id: node_id(camera_id, &leaf),
163        browse_name: leaf,
164        description: format!(
165            "Camera '{camera_id}' health verdict (unknown/healthy/degraded/down). A healthy \
166             verdict means frames are arriving and changing; it does NOT mean the camera can \
167             see what matters. {SAFETY_NOTICE}"
168        ),
169        node_type: NodeType::String,
170    }
171}
172
173/// A node carrying a camera's clock offset in seconds.
174pub fn clock_offset_node(camera_id: &str) -> NodeSpec {
175    NodeSpec {
176        node_id: node_id(camera_id, "ClockOffsetSeconds"),
177        browse_name: "ClockOffsetSeconds".to_owned(),
178        description: format!(
179            "Camera '{camera_id}' clock offset from the host, in seconds; positive means the \
180             camera is ahead. Diagnostic only. {SAFETY_NOTICE}"
181        ),
182        node_type: NodeType::Int64,
183    }
184}
185
186/// A node reporting whether a capability was confirmed.
187///
188/// Capabilities are facts about the device, not detections, so these are the
189/// only nodes without the unsafe marker.
190pub fn capability_node(camera_id: &str, capability: Capability) -> NodeSpec {
191    let leaf = format!("Capability_{}", capability.name());
192    NodeSpec {
193        node_id: node_id(camera_id, &leaf),
194        browse_name: leaf,
195        description: format!(
196            "Whether camera '{camera_id}' confirmed the '{}' capability. False means the device \
197             did not advertise it, or was never probed — never that it was assumed.",
198            capability.name()
199        ),
200        node_type: NodeType::Boolean,
201    }
202}
203
204/// Every node for one camera, given the event kinds it may report.
205pub fn nodes_for_camera(camera_id: &str, kinds: &[EventKind]) -> Vec<NodeSpec> {
206    let mut nodes = vec![health_node(camera_id), clock_offset_node(camera_id)];
207    nodes.extend(kinds.iter().map(|kind| detection_node(camera_id, kind)));
208    nodes.extend(Capability::all().iter().map(|c| capability_node(camera_id, *c)));
209    nodes
210}
211
212/// Map an event onto its node and value.
213///
214/// A `Start` publishes `true`; a `Stop` publishes `false`. A `Pulse` publishes
215/// `true` and is **not** followed by a `false` — a momentary event has no
216/// duration, and the caller must decide how long to hold it. Modelling a pulse
217/// as a latched `true` is how an OPC UA client ends up with a tag stuck on.
218pub fn event_update(event: &Event) -> (NodeSpec, NodeValue) {
219    let node = detection_node(event.camera_id.as_str(), &event.kind);
220    let value = NodeValue::Boolean(matches!(event.state, EventState::Start | EventState::Pulse));
221    (node, value)
222}
223
224/// Map a health report onto its node and value.
225pub fn health_update(report: &HealthReport) -> (NodeSpec, NodeValue) {
226    let node = health_node(report.camera_id.as_str());
227    let text = match report.health {
228        Health::Unknown => "unknown",
229        Health::Healthy => "healthy",
230        Health::Degraded => "degraded",
231        Health::Down => "down",
232    };
233    (node, NodeValue::Text(text.to_owned()))
234}
235
236/// Map a capability profile onto its nodes and values.
237pub fn capability_updates(
238    camera_id: &str,
239    caps: &CapabilitySet,
240) -> Vec<(NodeSpec, NodeValue)> {
241    Capability::all()
242        .iter()
243        .map(|capability| {
244            (
245                capability_node(camera_id, *capability),
246                NodeValue::Boolean(caps.supports(*capability)),
247            )
248        })
249        .collect()
250}
251
252/// Severity as an OPC UA-friendly integer, matching the enum's ordering.
253pub fn severity_code(severity: Severity) -> i64 {
254    match severity {
255        Severity::Info => 0,
256        Severity::Warning => 1,
257        Severity::Alarm => 2,
258        Severity::Critical => 3,
259    }
260}
261
262/// Declare every node for a camera on a backend.
263pub fn declare_camera(
264    backend: &dyn OpcUaBackend,
265    camera_id: &str,
266    kinds: &[EventKind],
267) -> Result<(), String> {
268    for node in nodes_for_camera(camera_id, kinds) {
269        backend.declare(&node)?;
270    }
271    Ok(())
272}
273
274#[cfg(test)]
275mod tests {
276    use super::*;
277    use std::sync::Mutex;
278
279    fn kinds() -> Vec<EventKind> {
280        vec![EventKind::Motion, EventKind::CrossLine, EventKind::Intrusion]
281    }
282
283    /// The central guarantee: an integrator cannot browse to a detection value
284    /// without `NotSafetyRated` appearing in the identifier they drag.
285    #[test]
286    fn every_detection_node_is_marked_unsafe_in_its_own_name() {
287        for kind in kinds() {
288            let node = detection_node("front", &kind);
289            assert!(node.is_marked_unsafe(), "{}", node.node_id);
290            assert!(node.node_id.contains(NOT_SAFETY_RATED));
291            assert!(node.browse_name.contains(NOT_SAFETY_RATED));
292        }
293    }
294
295    #[test]
296    fn the_health_node_is_marked_unsafe_too() {
297        let node = health_node("front");
298        assert!(node.is_marked_unsafe(), "{}", node.node_id);
299    }
300
301    #[test]
302    fn no_node_is_ever_safe_for_an_interlock() {
303        for node in nodes_for_camera("front", &kinds()) {
304            assert!(!node.is_safe_for_interlock(), "{}", node.node_id);
305        }
306    }
307
308    #[test]
309    fn every_node_carries_the_full_safety_notice() {
310        for node in nodes_for_camera("front", &kinds()) {
311            assert!(
312                node.description.contains("MUST NOT be used as an interlock")
313                    || node.description.contains("never that it was assumed"),
314                "{}: {}",
315                node.node_id,
316                node.description
317            );
318        }
319    }
320
321    #[test]
322    fn detection_descriptions_state_that_absence_means_nothing() {
323        let node = detection_node("front", &EventKind::Motion);
324        assert!(node.description.contains("Absence of a detection means nothing"), "{node:?}");
325    }
326
327    /// Capabilities are facts about hardware, not detections, so they are the
328    /// only nodes without the marker.
329    #[test]
330    fn capability_nodes_are_not_marked_unsafe_because_they_are_not_detections() {
331        let node = capability_node("front", Capability::Ptz);
332        assert!(!node.is_marked_unsafe());
333        assert_eq!(node.node_id, "Camera_front_Capability_ptz");
334    }
335
336    #[test]
337    fn node_ids_are_unique_within_a_camera() {
338        let nodes = nodes_for_camera("front", &kinds());
339        let ids: std::collections::BTreeSet<_> = nodes.iter().map(|n| &n.node_id).collect();
340        assert_eq!(ids.len(), nodes.len(), "duplicate node id");
341    }
342
343    #[test]
344    fn node_ids_are_namespaced_per_camera() {
345        assert_ne!(
346            detection_node("front", &EventKind::Motion).node_id,
347            detection_node("back", &EventKind::Motion).node_id
348        );
349    }
350
351    #[test]
352    fn a_camera_id_with_punctuation_yields_a_usable_node_id() {
353        let node = detection_node("front/cam 1", &EventKind::Motion);
354        assert!(
355            node.node_id.chars().all(|c| c.is_ascii_alphanumeric() || c == '_'),
356            "{}",
357            node.node_id
358        );
359    }
360
361    #[test]
362    fn a_start_sets_the_node_true_and_a_stop_sets_it_false() {
363        let start = Event::new("front", EventKind::Motion, EventState::Start);
364        let stop = Event::new("front", EventKind::Motion, EventState::Stop);
365
366        assert_eq!(event_update(&start).1, NodeValue::Boolean(true));
367        assert_eq!(event_update(&stop).1, NodeValue::Boolean(false));
368        assert_eq!(event_update(&start).0.node_id, event_update(&stop).0.node_id);
369    }
370
371    /// A pulse has no duration. Publishing it as a latched `true` with no
372    /// matching `false` is how a PLC tag ends up stuck on forever.
373    #[test]
374    fn a_pulse_publishes_true_and_the_caller_owns_clearing_it() {
375        let pulse = Event::new("front", EventKind::SceneChange, EventState::Pulse);
376        assert_eq!(event_update(&pulse).1, NodeValue::Boolean(true));
377    }
378
379    #[test]
380    fn an_unknown_event_code_maps_onto_a_single_unknown_node() {
381        // Otherwise a firmware emitting novel codes would grow the address
382        // space without bound.
383        let a = Event::new(
384            "front",
385            EventKind::Unknown { code: "A".into(), raw: String::new() },
386            EventState::Start,
387        );
388        let b = Event::new(
389            "front",
390            EventKind::Unknown { code: "B".into(), raw: String::new() },
391            EventState::Start,
392        );
393        assert_eq!(event_update(&a).0.node_id, event_update(&b).0.node_id);
394    }
395
396    #[test]
397    fn health_maps_to_its_lowercase_name() {
398        let report = HealthReport {
399            camera_id: "front".into(),
400            health: Health::Degraded,
401            issues: Vec::new(),
402            since_last_frame_ms: Some(0),
403            since_last_change_ms: Some(0),
404        };
405        assert_eq!(health_update(&report).1, NodeValue::Text("degraded".into()));
406    }
407
408    #[test]
409    fn capability_updates_report_false_for_everything_unprobed() {
410        let updates = capability_updates("front", &CapabilitySet::default());
411        assert_eq!(updates.len(), Capability::all().len());
412        assert!(updates.iter().all(|(_, v)| *v == NodeValue::Boolean(false)));
413    }
414
415    #[test]
416    fn severity_codes_preserve_the_ordering() {
417        assert!(severity_code(Severity::Info) < severity_code(Severity::Warning));
418        assert!(severity_code(Severity::Alarm) < severity_code(Severity::Critical));
419    }
420
421    /// A recording backend, so declaration can be checked without a server.
422    #[derive(Default)]
423    struct RecordingBackend {
424        declared: Mutex<Vec<NodeSpec>>,
425    }
426
427    impl OpcUaBackend for RecordingBackend {
428        fn declare(&self, spec: &NodeSpec) -> Result<(), String> {
429            self.declared.lock().expect("mutex").push(spec.clone());
430            Ok(())
431        }
432        fn publish(&self, _node_id: &str, _value: NodeValue) -> Result<(), String> {
433            Ok(())
434        }
435    }
436
437    #[test]
438    fn declaring_a_camera_registers_every_node_marked_correctly() {
439        let backend = RecordingBackend::default();
440        declare_camera(&backend, "front", &kinds()).expect("declares");
441
442        let declared = backend.declared.lock().expect("mutex");
443        assert_eq!(declared.len(), nodes_for_camera("front", &kinds()).len());
444
445        for node in declared.iter() {
446            let is_capability = node.node_id.contains("_Capability_");
447            assert_eq!(
448                node.is_marked_unsafe(),
449                !is_capability && !node.node_id.contains("ClockOffset"),
450                "wrong marking on {}",
451                node.node_id
452            );
453        }
454    }
455}