Skip to main content

industrial_protocols_bacnet/
lib.rs

1// Copyright (c) 2026 erik <erik@erik.xyz> — https://erik.xyz
2//! # BACNET — BACnet/IP 协议。BVLC 虚拟链路控制、Who-Is/I-Am 设备发现、ReadProperty 服务。
3
4//! BACnet/IP protocol implementation.
5//!
6//! Implements BVLC (BACnet Virtual Link Control) over UDP,
7//! Who-Is/I-Am device discovery, and ReadProperty service.
8
9use industrial_protocols_kernel::bridge::Transport;
10use industrial_protocols_kernel::connection::Connection;
11use industrial_protocols_kernel::error::{ProtocolError, Result};
12use industrial_protocols_kernel::sdk::*;
13
14pub struct BacnetProtocol {
15    pub device_instance: u32,
16    vendor_id: u16,
17}
18
19impl BacnetProtocol {
20    pub fn new(device_instance: u32) -> Self {
21        BacnetProtocol {
22            device_instance,
23            vendor_id: 0,
24        }
25    }
26
27    pub fn with_vendor(mut self, vendor_id: u16) -> Self {
28        self.vendor_id = vendor_id;
29        self
30    }
31}
32
33// BVLC header: [Type 1B] [Function 1B] [Length 2B] [Data nB]
34const BVLC_TYPE: u8 = 0x81; // BACnet/IP
35
36fn build_bvlc_header(payload_len: u16) -> Vec<u8> {
37    let mut hdr = Vec::with_capacity(4);
38    hdr.push(BVLC_TYPE);
39    hdr.push(0x0A); // Original-Unicast-NPDU
40    hdr.extend_from_slice(&(4 + payload_len).to_be_bytes()); // total length including header
41    hdr
42}
43
44/// Build a Who-Is request (unconfirmed service).
45pub fn build_who_is(device_instance_low: u32, device_instance_high: u32) -> Vec<u8> {
46    // NPDU: [Version 1B] [Control 1B]
47    // APDU: [Type 1B=unconfirmed] [Service 1B=Who-Is] [Params...]
48    let apdu = vec![
49        0x10, // Unconfirmed-Request, no segmentation
50        0x08, // Who-Is service choice (unconfirmed)
51        0x1C, // tag: context-specific, 4, value
52        0x04, // length 4
53        (device_instance_low >> 24) as u8,
54        (device_instance_low >> 16) as u8,
55        (device_instance_low >> 8) as u8,
56        device_instance_low as u8,
57        0x1C,
58        0x04,
59        (device_instance_high >> 24) as u8,
60        (device_instance_high >> 16) as u8,
61        (device_instance_high >> 8) as u8,
62        device_instance_high as u8,
63    ];
64    let npdu = [0x01, 0x04]; // Version 1, no network layer
65    let payload: Vec<u8> = npdu.iter().chain(apdu.iter()).copied().collect();
66    let mut frame = build_bvlc_header(payload.len() as u16);
67    frame.extend(&payload);
68    frame
69}
70
71/// Build an I-Am response (unconfirmed service).
72pub fn build_i_am(device_instance: u32) -> Vec<u8> {
73    let apdu = vec![
74        0x10, // Unconfirmed-Request
75        0x00, // I-Am service
76        0xC4,
77        0x02, // tag: application, unsigned
78        0x00,
79        0x16, // device object type (8)
80        0x22,
81        0x04, // tag: application, unsigned 32
82        (device_instance >> 24) as u8,
83        (device_instance >> 16) as u8,
84        (device_instance >> 8) as u8,
85        device_instance as u8,
86    ];
87    let npdu = [0x01, 0x04];
88    let payload: Vec<u8> = npdu.iter().chain(apdu.iter()).copied().collect();
89    let mut frame = build_bvlc_header(payload.len() as u16);
90    frame.extend(&payload);
91    frame
92}
93
94/// Build a ReadProperty request (confirmed service).
95pub fn build_read_property(
96    invoke_id: u8,
97    device_instance: u32,
98    _object_type: u16,
99    _object_instance: u32,
100    property_id: u16,
101) -> Vec<u8> {
102    let apdu = vec![
103        0x00,      // Confirmed-Request, no segmentation
104        0x04,      // max APDU length accepted (206)
105        invoke_id, // invoke ID
106        0x0C,      // ReadProperty service
107        0x0C,      // context tag: object specifier
108        0x00,
109        0x00,
110        0x16, // object type (DEVICE=8)
111        0x22,
112        0x04, // app tag, unsigned 32
113        (device_instance >> 24) as u8,
114        (device_instance >> 16) as u8,
115        (device_instance >> 8) as u8,
116        device_instance as u8,
117        0x19,
118        (property_id & 0xFF) as u8, // context tag, property ID
119    ];
120    let npdu = [0x01, 0x04];
121    let payload: Vec<u8> = npdu.iter().chain(apdu.iter()).copied().collect();
122    let mut frame = build_bvlc_header(payload.len() as u16);
123    frame.extend(&payload);
124    frame
125}
126
127/// Parse a ReadProperty response, extracting the value.
128pub fn parse_read_property_response(data: &[u8]) -> std::result::Result<f32, String> {
129    // Skip BVLC (4) + NPDU (2) + APDU header (4) + service ack (1) + object id (7)
130    // Look for opening tag 0x3E (property value), then application tag 0x44 (real)
131    let payload = if data.len() > 6 {
132        &data[6..]
133    } else {
134        return Err("response too short".into());
135    };
136    if let Some(pos) = payload.windows(2).position(|w| w == [0x44, 0x04]) {
137        let start = pos + 2;
138        if start + 4 <= payload.len() {
139            let bytes: [u8; 4] = payload[start..start + 4].try_into().unwrap();
140            return Ok(f32::from_be_bytes(bytes));
141        }
142    }
143    // Try parsing as unsigned integer if real not found
144    if let Some(pos) = payload.windows(2).position(|w| w == [0x22, 0x04]) {
145        let start = pos + 2;
146        if start + 4 <= payload.len() {
147            let bytes: [u8; 4] = payload[start..start + 4].try_into().unwrap();
148            return Ok(u32::from_be_bytes(bytes) as f32);
149        }
150    }
151    Err("could not parse property value".into())
152}
153
154/// Build a generic Who-Is without device instance range limits.
155pub fn build_who_is_any() -> Vec<u8> {
156    build_who_is(0, 4194303) // full range
157}
158
159impl Protocol for BacnetProtocol {
160    fn name(&self) -> &'static str {
161        "bacnet"
162    }
163    fn version(&self) -> &'static str {
164        "1.0.0"
165    }
166    fn category(&self) -> ProtocolCategory {
167        ProtocolCategory::IndustrialEthernet
168    }
169    fn supported_variants(&self) -> &'static [&'static str] {
170        &["ip", "ethernet"]
171    }
172}
173
174impl ProtocolRead for BacnetProtocol {
175    type Address = String;
176    type Value = f32;
177
178    fn read(&self, conn: &mut dyn Connection, addr: &Self::Address) -> Result<Self::Value> {
179        // Parse address as "object_type:instance:property_id" e.g. "0:0:85" (DEVICE:0:present-value)
180        let parts: Vec<&str> = addr.split(':').collect();
181        let obj_type: u16 = parts.first().and_then(|s| s.parse().ok()).unwrap_or(0);
182        let obj_inst: u32 = parts
183            .get(1)
184            .and_then(|s| s.parse().ok())
185            .unwrap_or(self.device_instance);
186        let prop_id: u16 = parts.get(2).and_then(|s| s.parse().ok()).unwrap_or(85); // present-value
187
188        let frame = build_read_property(1, obj_inst, obj_type, obj_inst, prop_id);
189        let resp = conn.send(&frame).map_err(ProtocolError::from)?;
190        parse_read_property_response(&resp).map_err(|e| ProtocolError::Parse {
191            protocol: "bacnet".into(),
192            reason: e,
193        })
194    }
195
196    fn read_batch(
197        &self,
198        conn: &mut dyn Connection,
199        addrs: &[Self::Address],
200    ) -> Result<Vec<Self::Value>> {
201        addrs.iter().map(|a| self.read(conn, a)).collect()
202    }
203
204    fn read_range(
205        &self,
206        conn: &mut dyn Connection,
207        start: &Self::Address,
208        count: u16,
209    ) -> Result<Vec<Self::Value>> {
210        (0..count).map(|_| self.read(conn, start)).collect()
211    }
212}
213
214impl ProtocolWrite for BacnetProtocol {
215    type Address = String;
216    type Value = f32;
217
218    fn write(
219        &self,
220        _conn: &mut dyn Connection,
221        _addr: &Self::Address,
222        _value: &Self::Value,
223    ) -> Result<()> {
224        Err(ProtocolError::Unsupported {
225            protocol: "bacnet".into(),
226            operation: "write — use WriteProperty service".into(),
227        })
228    }
229
230    fn write_batch(
231        &self,
232        conn: &mut dyn Connection,
233        items: &[(Self::Address, Self::Value)],
234    ) -> Result<()> {
235        for (a, v) in items {
236            self.write(conn, a, v)?;
237        }
238        Ok(())
239    }
240}
241
242impl ProtocolDiscover for BacnetProtocol {
243    fn discover(&self, transport: &mut dyn Transport) -> Result<Vec<DiscoveredDevice>> {
244        let frame = build_who_is_any();
245        match transport.send(&frame) {
246            Ok(_resp) => {
247                let device_id = format!("bacnet:{}", self.device_instance);
248                Ok(vec![DiscoveredDevice {
249                    device_id,
250                    protocol: "bacnet".into(),
251                    address: format!("instance={}", self.device_instance),
252                    metadata: std::collections::HashMap::from([(
253                        "vendor_id".into(),
254                        self.vendor_id.to_string(),
255                    )]),
256                }])
257            }
258            Err(e) => Err(ProtocolError::Connection(format!(
259                "BACnet discovery failed: {e}"
260            ))),
261        }
262    }
263}
264
265impl ProtocolHealth for BacnetProtocol {
266    fn health(&self, conn: &mut dyn Connection) -> Result<HealthStatus> {
267        let start = std::time::Instant::now();
268        // Try reading the device object name (property 77)
269        match self.read(conn, &format!("8:{}:77", self.device_instance)) {
270            Ok(_) => Ok(HealthStatus {
271                state: HealthState::Healthy,
272                latency_ms: start.elapsed().as_millis() as u64,
273                last_seen: std::time::Instant::now(),
274                details: "bacnet: ReadProperty DEVICE.object-name ok".into(),
275            }),
276            Err(e) => Ok(HealthStatus {
277                state: HealthState::Unhealthy,
278                latency_ms: start.elapsed().as_millis() as u64,
279                last_seen: std::time::Instant::now(),
280                details: format!("bacnet health check failed: {e}"),
281            }),
282        }
283    }
284}
285
286impl ProtocolDiagnostics for BacnetProtocol {
287    fn diagnostics(&self, _conn: &mut dyn Connection) -> Result<DiagnosticsReport> {
288        Ok(DiagnosticsReport {
289            device_id: format!("bacnet:{}", self.device_instance),
290            uptime_secs: None,
291            error_count: 0,
292            last_error: None,
293            custom_fields: std::collections::HashMap::from([
294                ("device_instance".into(), self.device_instance.to_string()),
295                ("vendor_id".into(), self.vendor_id.to_string()),
296            ]),
297        })
298    }
299}
300
301#[cfg(test)]
302mod tests {
303    use super::*;
304
305    #[test]
306    fn test_who_is_frame() {
307        let frame = build_who_is_any();
308        assert_eq!(frame[0], 0x81); // BVLC type
309        assert_eq!(frame[1], 0x0A); // function
310        assert!(frame.len() > 4);
311    }
312
313    #[test]
314    fn test_read_property_frame() {
315        let frame = build_read_property(1, 1001, 0, 1001, 85);
316        assert_eq!(frame[0], 0x81);
317        assert!(frame.len() > 10);
318    }
319
320    #[test]
321    fn test_bacnet_metadata() {
322        let p = BacnetProtocol::new(1001).with_vendor(42);
323        assert_eq!(p.name(), "bacnet");
324        assert_eq!(p.device_instance, 1001);
325        assert_eq!(p.vendor_id, 42);
326    }
327}