Skip to main content

viva_genapi/nodemap/
ports.rs

1//! Ports: where a register's address points (GA-12, ADR-0026).
2//!
3//! GenICam Standard v2.1.1 §2.8.16: every register reaches its bytes through a
4//! `<Port>`, named by `<pPort>`. The device port forwards to the transport —
5//! here the [`RegisterIo`] passed to each call. A port with a `<ChunkID>`
6//! "does not give access to a real device, but rather to the chunk of data
7//! residing in memory", and a port with an `<EventID>` likewise to the data an
8//! event message carries. Their addresses count from the start of that chunk
9//! or event, so reading one from device memory reads something else entirely:
10//! GVCP bootstrap registers, or a `BAD_ALIGNMENT` refusal for a 2-byte read at
11//! address 0x2 (#112).
12//!
13//! So a register on a chunk or event port reads only data attached to the
14//! nodemap — [`NodeMap::attach_chunks`], [`NodeMap::attach_event`] — and is
15//! an error, never a device read, when nothing is. Attaching or detaching
16//! invalidates everything that depends on the port, so a cached value never
17//! outlives the data it was read from. Writes to those ports are refused.
18
19use std::collections::{HashMap, HashSet};
20
21use bytes::Bytes;
22use viva_genapi_xml::{Addressing, PortKind};
23
24use super::NodeMap;
25use crate::nodes::{Node, node_addressing};
26use crate::{GenApiError, RegisterIo};
27
28/// The chunks of one stream buffer, by chunk ID: what a nodemap's chunk ports
29/// read.
30///
31/// Built by the transport layer, which knows the buffer's chunk layout —
32/// `viva-genicam`'s `Frame` makes one from a GigE Vision payload. Each chunk
33/// is a [`Bytes`] slice of the buffer, so building and attaching one copies no
34/// image data.
35///
36/// When a buffer carries two chunks with the same ID, the first one pushed is
37/// the one ports read.
38#[derive(Clone, Default, PartialEq, Eq)]
39pub struct ChunkData {
40    chunks: Vec<(u64, Bytes)>,
41}
42
43impl ChunkData {
44    /// No chunks.
45    pub fn new() -> Self {
46        Self::default()
47    }
48
49    /// Add the data of chunk `id`.
50    pub fn push(&mut self, id: u64, data: Bytes) {
51        self.chunks.push((id, data));
52    }
53
54    /// The data of chunk `id`, if the buffer carried one.
55    pub fn get(&self, id: u64) -> Option<&Bytes> {
56        self.chunks
57            .iter()
58            .find(|(chunk, _)| *chunk == id)
59            .map(|(_, data)| data)
60    }
61
62    /// Every chunk, in the order pushed.
63    pub fn iter(&self) -> impl Iterator<Item = (u64, &Bytes)> {
64        self.chunks.iter().map(|(id, data)| (*id, data))
65    }
66
67    /// The chunk IDs, in the order pushed.
68    pub fn ids(&self) -> impl Iterator<Item = u64> + '_ {
69        self.chunks.iter().map(|(id, _)| *id)
70    }
71
72    /// Number of chunks.
73    pub fn len(&self) -> usize {
74        self.chunks.len()
75    }
76
77    /// Whether there are none.
78    pub fn is_empty(&self) -> bool {
79        self.chunks.is_empty()
80    }
81}
82
83impl FromIterator<(u64, Bytes)> for ChunkData {
84    fn from_iter<I: IntoIterator<Item = (u64, Bytes)>>(iter: I) -> Self {
85        Self {
86            chunks: iter.into_iter().collect(),
87        }
88    }
89}
90
91/// Lengths only: a chunk can be a whole image.
92impl std::fmt::Debug for ChunkData {
93    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
94        f.debug_map()
95            .entries(
96                self.chunks
97                    .iter()
98                    .map(|(id, data)| (format!("{id:#x}"), data.len())),
99            )
100            .finish()
101    }
102}
103
104/// Data attached to a nodemap's chunk and event ports.
105#[derive(Default)]
106pub(crate) struct Attached {
107    pub(crate) chunks: ChunkData,
108    pub(crate) events: HashMap<u64, Bytes>,
109}
110
111impl std::fmt::Debug for Attached {
112    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
113        let mut events: Vec<(String, usize)> = self
114            .events
115            .iter()
116            .map(|(id, data)| (format!("{id:#x}"), data.len()))
117            .collect();
118        events.sort();
119        f.debug_struct("Attached")
120            .field("chunks", &self.chunks)
121            .field("events", &events)
122            .finish()
123    }
124}
125
126/// Where a register's bytes are, once its address is resolved.
127pub(crate) enum Location<'a> {
128    /// Device memory, through the transport.
129    Device { address: u64, len: u32 },
130    /// Bytes attached to a chunk or event port.
131    Data {
132        port: &'a str,
133        bytes: &'a Bytes,
134        /// Resolved offset; negative only on a chunk port.
135        offset: i64,
136        len: u32,
137        /// Whether a negative offset counts from the end (chunk ports).
138        from_end: bool,
139    },
140}
141
142/// The port a register is on, before anything is read.
143enum Route<'a> {
144    Device,
145    Chunk { port: &'a str, id: u64 },
146    Event { port: &'a str, id: u64 },
147}
148
149impl NodeMap {
150    /// Attach one stream buffer's chunks, replacing any attached before.
151    ///
152    /// Every register on a chunk port reads from `chunks` until the next
153    /// attach or [`NodeMap::detach_chunks`]; a chunk port whose ID `chunks`
154    /// lacks reads as [`GenApiError::NotAttached`]. Everything that depends on
155    /// a chunk port is invalidated, so nothing read from the previous buffer
156    /// survives. The chunk data is shared, not copied.
157    pub fn attach_chunks(&mut self, chunks: &ChunkData) {
158        self.attached.chunks = chunks.clone();
159        self.invalidate_ports(|kind| matches!(kind, PortKind::Chunk { .. }));
160    }
161
162    /// Detach the chunks attached by [`NodeMap::attach_chunks`]. Chunk
163    /// features then read as [`GenApiError::NotAttached`].
164    pub fn detach_chunks(&mut self) {
165        self.attached.chunks = ChunkData::default();
166        self.invalidate_ports(|kind| matches!(kind, PortKind::Chunk { .. }));
167    }
168
169    /// Attach one event's bytes to the ports whose `<EventID>` is `event_id`,
170    /// replacing the previous event with that ID.
171    ///
172    /// `data` is the event as the device sent it, header included: event-port
173    /// addresses count from its first byte. Every corpus document that names
174    /// an event's timestamp puts it at 0x8 on a 16-bit-block-id GigE Vision
175    /// event, where the header's timestamp field is. Other event IDs keep
176    /// what was attached for them, as GenApi's event model keeps the last
177    /// event of each kind.
178    pub fn attach_event(&mut self, event_id: u64, data: Bytes) {
179        self.attached.events.insert(event_id, data);
180        self.invalidate_ports(|kind| *kind == PortKind::Event { event_id });
181    }
182
183    /// Detach every event attached by [`NodeMap::attach_event`].
184    pub fn detach_events(&mut self) {
185        self.attached.events.clear();
186        self.invalidate_ports(|kind| matches!(kind, PortKind::Event { .. }));
187    }
188
189    /// The ports the document declares, with what each reads, in name order.
190    pub fn ports(&self) -> Vec<(&str, PortKind)> {
191        let mut ports: Vec<(&str, PortKind)> = self
192            .ports
193            .iter()
194            .map(|(name, kind)| (name.as_str(), *kind))
195            .collect();
196        ports.sort_by(|a, b| a.0.cmp(b.0));
197        ports
198    }
199
200    /// The features whose value depends on `port`: category members reached
201    /// from the registers on it through `<pValue>` chains, formulas and the
202    /// other edges [`NodeMap::dependents`] records. Sorted by name; empty for
203    /// a port nothing reads.
204    ///
205    /// For FLIR's `TimestampPort` that is `ChunkTimestamp`, an `<Integer>`
206    /// over the `ChunkTimestamp_Val` register on the port — the feature, not
207    /// the register behind it.
208    pub fn port_features(&self, port: &str) -> Vec<&str> {
209        let features: HashSet<&str> = self
210            .nodes
211            .values()
212            .filter_map(|node| match node {
213                Node::Category(cat) => Some(cat.children.iter().map(String::as_str)),
214                _ => None,
215            })
216            .flatten()
217            .collect();
218        let mut seen: HashSet<&str> = HashSet::new();
219        let mut pending: Vec<&str> = self.dependents(port).iter().map(String::as_str).collect();
220        while let Some(name) = pending.pop() {
221            if !seen.insert(name) {
222                continue;
223            }
224            pending.extend(self.dependents(name).iter().map(String::as_str));
225        }
226        let mut out: Vec<&str> = seen
227            .into_iter()
228            .filter(|name| features.contains(name) && self.nodes.contains_key(*name))
229            .collect();
230        out.sort_unstable();
231        out
232    }
233
234    /// Record each register on a chunk or event port as a dependent of the
235    /// port, so that attaching new data invalidates it and everything above
236    /// it.
237    pub(super) fn link_port_dependents(&mut self) {
238        let mut links: Vec<(String, String)> = Vec::new();
239        for node in self.nodes.values() {
240            let Some(port) = node_addressing(node).and_then(Addressing::port) else {
241                continue;
242            };
243            if matches!(
244                self.ports.get(port),
245                Some(PortKind::Chunk { .. } | PortKind::Event { .. })
246            ) {
247                links.push((port.to_string(), node.name().to_string()));
248            }
249        }
250        for (port, node) in links {
251            let list = self.dependents.entry(port).or_default();
252            if !list.contains(&node) {
253                list.push(node);
254            }
255        }
256    }
257
258    fn invalidate_ports(&self, which: impl Fn(&PortKind) -> bool) {
259        for (name, kind) in &self.ports {
260            if which(kind) {
261                self.invalidate_dependents(name);
262            }
263        }
264        self.bump_generation();
265    }
266
267    /// The port `addressing` is on. A `<pPort>` naming no declared port is
268    /// refused unless it names `Device`, which documents also use without
269    /// declaring it.
270    fn route<'a>(
271        &'a self,
272        node: &str,
273        addressing: &'a Addressing,
274    ) -> Result<Route<'a>, GenApiError> {
275        let Some(port) = addressing.port() else {
276            return Ok(Route::Device);
277        };
278        match self.ports.get(port) {
279            Some(PortKind::Device) => Ok(Route::Device),
280            Some(PortKind::Chunk { chunk_id }) => Ok(Route::Chunk {
281                port,
282                id: *chunk_id,
283            }),
284            Some(PortKind::Event { event_id }) => Ok(Route::Event {
285                port,
286                id: *event_id,
287            }),
288            None if port.eq_ignore_ascii_case("Device") => Ok(Route::Device),
289            _ => Err(GenApiError::UnknownPort {
290                node: node.to_string(),
291                port: port.to_string(),
292            }),
293        }
294    }
295
296    /// Where `node`'s bytes are for a read.
297    ///
298    /// The port comes first: a chunk or event port with nothing attached is
299    /// [`GenApiError::NotAttached`] before any address term is evaluated, so
300    /// the device is not touched at all.
301    pub(crate) fn locate<'a>(
302        &'a self,
303        node: &str,
304        addressing: &'a Addressing,
305        io: &dyn RegisterIo,
306    ) -> Result<Location<'a>, GenApiError> {
307        let (port, bytes, from_end) = match self.route(node, addressing)? {
308            Route::Device => {
309                let (address, len) = self.resolve_device_address(node, addressing, io)?;
310                return Ok(Location::Device { address, len });
311            }
312            Route::Chunk { port, id } => (port, self.attached.chunks.get(id), true),
313            Route::Event { port, id } => (port, self.attached.events.get(&id), false),
314        };
315        let bytes = bytes.ok_or_else(|| GenApiError::NotAttached {
316            node: node.to_string(),
317            port: port.to_string(),
318        })?;
319        let (offset, len) = self.resolve_address(node, addressing, io)?;
320        Ok(Location::Data {
321            port,
322            bytes,
323            // The sum wraps like the device address does; on a chunk port
324            // its two's-complement reading is the signed offset §2.8.16
325            // allows.
326            offset: offset as i64,
327            len,
328            from_end,
329        })
330    }
331
332    /// The device address `node` writes to. A chunk or event port is refused
333    /// whether or not anything is attached to it.
334    pub(crate) fn locate_for_write(
335        &self,
336        node: &str,
337        addressing: &Addressing,
338        io: &dyn RegisterIo,
339    ) -> Result<(u64, u32), GenApiError> {
340        match self.route(node, addressing)? {
341            Route::Device => self.resolve_device_address(node, addressing, io),
342            Route::Chunk { port, .. } | Route::Event { port, .. } => {
343                Err(GenApiError::PortNotWritable {
344                    node: node.to_string(),
345                    port: port.to_string(),
346                })
347            }
348        }
349    }
350
351    /// Read the bytes at `location`.
352    pub(crate) fn read_location(
353        &self,
354        node: &str,
355        location: &Location<'_>,
356        io: &dyn RegisterIo,
357    ) -> Result<Vec<u8>, GenApiError> {
358        match *location {
359            Location::Device { address, len } => io.read(address, len as usize),
360            Location::Data {
361                port,
362                bytes,
363                offset,
364                len,
365                from_end,
366            } => slice_port_data(node, port, bytes, offset, len, from_end).map(<[u8]>::to_vec),
367        }
368    }
369}
370
371/// `len` bytes at `offset` of a port's data. On a chunk port a negative offset
372/// is "interpreted as offset from the back of the chunk" (GenICam Standard
373/// v2.1.1 §2.8.16): `-4` is the last four bytes. Anything outside the data is
374/// an error naming the offset.
375fn slice_port_data<'a>(
376    node: &str,
377    port: &str,
378    bytes: &'a [u8],
379    offset: i64,
380    len: u32,
381    from_end: bool,
382) -> Result<&'a [u8], GenApiError> {
383    let size = bytes.len();
384    let out_of_range = || GenApiError::PortOutOfRange {
385        node: node.to_string(),
386        port: port.to_string(),
387        offset,
388        len,
389        size,
390    };
391    let start = if offset < 0 {
392        if !from_end {
393            return Err(out_of_range());
394        }
395        let back = usize::try_from(offset.unsigned_abs()).map_err(|_| out_of_range())?;
396        size.checked_sub(back).ok_or_else(out_of_range)?
397    } else {
398        usize::try_from(offset).map_err(|_| out_of_range())?
399    };
400    let end = start
401        .checked_add(len as usize)
402        .filter(|end| *end <= size)
403        .ok_or_else(out_of_range)?;
404    Ok(&bytes[start..end])
405}
406
407#[cfg(test)]
408mod tests {
409    use super::*;
410
411    #[test]
412    fn a_negative_offset_counts_from_the_end_of_a_chunk() {
413        let data = [1u8, 2, 3, 4, 5, 6, 7, 8];
414        assert_eq!(
415            slice_port_data("n", "p", &data, -4, 4, true).expect("in range"),
416            &[5, 6, 7, 8]
417        );
418        assert_eq!(
419            slice_port_data("n", "p", &data, -8, 2, true).expect("in range"),
420            &[1, 2]
421        );
422    }
423
424    #[test]
425    fn out_of_range_is_an_error_not_a_panic() {
426        let data = [0u8; 8];
427        for (offset, len, from_end) in [
428            (-9, 1, true),
429            (-4, 8, true),
430            (-1, 1, false),
431            (7, 2, false),
432            (8, 1, false),
433            (i64::MIN, 4, true),
434            (i64::MAX, 4, true),
435            (0, u32::MAX, true),
436        ] {
437            let err = slice_port_data("n", "p", &data, offset, len, from_end)
438                .expect_err("outside the data");
439            assert!(
440                matches!(err, GenApiError::PortOutOfRange { size: 8, .. }),
441                "{err}"
442            );
443        }
444    }
445
446    #[test]
447    fn chunk_data_reads_the_first_chunk_with_an_id() {
448        let chunks: ChunkData = [
449            (1, Bytes::from_static(b"one")),
450            (2, Bytes::from_static(b"two")),
451            (1, Bytes::from_static(b"again")),
452        ]
453        .into_iter()
454        .collect();
455        assert_eq!(chunks.get(1).map(|b| &b[..]), Some(&b"one"[..]));
456        assert_eq!(chunks.get(3), None);
457        assert_eq!(chunks.ids().collect::<Vec<_>>(), vec![1, 2, 1]);
458        assert_eq!(format!("{chunks:?}"), r#"{"0x1": 3, "0x2": 3, "0x1": 5}"#);
459    }
460}