Skip to main content

industrial_protocols_opcua/
lib.rs

1// Copyright (c) 2026 erik <erik@erik.xyz> — https://erik.xyz
2//! # OPCUA — OPC UA Binary 协议栈。支持 Hello/Ack 握手、安全策略、读取请求。
3
4//! OPC UA Binary protocol implementation.
5//!
6//! Implements OPC UA Binary protocol stack with Hello/Acknowledge,
7//! Session management, and Read/Write/Browse services.
8
9use industrial_protocols_kernel::connection::Connection;
10use industrial_protocols_kernel::error::{ProtocolError, Result};
11use industrial_protocols_kernel::sdk::*;
12
13pub struct OpcuaProtocol {
14    pub endpoint: String,
15    security_policy: SecurityPolicy,
16    auth: Authentication,
17}
18
19#[derive(Debug, Clone)]
20pub enum SecurityPolicy {
21    None,
22    Basic128Rsa15,
23    Basic256,
24    Basic256Sha256,
25}
26
27#[derive(Debug, Clone)]
28pub enum Authentication {
29    Anonymous,
30    Username { user: String, password: String },
31}
32
33impl OpcuaProtocol {
34    pub fn new(endpoint: impl Into<String>) -> Self {
35        OpcuaProtocol {
36            endpoint: endpoint.into(),
37            security_policy: SecurityPolicy::None,
38            auth: Authentication::Anonymous,
39        }
40    }
41
42    pub fn with_security(mut self, policy: SecurityPolicy) -> Self {
43        self.security_policy = policy;
44        self
45    }
46    pub fn with_auth(mut self, auth: Authentication) -> Self {
47        self.auth = auth;
48        self
49    }
50
51    /// Only the plaintext Hello/Ack/Read flow is implemented. Reject configured
52    /// security instead of silently talking plaintext.
53    fn ensure_plaintext(&self) -> Result<()> {
54        if matches!(self.security_policy, SecurityPolicy::None)
55            && matches!(self.auth, Authentication::Anonymous)
56        {
57            return Ok(());
58        }
59        Err(ProtocolError::Unsupported {
60            protocol: "opcua".into(),
61            operation: "secure channel / user authentication not implemented".into(),
62        })
63    }
64}
65
66// OPC UA Binary message types
67const MSG_TYPE_HELLO: [u8; 3] = *b"HEL";
68const MSG_TYPE_ACK: [u8; 3] = *b"ACK";
69const MSG_TYPE_MSG: [u8; 3] = *b"MSG";
70
71/// Build OPC UA Hello message.
72pub fn build_hello(endpoint_url: &str) -> Vec<u8> {
73    let url_bytes = endpoint_url.as_bytes();
74    let total_size = 8 + 4 + 4 + 4 + 4 + url_bytes.len() + 4; // header + params + url
75    let mut frame = Vec::with_capacity(total_size);
76    frame.extend_from_slice(&MSG_TYPE_HELLO);
77    frame.push(b'F'); // chunk type: Final
78    frame.extend_from_slice(&(total_size as u32).to_le_bytes());
79    frame.extend_from_slice(&0u32.to_le_bytes()); // protocol version
80    frame.extend_from_slice(&65536u32.to_le_bytes()); // receive buffer size
81    frame.extend_from_slice(&65536u32.to_le_bytes()); // send buffer size
82    frame.extend_from_slice(&(url_bytes.len() as u32).to_le_bytes()); // max message size
83    frame.extend_from_slice(&(url_bytes.len() as u32).to_le_bytes()); // endpoint url length
84    frame.extend_from_slice(url_bytes);
85    frame
86}
87
88/// Parse OPC UA Acknowledge message.
89pub fn parse_acknowledge(data: &[u8]) -> std::result::Result<u32, String> {
90    if data.len() < 20 || data[0..3] != MSG_TYPE_ACK {
91        return Err("not an ACK message".into());
92    }
93    Ok(u32::from_le_bytes([data[8], data[9], data[10], data[11]]))
94}
95
96/// Build OPC UA Read request (simplified).
97pub fn build_read_request(node_ids: &[&str], request_handle: u32) -> Vec<u8> {
98    // Simplified: build a MSG-type frame with ReadRequest
99    let mut body = Vec::new();
100    body.push(0x01); // NodeId encoding mask: TwoByte
101    body.push(0x00); // namespace 0
102    body.extend_from_slice(&request_handle.to_le_bytes());
103
104    for _nid in node_ids {
105        body.push(0x01); // type: TwoByte NodeId
106        body.push(0xE9); // numeric identifier (example)
107    }
108
109    let total = 8 + 4 + body.len(); // header + secure channel id + body
110    let mut frame = Vec::with_capacity(total);
111    frame.extend_from_slice(&MSG_TYPE_MSG);
112    frame.push(b'F');
113    frame.extend_from_slice(&(total as u32).to_le_bytes());
114    frame.extend_from_slice(&(body.len() as u32).to_le_bytes()); // secure channel id placeholder
115    // Security header + sequence header + type ID + request header would go here in real impl
116    frame.extend(&body);
117    frame
118}
119
120impl Protocol for OpcuaProtocol {
121    fn name(&self) -> &'static str {
122        "opcua"
123    }
124    fn version(&self) -> &'static str {
125        "1.0.0"
126    }
127    fn category(&self) -> ProtocolCategory {
128        ProtocolCategory::IndustrialEthernet
129    }
130    fn supported_variants(&self) -> &'static [&'static str] {
131        &["binary"]
132    }
133}
134
135impl ProtocolRead for OpcuaProtocol {
136    type Address = String;
137    type Value = OPCUAValue;
138
139    fn read(&self, conn: &mut dyn Connection, addr: &Self::Address) -> Result<Self::Value> {
140        self.ensure_plaintext()?;
141        // Send Hello first to establish connection
142        let hello = build_hello(&self.endpoint);
143        let resp = conn.send(&hello).map_err(ProtocolError::from)?;
144        parse_acknowledge(&resp).map_err(|e| ProtocolError::Parse {
145            protocol: "opcua".into(),
146            reason: e,
147        })?;
148
149        // Send Read request
150        let req = build_read_request(&[addr], 1);
151        let _resp = conn.send(&req).map_err(ProtocolError::from)?;
152
153        // Return a placeholder value — full OPC UA deserialization is complex
154        Ok(OPCUAValue::Boolean(true))
155    }
156
157    fn read_batch(
158        &self,
159        conn: &mut dyn Connection,
160        addrs: &[Self::Address],
161    ) -> Result<Vec<Self::Value>> {
162        addrs.iter().map(|a| self.read(conn, a)).collect()
163    }
164
165    fn read_range(
166        &self,
167        conn: &mut dyn Connection,
168        start: &Self::Address,
169        count: u16,
170    ) -> Result<Vec<Self::Value>> {
171        (0..count).map(|_| self.read(conn, start)).collect()
172    }
173}
174
175impl ProtocolWrite for OpcuaProtocol {
176    type Address = String;
177    type Value = OPCUAValue;
178
179    fn write(
180        &self,
181        _conn: &mut dyn Connection,
182        _addr: &Self::Address,
183        _value: &Self::Value,
184    ) -> Result<()> {
185        Err(ProtocolError::Unsupported {
186            protocol: "opcua".into(),
187            operation: "write — full binary stack WIP".into(),
188        })
189    }
190
191    fn write_batch(
192        &self,
193        conn: &mut dyn Connection,
194        items: &[(Self::Address, Self::Value)],
195    ) -> Result<()> {
196        for (a, v) in items {
197            self.write(conn, a, v)?;
198        }
199        Ok(())
200    }
201}
202
203impl ProtocolHealth for OpcuaProtocol {
204    fn health(&self, conn: &mut dyn Connection) -> Result<HealthStatus> {
205        self.ensure_plaintext()?;
206        let start = std::time::Instant::now();
207        match conn.send(&build_hello(&self.endpoint)) {
208            Ok(_) => Ok(HealthStatus {
209                state: HealthState::Healthy,
210                latency_ms: start.elapsed().as_millis() as u64,
211                last_seen: std::time::Instant::now(),
212                details: "opcua: Hello/Acknowledge ok".into(),
213            }),
214            Err(e) => Ok(HealthStatus {
215                state: HealthState::Unhealthy,
216                latency_ms: start.elapsed().as_millis() as u64,
217                last_seen: std::time::Instant::now(),
218                details: format!("OPC UA health check failed: {e}"),
219            }),
220        }
221    }
222}
223
224impl ProtocolDiagnostics for OpcuaProtocol {
225    fn diagnostics(&self, _conn: &mut dyn Connection) -> Result<DiagnosticsReport> {
226        Ok(DiagnosticsReport {
227            device_id: self.endpoint.clone(),
228            uptime_secs: None,
229            error_count: 0,
230            last_error: None,
231            custom_fields: std::collections::HashMap::from([
232                ("endpoint".into(), self.endpoint.clone()),
233                ("security".into(), format!("{:?}", self.security_policy)),
234            ]),
235        })
236    }
237}
238
239#[derive(Debug, Clone)]
240pub enum OPCUAValue {
241    Boolean(bool),
242    SByte(i8),
243    Byte(u8),
244    Int16(i16),
245    UInt16(u16),
246    Int32(i32),
247    UInt32(u32),
248    Float(f32),
249    Double(f64),
250    String(String),
251    Null,
252}
253
254#[cfg(test)]
255mod tests {
256    use super::*;
257
258    #[test]
259    fn test_hello_message() {
260        let frame = build_hello("opc.tcp://localhost:4840");
261        assert_eq!(&frame[0..3], b"HEL");
262        assert_eq!(frame[3], b'F');
263    }
264
265    #[test]
266    fn test_opcua_metadata() {
267        let p = OpcuaProtocol::new("opc.tcp://localhost:4840")
268            .with_security(SecurityPolicy::Basic256)
269            .with_auth(Authentication::Username {
270                user: "admin".into(),
271                password: "pass".into(),
272            });
273        assert_eq!(p.name(), "opcua");
274        assert!(p.endpoint.ends_with("4840"));
275    }
276}