Skip to main content

viva_fake_gige/
registers.rs

1//! In-memory bootstrap register map and embedded GenApi XML.
2//!
3//! # Register Address Map
4//!
5//! | Address     | Length | Feature                         | Type     |
6//! |-------------|--------|---------------------------------|----------|
7//! | `0x0000`    | 4      | Version (RO)                    | u32 BE   |
8//! | `0x0004`    | 4      | DeviceMode (RO)                 | u32 BE   |
9//! | `0x0008`    | 4      | DeviceMACAddressHigh (RO)       | u32 BE   |
10//! | `0x000c`    | 4      | DeviceMACAddressLow (RO)        | u32 BE   |
11//! | `0x0010`    | 4      | SupportedIPConfiguration (RO)   | u32 BE   |
12//! | `0x0014`    | 4      | CurrentIPConfiguration          | u32 BE   |
13//! | `0x0024`    | 4      | CurrentIPAddress (RO)           | IPv4     |
14//! | `0x0034`    | 4      | CurrentSubnetMask (RO)          | IPv4     |
15//! | `0x0044`    | 4      | CurrentDefaultGateway (RO)      | IPv4     |
16//! | `0x0900`    | 4      | GevNumberOfMessageChannels (RO) | u32 BE   |
17//! | `0x0904`    | 4      | GevNumberOfStreamChannels (RO)  | u32 BE   |
18//! | `0x0a00`    | 4      | CCP (Control Channel Privilege) | u32 BE   |
19//! | `0x0934`    | 4      | GVCP Capability (RO)            | u32 BE   |
20//! | `0x0938`    | 4      | Heartbeat Timeout               | u32 BE   |
21//! | `0x093c`    | 4      | Timestamp tick frequency, high  | u32 BE   |
22//! | `0x0940`    | 4      | Timestamp tick frequency, low   | u32 BE   |
23//! | `0x0b00`    | 4      | GevMCP (message channel port)   | u32 BE   |
24//! | `0x0b10`    | 4      | GevMCDA (message channel addr)  | u32 BE   |
25//! | `0x0d00+`   | varies | Stream Channel 0 registers      | u32 BE   |
26//! | `0x20000`   | 4      | Width                           | u32 BE   |
27//! | `0x20004`   | 4      | Height                          | u32 BE   |
28//! | `0x20008`   | 4      | PixelFormat                     | u32 BE   |
29//! | `0x2000c`   | 4      | OffsetX                         | u32 BE   |
30//! | `0x20010`   | 4      | OffsetY                         | u32 BE   |
31//! | `0x20014`   | 4      | SensorWidth (RO)                | u32 BE   |
32//! | `0x20018`   | 4      | SensorHeight (RO)               | u32 BE   |
33//! | `0x20020`   | 4      | AcquisitionMode                 | u32 BE   |
34//! | `0x20024`   | 4      | AcquisitionStart (command)      | u32 BE   |
35//! | `0x20028`   | 4      | AcquisitionStop (command)       | u32 BE   |
36//! | `0x2002c`   | 4      | AcquisitionFrameRate            | f32→u32  |
37//! | `0x20030`   | 8      | ExposureTime                    | f64 BE   |
38//! | `0x20038`   | 4      | ExposureAuto                    | u32 BE   |
39//! | `0x20040`   | 8      | Gain                            | f64 BE   |
40//! | `0x20048`   | 4      | GainAuto                        | u32 BE   |
41//! | `0x20050`   | 4      | BlackLevel                      | u32 BE   |
42//! | `0x20054`   | 4      | AcquisitionFrameRateEnable      | u32 BE   |
43//! | `0x20058`   | 4      | SensorType                      | u32 BE   |
44//! | `0x20060`   | 4      | GevTimestampTickFrequency (RO)  | u32 BE   |
45//! | `0x20068`   | 8      | GevTimestampValue (RO)          | u64 BE   |
46//! | `0x20070`   | 4      | TimestampLatch (command)        | u32 BE   |
47//! | `0x20078`   | 8      | GevIEEE1588OffsetFromMaster…    | u64 BE   |
48//! | `0x20080`   | 4      | ChunkModeActive                 | u32 BE   |
49//! | `0x20084`   | 4      | ChunkSelector                   | u32 BE   |
50//! | `0x20088`   | 4      | ChunkEnable                     | u32 BE   |
51//! | `0x200a0`   | 4      | EventSelector                   | u32 BE   |
52//! | `0x200a4`   | 4      | EventNotification (per selector)| u32 BE   |
53//! | `0x200a8`   | 4      | UserSetSelector                 | u32 BE   |
54//! | `0x200ac`   | 4      | UserSetLoad (command)           | u32 BE   |
55//! | `0x200b0`   | 4      | SoftwareSignal*Pulse (WO bits)  | u32 BE   |
56//! | `0x200b4`   | 4      | UserSetSave (command)           | u32 BE   |
57//! | `0x20100`   | 4      | WidthMin (RO)                   | u32 BE   |
58//! | `0x20104`   | 4      | WidthMax (RO)                   | u32 BE   |
59//! | `0x20108`   | 4      | HeightMin (RO)                  | u32 BE   |
60//! | `0x2010c`   | 4      | HeightMax (RO)                  | u32 BE   |
61//! | `0x20110`   | 8      | ChunkTimestamp_Val (RO)         | u64 **LE** |
62//! | `0x20118`   | 4      | ChunkWidth_Val (RO)             | u32 **LE** |
63//! | `0x20120`   | 4      | PayloadSize (RO, computed)      | u32 BE   |
64//! | `0x20200`   | 32     | DeviceModelName (RO)            | string   |
65//! | `0x20220`   | 32     | DeviceVendorName (RO)           | string   |
66//! | `0x20240`   | 16     | DeviceSerialNumber (RO)         | string   |
67//! | `0x20260`   | 32     | DeviceFirmwareVersion (RO)      | string   |
68//! | `0x20280`   | 32     | DeviceID (RO)                   | string   |
69//! | `0x20300`   | 4      | DeviceTemperature_Val (RO)      | i32 BE, °C × 256 |
70//! | `0x20400`   | 16     | DeviceUserID                    | string   |
71//! | `0x20410`   | 16     | DeviceUserBuffer                | bytes    |
72
73use std::collections::{HashMap, HashSet};
74use std::net::{Ipv4Addr, SocketAddr};
75use std::time::{Duration, Instant};
76
77use crate::gvcp_server::FAKE_MAC;
78
79// Bootstrap register addresses and bits are GigE Vision's vocabulary, imported
80// rather than copied (ADR-0030). What each register holds, and how the fake
81// answers it, is still this file's own reading of the specification.
82pub(crate) use viva_gige::consts::{
83    CAPABILITY_CCP_APPLICATION_PORT_IP, CAPABILITY_CONCATENATION, CAPABILITY_PACKET_RESEND,
84    CAPABILITY_PENDING_ACK, CAPABILITY_WRITEMEM, CCP_CONTROL, CCP_EXCLUSIVE,
85    CONFIGURATION_PENDING_ACK_ENABLE, CONTROL_CHANNEL_PRIVILEGE, CURRENT_DEFAULT_GATEWAY,
86    CURRENT_IP_ADDRESS, CURRENT_IP_CONFIG, CURRENT_SUBNET_MASK, DEVICE_MAC_ADDRESS_HIGH,
87    DEVICE_MAC_ADDRESS_LOW, DEVICE_MODE, FIRST_URL, GVCP_CAPABILITY, GVCP_CONFIGURATION,
88    HEARTBEAT_TIMEOUT, MESSAGE_CHANNEL_RETRY_COUNT, MESSAGE_CHANNEL_TIMEOUT,
89    MESSAGE_DESTINATION_ADDRESS, MESSAGE_DESTINATION_PORT, NUMBER_OF_MESSAGE_CHANNELS,
90    NUMBER_OF_STREAM_CHANNELS, PERSISTENT_DEFAULT_GATEWAY, PERSISTENT_IP_ADDRESS,
91    PERSISTENT_SUBNET_MASK, PRIMARY_APPLICATION_IP, PRIMARY_APPLICATION_PORT, SCPS_DO_NOT_FRAGMENT,
92    SCPS_FIRE_TEST_PACKET, STREAM_CHANNEL_BASE, STREAM_CHANNEL_STRIDE, STREAM_DESTINATION_ADDRESS,
93    STREAM_DESTINATION_PORT, STREAM_PACKET_DELAY, STREAM_PACKET_SIZE, STREAM_PACKET_SIZE_MASK,
94    SUPPORTED_IP_CONFIG, TIMESTAMP_TICK_FREQUENCY_HIGH, TIMESTAMP_TICK_FREQUENCY_LOW, URL_LEN,
95    VERSION,
96};
97
98/// `DeviceMode`: big-endian (bit 31), character set 1 (UTF-8), class
99/// Transmitter (0).
100pub const DEVICE_MODE_VALUE: u32 = 0x8000_0001;
101
102/// The fake's timestamp clock: nanoseconds, so 1 GHz.
103pub const TICK_FREQUENCY_HZ: u64 = 1_000_000_000;
104
105/// Address where the actual XML blob is stored in the register space.
106pub const XML_BLOB_BASE: u64 = 0x1_0000;
107
108// ── Feature register addresses ──────────────────────────────────────────────
109
110/// Image format registers.
111pub const REG_WIDTH: u64 = 0x20000;
112pub const REG_HEIGHT: u64 = 0x20004;
113pub const REG_PIXEL_FORMAT: u64 = 0x20008;
114pub const REG_OFFSET_X: u64 = 0x2000c;
115pub const REG_OFFSET_Y: u64 = 0x20010;
116pub const REG_SENSOR_WIDTH: u64 = 0x20014;
117pub const REG_SENSOR_HEIGHT: u64 = 0x20018;
118
119/// Acquisition registers.
120pub const REG_ACQ_MODE: u64 = 0x20020;
121pub const REG_ACQ_START: u64 = 0x20024;
122pub const REG_ACQ_STOP: u64 = 0x20028;
123pub const REG_ACQ_FRAME_RATE: u64 = 0x2002c;
124
125/// Analog control registers.
126pub const REG_EXPOSURE_TIME: u64 = 0x20030;
127pub const REG_EXPOSURE_AUTO: u64 = 0x20038;
128pub const REG_GAIN: u64 = 0x20040;
129pub const REG_GAIN_AUTO: u64 = 0x20048;
130pub const REG_BLACK_LEVEL: u64 = 0x20050;
131
132/// Predicate-gating registers driving realistic feature behaviour.
133///
134/// `REG_ACQ_FRAME_RATE_ENABLE` backs the SFNC `AcquisitionFrameRateEnable`
135/// Boolean and gates `AcquisitionFrameRate` via `pIsAvailable`.
136/// `REG_SENSOR_TYPE` backs a `SensorType` enumeration (Monochrome / BayerRG /
137/// Color) that gates `PixelFormat` entries via `pIsImplemented`. On real
138/// hardware `SensorType` would be read-only sensor metadata, but exposing it
139/// as RW here keeps the fake camera a configurable simulator.
140pub const REG_ACQ_FRAME_RATE_ENABLE: u64 = 0x20054;
141pub const REG_SENSOR_TYPE: u64 = 0x20058;
142
143/// Device capability inquiry bits, exposed through a `<StructReg>` whose
144/// address is `<pAddress>` (a base node) plus a fixed `<Address>` offset — the
145/// shape Point Grey, FLIR and Hikrobot use for their inquiry blocks.
146pub const REG_DEVICE_CAPS: u64 = 0x2005c;
147
148/// Which stream channel the `GevSCP*` features address.
149///
150/// Backs a `<pIndex>` term, so changing it moves those registers by
151/// [`STREAM_CHANNEL_STRIDE`].
152pub const REG_STREAM_CHANNEL_SELECTOR: u64 = 0x20090;
153
154/// Timestamp registers.
155pub const REG_TIMESTAMP_FREQ: u64 = 0x20060;
156pub const REG_TIMESTAMP_VALUE: u64 = 0x20068;
157pub const REG_TIMESTAMP_LATCH: u64 = 0x20070;
158
159/// A PTP offset-from-master, copied in shape from the FLIR BFS-PGE-31S4C-C
160/// description in the corpus (`<Length>8</Length>`, `<Sign>Unsigned</Sign>`,
161/// `<Endianess>BigEndian</Endianess>`). It is the node issue #140 was filed
162/// against, and it is declared unsigned although a clock offset is signed by
163/// nature — so its top bit is set whenever the slave leads the master. That
164/// combination is what made the node unreadable.
165pub const REG_PTP_OFFSET_LATCHED: u64 = 0x20078;
166
167/// Chunk value registers, declared **little-endian** exactly as FLIR, Point
168/// Grey and Hikrobot declare theirs. 311 plain `<IntReg>` declarations across
169/// 16 of the 38 corpus documents are of this shape; before GA-28 every one of
170/// them decoded byte-swapped, and nothing in the tree could notice.
171pub const REG_CHUNK_TIMESTAMP_LE: u64 = 0x20110;
172pub const REG_CHUNK_WIDTH_LE: u64 = 0x20118;
173/// `PayloadSize`: the bytes of the next block's payload, computed from the
174/// image format and the chunk configuration when read, as a camera does.
175pub const REG_PAYLOAD_SIZE: u64 = 0x20120;
176
177/// Value latched into [`REG_PTP_OFFSET_LATCHED`]: the slave leading the master
178/// by 1 234 567 ns. Stored as the two's-complement bit pattern a camera would
179/// put on the wire, so the test asserts the bytes and the decoded value
180/// separately rather than round-tripping through our own codec.
181pub const PTP_OFFSET_NS: i64 = -1_234_567;
182
183/// Value latched into [`REG_CHUNK_TIMESTAMP_LE`]. Chosen so that reading it in
184/// the wrong byte order yields a plausible positive number
185/// (`0x7856_3412_0000_0000`) rather than an error — a byte-order defect that
186/// announces itself is not the one that shipped.
187pub const CHUNK_TIMESTAMP_TICKS: u64 = 0x0000_0000_1234_5678;
188
189/// Value latched into [`REG_CHUNK_WIDTH_LE`]. Most of the 311 are 4 bytes
190/// wide, so the common width gets its own node.
191pub const CHUNK_WIDTH_PX: u32 = 1440;
192
193/// Chunk data registers.
194pub const REG_CHUNK_MODE_ACTIVE: u64 = 0x20080;
195pub const REG_CHUNK_SELECTOR: u64 = 0x20084;
196/// `ChunkEnable` for the selected chunk: a *selected* feature, backed by the
197/// set of enabled selector values (`RegisterMap::chunk_enabled`).
198pub const REG_CHUNK_ENABLE: u64 = 0x20088;
199
200/// `ChunkSelector` entry values, this fake's own numbering.
201pub const CHUNK_SELECTOR_TIMESTAMP: u32 = 1;
202/// `ChunkSelector` = `ExposureTime`.
203pub const CHUNK_SELECTOR_EXPOSURE_TIME: u32 = 2;
204/// `ChunkSelector` = `FrameID`.
205pub const CHUNK_SELECTOR_FRAME_ID: u32 = 4;
206/// `ChunkSelector` = `ImageInfo`: width, height and image length in one
207/// chunk, with the length at a negative address as Baumer's HXG20 declares
208/// `ChunkImageLength`.
209pub const CHUNK_SELECTOR_IMAGE_INFO: u32 = 5;
210
211/// Chunk IDs on this fake's chunk ports, as its XML declares them. A real
212/// camera's are whatever its XML says; two here are above 0xFFFF, which a
213/// 16-bit ID could not carry.
214pub const CHUNK_ID_IMAGE: u32 = 0x0000_0001;
215/// `ChunkTimestamp`: the leader's timestamp, 8 bytes little-endian.
216pub const CHUNK_ID_TIMESTAMP: u32 = 0x0000_0002;
217/// `ChunkExposureTime`: IEEE 754 double, little-endian.
218pub const CHUNK_ID_EXPOSURE_TIME: u32 = 0x0000_0003;
219/// `ChunkFrameID`: the block id, 8 bytes little-endian.
220pub const CHUNK_ID_FRAME_ID: u32 = 0x0504_0003;
221/// `ImageInfo`: width, height, reserved, image length — four big-endian
222/// `u32`s; `ChunkImageLength` reads the last at address `-4`.
223pub const CHUNK_ID_IMAGE_INFO: u32 = 0xA5A5_0100;
224
225/// This fake's `GevMCTT`: milliseconds before an unacknowledged event message
226/// is sent again.
227pub const DEFAULT_MESSAGE_TIMEOUT_MS: u32 = 40;
228/// This fake's `GevMCRC`: retransmissions before an event message is
229/// abandoned.
230pub const DEFAULT_MESSAGE_RETRY_COUNT: u32 = 25;
231
232/// GigE Vision event identifier this fake sends for ExposureEnd, as an
233/// `EVENTDATA` carrying the frame id. Device-specific range, this fake's own
234/// choice; its event port declares `<EventID>9001</EventID>`.
235pub const EVENT_EXPOSURE_END: u16 = 0x9001;
236
237/// `EventSelector` backing register: a GigE Vision event identifier.
238/// `REG_FEATURE_STATUS` is a FLIR-shaped feature-status word: one big-endian
239/// register whose individual bits say whether a feature is implemented,
240/// available and locked, addressed by `<MaskedIntReg>` + `<Bit>`.
241///
242/// It exists so the fake can disagree with us about bit numbering. Every other
243/// predicate here is an `<IntSwissKnife>` or a `<StructEntry>`, and both of
244/// those took the code path that was already correct — so the whole suite
245/// passed while `<MaskedIntReg>` read big-endian registers off the wrong end on
246/// real hardware (issue #120). GenICam counts `<Bit>` from the MSB on a
247/// big-endian register, so bit 0 is `0x8000_0000`.
248pub const REG_FEATURE_STATUS: u64 = 0x2009c;
249
250pub const REG_EVENT_SELECTOR: u64 = 0x200a0;
251/// `EventNotification` backing register for the selected event (0 = Off, 1 = On).
252///
253/// A *selected* feature: reads and writes apply to whichever event
254/// [`REG_EVENT_SELECTOR`] currently names, so the register is backed by a set
255/// of enabled event ids rather than by one stored word. Query it with
256/// [`RegisterMap::event_notification_on`].
257pub const REG_EVENT_NOTIFICATION: u64 = 0x200a4;
258
259/// Exposure the fake boots with, and returns to when `UserSetLoad` loads
260/// `Default`.
261pub const DEFAULT_EXPOSURE_US: f64 = 5000.0;
262
263/// `REG_USER_SET_SELECTOR`, `REG_USER_SET_LOAD` and `REG_USER_SET_SAVE` back
264/// the SFNC user-set features, so the fake can answer the workflow issue #121
265/// was filed about.
266///
267/// They are shaped after the Hikrobot MV-CS050-10GC
268/// (`Hikrobot_MV-CS050-10GC.xml:23009-23148` in the vendor corpus): both
269/// commands take the value they write from `<pCommandValue>`, an
270/// `<IntSwissKnife>` reading the selector register, so the *written value*
271/// names the user set. The fake acts on that value, not on the selector
272/// register — so a client that writes a constant `1` with `UserSet2` selected
273/// saves into set 1 here as it would on the camera, and a test can see it
274/// (backlog GA-35; ADR-0019's "fakes must be able to disagree").
275pub const REG_USER_SET_SELECTOR: u64 = 0x200a8;
276/// `UserSetLoad`: writing `n` loads user set `n`, `0` being `Default`.
277pub const REG_USER_SET_LOAD: u64 = 0x200ac;
278/// `UserSetSave`: writing `n` saves the current settings into user set `n`.
279/// `Default` cannot be saved: the XML makes the command unavailable while it
280/// is selected, and the fake ignores a write of `0`.
281pub const REG_USER_SET_SAVE: u64 = 0x200b4;
282
283/// A write-only register addressed bit by bit: a `<StructReg>` with
284/// `AccessMode WO` whose `<StructEntry>` bits each pulse one software signal.
285///
286/// It is here so the fake can refuse a masked write that reads first
287/// (backlog GA-31, [#135](https://github.com/VitalyVorobyev/viva-genicam/issues/135)).
288/// Every other WO node in this XML is a whole-register command, and a
289/// whole-register write never needs the other bits — so the read-modify-write
290/// path had no in-tree coverage at all. A `<StructEntry>` inherits the
291/// register's access mode and always has a bitfield, which is the shape the
292/// vendor corpus uses.
293pub const REG_SOFTWARE_SIGNAL_PULSE: u64 = 0x200b0;
294
295/// `TriggerSelector`: which trigger `TriggerMode`, `TriggerSource` and
296/// `TriggerSoftware` act on. `FrameStart` is 0, `AcquisitionStart` 1; the
297/// selected value indexes the mode and source registers (`<pIndex>`, as the
298/// Basler acA1600 and Hikrobot documents address theirs).
299pub const REG_TRIGGER_SELECTOR: u64 = 0x200c0;
300/// `TriggerSelector` value of `FrameStart`.
301pub const TRIGGER_FRAME_START: u32 = 0;
302/// `TriggerMode` of the trigger at index `n` lives at `REG_TRIGGER_MODE + 4n`;
303/// `1` is `On`.
304pub const REG_TRIGGER_MODE: u64 = 0x200c4;
305/// `TriggerSource` of the trigger at index `n` lives at
306/// `REG_TRIGGER_SOURCE + 4n`.
307pub const REG_TRIGGER_SOURCE: u64 = 0x200d0;
308/// `TriggerSource` value of `Line1`, the source the fake boots with.
309pub const TRIGGER_SOURCE_LINE1: u32 = 0;
310/// `TriggerSource` value of `Software`.
311pub const TRIGGER_SOURCE_SOFTWARE: u32 = 1;
312/// `TriggerSoftware`: a write starts one frame while the `FrameStart`
313/// trigger is `On` with source `Software`. With the trigger on, the fake
314/// sends no frame without one: the data path is gated, not only the register.
315pub const REG_TRIGGER_SOFTWARE: u64 = 0x200e0;
316/// `BinningHorizontal`, 1 to 4.
317pub const REG_BINNING_HORIZONTAL: u64 = 0x200e4;
318/// `BinningVertical`, 1 to 4.
319pub const REG_BINNING_VERTICAL: u64 = 0x200e8;
320/// `UserSetDefault` (SFNC 2) or, in the legacy profile,
321/// `UserSetDefaultSelector`: the set the camera loads at power-up.
322pub const REG_USER_SET_DEFAULT: u64 = 0x200ec;
323/// `GainRaw` of `GainSelector` entry `n` lives at `REG_GAIN_RAW + 4n`
324/// (legacy profile only).
325pub const REG_GAIN_RAW: u64 = 0x200f0;
326
327/// Registers the XML declares `WO`. Reading any of them is refused with
328/// `ACCESS_DENIED`, as a real device refuses it.
329///
330/// Listed explicitly rather than derived from the XML: the fake must be able to
331/// disagree with our parser, and deriving the list through it would make the
332/// two agree by construction (ADR-0019).
333pub const WRITE_ONLY_REGISTERS: &[u64] = &[
334    REG_ACQ_START,
335    REG_ACQ_STOP,
336    REG_TIMESTAMP_LATCH,
337    REG_USER_SET_LOAD,
338    REG_SOFTWARE_SIGNAL_PULSE,
339    REG_USER_SET_SAVE,
340    REG_TRIGGER_SOFTWARE,
341];
342
343/// Limit registers.
344pub const REG_WIDTH_MIN: u64 = 0x20100;
345pub const REG_WIDTH_MAX: u64 = 0x20104;
346pub const REG_HEIGHT_MIN: u64 = 0x20108;
347pub const REG_HEIGHT_MAX: u64 = 0x2010c;
348
349/// Device info string registers.
350pub const REG_DEVICE_MODEL_NAME: u64 = 0x20200;
351pub const REG_DEVICE_VENDOR_NAME: u64 = 0x20220;
352pub const REG_DEVICE_SERIAL_NUMBER: u64 = 0x20240;
353pub const REG_DEVICE_FIRMWARE_VERSION: u64 = 0x20260;
354pub const REG_DEVICE_ID: u64 = 0x20280;
355
356/// `DeviceUserID`: SFNC's user-settable name, a read-write `<StringReg>`.
357pub const REG_DEVICE_USER_ID: u64 = 0x20400;
358/// Length of `DeviceUserID`, in bytes.
359pub const DEVICE_USER_ID_LEN: usize = 16;
360/// `DeviceUserBuffer`: a read-write `<Register>`, sixteen bytes the camera
361/// stores as written — the shape of a vendor's user data area.
362pub const REG_DEVICE_USER_BUFFER: u64 = 0x20410;
363/// Length of `DeviceUserBuffer`, in bytes.
364pub const DEVICE_USER_BUFFER_LEN: usize = 16;
365
366/// `DeviceTemperature_Val`: the sensor temperature in 1/256 °C, which the
367/// camera changes on its own — no write moves it. The XML declares it the
368/// way FLIR's BFS does (`FLIR_BFS_PGE_31S4C_C.xml`): `NoCache`, with a
369/// `<PollingTime>` of 500 ms, behind a `<Converter>` and a `<Float>`. A client
370/// that caches it shows the first reading forever (backlog GA-05).
371pub const REG_DEVICE_TEMPERATURE: u64 = 0x20300;
372/// The temperature the fake starts at, in °C.
373pub const DEVICE_TEMPERATURE_START_C: f64 = 40.0;
374/// How far the temperature rises each [`DEVICE_TEMPERATURE_PERIOD`], in °C.
375pub const DEVICE_TEMPERATURE_STEP_C: f64 = 0.25;
376/// How often the temperature moves.
377pub const DEVICE_TEMPERATURE_PERIOD: Duration = Duration::from_millis(200);
378/// Steps before the temperature falls back to the start: a sawtooth from 40
379/// to 60 °C every 16 s, so a viewer polling it sees it move.
380pub const DEVICE_TEMPERATURE_STEPS: u64 = 80;
381
382// ── GenApi XML ──────────────────────────────────────────────────────────────
383
384/// GenApi XML describing a realistic fake camera following SFNC conventions.
385///
386/// The XML is organized with proper SFNC category hierarchy:
387///
388/// ```text
389/// Root
390/// ├── DeviceControl        — model name, vendor, serial, firmware, device ID
391/// ├── ImageFormatControl   — width, height, offset, pixel format, sensor size
392/// ├── AcquisitionControl   — start/stop, mode, frame rate, exposure, auto
393/// ├── AnalogControl        — gain, gain auto, black level
394/// ├── TransportLayerControl — timestamp tick frequency, value, latch
395/// └── ChunkDataControl     — chunk mode, selector, enable
396/// ```
397///
398/// All feature registers use big-endian byte order. Register addresses are
399/// documented in the module-level doc comment.
400pub const FAKE_XML: &str = r#"<?xml version="1.0" encoding="UTF-8"?>
401<RegisterDescription
402  xmlns="http://www.genicam.org/GenApi/Version_1_1"
403  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
404  xsi:schemaLocation="http://www.genicam.org/GenApi/Version_1_1 http://www.genicam.org/GenApi/GenApiSchema_Version_1_1.xsd"
405  ModelName="VivaCam_Fake"
406  VendorName="vitavision"
407  ToolTip="Simulated GigE Vision camera for testing"
408  StandardNameSpace="GEV"
409  SchemaMajorVersion="1"
410  SchemaMinorVersion="1"
411  SchemaSubMinorVersion="0"
412  MajorVersion="1"
413  MinorVersion="0"
414  SubMinorVersion="0"
415  ProductGuid="76697661-6361-6d00-0000-000000000000"
416  VersionGuid="76697661-6361-6d00-0000-000000000001">
417
418  <!-- ════════════════════════════════════════════════════════════════════
419       Category Hierarchy (SFNC Standard)
420       ════════════════════════════════════════════════════════════════════ -->
421
422  <Category Name="Root" NameSpace="Standard">
423    <pFeature>DeviceControl</pFeature>
424    <pFeature>ImageFormatControl</pFeature>
425    <pFeature>AcquisitionControl</pFeature>
426    <pFeature>AnalogControl</pFeature>
427    <pFeature>TransportLayerControl</pFeature>
428    <pFeature>ChunkDataControl</pFeature>
429    <pFeature>UserSetControl</pFeature>
430  </Category>
431
432  <Category Name="UserSetControl">
433    <DisplayName>User Set Control</DisplayName>
434    <pFeature>UserSetSelector</pFeature>
435    <pFeature>UserSetLoad</pFeature>
436    <pFeature>UserSetSave</pFeature>
437    <!-- profile:user-set-default-category --><pFeature>UserSetDefault</pFeature><!-- /profile:user-set-default-category -->
438  </Category>
439
440  <Category Name="DeviceControl">
441    <DisplayName>Device Control</DisplayName>
442    <pFeature>DeviceVendorName</pFeature>
443    <pFeature>DeviceModelName</pFeature>
444    <pFeature>DeviceSerialNumber</pFeature>
445    <pFeature>DeviceFirmwareVersion</pFeature>
446    <pFeature>DeviceID</pFeature>
447    <pFeature>DeviceUserID</pFeature>
448    <pFeature>DeviceUserBuffer</pFeature>
449    <pFeature>DeviceTemperature</pFeature>
450  </Category>
451
452  <Category Name="ImageFormatControl">
453    <DisplayName>Image Format Control</DisplayName>
454    <pFeature>SensorType</pFeature>
455    <pFeature>SensorWidth</pFeature>
456    <pFeature>SensorHeight</pFeature>
457    <pFeature>Width</pFeature>
458    <pFeature>Height</pFeature>
459    <pFeature>OffsetX</pFeature>
460    <pFeature>OffsetY</pFeature>
461    <pFeature>BinningHorizontal</pFeature>
462    <pFeature>BinningVertical</pFeature>
463    <pFeature>PixelFormat</pFeature>
464  </Category>
465
466  <Category Name="AcquisitionControl">
467    <DisplayName>Acquisition Control</DisplayName>
468    <pFeature>AcquisitionMode</pFeature>
469    <pFeature>AcquisitionStart</pFeature>
470    <pFeature>AcquisitionStop</pFeature>
471    <pFeature>AcquisitionFrameRateEnable</pFeature>
472    <!-- profile:frame-rate-category --><pFeature>AcquisitionFrameRate</pFeature><!-- /profile:frame-rate-category -->
473    <!-- profile:exposure-category --><pFeature>ExposureTime</pFeature><!-- /profile:exposure-category -->
474    <pFeature>ExposureAuto</pFeature>
475    <pFeature>TriggerSelector</pFeature>
476    <pFeature>TriggerMode</pFeature>
477    <pFeature>TriggerSource</pFeature>
478    <pFeature>TriggerSoftware</pFeature>
479  </Category>
480
481  <Category Name="AnalogControl">
482    <DisplayName>Analog Control</DisplayName>
483    <!-- profile:gain-category --><pFeature>Gain</pFeature><!-- /profile:gain-category -->
484    <pFeature>GainAuto</pFeature>
485    <pFeature>BlackLevel</pFeature>
486  </Category>
487
488  <Category Name="TransportLayerControl">
489    <DisplayName>Transport Layer Control</DisplayName>
490    <pFeature>PayloadSize</pFeature>
491    <pFeature>TLParamsLocked</pFeature>
492    <pFeature>GevTimestampTickFrequency</pFeature>
493    <pFeature>GevTimestampValue</pFeature>
494    <pFeature>TimestampLatch</pFeature>
495    <pFeature>GevIEEE1588OffsetFromMasterLatched_Val</pFeature>
496    <pFeature>ChunkTimestamp_Val</pFeature>
497    <pFeature>ChunkWidth_Val</pFeature>
498  </Category>
499
500  <Category Name="ChunkDataControl">
501    <DisplayName>Chunk Data Control</DisplayName>
502    <pFeature>ChunkModeActive</pFeature>
503    <pFeature>ChunkSelector</pFeature>
504    <pFeature>ChunkEnable</pFeature>
505    <pFeature>ChunkTimestamp</pFeature>
506    <pFeature>ChunkExposureTime</pFeature>
507    <pFeature>ChunkFrameID</pFeature>
508    <pFeature>ChunkWidth</pFeature>
509    <pFeature>ChunkHeight</pFeature>
510    <pFeature>ChunkImageLength</pFeature>
511  </Category>
512
513  <Category Name="EventControl">
514    <DisplayName>Event Control</DisplayName>
515    <pFeature>EventSelector</pFeature>
516    <pFeature>EventNotification</pFeature>
517    <pFeature>EventExposureEnd</pFeature>
518    <pFeature>EventExposureEndTimestamp</pFeature>
519    <pFeature>EventExposureEndFrameID</pFeature>
520  </Category>
521
522  <!-- The device's own register space: every register that is not on a
523       chunk or event port names it. -->
524  <Port Name="Device" NameSpace="Standard"/>
525
526  <!-- ════════════════════════════════════════════════════════════════════
527       Device Control Features
528       ════════════════════════════════════════════════════════════════════ -->
529
530  <StringReg Name="DeviceVendorName" NameSpace="Standard">
531    <ToolTip>Name of the device vendor</ToolTip>
532    <Address>0x20220</Address>
533    <Length>32</Length>
534    <AccessMode>RO</AccessMode>
535    <pPort>Device</pPort>
536  </StringReg>
537
538  <StringReg Name="DeviceModelName" NameSpace="Standard">
539    <ToolTip>Name of the device model</ToolTip>
540    <Address>0x20200</Address>
541    <Length>32</Length>
542    <AccessMode>RO</AccessMode>
543    <pPort>Device</pPort>
544  </StringReg>
545
546  <StringReg Name="DeviceSerialNumber" NameSpace="Standard">
547    <ToolTip>Serial number of the device</ToolTip>
548    <Address>0x20240</Address>
549    <Length>16</Length>
550    <AccessMode>RO</AccessMode>
551    <pPort>Device</pPort>
552  </StringReg>
553
554  <StringReg Name="DeviceFirmwareVersion" NameSpace="Standard">
555    <ToolTip>Firmware version of the device</ToolTip>
556    <Address>0x20260</Address>
557    <Length>32</Length>
558    <AccessMode>RO</AccessMode>
559    <pPort>Device</pPort>
560  </StringReg>
561
562  <StringReg Name="DeviceID" NameSpace="Standard">
563    <ToolTip>User-configurable device identifier</ToolTip>
564    <Address>0x20280</Address>
565    <Length>32</Length>
566    <AccessMode>RO</AccessMode>
567    <pPort>Device</pPort>
568  </StringReg>
569
570  <StringReg Name="DeviceUserID" NameSpace="Standard">
571    <ToolTip>A name the user gives the device</ToolTip>
572    <Address>0x20400</Address>
573    <Length>16</Length>
574    <AccessMode>RW</AccessMode>
575    <pPort>Device</pPort>
576  </StringReg>
577
578  <Register Name="DeviceUserBuffer" NameSpace="Custom">
579    <ToolTip>Sixteen bytes of user data, stored as written</ToolTip>
580    <Address>0x20410</Address>
581    <Length>16</Length>
582    <AccessMode>RW</AccessMode>
583    <pPort>Device</pPort>
584  </Register>
585
586  <!-- A value the camera changes on its own, declared as FLIR's BFS declares
587       it (FLIR_BFS_PGE_31S4C_C.xml): a Float over a Converter over an IntReg
588       that is NoCache and polled every 500 ms (GA-05). -->
589  <Float Name="DeviceTemperature" NameSpace="Standard">
590    <ToolTip>Device temperature in degrees Celsius</ToolTip>
591    <ImposedAccessMode>RO</ImposedAccessMode>
592    <pValue>DeviceTemperature_FloatVal</pValue>
593    <Unit>C</Unit>
594  </Float>
595  <Converter Name="DeviceTemperature_FloatVal">
596    <FormulaTo>FROM*256</FormulaTo>
597    <FormulaFrom>TO/256</FormulaFrom>
598    <pValue>DeviceTemperature_Val</pValue>
599    <Slope>Increasing</Slope>
600  </Converter>
601  <IntReg Name="DeviceTemperature_Val">
602    <Address>0x20300</Address>
603    <Length>4</Length>
604    <AccessMode>RO</AccessMode>
605    <pPort>Device</pPort>
606    <Cachable>NoCache</Cachable>
607    <PollingTime>500</PollingTime>
608    <Sign>Signed</Sign>
609    <Endianess>BigEndian</Endianess>
610  </IntReg>
611
612  <!-- ════════════════════════════════════════════════════════════════════
613       Image Format Control Features
614       ════════════════════════════════════════════════════════════════════ -->
615
616  <Integer Name="SensorWidth" NameSpace="Standard">
617    <ToolTip>Physical sensor width in pixels</ToolTip>
618    <pValue>SensorWidthReg</pValue>
619    <Min>1</Min>
620    <Max>4096</Max>
621  </Integer>
622  <IntReg Name="SensorWidthReg"><Address>0x20014</Address><Length>4</Length><AccessMode>RO</AccessMode><pPort>Device</pPort><Sign>Unsigned</Sign><Endianess>BigEndian</Endianess></IntReg>
623
624  <Integer Name="SensorHeight" NameSpace="Standard">
625    <ToolTip>Physical sensor height in pixels</ToolTip>
626    <pValue>SensorHeightReg</pValue>
627    <Min>1</Min>
628    <Max>4096</Max>
629  </Integer>
630  <IntReg Name="SensorHeightReg"><Address>0x20018</Address><Length>4</Length><AccessMode>RO</AccessMode><pPort>Device</pPort><Sign>Unsigned</Sign><Endianess>BigEndian</Endianess></IntReg>
631
632  <!-- The ROI shape every corpus document shares: a size's maximum shrinks
633       as its offset grows, and an offset's as the size grows, so the order
634       of writes decides whether a new ROI can be reached at all. The size and
635       format are locked while TLParamsLocked is set (FLIR, Basler, Hikrobot).
636       Binning rescales the region (SFNC: WidthMax is counted after binning),
637       which each node below says with a pInvalidator, as Basler's acA1600
638       does on its WidthMax register — on the feature, and on the register
639       behind it, where a GenApi caches the value. -->
640  <Integer Name="Width" NameSpace="Standard">
641    <ToolTip>Width of the image in pixels</ToolTip>
642    <pIsLocked>TLParamsLocked</pIsLocked>
643    <pInvalidator>BinningHorizontal</pInvalidator>
644    <Streamable>Yes</Streamable>
645    <pValue>WidthReg</pValue>
646    <pMin>WidthMin</pMin>
647    <pMax>WidthMaxNow</pMax>
648  </Integer>
649  <IntReg Name="WidthReg"><Address>0x20000</Address><Length>4</Length><AccessMode>RW</AccessMode><pPort>Device</pPort><pInvalidator>BinningHorizontal</pInvalidator><Sign>Unsigned</Sign><Endianess>BigEndian</Endianess></IntReg>
650  <IntSwissKnife Name="WidthMaxNow">
651    <pVariable Name="WMAX">WidthMax</pVariable>
652    <pVariable Name="OX">OffsetXReg</pVariable>
653    <Formula>WMAX - OX</Formula>
654  </IntSwissKnife>
655  <IntReg Name="WidthMin"><Address>0x20100</Address><Length>4</Length><AccessMode>RO</AccessMode><pPort>Device</pPort><Sign>Unsigned</Sign><Endianess>BigEndian</Endianess></IntReg>
656  <IntReg Name="WidthMax"><Address>0x20104</Address><Length>4</Length><AccessMode>RO</AccessMode><pPort>Device</pPort><pInvalidator>BinningHorizontal</pInvalidator><Sign>Unsigned</Sign><Endianess>BigEndian</Endianess></IntReg>
657
658  <Integer Name="Height" NameSpace="Standard">
659    <ToolTip>Height of the image in pixels</ToolTip>
660    <pIsLocked>TLParamsLocked</pIsLocked>
661    <pInvalidator>BinningVertical</pInvalidator>
662    <Streamable>Yes</Streamable>
663    <pValue>HeightReg</pValue>
664    <pMin>HeightMin</pMin>
665    <pMax>HeightMaxNow</pMax>
666  </Integer>
667  <IntReg Name="HeightReg"><Address>0x20004</Address><Length>4</Length><AccessMode>RW</AccessMode><pPort>Device</pPort><pInvalidator>BinningVertical</pInvalidator><Sign>Unsigned</Sign><Endianess>BigEndian</Endianess></IntReg>
668  <IntSwissKnife Name="HeightMaxNow">
669    <pVariable Name="HMAX">HeightMax</pVariable>
670    <pVariable Name="OY">OffsetYReg</pVariable>
671    <Formula>HMAX - OY</Formula>
672  </IntSwissKnife>
673  <IntReg Name="HeightMin"><Address>0x20108</Address><Length>4</Length><AccessMode>RO</AccessMode><pPort>Device</pPort><Sign>Unsigned</Sign><Endianess>BigEndian</Endianess></IntReg>
674  <IntReg Name="HeightMax"><Address>0x2010c</Address><Length>4</Length><AccessMode>RO</AccessMode><pPort>Device</pPort><pInvalidator>BinningVertical</pInvalidator><Sign>Unsigned</Sign><Endianess>BigEndian</Endianess></IntReg>
675
676  <Integer Name="OffsetX" NameSpace="Standard">
677    <ToolTip>Horizontal offset from the sensor origin</ToolTip>
678    <pInvalidator>BinningHorizontal</pInvalidator>
679    <Streamable>Yes</Streamable>
680    <pValue>OffsetXReg</pValue>
681    <Min>0</Min>
682    <pMax>OffsetXMax</pMax>
683  </Integer>
684  <IntReg Name="OffsetXReg"><Address>0x2000c</Address><Length>4</Length><AccessMode>RW</AccessMode><pPort>Device</pPort><pInvalidator>BinningHorizontal</pInvalidator><Sign>Unsigned</Sign><Endianess>BigEndian</Endianess></IntReg>
685
686  <Integer Name="OffsetY" NameSpace="Standard">
687    <ToolTip>Vertical offset from the sensor origin</ToolTip>
688    <pInvalidator>BinningVertical</pInvalidator>
689    <Streamable>Yes</Streamable>
690    <pValue>OffsetYReg</pValue>
691    <Min>0</Min>
692    <pMax>OffsetYMax</pMax>
693  </Integer>
694  <IntReg Name="OffsetYReg"><Address>0x20010</Address><Length>4</Length><AccessMode>RW</AccessMode><pPort>Device</pPort><pInvalidator>BinningVertical</pInvalidator><Sign>Unsigned</Sign><Endianess>BigEndian</Endianess></IntReg>
695
696  <IntSwissKnife Name="OffsetXMax">
697    <pVariable Name="WMAX">WidthMax</pVariable>
698    <pVariable Name="W">WidthReg</pVariable>
699    <Formula>WMAX - W</Formula>
700  </IntSwissKnife>
701  <IntSwissKnife Name="OffsetYMax">
702    <pVariable Name="HMAX">HeightMax</pVariable>
703    <pVariable Name="H">HeightReg</pVariable>
704    <Formula>HMAX - H</Formula>
705  </IntSwissKnife>
706
707  <Integer Name="BinningHorizontal" NameSpace="Standard">
708    <ToolTip>Pixels combined horizontally</ToolTip>
709    <Streamable>Yes</Streamable>
710    <pValue>BinningHorizontalReg</pValue>
711    <Min>1</Min>
712    <Max>4</Max>
713  </Integer>
714  <IntReg Name="BinningHorizontalReg"><Address>0x200e4</Address><Length>4</Length><AccessMode>RW</AccessMode><pPort>Device</pPort><Sign>Unsigned</Sign><Endianess>BigEndian</Endianess></IntReg>
715  <Integer Name="BinningVertical" NameSpace="Standard">
716    <ToolTip>Pixels combined vertically</ToolTip>
717    <Streamable>Yes</Streamable>
718    <pValue>BinningVerticalReg</pValue>
719    <Min>1</Min>
720    <Max>4</Max>
721  </Integer>
722  <IntReg Name="BinningVerticalReg"><Address>0x200e8</Address><Length>4</Length><AccessMode>RW</AccessMode><pPort>Device</pPort><Sign>Unsigned</Sign><Endianess>BigEndian</Endianess></IntReg>
723
724  <Enumeration Name="SensorType" NameSpace="Standard">
725    <ToolTip>Sensor variant (Monochrome / BayerRG / Color). On real hardware this would be read-only sensor metadata; here it is RW so tests can reconfigure the simulator.</ToolTip>
726    <EnumEntry Name="Monochrome"><Value>0</Value></EnumEntry>
727    <EnumEntry Name="BayerRG"><Value>1</Value></EnumEntry>
728    <EnumEntry Name="Color"><Value>2</Value></EnumEntry>
729    <pValue>SensorTypeReg</pValue>
730  </Enumeration>
731  <IntReg Name="SensorTypeReg"><Address>0x20058</Address><Length>4</Length><AccessMode>RW</AccessMode><pPort>Device</pPort><Sign>Unsigned</Sign><Endianess>BigEndian</Endianess></IntReg>
732
733  <Enumeration Name="PixelFormat" NameSpace="Standard">
734    <ToolTip>Format of the pixel data — entries are gated by SensorType</ToolTip>
735    <pIsLocked>TLParamsLocked</pIsLocked>
736    <Streamable>Yes</Streamable>
737    <EnumEntry Name="Mono8" NameSpace="Standard">
738      <pIsImplemented>PfMono8Avail</pIsImplemented>
739      <Value>0x01080001</Value>
740    </EnumEntry>
741    <EnumEntry Name="Mono16" NameSpace="Standard">
742      <pIsImplemented>PfMono16Avail</pIsImplemented>
743      <Value>0x01100007</Value>
744    </EnumEntry>
745    <EnumEntry Name="RGB8" NameSpace="Standard">
746      <pIsImplemented>PfRGB8Avail</pIsImplemented>
747      <Value>0x02180014</Value>
748    </EnumEntry>
749    <EnumEntry Name="BayerRG8" NameSpace="Standard">
750      <pIsImplemented>PfBayerRG8Avail</pIsImplemented>
751      <Value>0x01080009</Value>
752    </EnumEntry>
753    <pValue>PixelFormatReg</pValue>
754  </Enumeration>
755  <IntReg Name="PixelFormatReg"><Address>0x20008</Address><Length>4</Length><AccessMode>RW</AccessMode><pPort>Device</pPort><Sign>Unsigned</Sign><Endianess>BigEndian</Endianess></IntReg>
756
757  <!-- PixelFormat entry availability driven by SensorType:
758         Monochrome (0) → Mono8, Mono16
759         BayerRG    (1) → BayerRG8
760         Color      (2) → RGB8 -->
761  <IntSwissKnife Name="PfMono8Avail">
762    <pVariable Name="ST">SensorTypeReg</pVariable>
763    <Formula>ST = 0</Formula>
764  </IntSwissKnife>
765  <IntSwissKnife Name="PfMono16Avail">
766    <pVariable Name="ST">SensorTypeReg</pVariable>
767    <Formula>ST = 0</Formula>
768  </IntSwissKnife>
769  <IntSwissKnife Name="PfBayerRG8Avail">
770    <pVariable Name="ST">SensorTypeReg</pVariable>
771    <Formula>ST = 1</Formula>
772  </IntSwissKnife>
773  <IntSwissKnife Name="PfRGB8Avail">
774    <pVariable Name="ST">SensorTypeReg</pVariable>
775    <Formula>ST = 2</Formula>
776  </IntSwissKnife>
777
778  <!-- ════════════════════════════════════════════════════════════════════
779       Device capability inquiry bits
780
781       Real inquiry blocks are addressed as `<pAddress>` (the block base) plus
782       a fixed `<Address>` offset, and the individual bits come from a
783       <StructReg>. Both terms contribute: keeping only one reads the wrong
784       register, which is what made issue #35's camera misreport every
785       capability it had.
786       ════════════════════════════════════════════════════════════════════ -->
787  <IntSwissKnife Name="DeviceRegBaseAddress">
788    <Formula>0x20000</Formula>
789  </IntSwissKnife>
790  <StructReg Comment="Device capability inquiry">
791    <pAddress>DeviceRegBaseAddress</pAddress>
792    <Address>0x5C</Address>
793    <Length>4</Length>
794    <AccessMode>RO</AccessMode>
795    <pPort>Device</pPort>
796    <Endianess>BigEndian</Endianess>
797    <StructEntry Name="FrameRateControlInq_Bit"><Bit>0</Bit></StructEntry>
798    <StructEntry Name="ChunkSupportInq_Bit"><Bit>1</Bit></StructEntry>
799    <StructEntry Name="SequencerInq_Bit"><Bit>2</Bit></StructEntry>
800  </StructReg>
801
802  <!-- ════════════════════════════════════════════════════════════════════
803       GigE Vision stream channel registers
804
805       Stream channel N lives at 0x0D00 + N * 0x40, so the packet size
806       register is a fixed <Address> plus a <pIndex> scaled by the channel
807       stride. Ignoring the <pIndex> term always addresses channel 0.
808       ════════════════════════════════════════════════════════════════════ -->
809  <Integer Name="GevStreamChannelSelector" NameSpace="Standard">
810    <ToolTip>Stream channel the GevSCP* features address</ToolTip>
811    <pValue>GevStreamChannelSelectorReg</pValue>
812    <Min>0</Min>
813    <Max>1</Max>
814  </Integer>
815  <IntReg Name="GevStreamChannelSelectorReg"><Address>0x20090</Address><Length>4</Length><AccessMode>RW</AccessMode><pPort>Device</pPort><Sign>Unsigned</Sign><Endianess>BigEndian</Endianess></IntReg>
816  <Integer Name="GevSCPSPacketSize" NameSpace="Standard">
817    <ToolTip>Stream channel packet size in bytes</ToolTip>
818    <pValue>GevSCPSPacketSizeReg</pValue>
819    <Min>0</Min>
820    <Max>65535</Max>
821  </Integer>
822  <!-- The size is the low 16 bits; bit 30, do-not-fragment, is stored
823       above it, so the size is a masked field, as the corpus declares it
824       (the Manta G-125B's RegSCPSPacketSize: LSB 31, MSB 16). -->
825  <MaskedIntReg Name="GevSCPSPacketSizeReg">
826    <Address>0x0D04</Address>
827    <pIndex Offset="0x40">GevStreamChannelSelector</pIndex>
828    <Length>4</Length><AccessMode>RW</AccessMode><pPort>Device</pPort>
829    <LSB>31</LSB><MSB>16</MSB><Sign>Unsigned</Sign><Endianess>BigEndian</Endianess>
830  </MaskedIntReg>
831
832  <!-- ════════════════════════════════════════════════════════════════════
833       Acquisition Control Features
834       ════════════════════════════════════════════════════════════════════ -->
835
836  <Enumeration Name="AcquisitionMode" NameSpace="Standard">
837    <ToolTip>Camera acquisition mode</ToolTip>
838    <Streamable>Yes</Streamable>
839    <EnumEntry Name="Continuous"><Value>0</Value></EnumEntry>
840    <EnumEntry Name="SingleFrame"><Value>1</Value></EnumEntry>
841    <EnumEntry Name="MultiFrame"><Value>2</Value></EnumEntry>
842    <pValue>AcquisitionModeReg</pValue>
843  </Enumeration>
844  <IntReg Name="AcquisitionModeReg"><Address>0x20020</Address><Length>4</Length><AccessMode>RW</AccessMode><pPort>Device</pPort><Sign>Unsigned</Sign><Endianess>BigEndian</Endianess></IntReg>
845
846  <!-- Every <Command> here reaches its register through <pValue>, the shape
847       all 490 commands in the vendor corpus use; none has an <Address> of its
848       own (backlog GA-10). -->
849  <Command Name="AcquisitionStart" NameSpace="Standard">
850    <ToolTip>Start image acquisition</ToolTip>
851    <pValue>AcquisitionStartReg</pValue>
852    <CommandValue>1</CommandValue>
853  </Command>
854  <IntReg Name="AcquisitionStartReg"><Address>0x20024</Address><Length>4</Length><AccessMode>WO</AccessMode><pPort>Device</pPort><Sign>Unsigned</Sign><Endianess>BigEndian</Endianess></IntReg>
855
856  <!-- The Hikrobot MV-CS050-10GC user-set block (Hikrobot_MV-CS050-10GC.xml,
857       lines 23009-23148): both commands write the selected set's index,
858       taken through <pCommandValue> from the selector register, and saving is
859       unavailable while Default is selected. -->
860  <Enumeration Name="UserSetSelector" NameSpace="Standard">
861    <ToolTip>User set that UserSetLoad and UserSetSave act on</ToolTip>
862    <EnumEntry Name="Default"><Value>0</Value></EnumEntry>
863    <EnumEntry Name="UserSet1"><Value>1</Value></EnumEntry>
864    <EnumEntry Name="UserSet2"><Value>2</Value></EnumEntry>
865    <pValue>UserSetSelectorReg</pValue>
866    <pSelected>UserSetLoad</pSelected>
867    <pSelected>UserSetSave</pSelected>
868  </Enumeration>
869  <IntReg Name="UserSetSelectorReg"><Address>0x200a8</Address><Length>4</Length><AccessMode>RW</AccessMode><pPort>Device</pPort><Sign>Unsigned</Sign><Endianess>BigEndian</Endianess></IntReg>
870
871  <Command Name="UserSetLoad" NameSpace="Standard">
872    <ToolTip>Load the selected user set</ToolTip>
873    <ImposedAccessMode>WO</ImposedAccessMode>
874    <pValue>UserSetLoadReg</pValue>
875    <pCommandValue>UserSetLoad_CmdValue</pCommandValue>
876  </Command>
877  <IntSwissKnife Name="UserSetLoad_CmdValue">
878    <pVariable Name="VALUE">UserSetSelectorReg</pVariable>
879    <Formula>VALUE</Formula>
880  </IntSwissKnife>
881  <IntReg Name="UserSetLoadReg"><Address>0x200ac</Address><Length>4</Length><AccessMode>WO</AccessMode><pPort>Device</pPort><Sign>Unsigned</Sign><Endianess>BigEndian</Endianess></IntReg>
882
883  <Command Name="UserSetSave" NameSpace="Standard">
884    <ToolTip>Save the current settings into the selected user set</ToolTip>
885    <pIsAvailable>UserSetSaveAvailable</pIsAvailable>
886    <ImposedAccessMode>WO</ImposedAccessMode>
887    <pValue>UserSetSaveReg</pValue>
888    <pCommandValue>UserSetSave_CmdValue</pCommandValue>
889  </Command>
890  <IntSwissKnife Name="UserSetSave_CmdValue">
891    <pVariable Name="VALUE">UserSetSelectorReg</pVariable>
892    <Formula>VALUE</Formula>
893  </IntSwissKnife>
894  <IntSwissKnife Name="UserSetSaveAvailable">
895    <pVariable Name="VAL">UserSetSelectorReg</pVariable>
896    <Formula>(VAL = 0)? 0:1</Formula>
897  </IntSwissKnife>
898  <IntReg Name="UserSetSaveReg"><Address>0x200b4</Address><Length>4</Length><AccessMode>WO</AccessMode><pPort>Device</pPort><Sign>Unsigned</Sign><Endianess>BigEndian</Endianess></IntReg>
899
900  <!-- profile:user-set-default -->
901  <Enumeration Name="UserSetDefault" NameSpace="Standard">
902    <ToolTip>User set loaded at power-up</ToolTip>
903    <EnumEntry Name="Default"><Value>0</Value></EnumEntry>
904    <EnumEntry Name="UserSet1"><Value>1</Value></EnumEntry>
905    <EnumEntry Name="UserSet2"><Value>2</Value></EnumEntry>
906    <pValue>UserSetDefaultReg</pValue>
907  </Enumeration>
908  <!-- /profile:user-set-default -->
909  <IntReg Name="UserSetDefaultReg"><Address>0x200ec</Address><Length>4</Length><AccessMode>RW</AccessMode><pPort>Device</pPort><Sign>Unsigned</Sign><Endianess>BigEndian</Endianess></IntReg>
910
911  <!-- Triggers, as the Basler acA1600 and Hikrobot documents shape them: the
912       selector's value indexes the mode and source registers. -->
913  <Enumeration Name="TriggerSelector" NameSpace="Standard">
914    <ToolTip>Trigger that TriggerMode, TriggerSource and TriggerSoftware act on</ToolTip>
915    <Streamable>Yes</Streamable>
916    <EnumEntry Name="FrameStart"><Value>0</Value></EnumEntry>
917    <EnumEntry Name="AcquisitionStart"><Value>1</Value></EnumEntry>
918    <pValue>TriggerSelectorReg</pValue>
919    <pSelected>TriggerMode</pSelected>
920    <pSelected>TriggerSource</pSelected>
921    <pSelected>TriggerSoftware</pSelected>
922  </Enumeration>
923  <IntReg Name="TriggerSelectorReg"><Address>0x200c0</Address><Length>4</Length><AccessMode>RW</AccessMode><pPort>Device</pPort><Sign>Unsigned</Sign><Endianess>BigEndian</Endianess></IntReg>
924  <Enumeration Name="TriggerMode" NameSpace="Standard">
925    <ToolTip>Whether the selected trigger is active</ToolTip>
926    <Streamable>Yes</Streamable>
927    <EnumEntry Name="Off"><Value>0</Value></EnumEntry>
928    <EnumEntry Name="On"><Value>1</Value></EnumEntry>
929    <pValue>TriggerModeReg</pValue>
930  </Enumeration>
931  <IntReg Name="TriggerModeReg">
932    <Address>0x200c4</Address>
933    <pIndex Offset="4">TriggerSelectorReg</pIndex>
934    <Length>4</Length><AccessMode>RW</AccessMode><pPort>Device</pPort><Sign>Unsigned</Sign><Endianess>BigEndian</Endianess>
935  </IntReg>
936  <Enumeration Name="TriggerSource" NameSpace="Standard">
937    <ToolTip>Signal the selected trigger waits for</ToolTip>
938    <Streamable>Yes</Streamable>
939    <EnumEntry Name="Line1"><Value>0</Value></EnumEntry>
940    <EnumEntry Name="Software"><Value>1</Value></EnumEntry>
941    <pValue>TriggerSourceReg</pValue>
942  </Enumeration>
943  <IntReg Name="TriggerSourceReg">
944    <Address>0x200d0</Address>
945    <pIndex Offset="4">TriggerSelectorReg</pIndex>
946    <Length>4</Length><AccessMode>RW</AccessMode><pPort>Device</pPort><Sign>Unsigned</Sign><Endianess>BigEndian</Endianess>
947  </IntReg>
948  <Command Name="TriggerSoftware" NameSpace="Standard">
949    <ToolTip>Fire the selected trigger once</ToolTip>
950    <pValue>TriggerSoftwareReg</pValue>
951    <CommandValue>1</CommandValue>
952  </Command>
953  <IntReg Name="TriggerSoftwareReg"><Address>0x200e0</Address><Length>4</Length><AccessMode>WO</AccessMode><pPort>Device</pPort><Sign>Unsigned</Sign><Endianess>BigEndian</Endianess></IntReg>
954
955  <!-- A write-only register addressed bit by bit. Each entry inherits WO from
956       the StructReg, so setting one bit cannot read the register for the
957       others: the device refuses the read (backlog GA-31, issue #135). -->
958  <StructReg Comment="Software signal pulse">
959    <Address>0x200b0</Address>
960    <Length>4</Length>
961    <AccessMode>WO</AccessMode>
962    <pPort>Device</pPort>
963    <Endianess>BigEndian</Endianess>
964    <StructEntry Name="SoftwareSignal0Pulse"><Bit>0</Bit></StructEntry>
965    <StructEntry Name="SoftwareSignal1Pulse"><Bit>1</Bit></StructEntry>
966  </StructReg>
967
968  <Command Name="AcquisitionStop" NameSpace="Standard">
969    <ToolTip>Stop image acquisition</ToolTip>
970    <pValue>AcquisitionStopReg</pValue>
971    <CommandValue>1</CommandValue>
972  </Command>
973  <IntReg Name="AcquisitionStopReg"><Address>0x20028</Address><Length>4</Length><AccessMode>WO</AccessMode><pPort>Device</pPort><Sign>Unsigned</Sign><Endianess>BigEndian</Endianess></IntReg>
974
975  <Boolean Name="AcquisitionFrameRateEnable" NameSpace="Standard">
976    <ToolTip>Enable manual control of AcquisitionFrameRate. When false, the frame rate is unavailable for read/write.</ToolTip>
977    <Streamable>Yes</Streamable>
978    <pValue>AcquisitionFrameRateEnableReg</pValue>
979  </Boolean>
980  <IntReg Name="AcquisitionFrameRateEnableReg">
981    <pIsImplemented>FrameRateControlInq_Bit</pIsImplemented>
982    <Address>0x20054</Address><Length>4</Length><AccessMode>RW</AccessMode><pPort>Device</pPort><Sign>Unsigned</Sign><Endianess>BigEndian</Endianess>
983  </IntReg>
984
985  <!-- profile:frame-rate -->
986  <Float Name="AcquisitionFrameRate" NameSpace="Standard">
987    <ToolTip>Target frame rate in Hz</ToolTip>
988    <pIsAvailable>AcquisitionFrameRateEnable</pIsAvailable>
989    <Streamable>Yes</Streamable>
990    <pValue>AcquisitionFrameRateReg</pValue>
991    <Min>1.0</Min>
992    <Max>120.0</Max>
993    <Unit>Hz</Unit>
994  </Float>
995  <FloatReg Name="AcquisitionFrameRateReg"><Address>0x2002c</Address><Length>4</Length><AccessMode>RW</AccessMode><pPort>Device</pPort><Endianess>BigEndian</Endianess></FloatReg>
996  <!-- /profile:frame-rate -->
997
998  <!-- profile:exposure -->
999  <Float Name="ExposureTime" NameSpace="Standard">
1000    <ToolTip>Exposure time in microseconds — locked to RO when ExposureAuto is not Off</ToolTip>
1001    <pIsImplemented>ExposureTime_Imp</pIsImplemented>
1002    <pIsAvailable>ExposureTime_Avl</pIsAvailable>
1003    <pIsLocked>ExposureAutoActive</pIsLocked>
1004    <Streamable>Yes</Streamable>
1005    <pValue>ExposureTimeReg</pValue>
1006    <Min>10.0</Min>
1007    <Max>1000000.0</Max>
1008    <Unit>us</Unit>
1009  </Float>
1010  <!-- /profile:exposure -->
1011  <!-- The FLIR shape: the register, not the feature, carries <pInvalidator>,
1012       and it names the command's pValue register rather than the command. So
1013       executing UserSetLoad writes UserSetLoadReg, which marks this register
1014       stale, which marks ExposureTime stale through its <pValue> (GA-24). -->
1015  <FloatReg Name="ExposureTimeReg">
1016    <Address>0x20030</Address>
1017    <Length>8</Length>
1018    <AccessMode>RW</AccessMode>
1019    <pPort>Device</pPort>
1020    <pInvalidator>UserSetLoadReg</pInvalidator>
1021    <Endianess>BigEndian</Endianess>
1022  </FloatReg>
1023
1024  <!-- Feature-status bits in one big-endian word, the shape FLIR ships and the
1025       shape that exposed issue #120. GenICam counts <Bit> from the MSB here, so
1026       bit 0 is 0x80000000 and bit 1 is 0x40000000; the fake boots this register
1027       to 0xC0000000. Read from the wrong end these both come out zero and
1028       ExposureTime becomes unavailable, which is what the reporter saw. -->
1029  <MaskedIntReg Name="ExposureTime_Imp">
1030    <Address>0x2009c</Address><Length>4</Length><AccessMode>RO</AccessMode><pPort>Device</pPort>
1031    <Bit>0</Bit><Sign>Unsigned</Sign><Endianess>BigEndian</Endianess>
1032  </MaskedIntReg>
1033  <MaskedIntReg Name="ExposureTime_Avl">
1034    <Address>0x2009c</Address><Length>4</Length><AccessMode>RO</AccessMode><pPort>Device</pPort>
1035    <Bit>1</Bit><Sign>Unsigned</Sign><Endianess>BigEndian</Endianess>
1036  </MaskedIntReg>
1037
1038  <Enumeration Name="ExposureAuto" NameSpace="Standard">
1039    <ToolTip>Automatic exposure control</ToolTip>
1040    <Streamable>Yes</Streamable>
1041    <EnumEntry Name="Off"><Value>0</Value></EnumEntry>
1042    <EnumEntry Name="Once"><Value>1</Value></EnumEntry>
1043    <EnumEntry Name="Continuous"><Value>2</Value></EnumEntry>
1044    <pValue>ExposureAutoReg</pValue>
1045  </Enumeration>
1046  <IntReg Name="ExposureAutoReg"><Address>0x20038</Address><Length>4</Length><AccessMode>RW</AccessMode><pPort>Device</pPort><Sign>Unsigned</Sign><Endianess>BigEndian</Endianess></IntReg>
1047
1048  <IntSwissKnife Name="ExposureAutoActive">
1049    <pVariable Name="EA">ExposureAutoReg</pVariable>
1050    <Formula>EA &lt;&gt; 0</Formula>
1051  </IntSwissKnife>
1052
1053  <!-- ════════════════════════════════════════════════════════════════════
1054       Analog Control Features
1055       ════════════════════════════════════════════════════════════════════ -->
1056
1057  <!-- profile:gain -->
1058  <Float Name="Gain" NameSpace="Standard">
1059    <!-- CDATA-wrapped tooltip, as shipped by several vendors: the literal `&`
1060         and `<` inside are legal here and must survive parsing (issue #45). -->
1061    <ToolTip><![CDATA[Gain applied to the image in dB — locked to RO when GainAuto is not Off (0 < gain & gain < 48)]]></ToolTip>
1062    <pIsLocked>GainAutoActive</pIsLocked>
1063    <Streamable>Yes</Streamable>
1064    <pValue>GainReg</pValue>
1065    <Min>0.0</Min>
1066    <Max>48.0</Max>
1067  </Float>
1068  <FloatReg Name="GainReg"><Address>0x20040</Address><Length>8</Length><AccessMode>RW</AccessMode><pPort>Device</pPort><Endianess>BigEndian</Endianess></FloatReg>
1069  <!-- /profile:gain -->
1070
1071  <Enumeration Name="GainAuto" NameSpace="Standard">
1072    <ToolTip>Automatic gain control</ToolTip>
1073    <Streamable>Yes</Streamable>
1074    <EnumEntry Name="Off"><Value>0</Value></EnumEntry>
1075    <EnumEntry Name="Once"><Value>1</Value></EnumEntry>
1076    <EnumEntry Name="Continuous"><Value>2</Value></EnumEntry>
1077    <pValue>GainAutoReg</pValue>
1078  </Enumeration>
1079  <IntReg Name="GainAutoReg"><Address>0x20048</Address><Length>4</Length><AccessMode>RW</AccessMode><pPort>Device</pPort><Sign>Unsigned</Sign><Endianess>BigEndian</Endianess></IntReg>
1080
1081  <IntSwissKnife Name="GainAutoActive">
1082    <pVariable Name="GA">GainAutoReg</pVariable>
1083    <Formula>GA &lt;&gt; 0</Formula>
1084  </IntSwissKnife>
1085
1086  <Integer Name="BlackLevel" NameSpace="Standard">
1087    <ToolTip>Analog black level offset</ToolTip>
1088    <Streamable>Yes</Streamable>
1089    <pValue>BlackLevelReg</pValue>
1090    <Min>0</Min>
1091    <Max>255</Max>
1092  </Integer>
1093  <IntReg Name="BlackLevelReg"><Address>0x20050</Address><Length>4</Length><AccessMode>RW</AccessMode><pPort>Device</pPort><Sign>Unsigned</Sign><Endianess>BigEndian</Endianess></IntReg>
1094
1095  <!-- ════════════════════════════════════════════════════════════════════
1096       Transport Layer Control (Timestamp)
1097       ════════════════════════════════════════════════════════════════════ -->
1098
1099  <!-- SFNC's PayloadSize: what a host sizes its buffers by, computed by the
1100       device from the format and the chunks, and so never cached. -->
1101  <Integer Name="PayloadSize" NameSpace="Standard">
1102    <ToolTip>Bytes of one block's payload: the image, and its chunks in chunk mode</ToolTip>
1103    <ImposedAccessMode>RO</ImposedAccessMode>
1104    <pValue>PayloadSizeReg</pValue>
1105  </Integer>
1106  <IntReg Name="PayloadSizeReg"><Address>0x20120</Address><Length>4</Length><AccessMode>RO</AccessMode><pPort>Device</pPort><Cachable>NoCache</Cachable><Sign>Unsigned</Sign><Endianess>BigEndian</Endianess></IntReg>
1107
1108  <!-- A variable the host sets while it streams, with no register behind
1109       it: FLIR, Basler and Hikrobot declare it so (27 corpus documents use an
1110       Integer). -->
1111  <!-- profile:tl-params-locked -->
1112  <Integer Name="TLParamsLocked">
1113    <ToolTip>Indicates whether a live grab is under way</ToolTip>
1114    <Visibility>Invisible</Visibility>
1115    <Value>0</Value>
1116    <Min>0</Min>
1117    <Max>1</Max>
1118  </Integer>
1119  <!-- /profile:tl-params-locked -->
1120
1121  <IntReg Name="GevTimestampTickFrequency" NameSpace="Standard">
1122    <ToolTip>Device timestamp tick frequency in Hz (1 GHz)</ToolTip>
1123    <Address>0x20060</Address>
1124    <Length>4</Length>
1125    <AccessMode>RO</AccessMode>
1126    <pPort>Device</pPort>
1127    <Sign>Unsigned</Sign>
1128    <Endianess>BigEndian</Endianess>
1129  </IntReg>
1130
1131  <!-- An Integer over an IntReg, as every timestamp in the vendor corpus is
1132       declared, and with nothing linking it to the latch: the cache holds the
1133       reading in the register node. -->
1134  <Integer Name="GevTimestampValue" NameSpace="Standard">
1135    <ToolTip>Current device timestamp in ticks (latched)</ToolTip>
1136    <pValue>GevTimestampValueReg</pValue>
1137  </Integer>
1138  <IntReg Name="GevTimestampValueReg">
1139    <Address>0x20068</Address>
1140    <Length>8</Length>
1141    <AccessMode>RO</AccessMode>
1142    <pPort>Device</pPort>
1143    <Sign>Unsigned</Sign>
1144    <Endianess>BigEndian</Endianess>
1145  </IntReg>
1146
1147  <IntReg Name="GevIEEE1588OffsetFromMasterLatched_Val" NameSpace="Custom">
1148    <ToolTip>PTP offset from master in ns, latched</ToolTip>
1149    <Address>0x20078</Address>
1150    <Length>8</Length>
1151    <AccessMode>RO</AccessMode>
1152    <pPort>Device</pPort>
1153    <Sign>Unsigned</Sign>
1154    <Endianess>BigEndian</Endianess>
1155  </IntReg>
1156
1157  <IntReg Name="ChunkTimestamp_Val" NameSpace="Custom">
1158    <ToolTip>Chunk timestamp in ticks</ToolTip>
1159    <Address>0x20110</Address>
1160    <Length>8</Length>
1161    <AccessMode>RO</AccessMode>
1162    <pPort>Device</pPort>
1163    <Sign>Unsigned</Sign>
1164    <Endianess>LittleEndian</Endianess>
1165  </IntReg>
1166
1167  <IntReg Name="ChunkWidth_Val" NameSpace="Custom">
1168    <ToolTip>Chunk image width in pixels</ToolTip>
1169    <Address>0x20118</Address>
1170    <Length>4</Length>
1171    <AccessMode>RO</AccessMode>
1172    <pPort>Device</pPort>
1173    <Sign>Unsigned</Sign>
1174    <Endianess>LittleEndian</Endianess>
1175  </IntReg>
1176
1177  <Command Name="TimestampLatch" NameSpace="Standard">
1178    <ToolTip>Latch the current timestamp into GevTimestampValue</ToolTip>
1179    <pValue>TimestampLatchReg</pValue>
1180    <CommandValue>1</CommandValue>
1181  </Command>
1182  <IntReg Name="TimestampLatchReg"><Address>0x20070</Address><Length>4</Length><AccessMode>WO</AccessMode><pPort>Device</pPort><Sign>Unsigned</Sign><Endianess>BigEndian</Endianess></IntReg>
1183
1184  <!-- ════════════════════════════════════════════════════════════════════
1185       Chunk Data Control
1186       ════════════════════════════════════════════════════════════════════ -->
1187
1188  <!-- SFNC defines ChunkModeActive and ChunkEnable as IBoolean, and all 23
1189       vendor-corpus documents that declare ChunkModeActive use <Boolean> over
1190       a backing <IntReg> - none uses <Integer>. Declaring them as <Integer>
1191       here made Camera::configure_chunks, which correctly calls set_bool,
1192       fail against the only camera we can test with. -->
1193  <Boolean Name="ChunkModeActive" NameSpace="Standard">
1194    <ToolTip>Enable chunk data in image frames</ToolTip>
1195    <Streamable>Yes</Streamable>
1196    <pValue>ChunkModeActiveReg</pValue>
1197  </Boolean>
1198  <IntReg Name="ChunkModeActiveReg"><Address>0x20080</Address><Length>4</Length><AccessMode>RW</AccessMode><pPort>Device</pPort><Sign>Unsigned</Sign><Endianess>BigEndian</Endianess></IntReg>
1199
1200  <Enumeration Name="ChunkSelector" NameSpace="Standard">
1201    <ToolTip>Select which chunk feature to configure</ToolTip>
1202    <EnumEntry Name="Timestamp"><Value>1</Value></EnumEntry>
1203    <EnumEntry Name="ExposureTime"><Value>2</Value></EnumEntry>
1204    <EnumEntry Name="Gain"><Value>3</Value></EnumEntry>
1205    <EnumEntry Name="FrameID"><Value>4</Value></EnumEntry>
1206    <EnumEntry Name="ImageInfo" NameSpace="Custom"><Value>5</Value></EnumEntry>
1207    <pValue>ChunkSelectorReg</pValue>
1208  </Enumeration>
1209  <IntReg Name="ChunkSelectorReg"><Address>0x20084</Address><Length>4</Length><AccessMode>RW</AccessMode><pPort>Device</pPort><Sign>Unsigned</Sign><Endianess>BigEndian</Endianess></IntReg>
1210
1211  <Boolean Name="ChunkEnable" NameSpace="Standard">
1212    <ToolTip>Enable the selected chunk feature</ToolTip>
1213    <pValue>ChunkEnableReg</pValue>
1214  </Boolean>
1215  <IntReg Name="ChunkEnableReg"><Address>0x20088</Address><Length>4</Length><AccessMode>RW</AccessMode><pPort>Device</pPort><Sign>Unsigned</Sign><Endianess>BigEndian</Endianess></IntReg>
1216
1217  <!-- Chunk ports (GenICam Standard v2.1.1 §2.8.16): each register below
1218       addresses one chunk of a frame, from the chunk's start, not device
1219       memory. The shapes are the corpus's: FLIR declares its chunk values
1220       little-endian at offset 0 of their own chunks; Baumer's HXG20 reads
1221       ChunkImageLength at address -4, "offset from the back of the chunk". -->
1222  <Port Name="ChunkImagePort" NameSpace="Custom"><ChunkID>00000001</ChunkID></Port>
1223  <Port Name="ChunkTimestampPort" NameSpace="Custom"><ChunkID>00000002</ChunkID></Port>
1224  <Port Name="ChunkExposureTimePort" NameSpace="Custom"><ChunkID>00000003</ChunkID></Port>
1225  <Port Name="ChunkFrameIDPort" NameSpace="Custom"><ChunkID>05040003</ChunkID></Port>
1226  <Port Name="ChunkImageInfoPort" NameSpace="Custom"><ChunkID>A5A50100</ChunkID></Port>
1227
1228  <Integer Name="ChunkTimestamp" NameSpace="Standard">
1229    <ToolTip>Timestamp of the image, in ticks</ToolTip>
1230    <ImposedAccessMode>RO</ImposedAccessMode>
1231    <pValue>ChunkTimestampReg</pValue>
1232  </Integer>
1233  <IntReg Name="ChunkTimestampReg"><Address>0x0</Address><Length>8</Length><AccessMode>RO</AccessMode><pPort>ChunkTimestampPort</pPort><Sign>Unsigned</Sign><Endianess>LittleEndian</Endianess></IntReg>
1234
1235  <Float Name="ChunkExposureTime" NameSpace="Standard">
1236    <ToolTip>Exposure time used to capture the image</ToolTip>
1237    <ImposedAccessMode>RO</ImposedAccessMode>
1238    <pValue>ChunkExposureTimeReg</pValue>
1239    <Unit>us</Unit>
1240  </Float>
1241  <FloatReg Name="ChunkExposureTimeReg"><Address>0x0</Address><Length>8</Length><AccessMode>RO</AccessMode><pPort>ChunkExposureTimePort</pPort><Endianess>LittleEndian</Endianess></FloatReg>
1242
1243  <Integer Name="ChunkFrameID" NameSpace="Standard">
1244    <ToolTip>Frame id of the image</ToolTip>
1245    <ImposedAccessMode>RO</ImposedAccessMode>
1246    <pValue>ChunkFrameIDReg</pValue>
1247  </Integer>
1248  <IntReg Name="ChunkFrameIDReg"><Address>0x0</Address><Length>8</Length><AccessMode>RO</AccessMode><pPort>ChunkFrameIDPort</pPort><Sign>Unsigned</Sign><Endianess>LittleEndian</Endianess></IntReg>
1249
1250  <Integer Name="ChunkWidth" NameSpace="Standard">
1251    <ImposedAccessMode>RO</ImposedAccessMode>
1252    <pValue>ChunkWidthReg</pValue>
1253  </Integer>
1254  <IntReg Name="ChunkWidthReg"><Address>0x0</Address><Length>4</Length><AccessMode>RO</AccessMode><pPort>ChunkImageInfoPort</pPort><Sign>Unsigned</Sign><Endianess>BigEndian</Endianess></IntReg>
1255
1256  <Integer Name="ChunkHeight" NameSpace="Standard">
1257    <ImposedAccessMode>RO</ImposedAccessMode>
1258    <pValue>ChunkHeightReg</pValue>
1259  </Integer>
1260  <IntReg Name="ChunkHeightReg"><Address>0x4</Address><Length>4</Length><AccessMode>RO</AccessMode><pPort>ChunkImageInfoPort</pPort><Sign>Unsigned</Sign><Endianess>BigEndian</Endianess></IntReg>
1261
1262  <Integer Name="ChunkImageLength" NameSpace="Custom">
1263    <ToolTip>Bytes of image data, read from the end of the ImageInfo chunk</ToolTip>
1264    <ImposedAccessMode>RO</ImposedAccessMode>
1265    <pValue>ChunkImageLengthReg</pValue>
1266  </Integer>
1267  <IntReg Name="ChunkImageLengthReg"><Address>-4</Address><Length>4</Length><AccessMode>RO</AccessMode><pPort>ChunkImageInfoPort</pPort><Sign>Unsigned</Sign><Endianess>BigEndian</Endianess></IntReg>
1268
1269  <!-- Event delivery is selected through GenApi, not through a bootstrap
1270       register: EventSelector picks a GigE Vision event id and
1271       EventNotification turns it on. The ids are the standard ones
1272       (GEV_EVENT_START_OF_TRANSFER = 0x0005, END_OF_TRANSFER = 0x0006). -->
1273  <Enumeration Name="EventSelector" NameSpace="Standard">
1274    <ToolTip>Select which event to configure</ToolTip>
1275    <EnumEntry Name="StartOfTransfer"><Value>5</Value></EnumEntry>
1276    <EnumEntry Name="EndOfTransfer"><Value>6</Value></EnumEntry>
1277    <EnumEntry Name="ExposureEnd"><Value>0x9001</Value></EnumEntry>
1278    <pValue>EventSelectorReg</pValue>
1279  </Enumeration>
1280  <IntReg Name="EventSelectorReg"><Address>0x200A0</Address><Length>4</Length><AccessMode>RW</AccessMode><pPort>Device</pPort><Sign>Unsigned</Sign><Endianess>BigEndian</Endianess></IntReg>
1281
1282  <Enumeration Name="EventNotification" NameSpace="Standard">
1283    <ToolTip>Enable notification for the selected event</ToolTip>
1284    <EnumEntry Name="Off"><Value>0</Value></EnumEntry>
1285    <EnumEntry Name="On"><Value>1</Value></EnumEntry>
1286    <pValue>EventNotificationReg</pValue>
1287  </Enumeration>
1288  <IntReg Name="EventNotificationReg"><Address>0x200A4</Address><Length>4</Length><AccessMode>RW</AccessMode><pPort>Device</pPort><Sign>Unsigned</Sign><Endianess>BigEndian</Endianess></IntReg>
1289
1290  <!-- The ExposureEnd event port: its registers address the event as it was
1291       sent, header included — the event id at 0x2 and the timestamp at 0x8,
1292       where every corpus document puts them, and the frame id in the event
1293       data at 0x10, little-endian, as FLIR declares EventExposureEndFrameID. -->
1294  <Port Name="EventExposureEndPort"><EventID>9001</EventID></Port>
1295  <Integer Name="EventExposureEnd" NameSpace="Standard">
1296    <ImposedAccessMode>RO</ImposedAccessMode>
1297    <pValue>EventExposureEndReg</pValue>
1298  </Integer>
1299  <IntReg Name="EventExposureEndReg"><Address>0x2</Address><Length>2</Length><AccessMode>RO</AccessMode><pPort>EventExposureEndPort</pPort><Sign>Unsigned</Sign><Endianess>BigEndian</Endianess></IntReg>
1300  <Integer Name="EventExposureEndTimestamp" NameSpace="Standard">
1301    <ImposedAccessMode>RO</ImposedAccessMode>
1302    <pValue>EventExposureEndTimestampReg</pValue>
1303  </Integer>
1304  <IntReg Name="EventExposureEndTimestampReg"><Address>0x8</Address><Length>8</Length><AccessMode>RO</AccessMode><pPort>EventExposureEndPort</pPort><Sign>Unsigned</Sign><Endianess>BigEndian</Endianess></IntReg>
1305  <Integer Name="EventExposureEndFrameID" NameSpace="Standard">
1306    <ImposedAccessMode>RO</ImposedAccessMode>
1307    <pValue>EventExposureEndFrameIDReg</pValue>
1308  </Integer>
1309  <IntReg Name="EventExposureEndFrameIDReg"><Address>0x10</Address><Length>8</Length><AccessMode>RO</AccessMode><pPort>EventExposureEndPort</pPort><Sign>Unsigned</Sign><Endianess>LittleEndian</Endianess></IntReg>
1310
1311</RegisterDescription>
1312"#;
1313
1314/// Which GenApi XML the fake serves.
1315#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
1316#[non_exhaustive]
1317pub enum XmlProfile {
1318    /// [`FAKE_XML`]: SFNC 2 names — `ExposureTime`, `Gain`,
1319    /// `AcquisitionFrameRate`, `UserSetDefault` — with `TLParamsLocked` an
1320    /// `<Integer>`.
1321    #[default]
1322    Sfnc,
1323    /// The names older cameras use instead, as the Basler acA1600-20gm
1324    /// declares them (`Basler_acA1600_20gm.xml` in the vendor corpus):
1325    /// `ExposureTimeAbs` with no `ExposureTime`, `GainRaw` (an `<Integer>`
1326    /// per `GainSelector` entry) with no `Gain`, `AcquisitionFrameRateAbs`,
1327    /// `UserSetDefaultSelector`; and `TLParamsLocked` a `<Boolean>` with a
1328    /// `<Value>`, as AVT and Prosilica declare it. Same registers, same
1329    /// behaviour.
1330    Legacy,
1331}
1332
1333/// The legacy profile's replacement for each `<!-- profile:NAME -->` section
1334/// of [`FAKE_XML`].
1335const LEGACY_SECTIONS: &[(&str, &str)] = &[
1336    ("exposure-category", "<pFeature>ExposureTimeAbs</pFeature>"),
1337    (
1338        "exposure",
1339        r#"<Float Name="ExposureTimeAbs" NameSpace="Standard">
1340    <ToolTip>Directly sets the camera's exposure time in microseconds</ToolTip>
1341    <pIsLocked>ExposureAutoActive</pIsLocked>
1342    <pValue>ExposureTimeReg</pValue>
1343    <Min>10.0</Min>
1344    <Max>1000000.0</Max>
1345    <Unit>us</Unit>
1346  </Float>"#,
1347    ),
1348    (
1349        "frame-rate-category",
1350        "<pFeature>AcquisitionFrameRateAbs</pFeature>",
1351    ),
1352    (
1353        "frame-rate",
1354        r#"<Float Name="AcquisitionFrameRateAbs" NameSpace="Standard">
1355    <ToolTip>Acquisition frame rate in frames per second, when enabled</ToolTip>
1356    <pIsAvailable>AcquisitionFrameRateEnable</pIsAvailable>
1357    <pValue>AcquisitionFrameRateAbsReg</pValue>
1358    <Min>1.0</Min>
1359    <Max>120.0</Max>
1360    <Unit>Hz</Unit>
1361  </Float>
1362  <FloatReg Name="AcquisitionFrameRateAbsReg"><Address>0x2002c</Address><Length>4</Length><AccessMode>RW</AccessMode><pPort>Device</pPort><Endianess>BigEndian</Endianess></FloatReg>"#,
1363    ),
1364    (
1365        "gain-category",
1366        "<pFeature>GainSelector</pFeature><pFeature>GainRaw</pFeature>",
1367    ),
1368    (
1369        "gain",
1370        r#"<Enumeration Name="GainSelector" NameSpace="Standard">
1371    <ToolTip>Selects the gain control to configure</ToolTip>
1372    <EnumEntry Name="All"><Value>0</Value></EnumEntry>
1373    <EnumEntry Name="Tap1"><Value>1</Value></EnumEntry>
1374    <EnumEntry Name="Tap2"><Value>2</Value></EnumEntry>
1375    <pValue>GainSelectorReg</pValue>
1376    <pSelected>GainRaw</pSelected>
1377  </Enumeration>
1378  <IntReg Name="GainSelectorReg"><Address>0x200fc</Address><Length>4</Length><AccessMode>RW</AccessMode><pPort>Device</pPort><Sign>Unsigned</Sign><Endianess>BigEndian</Endianess></IntReg>
1379  <Integer Name="GainRaw" NameSpace="Standard">
1380    <ToolTip>Sets the selected gain control in device specific units</ToolTip>
1381    <pIsLocked>GainAutoActive</pIsLocked>
1382    <pValue>GainRawReg</pValue>
1383    <Min>0</Min>
1384    <Max>1023</Max>
1385  </Integer>
1386  <IntReg Name="GainRawReg">
1387    <Address>0x200f0</Address>
1388    <pIndex Offset="4">GainSelectorReg</pIndex>
1389    <Length>4</Length><AccessMode>RW</AccessMode><pPort>Device</pPort><Sign>Unsigned</Sign><Endianess>BigEndian</Endianess>
1390  </IntReg>"#,
1391    ),
1392    (
1393        "user-set-default-category",
1394        "<pFeature>UserSetDefaultSelector</pFeature>",
1395    ),
1396    (
1397        "user-set-default",
1398        r#"<Enumeration Name="UserSetDefaultSelector" NameSpace="Standard">
1399    <ToolTip>Selects the user set loaded at power-up</ToolTip>
1400    <EnumEntry Name="Default"><Value>0</Value></EnumEntry>
1401    <EnumEntry Name="UserSet1"><Value>1</Value></EnumEntry>
1402    <EnumEntry Name="UserSet2"><Value>2</Value></EnumEntry>
1403    <pValue>UserSetDefaultReg</pValue>
1404  </Enumeration>"#,
1405    ),
1406    (
1407        "tl-params-locked",
1408        r#"<Boolean Name="TLParamsLocked" NameSpace="Standard">
1409    <Value>0</Value>
1410    <OnValue>1</OnValue>
1411    <OffValue>0</OffValue>
1412  </Boolean>"#,
1413    ),
1414];
1415
1416/// `GainSelector`'s register in the legacy profile.
1417pub const REG_GAIN_SELECTOR: u64 = 0x200fc;
1418
1419/// The GenApi XML a camera with this profile serves.
1420pub fn genapi_xml(profile: XmlProfile) -> std::borrow::Cow<'static, str> {
1421    match profile {
1422        XmlProfile::Sfnc => std::borrow::Cow::Borrowed(FAKE_XML),
1423        XmlProfile::Legacy => {
1424            let mut xml = FAKE_XML.to_string();
1425            for (section, replacement) in LEGACY_SECTIONS {
1426                let begin = format!("<!-- profile:{section} -->");
1427                let end = format!("<!-- /profile:{section} -->");
1428                let start = xml
1429                    .find(&begin)
1430                    .unwrap_or_else(|| panic!("FAKE_XML has no {begin}"));
1431                let stop = xml[start..]
1432                    .find(&end)
1433                    .map(|at| start + at + end.len())
1434                    .unwrap_or_else(|| panic!("FAKE_XML has no {end}"));
1435                xml.replace_range(start..stop, replacement);
1436            }
1437            std::borrow::Cow::Owned(xml)
1438        }
1439    }
1440}
1441
1442// ── Register Map ────────────────────────────────────────────────────────────
1443
1444/// Pre-populated register store for the fake camera.
1445///
1446/// All feature registers are initialized with realistic defaults.
1447/// The register map is thread-safe via external `Mutex` wrapping.
1448pub struct RegisterMap {
1449    regs: HashMap<u64, Vec<u8>>,
1450    xml_blob: Vec<u8>,
1451    clock_origin: Instant,
1452    /// Event identifiers whose `EventNotification` is `On`.
1453    ///
1454    /// One word cannot hold this. `EventSelector`/`EventNotification` is a
1455    /// selector pair, so a controller enabling two events writes the same
1456    /// address twice with a different selector in between — and a single
1457    /// stored word would let the second write turn the first event back off.
1458    enabled_events: HashSet<u16>,
1459    /// `ChunkSelector` values whose `ChunkEnable` is on: a selected feature,
1460    /// as `EventNotification` is.
1461    enabled_chunks: HashSet<u32>,
1462    /// When the controller last sent a register-access command, for the
1463    /// heartbeat rule.
1464    last_register_command: Instant,
1465    /// The application holding control privilege: the address and port its
1466    /// commands come from. `None` while nobody holds it.
1467    controller: Option<SocketAddr>,
1468    /// Whether [`RegisterMap::enforce_heartbeat`] is armed.
1469    enforce_heartbeat: bool,
1470    /// Largest `GevSCPSPacketSize` this device accepts, if it clamps at all.
1471    ///
1472    /// Real cameras cap the packet size at what their MAC can emit and reduce a
1473    /// larger request silently — the write is acknowledged and the register then
1474    /// reads back lower. Nothing distinguishes that from acceptance on the wire,
1475    /// which is why a host that trusts its own request reassembles at the wrong
1476    /// stride and completes no frame
1477    /// ([#112](https://github.com/VitalyVorobyev/viva-genicam/issues/112)).
1478    ///
1479    /// The fake accepted anything until 0.4.1, so it could not express the
1480    /// camera that caused that report, and no test could have caught the defect
1481    /// — the ADR-0019 failure mode of a fake that only agrees with its client.
1482    /// `None` keeps the old accept-anything behaviour.
1483    max_packet_size: Option<u32>,
1484    /// Largest GVSP datagram this device's *path* will actually deliver.
1485    ///
1486    /// Distinct from [`RegisterMap::max_packet_size`], and the distinction is
1487    /// the whole of [#112](https://github.com/VitalyVorobyev/viva-genicam/issues/112):
1488    /// that camera declares `Max=16366`, stores 16114 without complaint, and
1489    /// then streams nothing, because the link tops out at a 9216-byte frame.
1490    /// A register read cannot find that; only a test packet can.
1491    max_on_wire: Option<u32>,
1492    /// Size requested by the most recent write with the fire-test-packet bit,
1493    /// for the GVCP server to act on once it has released the register lock.
1494    pending_test_packet: Option<u32>,
1495    /// User sets saved by `UserSetSave`, by set number: the registers a
1496    /// `UserSetLoad` of that set restores.
1497    user_sets: HashMap<u32, Vec<(u64, Vec<u8>)>>,
1498    /// `TriggerSoftware` executions for `FrameStart` not yet turned into a
1499    /// frame.
1500    pending_frame_triggers: u32,
1501    /// Every `TriggerSoftware` execution.
1502    software_triggers: u64,
1503    /// The binning the region of interest is counted in, horizontal and
1504    /// vertical: the factor the last binning write left in place, which the
1505    /// next one rescales from.
1506    binning: (u32, u32),
1507}
1508
1509/// Registers a user set holds: the analog-control settings.
1510const USER_SET_REGISTERS: &[u64] = &[
1511    REG_EXPOSURE_TIME,
1512    REG_GAIN,
1513    REG_EXPOSURE_AUTO,
1514    REG_GAIN_AUTO,
1515];
1516
1517/// Compress the GenApi XML into a single-entry ZIP archive (deflate) whose
1518/// local and central headers carry `extra` as their extra field.
1519///
1520/// Written by hand from the ZIP format (APPNOTE 4.3.7, 4.3.12, 4.3.16) so
1521/// that `extra` can be bytes a ZIP writer would refuse: real cameras serve
1522/// such archives.
1523fn zip_xml_blob(xml: &[u8], extra: &[u8]) -> Vec<u8> {
1524    use std::io::Write;
1525    const NAME: &[u8] = b"fake.xml";
1526    let mut encoder =
1527        flate2::write::DeflateEncoder::new(Vec::new(), flate2::Compression::default());
1528    encoder.write_all(xml).expect("deflate the XML");
1529    let packed = encoder.finish().expect("deflate the XML");
1530    let mut crc = flate2::Crc::new();
1531    crc.update(xml);
1532
1533    // The fields the local and the central header share: version needed,
1534    // flags, method (8, DEFLATE), time, date, CRC-32, sizes, lengths.
1535    let mut common = Vec::new();
1536    for field in [20u16, 0, 8, 0, 0] {
1537        common.extend_from_slice(&field.to_le_bytes());
1538    }
1539    for field in [crc.sum(), packed.len() as u32, xml.len() as u32] {
1540        common.extend_from_slice(&field.to_le_bytes());
1541    }
1542    for field in [NAME.len() as u16, extra.len() as u16] {
1543        common.extend_from_slice(&field.to_le_bytes());
1544    }
1545
1546    let mut archive = b"PK\x03\x04".to_vec();
1547    archive.extend_from_slice(&common);
1548    archive.extend_from_slice(NAME);
1549    archive.extend_from_slice(extra);
1550    archive.extend_from_slice(&packed);
1551
1552    let directory = archive.len();
1553    archive.extend_from_slice(b"PK\x01\x02");
1554    archive.extend_from_slice(&0x0314u16.to_le_bytes()); // version made by
1555    archive.extend_from_slice(&common);
1556    // Comment length, disk, internal and external attributes, and the local
1557    // header's offset: all zero.
1558    archive.extend_from_slice(&[0; 14]);
1559    archive.extend_from_slice(NAME);
1560    archive.extend_from_slice(extra);
1561    let directory_len = archive.len() - directory;
1562
1563    archive.extend_from_slice(b"PK\x05\x06");
1564    archive.extend_from_slice(&[0; 4]); // disk numbers
1565    archive.extend_from_slice(&1u16.to_le_bytes());
1566    archive.extend_from_slice(&1u16.to_le_bytes());
1567    archive.extend_from_slice(&(directory_len as u32).to_le_bytes());
1568    archive.extend_from_slice(&(directory as u32).to_le_bytes());
1569    archive.extend_from_slice(&0u16.to_le_bytes());
1570    archive
1571}
1572
1573impl RegisterMap {
1574    /// Create a new register map with the given image dimensions.
1575    ///
1576    /// Initializes all bootstrap, feature, and device info registers with
1577    /// sensible defaults. The GenApi XML is embedded at [`XML_BLOB_BASE`],
1578    /// served as a ZIP archive when `xml_zip` is given (as many real cameras
1579    /// do), with those bytes as the archive's extra field.
1580    pub fn new(
1581        width: u32,
1582        height: u32,
1583        pixel_format: u32,
1584        xml_zip: Option<&[u8]>,
1585        profile: XmlProfile,
1586    ) -> Self {
1587        let mut regs = HashMap::new();
1588
1589        // ── Bootstrap registers ─────────────────────────────────────────
1590        // The mandatory block every GigE Vision device answers. The fake used
1591        // to leave it at zero, which reads as "this camera reports version
1592        // 0.0 and has no stream channels" — a diagnostic dump of a real
1593        // camera would look nothing like one taken from the fake.
1594        regs.insert(VERSION, 0x0002_0000u32.to_be_bytes().to_vec()); // GEV 2.0
1595        regs.insert(DEVICE_MODE, DEVICE_MODE_VALUE.to_be_bytes().to_vec());
1596        regs.insert(
1597            DEVICE_MAC_ADDRESS_HIGH,
1598            u32::from(u16::from_be_bytes([FAKE_MAC[0], FAKE_MAC[1]]))
1599                .to_be_bytes()
1600                .to_vec(),
1601        );
1602        regs.insert(
1603            DEVICE_MAC_ADDRESS_LOW,
1604            u32::from_be_bytes([FAKE_MAC[2], FAKE_MAC[3], FAKE_MAC[4], FAKE_MAC[5]])
1605                .to_be_bytes()
1606                .to_vec(),
1607        );
1608        // Persistent IP + DHCP + link-local, matching CURRENT_IP_CONFIG below.
1609        regs.insert(SUPPORTED_IP_CONFIG, 0x8000_0007u32.to_be_bytes().to_vec());
1610        regs.insert(CURRENT_IP_ADDRESS, Ipv4Addr::LOCALHOST.octets().to_vec());
1611        regs.insert(CURRENT_SUBNET_MASK, [255, 0, 0, 0].to_vec());
1612        regs.insert(CURRENT_DEFAULT_GATEWAY, vec![0, 0, 0, 0]);
1613        regs.insert(NUMBER_OF_MESSAGE_CHANNELS, 1u32.to_be_bytes().to_vec());
1614        regs.insert(NUMBER_OF_STREAM_CHANNELS, 1u32.to_be_bytes().to_vec());
1615        regs.insert(CONTROL_CHANNEL_PRIVILEGE, vec![0, 0, 0, 0]);
1616        regs.insert(
1617            GVCP_CAPABILITY,
1618            (CAPABILITY_CCP_APPLICATION_PORT_IP
1619                | CAPABILITY_PENDING_ACK
1620                | CAPABILITY_PACKET_RESEND
1621                | CAPABILITY_WRITEMEM
1622                | CAPABILITY_CONCATENATION)
1623                .to_be_bytes()
1624                .to_vec(),
1625        );
1626        regs.insert(GVCP_CONFIGURATION, 0u32.to_be_bytes().to_vec());
1627        regs.insert(HEARTBEAT_TIMEOUT, 3000u32.to_be_bytes().to_vec());
1628        regs.insert(
1629            TIMESTAMP_TICK_FREQUENCY_HIGH,
1630            ((TICK_FREQUENCY_HZ >> 32) as u32).to_be_bytes().to_vec(),
1631        );
1632        regs.insert(
1633            TIMESTAMP_TICK_FREQUENCY_LOW,
1634            (TICK_FREQUENCY_HZ as u32).to_be_bytes().to_vec(),
1635        );
1636        regs.insert(MESSAGE_DESTINATION_PORT, 0u32.to_be_bytes().to_vec());
1637        regs.insert(MESSAGE_DESTINATION_ADDRESS, vec![0, 0, 0, 0]);
1638        // This fake's own message channel timing (the Manta G-125B's was
1639        // 100 ms and 0xFFFFFFFF retries).
1640        regs.insert(
1641            MESSAGE_CHANNEL_TIMEOUT,
1642            DEFAULT_MESSAGE_TIMEOUT_MS.to_be_bytes().to_vec(),
1643        );
1644        regs.insert(
1645            MESSAGE_CHANNEL_RETRY_COUNT,
1646            DEFAULT_MESSAGE_RETRY_COUNT.to_be_bytes().to_vec(),
1647        );
1648
1649        // IP configuration: DHCP + persistent + LLA = 0x07
1650        regs.insert(CURRENT_IP_CONFIG, 0x0000_0005u32.to_be_bytes().to_vec());
1651        regs.insert(PERSISTENT_IP_ADDRESS, vec![0, 0, 0, 0]);
1652        regs.insert(PERSISTENT_SUBNET_MASK, vec![0, 0, 0, 0]);
1653        regs.insert(PERSISTENT_DEFAULT_GATEWAY, vec![0, 0, 0, 0]);
1654
1655        // Stream channel 0
1656        let base = STREAM_CHANNEL_BASE;
1657        regs.insert(base + STREAM_DESTINATION_PORT, vec![0, 0, 0, 0]);
1658        regs.insert(base + STREAM_PACKET_SIZE, 1500u32.to_be_bytes().to_vec());
1659        // A second channel, so a `<pIndex>` term that is ignored is visible:
1660        // its packet size differs from channel 0's.
1661        regs.insert(
1662            base + STREAM_CHANNEL_STRIDE + STREAM_PACKET_SIZE,
1663            9000u32.to_be_bytes().to_vec(),
1664        );
1665        regs.insert(REG_STREAM_CHANNEL_SELECTOR, 0u32.to_be_bytes().to_vec());
1666        regs.insert(base + STREAM_PACKET_DELAY, vec![0, 0, 0, 0]);
1667        regs.insert(base + STREAM_DESTINATION_ADDRESS, vec![0, 0, 0, 0]);
1668
1669        // ── Device info (read-only strings) ─────────────────────────────
1670        regs.insert(REG_DEVICE_MODEL_NAME, pad_string("VivaCam Fake", 32));
1671        regs.insert(REG_DEVICE_VENDOR_NAME, pad_string("vitavision.dev", 32));
1672        regs.insert(REG_DEVICE_SERIAL_NUMBER, pad_string("VIVA-FAKE-001", 16));
1673        regs.insert(REG_DEVICE_FIRMWARE_VERSION, pad_string("1.0.0-fake", 32));
1674        regs.insert(REG_DEVICE_ID, pad_string("VivaCam-0", 32));
1675        regs.insert(REG_DEVICE_USER_ID, vec![0; DEVICE_USER_ID_LEN]);
1676        regs.insert(REG_DEVICE_USER_BUFFER, vec![0; DEVICE_USER_BUFFER_LEN]);
1677
1678        // ── Image format ────────────────────────────────────────────────
1679        regs.insert(REG_WIDTH, width.to_be_bytes().to_vec());
1680        regs.insert(REG_HEIGHT, height.to_be_bytes().to_vec());
1681        regs.insert(REG_PIXEL_FORMAT, pixel_format.to_be_bytes().to_vec());
1682        regs.insert(REG_OFFSET_X, 0u32.to_be_bytes().to_vec());
1683        regs.insert(REG_OFFSET_Y, 0u32.to_be_bytes().to_vec());
1684        regs.insert(REG_SENSOR_WIDTH, 4096u32.to_be_bytes().to_vec());
1685        regs.insert(REG_SENSOR_HEIGHT, 4096u32.to_be_bytes().to_vec());
1686
1687        // Width/Height limits
1688        regs.insert(REG_WIDTH_MIN, 16u32.to_be_bytes().to_vec());
1689        regs.insert(REG_WIDTH_MAX, 4096u32.to_be_bytes().to_vec());
1690        regs.insert(REG_HEIGHT_MIN, 16u32.to_be_bytes().to_vec());
1691        regs.insert(REG_HEIGHT_MAX, 4096u32.to_be_bytes().to_vec());
1692
1693        // ── Acquisition control ─────────────────────────────────────────
1694        regs.insert(REG_ACQ_MODE, 0u32.to_be_bytes().to_vec()); // Continuous
1695        regs.insert(REG_ACQ_START, vec![0, 0, 0, 0]);
1696        regs.insert(REG_USER_SET_SELECTOR, 0u32.to_be_bytes().to_vec()); // Default
1697        regs.insert(REG_USER_SET_LOAD, 0u32.to_be_bytes().to_vec());
1698        regs.insert(REG_USER_SET_SAVE, 0u32.to_be_bytes().to_vec());
1699        regs.insert(REG_SOFTWARE_SIGNAL_PULSE, 0u32.to_be_bytes().to_vec());
1700        regs.insert(REG_USER_SET_DEFAULT, 0u32.to_be_bytes().to_vec());
1701        // Triggers off, waiting on Line1, for both selector entries.
1702        regs.insert(
1703            REG_TRIGGER_SELECTOR,
1704            TRIGGER_FRAME_START.to_be_bytes().to_vec(),
1705        );
1706        for index in 0..2u64 {
1707            regs.insert(REG_TRIGGER_MODE + 4 * index, 0u32.to_be_bytes().to_vec());
1708            regs.insert(
1709                REG_TRIGGER_SOURCE + 4 * index,
1710                TRIGGER_SOURCE_LINE1.to_be_bytes().to_vec(),
1711            );
1712        }
1713        regs.insert(REG_TRIGGER_SOFTWARE, 0u32.to_be_bytes().to_vec());
1714        regs.insert(REG_BINNING_HORIZONTAL, 1u32.to_be_bytes().to_vec());
1715        regs.insert(REG_BINNING_VERTICAL, 1u32.to_be_bytes().to_vec());
1716        regs.insert(REG_GAIN_SELECTOR, 0u32.to_be_bytes().to_vec());
1717        for index in 0..3u64 {
1718            regs.insert(REG_GAIN_RAW + 4 * index, 0u32.to_be_bytes().to_vec());
1719        }
1720        regs.insert(REG_ACQ_STOP, vec![0, 0, 0, 0]);
1721        regs.insert(REG_ACQ_FRAME_RATE, 30.0f32.to_be_bytes().to_vec());
1722        regs.insert(
1723            REG_EXPOSURE_TIME,
1724            DEFAULT_EXPOSURE_US.to_be_bytes().to_vec(),
1725        );
1726        regs.insert(REG_EXPOSURE_AUTO, 0u32.to_be_bytes().to_vec()); // Off
1727
1728        // ── Analog control ──────────────────────────────────────────────
1729        regs.insert(REG_GAIN, 0.0f64.to_be_bytes().to_vec());
1730        regs.insert(REG_GAIN_AUTO, 0u32.to_be_bytes().to_vec()); // Off
1731        regs.insert(REG_BLACK_LEVEL, 0u32.to_be_bytes().to_vec());
1732
1733        // ── Predicate gating ────────────────────────────────────────────
1734        // Frame rate manually controllable by default; sensor boots as a
1735        // monochrome sensor so Mono8/Mono16 PixelFormat entries are
1736        // available at boot.
1737        regs.insert(REG_ACQ_FRAME_RATE_ENABLE, 1u32.to_be_bytes().to_vec());
1738        regs.insert(REG_SENSOR_TYPE, 0u32.to_be_bytes().to_vec());
1739        // Capability bits, MSB-first as GenICam counts them on a big-endian
1740        // register: bit 0 = frame rate control present, bit 1 = chunk support.
1741        regs.insert(REG_DEVICE_CAPS, 0xC000_0000u32.to_be_bytes().to_vec());
1742        // ExposureTime implemented (bit 0) and available (bit 1), MSB-first —
1743        // see REG_FEATURE_STATUS.
1744        regs.insert(REG_FEATURE_STATUS, 0xC000_0000u32.to_be_bytes().to_vec());
1745
1746        // ── Timestamp (1 GHz tick frequency) ────────────────────────────
1747        regs.insert(REG_TIMESTAMP_FREQ, 1_000_000_000u32.to_be_bytes().to_vec());
1748        regs.insert(REG_TIMESTAMP_VALUE, vec![0u8; 8]);
1749        regs.insert(REG_TIMESTAMP_LATCH, vec![0, 0, 0, 0]);
1750        regs.insert(
1751            REG_PTP_OFFSET_LATCHED,
1752            (PTP_OFFSET_NS as u64).to_be_bytes().to_vec(),
1753        );
1754        regs.insert(
1755            REG_CHUNK_TIMESTAMP_LE,
1756            CHUNK_TIMESTAMP_TICKS.to_le_bytes().to_vec(),
1757        );
1758        regs.insert(REG_CHUNK_WIDTH_LE, CHUNK_WIDTH_PX.to_le_bytes().to_vec());
1759
1760        // ── Chunk data ──────────────────────────────────────────────────
1761        regs.insert(REG_CHUNK_MODE_ACTIVE, 0u32.to_be_bytes().to_vec());
1762        regs.insert(REG_CHUNK_SELECTOR, 1u32.to_be_bytes().to_vec()); // Timestamp
1763        regs.insert(REG_CHUNK_ENABLE, 0u32.to_be_bytes().to_vec());
1764        regs.insert(REG_EVENT_SELECTOR, 5u32.to_be_bytes().to_vec());
1765
1766        // ── XML URL register ────────────────────────────────────────────
1767        let xml = genapi_xml(profile);
1768        let (xml_blob, xml_name) = match xml_zip {
1769            Some(extra) => (zip_xml_blob(xml.as_bytes(), extra), "fake.zip"),
1770            None => (xml.as_bytes().to_vec(), "fake.xml"),
1771        };
1772        let url = format!(
1773            "Local:{xml_name};{:x};{:x}\0",
1774            XML_BLOB_BASE,
1775            xml_blob.len()
1776        );
1777        let mut url_bytes = vec![0u8; URL_LEN];
1778        let src = url.as_bytes();
1779        url_bytes[..src.len()].copy_from_slice(src);
1780        regs.insert(FIRST_URL, url_bytes);
1781
1782        Self {
1783            regs,
1784            xml_blob,
1785            clock_origin: Instant::now(),
1786            enabled_events: HashSet::new(),
1787            enabled_chunks: HashSet::new(),
1788            last_register_command: Instant::now(),
1789            controller: None,
1790            enforce_heartbeat: false,
1791            max_packet_size: None,
1792            max_on_wire: None,
1793            pending_test_packet: None,
1794            user_sets: HashMap::new(),
1795            pending_frame_triggers: 0,
1796            software_triggers: 0,
1797            binning: (1, 1),
1798        }
1799    }
1800
1801    /// Arm the GigE Vision heartbeat rule: release control privilege when the
1802    /// controller goes quiet for longer than `GevHeartbeatTimeout`.
1803    ///
1804    /// Real devices always do this, and it is the entire reason a client needs a
1805    /// keepalive — GVSP image traffic does not refresh the timer, so a camera can
1806    /// be streaming at full rate while its control channel times out underneath.
1807    /// A fake that never expires CCP cannot tell a working keepalive from a
1808    /// missing one, which is how SR-05 stayed open through three app-layer
1809    /// reimplementations of the same loop.
1810    ///
1811    /// **Off by default**, because arming it makes every test that holds control
1812    /// privilege sensitive to a 3 s stall — on a loaded CI runner that is a
1813    /// flake, not a finding. Tests that are *about* the keepalive turn it on.
1814    pub fn enforce_heartbeat(&mut self, enable: bool) {
1815        self.enforce_heartbeat = enable;
1816        self.last_register_command = Instant::now();
1817    }
1818
1819    /// Clamp `GevSCPSPacketSize` writes to `max`, the way a real device does.
1820    ///
1821    /// A request above `max` is acknowledged and silently reduced, so the
1822    /// register reads back lower than what was written — nothing on the wire
1823    /// distinguishes that from acceptance, which is the defect in
1824    /// [#112](https://github.com/VitalyVorobyev/viva-genicam/issues/112).
1825    /// Silently drop any GVSP datagram larger than `max`, as a path with a
1826    /// smaller frame ceiling than either endpoint believes does.
1827    ///
1828    /// See [`RegisterMap::max_on_wire`].
1829    pub fn set_max_on_wire(&mut self, max: u32) {
1830        self.max_on_wire = Some(max);
1831    }
1832
1833    /// The path ceiling, if one was configured.
1834    pub fn max_on_wire(&self) -> Option<u32> {
1835        self.max_on_wire
1836    }
1837
1838    /// Take the size requested by the last fire-test-packet write, if any.
1839    pub fn take_pending_test_packet(&mut self) -> Option<u32> {
1840        self.pending_test_packet.take()
1841    }
1842
1843    pub fn set_max_packet_size(&mut self, max: u32) {
1844        self.max_packet_size = Some(max);
1845        // Apply it to whatever the register already holds, so a device
1846        // configured with a cap never reports a size above it.
1847        let current = self.stream_packet_size();
1848        if current > max {
1849            self.write(STREAM_CHANNEL_BASE + STREAM_PACKET_SIZE, &max.to_be_bytes());
1850        }
1851    }
1852
1853    /// Apply the heartbeat rule to a register-access command from `peer`, and
1854    /// report whether privilege was just revoked.
1855    ///
1856    /// Called for register-access commands only. Discovery and FORCEIP are
1857    /// broadcast by any application on the subnet, so counting them would let an
1858    /// unrelated `viva-camctl list` hold another application's privilege open.
1859    /// Only the controller's own commands refresh its timer: a monitor reading
1860    /// registers keeps nobody's privilege alive.
1861    pub fn note_register_command(&mut self, peer: SocketAddr) -> bool {
1862        let revoked = self.enforce_heartbeat
1863            && self.controller.is_some()
1864            && self.heartbeat_expired(self.last_register_command.elapsed());
1865        if revoked {
1866            self.revoke_control();
1867        }
1868        if self.controller == Some(peer) {
1869            self.last_register_command = Instant::now();
1870        }
1871        revoked
1872    }
1873
1874    fn heartbeat_expired(&self, elapsed: Duration) -> bool {
1875        let timeout = Duration::from_millis(u64::from(self.heartbeat_timeout_ms()));
1876        !timeout.is_zero() && elapsed > timeout
1877    }
1878
1879    /// Give control privilege up on the device side, as a device does when its
1880    /// heartbeat expires: CCP reads 0 and nobody is the controller.
1881    pub fn revoke_control(&mut self) {
1882        self.controller = None;
1883        self.regs
1884            .insert(CONTROL_CHANNEL_PRIVILEGE, 0u32.to_be_bytes().to_vec());
1885    }
1886
1887    /// The application holding control privilege, if any.
1888    pub fn controller(&self) -> Option<SocketAddr> {
1889        self.controller
1890    }
1891
1892    /// Whether `peer` may access the device's registers.
1893    ///
1894    /// While an application holds control, another may still read (it
1895    /// monitors) unless the privilege is exclusive, and may not write. While
1896    /// nobody holds control every application may read and none may write:
1897    /// an Allied Vision Manta G-125B answered a write from an application
1898    /// without control `ACCESS_DENIED` while nobody held it (aravis's fake
1899    /// camera takes it, `arvgvfakecamera.c`).
1900    pub fn may_access(&self, peer: SocketAddr, write: bool) -> bool {
1901        match self.controller {
1902            None => !write,
1903            Some(controller) if controller == peer => true,
1904            Some(_) if write => false,
1905            Some(_) => self.read_u32_be(CONTROL_CHANNEL_PRIVILEGE) & CCP_EXCLUSIVE == 0,
1906        }
1907    }
1908
1909    /// A write of `value` to CCP from `peer`, and whether it was accepted.
1910    /// Claims control with either access bit set, gives it up with neither.
1911    /// Refused while another application holds control: this device offers
1912    /// no switchover.
1913    pub fn write_ccp(&mut self, peer: SocketAddr, value: u32) -> bool {
1914        if self.controller.is_some_and(|controller| controller != peer) {
1915            return false;
1916        }
1917        if value & (CCP_CONTROL | CCP_EXCLUSIVE) != 0 {
1918            self.controller = Some(peer);
1919            self.last_register_command = Instant::now();
1920            self.regs
1921                .insert(CONTROL_CHANNEL_PRIVILEGE, value.to_be_bytes().to_vec());
1922        } else {
1923            self.revoke_control();
1924        }
1925        true
1926    }
1927
1928    /// Whether this device answers a slow command with `PENDING_ACK`: it
1929    /// says it can (GVCP Capability) and the controller has enabled it (GVCP
1930    /// Configuration).
1931    pub fn pending_ack_enabled(&self) -> bool {
1932        self.read_u32_be(GVCP_CAPABILITY) & CAPABILITY_PENDING_ACK != 0
1933            && self.read_u32_be(GVCP_CONFIGURATION) & CONFIGURATION_PENDING_ACK_ENABLE != 0
1934    }
1935
1936    /// Set or clear the `PENDING_ACK` bit of the capability register.
1937    pub fn set_pending_ack_supported(&mut self, supported: bool) {
1938        let mut caps = self.read_u32_be(GVCP_CAPABILITY);
1939        if supported {
1940            caps |= CAPABILITY_PENDING_ACK;
1941        } else {
1942            caps &= !CAPABILITY_PENDING_ACK;
1943        }
1944        self.regs
1945            .insert(GVCP_CAPABILITY, caps.to_be_bytes().to_vec());
1946    }
1947
1948    /// Say, or stop saying, that the device names its primary application
1949    /// (GVCP Capability `0x0800_0000`); without it `0x0A04` and `0x0A14` are
1950    /// not registers of this device ([`Self::is_invalid_address`]).
1951    pub fn set_names_primary_application(&mut self, names: bool) {
1952        let mut caps = self.read_u32_be(GVCP_CAPABILITY);
1953        if names {
1954            caps |= CAPABILITY_CCP_APPLICATION_PORT_IP;
1955        } else {
1956            caps &= !CAPABILITY_CCP_APPLICATION_PORT_IP;
1957        }
1958        self.regs
1959            .insert(GVCP_CAPABILITY, caps.to_be_bytes().to_vec());
1960    }
1961
1962    /// Whether `len` bytes at `addr` touch a register this device does not
1963    /// have, which it answers with `INVALID_ADDRESS`: the primary application
1964    /// registers of a device whose GVCP Capability does not offer them.
1965    pub fn is_invalid_address(&self, addr: u64, len: usize) -> bool {
1966        let names_owner =
1967            self.read_u32_be(GVCP_CAPABILITY) & CAPABILITY_CCP_APPLICATION_PORT_IP != 0;
1968        let end = addr + len as u64;
1969        !names_owner
1970            && [PRIMARY_APPLICATION_PORT, PRIMARY_APPLICATION_IP]
1971                .iter()
1972                .any(|&reg| reg < end && addr < reg + 4)
1973    }
1974
1975    /// Report `ip`, `mask` and `gateway` as the current IP configuration
1976    /// (bootstrap `0x0024`, `0x0034`, `0x0044`), as the Discovery ACK does.
1977    pub fn set_network(&mut self, ip: Ipv4Addr, mask: Ipv4Addr, gateway: Ipv4Addr) {
1978        self.regs.insert(CURRENT_IP_ADDRESS, ip.octets().to_vec());
1979        self.regs
1980            .insert(CURRENT_SUBNET_MASK, mask.octets().to_vec());
1981        self.regs
1982            .insert(CURRENT_DEFAULT_GATEWAY, gateway.octets().to_vec());
1983    }
1984
1985    /// Report a different `GevHeartbeatTimeout` than the 3 000 ms default.
1986    ///
1987    /// Lets a test pick a window short enough to wait out without making the
1988    /// suite slow, and makes the timing it depends on explicit rather than
1989    /// implied by this crate's default.
1990    pub fn set_heartbeat_timeout_ms(&mut self, timeout_ms: u32) {
1991        self.write(HEARTBEAT_TIMEOUT, &timeout_ms.to_be_bytes());
1992    }
1993
1994    /// Report `mac` from the bootstrap MAC registers instead of [`FAKE_MAC`],
1995    /// so they agree with a Discovery ACK built from the same identity.
1996    pub fn set_mac(&mut self, mac: [u8; 6]) {
1997        let high = u32::from(u16::from_be_bytes([mac[0], mac[1]]));
1998        let low = u32::from_be_bytes([mac[2], mac[3], mac[4], mac[5]]);
1999        self.regs
2000            .insert(DEVICE_MAC_ADDRESS_HIGH, high.to_be_bytes().to_vec());
2001        self.regs
2002            .insert(DEVICE_MAC_ADDRESS_LOW, low.to_be_bytes().to_vec());
2003    }
2004
2005    /// Report `hz` as the timestamp tick frequency, the unit of `GevSCPD`.
2006    /// `0` is what a device without a timestamp clock reports.
2007    pub fn set_tick_frequency(&mut self, hz: u64) {
2008        self.regs.insert(
2009            TIMESTAMP_TICK_FREQUENCY_HIGH,
2010            ((hz >> 32) as u32).to_be_bytes().to_vec(),
2011        );
2012        self.regs.insert(
2013            TIMESTAMP_TICK_FREQUENCY_LOW,
2014            (hz as u32).to_be_bytes().to_vec(),
2015        );
2016    }
2017
2018    /// Set or clear the `PACKETRESEND_CMD` bit of the capability register.
2019    pub fn set_packet_resend(&mut self, supported: bool) {
2020        let mut caps = self.read_u32_be(GVCP_CAPABILITY);
2021        if supported {
2022            caps |= CAPABILITY_PACKET_RESEND;
2023        } else {
2024            caps &= !CAPABILITY_PACKET_RESEND;
2025        }
2026        self.regs
2027            .insert(GVCP_CAPABILITY, caps.to_be_bytes().to_vec());
2028    }
2029
2030    /// Whether the capability register says this device answers
2031    /// `PACKETRESEND_CMD`.
2032    pub fn packet_resend_supported(&self) -> bool {
2033        self.read_u32_be(GVCP_CAPABILITY) & CAPABILITY_PACKET_RESEND != 0
2034    }
2035
2036    /// The heartbeat window this device reports, in milliseconds.
2037    pub fn heartbeat_timeout_ms(&self) -> u32 {
2038        let data = self.read(HEARTBEAT_TIMEOUT, 4);
2039        u32::from_be_bytes([data[0], data[1], data[2], data[3]])
2040    }
2041
2042    /// Whether `[addr, addr + len)` touches a register the XML declares `WO`.
2043    ///
2044    /// Checked by the GVCP server before it serves a read, so a READREG or
2045    /// READMEM of a write-only register is refused on the wire. The store
2046    /// itself stays readable: `peek`-style test access and the fake's own
2047    /// side effects must still see what was written.
2048    pub fn is_write_only(&self, addr: u64, len: usize) -> bool {
2049        let end = addr.saturating_add(len as u64);
2050        WRITE_ONLY_REGISTERS
2051            .iter()
2052            .any(|&reg| reg < end && addr < reg + 4)
2053    }
2054
2055    /// Read `len` bytes starting at `addr`.
2056    pub fn read(&self, addr: u64, len: usize) -> Vec<u8> {
2057        // XML blob region
2058        if addr >= XML_BLOB_BASE {
2059            let offset = (addr - XML_BLOB_BASE) as usize;
2060            if offset < self.xml_blob.len() {
2061                let end = (offset + len).min(self.xml_blob.len());
2062                let mut result = self.xml_blob[offset..end].to_vec();
2063                result.resize(len, 0);
2064                return result;
2065            }
2066        }
2067
2068        // The primary application is whoever holds control right now.
2069        if addr == PRIMARY_APPLICATION_PORT || addr == PRIMARY_APPLICATION_IP {
2070            let word = match (addr, self.controller) {
2071                (PRIMARY_APPLICATION_PORT, Some(owner)) => u32::from(owner.port()),
2072                (PRIMARY_APPLICATION_IP, Some(SocketAddr::V4(owner))) => u32::from(*owner.ip()),
2073                _ => 0,
2074            };
2075            let mut result = word.to_be_bytes().to_vec();
2076            result.resize(len, 0);
2077            return result;
2078        }
2079
2080        // The next block's size follows the format and the chunks.
2081        if addr == REG_PAYLOAD_SIZE {
2082            let mut result = self.payload_size().to_be_bytes().to_vec();
2083            result.resize(len, 0);
2084            result.truncate(len);
2085            return result;
2086        }
2087
2088        // The temperature moves with time, not with writes.
2089        if addr == REG_DEVICE_TEMPERATURE {
2090            let mut result = self.device_temperature_raw().to_be_bytes().to_vec();
2091            result.resize(len, 0);
2092            return result;
2093        }
2094
2095        // `EventNotification` reports the selected event, not a stored word.
2096        if addr == REG_EVENT_NOTIFICATION {
2097            let on = u32::from(self.event_notification_on(self.event_selector()));
2098            let mut result = on.to_be_bytes().to_vec();
2099            result.resize(len, 0);
2100            result.truncate(len);
2101            return result;
2102        }
2103
2104        if addr == REG_CHUNK_ENABLE {
2105            let on = u32::from(self.chunk_enabled(self.chunk_selector()));
2106            let mut result = on.to_be_bytes().to_vec();
2107            result.resize(len, 0);
2108            result.truncate(len);
2109            return result;
2110        }
2111
2112        // Exact register match
2113        if let Some(data) = self.regs.get(&addr) {
2114            let mut result = data.clone();
2115            result.resize(len, 0);
2116            result.truncate(len);
2117            return result;
2118        }
2119
2120        // Sub-register access (read within a larger register)
2121        for (&reg_addr, data) in &self.regs {
2122            if addr >= reg_addr && (addr - reg_addr) < data.len() as u64 {
2123                let offset = (addr - reg_addr) as usize;
2124                let end = (offset + len).min(data.len());
2125                let mut result = data[offset..end].to_vec();
2126                result.resize(len, 0);
2127                return result;
2128            }
2129        }
2130
2131        vec![0u8; len]
2132    }
2133
2134    /// Write `data` starting at `addr`.
2135    pub fn write(&mut self, addr: u64, data: &[u8]) {
2136        // `GevSCPSPacketSize` carries two flags above the 16-bit size field:
2137        // bit 31 fires a test packet and bit 30 sets do-not-fragment. The first
2138        // is an action, recorded for the caller and not stored; the second is
2139        // a setting, stored and read back as an Allied Vision Manta G-125B
2140        // does (it read `0x400005DC`).
2141        let stripped;
2142        let mut data = data;
2143        if addr == STREAM_CHANNEL_BASE + STREAM_PACKET_SIZE && data.len() >= 4 {
2144            let raw = u32::from_be_bytes([data[0], data[1], data[2], data[3]]);
2145            self.pending_test_packet =
2146                (raw & SCPS_FIRE_TEST_PACKET != 0).then_some(raw & STREAM_PACKET_SIZE_MASK);
2147            if raw & !(SCPS_DO_NOT_FRAGMENT | STREAM_PACKET_SIZE_MASK) != 0 {
2148                stripped = (raw & (SCPS_DO_NOT_FRAGMENT | STREAM_PACKET_SIZE_MASK)).to_be_bytes();
2149                data = &stripped[..];
2150            }
2151        }
2152
2153        // A capped device reduces an oversized packet size instead of refusing
2154        // it — silently, exactly as the hardware in #112 does.
2155        let clamped;
2156        let data = match self.max_packet_size {
2157            Some(max)
2158                if addr == STREAM_CHANNEL_BASE + STREAM_PACKET_SIZE
2159                    && data.len() >= 4
2160                    && u32::from_be_bytes([data[0], data[1], data[2], data[3]])
2161                        & STREAM_PACKET_SIZE_MASK
2162                        > max =>
2163            {
2164                let flags = u32::from_be_bytes([data[0], data[1], data[2], data[3]])
2165                    & !STREAM_PACKET_SIZE_MASK;
2166                clamped = (flags | max).to_be_bytes();
2167                &clamped[..]
2168            }
2169            _ => data,
2170        };
2171
2172        // `EventNotification` applies to the selected event. Enabling a second
2173        // event must not disable the first, so the value lands in the set
2174        // keyed by the current selector rather than in a shared register.
2175        if addr == REG_EVENT_NOTIFICATION && data.len() >= 4 {
2176            let event = self.event_selector();
2177            if u32::from_be_bytes([data[0], data[1], data[2], data[3]]) != 0 {
2178                self.enabled_events.insert(event);
2179            } else {
2180                self.enabled_events.remove(&event);
2181            }
2182            return;
2183        }
2184
2185        if addr == REG_CHUNK_ENABLE && data.len() >= 4 {
2186            let selector = self.chunk_selector();
2187            if u32::from_be_bytes([data[0], data[1], data[2], data[3]]) != 0 {
2188                self.enabled_chunks.insert(selector);
2189            } else {
2190                self.enabled_chunks.remove(&selector);
2191            }
2192            return;
2193        }
2194
2195        if let Some(existing) = self.regs.get_mut(&addr) {
2196            let len = existing.len().min(data.len());
2197            existing[..len].copy_from_slice(&data[..len]);
2198            return;
2199        }
2200
2201        // Write within an existing register
2202        let addrs: Vec<u64> = self.regs.keys().copied().collect();
2203        for reg_addr in addrs {
2204            let reg_data = self.regs.get(&reg_addr).unwrap();
2205            if addr >= reg_addr && (addr - reg_addr) < reg_data.len() as u64 {
2206                let offset = (addr - reg_addr) as usize;
2207                let end = (offset + data.len()).min(reg_data.len());
2208                let reg_data = self.regs.get_mut(&reg_addr).unwrap();
2209                reg_data[offset..end].copy_from_slice(&data[..end - offset]);
2210                return;
2211            }
2212        }
2213
2214        self.regs.insert(addr, data.to_vec());
2215    }
2216
2217    /// Handle side effects of register writes.
2218    pub fn handle_special_write(&mut self, addr: u64) {
2219        if addr == REG_BINNING_HORIZONTAL {
2220            let old = self.binning.0;
2221            self.binning.0 = self.rebin(
2222                old,
2223                REG_BINNING_HORIZONTAL,
2224                [REG_SENSOR_WIDTH, REG_WIDTH_MAX, REG_WIDTH, REG_OFFSET_X],
2225            );
2226        }
2227        if addr == REG_BINNING_VERTICAL {
2228            let old = self.binning.1;
2229            self.binning.1 = self.rebin(
2230                old,
2231                REG_BINNING_VERTICAL,
2232                [REG_SENSOR_HEIGHT, REG_HEIGHT_MAX, REG_HEIGHT, REG_OFFSET_Y],
2233            );
2234        }
2235        if addr == REG_TIMESTAMP_LATCH {
2236            let ts = self.device_timestamp();
2237            self.regs
2238                .insert(REG_TIMESTAMP_VALUE, ts.to_be_bytes().to_vec());
2239        }
2240        if addr == REG_USER_SET_LOAD {
2241            let set = self.read_u32_be(REG_USER_SET_LOAD);
2242            self.load_user_set(set);
2243        }
2244        if addr == REG_USER_SET_SAVE {
2245            let set = self.read_u32_be(REG_USER_SET_SAVE);
2246            self.save_user_set(set);
2247        }
2248        if addr == REG_TRIGGER_SOFTWARE {
2249            self.software_triggers += 1;
2250            if self.read_u32_be(REG_TRIGGER_SELECTOR) == TRIGGER_FRAME_START {
2251                self.pending_frame_triggers += 1;
2252            }
2253        }
2254    }
2255
2256    /// Apply a new binning factor along one axis and return it.
2257    ///
2258    /// SFNC counts `WidthMax` "after horizontal binning", so the maximum is
2259    /// the sensor size divided by the factor. The region of interest keeps its
2260    /// place on the sensor, counted in binned pixels: size and offset scale by
2261    /// the old factor over the new. That is one way a camera keeps a region
2262    /// valid when the maximum moves; a camera that resets the region instead
2263    /// makes the order of writes matter just as much — a size written before
2264    /// the binning does not survive it.
2265    fn rebin(&mut self, old: u32, factor_reg: u64, [sensor, max, size, offset]: [u64; 4]) -> u32 {
2266        let new = self.read_u32_be(factor_reg);
2267        if new == 0 || new == old {
2268            return old.max(1);
2269        }
2270        let scale = |value: u32| (u64::from(value) * u64::from(old) / u64::from(new)) as u32;
2271        let maximum = self.read_u32_be(sensor) / new;
2272        let size_now = scale(self.read_u32_be(size)).max(1);
2273        let offset_now = scale(self.read_u32_be(offset)).min(maximum.saturating_sub(size_now));
2274        self.regs.insert(max, maximum.to_be_bytes().to_vec());
2275        self.regs
2276            .insert(size, size_now.min(maximum).to_be_bytes().to_vec());
2277        self.regs.insert(offset, offset_now.to_be_bytes().to_vec());
2278        new
2279    }
2280
2281    /// Whether the next frame may start now. Always, while the `FrameStart`
2282    /// trigger is `Off`; once per `TriggerSoftware` while it is `On` with
2283    /// source `Software`; never while it waits on a line, which nothing
2284    /// drives here.
2285    pub fn take_frame_start(&mut self) -> bool {
2286        let index = u64::from(TRIGGER_FRAME_START);
2287        if self.read_u32_be(REG_TRIGGER_MODE + 4 * index) == 0 {
2288            return true;
2289        }
2290        if self.read_u32_be(REG_TRIGGER_SOURCE + 4 * index) != TRIGGER_SOURCE_SOFTWARE
2291            || self.pending_frame_triggers == 0
2292        {
2293            return false;
2294        }
2295        self.pending_frame_triggers -= 1;
2296        true
2297    }
2298
2299    /// How many times `TriggerSoftware` was executed.
2300    pub fn software_triggers(&self) -> u64 {
2301        self.software_triggers
2302    }
2303
2304    fn read_u32_be(&self, addr: u64) -> u32 {
2305        let data = self.read(addr, 4);
2306        u32::from_be_bytes([data[0], data[1], data[2], data[3]])
2307    }
2308
2309    /// Restore user set `set`, as `UserSetLoad` does on a real camera: `0` is
2310    /// `Default`, the analog-control defaults the fake boots with, and so is a
2311    /// set never saved.
2312    ///
2313    /// A command that only acknowledges the write is untestable: a test could
2314    /// assert nothing beyond the absence of an error, which is the fake
2315    /// agreeing with itself. Restoring observable device state means a test can
2316    /// change a feature, execute the command, and read the change back out
2317    /// (ADR-0019).
2318    fn load_user_set(&mut self, set: u32) {
2319        if let Some(saved) = self.user_sets.get(&set).cloned() {
2320            for (addr, bytes) in saved {
2321                self.regs.insert(addr, bytes);
2322            }
2323            return;
2324        }
2325        self.regs.insert(
2326            REG_EXPOSURE_TIME,
2327            DEFAULT_EXPOSURE_US.to_be_bytes().to_vec(),
2328        );
2329        self.regs.insert(REG_GAIN, 0.0f64.to_be_bytes().to_vec());
2330        self.regs
2331            .insert(REG_EXPOSURE_AUTO, 0u32.to_be_bytes().to_vec());
2332        self.regs.insert(REG_GAIN_AUTO, 0u32.to_be_bytes().to_vec());
2333    }
2334
2335    /// Save the current settings into user set `set`. `Default` (`0`) is the
2336    /// factory set and cannot be overwritten, so a write of `0` is ignored.
2337    fn save_user_set(&mut self, set: u32) {
2338        if set == 0 {
2339            return;
2340        }
2341        let saved = USER_SET_REGISTERS
2342            .iter()
2343            .filter_map(|addr| self.regs.get(addr).map(|bytes| (*addr, bytes.clone())))
2344            .collect();
2345        self.user_sets.insert(set, saved);
2346    }
2347
2348    /// The exposure saved in user set `set`, or `None` if nothing has been
2349    /// saved there.
2350    ///
2351    /// Device state, read past the protocol: a test can check *which* set a
2352    /// `UserSetSave` landed in without trusting the client's own account of
2353    /// what it wrote.
2354    pub fn saved_exposure(&self, set: u32) -> Option<f64> {
2355        let saved = self.user_sets.get(&set)?;
2356        let (_, bytes) = saved.iter().find(|(addr, _)| *addr == REG_EXPOSURE_TIME)?;
2357        Some(f64::from_be_bytes(bytes.as_slice().try_into().ok()?))
2358    }
2359
2360    // ── Accessors ───────────────────────────────────────────────────────
2361
2362    /// Current device timestamp in nanoseconds since creation.
2363    pub fn device_timestamp(&self) -> u64 {
2364        self.clock_origin.elapsed().as_nanos() as u64
2365    }
2366
2367    /// `DeviceTemperature_Val` now, in 1/256 °C: [`DEVICE_TEMPERATURE_START_C`]
2368    /// plus [`DEVICE_TEMPERATURE_STEP_C`] for every
2369    /// [`DEVICE_TEMPERATURE_PERIOD`] since the fake started, falling back to
2370    /// the start after [`DEVICE_TEMPERATURE_STEPS`] steps.
2371    pub fn device_temperature_raw(&self) -> i32 {
2372        let periods =
2373            self.clock_origin.elapsed().as_nanos() / DEVICE_TEMPERATURE_PERIOD.as_nanos().max(1);
2374        let step = (periods % u128::from(DEVICE_TEMPERATURE_STEPS)) as f64;
2375        ((DEVICE_TEMPERATURE_START_C + step * DEVICE_TEMPERATURE_STEP_C) * 256.0) as i32
2376    }
2377
2378    /// Stream destination IP address.
2379    pub fn stream_dest_ip(&self) -> Ipv4Addr {
2380        let data = self.read(STREAM_CHANNEL_BASE + STREAM_DESTINATION_ADDRESS, 4);
2381        Ipv4Addr::new(data[0], data[1], data[2], data[3])
2382    }
2383
2384    /// Stream destination port.
2385    pub fn stream_dest_port(&self) -> u16 {
2386        let data = self.read(STREAM_CHANNEL_BASE + STREAM_DESTINATION_PORT, 4);
2387        u16::from_be_bytes([data[2], data[3]])
2388    }
2389
2390    /// Message channel destination address (`GevMCDA`).
2391    pub fn message_dest_ip(&self) -> Ipv4Addr {
2392        let data = self.read(MESSAGE_DESTINATION_ADDRESS, 4);
2393        Ipv4Addr::new(data[0], data[1], data[2], data[3])
2394    }
2395
2396    /// Milliseconds an event message waits for its acknowledgement before it
2397    /// is sent again (`GevMCTT`).
2398    pub fn message_timeout_ms(&self) -> u32 {
2399        let data = self.read(MESSAGE_CHANNEL_TIMEOUT, 4);
2400        u32::from_be_bytes([data[0], data[1], data[2], data[3]])
2401    }
2402
2403    /// Times an unacknowledged event message is sent again before it is
2404    /// abandoned (`GevMCRC`).
2405    pub fn message_retry_count(&self) -> u32 {
2406        let data = self.read(MESSAGE_CHANNEL_RETRY_COUNT, 4);
2407        u32::from_be_bytes([data[0], data[1], data[2], data[3]])
2408    }
2409
2410    /// Message channel destination port (`GevMCP`), low 16 bits of the register.
2411    pub fn message_dest_port(&self) -> u16 {
2412        let data = self.read(MESSAGE_DESTINATION_PORT, 4);
2413        u16::from_be_bytes([data[2], data[3]])
2414    }
2415
2416    /// Event identifier currently selected by `EventSelector`.
2417    pub fn event_selector(&self) -> u16 {
2418        let data = self.read(REG_EVENT_SELECTOR, 4);
2419        u32::from_be_bytes([data[0], data[1], data[2], data[3]]) as u16
2420    }
2421
2422    /// Whether `EventNotification` is `On` for `event_id`.
2423    ///
2424    /// Takes the event explicitly: the emitter cares whether *its* event is
2425    /// enabled, which is independent of whichever entry the controller
2426    /// happened to select last.
2427    pub fn event_notification_on(&self, event_id: u16) -> bool {
2428        self.enabled_events.contains(&event_id)
2429    }
2430
2431    /// Stream packet size: the register's low 16 bits, without the
2432    /// do-not-fragment flag stored above them.
2433    pub fn stream_packet_size(&self) -> u32 {
2434        let data = self.read(STREAM_CHANNEL_BASE + STREAM_PACKET_SIZE, 4);
2435        u32::from_be_bytes([data[0], data[1], data[2], data[3]]) & STREAM_PACKET_SIZE_MASK
2436    }
2437
2438    /// `GevSCPD`: the delay between stream packets, in timestamp ticks.
2439    pub fn stream_packet_delay_ticks(&self) -> u32 {
2440        let data = self.read(STREAM_CHANNEL_BASE + STREAM_PACKET_DELAY, 4);
2441        u32::from_be_bytes([data[0], data[1], data[2], data[3]])
2442    }
2443
2444    /// Timestamp tick frequency from bootstrap 0x093C (high) and 0x0940 (low).
2445    pub fn tick_frequency(&self) -> u64 {
2446        let high = self.read(TIMESTAMP_TICK_FREQUENCY_HIGH, 4);
2447        let low = self.read(TIMESTAMP_TICK_FREQUENCY_LOW, 4);
2448        (u64::from(u32::from_be_bytes([high[0], high[1], high[2], high[3]])) << 32)
2449            | u64::from(u32::from_be_bytes([low[0], low[1], low[2], low[3]]))
2450    }
2451
2452    /// Image width.
2453    pub fn width(&self) -> u32 {
2454        let data = self.read(REG_WIDTH, 4);
2455        u32::from_be_bytes([data[0], data[1], data[2], data[3]])
2456    }
2457
2458    /// Image height.
2459    pub fn height(&self) -> u32 {
2460        let data = self.read(REG_HEIGHT, 4);
2461        u32::from_be_bytes([data[0], data[1], data[2], data[3]])
2462    }
2463
2464    /// Pixel format PFNC code.
2465    pub fn pixel_format_code(&self) -> u32 {
2466        let data = self.read(REG_PIXEL_FORMAT, 4);
2467        u32::from_be_bytes([data[0], data[1], data[2], data[3]])
2468    }
2469
2470    /// Value currently selected by `ChunkSelector`.
2471    pub fn chunk_selector(&self) -> u32 {
2472        let data = self.read(REG_CHUNK_SELECTOR, 4);
2473        u32::from_be_bytes([data[0], data[1], data[2], data[3]])
2474    }
2475
2476    /// Whether `ChunkEnable` is on for `selector`, whichever chunk the
2477    /// controller selected last.
2478    pub fn chunk_enabled(&self, selector: u32) -> bool {
2479        self.enabled_chunks.contains(&selector)
2480    }
2481
2482    /// Whether chunk mode is active.
2483    pub fn chunk_mode_active(&self) -> bool {
2484        let data = self.read(REG_CHUNK_MODE_ACTIVE, 4);
2485        u32::from_be_bytes([data[0], data[1], data[2], data[3]]) != 0
2486    }
2487
2488    /// `PayloadSize`: the bytes of a block's payload as the sender builds
2489    /// it — the image, and in chunk mode the image chunk and every enabled
2490    /// chunk, each with its tag.
2491    pub fn payload_size(&self) -> u32 {
2492        let image = crate::gvsp::image_size(self.pixel_format_code(), self.width(), self.height());
2493        let size = if self.chunk_mode_active() {
2494            let enabled: Vec<u32> = [
2495                CHUNK_SELECTOR_TIMESTAMP,
2496                CHUNK_SELECTOR_EXPOSURE_TIME,
2497                CHUNK_SELECTOR_FRAME_ID,
2498                CHUNK_SELECTOR_IMAGE_INFO,
2499            ]
2500            .into_iter()
2501            .filter(|selector| self.chunk_enabled(*selector))
2502            .collect();
2503            crate::gvsp_sender::chunk_block_len(&enabled, image)
2504        } else {
2505            image
2506        };
2507        u32::try_from(size).unwrap_or(u32::MAX)
2508    }
2509
2510    /// Current exposure time in microseconds.
2511    pub fn exposure_time(&self) -> f64 {
2512        let data = self.read(REG_EXPOSURE_TIME, 8);
2513        f64::from_be_bytes([
2514            data[0], data[1], data[2], data[3], data[4], data[5], data[6], data[7],
2515        ])
2516    }
2517}
2518
2519/// Pad a string to a fixed length with null bytes.
2520fn pad_string(s: &str, len: usize) -> Vec<u8> {
2521    let mut buf = vec![0u8; len];
2522    let src = s.as_bytes();
2523    let copy_len = src.len().min(len);
2524    buf[..copy_len].copy_from_slice(&src[..copy_len]);
2525    buf
2526}
2527
2528#[cfg(test)]
2529mod tests {
2530    use super::*;
2531
2532    fn map() -> RegisterMap {
2533        RegisterMap::new(64, 48, 0x0108_0001, None, XmlProfile::Sfnc)
2534    }
2535
2536    fn select_and_enable(regs: &mut RegisterMap, event: u32, on: bool) {
2537        regs.write(REG_EVENT_SELECTOR, &event.to_be_bytes());
2538        regs.write(REG_EVENT_NOTIFICATION, &u32::from(on).to_be_bytes());
2539    }
2540
2541    /// `EventNotification` is a selected feature, so a controller enabling two
2542    /// events writes the same address twice. Backing it with a single stored
2543    /// word made the second write turn the first event off, and the fake then
2544    /// silently emitted nothing — the failure a fake exists to prevent.
2545    #[test]
2546    fn enabling_a_second_event_leaves_the_first_enabled() {
2547        let mut regs = map();
2548        select_and_enable(&mut regs, 5, true);
2549        select_and_enable(&mut regs, 6, true);
2550        assert!(regs.event_notification_on(5));
2551        assert!(regs.event_notification_on(6));
2552    }
2553
2554    /// `ChunkEnable` is a selected feature too: enabling two chunks writes
2555    /// the same address twice, with `ChunkSelector` changed in between.
2556    #[test]
2557    fn chunk_enable_follows_the_selector() {
2558        let mut regs = map();
2559        for selector in [CHUNK_SELECTOR_TIMESTAMP, CHUNK_SELECTOR_FRAME_ID] {
2560            regs.write(REG_CHUNK_SELECTOR, &selector.to_be_bytes());
2561            regs.write(REG_CHUNK_ENABLE, &1u32.to_be_bytes());
2562        }
2563        assert!(regs.chunk_enabled(CHUNK_SELECTOR_TIMESTAMP));
2564        assert!(regs.chunk_enabled(CHUNK_SELECTOR_FRAME_ID));
2565        assert!(!regs.chunk_enabled(CHUNK_SELECTOR_IMAGE_INFO));
2566        regs.write(REG_CHUNK_SELECTOR, &CHUNK_SELECTOR_IMAGE_INFO.to_be_bytes());
2567        assert_eq!(regs.read(REG_CHUNK_ENABLE, 4), vec![0, 0, 0, 0]);
2568        regs.write(REG_CHUNK_SELECTOR, &CHUNK_SELECTOR_FRAME_ID.to_be_bytes());
2569        assert_eq!(regs.read(REG_CHUNK_ENABLE, 4), vec![0, 0, 0, 1]);
2570    }
2571
2572    #[test]
2573    fn disabling_one_event_leaves_the_others_alone() {
2574        let mut regs = map();
2575        select_and_enable(&mut regs, 5, true);
2576        select_and_enable(&mut regs, 6, true);
2577        select_and_enable(&mut regs, 5, false);
2578        assert!(!regs.event_notification_on(5));
2579        assert!(regs.event_notification_on(6));
2580    }
2581
2582    /// The MAC in the bootstrap registers must be the MAC in the Discovery
2583    /// ACK. Two independent copies of one fact is how #57 happened: the ACK
2584    /// layout drifted and nothing compared it against anything.
2585    #[test]
2586    fn the_bootstrap_mac_matches_the_discovery_mac() {
2587        let regs = map();
2588        let high = regs.read(DEVICE_MAC_ADDRESS_HIGH, 4);
2589        let low = regs.read(DEVICE_MAC_ADDRESS_LOW, 4);
2590        assert_eq!(&high[..2], &[0, 0], "top two bytes are reserved");
2591        let mac = [high[2], high[3], low[0], low[1], low[2], low[3]];
2592        assert_eq!(mac, FAKE_MAC);
2593    }
2594
2595    #[test]
2596    fn set_mac_rewrites_the_bootstrap_mac() {
2597        let mut regs = map();
2598        let other = [0x02, 0x00, 0x00, 0x00, 0x00, 0x02];
2599        regs.set_mac(other);
2600        let high = regs.read(DEVICE_MAC_ADDRESS_HIGH, 4);
2601        let low = regs.read(DEVICE_MAC_ADDRESS_LOW, 4);
2602        assert_eq!(&high[..2], &[0, 0], "top two bytes are reserved");
2603        assert_eq!([high[2], high[3], low[0], low[1], low[2], low[3]], other);
2604    }
2605
2606    #[test]
2607    fn the_device_reports_one_channel_of_each_kind() {
2608        let regs = map();
2609        assert_eq!(regs.read(NUMBER_OF_MESSAGE_CHANNELS, 4), vec![0, 0, 0, 1]);
2610        assert_eq!(regs.read(NUMBER_OF_STREAM_CHANNELS, 4), vec![0, 0, 0, 1]);
2611    }
2612
2613    /// GigE Vision bootstrap: tick frequency high at 0x093C, low at 0x0940,
2614    /// so `GevSCPD` (in ticks) can be converted to time.
2615    #[test]
2616    fn the_tick_frequency_is_published_at_bootstrap() {
2617        let regs = map();
2618        assert_eq!(regs.read(0x093C, 4), vec![0, 0, 0, 0]);
2619        assert_eq!(
2620            regs.read(0x0940, 4),
2621            1_000_000_000u32.to_be_bytes().to_vec()
2622        );
2623        assert_eq!(regs.tick_frequency(), 1_000_000_000);
2624    }
2625
2626    /// GVCP Capability at 0x0934: the primary application's IP and port
2627    /// (mask 0x0800_0000), `PENDING_ACK` (0x20) and packet resend (0x4) on
2628    /// by default, resend switchable.
2629    #[test]
2630    fn the_capability_register_advertises_packet_resend() {
2631        let mut regs = map();
2632        assert_eq!(regs.read(0x0934, 4), vec![0x08, 0, 0, 0x27]);
2633        assert!(regs.packet_resend_supported());
2634        regs.set_packet_resend(false);
2635        assert_eq!(regs.read(0x0934, 4), vec![0x08, 0, 0, 0x23]);
2636        assert!(!regs.packet_resend_supported());
2637    }
2638
2639    /// `PENDING_ACK` is sent only when the capability says so *and* the
2640    /// controller set bit `0x2` of GVCP Configuration (0x0954).
2641    #[test]
2642    fn pending_ack_needs_the_capability_and_the_enable_bit() {
2643        let mut regs = map();
2644        assert!(!regs.pending_ack_enabled(), "off until enabled");
2645        regs.write(0x0954, &2u32.to_be_bytes());
2646        assert!(regs.pending_ack_enabled());
2647        regs.set_pending_ack_supported(false);
2648        assert!(!regs.pending_ack_enabled(), "not without the capability");
2649    }
2650
2651    /// CCP belongs to the address and port that claimed it: another may read
2652    /// but not write or claim, until the owner writes 0. With the exclusive
2653    /// bit, another may not even read.
2654    #[test]
2655    fn control_belongs_to_the_application_that_claimed_it() {
2656        let owner: SocketAddr = "127.0.0.1:50001".parse().unwrap();
2657        let other: SocketAddr = "127.0.0.1:50002".parse().unwrap();
2658        let mut regs = map();
2659        assert!(
2660            regs.may_access(other, false),
2661            "nobody controls yet: all read"
2662        );
2663        assert!(!regs.may_access(other, true), "and nobody writes");
2664        assert!(regs.write_ccp(owner, CCP_CONTROL));
2665        assert_eq!(regs.controller(), Some(owner));
2666        assert_eq!(
2667            regs.read(PRIMARY_APPLICATION_PORT, 4),
2668            50001u32.to_be_bytes()
2669        );
2670        assert_eq!(regs.read(PRIMARY_APPLICATION_IP, 4), [127, 0, 0, 1]);
2671        assert!(regs.may_access(other, false));
2672        assert!(!regs.may_access(other, true));
2673        assert!(!regs.write_ccp(other, CCP_CONTROL));
2674        assert!(!regs.write_ccp(other, 0), "only the owner releases");
2675        assert!(regs.write_ccp(owner, CCP_CONTROL | CCP_EXCLUSIVE));
2676        assert!(!regs.may_access(other, false));
2677        assert!(regs.write_ccp(owner, 0));
2678        assert_eq!(regs.controller(), None);
2679        assert_eq!(regs.read(PRIMARY_APPLICATION_IP, 4), [0, 0, 0, 0]);
2680        assert_eq!(regs.read(CONTROL_CHANNEL_PRIVILEGE, 4), vec![0, 0, 0, 0]);
2681    }
2682
2683    #[test]
2684    fn the_tick_frequency_can_be_changed() {
2685        let mut regs = map();
2686        regs.set_tick_frequency(125_000_000);
2687        assert_eq!(regs.tick_frequency(), 125_000_000);
2688        assert_eq!(regs.read(0x0940, 4), 125_000_000u32.to_be_bytes().to_vec());
2689    }
2690
2691    #[test]
2692    fn no_event_is_enabled_by_default() {
2693        let regs = map();
2694        assert!(!regs.event_notification_on(5));
2695        assert!(!regs.event_notification_on(6));
2696    }
2697
2698    /// Reading the register back must report the *selected* event, which is
2699    /// what a GenApi `EventNotification` read does.
2700    #[test]
2701    fn reading_notification_follows_the_selector() {
2702        let mut regs = map();
2703        select_and_enable(&mut regs, 5, true);
2704        regs.write(REG_EVENT_SELECTOR, &6u32.to_be_bytes());
2705        assert_eq!(regs.read(REG_EVENT_NOTIFICATION, 4), vec![0, 0, 0, 0]);
2706        regs.write(REG_EVENT_SELECTOR, &5u32.to_be_bytes());
2707        assert_eq!(regs.read(REG_EVENT_NOTIFICATION, 4), vec![0, 0, 0, 1]);
2708    }
2709
2710    /// The legacy profile replaces every marked section, so it declares the
2711    /// older names and none of the SFNC 2 ones it stands in for.
2712    #[test]
2713    fn the_legacy_profile_replaces_every_section() {
2714        let xml = genapi_xml(XmlProfile::Legacy);
2715        assert!(!xml.contains("<!-- profile:"), "a section was left in");
2716        for present in [
2717            r#"Name="ExposureTimeAbs""#,
2718            r#"Name="GainRaw""#,
2719            r#"Name="GainSelector""#,
2720            r#"Name="AcquisitionFrameRateAbs""#,
2721            r#"Name="UserSetDefaultSelector""#,
2722            r#"<Boolean Name="TLParamsLocked""#,
2723        ] {
2724            assert!(xml.contains(present), "missing {present}");
2725        }
2726        for absent in [
2727            r#"<Float Name="ExposureTime""#,
2728            r#"<Float Name="Gain""#,
2729            r#"<Float Name="AcquisitionFrameRate""#,
2730            r#"<Enumeration Name="UserSetDefault""#,
2731            "<pFeature>Gain</pFeature>",
2732        ] {
2733            assert!(!xml.contains(absent), "still declares {absent}");
2734        }
2735    }
2736
2737    /// The elements of every `<tag ...>` block in `xml`, comments' bare
2738    /// `<Tag>` mentions aside.
2739    fn blocks<'a>(xml: &'a str, tag: &str) -> Vec<&'a str> {
2740        let open = format!("<{tag} ");
2741        let close = format!("</{tag}>");
2742        let mut found = Vec::new();
2743        let mut rest = xml;
2744        while let Some(start) = rest.find(&open) {
2745            let after = &rest[start..];
2746            let end = after.find(&close).map_or(after.len(), |e| e + close.len());
2747            found.push(&after[..end]);
2748            rest = &after[end..];
2749        }
2750        found
2751    }
2752
2753    /// What EMVA's reference GenApi, and the GenApi 1.1 schema, require of
2754    /// the XML a camera serves — the rules this fake broke until GenTL
2755    /// consumers read it (ADR-0031): the schema's namespace, model and vendor
2756    /// names that are `CName_t`s, an `<Address>` only on a register node, and
2757    /// a `<pPort>` on every register. Our parser accepted all of it, which is
2758    /// why it went unnoticed.
2759    #[test]
2760    fn the_xml_is_genapi_schema_shaped() {
2761        let name_ok = |name: &str| {
2762            name.chars().next().is_some_and(|c| c.is_ascii_alphabetic())
2763                && name.chars().all(|c| c.is_ascii_alphanumeric() || c == '_')
2764        };
2765        for profile in [XmlProfile::Sfnc, XmlProfile::Legacy] {
2766            let xml = genapi_xml(profile);
2767            assert!(
2768                xml.contains(r#"xmlns="http://www.genicam.org/GenApi/Version_1_1""#),
2769                "{profile:?}: the GenApi 1.1 namespace"
2770            );
2771            for attribute in ["ModelName=\"", "VendorName=\""] {
2772                let at = xml.find(attribute).expect("attribute") + attribute.len();
2773                let value = &xml[at..at + xml[at..].find('"').expect("closing quote")];
2774                assert!(name_ok(value), "{profile:?}: {attribute}{value}");
2775            }
2776            for tag in ["Integer", "Float", "String"] {
2777                for block in blocks(&xml, tag) {
2778                    assert!(
2779                        !block.contains("<Address>"),
2780                        "{profile:?}: a <{tag}> has no address of its own:\n{block}"
2781                    );
2782                }
2783            }
2784            for tag in [
2785                "IntReg",
2786                "MaskedIntReg",
2787                "FloatReg",
2788                "StringReg",
2789                "Register",
2790                "StructReg",
2791            ] {
2792                for block in blocks(&xml, tag) {
2793                    assert!(
2794                        block.contains("<pPort>"),
2795                        "{profile:?}: every register names its port:\n{block}"
2796                    );
2797                }
2798            }
2799        }
2800    }
2801}