1#![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
45pub const NOT_SAFETY_RATED: &str = "NotSafetyRated";
50
51pub 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#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
59#[serde(rename_all = "PascalCase")]
60pub enum NodeType {
61 Boolean,
63 String,
65 Int64,
67 DateTime,
69}
70
71#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
73pub struct NodeSpec {
74 pub node_id: String,
76 pub browse_name: String,
78 pub description: String,
80 pub node_type: NodeType,
82}
83
84impl NodeSpec {
85 pub fn is_safe_for_interlock(&self) -> bool {
91 false
92 }
93
94 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#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
102#[serde(untagged)]
103pub enum NodeValue {
104 Boolean(bool),
106 Text(String),
108 Int64(i64),
110}
111
112pub trait OpcUaBackend: Send + Sync {
118 fn declare(&self, spec: &NodeSpec) -> Result<(), String>;
120 fn publish(&self, node_id: &str, value: NodeValue) -> Result<(), String>;
122}
123
124fn 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
133pub 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
158pub 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
173pub 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
186pub 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
204pub 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
212pub 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
224pub 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
236pub 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
252pub 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
262pub 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 #[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 #[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 #[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 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 #[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}