1#![cfg_attr(docsrs, feature(doc_cfg))]
2use serde::{Deserialize, Serialize};
11
12pub mod camera_event;
13pub mod camera_tools;
14pub mod evs_header;
15pub mod frame_header;
16pub mod frame_metadata;
17pub use camera_event::{
18 CameraEvent, EventCommand, EventControlRequest, EventFeature, EventMonitorStatus,
19};
20#[cfg(feature = "genicam")]
21#[cfg_attr(docsrs, doc(cfg(feature = "genicam")))]
22pub use camera_event::{restore_warnings, setup_error_message};
23pub use camera_tools::{
24 ConfigurationLoadRequest, ConfigurationLoaded, ConfigurationOmission, ConfigurationSaved,
25 RegisterData, RegisterWriteRequest,
26};
27pub use evs_header::{EVS_HEADER_SIZE, EVS_MAGIC, EvsFormat, EvsHeader, EvsHeaderError};
28pub use frame_header::{FRAME_MAGIC, FrameHeader, FrameHeaderError, HEADER_SIZE};
29pub use frame_metadata::{
30 FrameChunk, FrameFeature, FrameMetadata, MAX_FRAME_METADATA_BYTES, MAX_FRAME_METADATA_ITEMS,
31 MAX_FRAME_METADATA_TEXT,
32};
33
34pub const API_VERSION: u32 = 10;
82
83#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
91#[non_exhaustive]
92pub struct DeviceAnnounce {
93 pub id: String,
96 pub name: String,
98 pub model: String,
100 pub serial: String,
104 #[serde(default)]
109 pub api_version: Option<u32>,
110 #[serde(default, skip_serializing_if = "Option::is_none")]
113 pub ip: Option<String>,
114 #[serde(default, skip_serializing_if = "Option::is_none")]
116 pub mac: Option<String>,
117 #[serde(default, skip_serializing_if = "Option::is_none")]
120 pub user_name: Option<String>,
121 #[serde(default, skip_serializing_if = "Option::is_none")]
123 pub manufacturer: Option<String>,
124}
125
126impl DeviceAnnounce {
127 pub fn new(
130 id: impl Into<String>,
131 name: impl Into<String>,
132 model: impl Into<String>,
133 serial: impl Into<String>,
134 ) -> Self {
135 Self {
136 id: id.into(),
137 name: name.into(),
138 model: model.into(),
139 serial: serial.into(),
140 api_version: Some(API_VERSION),
141 ip: None,
142 mac: None,
143 user_name: None,
144 manufacturer: None,
145 }
146 }
147
148 pub fn for_gige(
156 mac: &[u8; 6],
157 ip: std::net::Ipv4Addr,
158 model: Option<&str>,
159 serial: Option<&str>,
160 user_name: Option<&str>,
161 manufacturer: Option<&str>,
162 ) -> Self {
163 let name = user_name
164 .or(model)
165 .map_or_else(|| ip.to_string(), str::to_string);
166 let mut announce = Self::new(
167 gige_device_id(mac),
168 name,
169 model.unwrap_or_default(),
170 serial.unwrap_or_default(),
171 );
172 announce.ip = Some(ip.to_string());
173 announce.mac = Some(
174 mac.iter()
175 .map(|b| format!("{b:02X}"))
176 .collect::<Vec<_>>()
177 .join(":"),
178 );
179 announce.user_name = user_name.map(str::to_string);
180 announce.manufacturer = manufacturer.map(str::to_string);
181 announce
182 }
183}
184
185pub fn gige_device_id(mac: &[u8; 6]) -> String {
195 let hex: String = mac.iter().map(|b| format!("{b:02x}")).collect();
196 format!("cam-{hex}")
197}
198
199pub fn u3v_device_id(
216 vendor_id: u16,
217 product_id: u16,
218 serial: Option<&str>,
219 bus: &str,
220 address: u8,
221) -> String {
222 let instance = match serial.map(str::trim).filter(|s| !s.is_empty()) {
223 Some(serial) => serial.to_string(),
224 None => format!("{bus}-{address}"),
225 };
226 let mut escaped = String::with_capacity(instance.len());
227 for byte in instance.bytes() {
228 match byte {
229 b'A'..=b'Z' | b'a'..=b'z' | b'0'..=b'9' | b'-' | b'.' => escaped.push(char::from(byte)),
230 _ => escaped.push_str(&format!("_{byte:02x}")),
231 }
232 }
233 format!("cam-u3v-{vendor_id:04x}{product_id:04x}-{escaped}")
234}
235
236#[derive(Debug, Clone, Serialize, Deserialize)]
244#[non_exhaustive]
245pub struct DeviceStatus {
246 pub connected: bool,
248 pub error: Option<String>,
250}
251
252impl DeviceStatus {
253 pub fn connected() -> Self {
255 Self {
256 connected: true,
257 error: None,
258 }
259 }
260
261 pub fn disconnected(error: Option<String>) -> Self {
263 Self {
264 connected: false,
265 error,
266 }
267 }
268}
269
270#[derive(Debug, Clone, Serialize, Deserialize)]
272#[non_exhaustive]
273pub struct DeviceXmlResponse {
274 pub xml: String,
276}
277
278impl DeviceXmlResponse {
279 pub fn new(xml: impl Into<String>) -> Self {
281 Self { xml: xml.into() }
282 }
283}
284
285#[derive(Debug, Clone, Serialize, Deserialize)]
287#[non_exhaustive]
288pub struct DeviceReportRequest {
289 #[serde(default = "default_true")]
291 pub include_xml: bool,
292}
293
294impl DeviceReportRequest {
295 pub fn new(include_xml: bool) -> Self {
297 Self { include_xml }
298 }
299}
300
301#[derive(Debug, Clone, Serialize, Deserialize)]
305#[non_exhaustive]
306pub struct DeviceReportResponse {
307 pub report: String,
309}
310
311impl DeviceReportResponse {
312 pub fn new(report: impl Into<String>) -> Self {
314 Self {
315 report: report.into(),
316 }
317 }
318}
319
320#[derive(Debug, Clone, Serialize, Deserialize)]
333#[non_exhaustive]
334pub struct NodeValueUpdate {
335 pub value: serde_json::Value,
337 pub access_mode: String,
339 #[serde(skip_serializing_if = "Option::is_none")]
341 pub min: Option<f64>,
342 #[serde(skip_serializing_if = "Option::is_none")]
344 pub max: Option<f64>,
345 #[serde(skip_serializing_if = "Option::is_none")]
347 pub inc: Option<f64>,
348}
349
350impl NodeValueUpdate {
351 pub fn new(value: serde_json::Value, access_mode: impl Into<String>) -> Self {
353 Self {
354 value,
355 access_mode: access_mode.into(),
356 min: None,
357 max: None,
358 inc: None,
359 }
360 }
361}
362
363#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
373#[cfg_attr(feature = "ts", derive(ts_rs::TS))]
374#[cfg_attr(feature = "ts", ts(optional_fields))]
375#[non_exhaustive]
376pub struct NumericRange {
377 pub min: f64,
379 pub max: f64,
381 #[serde(default, skip_serializing_if = "Option::is_none")]
383 pub inc: Option<f64>,
384}
385
386impl NumericRange {
387 pub fn new(min: f64, max: f64, inc: Option<f64>) -> Self {
389 Self { min, max, inc }
390 }
391}
392
393#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
414#[cfg_attr(feature = "ts", derive(ts_rs::TS))]
415#[cfg_attr(feature = "ts", ts(optional_fields))]
416#[non_exhaustive]
417pub struct FeatureState {
418 pub value: serde_json::Value,
425 pub access_mode: String,
427 pub kind: String,
429 #[serde(default = "default_true")]
431 pub is_implemented: bool,
432 #[serde(default = "default_true")]
434 pub is_available: bool,
435 #[serde(default, skip_serializing_if = "Option::is_none")]
437 pub numeric: Option<NumericRange>,
438 #[serde(default, skip_serializing_if = "Option::is_none")]
440 pub enum_available: Option<Vec<String>>,
441 #[serde(default, skip_serializing_if = "Option::is_none")]
443 pub unit: Option<String>,
444 #[serde(default, skip_serializing_if = "Option::is_none")]
448 pub polling_ms: Option<u64>,
449 #[serde(default, skip_serializing_if = "Option::is_none")]
455 pub caching: Option<String>,
456}
457
458fn default_true() -> bool {
459 true
460}
461
462impl FeatureState {
463 pub fn new(
466 value: serde_json::Value,
467 access_mode: impl Into<String>,
468 kind: impl Into<String>,
469 ) -> Self {
470 Self {
471 value,
472 access_mode: access_mode.into(),
473 kind: kind.into(),
474 is_implemented: true,
475 is_available: true,
476 numeric: None,
477 enum_available: None,
478 unit: None,
479 polling_ms: None,
480 caching: None,
481 }
482 }
483
484 pub fn to_node_value_update(&self) -> NodeValueUpdate {
487 let (min, max, inc) = match &self.numeric {
488 Some(r) => (Some(r.min), Some(r.max), r.inc),
489 None => (None, None, None),
490 };
491 let mut update = NodeValueUpdate::new(self.value.clone(), self.access_mode.clone());
492 update.min = min;
493 update.max = max;
494 update.inc = inc;
495 update
496 }
497}
498
499impl From<&FeatureState> for NodeValueUpdate {
500 fn from(s: &FeatureState) -> Self {
501 s.to_node_value_update()
502 }
503}
504
505#[cfg(feature = "genapi")]
511#[cfg_attr(docsrs, doc(cfg(feature = "genapi")))]
512impl From<viva_genapi::FeatureState> for FeatureState {
513 fn from(state: viva_genapi::FeatureState) -> Self {
514 use viva_genapi::{AccessMode, FeatureValue};
515
516 let value = match state.value {
517 FeatureValue::None => serde_json::Value::Null,
518 FeatureValue::Integer(v) => serde_json::Value::Number(v.into()),
519 FeatureValue::Float(v) => f64_to_json(v),
520 FeatureValue::Boolean(v) => serde_json::Value::Bool(v),
521 FeatureValue::Enum(v) | FeatureValue::String(v) => serde_json::Value::String(v),
522 FeatureValue::Register { len } => {
523 serde_json::json!({ "kind": "register", "length": len })
524 }
525 _ => serde_json::json!({ "kind": state.kind, "unsupported": true }),
528 };
529 let access_mode = match state.access {
530 Some(AccessMode::RO) => "RO",
531 Some(AccessMode::RW) => "RW",
532 Some(AccessMode::WO) => "WO",
533 None => "NA",
534 };
535 FeatureState {
536 value,
537 access_mode: access_mode.to_string(),
538 kind: state.kind.to_string(),
539 is_implemented: state.is_implemented,
540 is_available: state.is_available,
541 numeric: state.range.map(|r| NumericRange {
542 min: r.min,
543 max: r.max,
544 inc: r.inc,
545 }),
546 enum_available: state.enum_entries,
547 unit: state.unit,
548 polling_ms: state
549 .polling_time
550 .map(|t| u64::try_from(t.as_millis()).unwrap_or(u64::MAX)),
551 caching: Some(caching_text(state.caching).to_string()),
552 }
553 }
554}
555
556#[cfg(feature = "genapi")]
558fn caching_text(mode: viva_genapi::CachingMode) -> &'static str {
559 match mode {
560 viva_genapi::CachingMode::NoCache => "NoCache",
561 viva_genapi::CachingMode::WriteThrough => "WriteThrough",
562 viva_genapi::CachingMode::WriteAround => "WriteAround",
563 }
564}
565
566#[cfg(feature = "genapi")]
569fn f64_to_json(v: f64) -> serde_json::Value {
570 serde_json::Number::from_f64(v)
571 .map(serde_json::Value::Number)
572 .unwrap_or_else(|| serde_json::Value::String(v.to_string()))
573}
574
575#[derive(Debug, Clone, Serialize, Deserialize)]
585#[cfg_attr(feature = "ts", derive(ts_rs::TS))]
586#[cfg_attr(feature = "ts", ts(optional_fields))]
587#[non_exhaustive]
588pub struct CommandResult {
589 pub ok: bool,
591 #[serde(default, skip_serializing_if = "Option::is_none")]
592 pub error: Option<String>,
594 #[serde(default, skip_serializing_if = "std::collections::HashMap::is_empty")]
597 #[cfg_attr(feature = "ts", ts(optional = nullable))]
600 pub affected_states: std::collections::HashMap<String, FeatureState>,
601}
602
603impl CommandResult {
604 pub fn ok() -> Self {
606 Self {
607 ok: true,
608 error: None,
609 affected_states: std::collections::HashMap::new(),
610 }
611 }
612
613 pub fn err(error: impl Into<String>) -> Self {
615 Self {
616 ok: false,
617 error: Some(error.into()),
618 affected_states: std::collections::HashMap::new(),
619 }
620 }
621}
622
623#[derive(Debug, Clone, Serialize, Deserialize)]
625#[non_exhaustive]
626pub struct NodeSetRequest {
627 pub value: serde_json::Value,
629}
630
631impl NodeSetRequest {
632 pub fn new(value: serde_json::Value) -> Self {
634 Self { value }
635 }
636}
637
638#[derive(Debug, Clone, Serialize, Deserialize)]
640#[non_exhaustive]
641pub struct NodeOpResponse {
642 pub ok: bool,
644 pub error: Option<String>,
646 #[serde(default, skip_serializing_if = "Vec::is_empty")]
653 pub invalidated: Vec<String>,
654}
655
656impl NodeOpResponse {
657 pub fn ok() -> Self {
659 Self {
660 ok: true,
661 error: None,
662 invalidated: Vec::new(),
663 }
664 }
665
666 pub fn err(error: impl Into<String>) -> Self {
668 Self {
669 ok: false,
670 error: Some(error.into()),
671 invalidated: Vec::new(),
672 }
673 }
674
675 pub fn with_invalidated(mut self, invalidated: Vec<String>) -> Self {
677 self.invalidated = invalidated;
678 self
679 }
680}
681
682#[derive(Debug, Clone, Serialize, Deserialize)]
688#[non_exhaustive]
689pub struct BulkReadRequest {
690 pub names: Vec<String>,
692}
693
694impl BulkReadRequest {
695 pub fn new(names: Vec<String>) -> Self {
697 Self { names }
698 }
699}
700
701#[derive(Debug, Clone, Serialize, Deserialize)]
706#[non_exhaustive]
707pub struct BulkReadResponse {
708 pub values: std::collections::HashMap<String, NodeValueUpdate>,
710}
711
712impl BulkReadResponse {
713 pub fn new(values: std::collections::HashMap<String, NodeValueUpdate>) -> Self {
715 Self { values }
716 }
717}
718
719#[derive(Debug, Clone, Serialize, Deserialize)]
723#[non_exhaustive]
724pub struct AcquisitionControlRequest {
725 pub command: AcquisitionCommand,
727 #[serde(default, skip_serializing_if = "Option::is_none")]
732 pub packet_size: Option<u32>,
733}
734
735impl AcquisitionControlRequest {
736 pub fn new(command: AcquisitionCommand) -> Self {
738 Self {
739 command,
740 packet_size: None,
741 }
742 }
743}
744
745#[derive(Debug, Clone, Serialize, Deserialize)]
746#[serde(rename_all = "lowercase")]
747pub enum AcquisitionCommand {
749 Start,
751 Stop,
753}
754
755#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
760#[cfg_attr(feature = "ts", derive(ts_rs::TS))]
761#[non_exhaustive]
762pub struct AcquisitionStatus {
763 pub active: bool,
765 pub fps: Option<f32>,
769 pub stats: Option<StreamCounters>,
773}
774
775impl AcquisitionStatus {
776 pub fn active(fps: Option<f32>, stats: Option<StreamCounters>) -> Self {
778 Self {
779 active: true,
780 fps,
781 stats,
782 }
783 }
784
785 pub fn inactive() -> Self {
787 Self {
788 active: false,
789 fps: None,
790 stats: None,
791 }
792 }
793
794 pub fn stopped(stats: StreamCounters) -> Self {
796 Self {
797 active: false,
798 fps: None,
799 stats: Some(stats),
800 }
801 }
802}
803
804#[derive(Debug, Clone, Copy, PartialEq, Default, Serialize, Deserialize)]
817#[cfg_attr(feature = "ts", derive(ts_rs::TS))]
818#[non_exhaustive]
819pub struct StreamCounters {
820 pub frames_complete: u64,
822 pub frames_incomplete: u64,
826 pub frames_missed: u64,
828 pub frames_backpressure: u64,
831 pub frames_unsupported: u64,
833 pub packets_received: u64,
835 pub packets_missing: u64,
838 pub packets_duplicate: u64,
840 pub packets_ignored: u64,
844 pub resend_requested: u64,
846 pub resend_recovered: u64,
848 pub resend_unavailable: u64,
850 pub transfer_errors: u64,
854 pub bytes: u64,
856 pub avg_mbps: f64,
858 pub avg_latency_ms: Option<f64>,
861 pub elapsed_ms: u64,
863}
864
865impl StreamCounters {
866 pub fn frames_lost(&self) -> u64 {
869 self.frames_incomplete + self.frames_missed + self.frames_backpressure
870 }
871}
872
873#[cfg(feature = "genicam")]
874#[cfg_attr(docsrs, doc(cfg(feature = "genicam")))]
875impl From<&viva_genicam::StreamStats> for StreamCounters {
876 fn from(stats: &viva_genicam::StreamStats) -> Self {
877 Self {
878 frames_complete: stats.frames_complete,
879 frames_incomplete: stats.frames_incomplete,
880 frames_missed: stats.frames_missed,
881 frames_backpressure: stats.frames_backpressure,
882 frames_unsupported: stats.frames_unsupported,
883 packets_received: stats.packets_received,
884 packets_missing: stats.packets_missing,
885 packets_duplicate: stats.packets_duplicate,
886 packets_ignored: stats.packets_ignored(),
887 resend_requested: stats.resend_requested,
888 resend_recovered: stats.resend_recovered,
889 resend_unavailable: stats.resend_unavailable,
890 transfer_errors: stats.transfer_errors,
891 bytes: stats.bytes,
892 avg_mbps: stats.avg_mbps,
893 avg_latency_ms: stats.avg_latency_ms,
894 elapsed_ms: u64::try_from(stats.elapsed.as_millis()).unwrap_or(u64::MAX),
895 }
896 }
897}
898
899mod pfnc_name {
906 use serde::{Deserialize, Deserializer, Serializer};
907 use viva_pfnc::PixelFormat;
908
909 pub(crate) fn serialize<S: Serializer>(
910 format: &PixelFormat,
911 serializer: S,
912 ) -> Result<S::Ok, S::Error> {
913 serializer.serialize_str(format.name().unwrap_or("Unknown"))
914 }
915
916 pub(crate) fn deserialize<'de, D: Deserializer<'de>>(
917 deserializer: D,
918 ) -> Result<PixelFormat, D::Error> {
919 let name = String::deserialize(deserializer)?;
920 Ok(PixelFormat::from_name(&name))
921 }
922}
923
924#[derive(Debug, Clone, Serialize, Deserialize)]
926#[cfg_attr(feature = "ts", derive(ts_rs::TS))]
927#[non_exhaustive]
928pub struct ImageMeta {
929 #[serde(with = "pfnc_name")]
932 #[cfg_attr(feature = "ts", ts(type = "string"))]
933 pub pixel_format: viva_pfnc::PixelFormat,
934 pub width: u32,
936 pub height: u32,
938 pub payload_size: u64,
941}
942
943impl ImageMeta {
944 pub fn new(
946 pixel_format: viva_pfnc::PixelFormat,
947 width: u32,
948 height: u32,
949 payload_size: u64,
950 ) -> Self {
951 Self {
952 pixel_format,
953 width,
954 height,
955 payload_size,
956 }
957 }
958}
959
960pub const ANNOUNCE_INTERVAL: std::time::Duration = std::time::Duration::from_secs(2);
969
970pub const ANNOUNCE_EXPIRY: std::time::Duration = std::time::Duration::from_secs(6);
973
974pub mod keys {
978 pub const ANNOUNCE_ALL: &str = "genicam/devices/*/announce";
980
981 pub fn announce(device_id: &str) -> String {
983 format!("genicam/devices/{device_id}/announce")
984 }
985
986 pub fn xml(device_id: &str) -> String {
988 format!("genicam/devices/{device_id}/xml")
989 }
990
991 pub fn report(device_id: &str) -> String {
994 format!("genicam/devices/{device_id}/report")
995 }
996
997 pub fn status(device_id: &str) -> String {
999 format!("genicam/devices/{device_id}/status")
1000 }
1001
1002 pub fn node_value(device_id: &str, node_name: &str) -> String {
1004 format!("genicam/devices/{device_id}/nodes/{node_name}/value")
1005 }
1006
1007 pub fn node_value_wildcard(device_id: &str) -> String {
1009 format!("genicam/devices/{device_id}/nodes/*/value")
1010 }
1011
1012 pub fn node_set(device_id: &str, node_name: &str) -> String {
1014 format!("genicam/devices/{device_id}/nodes/{node_name}/set")
1015 }
1016
1017 pub fn node_execute(device_id: &str, node_name: &str) -> String {
1019 format!("genicam/devices/{device_id}/nodes/{node_name}/execute")
1020 }
1021
1022 pub fn node_introspect(device_id: &str, node_name: &str) -> String {
1026 format!("genicam/devices/{device_id}/nodes/{node_name}/state")
1027 }
1028
1029 pub fn node_state_wildcard(device_id: &str) -> String {
1032 format!("genicam/devices/{device_id}/nodes/*/state")
1033 }
1034
1035 pub fn nodes_bulk_read(device_id: &str) -> String {
1038 format!("genicam/devices/{device_id}/nodes/bulk/read")
1039 }
1040
1041 pub fn nodes_bulk_state(device_id: &str) -> String {
1045 format!("genicam/devices/{device_id}/nodes/bulk/state")
1046 }
1047
1048 pub fn acquisition_control(device_id: &str) -> String {
1050 format!("genicam/devices/{device_id}/acquisition/control")
1051 }
1052
1053 pub fn acquisition_status(device_id: &str) -> String {
1055 format!("genicam/devices/{device_id}/acquisition/status")
1056 }
1057
1058 pub fn image(device_id: &str) -> String {
1060 format!("genicam/devices/{device_id}/image")
1061 }
1062
1063 pub fn image_meta(device_id: &str) -> String {
1065 format!("genicam/devices/{device_id}/image/meta")
1066 }
1067
1068 pub fn evs(device_id: &str) -> String {
1078 format!("genicam/devices/{device_id}/evs")
1079 }
1080
1081 pub fn node_register(device_id: &str, node_name: &str) -> String {
1085 format!("genicam/devices/{device_id}/nodes/{node_name}/register")
1086 }
1087
1088 pub fn node_register_set(device_id: &str, node_name: &str) -> String {
1093 format!("genicam/devices/{device_id}/nodes/{node_name}/register_set")
1094 }
1095
1096 pub fn configuration_save(device_id: &str) -> String {
1101 format!("genicam/devices/{device_id}/configuration/save")
1102 }
1103
1104 pub fn configuration_load(device_id: &str) -> String {
1110 format!("genicam/devices/{device_id}/configuration/load")
1111 }
1112
1113 pub fn events_control(device_id: &str) -> String {
1118 format!("genicam/devices/{device_id}/events/control")
1119 }
1120
1121 pub fn events(device_id: &str) -> String {
1126 format!("genicam/devices/{device_id}/events")
1127 }
1128
1129 pub fn events_status(device_id: &str) -> String {
1133 format!("genicam/devices/{device_id}/events/status")
1134 }
1135
1136 pub fn extract_node_name(key: &str) -> Option<&str> {
1140 let parts: Vec<&str> = key.split('/').collect();
1141 if parts.len() >= 6 && parts[parts.len() - 3] == "nodes" {
1142 Some(parts[parts.len() - 2])
1143 } else {
1144 None
1145 }
1146 }
1147}
1148
1149#[cfg(test)]
1150mod tests {
1151 use super::*;
1152
1153 #[test]
1159 fn a_u3v_device_id_is_keyed_by_serial() {
1160 assert_eq!(
1161 u3v_device_id(0x164c, 0x5533, Some("FF003089"), "1", 3),
1162 "cam-u3v-164c5533-FF003089"
1163 );
1164 assert_eq!(
1165 u3v_device_id(0x164c, 0x5533, Some("FF003089"), "20", 9),
1166 u3v_device_id(0x164c, 0x5533, Some("FF003089"), "1", 3),
1167 );
1168 assert_eq!(
1169 u3v_device_id(0x2676, 0xba02, None, "2", 7),
1170 "cam-u3v-2676ba02-2-7"
1171 );
1172 assert_eq!(
1173 u3v_device_id(0x2676, 0xba02, Some(" "), "2", 7),
1174 "cam-u3v-2676ba02-2-7"
1175 );
1176 assert_eq!(
1177 u3v_device_id(0x2676, 0xba02, Some("a/b*c$#?"), "2", 7),
1178 "cam-u3v-2676ba02-a_2fb_2ac_24_23_3f"
1179 );
1180 }
1181
1182 #[test]
1186 fn serials_that_differ_only_where_a_key_cannot_carry_them_stay_distinct() {
1187 let id = |serial| u3v_device_id(0x2676, 0xba02, Some(serial), "2", 7);
1188 assert_ne!(id("a/b"), id("a*b"));
1189 assert_ne!(id("a_b"), id("a/b"));
1190 assert_ne!(id("a_2fb"), id("a/b"));
1191 }
1192
1193 #[test]
1194 fn test_device_announce_deserializes_without_api_version() {
1195 let legacy = r#"{"id":"cam0","name":"Test Cam","model":"M1","serial":"S1"}"#;
1196 let a: DeviceAnnounce = serde_json::from_str(legacy).expect("should deserialize");
1197 assert!(
1198 a.api_version.is_none(),
1199 "api_version should be None for legacy JSON"
1200 );
1201 }
1202
1203 #[test]
1204 fn test_device_announce_deserializes_with_api_version() {
1205 let json = r#"{"id":"cam0","name":"Test","model":"M","serial":"S","api_version":1}"#;
1206 let a: DeviceAnnounce = serde_json::from_str(json).expect("should deserialize");
1207 assert_eq!(a.api_version, Some(1));
1208 }
1209
1210 #[test]
1211 fn device_announce_round_trips_every_identity_field() {
1212 let mut a = DeviceAnnounce::new("cam-deadbeefcafe", "Left", "FakeGigE", "FAKE-001");
1213 a.ip = Some("192.168.1.10".into());
1214 a.mac = Some("DE:AD:BE:EF:CA:FE".into());
1215 a.user_name = Some("Left".into());
1216 a.manufacturer = Some("viva-genicam".into());
1217 let json = serde_json::to_string(&a).expect("serialize");
1218 let back: DeviceAnnounce = serde_json::from_str(&json).expect("deserialize");
1219 assert_eq!(back, a);
1220 assert_eq!(back.api_version, Some(API_VERSION));
1221 }
1222
1223 #[test]
1224 fn device_announce_omits_unset_identity_fields() {
1225 let a = DeviceAnnounce::new("cam-u3v-00010002", "U3V", "U3V", "");
1226 let json = serde_json::to_string(&a).expect("serialize");
1227 for field in ["ip", "mac", "user_name", "manufacturer"] {
1228 assert!(!json.contains(&format!("\"{field}\"")), "{field} in {json}");
1229 }
1230 let back: DeviceAnnounce = serde_json::from_str(&json).expect("deserialize");
1231 assert_eq!(back, a);
1232 }
1233
1234 #[test]
1238 fn device_announce_deserializes_a_version_2_payload() {
1239 let v2 = r#"{"id":"cam-deadbeefcafe","name":"FakeGigE","model":"FakeGigE","serial":"cam-deadbeefcafe","api_version":2}"#;
1240 let a: DeviceAnnounce = serde_json::from_str(v2).expect("should deserialize");
1241 assert_eq!(a.api_version, Some(2));
1242 assert_eq!(a.serial, "cam-deadbeefcafe");
1243 assert_eq!(a.ip, None);
1244 assert_eq!(a.mac, None);
1245 assert_eq!(a.user_name, None);
1246 assert_eq!(a.manufacturer, None);
1247 }
1248
1249 #[test]
1250 fn for_gige_carries_the_device_identity() {
1251 let a = DeviceAnnounce::for_gige(
1252 &[0xDE, 0xAD, 0xBE, 0xEF, 0xCA, 0xFE],
1253 std::net::Ipv4Addr::new(192, 168, 1, 10),
1254 Some("FakeGigE"),
1255 Some("FAKE-001"),
1256 Some("Left"),
1257 Some("viva-genicam"),
1258 );
1259 assert_eq!(a.id, "cam-deadbeefcafe");
1260 assert_eq!(a.name, "Left");
1261 assert_eq!(a.model, "FakeGigE");
1262 assert_eq!(a.serial, "FAKE-001");
1263 assert_eq!(a.ip.as_deref(), Some("192.168.1.10"));
1264 assert_eq!(a.mac.as_deref(), Some("DE:AD:BE:EF:CA:FE"));
1265 assert_eq!(a.user_name.as_deref(), Some("Left"));
1266 assert_eq!(a.manufacturer.as_deref(), Some("viva-genicam"));
1267 assert_eq!(a.api_version, Some(API_VERSION));
1268 }
1269
1270 #[test]
1271 fn for_gige_names_by_user_name_then_model_then_address() {
1272 let mac = [0, 1, 2, 3, 4, 5];
1273 let ip = std::net::Ipv4Addr::new(10, 0, 0, 7);
1274 let name = |model, user_name| {
1275 DeviceAnnounce::for_gige(&mac, ip, model, None, user_name, None).name
1276 };
1277 assert_eq!(name(Some("M"), Some("U")), "U");
1278 assert_eq!(name(Some("M"), None), "M");
1279 assert_eq!(name(None, None), "10.0.0.7");
1280 }
1281
1282 #[test]
1285 fn for_gige_does_not_invent_a_serial() {
1286 let a = DeviceAnnounce::for_gige(
1287 &[0, 1, 2, 3, 4, 5],
1288 std::net::Ipv4Addr::new(10, 0, 0, 7),
1289 Some("M"),
1290 None,
1291 None,
1292 None,
1293 );
1294 assert_eq!(a.serial, "");
1295 assert_eq!(a.user_name, None);
1296 assert_eq!(a.manufacturer, None);
1297 }
1298
1299 #[test]
1300 fn gige_device_id_is_lowercase_mac_hex() {
1301 assert_eq!(
1302 gige_device_id(&[0xDE, 0xAD, 0xBE, 0xEF, 0xCA, 0xFE]),
1303 "cam-deadbeefcafe"
1304 );
1305 assert_eq!(
1306 gige_device_id(&[0x00, 0x0C, 0xDF, 0x06, 0x5B, 0x2F]),
1307 "cam-000cdf065b2f"
1308 );
1309 }
1310
1311 #[test]
1312 fn test_node_value_update_without_constraints() {
1313 let u = NodeValueUpdate {
1314 value: serde_json::json!(42),
1315 access_mode: "RW".to_string(),
1316 min: None,
1317 max: None,
1318 inc: None,
1319 };
1320 let s = serde_json::to_string(&u).expect("serialization failed");
1321 assert!(!s.contains("\"min\""), "min should be absent: {s}");
1322 assert!(!s.contains("\"max\""), "max should be absent: {s}");
1323 assert!(!s.contains("\"inc\""), "inc should be absent: {s}");
1324 assert!(s.contains("\"value\""));
1325 assert!(s.contains("\"access_mode\""));
1326 }
1327
1328 #[test]
1329 fn test_node_value_update_with_constraints() {
1330 let u = NodeValueUpdate {
1331 value: serde_json::json!(1024),
1332 access_mode: "RW".to_string(),
1333 min: Some(1.0),
1334 max: Some(4096.0),
1335 inc: Some(1.0),
1336 };
1337 let s = serde_json::to_string(&u).expect("serialization failed");
1338 let d: NodeValueUpdate = serde_json::from_str(&s).expect("deserialization failed");
1339 assert_eq!(d.min, Some(1.0));
1340 assert_eq!(d.max, Some(4096.0));
1341 assert_eq!(d.inc, Some(1.0));
1342 assert_eq!(d.access_mode, "RW");
1343 }
1344
1345 #[test]
1346 fn test_extract_node_name_value_key() {
1347 assert_eq!(
1348 keys::extract_node_name("genicam/devices/cam0/nodes/Width/value"),
1349 Some("Width")
1350 );
1351 }
1352
1353 #[test]
1354 fn test_extract_node_name_set_key() {
1355 assert_eq!(
1356 keys::extract_node_name("genicam/devices/cam0/nodes/Width/set"),
1357 Some("Width")
1358 );
1359 }
1360
1361 #[test]
1362 fn test_extract_node_name_execute_key() {
1363 assert_eq!(
1364 keys::extract_node_name("genicam/devices/cam0/nodes/AcquisitionStart/execute"),
1365 Some("AcquisitionStart")
1366 );
1367 }
1368
1369 #[test]
1370 fn test_extract_node_name_register_keys() {
1371 for key in [
1372 keys::node_register("cam0", "DeviceUserBuffer"),
1373 keys::node_register_set("cam0", "DeviceUserBuffer"),
1374 ] {
1375 assert_eq!(
1376 keys::extract_node_name(&key),
1377 Some("DeviceUserBuffer"),
1378 "{key}"
1379 );
1380 }
1381 }
1382
1383 #[test]
1384 fn test_extract_node_name_too_short() {
1385 assert_eq!(keys::extract_node_name("genicam/devices/cam0"), None);
1386 }
1387
1388 #[test]
1389 fn test_extract_node_name_non_node_key() {
1390 assert_eq!(
1391 keys::extract_node_name("genicam/devices/cam0/acquisition/control/something"),
1392 None
1393 );
1394 }
1395
1396 #[test]
1397 fn test_node_value_update_deserializes_legacy() {
1398 let legacy = r#"{"value": 1024, "access_mode": "RW"}"#;
1399 let d: NodeValueUpdate = serde_json::from_str(legacy).expect("deserialization failed");
1400 assert!(d.min.is_none());
1401 assert!(d.max.is_none());
1402 assert!(d.inc.is_none());
1403 assert_eq!(d.access_mode, "RW");
1404 }
1405
1406 #[cfg(feature = "genapi")]
1412 #[test]
1413 fn a_genapi_state_carries_its_polling_time_and_caching_mode() {
1414 let xml = r#"<RegisterDescription SchemaMajorVersion="1" SchemaMinorVersion="1" SchemaSubMinorVersion="0">
1415 <Float Name="DeviceTemperature"><pValue>DeviceTemperatureReg</pValue></Float>
1416 <FloatReg Name="DeviceTemperatureReg"><Address>0x0</Address><Length>4</Length><AccessMode>RO</AccessMode><Cachable>NoCache</Cachable><PollingTime>500</PollingTime></FloatReg>
1417 <Integer Name="Width"><Address>0x4</Address><Length>4</Length><AccessMode>RW</AccessMode></Integer>
1418 </RegisterDescription>"#;
1419 let model = viva_genapi_xml::parse(xml).expect("parse");
1420 let map = viva_genapi::NodeMap::try_from_xml(model).expect("build");
1421 let io = viva_genapi::NullIo;
1422 let wire = FeatureState::from(map.feature_state("DeviceTemperature", &io).unwrap());
1423 assert_eq!(wire.polling_ms, Some(500));
1424 assert_eq!(wire.caching.as_deref(), Some("NoCache"));
1425 let json = serde_json::to_string(&wire).unwrap();
1426 assert!(json.contains(r#""polling_ms":500"#), "{json}");
1427 let wire = FeatureState::from(map.feature_state("Width", &io).unwrap());
1428 assert_eq!(wire.polling_ms, None);
1429 assert_eq!(wire.caching.as_deref(), Some("WriteThrough"));
1430 }
1431
1432 #[test]
1437 fn an_acquisition_status_round_trips_its_counters() {
1438 let stats = StreamCounters {
1439 frames_complete: 2_410,
1440 frames_incomplete: 2,
1441 frames_missed: 1,
1442 packets_received: 1_000_000,
1443 transfer_errors: 3,
1444 avg_mbps: 812.5,
1445 avg_latency_ms: Some(1.25),
1446 elapsed_ms: 10_000,
1447 ..Default::default()
1448 };
1449
1450 for status in [
1451 AcquisitionStatus::active(Some(241.0), Some(stats)),
1452 AcquisitionStatus::stopped(stats),
1453 ] {
1454 let json = serde_json::to_string(&status).unwrap();
1455 let back: AcquisitionStatus = serde_json::from_str(&json).unwrap();
1456 assert_eq!(back, status, "{json}");
1457 }
1458 assert_eq!(stats.frames_lost(), 3);
1459 let stopped = AcquisitionStatus::stopped(stats);
1460 assert!(!stopped.active);
1461 assert_eq!(stopped.fps, None);
1462
1463 let json = serde_json::to_value(AcquisitionStatus::inactive()).unwrap();
1465 assert_eq!(
1466 json,
1467 serde_json::json!({ "active": false, "fps": null, "stats": null })
1468 );
1469 }
1470
1471 #[cfg(feature = "genicam")]
1474 #[test]
1475 fn stream_counters_carry_the_librarys_stream_stats() {
1476 let mut stats = viva_genicam::StreamStats::default();
1477 stats.frames_complete = 10;
1478 stats.frames_incomplete = 1;
1479 stats.frames_missed = 2;
1480 stats.frames_backpressure = 3;
1481 stats.frames_unsupported = 4;
1482 stats.packets_received = 500;
1483 stats.packets_missing = 5;
1484 stats.packets_duplicate = 6;
1485 stats.packets_ignored_malformed = 1;
1486 stats.packets_ignored_unsupported = 2;
1487 stats.packets_ignored_out_of_range = 3;
1488 stats.packets_ignored_late = 4;
1489 stats.packets_ignored_error_status = 5;
1490 stats.packets_ignored_foreign = 6;
1491 stats.resend_requested = 7;
1492 stats.resend_recovered = 8;
1493 stats.resend_unavailable = 9;
1494 stats.transfer_errors = 11;
1495 stats.bytes = 12_345;
1496 stats.avg_mbps = 98.5;
1497 stats.avg_latency_ms = Some(0.5);
1498 stats.elapsed = std::time::Duration::from_micros(2_500_900);
1499
1500 let wire = StreamCounters::from(&stats);
1501 assert_eq!(wire.packets_ignored, 21);
1502 assert_eq!(wire.packets_ignored, stats.packets_ignored());
1503 assert_eq!(wire.elapsed_ms, 2_500);
1504 assert_eq!(wire.frames_lost(), stats.frames_lost());
1505 assert_eq!(
1506 (
1507 wire.frames_complete,
1508 wire.frames_incomplete,
1509 wire.frames_missed,
1510 wire.frames_backpressure,
1511 wire.frames_unsupported,
1512 ),
1513 (10, 1, 2, 3, 4)
1514 );
1515 assert_eq!(
1516 (
1517 wire.packets_received,
1518 wire.packets_missing,
1519 wire.packets_duplicate,
1520 ),
1521 (500, 5, 6)
1522 );
1523 assert_eq!(
1524 (
1525 wire.resend_requested,
1526 wire.resend_recovered,
1527 wire.resend_unavailable,
1528 wire.transfer_errors,
1529 ),
1530 (7, 8, 9, 11)
1531 );
1532 assert_eq!(wire.bytes, 12_345);
1533 assert_eq!(wire.avg_mbps, 98.5);
1534 assert_eq!(wire.avg_latency_ms, Some(0.5));
1535 }
1536
1537 #[test]
1538 fn test_feature_state_minimal_roundtrip() {
1539 let s = FeatureState {
1540 value: serde_json::json!(1920),
1541 access_mode: "RW".to_string(),
1542 kind: "Integer".to_string(),
1543 is_implemented: true,
1544 is_available: true,
1545 numeric: None,
1546 enum_available: None,
1547 unit: None,
1548 polling_ms: None,
1549 caching: None,
1550 };
1551 let j = serde_json::to_string(&s).expect("serialize");
1552 assert!(!j.contains("\"numeric\""), "numeric should be absent: {j}");
1554 assert!(
1555 !j.contains("\"enum_available\""),
1556 "enum_available absent: {j}"
1557 );
1558 assert!(!j.contains("\"unit\""), "unit absent: {j}");
1559 let d: FeatureState = serde_json::from_str(&j).expect("deserialize");
1560 assert_eq!(d, s);
1561 }
1562
1563 #[test]
1564 fn test_feature_state_defaults_when_fields_missing() {
1565 let legacy = r#"{"value":1920,"access_mode":"RW","kind":"Integer"}"#;
1568 let d: FeatureState = serde_json::from_str(legacy).expect("deserialize");
1569 assert!(d.is_implemented, "is_implemented defaults to true");
1570 assert!(d.is_available, "is_available defaults to true");
1571 }
1572
1573 #[test]
1574 fn test_feature_state_integer_with_range() {
1575 let s = FeatureState {
1576 value: serde_json::json!(512),
1577 access_mode: "RW".to_string(),
1578 kind: "Integer".to_string(),
1579 is_implemented: true,
1580 is_available: true,
1581 numeric: Some(NumericRange {
1582 min: 16.0,
1583 max: 4096.0,
1584 inc: Some(8.0),
1585 }),
1586 enum_available: None,
1587 unit: Some("px".to_string()),
1588 polling_ms: None,
1589 caching: None,
1590 };
1591 let j = serde_json::to_string(&s).expect("serialize");
1592 let d: FeatureState = serde_json::from_str(&j).expect("deserialize");
1593 assert_eq!(d, s);
1594 }
1595
1596 #[test]
1597 fn test_feature_state_to_node_value_update() {
1598 let s = FeatureState {
1599 value: serde_json::json!(512),
1600 access_mode: "RW".to_string(),
1601 kind: "Integer".to_string(),
1602 is_implemented: true,
1603 is_available: true,
1604 numeric: Some(NumericRange {
1605 min: 16.0,
1606 max: 4096.0,
1607 inc: Some(8.0),
1608 }),
1609 enum_available: None,
1610 unit: None,
1611 polling_ms: None,
1612 caching: None,
1613 };
1614 let u: NodeValueUpdate = (&s).into();
1615 assert_eq!(u.value, serde_json::json!(512));
1616 assert_eq!(u.access_mode, "RW");
1617 assert_eq!(u.min, Some(16.0));
1618 assert_eq!(u.max, Some(4096.0));
1619 assert_eq!(u.inc, Some(8.0));
1620 }
1621
1622 #[test]
1623 fn test_feature_state_enumeration() {
1624 let s = FeatureState {
1625 value: serde_json::json!("Once"),
1626 access_mode: "RW".to_string(),
1627 kind: "Enumeration".to_string(),
1628 is_implemented: true,
1629 is_available: true,
1630 numeric: None,
1631 enum_available: Some(vec!["Off".to_string(), "Once".to_string()]),
1632 unit: None,
1633 polling_ms: None,
1634 caching: None,
1635 };
1636 let j = serde_json::to_string(&s).expect("serialize");
1637 assert!(j.contains("\"enum_available\""));
1638 let d: FeatureState = serde_json::from_str(&j).expect("deserialize");
1639 assert_eq!(
1640 d.enum_available.as_deref(),
1641 Some(&["Off".to_string(), "Once".to_string()][..])
1642 );
1643 }
1644
1645 #[test]
1646 fn test_command_result_ok_empty() {
1647 let r = CommandResult {
1648 ok: true,
1649 error: None,
1650 affected_states: std::collections::HashMap::new(),
1651 };
1652 let j = serde_json::to_string(&r).expect("serialize");
1653 assert!(
1654 !j.contains("\"affected_states\""),
1655 "empty affected_states should be skipped: {j}"
1656 );
1657 assert!(
1658 !j.contains("\"error\""),
1659 "none error should be skipped: {j}"
1660 );
1661 }
1662
1663 #[test]
1664 fn test_command_result_with_affected_states() {
1665 let mut affected = std::collections::HashMap::new();
1666 affected.insert(
1667 "AcquisitionStatus".to_string(),
1668 FeatureState {
1669 value: serde_json::json!(true),
1670 access_mode: "RO".to_string(),
1671 kind: "Boolean".to_string(),
1672 is_implemented: true,
1673 is_available: true,
1674 numeric: None,
1675 enum_available: None,
1676 unit: None,
1677 polling_ms: None,
1678 caching: None,
1679 },
1680 );
1681 let r = CommandResult {
1682 ok: true,
1683 error: None,
1684 affected_states: affected,
1685 };
1686 let j = serde_json::to_string(&r).expect("serialize");
1687 let d: CommandResult = serde_json::from_str(&j).expect("deserialize");
1688 assert!(d.ok);
1689 assert_eq!(d.affected_states.len(), 1);
1690 assert!(d.affected_states.contains_key("AcquisitionStatus"));
1691 }
1692
1693 #[test]
1697 fn image_meta_names_the_format_as_pfnc_does() {
1698 for (format, name) in [
1699 (viva_pfnc::PixelFormat::Mono8, "Mono8"),
1700 (viva_pfnc::PixelFormat::RGB8Packed, "RGB8Packed"),
1701 (viva_pfnc::PixelFormat::Coord3DC16, "Coord3D_C16"),
1702 (viva_pfnc::PixelFormat::Coord3DABC32f, "Coord3D_ABC32f"),
1703 (viva_pfnc::PixelFormat::from_code(0x0123_4567), "Unknown"),
1704 ] {
1705 let meta = ImageMeta::new(format, 4, 2, 8);
1706 let json = serde_json::to_value(&meta).expect("serialize");
1707 assert_eq!(json["pixel_format"], name, "{format}");
1708 }
1709 }
1710
1711 #[test]
1713 fn image_meta_reads_the_pfnc_name_and_its_older_spellings() {
1714 for (name, format) in [
1715 ("Mono12Packed", viva_pfnc::PixelFormat::Mono12Packed),
1716 ("RGB8", viva_pfnc::PixelFormat::RGB8Packed),
1717 ("YUV422Packed", viva_pfnc::PixelFormat::YUV422_8_UYVY),
1718 ("Fancy42", viva_pfnc::PixelFormat::Unknown(0)),
1719 ] {
1720 let json =
1721 format!(r#"{{"pixel_format":"{name}","width":1,"height":1,"payload_size":1}}"#);
1722 let meta: ImageMeta = serde_json::from_str(&json).expect("deserialize");
1723 assert_eq!(meta.pixel_format, format, "{name}");
1724 }
1725 }
1726}