Skip to main content

cspcl/
bundle.rs

1use crate::cspcl_sys;
2use crate::error::{Error, Result};
3use crate::instance::Cspcl;
4
5impl Cspcl {
6    /// Send a bundle to a remote CSP address
7    ///
8    /// This will automatically fragment the bundle if it exceeds CSP MTU
9    /// and handle reassembly on the receiving end.
10    ///
11    /// # Arguments
12    /// * `bundle` - The serialized bundle data to send
13    /// * `dest_addr` - Destination CSP address
14    ///
15    /// # Returns
16    /// Ok(()) on success, or Err(Error) if the operation failed
17    pub fn send_bundle(&mut self, bundle: &[u8], dest_addr: u8) -> Result<()> {
18        if bundle.is_empty() {
19            return Err(Error::from_code(cspcl_sys::cspcl_error_t_CSPCL_ERR_INVALID_PARAM).unwrap_err());
20        }
21
22        unsafe {
23            Error::from_code(cspcl_sys::cspcl_send_bundle(
24                self.inner_mut(),
25                bundle.as_ptr(),
26                bundle.len(),
27                dest_addr,
28            ))?;
29        }
30        Ok(())
31    }
32
33    /// Receive a bundle with optional timeout
34    ///
35    /// This function blocks until a complete bundle is received or timeout occurs.
36    /// Incomplete bundles are automatically reassembled.
37    ///
38    /// # Arguments
39    /// * `timeout_ms` - Timeout in milliseconds (0 = no timeout)
40    ///
41    /// # Returns
42    /// Ok((bundle_data, source_address)) on success
43    /// Err(Error) if the operation timed out or failed
44    pub fn recv_bundle(&mut self, timeout_ms: u32) -> Result<(Vec<u8>, u8)> {
45        // TODO: Consider making buffer size configurable via constructor or method parameter
46        let mut buffer = vec![0u8; cspcl_sys::CSPCL_MAX_BUNDLE_SIZE as usize];
47        let mut len = buffer.len();
48        let mut src_addr: u8 = 0;
49
50        unsafe {
51            Error::from_code(cspcl_sys::cspcl_recv_bundle(
52                self.inner_mut(),
53                buffer.as_mut_ptr(),
54                &mut len,
55                &mut src_addr,
56                timeout_ms,
57            ))?;
58        }
59
60        buffer.truncate(len);
61        Ok((buffer, src_addr))
62    }
63}