Skip to main content

viva_fake_gige/
lib.rs

1//! In-process fake GigE Vision camera for testing and demos.
2//!
3//! This crate provides a simulated GigE Vision camera that speaks real GVCP/GVSP
4//! protocols over UDP on localhost. It is intended for integration testing and
5//! demonstrations without requiring physical camera hardware or external tools
6//! like aravis.
7//!
8//! # Example
9//!
10//! ```rust,no_run
11//! use viva_fake_gige::FakeCamera;
12//!
13//! # async fn example() {
14//! let camera = FakeCamera::builder()
15//!     .width(640)
16//!     .height(480)
17//!     .fps(30)
18//!     .bind_ip([127, 0, 0, 1].into())
19//!     .build()
20//!     .await
21//!     .expect("failed to start fake camera");
22//!
23//! // Camera is now discoverable on the configured port.
24//! // Use viva_genicam::gige::discover() to find it.
25//!
26//! // When done:
27//! camera.stop().await;
28//! # }
29//! ```
30
31mod gvcp_server;
32
33pub use gvcp_server::{
34    CommandCounters, DiscoveryRequest, FAKE_DEVICE_KEY, FAKE_GROUP_KEY, FAKE_GROUP_MASK, FAKE_MAC,
35    FAKE_MANUFACTURER, FAKE_MODEL, FAKE_SERIAL, FAKE_SUBNET_MASK, FAKE_USER_NAME, FAKE_VERSION,
36    GvcpCommand, RegisterCommandRefusal,
37};
38mod events;
39mod gvsp;
40mod gvsp_sender;
41mod registers;
42mod resend;
43
44// The modules are private; what tests and demos use is re-exported here
45// (ADR-0030). GigE Vision's own register addresses are `viva_gige::consts`;
46// the ones below are this fake camera's feature registers.
47pub use gvsp::{
48    BlockSpec, Datagram, PAYLOAD_TYPE_EXTENDED_CHUNK_DATA, PAYLOAD_TYPE_IMAGE_EXTENDED_CHUNK,
49    PacketKind, block_datagrams, chunk_payload, image_size, interleave,
50};
51pub use registers::{
52    CHUNK_ID_EXPOSURE_TIME, CHUNK_ID_FRAME_ID, CHUNK_ID_IMAGE, CHUNK_ID_IMAGE_INFO,
53    CHUNK_ID_TIMESTAMP, CHUNK_SELECTOR_FRAME_ID, DEFAULT_EXPOSURE_US, EVENT_EXPOSURE_END, FAKE_XML,
54    REG_ACQ_FRAME_RATE, REG_ACQ_FRAME_RATE_ENABLE, REG_ACQ_MODE, REG_ACQ_START, REG_ACQ_STOP,
55    REG_BINNING_HORIZONTAL, REG_BINNING_VERTICAL, REG_BLACK_LEVEL, REG_CHUNK_ENABLE,
56    REG_CHUNK_MODE_ACTIVE, REG_CHUNK_SELECTOR, REG_DEVICE_MODEL_NAME, REG_DEVICE_TEMPERATURE,
57    REG_DEVICE_USER_BUFFER, REG_DEVICE_USER_ID, REG_EXPOSURE_AUTO, REG_EXPOSURE_TIME, REG_GAIN,
58    REG_GAIN_AUTO, REG_GAIN_RAW, REG_HEIGHT, REG_OFFSET_X, REG_OFFSET_Y, REG_PIXEL_FORMAT,
59    REG_SENSOR_TYPE, REG_SOFTWARE_SIGNAL_PULSE, REG_TIMESTAMP_VALUE, REG_TRIGGER_MODE,
60    REG_TRIGGER_SELECTOR, REG_TRIGGER_SOURCE, REG_USER_SET_DEFAULT, REG_USER_SET_SAVE,
61    REG_USER_SET_SELECTOR, REG_WIDTH, TRIGGER_SOURCE_LINE1, TRIGGER_SOURCE_SOFTWARE,
62    WRITE_ONLY_REGISTERS,
63};
64
65use std::collections::HashMap;
66use std::net::{Ipv4Addr, SocketAddr};
67use std::sync::Arc;
68use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
69use std::time::Duration;
70
71pub use events::MessageChannelStats;
72pub use gvsp::{PacketScript, ScriptStep};
73pub use registers::{DEFAULT_MESSAGE_RETRY_COUNT, DEFAULT_MESSAGE_TIMEOUT_MS, XmlProfile};
74pub use resend::ResendStats;
75
76use socket2::{Domain, Protocol, Socket, Type};
77use tokio::net::UdpSocket;
78use tokio::sync::{Mutex, Notify};
79use tokio::task::JoinHandle;
80use tracing::info;
81use viva_pfnc::PixelFormat;
82
83/// Builder for configuring and starting a fake GigE Vision camera.
84pub struct FakeCameraBuilder {
85    width: u32,
86    height: u32,
87    fps: u32,
88    bind_ip: Ipv4Addr,
89    port: u16,
90    pixel_format: u32,
91    zip_xml: bool,
92    zip_xml_extra: Vec<u8>,
93    enforce_heartbeat: bool,
94    heartbeat_timeout_ms: Option<u32>,
95    max_packet_size: Option<u32>,
96    max_on_wire: Option<u32>,
97    refuse_register_commands: Option<RegisterCommandRefusal>,
98    identity: gvcp_server::Identity,
99    sender: gvsp_sender::SenderOptions,
100    packet_resend: bool,
101    resend_retention: usize,
102    tick_frequency: Option<u64>,
103    pending_ack: bool,
104    names_primary_application: bool,
105    action_commands: bool,
106    delayed_acks: HashMap<u64, Duration>,
107    profile: registers::XmlProfile,
108}
109
110/// PFNC `Mono8`, the fake's default pixel format. PFNC codes are
111/// vocabulary, from `viva-pfnc` (ADR-0030).
112pub const MONO8: u32 = PixelFormat::Mono8.code();
113/// PFNC `Mono16`. Sent as a byte ramp — byte `i` of block `b` is
114/// `(i × 7 + b) mod 256` — which a test can recompute exactly.
115pub const MONO16: u32 = PixelFormat::Mono16.code();
116/// PFNC `RGB8` (`RGB8Packed`).
117pub const RGB8: u32 = PixelFormat::RGB8Packed.code();
118/// GigE Vision `Mono12Packed`: two 12-bit pixels in three bytes.
119pub const MONO12_PACKED: u32 = PixelFormat::Mono12Packed.code();
120/// PFNC `Mono12p`: 12-bit pixels packed LSB-first.
121pub const MONO12P: u32 = PixelFormat::Mono12p.code();
122
123impl Default for FakeCameraBuilder {
124    fn default() -> Self {
125        Self {
126            width: 640,
127            height: 480,
128            fps: 30,
129            bind_ip: Ipv4Addr::LOCALHOST,
130            port: 3956,
131            pixel_format: MONO8,
132            zip_xml: false,
133            zip_xml_extra: Vec::new(),
134            enforce_heartbeat: false,
135            heartbeat_timeout_ms: None,
136            max_packet_size: None,
137            max_on_wire: None,
138            refuse_register_commands: None,
139            identity: gvcp_server::Identity::default(),
140            sender: gvsp_sender::SenderOptions::default(),
141            packet_resend: true,
142            resend_retention: resend::DEFAULT_RETENTION,
143            tick_frequency: None,
144            pending_ack: true,
145            names_primary_application: true,
146            action_commands: true,
147            delayed_acks: HashMap::new(),
148            profile: registers::XmlProfile::default(),
149        }
150    }
151}
152
153impl FakeCameraBuilder {
154    /// Set the image width in pixels.
155    pub fn width(mut self, width: u32) -> Self {
156        self.width = width;
157        self
158    }
159
160    /// Set the image height in pixels.
161    pub fn height(mut self, height: u32) -> Self {
162        self.height = height;
163        self
164    }
165
166    /// Set the target frame rate.
167    pub fn fps(mut self, fps: u32) -> Self {
168        self.fps = fps;
169        self
170    }
171
172    /// Set the IPv4 address to bind the GVCP socket to.
173    pub fn bind_ip(mut self, ip: Ipv4Addr) -> Self {
174        self.bind_ip = ip;
175        self
176    }
177
178    /// Set the GVCP control port (default: 3956).
179    pub fn port(mut self, port: u16) -> Self {
180        self.port = port;
181        self
182    }
183
184    /// Set the initial pixel format (PFNC code). Default: Mono8.
185    ///
186    /// Use [`MONO8`] or [`RGB8`] constants.
187    pub fn pixel_format(mut self, code: u32) -> Self {
188        self.pixel_format = code;
189        self
190    }
191
192    /// Serve the GenApi XML as a ZIP archive (default: plain XML).
193    ///
194    /// Many real cameras (Basler, FLIR, Hikrobot, ...) publish their
195    /// register-description XML zipped; enable this to exercise that path.
196    pub fn zip_xml(mut self, enable: bool) -> Self {
197        self.zip_xml = enable;
198        self
199    }
200
201    /// Serve the GenApi XML as a ZIP archive whose headers carry `extra` as
202    /// their extra field (default: none). Implies [`Self::zip_xml`].
203    ///
204    /// The bytes are written as given, valid ZIP extra records or not: a
205    /// Basler acA2440-20gc serves 20 bytes starting with `GCV0` that are not
206    /// (issue #236).
207    pub fn zip_xml_extra(mut self, extra: &[u8]) -> Self {
208        self.zip_xml = true;
209        self.zip_xml_extra = extra.to_vec();
210        self
211    }
212
213    /// Release control privilege when the controller stops sending GVCP commands
214    /// for longer than `GevHeartbeatTimeout` (default: off).
215    ///
216    /// Every real device behaves this way; it is off by default because it
217    /// makes every test that holds control sensitive to a 3 s stall, a flake
218    /// on a loaded CI runner. Tests that are about the keepalive turn it on.
219    pub fn enforce_heartbeat(mut self, enable: bool) -> Self {
220        self.enforce_heartbeat = enable;
221        self
222    }
223
224    /// Clamp `GevSCPSPacketSize` to `max`, the way a real camera caps it.
225    ///
226    /// A request above `max` is acknowledged and silently reduced, so the
227    /// register reads back lower than what was written. Off by default: the
228    /// fake accepts any size, which is what every existing test expects.
229    ///
230    /// The fake accepted anything until 0.4.1, so it could not express the
231    /// camera behind
232    /// [#112](https://github.com/VitalyVorobyev/viva-genicam/issues/112) and no
233    /// test could have caught that defect — the ADR-0019 failure mode of a fake
234    /// that only ever agrees with its client.
235    pub fn max_packet_size(mut self, max: u32) -> Self {
236        self.max_packet_size = Some(max);
237        self
238    }
239
240    /// Silently drop any GVSP datagram larger than `max`, as a network path
241    /// with a smaller frame ceiling than either endpoint believes does.
242    ///
243    /// Different from [`FakeCameraBuilder::max_packet_size`], and the
244    /// difference is the whole of
245    /// [#112](https://github.com/VitalyVorobyev/viva-genicam/issues/112): that
246    /// camera accepts and *stores* 16114, then streams nothing, because the
247    /// link tops out at a 9216-byte frame. No register read can find that —
248    /// only a test packet can.
249    pub fn max_on_wire(mut self, max: u32) -> Self {
250        self.max_on_wire = Some(max);
251        self
252    }
253
254    /// Refuse every READREG and WRITEREG, as a device that implements only the
255    /// memory commands would (default: serve them).
256    ///
257    /// The only way to exercise a controller's fallback from register to
258    /// memory access without hardware that lacks the register commands. The
259    /// refused command changes nothing on the device, so a test can tell a
260    /// write that fell back from one that was silently lost.
261    pub fn refuse_register_commands(mut self, refusal: RegisterCommandRefusal) -> Self {
262        self.refuse_register_commands = Some(refusal);
263        self
264    }
265
266    /// Send 20-byte extended-ID GVSP headers with 64-bit block ids and 32-bit
267    /// packet ids (GigE Vision 2.0), as a LUCID TRT009S-E does (default: off).
268    ///
269    /// The stride shrinks by the 12 extra header bytes, so a receiver that
270    /// assumes the 8-byte header places every packet after the first 12 bytes
271    /// too far.
272    pub fn extended_ids(mut self, enable: bool) -> Self {
273        self.sender.extended_ids = enable;
274        self
275    }
276
277    /// Send chunk-mode blocks with `payload_type` instead of `0x4001`: an
278    /// Allied Vision Manta G-125B sends GigE Vision 1.x's extended chunk data,
279    /// [`PAYLOAD_TYPE_EXTENDED_CHUNK_DATA`] (`0x0005`), in the layout that
280    /// constant describes.
281    pub fn chunk_payload_type(mut self, payload_type: u16) -> Self {
282        self.sender.chunk_payload_type = Some(payload_type);
283        self
284    }
285
286    /// Put `payload_type` in every leader and trailer instead of `0x0001`
287    /// (`0x4001` while chunk mode is active).
288    pub fn payload_type(mut self, payload_type: u16) -> Self {
289        self.sender.payload_type = Some(payload_type);
290        self
291    }
292
293    /// Send only the first `lines` lines of every image, with `lines` in the
294    /// trailer's Size Y, as a variable-height line-scan camera ends a frame
295    /// early; the leader keeps `Height`. Ignored in chunk mode.
296    pub fn delivered_lines(mut self, lines: u32) -> Self {
297        self.sender.delivered_lines = Some(lines);
298        self
299    }
300
301    /// Damage the stream deterministically: drop, repeat or reorder packets
302    /// by block and packet id. Block ids count from 1 at each acquisition
303    /// start.
304    pub fn packet_script(mut self, script: PacketScript) -> Self {
305        self.sender.script = script;
306        self
307    }
308
309    /// Answer `PACKETRESEND_CMD`, and say so in the GVCP Capability register
310    /// (`0x0934`, mask `0x4`) (default: on).
311    ///
312    /// Off, the capability bit is clear and requests are counted in
313    /// [`FakeCamera::resends`] but never answered, as on a device without
314    /// resend.
315    pub fn packet_resend(mut self, enable: bool) -> Self {
316        self.packet_resend = enable;
317        self
318    }
319
320    /// Keep the packets of the last `frames` blocks for resending (default
321    /// 4). A request for an older block is answered with a header-only GVSP
322    /// packet carrying `PACKET_UNAVAILABLE` (`0x800C`).
323    pub fn resend_retention(mut self, frames: usize) -> Self {
324        self.resend_retention = frames;
325        self
326    }
327
328    /// Report `hz` as the timestamp tick frequency (bootstrap `0x093C` and
329    /// `0x0940`; default 1 GHz), the unit `GevSCPD` counts in. `0` is what a
330    /// device without a timestamp clock reports.
331    pub fn tick_frequency(mut self, hz: u64) -> Self {
332        self.tick_frequency = Some(hz);
333        self
334    }
335
336    /// Also send every block from a second socket bound to `addr`, ahead of
337    /// the genuine one and with its image bytes inverted: valid GVSP from an
338    /// address that is not the camera's, which a receiver must ignore.
339    /// `addr` must be one of this host's addresses other than the camera's.
340    pub fn spoof_source(mut self, addr: Ipv4Addr) -> Self {
341        self.sender.spoof_source = Some(addr);
342        self
343    }
344
345    /// Report a different `GevHeartbeatTimeout` than the 3 000 ms default.
346    ///
347    /// A shorter window keeps a test that has to wait one out from dominating
348    /// the suite's runtime.
349    pub fn heartbeat_timeout_ms(mut self, timeout_ms: u32) -> Self {
350        self.heartbeat_timeout_ms = Some(timeout_ms);
351        self
352    }
353
354    /// Report `mac` instead of [`FAKE_MAC`], in the Discovery ACK and the
355    /// bootstrap MAC registers alike.
356    ///
357    /// Services key a GigE camera by its MAC, so two fakes that should appear
358    /// as two cameras need two MACs, not only two serials.
359    pub fn mac(mut self, mac: [u8; 6]) -> Self {
360        self.identity.mac = mac;
361        self
362    }
363
364    /// Report `model` instead of [`FAKE_MODEL`] in the Discovery ACK.
365    ///
366    /// The field is 32 bytes on the wire; a longer name is truncated.
367    pub fn model(mut self, model: impl Into<String>) -> Self {
368        self.identity.model = model.into();
369        self
370    }
371
372    /// Report `serial` instead of [`FAKE_SERIAL`] in the Discovery ACK.
373    ///
374    /// The field is 16 bytes on the wire; a longer serial is truncated.
375    pub fn serial(mut self, serial: impl Into<String>) -> Self {
376        self.identity.serial = serial.into();
377        self
378    }
379
380    /// Report `user_name` instead of [`FAKE_USER_NAME`] in the Discovery ACK.
381    /// An empty string reports no user-defined name, as an unnamed camera does.
382    ///
383    /// The field is 16 bytes on the wire; a longer name is truncated.
384    pub fn user_name(mut self, user_name: impl Into<String>) -> Self {
385        self.identity.user_name = user_name.into();
386        self
387    }
388
389    /// Report `ip` as the camera's current IP address in the Discovery ACK
390    /// and bootstrap `0x0024`, instead of the address it is bound to.
391    ///
392    /// A camera configured for another network still answers a broadcast
393    /// discovery, with an address the host cannot reach; this is that camera.
394    pub fn current_ip(mut self, ip: Ipv4Addr) -> Self {
395        self.identity.ip = Some(ip);
396        self
397    }
398
399    /// Report `mask` as the current subnet mask (default
400    /// [`FAKE_SUBNET_MASK`], loopback's `/8`).
401    pub fn subnet_mask(mut self, mask: Ipv4Addr) -> Self {
402        self.identity.subnet_mask = mask;
403        self
404    }
405
406    /// Report `gateway` as the current default gateway (default `0.0.0.0`).
407    pub fn gateway(mut self, gateway: Ipv4Addr) -> Self {
408        self.identity.gateway = gateway;
409        self
410    }
411
412    /// Say in GVCP Capability (`0x0934`, mask `0x20`) that this device can
413    /// answer a slow command with `PENDING_ACK` (default: on).
414    ///
415    /// It sends one only once the controller sets the enable bit (`0x2`) of
416    /// GVCP Configuration (`0x0954`), as the specification has it.
417    pub fn pending_ack(mut self, supported: bool) -> Self {
418        self.pending_ack = supported;
419        self
420    }
421
422    /// Say in GVCP Capability (`0x0934`, mask `0x0800_0000`) that this device
423    /// names its primary application at `0x0A04` (port) and `0x0A14` (IP)
424    /// (default: on).
425    ///
426    /// Off, the device is an Allied Vision Manta G-125B (firmware
427    /// 00.01.44.28514): the capability bit is clear and both registers answer
428    /// `INVALID_ADDRESS`, so CCP, which every application reads alike, is all
429    /// that says whether anyone holds control.
430    pub fn names_primary_application(mut self, names: bool) -> Self {
431        self.names_primary_application = names;
432        self
433    }
434
435    /// Act on `ACTION_CMD`s addressed to this device (default: on).
436    ///
437    /// Off, the device answers every action command as an Allied Vision
438    /// Manta G-125B (firmware 00.01.44.28514, GVCP Capability without the
439    /// action bit) did, broadcast or not: with status `NOT_IMPLEMENTED` under
440    /// the command's own opcode, `0x0100`, not `ACTION_ACK`.
441    pub fn action_commands(mut self, implemented: bool) -> Self {
442        self.action_commands = implemented;
443        self
444    }
445
446    /// Acknowledge every register-access command that starts at `addr` only
447    /// after `delay`, as a device busy with a flash write or a mode change
448    /// does — first with a `PENDING_ACK` of one and a half times `delay` when
449    /// `PENDING_ACK` is enabled. Other commands are served meanwhile, and a
450    /// retry of the delayed one is not executed again.
451    pub fn delay_ack(mut self, addr: u64, delay: Duration) -> Self {
452        self.delayed_acks.insert(addr, delay);
453        self
454    }
455
456    /// Serve this GenApi XML profile (default [`XmlProfile::Sfnc`]).
457    pub fn profile(mut self, profile: registers::XmlProfile) -> Self {
458        self.profile = profile;
459        self
460    }
461
462    /// Start the fake camera and return a handle.
463    pub async fn build(self) -> Result<FakeCamera, std::io::Error> {
464        let mut register_map = registers::RegisterMap::new(
465            self.width,
466            self.height,
467            self.pixel_format,
468            self.zip_xml.then_some(self.zip_xml_extra.as_slice()),
469            self.profile,
470        );
471        if let Some(timeout_ms) = self.heartbeat_timeout_ms {
472            register_map.set_heartbeat_timeout_ms(timeout_ms);
473        }
474        if let Some(max) = self.max_packet_size {
475            register_map.set_max_packet_size(max);
476        }
477        if let Some(max) = self.max_on_wire {
478            register_map.set_max_on_wire(max);
479        }
480        register_map.enforce_heartbeat(self.enforce_heartbeat);
481        register_map.set_mac(self.identity.mac);
482        register_map.set_packet_resend(self.packet_resend);
483        register_map.set_pending_ack_supported(self.pending_ack);
484        register_map.set_names_primary_application(self.names_primary_application);
485        register_map.set_network(
486            self.identity.ip.unwrap_or(self.bind_ip),
487            self.identity.subnet_mask,
488            self.identity.gateway,
489        );
490        if let Some(hz) = self.tick_frequency {
491            register_map.set_tick_frequency(hz);
492        }
493        let regs = Arc::new(Mutex::new(register_map));
494
495        let acq_start = Arc::new(Notify::new());
496        let acq_stop_flag = Arc::new(AtomicBool::new(false));
497        let counters = Arc::new(CommandCounters::default());
498        let discoveries = Arc::new(std::sync::Mutex::new(Vec::new()));
499        let expiries = Arc::new(AtomicU64::new(0));
500        let actions = Arc::new(AtomicU64::new(0));
501        let blocks_sent = Arc::new(AtomicU64::new(0));
502        let spoofed = Arc::new(AtomicU64::new(0));
503        let resends = Arc::new(resend::ResendCounters::default());
504        let link_down = Arc::new(AtomicBool::new(false));
505        let retention = Arc::new(std::sync::Mutex::new(resend::Retention::new(
506            self.resend_retention,
507        )));
508
509        // Bind GVCP control socket. On macOS `SO_REUSEADDR` is a no-op for UDP,
510        // so also set `SO_REUSEPORT` to let a fresh socket rebind the port while
511        // the previous camera's tokio task is still shutting down (matters for
512        // back-to-back module-scoped pytest fixtures).
513        let bind_addr: std::net::SocketAddr =
514            format!("{}:{}", self.bind_ip, self.port).parse().unwrap();
515        let sock = Socket::new(Domain::IPV4, Type::DGRAM, Some(Protocol::UDP))?;
516        sock.set_reuse_address(true)?;
517        #[cfg(unix)]
518        sock.set_reuse_port(true)?;
519        sock.set_nonblocking(true)?;
520        sock.bind(&bind_addr.into())?;
521        let std_sock: std::net::UdpSocket = sock.into();
522        let socket = Arc::new(UdpSocket::from_std(std_sock)?);
523        let local_addr = socket.local_addr()?;
524        info!(%local_addr, "fake camera GVCP listening");
525
526        // Spawn GVCP server task.
527        let (gvcp_shutdown, stopped) = tokio::sync::oneshot::channel();
528        let gvcp_handle = {
529            let socket = socket.clone();
530            let regs = regs.clone();
531            let acq_start = acq_start.clone();
532            let acq_stop = acq_stop_flag.clone();
533            let bind_ip = self.bind_ip;
534            let options = gvcp_server::ServerOptions {
535                shutdown: stopped,
536                counters: counters.clone(),
537                refuse_register_commands: self.refuse_register_commands,
538                retention: retention.clone(),
539                resend: resends.clone(),
540                discoveries: discoveries.clone(),
541                delayed_acks: Arc::new(self.delayed_acks),
542                expiries: expiries.clone(),
543                actions: actions.clone(),
544                action_commands: self.action_commands,
545                link_down: link_down.clone(),
546            };
547            let identity = self.identity;
548            tokio::spawn(async move {
549                gvcp_server::run(
550                    socket, regs, acq_start, acq_stop, bind_ip, options, identity,
551                )
552                .await;
553            })
554        };
555
556        // The message channel: events leave from a socket of their own on the
557        // camera's address, as the Manta's left from port 10020.
558        let events = Arc::new(events::Counters::default());
559        let (occurred, occurred_rx) = tokio::sync::mpsc::unbounded_channel();
560        let events_handle = {
561            let socket = UdpSocket::bind((self.bind_ip, 0)).await?;
562            let regs = regs.clone();
563            let events = events.clone();
564            let link_down = link_down.clone();
565            tokio::spawn(async move {
566                events::run(socket, occurred_rx, regs, events, link_down).await;
567            })
568        };
569
570        // Spawn GVSP streaming task.
571        let gvsp_handle = {
572            let regs = regs.clone();
573            let acq_start = acq_start.clone();
574            let acq_stop = acq_stop_flag.clone();
575            let fps = self.fps;
576            let options = self.sender;
577            let shared = gvsp_sender::SenderShared {
578                blocks_sent: blocks_sent.clone(),
579                spoofed: spoofed.clone(),
580                retention,
581                source_ip: self.bind_ip,
582                events: occurred,
583                link_down: link_down.clone(),
584            };
585            tokio::spawn(async move {
586                gvsp_sender::run(regs, acq_start, acq_stop, fps, options, shared).await;
587            })
588        };
589
590        Ok(FakeCamera {
591            gvcp_shutdown: Some(gvcp_shutdown),
592            gvcp_handle: Some(gvcp_handle),
593            gvsp_handle: Some(gvsp_handle),
594            events_handle: Some(events_handle),
595            events,
596            regs,
597            counters,
598            blocks_sent,
599            spoofed,
600            resends,
601            discoveries,
602            expiries,
603            actions,
604            link_down,
605            local_addr,
606        })
607    }
608}
609
610/// Handle to a running fake GigE Vision camera.
611///
612/// The camera runs as background tokio tasks. Call [`stop`](FakeCamera::stop) or
613/// drop the handle to shut down the camera.
614pub struct FakeCamera {
615    gvcp_shutdown: Option<tokio::sync::oneshot::Sender<()>>,
616    gvcp_handle: Option<JoinHandle<()>>,
617    gvsp_handle: Option<JoinHandle<()>>,
618    events_handle: Option<JoinHandle<()>>,
619    events: Arc<events::Counters>,
620    regs: Arc<Mutex<registers::RegisterMap>>,
621    counters: Arc<CommandCounters>,
622    blocks_sent: Arc<AtomicU64>,
623    spoofed: Arc<AtomicU64>,
624    resends: Arc<resend::ResendCounters>,
625    discoveries: Arc<std::sync::Mutex<Vec<DiscoveryRequest>>>,
626    expiries: Arc<AtomicU64>,
627    actions: Arc<AtomicU64>,
628    link_down: Arc<AtomicBool>,
629    local_addr: std::net::SocketAddr,
630}
631
632impl FakeCamera {
633    /// Create a new builder.
634    pub fn builder() -> FakeCameraBuilder {
635        FakeCameraBuilder::default()
636    }
637
638    /// Start a fake camera with default settings on 127.0.0.1:3956.
639    pub async fn start() -> Result<Self, std::io::Error> {
640        Self::builder().build().await
641    }
642
643    /// The local address the GVCP socket is bound to.
644    pub fn local_addr(&self) -> std::net::SocketAddr {
645        self.local_addr
646    }
647
648    /// The port the GVCP socket is listening on.
649    pub fn port(&self) -> u16 {
650        self.local_addr.port()
651    }
652
653    /// Which register-access commands this camera has received, and where.
654    ///
655    /// For tests that must assert *how* a value reached the device: READREG
656    /// and READMEM return identical bytes, so a test that checks only the
657    /// value cannot tell them apart.
658    pub fn commands(&self) -> &CommandCounters {
659        &self.counters
660    }
661
662    /// GVSP blocks this camera has produced, including any its packet script
663    /// then dropped whole.
664    ///
665    /// The left-hand side of a receiver's accounting identity: every block is
666    /// complete, incomplete, missed or dropped to backpressure on the host.
667    pub fn blocks_sent(&self) -> u64 {
668        self.blocks_sent.load(Ordering::Relaxed)
669    }
670
671    /// What this camera's message channel did: messages sent, how often,
672    /// acknowledged or abandoned, and events lost to a full queue
673    /// (`events` module: one message outstanding, sent again every `GevMCTT`
674    /// until acknowledged, as an Allied Vision Manta G-125B does).
675    pub fn message_channel(&self) -> MessageChannelStats {
676        self.events.snapshot()
677    }
678
679    /// What this camera did with `PACKETRESEND_CMD`s: requests received,
680    /// packets sent again, packets it no longer held.
681    pub fn resends(&self) -> ResendStats {
682        self.resends.snapshot()
683    }
684
685    /// Datagrams sent from the [`spoof_source`](FakeCameraBuilder::spoof_source)
686    /// address.
687    pub fn spoofed_packets(&self) -> u64 {
688        self.spoofed.load(Ordering::Relaxed)
689    }
690
691    /// The application holding control privilege — the address and port its
692    /// commands come from — or `None`.
693    pub async fn controller(&self) -> Option<SocketAddr> {
694        self.regs.lock().await.controller()
695    }
696
697    /// Give control privilege up on the device side, as a device does when
698    /// the controller's heartbeat expires: CCP reads 0 from then on.
699    pub async fn revoke_control(&self) {
700        self.regs.lock().await.revoke_control();
701    }
702
703    /// Take the camera's link down, as a pulled cable does: from now on
704    /// every datagram to it is lost unanswered, and every one it sends —
705    /// stream, events — is lost on the way. The camera itself runs on: it
706    /// keeps acquiring, and its heartbeat timer keeps counting.
707    /// [`plug_in`](Self::plug_in) brings the link back.
708    pub fn unplug(&self) {
709        info!("fake camera unplugged");
710        self.link_down.store(true, Ordering::Relaxed);
711    }
712
713    /// Bring the link [`unplug`](Self::unplug) took down back up.
714    pub fn plug_in(&self) {
715        info!("fake camera plugged in");
716        self.link_down.store(false, Ordering::Relaxed);
717    }
718
719    /// How often the heartbeat rule has revoked control privilege.
720    pub fn heartbeat_expiries(&self) -> u64 {
721        self.expiries.load(Ordering::Relaxed)
722    }
723
724    /// Action commands this camera acted on: its device key, group key and a
725    /// group mask that shares a bit with its own ([`FAKE_DEVICE_KEY`],
726    /// [`FAKE_GROUP_KEY`], [`FAKE_GROUP_MASK`]). One addressed elsewhere, or
727    /// malformed, is not counted.
728    pub fn actions(&self) -> u64 {
729        self.actions.load(Ordering::Relaxed)
730    }
731
732    /// Every `DISCOVERY_CMD` this camera received, in arrival order.
733    pub fn discovery_requests(&self) -> Vec<DiscoveryRequest> {
734        self.discoveries
735            .lock()
736            .map(|seen| seen.clone())
737            .unwrap_or_default()
738    }
739
740    /// Read `len` bytes of device state directly, bypassing GVCP.
741    ///
742    /// Not subject to access modes and not counted, so a test can check what a
743    /// write actually stored without trusting the client's own read-back.
744    pub async fn peek(&self, addr: u64, len: usize) -> Vec<u8> {
745        self.regs.lock().await.read(addr, len)
746    }
747
748    /// Whether `EventNotification` is `On` for `event_id`, as the device
749    /// keeps it per event, whatever `EventSelector` currently selects. Read
750    /// past the protocol, like [`FakeCamera::peek`].
751    pub async fn event_notification_on(&self, event_id: u16) -> bool {
752        self.regs.lock().await.event_notification_on(event_id)
753    }
754
755    /// How many times `TriggerSoftware` was executed, counted by the device.
756    pub async fn software_triggers(&self) -> u64 {
757        self.regs.lock().await.software_triggers()
758    }
759
760    /// The exposure saved in user set `set` by `UserSetSave`, or `None` if
761    /// nothing has been saved there. Read past the protocol, like
762    /// [`FakeCamera::peek`].
763    pub async fn saved_exposure(&self, set: u32) -> Option<f64> {
764        self.regs.lock().await.saved_exposure(set)
765    }
766
767    /// Stop the fake camera and wait for its background tasks to exit.
768    ///
769    /// The GVCP server cancels and drains its delayed acknowledgements, then
770    /// the other tasks are aborted and joined. No delayed task retains the
771    /// listening socket when this returns: a later fixture must not compete
772    /// with an obsolete socket for datagrams on the same port.
773    pub async fn stop(mut self) {
774        if let Some(shutdown) = self.gvcp_shutdown.take() {
775            let _ = shutdown.send(());
776        }
777        if let Some(h) = self.gvcp_handle.take() {
778            let _ = h.await;
779        }
780        if let Some(h) = self.gvsp_handle.take() {
781            h.abort();
782            let _ = h.await;
783        }
784        if let Some(h) = self.events_handle.take() {
785            h.abort();
786            let _ = h.await;
787        }
788    }
789}
790
791impl Drop for FakeCamera {
792    /// Best-effort cleanup when the handle is dropped without calling `stop`.
793    /// Does not wait for tasks to exit — use `stop().await` for that.
794    fn drop(&mut self) {
795        if let Some(shutdown) = self.gvcp_shutdown.take() {
796            let _ = shutdown.send(());
797        }
798        if let Some(h) = self.gvcp_handle.take() {
799            h.abort();
800        }
801        if let Some(h) = self.gvsp_handle.take() {
802            h.abort();
803        }
804        if let Some(h) = self.events_handle.take() {
805            h.abort();
806        }
807    }
808}