Skip to main content

opcua_server/diagnostics/
mod.rs

1//! This module contains the diagnostics node manager, and related types.
2
3mod node_manager;
4mod server;
5pub use node_manager::{DiagnosticsNodeManager, DiagnosticsNodeManagerBuilder, NamespaceMetadata};
6use opcua_core::sync::Mutex;
7use opcua_types::{DataValue, DateTime, IntoVariant};
8pub use server::{ServerDiagnostics, ServerDiagnosticsSummary};
9
10#[derive(Default)]
11/// Wrapper around a value in memory, used for metrics.
12/// We need to use a mutex to keep track of when the value was last
13/// updated.
14pub struct LocalValue<T> {
15    inner: Mutex<LocalValueInner<T>>,
16}
17
18#[derive(Default)]
19struct LocalValueInner<T> {
20    pub value: T,
21    pub timestamp: DateTime,
22}
23
24impl<T: Clone + IntoVariant> LocalValue<T> {
25    /// Create a new LocalValue with the given value.
26    pub fn new(value: T) -> Self {
27        Self {
28            inner: Mutex::new(LocalValueInner {
29                value,
30                timestamp: DateTime::now(),
31            }),
32        }
33    }
34
35    /// Update the value and set the timestamp.
36    pub fn modify(&self, fun: impl FnOnce(&mut T)) {
37        let mut inner = self.inner.lock();
38        fun(&mut inner.value);
39        inner.timestamp = DateTime::now();
40    }
41
42    /// Set the value and update the timestamp.
43    pub fn set(&self, value: T) {
44        let mut inner = self.inner.lock();
45        inner.value = value;
46        inner.timestamp = DateTime::now();
47    }
48
49    /// Get the current value as a datavalue.
50    pub fn sample(&self) -> DataValue {
51        let inner = self.inner.lock();
52        DataValue::new_at(inner.value.clone().into_variant(), inner.timestamp)
53    }
54
55    /// Get the current value.
56    pub fn get(&self) -> T {
57        let inner = self.inner.lock();
58        inner.value.clone()
59    }
60
61    /// Get the current value and timestamp.
62    pub fn get_with_time(&self) -> (T, DateTime) {
63        let inner = self.inner.lock();
64        (inner.value.clone(), inner.timestamp)
65    }
66}
67
68impl LocalValue<u32> {
69    /// Convenience function to increment the value.
70    pub fn increment(&self) {
71        self.modify(|v| *v += 1);
72    }
73
74    /// Convenience function to decrement the value.
75    pub fn decrement(&self) {
76        self.modify(|v| {
77            *v = v.saturating_sub(1);
78        });
79    }
80}