1use std::collections::VecDeque;
26use std::net::SocketAddr;
27use std::sync::Arc;
28use std::sync::atomic::{AtomicU64, Ordering};
29
30use tokio::net::UdpSocket;
31
32use crate::gvsp::{Datagram, header_only};
33
34pub(crate) use viva_gige::consts::PACKET_RESEND_COMMAND as PACKETRESEND_CMD;
36use viva_gige::consts::PACKET_RESEND_EXTENDED_IDS as EXTENDED_IDS_FLAG;
37pub(crate) const STATUS_PACKET_UNAVAILABLE: u16 = viva_gige::GigeStatus::PacketUnavailable.to_raw();
39pub const DEFAULT_RETENTION: usize = 4;
41
42#[derive(Debug, Clone, Copy, PartialEq, Eq)]
44pub struct ResendRequest {
45 pub channel: u16,
47 pub block_id: u64,
49 pub first: u32,
51 pub last: u32,
53 pub extended_ids: bool,
55}
56
57pub fn parse_request(flags: u8, payload: &[u8]) -> Option<ResendRequest> {
60 let u16_at = |at: usize| u16::from_be_bytes([payload[at], payload[at + 1]]);
61 let u32_at = |at: usize| {
62 u32::from_be_bytes([
63 payload[at],
64 payload[at + 1],
65 payload[at + 2],
66 payload[at + 3],
67 ])
68 };
69 if flags & EXTENDED_IDS_FLAG != 0 {
70 if payload.len() < 20 {
71 return None;
72 }
73 let mut block = [0u8; 8];
74 block.copy_from_slice(&payload[12..20]);
75 Some(ResendRequest {
76 channel: u16_at(0),
77 block_id: u64::from_be_bytes(block),
78 first: u32_at(4),
79 last: u32_at(8),
80 extended_ids: true,
81 })
82 } else {
83 if payload.len() < 12 {
84 return None;
85 }
86 Some(ResendRequest {
87 channel: u16_at(0),
88 block_id: u64::from(u16_at(2)),
89 first: u32_at(4) & 0x00FF_FFFF,
90 last: u32_at(8) & 0x00FF_FFFF,
91 extended_ids: false,
92 })
93 }
94}
95
96#[derive(Debug, Default)]
98pub struct ResendCounters {
99 requests: AtomicU64,
100 packets_resent: AtomicU64,
101 packets_unavailable: AtomicU64,
102}
103
104#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
106pub struct ResendStats {
107 pub requests: u64,
109 pub packets_resent: u64,
111 pub packets_unavailable: u64,
113}
114
115impl ResendCounters {
116 pub fn snapshot(&self) -> ResendStats {
118 ResendStats {
119 requests: self.requests.load(Ordering::Relaxed),
120 packets_resent: self.packets_resent.load(Ordering::Relaxed),
121 packets_unavailable: self.packets_unavailable.load(Ordering::Relaxed),
122 }
123 }
124}
125
126#[derive(Debug, Clone)]
128pub(crate) struct StreamPath {
129 pub socket: Arc<UdpSocket>,
130 pub dest: SocketAddr,
131 pub max_on_wire: Option<u32>,
132}
133
134#[derive(Debug)]
136pub(crate) struct Retention {
137 capacity: usize,
138 blocks: VecDeque<(u64, Vec<Vec<u8>>)>,
139 path: Option<StreamPath>,
140}
141
142#[derive(Debug, Default, PartialEq, Eq)]
145pub(crate) struct Answer {
146 pub resend: Vec<Vec<u8>>,
147 pub unavailable: Vec<Vec<u8>>,
148}
149
150impl Retention {
151 pub fn new(capacity: usize) -> Self {
152 Self {
153 capacity,
154 blocks: VecDeque::new(),
155 path: None,
156 }
157 }
158
159 pub fn set_path(&mut self, path: StreamPath) {
160 self.path = Some(path);
161 }
162
163 pub fn path(&self) -> Option<StreamPath> {
164 self.path.clone()
165 }
166
167 pub fn retain(&mut self, block_id: u64, datagrams: &[Datagram]) {
169 if self.capacity == 0 {
170 return;
171 }
172 let mut by_id: Vec<Vec<u8>> = Vec::new();
173 for d in datagrams {
174 let at = d.packet_id as usize;
175 if by_id.len() <= at {
176 by_id.resize(at + 1, Vec::new());
177 }
178 by_id[at] = d.bytes.clone();
179 }
180 self.blocks.retain(|(id, _)| *id != block_id);
181 while self.blocks.len() >= self.capacity {
182 self.blocks.pop_front();
183 }
184 self.blocks.push_back((block_id, by_id));
185 }
186
187 pub fn answer(&self, request: &ResendRequest) -> Answer {
190 let mut answer = Answer::default();
191 if request.first > request.last {
192 return answer;
193 }
194 let held = self
195 .blocks
196 .iter()
197 .find(|(id, _)| *id == request.block_id)
198 .map(|(_, packets)| packets);
199 for id in request.first..=request.last {
200 match held
201 .and_then(|p| p.get(id as usize))
202 .filter(|b| !b.is_empty())
203 {
204 Some(bytes) => answer.resend.push(bytes.clone()),
205 None => answer.unavailable.push(header_only(
206 request.block_id,
207 request.extended_ids,
208 id,
209 STATUS_PACKET_UNAVAILABLE,
210 )),
211 }
212 }
213 answer
214 }
215}
216
217pub(crate) async fn serve(
220 supported: bool,
221 retention: &std::sync::Mutex<Retention>,
222 counters: &ResendCounters,
223 flags: u8,
224 payload: &[u8],
225) {
226 counters.requests.fetch_add(1, Ordering::Relaxed);
227 if !supported {
228 tracing::debug!("PACKETRESEND_CMD ignored: the device does not support resend");
229 return;
230 }
231 let Some(request) = parse_request(flags, payload) else {
232 tracing::debug!(len = payload.len(), "malformed PACKETRESEND_CMD");
233 return;
234 };
235 let (answer, path) = match retention.lock() {
236 Ok(retention) => (retention.answer(&request), retention.path()),
237 Err(_) => return,
238 };
239 let Some(path) = path else {
240 return;
241 };
242 tracing::debug!(?request, resent = answer.resend.len(), "PACKETRESEND_CMD");
243 for packet in &answer.resend {
244 let on_wire = packet.len() + 28;
245 if path.max_on_wire.is_some_and(|max| on_wire > max as usize) {
246 continue;
247 }
248 if path.socket.send_to(packet, path.dest).await.is_ok() {
249 counters.packets_resent.fetch_add(1, Ordering::Relaxed);
250 }
251 }
252 for packet in &answer.unavailable {
253 counters.packets_unavailable.fetch_add(1, Ordering::Relaxed);
254 let _ = path.socket.send_to(packet, path.dest).await;
255 }
256}
257
258#[cfg(test)]
259mod tests {
260 use super::*;
261 use crate::gvsp::{BlockSpec, block_datagrams};
262
263 #[test]
265 fn a_standard_request_is_read_at_its_own_offsets() {
266 #[rustfmt::skip]
267 let payload = [
268 0x00, 0x02, 0x12, 0x34, 0xFF, 0x00, 0x00, 0x05, 0x00, 0x00, 0x00, 0x09, ];
273 assert_eq!(
274 parse_request(0x00, &payload),
275 Some(ResendRequest {
276 channel: 2,
277 block_id: 0x1234,
278 first: 5,
279 last: 9,
280 extended_ids: false,
281 })
282 );
283 assert_eq!(parse_request(0x00, &payload[..11]), None);
284 }
285
286 #[test]
287 fn an_extended_request_is_read_at_its_own_offsets() {
288 #[rustfmt::skip]
289 let payload = [
290 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x05, 0x01, 0x00, 0x00, 0x07, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x02, ];
296 assert_eq!(
297 parse_request(0x10, &payload),
298 Some(ResendRequest {
299 channel: 0,
300 block_id: (1 << 32) + 2,
301 first: 0x0100_0005,
302 last: 0x0100_0007,
303 extended_ids: true,
304 })
305 );
306 assert_eq!(parse_request(0x10, &payload[..19]), None);
307 }
308
309 fn block(id: u64) -> Vec<Datagram> {
310 block_datagrams(
311 &BlockSpec::image(id, 10, 1, 0x0108_0001, 28 + 8 + 4),
312 &[7u8; 10],
313 )
314 }
315
316 fn request(block_id: u64, first: u32, last: u32) -> ResendRequest {
317 ResendRequest {
318 channel: 0,
319 block_id,
320 first,
321 last,
322 extended_ids: false,
323 }
324 }
325
326 #[test]
327 fn a_retained_range_is_sent_again_as_built() {
328 let mut retention = Retention::new(2);
329 let datagrams = block(1);
330 retention.retain(1, &datagrams);
331 let answer = retention.answer(&request(1, 1, 2));
332 assert_eq!(
333 answer.resend,
334 vec![datagrams[1].bytes.clone(), datagrams[2].bytes.clone()]
335 );
336 assert!(answer.unavailable.is_empty());
337 }
338
339 #[test]
340 fn a_block_beyond_retention_is_answered_unavailable() {
341 let mut retention = Retention::new(2);
342 for id in 1..=3 {
343 retention.retain(id, &block(id));
344 }
345 let answer = retention.answer(&request(1, 2, 3));
346 assert!(answer.resend.is_empty());
347 assert_eq!(
349 answer.unavailable,
350 [
351 vec![0x80, 0x0C, 0x00, 0x01, 0x03, 0x00, 0x00, 0x02],
352 vec![0x80, 0x0C, 0x00, 0x01, 0x03, 0x00, 0x00, 0x03],
353 ]
354 );
355 assert_eq!(retention.answer(&request(3, 1, 1)).resend.len(), 1);
357 }
358}