openigtlink-rust 0.4.1

Rust implementation of the OpenIGTLink protocol for image-guided therapy
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
//! UDP-based OpenIGTLink communication
//!
//! Provides connectionless UDP transport for low-latency applications where
//! occasional packet loss is acceptable (e.g., real-time tracking).
//!
//! # Important Notes
//!
//! - **No delivery guarantee**: UDP does not guarantee message delivery or ordering
//! - **MTU limitation**: Single UDP datagram limited to ~65507 bytes
//! - **Use cases**: High-frequency tracking data (>60Hz), non-critical status updates
//! - **Not recommended for**: Large images, critical commands, file transfers
//!
//! # Example: High-Speed Tracking
//!
//! ```no_run
//! use openigtlink_rust::io::UdpClient;
//! use openigtlink_rust::protocol::types::TransformMessage;
//! use openigtlink_rust::protocol::message::IgtlMessage;
//!
//! // Client sends tracking data at 120Hz
//! let client = UdpClient::bind("0.0.0.0:0")?;
//!
//! loop {
//!     let transform = TransformMessage::identity();
//!     let msg = IgtlMessage::new(transform, "Tracker")?;
//!     client.send_to(&msg, "127.0.0.1:18944")?;
//!     std::thread::sleep(std::time::Duration::from_millis(8)); // 120Hz
//! }
//! # Ok::<(), openigtlink_rust::error::IgtlError>(())
//! ```

use std::net::{SocketAddr, UdpSocket};
use std::time::Duration;

use crate::error::{IgtlError, Result};
use crate::protocol::message::{IgtlMessage, Message};

/// Maximum UDP datagram size (IPv4 max - IP header - UDP header)
/// 65535 (max IP packet) - 20 (IP header) - 8 (UDP header) = 65507 bytes
pub const MAX_UDP_DATAGRAM_SIZE: usize = 65507;

/// UDP client for sending/receiving OpenIGTLink messages
///
/// Provides connectionless communication with low overhead. Suitable for
/// high-frequency updates where occasional packet loss is acceptable.
///
/// # Performance Characteristics
///
/// - **Latency**: Lower than TCP (no connection setup, no retransmission)
/// - **Throughput**: Limited by network MTU (~1500 bytes typical Ethernet)
/// - **Reliability**: None (packets may be lost, duplicated, or reordered)
///
/// # Examples
///
/// ```no_run
/// use openigtlink_rust::io::UdpClient;
/// use openigtlink_rust::protocol::types::TransformMessage;
/// use openigtlink_rust::protocol::message::IgtlMessage;
///
/// let client = UdpClient::bind("0.0.0.0:0")?;
/// let transform = TransformMessage::identity();
/// let msg = IgtlMessage::new(transform, "Tool")?;
/// client.send_to(&msg, "192.168.1.100:18944")?;
/// # Ok::<(), openigtlink_rust::error::IgtlError>(())
/// ```
pub struct UdpClient {
    socket: UdpSocket,
}

impl UdpClient {
    /// Bind to a local address
    ///
    /// # Arguments
    ///
    /// * `local_addr` - Local address to bind (use "0.0.0.0:0" for any available port)
    ///
    /// # Errors
    ///
    /// - [`IgtlError::Io`](crate::error::IgtlError::Io) - Failed to bind socket (address in use, permission denied, etc.)
    ///
    /// # Examples
    ///
    /// ```no_run
    /// use openigtlink_rust::io::UdpClient;
    ///
    /// // Bind to any available port
    /// let client = UdpClient::bind("0.0.0.0:0")?;
    ///
    /// // Bind to specific port
    /// let client = UdpClient::bind("0.0.0.0:18945")?;
    /// # Ok::<(), openigtlink_rust::error::IgtlError>(())
    /// ```
    pub fn bind(local_addr: &str) -> Result<Self> {
        let socket = UdpSocket::bind(local_addr)?;
        Ok(UdpClient { socket })
    }

    /// Send a message to a remote address
    ///
    /// # Arguments
    ///
    /// * `msg` - Message to send
    /// * `target` - Target address (e.g., "127.0.0.1:18944")
    ///
    /// # Errors
    ///
    /// - [`IgtlError::Io`](crate::error::IgtlError::Io) - Network transmission failed
    /// - [`IgtlError::BodyTooLarge`](crate::error::IgtlError::BodyTooLarge) - Message exceeds UDP MTU (65507 bytes)
    ///
    /// # Examples
    ///
    /// ```no_run
    /// use openigtlink_rust::io::UdpClient;
    /// use openigtlink_rust::protocol::types::TransformMessage;
    /// use openigtlink_rust::protocol::message::IgtlMessage;
    ///
    /// let client = UdpClient::bind("0.0.0.0:0")?;
    /// let transform = TransformMessage::identity();
    /// let msg = IgtlMessage::new(transform, "Device")?;
    /// client.send_to(&msg, "127.0.0.1:18944")?;
    /// # Ok::<(), openigtlink_rust::error::IgtlError>(())
    /// ```
    pub fn send_to<T: Message>(&self, msg: &IgtlMessage<T>, target: &str) -> Result<()> {
        let data = msg.encode()?;

        if data.len() > MAX_UDP_DATAGRAM_SIZE {
            return Err(IgtlError::BodyTooLarge {
                size: data.len(),
                max: MAX_UDP_DATAGRAM_SIZE,
            });
        }

        self.socket.send_to(&data, target)?;
        Ok(())
    }

    /// Receive a message (blocking)
    ///
    /// Blocks until a datagram is received. Returns the message and sender address.
    ///
    /// # Returns
    ///
    /// Tuple of (message, sender_address)
    ///
    /// # Errors
    ///
    /// - [`IgtlError::Io`](crate::error::IgtlError::Io) - Network read failed or timeout
    /// - [`IgtlError::InvalidHeader`](crate::error::IgtlError::InvalidHeader) - Malformed header
    /// - [`IgtlError::CrcMismatch`](crate::error::IgtlError::CrcMismatch) - Data corruption detected
    ///
    /// # Examples
    ///
    /// ```no_run
    /// use openigtlink_rust::io::UdpClient;
    /// use openigtlink_rust::protocol::types::TransformMessage;
    ///
    /// let client = UdpClient::bind("0.0.0.0:18944")?;
    /// let (msg, sender) = client.receive_from::<TransformMessage>()?;
    /// println!("Received from {}", sender);
    /// # Ok::<(), openigtlink_rust::error::IgtlError>(())
    /// ```
    pub fn receive_from<T: Message>(&self) -> Result<(IgtlMessage<T>, SocketAddr)> {
        let mut buf = vec![0u8; MAX_UDP_DATAGRAM_SIZE];
        let (size, src) = self.socket.recv_from(&mut buf)?;

        let msg = IgtlMessage::decode(&buf[..size])?;
        Ok((msg, src))
    }

    /// Set read timeout
    ///
    /// # Arguments
    ///
    /// * `timeout` - Timeout duration (None for blocking forever)
    ///
    /// # Errors
    ///
    /// - [`IgtlError::Io`](crate::error::IgtlError::Io) - Failed to set socket option
    ///
    /// # Examples
    ///
    /// ```no_run
    /// use openigtlink_rust::io::UdpClient;
    /// use std::time::Duration;
    ///
    /// let client = UdpClient::bind("0.0.0.0:0")?;
    /// client.set_read_timeout(Some(Duration::from_secs(5)))?;
    /// # Ok::<(), openigtlink_rust::error::IgtlError>(())
    /// ```
    pub fn set_read_timeout(&self, timeout: Option<Duration>) -> Result<()> {
        self.socket.set_read_timeout(timeout)?;
        Ok(())
    }

    /// Set write timeout
    ///
    /// # Arguments
    ///
    /// * `timeout` - Timeout duration (None for blocking forever)
    ///
    /// # Errors
    ///
    /// - [`IgtlError::Io`](crate::error::IgtlError::Io) - Failed to set socket option
    pub fn set_write_timeout(&self, timeout: Option<Duration>) -> Result<()> {
        self.socket.set_write_timeout(timeout)?;
        Ok(())
    }

    /// Get local socket address
    ///
    /// # Errors
    ///
    /// - [`IgtlError::Io`](crate::error::IgtlError::Io) - Failed to get socket address
    pub fn local_addr(&self) -> Result<SocketAddr> {
        Ok(self.socket.local_addr()?)
    }
}

/// UDP server for receiving OpenIGTLink messages
///
/// Listens for incoming datagrams on a specific port.
///
/// # Examples
///
/// ```no_run
/// use openigtlink_rust::io::UdpServer;
/// use openigtlink_rust::protocol::types::TransformMessage;
/// use openigtlink_rust::protocol::message::IgtlMessage;
///
/// # fn main() -> Result<(), openigtlink_rust::error::IgtlError> {
/// let server = UdpServer::bind("0.0.0.0:18944")?;
///
/// # let mut count = 0;
/// loop {
///     let (msg, sender) = server.receive::<TransformMessage>()?;
///     println!("Received from {}", sender);
///
///     // Echo back
///     let response = IgtlMessage::new(msg.content, "Server")?;
///     server.send_to(&response, sender)?;
///
///     # count += 1;
///     # if count >= 1 { break; }
/// }
/// # Ok(())
/// # }
/// ```
pub struct UdpServer {
    socket: UdpSocket,
}

impl UdpServer {
    /// Bind server to an address
    ///
    /// # Arguments
    ///
    /// * `addr` - Address to bind (e.g., "0.0.0.0:18944")
    ///
    /// # Errors
    ///
    /// - [`IgtlError::Io`](crate::error::IgtlError::Io) - Failed to bind (port in use, permission denied, etc.)
    ///
    /// # Examples
    ///
    /// ```no_run
    /// use openigtlink_rust::io::UdpServer;
    ///
    /// let server = UdpServer::bind("0.0.0.0:18944")?;
    /// # Ok::<(), openigtlink_rust::error::IgtlError>(())
    /// ```
    pub fn bind(addr: &str) -> Result<Self> {
        let socket = UdpSocket::bind(addr)?;
        Ok(UdpServer { socket })
    }

    /// Receive a message (blocking)
    ///
    /// # Returns
    ///
    /// Tuple of (message, sender_address)
    ///
    /// # Errors
    ///
    /// - [`IgtlError::Io`](crate::error::IgtlError::Io) - Network read failed or timeout
    /// - [`IgtlError::InvalidHeader`](crate::error::IgtlError::InvalidHeader) - Malformed header
    /// - [`IgtlError::CrcMismatch`](crate::error::IgtlError::CrcMismatch) - Data corruption
    pub fn receive<T: Message>(&self) -> Result<(IgtlMessage<T>, SocketAddr)> {
        let mut buf = vec![0u8; MAX_UDP_DATAGRAM_SIZE];
        let (size, src) = self.socket.recv_from(&mut buf)?;

        let msg = IgtlMessage::decode(&buf[..size])?;
        Ok((msg, src))
    }

    /// Send a response to a specific address
    ///
    /// # Arguments
    ///
    /// * `msg` - Message to send
    /// * `target` - Target socket address
    ///
    /// # Errors
    ///
    /// - [`IgtlError::Io`](crate::error::IgtlError::Io) - Network transmission failed
    /// - [`IgtlError::BodyTooLarge`](crate::error::IgtlError::BodyTooLarge) - Message exceeds UDP MTU
    pub fn send_to<T: Message>(&self, msg: &IgtlMessage<T>, target: SocketAddr) -> Result<()> {
        let data = msg.encode()?;

        if data.len() > MAX_UDP_DATAGRAM_SIZE {
            return Err(IgtlError::BodyTooLarge {
                size: data.len(),
                max: MAX_UDP_DATAGRAM_SIZE,
            });
        }

        self.socket.send_to(&data, target)?;
        Ok(())
    }

    /// Set read timeout
    ///
    /// # Arguments
    ///
    /// * `timeout` - Timeout duration (None for blocking forever)
    ///
    /// # Errors
    ///
    /// - [`IgtlError::Io`](crate::error::IgtlError::Io) - Failed to set socket option
    pub fn set_read_timeout(&self, timeout: Option<Duration>) -> Result<()> {
        self.socket.set_read_timeout(timeout)?;
        Ok(())
    }

    /// Get local socket address
    ///
    /// # Errors
    ///
    /// - [`IgtlError::Io`](crate::error::IgtlError::Io) - Failed to get socket address
    pub fn local_addr(&self) -> Result<SocketAddr> {
        Ok(self.socket.local_addr()?)
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::protocol::types::TransformMessage;

    #[test]
    fn test_max_datagram_size() {
        assert_eq!(MAX_UDP_DATAGRAM_SIZE, 65507);
    }

    #[test]
    fn test_client_bind() {
        let client = UdpClient::bind("127.0.0.1:0");
        assert!(client.is_ok());
    }

    #[test]
    fn test_server_bind() {
        let server = UdpServer::bind("127.0.0.1:0");
        assert!(server.is_ok());
    }

    #[test]
    fn test_local_addr() {
        let client = UdpClient::bind("127.0.0.1:0").unwrap();
        let addr = client.local_addr().unwrap();
        assert_eq!(addr.ip().to_string(), "127.0.0.1");
        assert!(addr.port() > 0);
    }

    #[test]
    fn test_send_receive() {
        // Bind server first to get a known port
        let server = UdpServer::bind("127.0.0.1:0").unwrap();
        let server_addr = server.local_addr().unwrap();

        // Create client
        let client = UdpClient::bind("127.0.0.1:0").unwrap();

        // Send message
        let transform = TransformMessage::identity();
        let msg = IgtlMessage::new(transform, "TestDevice").unwrap();
        client.send_to(&msg, &server_addr.to_string()).unwrap();

        // Receive message
        let (received_msg, sender) = server.receive::<TransformMessage>().unwrap();
        assert_eq!(
            received_msg.header.device_name.as_str().unwrap(),
            "TestDevice"
        );
        assert_eq!(sender, client.local_addr().unwrap());
    }

    #[test]
    fn test_timeout() {
        let client = UdpClient::bind("127.0.0.1:0").unwrap();
        client
            .set_read_timeout(Some(Duration::from_millis(100)))
            .unwrap();

        // Should timeout since no data is available
        let result = client.receive_from::<TransformMessage>();
        assert!(result.is_err());
    }

    #[test]
    fn test_message_too_large() {
        let _client = UdpClient::bind("127.0.0.1:0").unwrap();

        // This would fail during encoding if we tried to create a message > 65507 bytes
        // Verify the constant is within valid UDP datagram size
        const _: () = assert!(MAX_UDP_DATAGRAM_SIZE < 65536);
    }
}