bacnet-cli 0.13.0

BACnet command-line tool for device discovery, reading, and writing
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
//! Output formatting for the BACnet CLI.
//!
//! Supports table (human-readable) and JSON output formats with automatic
//! TTY detection.

use std::net::Ipv4Addr;

use bacnet_client::discovery::DiscoveredDevice;
use bacnet_types::primitives::PropertyValue;
use owo_colors::OwoColorize;
use serde::Serialize;

/// Output format for CLI results.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum OutputFormat {
    /// Human-readable table layout.
    Table,
    /// Machine-readable JSON.
    Json,
}

/// Device information for display purposes.
#[derive(Debug, Clone, Serialize)]
pub struct DeviceInfo {
    /// BACnet device instance number.
    pub instance: u32,
    /// Network address (e.g., "192.168.1.10:47808").
    pub address: String,
    /// BACnet vendor identifier.
    pub vendor_id: u16,
    /// Maximum APDU length accepted.
    pub max_apdu: u32,
    /// Segmentation support description.
    pub segmentation: String,
    /// Remote BACnet network number (if behind a router).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub network: Option<u16>,
    /// Device MAC on the remote network (if behind a router).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub remote_mac: Option<String>,
}

/// Format a MAC address as a target the CLI reads back: a BIP MAC (6 bytes:
/// 4 IP + 2 port) as `ip:port`, and a B/IPv6 VMAC (3 bytes, the only
/// 3-byte MAC the CLI's transports use) as `bip6:0x0004D2`. Falls back to
/// hex display for other MACs.
pub fn format_mac(mac: &[u8]) -> String {
    if mac.len() == 6 {
        let ip = Ipv4Addr::new(mac[0], mac[1], mac[2], mac[3]);
        let port = u16::from_be_bytes([mac[4], mac[5]]);
        format!("{ip}:{port}")
    } else if let Ok(vmac) = <[u8; 3]>::try_from(mac) {
        bacnet_transport::bip6::format_vmac_text(bacnet_transport::bip6::Bip6Vmac::new(vmac))
    } else {
        mac.iter()
            .map(|b| format!("{b:02x}"))
            .collect::<Vec<_>>()
            .join(":")
    }
}

/// Convert a `DiscoveredDevice` into a `DeviceInfo` for display.
pub fn device_info(d: &DiscoveredDevice) -> DeviceInfo {
    DeviceInfo {
        instance: d.object_identifier.instance_number(),
        address: format_mac(d.mac_address.as_slice()),
        vendor_id: d.vendor_id,
        max_apdu: d.max_apdu_length,
        segmentation: format!("{}", d.segmentation_supported),
        network: d.source_network,
        remote_mac: d.source_address.as_ref().map(|m| format_mac(m.as_slice())),
    }
}

/// Print a list of discovered devices.
pub fn print_devices(devices: &[DeviceInfo], format: OutputFormat) {
    match format {
        OutputFormat::Table => {
            if devices.is_empty() {
                println!("{}", "No devices found.".yellow());
                return;
            }
            let has_routing = devices.iter().any(|d| d.network.is_some());
            let mut table = comfy_table::Table::new();
            if has_routing {
                table.set_header(vec![
                    "Instance",
                    "Router",
                    "DNET",
                    "Remote MAC",
                    "Vendor",
                    "Max APDU",
                    "Segmentation",
                ]);
                for d in devices {
                    table.add_row(vec![
                        d.instance.to_string(),
                        d.address.clone(),
                        d.network
                            .map(|n| n.to_string())
                            .unwrap_or_else(|| "-".into()),
                        d.remote_mac.clone().unwrap_or_else(|| "-".into()),
                        d.vendor_id.to_string(),
                        d.max_apdu.to_string(),
                        d.segmentation.clone(),
                    ]);
                }
            } else {
                table.set_header(vec![
                    "Instance",
                    "Address",
                    "Vendor",
                    "Max APDU",
                    "Segmentation",
                ]);
                for d in devices {
                    table.add_row(vec![
                        d.instance.to_string(),
                        d.address.clone(),
                        d.vendor_id.to_string(),
                        d.max_apdu.to_string(),
                        d.segmentation.clone(),
                    ]);
                }
            }
            println!("{table}");
            println!("{}", format!("Found {} device(s)", devices.len()).green());
        }
        OutputFormat::Json => {
            let json = serde_json::to_string_pretty(devices).expect("serialize devices");
            println!("{json}");
        }
    }
}

/// Format a `PropertyValue` as a human-readable string.
pub fn format_property_value(value: &PropertyValue) -> String {
    match value {
        PropertyValue::Null => "null".to_string(),
        PropertyValue::Boolean(b) => b.to_string(),
        PropertyValue::Unsigned(v) => v.to_string(),
        PropertyValue::Signed(v) => v.to_string(),
        PropertyValue::Real(v) => format!("{v}"),
        PropertyValue::Double(v) => format!("{v}"),
        PropertyValue::OctetString(bytes) => {
            let hex: Vec<String> = bytes.iter().map(|b| format!("{b:02x}")).collect();
            format!("[{}]", hex.join(" "))
        }
        PropertyValue::CharacterString(s) => format!("\"{s}\""),
        PropertyValue::BitString { unused_bits, data } => {
            let total_bits = (data.len() * 8).saturating_sub(*unused_bits as usize);
            let mut bits = String::with_capacity(total_bits);
            for i in 0..total_bits {
                let byte_idx = i / 8;
                let bit_idx = 7 - (i % 8);
                if data[byte_idx] & (1 << bit_idx) != 0 {
                    bits.push('1');
                } else {
                    bits.push('0');
                }
            }
            format!("bits({bits})")
        }
        PropertyValue::Enumerated(v) => format!("enumerated({v})"),
        PropertyValue::Date(d) => {
            let year_str = if d.year == 0xFF {
                "*".to_string()
            } else {
                format!("{}", d.year as u16 + 1900)
            };
            let month_str = if d.month == 0xFF {
                "*".to_string()
            } else {
                format!("{:02}", d.month)
            };
            let day_str = if d.day == 0xFF {
                "*".to_string()
            } else {
                format!("{:02}", d.day)
            };
            format!("{year_str}-{month_str}-{day_str}")
        }
        PropertyValue::Time(t) => {
            let hour_str = if t.hour == 0xFF {
                "*".to_string()
            } else {
                format!("{:02}", t.hour)
            };
            let minute_str = if t.minute == 0xFF {
                "*".to_string()
            } else {
                format!("{:02}", t.minute)
            };
            let second_str = if t.second == 0xFF {
                "*".to_string()
            } else {
                format!("{:02}", t.second)
            };
            let hundredths_str = if t.hundredths == 0xFF {
                "*".to_string()
            } else {
                format!("{:02}", t.hundredths)
            };
            format!("{hour_str}:{minute_str}:{second_str}.{hundredths_str}")
        }
        PropertyValue::ObjectIdentifier(oid) => {
            format!("{}:{}", oid.object_type(), oid.instance_number())
        }
        PropertyValue::List(items) => {
            let formatted: Vec<String> = items.iter().map(format_property_value).collect();
            format!("[{}]", formatted.join(", "))
        }
        PropertyValue::ApplicationData(bytes) => {
            let hex: Vec<String> = bytes.iter().map(|b| format!("{b:02x}")).collect();
            format!("application-data([{}])", hex.join(" "))
        }
    }
}

/// Print a single read result.
pub fn print_read_result(
    object: &str,
    property: &str,
    array_index: Option<u32>,
    value: &str,
    format: OutputFormat,
) {
    let prop_display = match array_index {
        Some(idx) => format!("{property}[{idx}]"),
        None => property.to_string(),
    };
    match format {
        OutputFormat::Table => {
            let mut table = comfy_table::Table::new();
            table.set_header(vec!["Object", "Property", "Value"]);
            table.add_row(vec![object, &prop_display, &format!("{}", value.green())]);
            println!("{table}");
        }
        OutputFormat::Json => {
            let result = serde_json::json!({
                "object": object,
                "property": prop_display,
                "value": value,
            });
            println!(
                "{}",
                serde_json::to_string_pretty(&result).expect("serialize read result")
            );
        }
    }
}

/// Print RPM results as a table.
///
/// Each entry is (object_str, property_str, array_index, value_str).
pub fn print_rpm_table(entries: &[(String, String, Option<u32>, String)], format: OutputFormat) {
    match format {
        OutputFormat::Table => {
            let mut table = comfy_table::Table::new();
            table.set_header(vec!["Object", "Property", "Value"]);
            for (obj, prop, idx, val) in entries {
                let prop_display = match idx {
                    Some(i) => format!("{prop}[{i}]"),
                    None => prop.clone(),
                };
                let colored_val = if val.starts_with("ERROR") {
                    format!("{}", val.red())
                } else {
                    format!("{}", val.green())
                };
                table.add_row(vec![obj.as_str(), &prop_display, &colored_val]);
            }
            println!("{table}");
        }
        OutputFormat::Json => {
            let json_results: Vec<serde_json::Value> = entries
                .iter()
                .map(|(obj, prop, idx, val)| {
                    let prop_display = match idx {
                        Some(i) => format!("{prop}[{i}]"),
                        None => prop.clone(),
                    };
                    serde_json::json!({
                        "object": obj,
                        "property": prop_display,
                        "value": val,
                    })
                })
                .collect();
            println!(
                "{}",
                serde_json::to_string_pretty(&json_results).expect("serialize rpm results")
            );
        }
    }
}

/// Print a success/status message.
pub fn print_success(msg: &str, format: OutputFormat) {
    match format {
        OutputFormat::Table => println!("{}", msg.green()),
        OutputFormat::Json => {
            let result = serde_json::json!({ "status": "ok", "message": msg });
            println!(
                "{}",
                serde_json::to_string_pretty(&result).expect("serialize success")
            );
        }
    }
}

/// Print a waiting/progress message to stderr.
pub fn print_waiting(secs: u64) {
    eprintln!("{}", format!("Waiting {secs}s for responses...").dimmed());
}

/// Print an error message to stderr.
pub fn print_error(msg: &str) {
    eprintln!("{} {}", "ERROR:".red().bold(), msg.red());
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn format_null() {
        assert_eq!(format_property_value(&PropertyValue::Null), "null");
    }

    #[test]
    fn format_boolean() {
        assert_eq!(format_property_value(&PropertyValue::Boolean(true)), "true");
    }

    #[test]
    fn format_unsigned() {
        assert_eq!(format_property_value(&PropertyValue::Unsigned(42)), "42");
    }

    #[test]
    fn format_string() {
        assert_eq!(
            format_property_value(&PropertyValue::CharacterString("hello".to_string())),
            "\"hello\""
        );
    }

    #[test]
    fn format_enumerated() {
        assert_eq!(
            format_property_value(&PropertyValue::Enumerated(3)),
            "enumerated(3)"
        );
    }

    #[test]
    fn output_format_equality() {
        assert_eq!(OutputFormat::Table, OutputFormat::Table);
        assert_ne!(OutputFormat::Table, OutputFormat::Json);
    }

    #[test]
    fn format_bitstring_empty_data() {
        // B4: empty data with unused_bits > 0 should not panic.
        let val = PropertyValue::BitString {
            unused_bits: 3,
            data: vec![],
        };
        assert_eq!(format_property_value(&val), "bits()");
    }

    #[test]
    fn format_date_human_readable() {
        use bacnet_types::primitives::Date;
        let d = Date {
            year: 124,
            month: 3,
            day: 15,
            day_of_week: 5,
        };
        assert_eq!(format_property_value(&PropertyValue::Date(d)), "2024-03-15");
    }

    #[test]
    fn format_date_unspecified() {
        use bacnet_types::primitives::Date;
        let d = Date {
            year: 0xFF,
            month: 12,
            day: 0xFF,
            day_of_week: 0xFF,
        };
        assert_eq!(format_property_value(&PropertyValue::Date(d)), "*-12-*");
    }

    #[test]
    fn format_time_human_readable() {
        use bacnet_types::primitives::Time;
        let t = Time {
            hour: 14,
            minute: 30,
            second: 0,
            hundredths: 0,
        };
        assert_eq!(
            format_property_value(&PropertyValue::Time(t)),
            "14:30:00.00"
        );
    }

    /// Each MAC prints as a target the CLI reads back: a B/IPv6 VMAC as
    /// `bip6:0x……`, not as hex, which no target form takes.
    #[test]
    fn macs_print_as_targets() {
        assert_eq!(format_mac(&[10, 0, 0, 1, 0xBA, 0xC0]), "10.0.0.1:47808");
        assert_eq!(format_mac(&[0x00, 0x04, 0xD2]), "bip6:0x0004D2");
        assert_eq!(format_mac(&[7]), "07");
        for mac in [vec![10, 0, 0, 1, 0xBA, 0xC0], vec![0x40, 0xAB, 0xCD]] {
            match crate::resolve::parse_target(&format_mac(&mac)) {
                Ok(crate::resolve::Target::Mac(parsed)) => assert_eq!(parsed, mac),
                _ => panic!("{} does not read back", format_mac(&mac)),
            }
        }
    }

    #[test]
    fn device_info_serializes() {
        let info = DeviceInfo {
            instance: 1234,
            address: "192.168.1.10:47808".to_string(),
            vendor_id: 42,
            max_apdu: 1476,
            segmentation: "both".to_string(),
            network: None,
            remote_mac: None,
        };
        let json = serde_json::to_string(&info).unwrap();
        assert!(json.contains("1234"));
        assert!(json.contains("192.168.1.10"));
    }
}