1use std::collections::HashSet;
4use std::io;
5use std::io::ErrorKind;
6use std::net::{IpAddr, Ipv4Addr, SocketAddr};
7use std::time::{Duration, Instant};
8
9use bytes::{BufMut, BytesMut};
10use tokio::net::UdpSocket;
11use tokio::time;
12use tracing::{debug, info, trace, warn};
13
14use crate::consts;
15use crate::gvcp::{GVCP_PORT, GvcpAckHeader, GvcpRequestHeader};
16
17const ACTION_PAYLOAD: usize = 12;
22const ACTION_PAYLOAD_SCHEDULED: usize = ACTION_PAYLOAD + 8;
27
28#[derive(Debug, Clone, PartialEq, Eq)]
30pub struct ActionParams {
31 pub device_key: u32,
33 pub group_key: u32,
35 pub group_mask: u32,
37 pub scheduled_time: Option<u64>,
44}
45
46#[derive(Debug, Default, Clone, PartialEq, Eq)]
48#[non_exhaustive]
49pub struct AckSummary {
50 pub sent: usize,
52 pub acks: usize,
54 pub refusals: Vec<ActionRefusal>,
56}
57
58#[derive(Debug, Clone, Copy, PartialEq, Eq)]
63pub struct ActionRefusal {
64 pub source: IpAddr,
66 pub status: crate::GigeStatus,
68}
69
70fn encode_payload(params: &ActionParams) -> BytesMut {
71 let mut buf = BytesMut::with_capacity(ACTION_PAYLOAD_SCHEDULED);
72 buf.put_u32(params.device_key);
73 buf.put_u32(params.group_key);
74 buf.put_u32(params.group_mask);
75 if let Some(ticks) = params.scheduled_time {
79 buf.put_u64(ticks);
80 }
81 buf
82}
83
84fn parse_ack(buf: &[u8]) -> io::Result<GvcpAckHeader> {
85 if buf.len() < 8 {
86 return Err(io::Error::new(
87 ErrorKind::InvalidData,
88 "acknowledgement shorter than GVCP header",
89 ));
90 }
91 let status = u16::from_be_bytes([buf[0], buf[1]]);
92 let opcode = u16::from_be_bytes([buf[2], buf[3]]);
93 let length = u16::from_be_bytes([buf[4], buf[5]]);
94 let request_id = u16::from_be_bytes([buf[6], buf[7]]);
95 Ok(GvcpAckHeader {
96 status: crate::GigeStatus::from_raw(status),
97 command: opcode,
98 length,
99 request_id,
100 })
101}
102
103fn is_broadcast(addr: &SocketAddr) -> bool {
104 matches!(addr.ip(), IpAddr::V4(ip) if ip == Ipv4Addr::BROADCAST)
105}
106
107pub async fn send_action(
109 broadcast: SocketAddr,
110 params: &ActionParams,
111 timeout_ms: u64,
112) -> io::Result<AckSummary> {
113 let destination = SocketAddr::new(broadcast.ip(), GVCP_PORT);
114 let local_ip = match destination.ip() {
115 IpAddr::V4(_) => IpAddr::V4(Ipv4Addr::UNSPECIFIED),
116 IpAddr::V6(_) => {
117 return Err(io::Error::new(
118 ErrorKind::InvalidInput,
119 "IPv6 destinations are not supported for actions",
120 ));
121 }
122 };
123 let socket = UdpSocket::bind(SocketAddr::new(local_ip, 0)).await?;
124 socket.set_broadcast(true)?;
128
129 let mut summary = AckSummary::default();
130 let payload = encode_payload(params);
131 let request_id = fastrand::u16(0x8000..=0xFFFE);
132 let mut flags = viva_gencp::CommandFlags::ACK_REQUIRED;
133 if is_broadcast(&destination) {
134 flags |= viva_gencp::CommandFlags::BROADCAST;
135 }
136 if params.scheduled_time.is_some() {
137 flags |= viva_gencp::CommandFlags::SCHEDULED_ACTION;
138 }
139 let header = GvcpRequestHeader {
140 flags,
141 command: consts::ACTION_COMMAND,
142 length: payload.len() as u16,
143 request_id,
144 };
145 let packet = header.encode(&payload);
146 trace!(bytes = packet.len(), %destination, request_id, "sending action command");
147 socket.send_to(&packet, destination).await?;
148 summary.sent = 1;
149
150 let timeout = Duration::from_millis(timeout_ms);
151 if timeout.is_zero() {
152 info!(acks = 0, "action command sent (no wait)");
153 return Ok(summary);
154 }
155
156 let start = Instant::now();
157 let mut buf = vec![0u8; 512];
158 let mut seen = HashSet::new();
159 while let Some(remaining) = timeout.checked_sub(start.elapsed()) {
160 if remaining.is_zero() {
161 break;
162 }
163 match time::timeout(remaining, socket.recv_from(&mut buf)).await {
164 Ok(Ok((len, src))) => {
165 trace!(bytes = len, %src, "received acknowledgement");
166 let header = parse_ack(&buf[..len])?;
167 if header.request_id != request_id {
168 debug!(
169 expected = request_id,
170 got = header.request_id,
171 "acknowledgement id mismatch"
172 );
173 continue;
174 }
175 if !matches!(header.command, consts::ACTION_ACK | consts::ACTION_COMMAND) {
177 debug!(
178 opcode = header.command,
179 "ignoring unrelated acknowledgement"
180 );
181 continue;
182 }
183 if !header.status.is_success() {
184 warn!(status = %header.status, %src, "device refused the action command");
185 if !summary.refusals.iter().any(|r| r.source == src.ip()) {
186 summary.refusals.push(ActionRefusal {
187 source: src.ip(),
188 status: header.status,
189 });
190 }
191 continue;
192 }
193 if header.command == consts::ACTION_ACK && seen.insert(src.ip()) {
194 summary.acks += 1;
195 }
196 }
197 Ok(Err(err)) => {
198 warn!(?err, "error receiving acknowledgement");
199 break;
200 }
201 Err(_) => break,
202 }
203 }
204
205 info!(
206 acks = summary.acks,
207 refused = summary.refusals.len(),
208 "action command completed"
209 );
210 Ok(summary)
211}
212
213#[cfg(test)]
214mod tests {
215 use super::*;
216
217 fn params() -> ActionParams {
218 ActionParams {
219 device_key: 0x1122_3344,
220 group_key: 0x5566_7788,
221 group_mask: 0xFFFF_0000,
222 scheduled_time: None,
223 }
224 }
225
226 #[test]
233 fn unscheduled_action_matches_spec_bytes() {
234 let payload = encode_payload(¶ms());
235 let packet = GvcpRequestHeader {
236 flags: viva_gencp::CommandFlags::ACK_REQUIRED,
237 command: consts::ACTION_COMMAND,
238 length: payload.len() as u16,
239 request_id: 0xBEEF,
240 }
241 .encode(&payload);
242
243 #[rustfmt::skip]
244 let expected: [u8; 20] = [
245 0x42, 0x01, 0x01, 0x00, 0x00, 0x0C, 0xBE, 0xEF, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88, 0xFF, 0xFF, 0x00, 0x00, ];
254 assert_eq!(&packet[..], &expected[..]);
255 }
256
257 #[test]
260 fn scheduled_action_sets_flag_and_appends_time() {
261 let mut p = params();
262 p.scheduled_time = Some(0x0102_0304_0506_0708);
263 let payload = encode_payload(&p);
264 let mut flags = viva_gencp::CommandFlags::ACK_REQUIRED;
265 flags |= viva_gencp::CommandFlags::SCHEDULED_ACTION;
266 let packet = GvcpRequestHeader {
267 flags,
268 command: consts::ACTION_COMMAND,
269 length: payload.len() as u16,
270 request_id: 0xBEEF,
271 }
272 .encode(&payload);
273
274 #[rustfmt::skip]
275 let expected: [u8; 28] = [
276 0x42,
277 0x81, 0x01, 0x00,
279 0x00, 0x14, 0xBE, 0xEF,
281 0x11, 0x22, 0x33, 0x44,
282 0x55, 0x66, 0x77, 0x88,
283 0xFF, 0xFF, 0x00, 0x00,
284 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08,
286 ];
287 assert_eq!(&packet[..], &expected[..]);
288 assert_eq!(payload.len(), ACTION_PAYLOAD_SCHEDULED);
289 }
290
291 #[test]
292 fn unscheduled_payload_stops_at_twelve_bytes() {
293 assert_eq!(encode_payload(¶ms()).len(), ACTION_PAYLOAD);
294 }
295
296 #[test]
298 fn action_opcodes_do_not_collide_with_register_access() {
299 assert_eq!(consts::ACTION_COMMAND, 0x0100);
300 assert_eq!(consts::ACTION_ACK, 0x0101);
301 assert_ne!(consts::ACTION_COMMAND, 0x0080); assert_ne!(consts::ACTION_ACK, 0x0081); }
304
305 #[test]
306 fn ack_parser() {
307 let mut buf = BytesMut::with_capacity(8);
308 buf.put_u16(viva_gencp::StatusCode::Success.to_raw());
309 buf.put_u16(consts::ACTION_ACK);
310 buf.put_u16(0);
311 buf.put_u16(0xBEEF);
312 let ack = parse_ack(&buf).expect("ack");
313 assert_eq!(ack.command, consts::ACTION_ACK);
314 assert_eq!(ack.request_id, 0xBEEF);
315 }
316}