industrial_protocols_bacnet/
lib.rs1use 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
33const BVLC_TYPE: u8 = 0x81; fn 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); hdr.extend_from_slice(&(4 + payload_len).to_be_bytes()); hdr
42}
43
44pub fn build_who_is(device_instance_low: u32, device_instance_high: u32) -> Vec<u8> {
46 let apdu = vec![
49 0x10, 0x08, 0x1C, 0x04, (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]; 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
71pub fn build_i_am(device_instance: u32) -> Vec<u8> {
73 let apdu = vec![
74 0x10, 0x00, 0xC4,
77 0x02, 0x00,
79 0x16, 0x22,
81 0x04, (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
94pub 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, 0x04, invoke_id, 0x0C, 0x0C, 0x00,
109 0x00,
110 0x16, 0x22,
112 0x04, (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, ];
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
127pub fn parse_read_property_response(data: &[u8]) -> std::result::Result<f32, String> {
129 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 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
154pub fn build_who_is_any() -> Vec<u8> {
156 build_who_is(0, 4194303) }
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 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); 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 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); assert_eq!(frame[1], 0x0A); 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}