1use std::fmt::Write as _;
20use std::net::{IpAddr, Ipv4Addr, SocketAddr};
21use std::sync::Arc;
22use std::time::Duration;
23
24use tokio::sync::Mutex;
25use viva_genapi::NodeMap;
26use viva_genapi_xml::{XmlError, XmlModel};
27use viva_gige::{DeviceInfo, GVCP_PORT};
28use viva_gige::{GigeDevice, consts};
29use viva_gige::{Iface, IfaceSelector};
30
31#[derive(Debug, Clone)]
33pub struct ReportRequest {
34 pub tool: String,
37 pub notes: Vec<String>,
40 pub target: ReportTarget,
42 pub iface: Option<IfaceSelector>,
44 pub discovery_timeout: Duration,
46 pub include_xml: bool,
49}
50
51impl ReportRequest {
52 pub fn new(tool: impl Into<String>, target: ReportTarget) -> Self {
55 Self {
56 tool: tool.into(),
57 notes: Vec::new(),
58 target,
59 iface: None,
60 discovery_timeout: Duration::from_millis(500),
61 include_xml: true,
62 }
63 }
64}
65
66#[derive(Debug, Clone, PartialEq, Eq)]
68#[non_exhaustive]
69pub enum ReportTarget {
70 None,
72 Ip(Ipv4Addr),
76 Index(usize),
78 Open(OpenCamera),
83}
84
85#[derive(Debug, Clone, PartialEq, Eq)]
88pub struct OpenCamera {
89 pub transport: String,
91 pub identity: Vec<(String, String)>,
94 pub xml: String,
96}
97
98#[derive(Clone, Copy)]
103enum Fmt {
104 Bits,
106 Dec,
107 Ipv4,
108}
109
110const BOOTSTRAP: &[(u64, &str, Fmt)] = &[
116 (consts::VERSION, "Version", Fmt::Bits),
117 (consts::DEVICE_MODE, "DeviceMode", Fmt::Bits),
118 (
119 consts::DEVICE_MAC_ADDRESS_HIGH,
120 "DeviceMACAddressHigh",
121 Fmt::Bits,
122 ),
123 (
124 consts::DEVICE_MAC_ADDRESS_LOW,
125 "DeviceMACAddressLow",
126 Fmt::Bits,
127 ),
128 (
129 consts::SUPPORTED_IP_CONFIG,
130 "SupportedIPConfiguration",
131 Fmt::Bits,
132 ),
133 (
134 consts::CURRENT_IP_CONFIG,
135 "CurrentIPConfiguration",
136 Fmt::Bits,
137 ),
138 (consts::CURRENT_IP_ADDRESS, "CurrentIPAddress", Fmt::Ipv4),
139 (consts::CURRENT_SUBNET_MASK, "CurrentSubnetMask", Fmt::Ipv4),
140 (
141 consts::CURRENT_DEFAULT_GATEWAY,
142 "CurrentDefaultGateway",
143 Fmt::Ipv4,
144 ),
145 (
146 consts::PERSISTENT_IP_ADDRESS,
147 "PersistentIPAddress",
148 Fmt::Ipv4,
149 ),
150 (
151 consts::PERSISTENT_SUBNET_MASK,
152 "PersistentSubnetMask",
153 Fmt::Ipv4,
154 ),
155 (
156 consts::PERSISTENT_DEFAULT_GATEWAY,
157 "PersistentDefaultGateway",
158 Fmt::Ipv4,
159 ),
160 (
161 consts::NUMBER_OF_MESSAGE_CHANNELS,
162 "GevNumberOfMessageChannels",
163 Fmt::Dec,
164 ),
165 (
166 consts::NUMBER_OF_STREAM_CHANNELS,
167 "GevNumberOfStreamChannels",
168 Fmt::Dec,
169 ),
170 (consts::GVCP_CAPABILITY, "GevGVCPCapability", Fmt::Bits),
171 (consts::HEARTBEAT_TIMEOUT, "GevHeartbeatTimeout", Fmt::Dec),
172 (
173 consts::TIMESTAMP_TICK_FREQUENCY_HIGH,
174 "GevTimestampTickFrequencyHigh",
175 Fmt::Dec,
176 ),
177 (
178 consts::TIMESTAMP_TICK_FREQUENCY_LOW,
179 "GevTimestampTickFrequencyLow",
180 Fmt::Dec,
181 ),
182 (consts::CONTROL_CHANNEL_PRIVILEGE, "GevCCP", Fmt::Bits),
183 (consts::MESSAGE_DESTINATION_PORT, "GevMCP", Fmt::Dec),
184 (consts::MESSAGE_DESTINATION_ADDRESS, "GevMCDA", Fmt::Ipv4),
185 (consts::MESSAGE_CHANNEL_TIMEOUT, "GevMCTT", Fmt::Dec),
186 (consts::MESSAGE_CHANNEL_RETRY_COUNT, "GevMCRC", Fmt::Dec),
187 (
188 consts::STREAM_CHANNEL_BASE + consts::STREAM_DESTINATION_PORT,
189 "GevSCPHostPort[0]",
190 Fmt::Dec,
191 ),
192 (
193 consts::STREAM_CHANNEL_BASE + consts::STREAM_PACKET_SIZE,
194 "GevSCPSPacketSize[0]",
195 Fmt::Bits,
196 ),
197 (
198 consts::STREAM_CHANNEL_BASE + consts::STREAM_PACKET_DELAY,
199 "GevSCPD[0]",
200 Fmt::Dec,
201 ),
202 (
203 consts::STREAM_CHANNEL_BASE + consts::STREAM_DESTINATION_ADDRESS,
204 "GevSCDA[0]",
205 Fmt::Ipv4,
206 ),
207];
208
209fn decode(value: u32, fmt: Fmt) -> String {
210 match fmt {
211 Fmt::Bits => String::new(),
212 Fmt::Dec => value.to_string(),
213 Fmt::Ipv4 => Ipv4Addr::from(value).to_string(),
214 }
215}
216
217pub async fn build_report(request: &ReportRequest) -> String {
220 let mut out = String::new();
221 let _ = writeln!(out, "# viva-genicam diagnostic report");
222 let _ = writeln!(out);
223
224 environment(&mut out, request);
225 interfaces(&mut out);
226 let devices = discovery(
227 &mut out,
228 request.iface.as_ref(),
229 request.discovery_timeout.as_millis() as u64,
230 )
231 .await;
232 usb_devices(&mut out).await;
233 camera(&mut out, request, &devices).await;
234
235 let _ = writeln!(out, "## End of report");
236 out
237}
238
239fn environment(out: &mut String, request: &ReportRequest) {
240 let _ = writeln!(out, "## Environment");
241 let _ = writeln!(out);
242 let _ = writeln!(out, "tool: {}", request.tool);
243 let _ = writeln!(
244 out,
245 "library: viva-genicam {}",
246 env!("CARGO_PKG_VERSION")
247 );
248 let _ = writeln!(
249 out,
250 "host: {} {}",
251 std::env::consts::OS,
252 std::env::consts::ARCH
253 );
254 for note in &request.notes {
255 let _ = writeln!(out, "{note}");
256 }
257 let _ = writeln!(out);
258}
259
260fn opt_ip(ip: Option<std::net::Ipv4Addr>) -> String {
261 ip.map_or_else(|| "-".to_string(), |ip| ip.to_string())
262}
263
264fn interfaces(out: &mut String) {
265 let _ = writeln!(out, "## Network interfaces");
266 let _ = writeln!(out);
267 let _ = writeln!(
268 out,
269 "As the library sees them. An interface missing here is invisible to \
270 discovery no matter what the OS reports elsewhere (#57)."
271 );
272 let _ = writeln!(out);
273 match Iface::list() {
278 Ok(ifaces) if ifaces.is_empty() => {
279 let _ = writeln!(out, "(none reported)");
280 }
281 Ok(ifaces) => {
282 for iface in ifaces {
283 let addrs = iface.all_ipv4().unwrap_or_default();
284 let addrs = if addrs.is_empty() {
285 "-".to_string()
286 } else {
287 addrs
288 .iter()
289 .map(|ip| ip.to_string())
290 .collect::<Vec<_>>()
291 .join(", ")
292 };
293 let mtu = viva_gige::mtu(&iface).to_string();
294 let _ = writeln!(
295 out,
296 "{:<16} index={:<5} mtu={:<9} ipv4=[{}]",
297 iface.name(),
298 iface.index(),
299 mtu,
300 addrs
301 );
302 }
303 }
304 Err(err) => {
305 let _ = writeln!(out, "FAILED to enumerate interfaces: {err}");
306 }
307 }
308 let _ = writeln!(out);
309}
310
311async fn discover_devices(
315 timeout: Duration,
316 iface: Option<&IfaceSelector>,
317) -> Result<Vec<DeviceInfo>, String> {
318 let options = viva_gige::DiscoveryOptions::new().allow_broadcast_ack(true);
319 match iface {
320 Some(selector) => {
321 let iface = selector
322 .resolve()
323 .map_err(|e| format!("resolve host interface '{selector}': {e}"))?;
324 viva_gige::discover_with(timeout, &options.interface(iface.name()))
325 .await
326 .map_err(|e| format!("discover devices on interface: {e}"))
327 }
328 None => viva_gige::discover_with(timeout, &options)
329 .await
330 .map_err(|e| format!("broadcast discovery: {e}")),
331 }
332}
333
334async fn discovery(
335 out: &mut String,
336 iface: Option<&IfaceSelector>,
337 timeout_ms: u64,
338) -> Vec<DeviceInfo> {
339 let _ = writeln!(out, "## Discovery");
340 let _ = writeln!(out);
341 let timeout = Duration::from_millis(timeout_ms);
342 match discover_devices(timeout, iface).await {
343 Ok(devices) if devices.is_empty() => {
344 let _ = writeln!(out, "no cameras answered within {timeout_ms} ms");
345 let _ = writeln!(out);
346 Vec::new()
347 }
348 Ok(devices) => {
349 for (index, dev) in devices.iter().enumerate() {
350 let _ = writeln!(out, "[{index}] {}", dev.ip);
351 let _ = writeln!(out, " mac: {}", dev.mac_string());
352 let _ = writeln!(out, " manufacturer: {}", opt(&dev.manufacturer));
353 let _ = writeln!(out, " model: {}", opt(&dev.model));
354 let _ = writeln!(out, " version: {}", opt(&dev.version));
355 let _ = writeln!(out, " serial: {}", opt(&dev.serial));
356 let _ = writeln!(out, " user name: {}", opt(&dev.user_name));
357 let _ = writeln!(out, " subnet: {}", opt_ip(dev.subnet));
358 let _ = writeln!(out, " gateway: {}", opt_ip(dev.gateway));
359 if let (Some(false), Some(host), Some(mask)) = (
360 dev.shares_subnet_with_host(),
361 dev.local_ip,
362 dev.local_netmask,
363 ) {
364 let _ = writeln!(
365 out,
366 " WARNING: not on the subnet of {host}/{}, which heard it; \
367 connections to it will fail until its address or the host's changes \
368 (viva-camctl set-ip)",
369 u32::from(mask).leading_ones()
370 );
371 }
372 }
373 let _ = writeln!(out);
374 devices
375 }
376 Err(err) => {
377 let _ = writeln!(out, "FAILED: {err}");
378 let _ = writeln!(out);
379 Vec::new()
380 }
381 }
382}
383
384#[cfg(feature = "u3v-usb")]
386async fn usb_devices(out: &mut String) {
387 let _ = writeln!(out, "## USB3 Vision devices");
388 let _ = writeln!(out);
389 match tokio::task::spawn_blocking(viva_u3v::discover).await {
391 Ok(Ok(devices)) if devices.is_empty() => {
392 let _ = writeln!(out, "none found");
393 }
394 Ok(Ok(devices)) => {
395 for (index, dev) in devices.iter().enumerate() {
396 let _ = writeln!(
397 out,
398 "[{index}] {:04x}:{:04x} on bus {} address {}",
399 dev.vendor_id, dev.product_id, dev.bus, dev.address
400 );
401 let _ = writeln!(out, " manufacturer: {}", opt(&dev.manufacturer));
402 let _ = writeln!(out, " model: {}", opt(&dev.model));
403 let _ = writeln!(out, " serial: {}", opt(&dev.serial));
404 let speed = dev.speed.map(|speed| speed.to_string());
405 let _ = writeln!(out, " link speed: {}", opt(&speed));
406 }
407 }
408 Ok(Err(err)) => {
409 let _ = writeln!(out, "FAILED: {err}");
410 }
411 Err(err) => {
412 let _ = writeln!(out, "FAILED: {err}");
413 }
414 }
415 let _ = writeln!(out);
416}
417
418#[cfg(not(feature = "u3v-usb"))]
419async fn usb_devices(_out: &mut String) {}
420
421async fn camera(out: &mut String, request: &ReportRequest, discovered: &[DeviceInfo]) {
422 let _ = writeln!(out, "## Camera");
423 let _ = writeln!(out);
424
425 if let ReportTarget::Open(camera) = &request.target {
426 let _ = writeln!(out, "transport: {}", camera.transport);
427 for (key, value) in &camera.identity {
428 let _ = writeln!(out, "{key}: {value}");
429 }
430 let _ = writeln!(out);
431 genapi(out, &camera.xml, request.include_xml);
432 return;
433 }
434
435 let device = match select(&request.target, discovered) {
436 Some(device) => device,
437 None => {
438 let _ = writeln!(
439 out,
440 "No camera selected, so there are no register, XML or feature sections."
441 );
442 let _ = writeln!(out);
443 return;
444 }
445 };
446 let _ = writeln!(out, "selected: {}", device.ip);
447 let _ = writeln!(out);
448
449 let addr = SocketAddr::new(IpAddr::V4(device.ip), GVCP_PORT);
450 let control = match GigeDevice::open(addr).await {
451 Ok(control) => Arc::new(Mutex::new(control)),
452 Err(err) => {
453 let _ = writeln!(
454 out,
455 "FAILED to open the control channel at {}: {err}",
456 device.ip
457 );
458 let _ = writeln!(out);
459 return;
460 }
461 };
462
463 bootstrap_registers(out, &control).await;
464
465 let xml = match fetch_xml(Arc::clone(&control)).await {
466 Ok(xml) => xml,
467 Err(err) => {
468 let _ = writeln!(out, "## GenApi XML");
469 let _ = writeln!(out);
470 let _ = writeln!(out, "FAILED to fetch: {err}");
471 let _ = writeln!(out);
472 return;
473 }
474 };
475 genapi(out, &xml, request.include_xml);
476}
477
478async fn fetch_xml(control: Arc<Mutex<GigeDevice>>) -> Result<String, XmlError> {
479 viva_genapi_xml::fetch_and_load_xml(move |address, length| {
480 let control = Arc::clone(&control);
481 async move {
482 let mut guard = control.lock().await;
483 guard
484 .read_mem(address, length)
485 .await
486 .map_err(XmlError::transport)
487 }
488 })
489 .await
490}
491
492fn select(target: &ReportTarget, discovered: &[DeviceInfo]) -> Option<DeviceInfo> {
493 match *target {
494 ReportTarget::None | ReportTarget::Open(_) => None,
495 ReportTarget::Ip(ip) => Some(
496 discovered
497 .iter()
498 .find(|dev| dev.ip == ip)
499 .cloned()
500 .unwrap_or_else(|| DeviceInfo::from_ip(ip)),
501 ),
502 ReportTarget::Index(index) => discovered.get(index).cloned(),
503 }
504}
505
506async fn bootstrap_registers(out: &mut String, control: &Arc<Mutex<GigeDevice>>) {
507 let _ = writeln!(out, "## Bootstrap registers");
508 let _ = writeln!(out);
509 let mut guard = control.lock().await;
510 for (addr, name, fmt) in BOOTSTRAP {
511 let value = match guard.read_register(*addr as u32).await {
512 Ok(value) => format!("0x{value:08X} {}", decode(value, *fmt)),
513 Err(err) => format!("read failed: {err}"),
514 };
515 let _ = writeln!(out, "0x{addr:04X} {name:<26} {}", value.trim_end());
516 }
517 let _ = writeln!(out);
518}
519
520fn genapi(out: &mut String, xml: &str, include_xml: bool) {
521 let _ = writeln!(out, "## GenApi");
522 let _ = writeln!(out);
523 let _ = writeln!(out, "XML size: {} bytes", xml.len());
524
525 let model: Option<XmlModel> = match viva_genapi_xml::parse(xml) {
526 Ok(model) => {
527 let _ = writeln!(
528 out,
529 "schema: {}\nparsed: {} nodes",
530 model.version,
531 model.nodes.len()
532 );
533 Some(model)
534 }
535 Err(err) => {
536 let _ = writeln!(out, "PARSE FAILED: {err}");
537 None
538 }
539 };
540
541 if let Some(model) = model {
542 match NodeMap::try_from_xml(model) {
543 Ok(nodemap) => {
544 let _ = writeln!(out, "built: {} features", nodemap.node_names().count());
545 let _ = writeln!(out);
546 let skipped = nodemap.skipped();
547 if skipped.is_empty() {
548 let _ = writeln!(out, "No features were dropped.");
549 } else {
550 let _ = writeln!(
551 out,
552 "{} feature(s) this camera has that we cannot expose — \
553 these are the interesting ones:",
554 skipped.len()
555 );
556 let _ = writeln!(out);
557 for node in skipped {
558 let _ = writeln!(
559 out,
560 " <{}> {}: {}",
561 node.tag,
562 node.name.as_deref().unwrap_or("<unnamed>"),
563 node.error
564 );
565 }
566 }
567 ignored_elements(out, nodemap.ignored());
568 }
569 Err(err) => {
570 let _ = writeln!(out, "NODEMAP BUILD FAILED: {err}");
571 }
572 }
573 }
574 let _ = writeln!(out);
575
576 if !include_xml {
577 let _ = writeln!(
578 out,
579 "## GenApi XML\n\nOmitted on request. Include it, or run \
580 `viva-camctl xml`, if asked for the document."
581 );
582 } else {
583 let _ = writeln!(out, "## GenApi XML");
584 let _ = writeln!(out);
585 let _ = writeln!(out, "{xml}");
586 }
587 let _ = writeln!(out);
588}
589
590fn ignored_elements(out: &mut String, ignored: &[viva_genapi::IgnoredElement]) {
594 if ignored.is_empty() {
595 return;
596 }
597 let mut groups: Vec<(&str, &str, usize, &str)> = Vec::new();
598 for element in ignored {
599 match groups
600 .iter_mut()
601 .find(|(kind, tag, _, _)| *kind == element.kind && *tag == element.element)
602 {
603 Some(group) => group.2 += 1,
604 None => groups.push((&element.kind, &element.element, 1, &element.node)),
605 }
606 }
607 let _ = writeln!(out);
608 let _ = writeln!(
609 out,
610 "{} element(s) of {} kind(s) the parser read past without interpreting \
611 (documentation, or a gap):",
612 ignored.len(),
613 groups.len()
614 );
615 let _ = writeln!(out);
616 for (kind, tag, count, example) in groups {
617 let _ = writeln!(out, " <{tag}> on {kind} x{count} (e.g. {example})");
618 }
619}
620
621fn opt(value: &Option<String>) -> &str {
622 value.as_deref().unwrap_or("-")
623}
624
625#[cfg(test)]
626mod tests {
627 use super::*;
628
629 #[test]
630 fn bootstrap_addresses_are_unique() {
631 let mut seen = std::collections::HashSet::new();
632 for (addr, name, _) in BOOTSTRAP {
633 assert!(seen.insert(*addr), "duplicate address for {name}");
634 }
635 }
636
637 #[test]
638 fn ip_registers_decode_to_dotted_quads() {
639 assert_eq!(decode(0x7F00_0001, Fmt::Ipv4), "127.0.0.1");
640 assert_eq!(decode(0xFF00_0000, Fmt::Ipv4), "255.0.0.0");
641 assert_eq!(decode(3000, Fmt::Dec), "3000");
642 assert_eq!(decode(0x8000_0001, Fmt::Bits), "");
643 }
644
645 #[test]
648 fn unparsable_xml_still_produces_a_section() {
649 let mut out = String::new();
650 genapi(&mut out, "<not-genicam>", false);
651 assert!(out.contains("PARSE FAILED"), "{out}");
652 assert!(out.contains("XML size: 13 bytes"), "{out}");
653 }
654
655 #[test]
656 fn skipped_features_are_listed() {
657 const XML: &str = r#"
658 <RegisterDescription SchemaMajorVersion="1" SchemaMinorVersion="1" SchemaSubMinorVersion="0">
659 <ConfRom Name="DeviceConfRom">
660 <Address>0x2000</Address>
661 <Length>512</Length>
662 </ConfRom>
663 </RegisterDescription>
664 "#;
665 let mut out = String::new();
666 genapi(&mut out, XML, false);
667 assert!(out.contains("<ConfRom> DeviceConfRom"), "{out}");
668 assert!(out.contains("cannot expose"), "{out}");
669 }
670
671 #[test]
674 fn elements_read_past_are_listed() {
675 const XML: &str = r#"
676 <RegisterDescription SchemaMajorVersion="1" SchemaMinorVersion="1" SchemaSubMinorVersion="0">
677 <Integer Name="A"><Value>1</Value><Extension/><EventID>9C43</EventID></Integer>
678 <Integer Name="B"><Value>2</Value><Extension/></Integer>
679 </RegisterDescription>
680 "#;
681 let mut out = String::new();
682 genapi(&mut out, XML, false);
683 assert!(out.contains("3 element(s) of 2 kind(s)"), "{out}");
684 assert!(out.contains("<Extension> on Integer x2 (e.g. A)"), "{out}");
685 assert!(out.contains("<EventID> on Integer x1 (e.g. A)"), "{out}");
686 }
687
688 #[test]
689 fn the_xml_is_included_unless_opted_out() {
690 const XML: &str = r#"<RegisterDescription SchemaMajorVersion="1" SchemaMinorVersion="1" SchemaSubMinorVersion="0"/>"#;
691 let mut with = String::new();
692 genapi(&mut with, XML, true);
693 assert!(with.contains("SchemaMajorVersion"), "{with}");
694
695 let mut without = String::new();
696 genapi(&mut without, XML, false);
697 assert!(without.contains("Omitted on request"), "{without}");
698 }
699}